dbus-keyring.c 30.4 KB
Newer Older
1 2 3 4 5
/* -*- mode: C; c-file-style: "gnu" -*- */
/* dbus-keyring.c Store secret cookies in your homedir
 *
 * Copyright (C) 2003  Red Hat Inc.
 *
6
 * Licensed under the Academic Free License version 2.0
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include "dbus-keyring.h"
25
#include "dbus-userdb.h"
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <dbus/dbus-string.h>
#include <dbus/dbus-list.h>
#include <dbus/dbus-sysdeps.h>

/**
 * @defgroup DBusKeyring keyring class
 * @ingroup  DBusInternals
 * @brief DBusKeyring data structure
 *
 * Types and functions related to DBusKeyring. DBusKeyring is intended
 * to manage cookies used to authenticate clients to servers.  This is
 * essentially the "verify that client can read the user's homedir"
 * authentication mechanism.  Both client and server must have access
 * to the homedir.
 *
 * The secret keys are not kept in locked memory, and are written to a
 * file in the user's homedir. However they are transient (only used
 * by a single server instance for a fixed period of time, then
 * discarded). Also, the keys are not sent over the wire.
45 46 47 48
 *
 * @todo there's a memory leak on some codepath in here, I saw it once
 * when running make check - probably some specific initial cookies
 * present in the cookie file, then depending on what we do with them.
49 50 51 52 53 54 55 56 57 58 59 60
 */

/**
 * @defgroup DBusKeyringInternals DBusKeyring implementation details
 * @ingroup  DBusInternals
 * @brief DBusKeyring implementation details
 *
 * The guts of DBusKeyring.
 *
 * @{
 */

61 62 63 64
/** The maximum age of a key before we create a new key to use in
 * challenges.  This isn't super-reliably enforced, since system
 * clocks can change or be wrong, but we make a best effort to only
 * use keys for a short time.
65
 */
66
#define NEW_KEY_TIMEOUT_SECONDS     (60*5)
67
/**
68 69 70
 * The time after which we drop a key from the secrets file.
 * The EXPIRE_KEYS_TIMEOUT_SECONDS - NEW_KEY_TIMEOUT_SECONDS is the minimum
 * time window a client has to complete authentication.
71
 */
72 73 74 75 76
#define EXPIRE_KEYS_TIMEOUT_SECONDS (NEW_KEY_TIMEOUT_SECONDS + (60*2))
/**
 * The maximum amount of time a key can be in the future.
 */
#define MAX_TIME_TRAVEL_SECONDS (60*5)
77

78 79 80 81 82 83 84 85 86 87
/**
 * Maximum number of keys in the keyring before
 * we just ignore the rest
 */
#ifdef DBUS_BUILD_TESTS
#define MAX_KEYS_IN_FILE 10
#else
#define MAX_KEYS_IN_FILE 256
#endif

88 89 90
/**
 * A single key from the cookie file
 */
91 92
typedef struct
{
93
  dbus_int32_t id; /**< identifier used to refer to the key */
94

95 96 97 98
  long creation_time; /**< when the key was generated,
                       *   as unix timestamp. signed long
                       *   matches struct timeval.
                       */
99 100 101 102 103 104 105 106 107 108 109 110 111
  
  DBusString secret; /**< the actual key */

} DBusKey;

/**
 * @brief Internals of DBusKeyring.
 * 
 * DBusKeyring internals. DBusKeyring is an opaque object, it must be
 * used via accessor functions.
 */
struct DBusKeyring
{
112
  int refcount;             /**< Reference count */
113
  DBusString username;      /**< Username keyring is for */
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
  DBusString directory;     /**< Directory the below two items are inside */
  DBusString filename;      /**< Keyring filename */
  DBusString filename_lock; /**< Name of lockfile */
  DBusKey *keys; /**< Keys loaded from the file */
  int n_keys;    /**< Number of keys */
};

static DBusKeyring*
_dbus_keyring_new (void)
{
  DBusKeyring *keyring;

  keyring = dbus_new0 (DBusKeyring, 1);
  if (keyring == NULL)
    goto out_0;
129
  
130
  if (!_dbus_string_init (&keyring->directory))
131 132
    goto out_1;

133
  if (!_dbus_string_init (&keyring->filename))
134 135
    goto out_2;

136
  if (!_dbus_string_init (&keyring->filename_lock))
137 138
    goto out_3;

139
  if (!_dbus_string_init (&keyring->username))
140 141
    goto out_4;
  
142 143 144 145 146
  keyring->refcount = 1;
  keyring->keys = NULL;
  keyring->n_keys = 0;

  return keyring;
147 148

 out_4:
149
  _dbus_string_free (&keyring->filename_lock);
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
 out_3:
  _dbus_string_free (&keyring->filename);
 out_2:
  _dbus_string_free (&keyring->directory);
 out_1:
  dbus_free (keyring);
 out_0:
  return NULL;
}

static void
free_keys (DBusKey *keys,
           int      n_keys)
{
  int i;

  /* should be safe for args NULL, 0 */
  
  i = 0;
  while (i < n_keys)
    {
      _dbus_string_free (&keys[i].secret);
      ++i;
    }

  dbus_free (keys);
}

/* Our locking scheme is highly unreliable.  However, there is
 * unfortunately no reliable locking scheme in user home directories;
 * between bugs in Linux NFS, people using Tru64 or other total crap
 * NFS, AFS, random-file-system-of-the-week, and so forth, fcntl() in
 * homedirs simply generates tons of bug reports. This has been
 * learned through hard experience with GConf, unfortunately.
 *
 * This bad hack might work better for the kind of lock we have here,
 * which we don't expect to hold for any length of time.  Crashing
 * while we hold it should be unlikely, and timing out such that we
 * delete a stale lock should also be unlikely except when the
 * filesystem is running really slowly.  Stuff might break in corner
 * cases but as long as it's not a security-level breakage it should
 * be OK.
 */

/** Maximum number of timeouts waiting for lock before we decide it's stale */
195
#define MAX_LOCK_TIMEOUTS 32
196
/** Length of each timeout while waiting for a lock */
197
#define LOCK_TIMEOUT_MILLISECONDS 250
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

static dbus_bool_t
_dbus_keyring_lock (DBusKeyring *keyring)
{
  int n_timeouts;
  
  n_timeouts = 0;
  while (n_timeouts < MAX_LOCK_TIMEOUTS)
    {
      DBusError error;

      dbus_error_init (&error);
      if (_dbus_create_file_exclusively (&keyring->filename_lock,
                                         &error))
        break;

214 215
      _dbus_verbose ("Did not get lock file, sleeping %d milliseconds (%s)\n",
                     LOCK_TIMEOUT_MILLISECONDS, error.message);
216 217
      dbus_error_free (&error);

218
      _dbus_sleep_milliseconds (LOCK_TIMEOUT_MILLISECONDS);
219 220 221 222 223 224
      
      ++n_timeouts;
    }

  if (n_timeouts == MAX_LOCK_TIMEOUTS)
    {
225 226 227 228
      DBusError error;
      
      _dbus_verbose ("Lock file timed out %d times, assuming stale\n",
                     n_timeouts);
229

230 231 232 233 234 235 236 237 238
      dbus_error_init (&error);

      if (!_dbus_delete_file (&keyring->filename_lock, &error))
        {
          _dbus_verbose ("Couldn't delete old lock file: %s\n",
                         error.message);
          dbus_error_free (&error);
          return FALSE;
        }
239 240

      if (!_dbus_create_file_exclusively (&keyring->filename_lock,
241
                                          &error))
242
        {
243 244 245
          _dbus_verbose ("Couldn't create lock file after deleting stale one: %s\n",
                         error.message);
          dbus_error_free (&error);
246 247 248 249 250 251 252 253 254 255
          return FALSE;
        }
    }
  
  return TRUE;
}

static void
_dbus_keyring_unlock (DBusKeyring *keyring)
{
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
  DBusError error;
  dbus_error_init (&error);
  if (!_dbus_delete_file (&keyring->filename_lock, &error))
    {
      _dbus_warn ("Failed to delete lock file: %s\n",
                  error.message);
      dbus_error_free (&error);
    }
}

static DBusKey*
find_key_by_id (DBusKey *keys,
                int      n_keys,
                int      id)
{
  int i;

  i = 0;
  while (i < n_keys)
    {
      if (keys[i].id == id)
        return &keys[i];
      
      ++i;
    }

  return NULL;
}

static dbus_bool_t
add_new_key (DBusKey  **keys_p,
             int       *n_keys_p,
             DBusError *error)
{
  DBusKey *new;
  DBusString bytes;
  int id;
  unsigned long timestamp;
  const unsigned char *s;
  dbus_bool_t retval;
  DBusKey *keys;
  int n_keys;
298 299 300

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  
301
  if (!_dbus_string_init (&bytes))
302
    {
303
      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
304 305 306 307 308 309 310 311 312 313 314 315
      return FALSE;
    }

  keys = *keys_p;
  n_keys = *n_keys_p;
  retval = FALSE;
      
  /* Generate an integer ID and then the actual key. */
 retry:
      
  if (!_dbus_generate_random_bytes (&bytes, 4))
    {
316
      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
317 318 319
      goto out;
    }

320
  s = (const unsigned char*) _dbus_string_get_const_data (&bytes);
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
      
  id = s[0] | (s[1] << 8) | (s[2] << 16) | (s[3] << 24);
  if (id < 0)
    id = - id;
  _dbus_assert (id >= 0);

  if (find_key_by_id (keys, n_keys, id) != NULL)
    {
      _dbus_string_set_length (&bytes, 0);
      _dbus_verbose ("Key ID %d already existed, trying another one\n",
                     id);
      goto retry;
    }

  _dbus_verbose ("Creating key with ID %d\n", id);
      
#define KEY_LENGTH_BYTES 24
  _dbus_string_set_length (&bytes, 0);
  if (!_dbus_generate_random_bytes (&bytes, KEY_LENGTH_BYTES))
    {
341
      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
342 343 344 345 346 347
      goto out;
    }

  new = dbus_realloc (keys, sizeof (DBusKey) * (n_keys + 1));
  if (new == NULL)
    {
348
      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
349 350 351 352
      goto out;
    }

  keys = new;
353
  *keys_p = keys; /* otherwise *keys_p ends up invalid */
354 355
  n_keys += 1;

356
  if (!_dbus_string_init (&keys[n_keys-1].secret))
357 358
    {
      n_keys -= 1; /* we don't want to free the one we didn't init */
359
      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
360 361 362 363 364 365 366 367 368 369 370
      goto out;
    }

  _dbus_get_current_time (&timestamp, NULL);
      
  keys[n_keys-1].id = id;
  keys[n_keys-1].creation_time = timestamp;
  if (!_dbus_string_move (&bytes, 0,
                          &keys[n_keys-1].secret,
                          0))
    {
371
      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
372 373
      _dbus_string_free (&keys[n_keys-1].secret);
      n_keys -= 1;
374 375 376 377 378 379
      goto out;
    }
  
  retval = TRUE;
  
 out:
380
  *n_keys_p = n_keys;
381 382 383
  
  _dbus_string_free (&bytes);
  return retval;
384 385 386 387
}

/**
 * Reloads the keyring file, optionally adds one new key to the file,
388 389 390 391 392 393
 * removes all expired keys from the file iff a key was added, then
 * resaves the file.  Stores the keys from the file in keyring->keys.
 * Note that the file is only resaved (written to) if a key is added,
 * this means that only servers ever write to the file and need to
 * lock it, which avoids a lot of lock contention at login time and
 * such.
394 395
 *
 * @param keyring the keyring
396
 * @param add_new #TRUE to add a new key to the file, expire keys, and resave
397 398 399 400 401 402 403 404
 * @param error return location for errors
 * @returns #FALSE on failure
 */
static dbus_bool_t
_dbus_keyring_reload (DBusKeyring *keyring,
                      dbus_bool_t  add_new,
                      DBusError   *error)
{
405 406 407 408 409 410 411 412
  DBusString contents;
  DBusString line;
  dbus_bool_t retval;
  dbus_bool_t have_lock;
  DBusKey *keys;
  int n_keys;
  int i;
  long now;
413
  DBusError tmp_error;
414 415

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
416
  
417
  if (!_dbus_string_init (&contents))
418
    {
419
      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
420 421 422
      return FALSE;
    }

423
  if (!_dbus_string_init (&line))
424
    {
425
      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
      _dbus_string_free (&contents);
      return FALSE;
    }

  keys = NULL;
  n_keys = 0;
  retval = FALSE;
  have_lock = FALSE;

  _dbus_get_current_time (&now, NULL);
  
  if (add_new)
    {
      if (!_dbus_keyring_lock (keyring))
        {
          dbus_set_error (error, DBUS_ERROR_FAILED,
                          "Could not lock keyring file to add to it");
          goto out;
        }

      have_lock = TRUE;
    }

449 450 451 452
  dbus_error_init (&tmp_error);
  if (!_dbus_file_get_contents (&contents, 
                                &keyring->filename,
                                &tmp_error))
453 454
    {
      _dbus_verbose ("Failed to load keyring file: %s\n",
455
                     tmp_error.message);
456
      /* continue with empty keyring file, so we recreate it */
457
      dbus_error_free (&tmp_error);
458 459 460 461 462 463 464 465
    }

  if (!_dbus_string_validate_ascii (&contents, 0,
                                    _dbus_string_get_length (&contents)))
    {
      _dbus_warn ("Secret keyring file contains non-ASCII! Ignoring existing contents\n");
      _dbus_string_set_length (&contents, 0);
    }
466 467 468 469

  /* FIXME this is badly inefficient for large keyring files
   * (not that large keyring files exist outside of test suites)
   */
470 471 472 473 474 475 476 477
  while (_dbus_string_pop_line (&contents, &line))
    {
      int next;
      long val;
      int id;
      long timestamp;
      int len;
      DBusKey *new;
478 479 480 481

      /* Don't load more than the max. */
      if (n_keys >= (add_new ? MAX_KEYS_IN_FILE : MAX_KEYS_IN_FILE - 1))
        break;
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
      
      next = 0;
      if (!_dbus_string_parse_int (&line, 0, &val, &next))
        {
          _dbus_verbose ("could not parse secret key ID at start of line\n");
          continue;
        }

      if (val > _DBUS_INT_MAX || val < 0)
        {
          _dbus_verbose ("invalid secret key ID at start of line\n");
          continue;
        }
      
      id = val;

      _dbus_string_skip_blank (&line, next, &next);
      
      if (!_dbus_string_parse_int (&line, next, &timestamp, &next))
        {
          _dbus_verbose ("could not parse secret key timestamp\n");
          continue;
        }
505

506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
      if (timestamp < 0 ||
          (now + MAX_TIME_TRAVEL_SECONDS) < timestamp ||
          (now - EXPIRE_KEYS_TIMEOUT_SECONDS) > timestamp)
        {
          _dbus_verbose ("dropping/ignoring %ld-seconds old key with timestamp %ld as current time is %ld\n",
                         now - timestamp, timestamp, now);
          continue;
        }
      
      _dbus_string_skip_blank (&line, next, &next);

      len = _dbus_string_get_length (&line);

      if ((len - next) == 0)
        {
          _dbus_verbose ("no secret key after ID and timestamp\n");
          continue;
        }
      
      /* We have all three parts */
      new = dbus_realloc (keys, sizeof (DBusKey) * (n_keys + 1));
      if (new == NULL)
        {
529
          dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
530 531 532 533 534 535
          goto out;
        }

      keys = new;
      n_keys += 1;

536
      if (!_dbus_string_init (&keys[n_keys-1].secret))
537 538
        {
          n_keys -= 1; /* we don't want to free the one we didn't init */
539
          dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
540 541 542 543 544 545 546 547 548
          goto out;
        }
      
      keys[n_keys-1].id = id;
      keys[n_keys-1].creation_time = timestamp;
      if (!_dbus_string_hex_decode (&line, next,
                                    &keys[n_keys-1].secret,
                                    0))
        {
549
          dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
          goto out;
        }
    }

  _dbus_verbose ("Successfully loaded %d existing keys\n",
                 n_keys);

  if (add_new)
    {
      if (!add_new_key (&keys, &n_keys, error))
        {
          _dbus_verbose ("Failed to generate new key: %s\n",
                         error ? "(unknown)" : error->message);
          goto out;
        }

      _dbus_string_set_length (&contents, 0);

      i = 0;
      while (i < n_keys)
        {
          if (!_dbus_string_append_int (&contents,
                                        keys[i].id))
            goto nomem;

          if (!_dbus_string_append_byte (&contents, ' '))
            goto nomem;

          if (!_dbus_string_append_int (&contents,
                                        keys[i].creation_time))
            goto nomem;

          if (!_dbus_string_append_byte (&contents, ' '))
            goto nomem;

          if (!_dbus_string_hex_encode (&keys[i].secret, 0,
                                        &contents,
                                        _dbus_string_get_length (&contents)))
            goto nomem;

          if (!_dbus_string_append_byte (&contents, '\n'))
            goto nomem;          
          
          ++i;
          continue;

        nomem:
597
          dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
598 599 600
          goto out;
        }
      
601 602 603
      if (!_dbus_string_save_to_file (&contents, &keyring->filename,
                                      error))
        goto out;
604 605
    }

606 607
  if (keyring->keys)
    free_keys (keyring->keys, keyring->n_keys);
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
  keyring->keys = keys;
  keyring->n_keys = n_keys;
  keys = NULL;
  n_keys = 0;
  
  retval = TRUE;  
  
 out:
  if (have_lock)
    _dbus_keyring_unlock (keyring);
  
  if (! ((retval == TRUE && (error == NULL || error->name == NULL)) ||
         (retval == FALSE && (error == NULL || error->name != NULL))))
    {
      if (error && error->name)
        _dbus_verbose ("error is %s: %s\n", error->name, error->message);
      _dbus_warn ("returning %d but error pointer %p name %s\n",
                  retval, error, error->name ? error->name : "(none)");
      _dbus_assert_not_reached ("didn't handle errors properly");
    }
  
  if (keys != NULL)
    {
      i = 0;
      while (i < n_keys)
        {
634
          _dbus_string_zero (&keys[i].secret);
635 636 637 638 639 640 641 642 643 644 645
          _dbus_string_free (&keys[i].secret);
          ++i;
        }

      dbus_free (keys);
    }
  
  _dbus_string_free (&contents);
  _dbus_string_free (&line);

  return retval;
646
}
647 648 649 650 651 652 653 654 655

/** @} */ /* end of internals */

/**
 * @addtogroup DBusKeyring
 *
 * @{
 */

656 657 658 659
/**
 * Increments reference count of the keyring
 *
 * @param keyring the keyring
660
 * @returns the keyring
661
 */
662
DBusKeyring *
663 664 665
_dbus_keyring_ref (DBusKeyring *keyring)
{
  keyring->refcount += 1;
666 667

  return keyring;
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
}

/**
 * Decrements refcount and finalizes if it reaches
 * zero.
 *
 * @param keyring the keyring
 */
void
_dbus_keyring_unref (DBusKeyring *keyring)
{
  keyring->refcount -= 1;

  if (keyring->refcount == 0)
    {
683
      _dbus_string_free (&keyring->username);
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
      _dbus_string_free (&keyring->filename);
      _dbus_string_free (&keyring->filename_lock);
      _dbus_string_free (&keyring->directory);
      free_keys (keyring->keys, keyring->n_keys);
      dbus_free (keyring);      
    }
}

/**
 * Creates a new keyring that lives in the ~/.dbus-keyrings
 * directory of the given user. If the username is #NULL,
 * uses the user owning the current process.
 *
 * @param username username to get keyring for, or #NULL
 * @param context which keyring to get
 * @param error return location for errors
 * @returns the keyring or #NULL on error
 */
DBusKeyring*
_dbus_keyring_new_homedir (const DBusString *username,
                           const DBusString *context,
                           DBusError        *error)
{
  DBusString homedir;
  DBusKeyring *keyring;
  dbus_bool_t error_set;
  DBusString dotdir;
711
  DBusError tmp_error;
712 713

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
714 715 716 717
  
  keyring = NULL;
  error_set = FALSE;
  
718
  if (!_dbus_string_init (&homedir))
719 720 721 722
    {
      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
      return FALSE;
    }
723 724 725 726 727 728

  _dbus_string_init_const (&dotdir, ".dbus-keyrings");
  
  if (username == NULL)
    {
      const DBusString *const_homedir;
729 730 731

      if (!_dbus_username_from_current_process (&username) ||
          !_dbus_homedir_from_current_process (&const_homedir))
732 733 734 735 736 737 738 739 740 741 742 743
        goto failed;

      if (!_dbus_string_copy (const_homedir, 0,
                              &homedir, 0))
        goto failed;
    }
  else
    {
      if (!_dbus_homedir_from_username (username, &homedir))
        goto failed;
    }

744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
#ifdef DBUS_BUILD_TESTS
 {
   const char *override;

   override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
   if (override != NULL && *override != '\0')
     {
       _dbus_string_set_length (&homedir, 0);
       if (!_dbus_string_append (&homedir, override))
         _dbus_assert_not_reached ("no memory");

       _dbus_verbose ("Using fake homedir for testing: %s\n",
                      _dbus_string_get_const_data (&homedir));
     }
   else
     {
760 761 762 763 764 765
       static dbus_bool_t already_warned = FALSE;
       if (!already_warned)
         {
           _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
           already_warned = TRUE;
         }
766 767 768 769
     }
 }
#endif
  
770 771
  _dbus_assert (username != NULL);    
  
772 773 774 775 776 777 778 779 780 781 782 783 784
  keyring = _dbus_keyring_new ();
  if (keyring == NULL)
    goto failed;

  /* should have been validated already, but paranoia check here */
  if (!_dbus_keyring_validate_context (context))
    {
      error_set = TRUE;
      dbus_set_error_const (error,
                            DBUS_ERROR_FAILED,
                            "Invalid context in keyring creation");
      goto failed;
    }
785 786 787 788 789

  if (!_dbus_string_copy (username, 0,
                          &keyring->username, 0))
    goto failed;
  
790 791 792
  if (!_dbus_string_copy (&homedir, 0,
                          &keyring->directory, 0))
    goto failed;
793
  
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
  if (!_dbus_concat_dir_and_file (&keyring->directory,
                                  &dotdir))
    goto failed;

  if (!_dbus_string_copy (&keyring->directory, 0,
                          &keyring->filename, 0))
    goto failed;

  if (!_dbus_concat_dir_and_file (&keyring->filename,
                                  context))
    goto failed;

  if (!_dbus_string_copy (&keyring->filename, 0,
                          &keyring->filename_lock, 0))
    goto failed;

810
  if (!_dbus_string_append (&keyring->filename_lock, ".lock"))
811 812
    goto failed;

813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
  dbus_error_init (&tmp_error);
  if (!_dbus_keyring_reload (keyring, FALSE, &tmp_error))
    {
      _dbus_verbose ("didn't load an existing keyring: %s\n",
                     tmp_error.message);
      dbus_error_free (&tmp_error);
    }
  
  /* We don't fail fatally if we can't create the directory,
   * but the keyring will probably always be empty
   * unless someone else manages to create it
   */
  dbus_error_init (&tmp_error);
  if (!_dbus_create_directory (&keyring->directory,
                               &tmp_error))
    {
      _dbus_verbose ("Creating keyring directory: %s\n",
                     tmp_error.message);
      dbus_error_free (&tmp_error);
    }
833 834

  _dbus_string_free (&homedir);
835
  
836 837 838 839 840 841
  return keyring;
  
 failed:
  if (!error_set)
    dbus_set_error_const (error,
                          DBUS_ERROR_NO_MEMORY,
842
                          NULL);
843 844 845 846 847 848 849 850 851 852 853 854 855
  if (keyring)
    _dbus_keyring_unref (keyring);
  _dbus_string_free (&homedir);
  return FALSE;

}

/**
 * Checks whether the context is a valid context.
 * Contexts that might cause confusion when used
 * in filenames are not allowed (contexts can't
 * start with a dot or contain dir separators).
 *
856 857 858
 * @todo this is the most inefficient implementation
 * imaginable.
 *
859 860 861 862 863 864
 * @param context the context
 * @returns #TRUE if valid
 */
dbus_bool_t
_dbus_keyring_validate_context (const DBusString *context)
{
865
  if (_dbus_string_get_length (context) == 0)
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
    {
      _dbus_verbose ("context is zero-length\n");
      return FALSE;
    }

  if (!_dbus_string_validate_ascii (context, 0,
                                    _dbus_string_get_length (context)))
    {
      _dbus_verbose ("context not valid ascii\n");
      return FALSE;
    }
  
  /* no directory separators */  
  if (_dbus_string_find (context, 0, "/", NULL))
    {
      _dbus_verbose ("context contains a slash\n");
      return FALSE;
    }

  if (_dbus_string_find (context, 0, "\\", NULL))
    {
      _dbus_verbose ("context contains a backslash\n");
      return FALSE;
    }

  /* prevent attempts to use dotfiles or ".." or ".lock"
   * all of which might allow some kind of attack
   */
  if (_dbus_string_find (context, 0, ".", NULL))
    {
      _dbus_verbose ("context contains a dot\n");
      return FALSE;
    }

900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
  /* no spaces/tabs, those are used for separators in the protocol */
  if (_dbus_string_find_blank (context, 0, NULL))
    {
      _dbus_verbose ("context contains a blank\n");
      return FALSE;
    }

  if (_dbus_string_find (context, 0, "\n", NULL))
    {
      _dbus_verbose ("context contains a newline\n");
      return FALSE;
    }

  if (_dbus_string_find (context, 0, "\r", NULL))
    {
      _dbus_verbose ("context contains a carriage return\n");
      return FALSE;
    }
  
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
  return TRUE;
}

static DBusKey*
find_recent_key (DBusKeyring *keyring)
{
  int i;
  long tv_sec, tv_usec;

  _dbus_get_current_time (&tv_sec, &tv_usec);
  
  i = 0;
  while (i < keyring->n_keys)
    {
      DBusKey *key = &keyring->keys[i];

935 936 937 938
      _dbus_verbose ("Key %d is %ld seconds old\n",
                     i, tv_sec - key->creation_time);
      
      if ((tv_sec - NEW_KEY_TIMEOUT_SECONDS) < key->creation_time)
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
        return key;
      
      ++i;
    }

  return NULL;
}

/**
 * Gets a recent key to use for authentication.
 * If no recent key exists, creates one. Returns
 * the key ID. If a key can't be written to the keyring
 * file so no recent key can be created, returns -1.
 * All valid keys are > 0.
 *
 * @param keyring the keyring
 * @param error error on failure
 * @returns key ID to use for auth, or -1 on failure
 */
int
_dbus_keyring_get_best_key (DBusKeyring  *keyring,
960
                            DBusError    *error)
961 962 963
{
  DBusKey *key;

964 965
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
  key = find_recent_key (keyring);
  if (key)
    return key->id;

  /* All our keys are too old, or we've never loaded the
   * keyring. Create a new one.
   */
  if (!_dbus_keyring_reload (keyring, TRUE,
                             error))
    return -1;

  key = find_recent_key (keyring);
  if (key)
    return key->id;
  else
    {
      dbus_set_error_const (error,
                            DBUS_ERROR_FAILED,
                            "No recent-enough key found in keyring, and unable to create a new key");
      return -1;
    }
}
988

989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
/**
 * Checks whether the keyring is for the given username.
 *
 * @param keyring the keyring
 * @param username the username to check
 *
 * @returns #TRUE if the keyring belongs to the given user
 */
dbus_bool_t
_dbus_keyring_is_for_user (DBusKeyring       *keyring,
                           const DBusString  *username)
{
  return _dbus_string_equal (&keyring->username,
                             username);
}

/**
 * Gets the hex-encoded secret key for the given ID.
 * Returns #FALSE if not enough memory. Returns #TRUE
 * but empty key on any other error such as unknown
 * key ID.
 *
 * @param keyring the keyring
 * @param key_id the key ID
 * @param hex_key string to append hex-encoded key to
 * @returns #TRUE if we had enough memory
 */
dbus_bool_t
_dbus_keyring_get_hex_key (DBusKeyring       *keyring,
                           int                key_id,
                           DBusString        *hex_key)
{
  DBusKey *key;

  key = find_key_by_id (keyring->keys,
                        keyring->n_keys,
                        key_id);
  if (key == NULL)
    return TRUE; /* had enough memory, so TRUE */

  return _dbus_string_hex_encode (&key->secret, 0,
                                  hex_key,
                                  _dbus_string_get_length (hex_key));
}

1034
/** @} */ /* end of exposed API */
1035

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
#ifdef DBUS_BUILD_TESTS
#include "dbus-test.h"
#include <stdio.h>

dbus_bool_t
_dbus_keyring_test (void)
{
  DBusString context;
  DBusKeyring *ring1;
  DBusKeyring *ring2;
  int id;
  DBusError error;
  int i;

  ring1 = NULL;
  ring2 = NULL;
  
  /* Context validation */
  
  _dbus_string_init_const (&context, "foo");
  _dbus_assert (_dbus_keyring_validate_context (&context));
  _dbus_string_init_const (&context, "org_freedesktop_blah");
  _dbus_assert (_dbus_keyring_validate_context (&context));
  
  _dbus_string_init_const (&context, "");
  _dbus_assert (!_dbus_keyring_validate_context (&context));
  _dbus_string_init_const (&context, ".foo");
  _dbus_assert (!_dbus_keyring_validate_context (&context));
  _dbus_string_init_const (&context, "bar.foo");
  _dbus_assert (!_dbus_keyring_validate_context (&context));
  _dbus_string_init_const (&context, "bar/foo");
  _dbus_assert (!_dbus_keyring_validate_context (&context));
  _dbus_string_init_const (&context, "bar\\foo");
  _dbus_assert (!_dbus_keyring_validate_context (&context));
  _dbus_string_init_const (&context, "foo\xfa\xf0");
  _dbus_assert (!_dbus_keyring_validate_context (&context));
  _dbus_string_init_const (&context, "foo\x80");
  _dbus_assert (!_dbus_keyring_validate_context (&context));
  _dbus_string_init_const (&context, "foo\x7f");
  _dbus_assert (_dbus_keyring_validate_context (&context));
1076 1077
  _dbus_string_init_const (&context, "foo bar");
  _dbus_assert (!_dbus_keyring_validate_context (&context));
1078
  
1079
  if (!_dbus_string_init (&context))
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
    _dbus_assert_not_reached ("no memory");
  if (!_dbus_string_append_byte (&context, '\0'))
    _dbus_assert_not_reached ("no memory");
  _dbus_assert (!_dbus_keyring_validate_context (&context));
  _dbus_string_free (&context);

  /* Now verify that if we create a key in keyring 1,
   * it is properly loaded in keyring 2
   */

  _dbus_string_init_const (&context, "org_freedesktop_dbus_testsuite");
  dbus_error_init (&error);
  ring1 = _dbus_keyring_new_homedir (NULL, &context,
                                     &error);
  _dbus_assert (ring1);
  _dbus_assert (error.name == NULL);

  id = _dbus_keyring_get_best_key (ring1, &error);
  if (id < 0)
    {
      fprintf (stderr, "Could not load keyring: %s\n", error.message);
      dbus_error_free (&error);
      goto failure;
    }

  ring2 = _dbus_keyring_new_homedir (NULL, &context, &error);
  _dbus_assert (ring2);
  _dbus_assert (error.name == NULL);
  
  if (ring1->n_keys != ring2->n_keys)
    {
      fprintf (stderr, "Different number of keys in keyrings\n");
      goto failure;
    }

  /* We guarantee we load and save keeping keys in a fixed
   * order
   */
  i = 0;
  while (i < ring1->n_keys)
    {
      if (ring1->keys[i].id != ring2->keys[i].id)
        {
          fprintf (stderr, "Keyring 1 has first key ID %d and keyring 2 has %d\n",
                   ring1->keys[i].id, ring2->keys[i].id);
          goto failure;
        }      

      if (ring1->keys[i].creation_time != ring2->keys[i].creation_time)
        {
          fprintf (stderr, "Keyring 1 has first key time %ld and keyring 2 has %ld\n",
                   ring1->keys[i].creation_time, ring2->keys[i].creation_time);
          goto failure;
        }

      if (!_dbus_string_equal (&ring1->keys[i].secret,
                               &ring2->keys[i].secret))
        {
          fprintf (stderr, "Keyrings 1 and 2 have different secrets for same ID/timestamp\n");
          goto failure;
        }
      
      ++i;
    }

  printf (" %d keys in test\n", ring1->n_keys);
1146

1147 1148 1149 1150 1151 1152 1153 1154
  /* Test ref/unref */
  _dbus_keyring_ref (ring1);
  _dbus_keyring_ref (ring2);
  _dbus_keyring_unref (ring1);
  _dbus_keyring_unref (ring2);


  /* really unref */
1155 1156
  _dbus_keyring_unref (ring1);
  _dbus_keyring_unref (ring2);
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
  
  return TRUE;

 failure:
  if (ring1)
    _dbus_keyring_unref (ring1);
  if (ring2)
    _dbus_keyring_unref (ring2);

  return FALSE;
}

#endif /* DBUS_BUILD_TESTS */