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