2005-01-27 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-keyring.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-keyring.c Store secret cookies in your homedir
3  *
4  * Copyright (C) 2003, 2004  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #include "dbus-keyring.h"
25 #include "dbus-userdb.h"
26 #include "dbus-protocol.h"
27 #include <dbus/dbus-string.h>
28 #include <dbus/dbus-list.h>
29 #include <dbus/dbus-sysdeps.h>
30
31 /**
32  * @defgroup DBusKeyring keyring class
33  * @ingroup  DBusInternals
34  * @brief DBusKeyring data structure
35  *
36  * Types and functions related to DBusKeyring. DBusKeyring is intended
37  * to manage cookies used to authenticate clients to servers.  This is
38  * essentially the "verify that client can read the user's homedir"
39  * authentication mechanism.  Both client and server must have access
40  * to the homedir.
41  *
42  * The secret keys are not kept in locked memory, and are written to a
43  * file in the user's homedir. However they are transient (only used
44  * by a single server instance for a fixed period of time, then
45  * discarded). Also, the keys are not sent over the wire.
46  *
47  * @todo there's a memory leak on some codepath in here, I saw it once
48  * when running make check - probably some specific initial cookies
49  * present in the cookie file, then depending on what we do with them.
50  */
51
52 /**
53  * @defgroup DBusKeyringInternals DBusKeyring implementation details
54  * @ingroup  DBusInternals
55  * @brief DBusKeyring implementation details
56  *
57  * The guts of DBusKeyring.
58  *
59  * @{
60  */
61
62 /** The maximum age of a key before we create a new key to use in
63  * challenges.  This isn't super-reliably enforced, since system
64  * clocks can change or be wrong, but we make a best effort to only
65  * use keys for a short time.
66  */
67 #define NEW_KEY_TIMEOUT_SECONDS     (60*5)
68 /**
69  * The time after which we drop a key from the secrets file.
70  * The EXPIRE_KEYS_TIMEOUT_SECONDS - NEW_KEY_TIMEOUT_SECONDS is the minimum
71  * time window a client has to complete authentication.
72  */
73 #define EXPIRE_KEYS_TIMEOUT_SECONDS (NEW_KEY_TIMEOUT_SECONDS + (60*2))
74 /**
75  * The maximum amount of time a key can be in the future.
76  */
77 #define MAX_TIME_TRAVEL_SECONDS (60*5)
78
79 /**
80  * Maximum number of keys in the keyring before
81  * we just ignore the rest
82  */
83 #ifdef DBUS_BUILD_TESTS
84 #define MAX_KEYS_IN_FILE 10
85 #else
86 #define MAX_KEYS_IN_FILE 256
87 #endif
88
89 /**
90  * A single key from the cookie file
91  */
92 typedef struct
93 {
94   dbus_int32_t id; /**< identifier used to refer to the key */
95
96   long creation_time; /**< when the key was generated,
97                        *   as unix timestamp. signed long
98                        *   matches struct timeval.
99                        */
100   
101   DBusString secret; /**< the actual key */
102
103 } DBusKey;
104
105 /**
106  * @brief Internals of DBusKeyring.
107  * 
108  * DBusKeyring internals. DBusKeyring is an opaque object, it must be
109  * used via accessor functions.
110  */
111 struct DBusKeyring
112 {
113   int refcount;             /**< Reference count */
114   DBusString username;      /**< Username keyring is for */
115   DBusString directory;     /**< Directory the below two items are inside */
116   DBusString filename;      /**< Keyring filename */
117   DBusString filename_lock; /**< Name of lockfile */
118   DBusKey *keys; /**< Keys loaded from the file */
119   int n_keys;    /**< Number of keys */
120 };
121
122 static DBusKeyring*
123 _dbus_keyring_new (void)
124 {
125   DBusKeyring *keyring;
126
127   keyring = dbus_new0 (DBusKeyring, 1);
128   if (keyring == NULL)
129     goto out_0;
130   
131   if (!_dbus_string_init (&keyring->directory))
132     goto out_1;
133
134   if (!_dbus_string_init (&keyring->filename))
135     goto out_2;
136
137   if (!_dbus_string_init (&keyring->filename_lock))
138     goto out_3;
139
140   if (!_dbus_string_init (&keyring->username))
141     goto out_4;
142   
143   keyring->refcount = 1;
144   keyring->keys = NULL;
145   keyring->n_keys = 0;
146
147   return keyring;
148
149  out_4:
150   _dbus_string_free (&keyring->filename_lock);
151  out_3:
152   _dbus_string_free (&keyring->filename);
153  out_2:
154   _dbus_string_free (&keyring->directory);
155  out_1:
156   dbus_free (keyring);
157  out_0:
158   return NULL;
159 }
160
161 static void
162 free_keys (DBusKey *keys,
163            int      n_keys)
164 {
165   int i;
166
167   /* should be safe for args NULL, 0 */
168   
169   i = 0;
170   while (i < n_keys)
171     {
172       _dbus_string_free (&keys[i].secret);
173       ++i;
174     }
175
176   dbus_free (keys);
177 }
178
179 /* Our locking scheme is highly unreliable.  However, there is
180  * unfortunately no reliable locking scheme in user home directories;
181  * between bugs in Linux NFS, people using Tru64 or other total crap
182  * NFS, AFS, random-file-system-of-the-week, and so forth, fcntl() in
183  * homedirs simply generates tons of bug reports. This has been
184  * learned through hard experience with GConf, unfortunately.
185  *
186  * This bad hack might work better for the kind of lock we have here,
187  * which we don't expect to hold for any length of time.  Crashing
188  * while we hold it should be unlikely, and timing out such that we
189  * delete a stale lock should also be unlikely except when the
190  * filesystem is running really slowly.  Stuff might break in corner
191  * cases but as long as it's not a security-level breakage it should
192  * be OK.
193  */
194
195 /** Maximum number of timeouts waiting for lock before we decide it's stale */
196 #define MAX_LOCK_TIMEOUTS 32
197 /** Length of each timeout while waiting for a lock */
198 #define LOCK_TIMEOUT_MILLISECONDS 250
199
200 static dbus_bool_t
201 _dbus_keyring_lock (DBusKeyring *keyring)
202 {
203   int n_timeouts;
204   
205   n_timeouts = 0;
206   while (n_timeouts < MAX_LOCK_TIMEOUTS)
207     {
208       DBusError error;
209
210       dbus_error_init (&error);
211       if (_dbus_create_file_exclusively (&keyring->filename_lock,
212                                          &error))
213         break;
214
215       _dbus_verbose ("Did not get lock file, sleeping %d milliseconds (%s)\n",
216                      LOCK_TIMEOUT_MILLISECONDS, error.message);
217       dbus_error_free (&error);
218
219       _dbus_sleep_milliseconds (LOCK_TIMEOUT_MILLISECONDS);
220       
221       ++n_timeouts;
222     }
223
224   if (n_timeouts == MAX_LOCK_TIMEOUTS)
225     {
226       DBusError error;
227       
228       _dbus_verbose ("Lock file timed out %d times, assuming stale\n",
229                      n_timeouts);
230
231       dbus_error_init (&error);
232
233       if (!_dbus_delete_file (&keyring->filename_lock, &error))
234         {
235           _dbus_verbose ("Couldn't delete old lock file: %s\n",
236                          error.message);
237           dbus_error_free (&error);
238           return FALSE;
239         }
240
241       if (!_dbus_create_file_exclusively (&keyring->filename_lock,
242                                           &error))
243         {
244           _dbus_verbose ("Couldn't create lock file after deleting stale one: %s\n",
245                          error.message);
246           dbus_error_free (&error);
247           return FALSE;
248         }
249     }
250   
251   return TRUE;
252 }
253
254 static void
255 _dbus_keyring_unlock (DBusKeyring *keyring)
256 {
257   DBusError error;
258   dbus_error_init (&error);
259   if (!_dbus_delete_file (&keyring->filename_lock, &error))
260     {
261       _dbus_warn ("Failed to delete lock file: %s\n",
262                   error.message);
263       dbus_error_free (&error);
264     }
265 }
266
267 static DBusKey*
268 find_key_by_id (DBusKey *keys,
269                 int      n_keys,
270                 int      id)
271 {
272   int i;
273
274   i = 0;
275   while (i < n_keys)
276     {
277       if (keys[i].id == id)
278         return &keys[i];
279       
280       ++i;
281     }
282
283   return NULL;
284 }
285
286 static dbus_bool_t
287 add_new_key (DBusKey  **keys_p,
288              int       *n_keys_p,
289              DBusError *error)
290 {
291   DBusKey *new;
292   DBusString bytes;
293   int id;
294   long timestamp;
295   const unsigned char *s;
296   dbus_bool_t retval;
297   DBusKey *keys;
298   int n_keys;
299
300   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
301   
302   if (!_dbus_string_init (&bytes))
303     {
304       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
305       return FALSE;
306     }
307
308   keys = *keys_p;
309   n_keys = *n_keys_p;
310   retval = FALSE;
311       
312   /* Generate an integer ID and then the actual key. */
313  retry:
314       
315   if (!_dbus_generate_random_bytes (&bytes, 4))
316     {
317       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
318       goto out;
319     }
320
321   s = (const unsigned char*) _dbus_string_get_const_data (&bytes);
322       
323   id = s[0] | (s[1] << 8) | (s[2] << 16) | (s[3] << 24);
324   if (id < 0)
325     id = - id;
326   _dbus_assert (id >= 0);
327
328   if (find_key_by_id (keys, n_keys, id) != NULL)
329     {
330       _dbus_string_set_length (&bytes, 0);
331       _dbus_verbose ("Key ID %d already existed, trying another one\n",
332                      id);
333       goto retry;
334     }
335
336   _dbus_verbose ("Creating key with ID %d\n", id);
337       
338 #define KEY_LENGTH_BYTES 24
339   _dbus_string_set_length (&bytes, 0);
340   if (!_dbus_generate_random_bytes (&bytes, KEY_LENGTH_BYTES))
341     {
342       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
343       goto out;
344     }
345
346   new = dbus_realloc (keys, sizeof (DBusKey) * (n_keys + 1));
347   if (new == NULL)
348     {
349       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
350       goto out;
351     }
352
353   keys = new;
354   *keys_p = keys; /* otherwise *keys_p ends up invalid */
355   n_keys += 1;
356
357   if (!_dbus_string_init (&keys[n_keys-1].secret))
358     {
359       n_keys -= 1; /* we don't want to free the one we didn't init */
360       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
361       goto out;
362     }
363
364   _dbus_get_current_time (&timestamp, NULL);
365       
366   keys[n_keys-1].id = id;
367   keys[n_keys-1].creation_time = timestamp;
368   if (!_dbus_string_move (&bytes, 0,
369                           &keys[n_keys-1].secret,
370                           0))
371     {
372       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
373       _dbus_string_free (&keys[n_keys-1].secret);
374       n_keys -= 1;
375       goto out;
376     }
377   
378   retval = TRUE;
379   
380  out:
381   *n_keys_p = n_keys;
382   
383   _dbus_string_free (&bytes);
384   return retval;
385 }
386
387 /**
388  * Reloads the keyring file, optionally adds one new key to the file,
389  * removes all expired keys from the file iff a key was added, then
390  * resaves the file.  Stores the keys from the file in keyring->keys.
391  * Note that the file is only resaved (written to) if a key is added,
392  * this means that only servers ever write to the file and need to
393  * lock it, which avoids a lot of lock contention at login time and
394  * such.
395  *
396  * @param keyring the keyring
397  * @param add_new #TRUE to add a new key to the file, expire keys, and resave
398  * @param error return location for errors
399  * @returns #FALSE on failure
400  */
401 static dbus_bool_t
402 _dbus_keyring_reload (DBusKeyring *keyring,
403                       dbus_bool_t  add_new,
404                       DBusError   *error)
405 {
406   DBusString contents;
407   DBusString line;
408   dbus_bool_t retval;
409   dbus_bool_t have_lock;
410   DBusKey *keys;
411   int n_keys;
412   int i;
413   long now;
414   DBusError tmp_error;
415
416   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
417   
418   if (!_dbus_string_init (&contents))
419     {
420       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
421       return FALSE;
422     }
423
424   if (!_dbus_string_init (&line))
425     {
426       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
427       _dbus_string_free (&contents);
428       return FALSE;
429     }
430
431   keys = NULL;
432   n_keys = 0;
433   retval = FALSE;
434   have_lock = FALSE;
435
436   _dbus_get_current_time (&now, NULL);
437   
438   if (add_new)
439     {
440       if (!_dbus_keyring_lock (keyring))
441         {
442           dbus_set_error (error, DBUS_ERROR_FAILED,
443                           "Could not lock keyring file to add to it");
444           goto out;
445         }
446
447       have_lock = TRUE;
448     }
449
450   dbus_error_init (&tmp_error);
451   if (!_dbus_file_get_contents (&contents, 
452                                 &keyring->filename,
453                                 &tmp_error))
454     {
455       _dbus_verbose ("Failed to load keyring file: %s\n",
456                      tmp_error.message);
457       /* continue with empty keyring file, so we recreate it */
458       dbus_error_free (&tmp_error);
459     }
460
461   if (!_dbus_string_validate_ascii (&contents, 0,
462                                     _dbus_string_get_length (&contents)))
463     {
464       _dbus_warn ("Secret keyring file contains non-ASCII! Ignoring existing contents\n");
465       _dbus_string_set_length (&contents, 0);
466     }
467
468   /* FIXME this is badly inefficient for large keyring files
469    * (not that large keyring files exist outside of test suites)
470    */
471   while (_dbus_string_pop_line (&contents, &line))
472     {
473       int next;
474       long val;
475       int id;
476       long timestamp;
477       int len;
478       int end;
479       DBusKey *new;
480
481       /* Don't load more than the max. */
482       if (n_keys >= (add_new ? MAX_KEYS_IN_FILE : MAX_KEYS_IN_FILE - 1))
483         break;
484       
485       next = 0;
486       if (!_dbus_string_parse_int (&line, 0, &val, &next))
487         {
488           _dbus_verbose ("could not parse secret key ID at start of line\n");
489           continue;
490         }
491
492       if (val > _DBUS_INT32_MAX || val < 0)
493         {
494           _dbus_verbose ("invalid secret key ID at start of line\n");
495           continue;
496         }
497       
498       id = val;
499
500       _dbus_string_skip_blank (&line, next, &next);
501       
502       if (!_dbus_string_parse_int (&line, next, &timestamp, &next))
503         {
504           _dbus_verbose ("could not parse secret key timestamp\n");
505           continue;
506         }
507
508       if (timestamp < 0 ||
509           (now + MAX_TIME_TRAVEL_SECONDS) < timestamp ||
510           (now - EXPIRE_KEYS_TIMEOUT_SECONDS) > timestamp)
511         {
512           _dbus_verbose ("dropping/ignoring %ld-seconds old key with timestamp %ld as current time is %ld\n",
513                          now - timestamp, timestamp, now);
514           continue;
515         }
516       
517       _dbus_string_skip_blank (&line, next, &next);
518
519       len = _dbus_string_get_length (&line);
520
521       if ((len - next) == 0)
522         {
523           _dbus_verbose ("no secret key after ID and timestamp\n");
524           continue;
525         }
526       
527       /* We have all three parts */
528       new = dbus_realloc (keys, sizeof (DBusKey) * (n_keys + 1));
529       if (new == NULL)
530         {
531           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
532           goto out;
533         }
534
535       keys = new;
536       n_keys += 1;
537
538       if (!_dbus_string_init (&keys[n_keys-1].secret))
539         {
540           n_keys -= 1; /* we don't want to free the one we didn't init */
541           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
542           goto out;
543         }
544       
545       keys[n_keys-1].id = id;
546       keys[n_keys-1].creation_time = timestamp;
547       if (!_dbus_string_hex_decode (&line, next, &end,
548                                     &keys[n_keys-1].secret, 0))
549         {
550           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
551           goto out;
552         }
553
554       if (_dbus_string_get_length (&line) != end)
555         {
556           _dbus_verbose ("invalid hex encoding in keyring file\n");
557           _dbus_string_free (&keys[n_keys - 1].secret);
558           n_keys -= 1;
559           continue;
560         }
561     }
562
563   _dbus_verbose ("Successfully loaded %d existing keys\n",
564                  n_keys);
565
566   if (add_new)
567     {
568       if (!add_new_key (&keys, &n_keys, error))
569         {
570           _dbus_verbose ("Failed to generate new key: %s\n",
571                          error ? "(unknown)" : error->message);
572           goto out;
573         }
574
575       _dbus_string_set_length (&contents, 0);
576
577       i = 0;
578       while (i < n_keys)
579         {
580           if (!_dbus_string_append_int (&contents,
581                                         keys[i].id))
582             goto nomem;
583
584           if (!_dbus_string_append_byte (&contents, ' '))
585             goto nomem;
586
587           if (!_dbus_string_append_int (&contents,
588                                         keys[i].creation_time))
589             goto nomem;
590
591           if (!_dbus_string_append_byte (&contents, ' '))
592             goto nomem;
593
594           if (!_dbus_string_hex_encode (&keys[i].secret, 0,
595                                         &contents,
596                                         _dbus_string_get_length (&contents)))
597             goto nomem;
598
599           if (!_dbus_string_append_byte (&contents, '\n'))
600             goto nomem;          
601           
602           ++i;
603           continue;
604
605         nomem:
606           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
607           goto out;
608         }
609       
610       if (!_dbus_string_save_to_file (&contents, &keyring->filename,
611                                       error))
612         goto out;
613     }
614
615   if (keyring->keys)
616     free_keys (keyring->keys, keyring->n_keys);
617   keyring->keys = keys;
618   keyring->n_keys = n_keys;
619   keys = NULL;
620   n_keys = 0;
621   
622   retval = TRUE;  
623   
624  out:
625   if (have_lock)
626     _dbus_keyring_unlock (keyring);
627   
628   if (! ((retval == TRUE && (error == NULL || error->name == NULL)) ||
629          (retval == FALSE && (error == NULL || error->name != NULL))))
630     {
631       if (error && error->name)
632         _dbus_verbose ("error is %s: %s\n", error->name, error->message);
633       _dbus_warn ("returning %d but error pointer %p name %s\n",
634                   retval, error, error->name ? error->name : "(none)");
635       _dbus_assert_not_reached ("didn't handle errors properly");
636     }
637   
638   if (keys != NULL)
639     {
640       i = 0;
641       while (i < n_keys)
642         {
643           _dbus_string_zero (&keys[i].secret);
644           _dbus_string_free (&keys[i].secret);
645           ++i;
646         }
647
648       dbus_free (keys);
649     }
650   
651   _dbus_string_free (&contents);
652   _dbus_string_free (&line);
653
654   return retval;
655 }
656
657 /** @} */ /* end of internals */
658
659 /**
660  * @addtogroup DBusKeyring
661  *
662  * @{
663  */
664
665 /**
666  * Increments reference count of the keyring
667  *
668  * @param keyring the keyring
669  * @returns the keyring
670  */
671 DBusKeyring *
672 _dbus_keyring_ref (DBusKeyring *keyring)
673 {
674   keyring->refcount += 1;
675
676   return keyring;
677 }
678
679 /**
680  * Decrements refcount and finalizes if it reaches
681  * zero.
682  *
683  * @param keyring the keyring
684  */
685 void
686 _dbus_keyring_unref (DBusKeyring *keyring)
687 {
688   keyring->refcount -= 1;
689
690   if (keyring->refcount == 0)
691     {
692       _dbus_string_free (&keyring->username);
693       _dbus_string_free (&keyring->filename);
694       _dbus_string_free (&keyring->filename_lock);
695       _dbus_string_free (&keyring->directory);
696       free_keys (keyring->keys, keyring->n_keys);
697       dbus_free (keyring);      
698     }
699 }
700
701 /**
702  * Creates a new keyring that lives in the ~/.dbus-keyrings
703  * directory of the given user. If the username is #NULL,
704  * uses the user owning the current process.
705  *
706  * @param username username to get keyring for, or #NULL
707  * @param context which keyring to get
708  * @param error return location for errors
709  * @returns the keyring or #NULL on error
710  */
711 DBusKeyring*
712 _dbus_keyring_new_homedir (const DBusString *username,
713                            const DBusString *context,
714                            DBusError        *error)
715 {
716   DBusString homedir;
717   DBusKeyring *keyring;
718   dbus_bool_t error_set;
719   DBusString dotdir;
720   DBusError tmp_error;
721
722   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
723   
724   keyring = NULL;
725   error_set = FALSE;
726   
727   if (!_dbus_string_init (&homedir))
728     {
729       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
730       return FALSE;
731     }
732
733   _dbus_string_init_const (&dotdir, ".dbus-keyrings");
734   
735   if (username == NULL)
736     {
737       const DBusString *const_homedir;
738
739       if (!_dbus_username_from_current_process (&username) ||
740           !_dbus_homedir_from_current_process (&const_homedir))
741         goto failed;
742
743       if (!_dbus_string_copy (const_homedir, 0,
744                               &homedir, 0))
745         goto failed;
746     }
747   else
748     {
749       if (!_dbus_homedir_from_username (username, &homedir))
750         goto failed;
751     }
752
753 #ifdef DBUS_BUILD_TESTS
754  {
755    const char *override;
756
757    override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
758    if (override != NULL && *override != '\0')
759      {
760        _dbus_string_set_length (&homedir, 0);
761        if (!_dbus_string_append (&homedir, override))
762          goto failed;
763
764        _dbus_verbose ("Using fake homedir for testing: %s\n",
765                       _dbus_string_get_const_data (&homedir));
766      }
767    else
768      {
769        static dbus_bool_t already_warned = FALSE;
770        if (!already_warned)
771          {
772            _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
773            already_warned = TRUE;
774          }
775      }
776  }
777 #endif
778   
779   _dbus_assert (username != NULL);    
780   
781   keyring = _dbus_keyring_new ();
782   if (keyring == NULL)
783     goto failed;
784
785   /* should have been validated already, but paranoia check here */
786   if (!_dbus_keyring_validate_context (context))
787     {
788       error_set = TRUE;
789       dbus_set_error_const (error,
790                             DBUS_ERROR_FAILED,
791                             "Invalid context in keyring creation");
792       goto failed;
793     }
794
795   if (!_dbus_string_copy (username, 0,
796                           &keyring->username, 0))
797     goto failed;
798   
799   if (!_dbus_string_copy (&homedir, 0,
800                           &keyring->directory, 0))
801     goto failed;
802   
803   if (!_dbus_concat_dir_and_file (&keyring->directory,
804                                   &dotdir))
805     goto failed;
806
807   if (!_dbus_string_copy (&keyring->directory, 0,
808                           &keyring->filename, 0))
809     goto failed;
810
811   if (!_dbus_concat_dir_and_file (&keyring->filename,
812                                   context))
813     goto failed;
814
815   if (!_dbus_string_copy (&keyring->filename, 0,
816                           &keyring->filename_lock, 0))
817     goto failed;
818
819   if (!_dbus_string_append (&keyring->filename_lock, ".lock"))
820     goto failed;
821
822   dbus_error_init (&tmp_error);
823   if (!_dbus_keyring_reload (keyring, FALSE, &tmp_error))
824     {
825       _dbus_verbose ("didn't load an existing keyring: %s\n",
826                      tmp_error.message);
827       dbus_error_free (&tmp_error);
828     }
829   
830   /* We don't fail fatally if we can't create the directory,
831    * but the keyring will probably always be empty
832    * unless someone else manages to create it
833    */
834   dbus_error_init (&tmp_error);
835   if (!_dbus_create_directory (&keyring->directory,
836                                &tmp_error))
837     {
838       _dbus_verbose ("Creating keyring directory: %s\n",
839                      tmp_error.message);
840       dbus_error_free (&tmp_error);
841     }
842
843   _dbus_string_free (&homedir);
844   
845   return keyring;
846   
847  failed:
848   if (!error_set)
849     dbus_set_error_const (error,
850                           DBUS_ERROR_NO_MEMORY,
851                           NULL);
852   if (keyring)
853     _dbus_keyring_unref (keyring);
854   _dbus_string_free (&homedir);
855   return FALSE;
856
857 }
858
859 /**
860  * Checks whether the context is a valid context.
861  * Contexts that might cause confusion when used
862  * in filenames are not allowed (contexts can't
863  * start with a dot or contain dir separators).
864  *
865  * @todo this is the most inefficient implementation
866  * imaginable.
867  *
868  * @param context the context
869  * @returns #TRUE if valid
870  */
871 dbus_bool_t
872 _dbus_keyring_validate_context (const DBusString *context)
873 {
874   if (_dbus_string_get_length (context) == 0)
875     {
876       _dbus_verbose ("context is zero-length\n");
877       return FALSE;
878     }
879
880   if (!_dbus_string_validate_ascii (context, 0,
881                                     _dbus_string_get_length (context)))
882     {
883       _dbus_verbose ("context not valid ascii\n");
884       return FALSE;
885     }
886   
887   /* no directory separators */  
888   if (_dbus_string_find (context, 0, "/", NULL))
889     {
890       _dbus_verbose ("context contains a slash\n");
891       return FALSE;
892     }
893
894   if (_dbus_string_find (context, 0, "\\", NULL))
895     {
896       _dbus_verbose ("context contains a backslash\n");
897       return FALSE;
898     }
899
900   /* prevent attempts to use dotfiles or ".." or ".lock"
901    * all of which might allow some kind of attack
902    */
903   if (_dbus_string_find (context, 0, ".", NULL))
904     {
905       _dbus_verbose ("context contains a dot\n");
906       return FALSE;
907     }
908
909   /* no spaces/tabs, those are used for separators in the protocol */
910   if (_dbus_string_find_blank (context, 0, NULL))
911     {
912       _dbus_verbose ("context contains a blank\n");
913       return FALSE;
914     }
915
916   if (_dbus_string_find (context, 0, "\n", NULL))
917     {
918       _dbus_verbose ("context contains a newline\n");
919       return FALSE;
920     }
921
922   if (_dbus_string_find (context, 0, "\r", NULL))
923     {
924       _dbus_verbose ("context contains a carriage return\n");
925       return FALSE;
926     }
927   
928   return TRUE;
929 }
930
931 static DBusKey*
932 find_recent_key (DBusKeyring *keyring)
933 {
934   int i;
935   long tv_sec, tv_usec;
936
937   _dbus_get_current_time (&tv_sec, &tv_usec);
938   
939   i = 0;
940   while (i < keyring->n_keys)
941     {
942       DBusKey *key = &keyring->keys[i];
943
944       _dbus_verbose ("Key %d is %ld seconds old\n",
945                      i, tv_sec - key->creation_time);
946       
947       if ((tv_sec - NEW_KEY_TIMEOUT_SECONDS) < key->creation_time)
948         return key;
949       
950       ++i;
951     }
952
953   return NULL;
954 }
955
956 /**
957  * Gets a recent key to use for authentication.
958  * If no recent key exists, creates one. Returns
959  * the key ID. If a key can't be written to the keyring
960  * file so no recent key can be created, returns -1.
961  * All valid keys are > 0.
962  *
963  * @param keyring the keyring
964  * @param error error on failure
965  * @returns key ID to use for auth, or -1 on failure
966  */
967 int
968 _dbus_keyring_get_best_key (DBusKeyring  *keyring,
969                             DBusError    *error)
970 {
971   DBusKey *key;
972
973   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
974   
975   key = find_recent_key (keyring);
976   if (key)
977     return key->id;
978
979   /* All our keys are too old, or we've never loaded the
980    * keyring. Create a new one.
981    */
982   if (!_dbus_keyring_reload (keyring, TRUE,
983                              error))
984     return -1;
985
986   key = find_recent_key (keyring);
987   if (key)
988     return key->id;
989   else
990     {
991       dbus_set_error_const (error,
992                             DBUS_ERROR_FAILED,
993                             "No recent-enough key found in keyring, and unable to create a new key");
994       return -1;
995     }
996 }
997
998 /**
999  * Checks whether the keyring is for the given username.
1000  *
1001  * @param keyring the keyring
1002  * @param username the username to check
1003  *
1004  * @returns #TRUE if the keyring belongs to the given user
1005  */
1006 dbus_bool_t
1007 _dbus_keyring_is_for_user (DBusKeyring       *keyring,
1008                            const DBusString  *username)
1009 {
1010   return _dbus_string_equal (&keyring->username,
1011                              username);
1012 }
1013
1014 /**
1015  * Gets the hex-encoded secret key for the given ID.
1016  * Returns #FALSE if not enough memory. Returns #TRUE
1017  * but empty key on any other error such as unknown
1018  * key ID.
1019  *
1020  * @param keyring the keyring
1021  * @param key_id the key ID
1022  * @param hex_key string to append hex-encoded key to
1023  * @returns #TRUE if we had enough memory
1024  */
1025 dbus_bool_t
1026 _dbus_keyring_get_hex_key (DBusKeyring       *keyring,
1027                            int                key_id,
1028                            DBusString        *hex_key)
1029 {
1030   DBusKey *key;
1031
1032   key = find_key_by_id (keyring->keys,
1033                         keyring->n_keys,
1034                         key_id);
1035   if (key == NULL)
1036     return TRUE; /* had enough memory, so TRUE */
1037
1038   return _dbus_string_hex_encode (&key->secret, 0,
1039                                   hex_key,
1040                                   _dbus_string_get_length (hex_key));
1041 }
1042
1043 /** @} */ /* end of exposed API */
1044
1045 #ifdef DBUS_BUILD_TESTS
1046 #include "dbus-test.h"
1047 #include <stdio.h>
1048
1049 dbus_bool_t
1050 _dbus_keyring_test (void)
1051 {
1052   DBusString context;
1053   DBusKeyring *ring1;
1054   DBusKeyring *ring2;
1055   int id;
1056   DBusError error;
1057   int i;
1058
1059   ring1 = NULL;
1060   ring2 = NULL;
1061   
1062   /* Context validation */
1063   
1064   _dbus_string_init_const (&context, "foo");
1065   _dbus_assert (_dbus_keyring_validate_context (&context));
1066   _dbus_string_init_const (&context, "org_freedesktop_blah");
1067   _dbus_assert (_dbus_keyring_validate_context (&context));
1068   
1069   _dbus_string_init_const (&context, "");
1070   _dbus_assert (!_dbus_keyring_validate_context (&context));
1071   _dbus_string_init_const (&context, ".foo");
1072   _dbus_assert (!_dbus_keyring_validate_context (&context));
1073   _dbus_string_init_const (&context, "bar.foo");
1074   _dbus_assert (!_dbus_keyring_validate_context (&context));
1075   _dbus_string_init_const (&context, "bar/foo");
1076   _dbus_assert (!_dbus_keyring_validate_context (&context));
1077   _dbus_string_init_const (&context, "bar\\foo");
1078   _dbus_assert (!_dbus_keyring_validate_context (&context));
1079   _dbus_string_init_const (&context, "foo\xfa\xf0");
1080   _dbus_assert (!_dbus_keyring_validate_context (&context));
1081   _dbus_string_init_const (&context, "foo\x80");
1082   _dbus_assert (!_dbus_keyring_validate_context (&context));
1083   _dbus_string_init_const (&context, "foo\x7f");
1084   _dbus_assert (_dbus_keyring_validate_context (&context));
1085   _dbus_string_init_const (&context, "foo bar");
1086   _dbus_assert (!_dbus_keyring_validate_context (&context));
1087   
1088   if (!_dbus_string_init (&context))
1089     _dbus_assert_not_reached ("no memory");
1090   if (!_dbus_string_append_byte (&context, '\0'))
1091     _dbus_assert_not_reached ("no memory");
1092   _dbus_assert (!_dbus_keyring_validate_context (&context));
1093   _dbus_string_free (&context);
1094
1095   /* Now verify that if we create a key in keyring 1,
1096    * it is properly loaded in keyring 2
1097    */
1098
1099   _dbus_string_init_const (&context, "org_freedesktop_dbus_testsuite");
1100   dbus_error_init (&error);
1101   ring1 = _dbus_keyring_new_homedir (NULL, &context,
1102                                      &error);
1103   _dbus_assert (ring1);
1104   _dbus_assert (error.name == NULL);
1105
1106   id = _dbus_keyring_get_best_key (ring1, &error);
1107   if (id < 0)
1108     {
1109       fprintf (stderr, "Could not load keyring: %s\n", error.message);
1110       dbus_error_free (&error);
1111       goto failure;
1112     }
1113
1114   ring2 = _dbus_keyring_new_homedir (NULL, &context, &error);
1115   _dbus_assert (ring2);
1116   _dbus_assert (error.name == NULL);
1117   
1118   if (ring1->n_keys != ring2->n_keys)
1119     {
1120       fprintf (stderr, "Different number of keys in keyrings\n");
1121       goto failure;
1122     }
1123
1124   /* We guarantee we load and save keeping keys in a fixed
1125    * order
1126    */
1127   i = 0;
1128   while (i < ring1->n_keys)
1129     {
1130       if (ring1->keys[i].id != ring2->keys[i].id)
1131         {
1132           fprintf (stderr, "Keyring 1 has first key ID %d and keyring 2 has %d\n",
1133                    ring1->keys[i].id, ring2->keys[i].id);
1134           goto failure;
1135         }      
1136
1137       if (ring1->keys[i].creation_time != ring2->keys[i].creation_time)
1138         {
1139           fprintf (stderr, "Keyring 1 has first key time %ld and keyring 2 has %ld\n",
1140                    ring1->keys[i].creation_time, ring2->keys[i].creation_time);
1141           goto failure;
1142         }
1143
1144       if (!_dbus_string_equal (&ring1->keys[i].secret,
1145                                &ring2->keys[i].secret))
1146         {
1147           fprintf (stderr, "Keyrings 1 and 2 have different secrets for same ID/timestamp\n");
1148           goto failure;
1149         }
1150       
1151       ++i;
1152     }
1153
1154   printf (" %d keys in test\n", ring1->n_keys);
1155
1156   /* Test ref/unref */
1157   _dbus_keyring_ref (ring1);
1158   _dbus_keyring_ref (ring2);
1159   _dbus_keyring_unref (ring1);
1160   _dbus_keyring_unref (ring2);
1161
1162
1163   /* really unref */
1164   _dbus_keyring_unref (ring1);
1165   _dbus_keyring_unref (ring2);
1166   
1167   return TRUE;
1168
1169  failure:
1170   if (ring1)
1171     _dbus_keyring_unref (ring1);
1172   if (ring2)
1173     _dbus_keyring_unref (ring2);
1174
1175   return FALSE;
1176 }
1177
1178 #endif /* DBUS_BUILD_TESTS */
1179