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