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