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