D-Bus 1.16.4
dbus-nonce.c
1/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2/* dbus-nonce.c Nonce handling functions used by nonce-tcp (internal to D-Bus implementation)
3 *
4 * Copyright (C) 2009 Klaralvdalens Datakonsult AB, a KDAB Group company, info@kdab.net
5 *
6 * SPDX-License-Identifier: AFL-2.1 OR GPL-2.0-or-later
7 *
8 * Licensed under the Academic Free License version 2.1
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 *
24 */
25
26#include <config.h>
27// major sections of this file are modified code from libassuan, (C) FSF
28#include "dbus-nonce.h"
29#include "dbus-internals.h"
30#include "dbus-protocol.h"
31#include "dbus-sysdeps.h"
32
33#include <stdio.h>
34
36{
37 DBusString path;
38 DBusString dir;
39};
40
41/* Bound time spent in nonce pre-auth read to avoid stalling accept path. */
42#define NONCE_READ_TIMEOUT_MS 1000
43
44static dbus_bool_t
45do_check_nonce (DBusSocket fd, const DBusString *nonce, DBusError *error)
46{
47 DBusString buffer;
48 DBusString p;
49 size_t nleft;
50 dbus_bool_t result;
51 int n;
52 int waited_ms = 0;
53
54 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
55
56 nleft = 16;
57
58 /* This is a trick to make it safe to call _dbus_string_free on these
59 * strings during error unwinding, even if allocating memory for them
60 * fails. A constant DBusString is considered to be valid to "free",
61 * even though there is nothing to free (of course the free operation
62 * is trivial, because it does not own its own buffer); but
63 * unlike a mutable DBusString, initializing a constant DBusString
64 * cannot fail.
65 *
66 * We must successfully re-initialize the strings to be mutable before
67 * writing to them, of course.
68 */
69 _dbus_string_init_const (&buffer, "");
71
72 if ( !_dbus_string_init (&buffer)
73 || !_dbus_string_init (&p) ) {
76 _dbus_string_free (&buffer);
77 return FALSE;
78 }
79
80 while (nleft)
81 {
82 int saved_errno;
83
84 n = _dbus_read_socket (fd, &p, nleft);
85 saved_errno = _dbus_save_socket_errno ();
86
87 if (n == -1 && _dbus_get_is_errno_eintr (saved_errno))
88 ;
89 else if (n == -1 && _dbus_get_is_errno_eagain_or_ewouldblock (saved_errno))
90 {
91 if (waited_ms >= NONCE_READ_TIMEOUT_MS)
92 {
94 "Timed out while reading nonce");
96 _dbus_string_free (&buffer);
97 return FALSE;
98 }
100 waited_ms += 100;
101 }
102 else if (n==-1)
103 {
104 dbus_set_error (error, DBUS_ERROR_IO_ERROR, "Could not read nonce from socket (fd=%" DBUS_SOCKET_FORMAT ")", _dbus_socket_printable (fd));
106 _dbus_string_free (&buffer);
107 return FALSE;
108 }
109 else if (!n)
110 {
112 _dbus_string_free (&buffer);
113 dbus_set_error (error, DBUS_ERROR_IO_ERROR, "Could not read nonce from socket (fd=%" DBUS_SOCKET_FORMAT ")", _dbus_socket_printable (fd));
114 return FALSE;
115 }
116 else
117 {
118 if (!_dbus_string_append_len (&buffer, _dbus_string_get_const_data (&p), n))
119 {
122 _dbus_string_free (&buffer);
123 return FALSE;
124 }
125 nleft -= n;
126 }
127 }
128
129 result = _dbus_string_equal_len (&buffer, nonce, 16);
130 if (!result)
131 dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED, "Nonces do not match, access denied (fd=%" DBUS_SOCKET_FORMAT ")", _dbus_socket_printable (fd));
132
134 _dbus_string_free (&buffer);
135
136 return result;
137}
138
148_dbus_read_nonce (const DBusString *fname, DBusString *nonce, DBusError* error)
149{
150 FILE *fp;
151 char buffer[17];
152 size_t nread;
153
154 buffer[sizeof buffer - 1] = '\0';
155
156 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
157
158 _dbus_verbose ("reading nonce from file: %s\n", _dbus_string_get_const_data (fname));
159
160
161 fp = fopen (_dbus_string_get_const_data (fname), "rb");
162 if (!fp)
163 {
164 dbus_set_error (error,
166 "Failed to open %s for read: %s",
167 _dbus_string_get_const_data (fname),
169 return FALSE;
170 }
171
172 nread = fread (buffer, 1, sizeof buffer - 1, fp);
173 fclose (fp);
174 if (!nread)
175 {
176 dbus_set_error (error, DBUS_ERROR_FILE_NOT_FOUND, "Could not read nonce from file %s", _dbus_string_get_const_data (fname));
177 return FALSE;
178 }
179
180 if (!_dbus_string_append_len (nonce, buffer, sizeof buffer - 1 ))
181 {
183 return FALSE;
184 }
185 return TRUE;
186}
187
189_dbus_accept_with_noncefile (DBusSocket listen_fd, const DBusNonceFile *noncefile)
190{
191 DBusSocket fd = _dbus_socket_get_invalid ();
192 DBusString nonce;
193
194 _dbus_assert (noncefile != NULL);
195
196 /* Make it valid to "free" this even if _dbus_string_init() runs
197 * out of memory: see comment in do_check_nonce() */
198 _dbus_string_init_const (&nonce, "");
199
200 if (!_dbus_string_init (&nonce))
201 goto out;
202
203 //PENDING(kdab): set better errors
204 if (_dbus_read_nonce (_dbus_noncefile_get_path(noncefile), &nonce, NULL) != TRUE)
205 goto out;
206
207 fd = _dbus_accept (listen_fd);
208
209 if (!_dbus_socket_is_valid (fd))
210 goto out;
211
213 {
215 goto out;
216 }
217
218 if (do_check_nonce(fd, &nonce, NULL) != TRUE) {
219 _dbus_verbose ("nonce check failed. Closing socket.\n");
221 goto out;
222 }
223
224out:
225 _dbus_string_free (&nonce);
226 return fd;
227}
228
229static dbus_bool_t
230generate_and_write_nonce (const DBusString *filename, DBusError *error)
231{
232 DBusString nonce;
233 dbus_bool_t ret;
234
235 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
236
237 if (!_dbus_string_init (&nonce))
238 {
240 return FALSE;
241 }
242
243 if (!_dbus_generate_random_bytes (&nonce, 16, error))
244 {
245 _dbus_string_free (&nonce);
246 return FALSE;
247 }
248
249 ret = _dbus_string_save_to_file (&nonce, filename, FALSE, error);
250
251 _dbus_string_free (&nonce);
252
253 return ret;
254}
255
266_dbus_send_nonce (DBusSocket fd,
267 const DBusString *noncefile,
268 DBusError *error)
269{
270 dbus_bool_t read_result;
271 int send_result;
272 DBusString nonce;
273
274 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
275
276 if (_dbus_string_get_length (noncefile) == 0)
277 return FALSE;
278
279 if (!_dbus_string_init (&nonce))
280 {
282 return FALSE;
283 }
284
285 read_result = _dbus_read_nonce (noncefile, &nonce, error);
286 if (!read_result)
287 {
288 _DBUS_ASSERT_ERROR_IS_SET (error);
289 _dbus_string_free (&nonce);
290 return FALSE;
291 }
292 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
293
294 send_result = _dbus_write_socket (fd, &nonce, 0, _dbus_string_get_length (&nonce));
295
296 _dbus_string_free (&nonce);
297
298 if (send_result == -1)
299 {
300 dbus_set_error (error,
302 "Failed to send nonce (fd=%" DBUS_SOCKET_FORMAT "): %s",
303 _dbus_socket_printable (fd),
305 return FALSE;
306 }
307
308 return TRUE;
309}
310
311static dbus_bool_t
312do_noncefile_create (DBusNonceFile **noncefile_out,
313 DBusError *error,
314 dbus_bool_t use_subdir)
315{
316 DBusNonceFile *noncefile = NULL;
317 DBusString randomStr;
318 const char *tmp;
319
320 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
321
322 _dbus_assert (noncefile_out != NULL);
323 _dbus_assert (*noncefile_out == NULL);
324
325 noncefile = dbus_new0 (DBusNonceFile, 1);
326 if (noncefile == NULL)
327 {
329 return FALSE;
330 }
331
332 /* Make it valid to "free" these even if _dbus_string_init() runs
333 * out of memory: see comment in do_check_nonce() */
334 _dbus_string_init_const (&randomStr, "");
335 _dbus_string_init_const (&noncefile->dir, "");
336 _dbus_string_init_const (&noncefile->path, "");
337
338 if (!_dbus_string_init (&randomStr))
339 {
341 goto on_error;
342 }
343
344 if (!_dbus_generate_random_ascii (&randomStr, 8, error))
345 {
346 goto on_error;
347 }
348
349 tmp = _dbus_get_tmpdir ();
350
351 if (!_dbus_string_init (&noncefile->dir)
352 || tmp == NULL
353 || !_dbus_string_append (&noncefile->dir, tmp))
354 {
356 goto on_error;
357 }
358 if (use_subdir)
359 {
360 if (!_dbus_string_append (&noncefile->dir, "/dbus_nonce-")
361 || !_dbus_string_append (&noncefile->dir, _dbus_string_get_const_data (&randomStr)) )
362 {
364 goto on_error;
365 }
366 if (!_dbus_string_init (&noncefile->path)
367 || !_dbus_string_copy (&noncefile->dir, 0, &noncefile->path, 0)
368 || !_dbus_string_append (&noncefile->path, "/nonce"))
369 {
371 goto on_error;
372 }
373 if (!_dbus_create_directory (&noncefile->dir, error))
374 {
375 _DBUS_ASSERT_ERROR_IS_SET (error);
376 goto on_error;
377 }
378 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
379
380 }
381 else
382 {
383 if (!_dbus_string_init (&noncefile->path)
384 || !_dbus_string_copy (&noncefile->dir, 0, &noncefile->path, 0)
385 || !_dbus_string_append (&noncefile->path, "/dbus_nonce-")
386 || !_dbus_string_append (&noncefile->path, _dbus_string_get_const_data (&randomStr)))
387 {
389 goto on_error;
390 }
391
392 }
393
394 if (!generate_and_write_nonce (&noncefile->path, error))
395 {
396 _DBUS_ASSERT_ERROR_IS_SET (error);
397 if (use_subdir)
398 _dbus_delete_directory (&noncefile->dir, NULL); //we ignore possible errors deleting the dir and return the write error instead
399 goto on_error;
400 }
401 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
402
403 *noncefile_out = noncefile;
404 _dbus_string_free (&randomStr);
405
406 return TRUE;
407 on_error:
408 if (use_subdir && _dbus_string_get_length (&noncefile->dir) != 0)
409 _dbus_delete_directory (&noncefile->dir, NULL);
410 _dbus_string_free (&noncefile->dir);
411 _dbus_string_free (&noncefile->path);
412 dbus_free (noncefile);
413 _dbus_string_free (&randomStr);
414 return FALSE;
415}
416
417#ifdef DBUS_WIN
426_dbus_noncefile_create (DBusNonceFile **noncefile_out,
427 DBusError *error)
428{
429 return do_noncefile_create (noncefile_out, error, /*use_subdir=*/FALSE);
430}
431
443_dbus_noncefile_delete (DBusNonceFile **noncefile_location,
444 DBusError *error)
445{
446 DBusNonceFile *noncefile;
447
448 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
449 _dbus_assert (noncefile_location != NULL);
450
451 noncefile = *noncefile_location;
452 *noncefile_location = NULL;
453
454 if (noncefile == NULL)
455 {
456 /* Nothing to do */
457 return TRUE;
458 }
459
460 _dbus_delete_file (&noncefile->path, error);
461 _dbus_string_free (&noncefile->dir);
462 _dbus_string_free (&noncefile->path);
463 dbus_free (noncefile);
464 return TRUE;
465}
466
467#else
477_dbus_noncefile_create (DBusNonceFile **noncefile_out,
478 DBusError *error)
479{
480 return do_noncefile_create (noncefile_out, error, /*use_subdir=*/TRUE);
481}
482
494_dbus_noncefile_delete (DBusNonceFile **noncefile_location,
495 DBusError *error)
496{
497 DBusNonceFile *noncefile;
498
499 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
500 _dbus_assert (noncefile_location != NULL);
501
502 noncefile = *noncefile_location;
503 *noncefile_location = NULL;
504
505 if (noncefile == NULL)
506 {
507 /* Nothing to do */
508 return TRUE;
509 }
510
511 _dbus_delete_directory (&noncefile->dir, error);
512 _dbus_string_free (&noncefile->dir);
513 _dbus_string_free (&noncefile->path);
514 dbus_free (noncefile);
515 return TRUE;
516}
517#endif
518
519
526const DBusString*
527_dbus_noncefile_get_path (const DBusNonceFile *noncefile)
528{
529 _dbus_assert (noncefile);
530 return &noncefile->path;
531}
532
544_dbus_noncefile_check_nonce (DBusSocket fd,
545 const DBusNonceFile *noncefile,
546 DBusError* error)
547{
548 return do_check_nonce (fd, _dbus_noncefile_get_path (noncefile), error);
549}
550
551
void dbus_set_error(DBusError *error, const char *name, const char *format,...)
Assigns an error name and message to a DBusError.
dbus_bool_t _dbus_delete_file(const DBusString *filename, DBusError *error)
Deletes the given file.
dbus_bool_t _dbus_string_save_to_file(const DBusString *str, const DBusString *filename, dbus_bool_t world_readable, DBusError *error)
Writes a string out to a file.
#define _dbus_assert(condition)
Aborts with an error message if the condition is false.
dbus_bool_t _dbus_generate_random_ascii(DBusString *str, int n_bytes, DBusError *error)
Generates the given number of random bytes, where the bytes are chosen from the alphanumeric ASCII su...
const char * _dbus_error_from_system_errno(void)
Converts the current system errno value into a DBusError name.
const char * _dbus_strerror_from_errno(void)
Get error message from errno.
dbus_bool_t _dbus_get_is_errno_eintr(int e)
See if errno is EINTR.
#define NULL
A null pointer, defined appropriately for C or C++.
Definition dbus-macros.h:51
#define TRUE
Expands to "1".
Definition dbus-macros.h:41
#define FALSE
Expands to "0".
Definition dbus-macros.h:44
void dbus_free(void *memory)
Frees a block of memory previously allocated by dbus_malloc() or dbus_malloc0().
#define dbus_new0(type, count)
Safe macro for using dbus_malloc0().
Definition dbus-memory.h:60
#define DBUS_ERROR_TIMEOUT
Certain timeout errors, possibly ETIMEDOUT on a socket.
#define DBUS_ERROR_IO_ERROR
Something went wrong reading or writing to a socket, for example.
#define DBUS_ERROR_ACCESS_DENIED
Security restrictions don't allow doing what you're trying to do.
#define DBUS_ERROR_NO_MEMORY
There was not enough memory to complete an operation.
#define DBUS_ERROR_FILE_NOT_FOUND
Missing file.
dbus_bool_t _dbus_string_append(DBusString *str, const char *buffer)
Appends a nul-terminated C-style string to a DBusString.
dbus_bool_t _dbus_string_init(DBusString *str)
Initializes a string.
void _dbus_string_init_const(DBusString *str, const char *value)
Initializes a constant string.
dbus_bool_t _dbus_string_copy(const DBusString *source, int start, DBusString *dest, int insert_at)
Like _dbus_string_move(), but does not delete the section of the source string that's copied to the d...
dbus_bool_t _dbus_string_append_len(DBusString *str, const char *buffer, int len)
Appends block of bytes with the given length to a DBusString.
void _dbus_string_free(DBusString *str)
Frees a string created by _dbus_string_init(), and fills it with the same contents as _DBUS_STRING_IN...
dbus_bool_t _dbus_string_equal_len(const DBusString *a, const DBusString *b, int len)
Tests two DBusString for equality up to the given length.
int _dbus_read_socket(DBusSocket fd, DBusString *buffer, int count)
Like _dbus_read(), but only works on sockets so is available on Windows.
int _dbus_write_socket(DBusSocket fd, const DBusString *buffer, int start, int len)
Like _dbus_write(), but only supports sockets and is thus available on Windows.
dbus_bool_t _dbus_set_socket_nonblocking(DBusSocket fd, DBusError *error)
Sets a file descriptor to be nonblocking.
dbus_bool_t _dbus_get_is_errno_eagain_or_ewouldblock(int e)
See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently for Winsock so is abstracted).
void _dbus_sleep_milliseconds(int milliseconds)
Sleeps the given number of milliseconds.
dbus_bool_t _dbus_close_socket(DBusSocket *fd, DBusError *error)
Closes a socket and invalidates it.
dbus_bool_t _dbus_generate_random_bytes(DBusString *str, int n_bytes, DBusError *error)
Generates the given number of securely random bytes, using the best mechanism we can come up with.
dbus_bool_t _dbus_delete_directory(const DBusString *filename, DBusError *error)
Removes a directory; Directory must be empty.
DBusSocket _dbus_accept(DBusSocket listen_fd)
Accepts a connection on a listening socket.
const char * _dbus_get_tmpdir(void)
Gets the temporary files directory by inspecting the environment variables TMPDIR,...
dbus_bool_t _dbus_create_directory(const DBusString *filename, DBusError *error)
Creates a directory.
dbus_uint32_t dbus_bool_t
A boolean, valid values are TRUE and FALSE.
Definition dbus-types.h:37
Object representing an exception.
Definition dbus-errors.h:51
Socket interface.