Main Page | Modules | Data Structures | File List | Data Fields | Related Pages

dbus-keyring.c

00001 /* -*- mode: C; c-file-style: "gnu" -*- */
00002 /* dbus-keyring.c Store secret cookies in your homedir
00003  *
00004  * Copyright (C) 2003  Red Hat Inc.
00005  *
00006  * Licensed under the Academic Free License version 2.0
00007  * 
00008  * This program is free software; you can redistribute it and/or modify
00009  * it under the terms of the GNU General Public License as published by
00010  * the Free Software Foundation; either version 2 of the License, or
00011  * (at your option) any later version.
00012  *
00013  * This program is distributed in the hope that it will be useful,
00014  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016  * GNU General Public License for more details.
00017  * 
00018  * You should have received a copy of the GNU General Public License
00019  * along with this program; if not, write to the Free Software
00020  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00021  *
00022  */
00023 
00024 #include "dbus-keyring.h"
00025 #include "dbus-userdb.h"
00026 #include <dbus/dbus-string.h>
00027 #include <dbus/dbus-list.h>
00028 #include <dbus/dbus-sysdeps.h>
00029 
00066 #define NEW_KEY_TIMEOUT_SECONDS     (60*5)
00067 
00072 #define EXPIRE_KEYS_TIMEOUT_SECONDS (NEW_KEY_TIMEOUT_SECONDS + (60*2))
00073 
00076 #define MAX_TIME_TRAVEL_SECONDS (60*5)
00077 
00082 #ifdef DBUS_BUILD_TESTS
00083 #define MAX_KEYS_IN_FILE 10
00084 #else
00085 #define MAX_KEYS_IN_FILE 256
00086 #endif
00087 
00091 typedef struct
00092 {
00093   dbus_int32_t id; 
00095   long creation_time; 
00100   DBusString secret; 
00102 } DBusKey;
00103 
00110 struct DBusKeyring
00111 {
00112   int refcount;             
00113   DBusString username;      
00114   DBusString directory;     
00115   DBusString filename;      
00116   DBusString filename_lock; 
00117   DBusKey *keys; 
00118   int n_keys;    
00119 };
00120 
00121 static DBusKeyring*
00122 _dbus_keyring_new (void)
00123 {
00124   DBusKeyring *keyring;
00125 
00126   keyring = dbus_new0 (DBusKeyring, 1);
00127   if (keyring == NULL)
00128     goto out_0;
00129   
00130   if (!_dbus_string_init (&keyring->directory))
00131     goto out_1;
00132 
00133   if (!_dbus_string_init (&keyring->filename))
00134     goto out_2;
00135 
00136   if (!_dbus_string_init (&keyring->filename_lock))
00137     goto out_3;
00138 
00139   if (!_dbus_string_init (&keyring->username))
00140     goto out_4;
00141   
00142   keyring->refcount = 1;
00143   keyring->keys = NULL;
00144   keyring->n_keys = 0;
00145 
00146   return keyring;
00147 
00148  out_4:
00149   _dbus_string_free (&keyring->filename_lock);
00150  out_3:
00151   _dbus_string_free (&keyring->filename);
00152  out_2:
00153   _dbus_string_free (&keyring->directory);
00154  out_1:
00155   dbus_free (keyring);
00156  out_0:
00157   return NULL;
00158 }
00159 
00160 static void
00161 free_keys (DBusKey *keys,
00162            int      n_keys)
00163 {
00164   int i;
00165 
00166   /* should be safe for args NULL, 0 */
00167   
00168   i = 0;
00169   while (i < n_keys)
00170     {
00171       _dbus_string_free (&keys[i].secret);
00172       ++i;
00173     }
00174 
00175   dbus_free (keys);
00176 }
00177 
00178 /* Our locking scheme is highly unreliable.  However, there is
00179  * unfortunately no reliable locking scheme in user home directories;
00180  * between bugs in Linux NFS, people using Tru64 or other total crap
00181  * NFS, AFS, random-file-system-of-the-week, and so forth, fcntl() in
00182  * homedirs simply generates tons of bug reports. This has been
00183  * learned through hard experience with GConf, unfortunately.
00184  *
00185  * This bad hack might work better for the kind of lock we have here,
00186  * which we don't expect to hold for any length of time.  Crashing
00187  * while we hold it should be unlikely, and timing out such that we
00188  * delete a stale lock should also be unlikely except when the
00189  * filesystem is running really slowly.  Stuff might break in corner
00190  * cases but as long as it's not a security-level breakage it should
00191  * be OK.
00192  */
00193 
00195 #define MAX_LOCK_TIMEOUTS 32
00196 
00197 #define LOCK_TIMEOUT_MILLISECONDS 250
00198 
00199 static dbus_bool_t
00200 _dbus_keyring_lock (DBusKeyring *keyring)
00201 {
00202   int n_timeouts;
00203   
00204   n_timeouts = 0;
00205   while (n_timeouts < MAX_LOCK_TIMEOUTS)
00206     {
00207       DBusError error;
00208 
00209       dbus_error_init (&error);
00210       if (_dbus_create_file_exclusively (&keyring->filename_lock,
00211                                          &error))
00212         break;
00213 
00214       _dbus_verbose ("Did not get lock file, sleeping %d milliseconds (%s)\n",
00215                      LOCK_TIMEOUT_MILLISECONDS, error.message);
00216       dbus_error_free (&error);
00217 
00218       _dbus_sleep_milliseconds (LOCK_TIMEOUT_MILLISECONDS);
00219       
00220       ++n_timeouts;
00221     }
00222 
00223   if (n_timeouts == MAX_LOCK_TIMEOUTS)
00224     {
00225       DBusError error;
00226       
00227       _dbus_verbose ("Lock file timed out %d times, assuming stale\n",
00228                      n_timeouts);
00229 
00230       dbus_error_init (&error);
00231 
00232       if (!_dbus_delete_file (&keyring->filename_lock, &error))
00233         {
00234           _dbus_verbose ("Couldn't delete old lock file: %s\n",
00235                          error.message);
00236           dbus_error_free (&error);
00237           return FALSE;
00238         }
00239 
00240       if (!_dbus_create_file_exclusively (&keyring->filename_lock,
00241                                           &error))
00242         {
00243           _dbus_verbose ("Couldn't create lock file after deleting stale one: %s\n",
00244                          error.message);
00245           dbus_error_free (&error);
00246           return FALSE;
00247         }
00248     }
00249   
00250   return TRUE;
00251 }
00252 
00253 static void
00254 _dbus_keyring_unlock (DBusKeyring *keyring)
00255 {
00256   DBusError error;
00257   dbus_error_init (&error);
00258   if (!_dbus_delete_file (&keyring->filename_lock, &error))
00259     {
00260       _dbus_warn ("Failed to delete lock file: %s\n",
00261                   error.message);
00262       dbus_error_free (&error);
00263     }
00264 }
00265 
00266 static DBusKey*
00267 find_key_by_id (DBusKey *keys,
00268                 int      n_keys,
00269                 int      id)
00270 {
00271   int i;
00272 
00273   i = 0;
00274   while (i < n_keys)
00275     {
00276       if (keys[i].id == id)
00277         return &keys[i];
00278       
00279       ++i;
00280     }
00281 
00282   return NULL;
00283 }
00284 
00285 static dbus_bool_t
00286 add_new_key (DBusKey  **keys_p,
00287              int       *n_keys_p,
00288              DBusError *error)
00289 {
00290   DBusKey *new;
00291   DBusString bytes;
00292   int id;
00293   unsigned long timestamp;
00294   const unsigned char *s;
00295   dbus_bool_t retval;
00296   DBusKey *keys;
00297   int n_keys;
00298 
00299   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00300   
00301   if (!_dbus_string_init (&bytes))
00302     {
00303       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00304       return FALSE;
00305     }
00306 
00307   keys = *keys_p;
00308   n_keys = *n_keys_p;
00309   retval = FALSE;
00310       
00311   /* Generate an integer ID and then the actual key. */
00312  retry:
00313       
00314   if (!_dbus_generate_random_bytes (&bytes, 4))
00315     {
00316       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00317       goto out;
00318     }
00319 
00320   s = (const unsigned char*) _dbus_string_get_const_data (&bytes);
00321       
00322   id = s[0] | (s[1] << 8) | (s[2] << 16) | (s[3] << 24);
00323   if (id < 0)
00324     id = - id;
00325   _dbus_assert (id >= 0);
00326 
00327   if (find_key_by_id (keys, n_keys, id) != NULL)
00328     {
00329       _dbus_string_set_length (&bytes, 0);
00330       _dbus_verbose ("Key ID %d already existed, trying another one\n",
00331                      id);
00332       goto retry;
00333     }
00334 
00335   _dbus_verbose ("Creating key with ID %d\n", id);
00336       
00337 #define KEY_LENGTH_BYTES 24
00338   _dbus_string_set_length (&bytes, 0);
00339   if (!_dbus_generate_random_bytes (&bytes, KEY_LENGTH_BYTES))
00340     {
00341       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00342       goto out;
00343     }
00344 
00345   new = dbus_realloc (keys, sizeof (DBusKey) * (n_keys + 1));
00346   if (new == NULL)
00347     {
00348       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00349       goto out;
00350     }
00351 
00352   keys = new;
00353   *keys_p = keys; /* otherwise *keys_p ends up invalid */
00354   n_keys += 1;
00355 
00356   if (!_dbus_string_init (&keys[n_keys-1].secret))
00357     {
00358       n_keys -= 1; /* we don't want to free the one we didn't init */
00359       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00360       goto out;
00361     }
00362 
00363   _dbus_get_current_time (&timestamp, NULL);
00364       
00365   keys[n_keys-1].id = id;
00366   keys[n_keys-1].creation_time = timestamp;
00367   if (!_dbus_string_move (&bytes, 0,
00368                           &keys[n_keys-1].secret,
00369                           0))
00370     {
00371       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00372       _dbus_string_free (&keys[n_keys-1].secret);
00373       n_keys -= 1;
00374       goto out;
00375     }
00376   
00377   retval = TRUE;
00378   
00379  out:
00380   *n_keys_p = n_keys;
00381   
00382   _dbus_string_free (&bytes);
00383   return retval;
00384 }
00385 
00400 static dbus_bool_t
00401 _dbus_keyring_reload (DBusKeyring *keyring,
00402                       dbus_bool_t  add_new,
00403                       DBusError   *error)
00404 {
00405   DBusString contents;
00406   DBusString line;
00407   dbus_bool_t retval;
00408   dbus_bool_t have_lock;
00409   DBusKey *keys;
00410   int n_keys;
00411   int i;
00412   long now;
00413   DBusError tmp_error;
00414 
00415   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00416   
00417   if (!_dbus_string_init (&contents))
00418     {
00419       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00420       return FALSE;
00421     }
00422 
00423   if (!_dbus_string_init (&line))
00424     {
00425       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00426       _dbus_string_free (&contents);
00427       return FALSE;
00428     }
00429 
00430   keys = NULL;
00431   n_keys = 0;
00432   retval = FALSE;
00433   have_lock = FALSE;
00434 
00435   _dbus_get_current_time (&now, NULL);
00436   
00437   if (add_new)
00438     {
00439       if (!_dbus_keyring_lock (keyring))
00440         {
00441           dbus_set_error (error, DBUS_ERROR_FAILED,
00442                           "Could not lock keyring file to add to it");
00443           goto out;
00444         }
00445 
00446       have_lock = TRUE;
00447     }
00448 
00449   dbus_error_init (&tmp_error);
00450   if (!_dbus_file_get_contents (&contents, 
00451                                 &keyring->filename,
00452                                 &tmp_error))
00453     {
00454       _dbus_verbose ("Failed to load keyring file: %s\n",
00455                      tmp_error.message);
00456       /* continue with empty keyring file, so we recreate it */
00457       dbus_error_free (&tmp_error);
00458     }
00459 
00460   if (!_dbus_string_validate_ascii (&contents, 0,
00461                                     _dbus_string_get_length (&contents)))
00462     {
00463       _dbus_warn ("Secret keyring file contains non-ASCII! Ignoring existing contents\n");
00464       _dbus_string_set_length (&contents, 0);
00465     }
00466 
00467   /* FIXME this is badly inefficient for large keyring files
00468    * (not that large keyring files exist outside of test suites)
00469    */
00470   while (_dbus_string_pop_line (&contents, &line))
00471     {
00472       int next;
00473       long val;
00474       int id;
00475       long timestamp;
00476       int len;
00477       DBusKey *new;
00478 
00479       /* Don't load more than the max. */
00480       if (n_keys >= (add_new ? MAX_KEYS_IN_FILE : MAX_KEYS_IN_FILE - 1))
00481         break;
00482       
00483       next = 0;
00484       if (!_dbus_string_parse_int (&line, 0, &val, &next))
00485         {
00486           _dbus_verbose ("could not parse secret key ID at start of line\n");
00487           continue;
00488         }
00489 
00490       if (val > _DBUS_INT_MAX || val < 0)
00491         {
00492           _dbus_verbose ("invalid secret key ID at start of line\n");
00493           continue;
00494         }
00495       
00496       id = val;
00497 
00498       _dbus_string_skip_blank (&line, next, &next);
00499       
00500       if (!_dbus_string_parse_int (&line, next, &timestamp, &next))
00501         {
00502           _dbus_verbose ("could not parse secret key timestamp\n");
00503           continue;
00504         }
00505 
00506       if (timestamp < 0 ||
00507           (now + MAX_TIME_TRAVEL_SECONDS) < timestamp ||
00508           (now - EXPIRE_KEYS_TIMEOUT_SECONDS) > timestamp)
00509         {
00510           _dbus_verbose ("dropping/ignoring %ld-seconds old key with timestamp %ld as current time is %ld\n",
00511                          now - timestamp, timestamp, now);
00512           continue;
00513         }
00514       
00515       _dbus_string_skip_blank (&line, next, &next);
00516 
00517       len = _dbus_string_get_length (&line);
00518 
00519       if ((len - next) == 0)
00520         {
00521           _dbus_verbose ("no secret key after ID and timestamp\n");
00522           continue;
00523         }
00524       
00525       /* We have all three parts */
00526       new = dbus_realloc (keys, sizeof (DBusKey) * (n_keys + 1));
00527       if (new == NULL)
00528         {
00529           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00530           goto out;
00531         }
00532 
00533       keys = new;
00534       n_keys += 1;
00535 
00536       if (!_dbus_string_init (&keys[n_keys-1].secret))
00537         {
00538           n_keys -= 1; /* we don't want to free the one we didn't init */
00539           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00540           goto out;
00541         }
00542       
00543       keys[n_keys-1].id = id;
00544       keys[n_keys-1].creation_time = timestamp;
00545       if (!_dbus_string_hex_decode (&line, next,
00546                                     &keys[n_keys-1].secret,
00547                                     0))
00548         {
00549           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00550           goto out;
00551         }
00552     }
00553 
00554   _dbus_verbose ("Successfully loaded %d existing keys\n",
00555                  n_keys);
00556 
00557   if (add_new)
00558     {
00559       if (!add_new_key (&keys, &n_keys, error))
00560         {
00561           _dbus_verbose ("Failed to generate new key: %s\n",
00562                          error ? "(unknown)" : error->message);
00563           goto out;
00564         }
00565 
00566       _dbus_string_set_length (&contents, 0);
00567 
00568       i = 0;
00569       while (i < n_keys)
00570         {
00571           if (!_dbus_string_append_int (&contents,
00572                                         keys[i].id))
00573             goto nomem;
00574 
00575           if (!_dbus_string_append_byte (&contents, ' '))
00576             goto nomem;
00577 
00578           if (!_dbus_string_append_int (&contents,
00579                                         keys[i].creation_time))
00580             goto nomem;
00581 
00582           if (!_dbus_string_append_byte (&contents, ' '))
00583             goto nomem;
00584 
00585           if (!_dbus_string_hex_encode (&keys[i].secret, 0,
00586                                         &contents,
00587                                         _dbus_string_get_length (&contents)))
00588             goto nomem;
00589 
00590           if (!_dbus_string_append_byte (&contents, '\n'))
00591             goto nomem;          
00592           
00593           ++i;
00594           continue;
00595 
00596         nomem:
00597           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00598           goto out;
00599         }
00600       
00601       if (!_dbus_string_save_to_file (&contents, &keyring->filename,
00602                                       error))
00603         goto out;
00604     }
00605 
00606   if (keyring->keys)
00607     free_keys (keyring->keys, keyring->n_keys);
00608   keyring->keys = keys;
00609   keyring->n_keys = n_keys;
00610   keys = NULL;
00611   n_keys = 0;
00612   
00613   retval = TRUE;  
00614   
00615  out:
00616   if (have_lock)
00617     _dbus_keyring_unlock (keyring);
00618   
00619   if (! ((retval == TRUE && (error == NULL || error->name == NULL)) ||
00620          (retval == FALSE && (error == NULL || error->name != NULL))))
00621     {
00622       if (error && error->name)
00623         _dbus_verbose ("error is %s: %s\n", error->name, error->message);
00624       _dbus_warn ("returning %d but error pointer %p name %s\n",
00625                   retval, error, error->name ? error->name : "(none)");
00626       _dbus_assert_not_reached ("didn't handle errors properly");
00627     }
00628   
00629   if (keys != NULL)
00630     {
00631       i = 0;
00632       while (i < n_keys)
00633         {
00634           _dbus_string_zero (&keys[i].secret);
00635           _dbus_string_free (&keys[i].secret);
00636           ++i;
00637         }
00638 
00639       dbus_free (keys);
00640     }
00641   
00642   _dbus_string_free (&contents);
00643   _dbus_string_free (&line);
00644 
00645   return retval;
00646 }
00647  /* end of internals */
00649 
00662 DBusKeyring *
00663 _dbus_keyring_ref (DBusKeyring *keyring)
00664 {
00665   keyring->refcount += 1;
00666 
00667   return keyring;
00668 }
00669 
00676 void
00677 _dbus_keyring_unref (DBusKeyring *keyring)
00678 {
00679   keyring->refcount -= 1;
00680 
00681   if (keyring->refcount == 0)
00682     {
00683       _dbus_string_free (&keyring->username);
00684       _dbus_string_free (&keyring->filename);
00685       _dbus_string_free (&keyring->filename_lock);
00686       _dbus_string_free (&keyring->directory);
00687       free_keys (keyring->keys, keyring->n_keys);
00688       dbus_free (keyring);      
00689     }
00690 }
00691 
00702 DBusKeyring*
00703 _dbus_keyring_new_homedir (const DBusString *username,
00704                            const DBusString *context,
00705                            DBusError        *error)
00706 {
00707   DBusString homedir;
00708   DBusKeyring *keyring;
00709   dbus_bool_t error_set;
00710   DBusString dotdir;
00711   DBusError tmp_error;
00712 
00713   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00714   
00715   keyring = NULL;
00716   error_set = FALSE;
00717   
00718   if (!_dbus_string_init (&homedir))
00719     {
00720       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00721       return FALSE;
00722     }
00723 
00724   _dbus_string_init_const (&dotdir, ".dbus-keyrings");
00725   
00726   if (username == NULL)
00727     {
00728       const DBusString *const_homedir;
00729 
00730       if (!_dbus_username_from_current_process (&username) ||
00731           !_dbus_homedir_from_current_process (&const_homedir))
00732         goto failed;
00733 
00734       if (!_dbus_string_copy (const_homedir, 0,
00735                               &homedir, 0))
00736         goto failed;
00737     }
00738   else
00739     {
00740       if (!_dbus_homedir_from_username (username, &homedir))
00741         goto failed;
00742     }
00743 
00744 #ifdef DBUS_BUILD_TESTS
00745  {
00746    const char *override;
00747 
00748    override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
00749    if (override != NULL && *override != '\0')
00750      {
00751        _dbus_string_set_length (&homedir, 0);
00752        if (!_dbus_string_append (&homedir, override))
00753          _dbus_assert_not_reached ("no memory");
00754 
00755        _dbus_verbose ("Using fake homedir for testing: %s\n",
00756                       _dbus_string_get_const_data (&homedir));
00757      }
00758    else
00759      {
00760        static dbus_bool_t already_warned = FALSE;
00761        if (!already_warned)
00762          {
00763            _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
00764            already_warned = TRUE;
00765          }
00766      }
00767  }
00768 #endif
00769   
00770   _dbus_assert (username != NULL);    
00771   
00772   keyring = _dbus_keyring_new ();
00773   if (keyring == NULL)
00774     goto failed;
00775 
00776   /* should have been validated already, but paranoia check here */
00777   if (!_dbus_keyring_validate_context (context))
00778     {
00779       error_set = TRUE;
00780       dbus_set_error_const (error,
00781                             DBUS_ERROR_FAILED,
00782                             "Invalid context in keyring creation");
00783       goto failed;
00784     }
00785 
00786   if (!_dbus_string_copy (username, 0,
00787                           &keyring->username, 0))
00788     goto failed;
00789   
00790   if (!_dbus_string_copy (&homedir, 0,
00791                           &keyring->directory, 0))
00792     goto failed;
00793   
00794   if (!_dbus_concat_dir_and_file (&keyring->directory,
00795                                   &dotdir))
00796     goto failed;
00797 
00798   if (!_dbus_string_copy (&keyring->directory, 0,
00799                           &keyring->filename, 0))
00800     goto failed;
00801 
00802   if (!_dbus_concat_dir_and_file (&keyring->filename,
00803                                   context))
00804     goto failed;
00805 
00806   if (!_dbus_string_copy (&keyring->filename, 0,
00807                           &keyring->filename_lock, 0))
00808     goto failed;
00809 
00810   if (!_dbus_string_append (&keyring->filename_lock, ".lock"))
00811     goto failed;
00812 
00813   dbus_error_init (&tmp_error);
00814   if (!_dbus_keyring_reload (keyring, FALSE, &tmp_error))
00815     {
00816       _dbus_verbose ("didn't load an existing keyring: %s\n",
00817                      tmp_error.message);
00818       dbus_error_free (&tmp_error);
00819     }
00820   
00821   /* We don't fail fatally if we can't create the directory,
00822    * but the keyring will probably always be empty
00823    * unless someone else manages to create it
00824    */
00825   dbus_error_init (&tmp_error);
00826   if (!_dbus_create_directory (&keyring->directory,
00827                                &tmp_error))
00828     {
00829       _dbus_verbose ("Creating keyring directory: %s\n",
00830                      tmp_error.message);
00831       dbus_error_free (&tmp_error);
00832     }
00833 
00834   _dbus_string_free (&homedir);
00835   
00836   return keyring;
00837   
00838  failed:
00839   if (!error_set)
00840     dbus_set_error_const (error,
00841                           DBUS_ERROR_NO_MEMORY,
00842                           NULL);
00843   if (keyring)
00844     _dbus_keyring_unref (keyring);
00845   _dbus_string_free (&homedir);
00846   return FALSE;
00847 
00848 }
00849 
00862 dbus_bool_t
00863 _dbus_keyring_validate_context (const DBusString *context)
00864 {
00865   if (_dbus_string_get_length (context) == 0)
00866     {
00867       _dbus_verbose ("context is zero-length\n");
00868       return FALSE;
00869     }
00870 
00871   if (!_dbus_string_validate_ascii (context, 0,
00872                                     _dbus_string_get_length (context)))
00873     {
00874       _dbus_verbose ("context not valid ascii\n");
00875       return FALSE;
00876     }
00877   
00878   /* no directory separators */  
00879   if (_dbus_string_find (context, 0, "/", NULL))
00880     {
00881       _dbus_verbose ("context contains a slash\n");
00882       return FALSE;
00883     }
00884 
00885   if (_dbus_string_find (context, 0, "\\", NULL))
00886     {
00887       _dbus_verbose ("context contains a backslash\n");
00888       return FALSE;
00889     }
00890 
00891   /* prevent attempts to use dotfiles or ".." or ".lock"
00892    * all of which might allow some kind of attack
00893    */
00894   if (_dbus_string_find (context, 0, ".", NULL))
00895     {
00896       _dbus_verbose ("context contains a dot\n");
00897       return FALSE;
00898     }
00899 
00900   /* no spaces/tabs, those are used for separators in the protocol */
00901   if (_dbus_string_find_blank (context, 0, NULL))
00902     {
00903       _dbus_verbose ("context contains a blank\n");
00904       return FALSE;
00905     }
00906 
00907   if (_dbus_string_find (context, 0, "\n", NULL))
00908     {
00909       _dbus_verbose ("context contains a newline\n");
00910       return FALSE;
00911     }
00912 
00913   if (_dbus_string_find (context, 0, "\r", NULL))
00914     {
00915       _dbus_verbose ("context contains a carriage return\n");
00916       return FALSE;
00917     }
00918   
00919   return TRUE;
00920 }
00921 
00922 static DBusKey*
00923 find_recent_key (DBusKeyring *keyring)
00924 {
00925   int i;
00926   long tv_sec, tv_usec;
00927 
00928   _dbus_get_current_time (&tv_sec, &tv_usec);
00929   
00930   i = 0;
00931   while (i < keyring->n_keys)
00932     {
00933       DBusKey *key = &keyring->keys[i];
00934 
00935       _dbus_verbose ("Key %d is %ld seconds old\n",
00936                      i, tv_sec - key->creation_time);
00937       
00938       if ((tv_sec - NEW_KEY_TIMEOUT_SECONDS) < key->creation_time)
00939         return key;
00940       
00941       ++i;
00942     }
00943 
00944   return NULL;
00945 }
00946 
00958 int
00959 _dbus_keyring_get_best_key (DBusKeyring  *keyring,
00960                             DBusError    *error)
00961 {
00962   DBusKey *key;
00963 
00964   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00965   
00966   key = find_recent_key (keyring);
00967   if (key)
00968     return key->id;
00969 
00970   /* All our keys are too old, or we've never loaded the
00971    * keyring. Create a new one.
00972    */
00973   if (!_dbus_keyring_reload (keyring, TRUE,
00974                              error))
00975     return -1;
00976 
00977   key = find_recent_key (keyring);
00978   if (key)
00979     return key->id;
00980   else
00981     {
00982       dbus_set_error_const (error,
00983                             DBUS_ERROR_FAILED,
00984                             "No recent-enough key found in keyring, and unable to create a new key");
00985       return -1;
00986     }
00987 }
00988 
00997 dbus_bool_t
00998 _dbus_keyring_is_for_user (DBusKeyring       *keyring,
00999                            const DBusString  *username)
01000 {
01001   return _dbus_string_equal (&keyring->username,
01002                              username);
01003 }
01004 
01016 dbus_bool_t
01017 _dbus_keyring_get_hex_key (DBusKeyring       *keyring,
01018                            int                key_id,
01019                            DBusString        *hex_key)
01020 {
01021   DBusKey *key;
01022 
01023   key = find_key_by_id (keyring->keys,
01024                         keyring->n_keys,
01025                         key_id);
01026   if (key == NULL)
01027     return TRUE; /* had enough memory, so TRUE */
01028 
01029   return _dbus_string_hex_encode (&key->secret, 0,
01030                                   hex_key,
01031                                   _dbus_string_get_length (hex_key));
01032 }
01033  /* end of exposed API */
01035 
01036 #ifdef DBUS_BUILD_TESTS
01037 #include "dbus-test.h"
01038 #include <stdio.h>
01039 
01040 dbus_bool_t
01041 _dbus_keyring_test (void)
01042 {
01043   DBusString context;
01044   DBusKeyring *ring1;
01045   DBusKeyring *ring2;
01046   int id;
01047   DBusError error;
01048   int i;
01049 
01050   ring1 = NULL;
01051   ring2 = NULL;
01052   
01053   /* Context validation */
01054   
01055   _dbus_string_init_const (&context, "foo");
01056   _dbus_assert (_dbus_keyring_validate_context (&context));
01057   _dbus_string_init_const (&context, "org_freedesktop_blah");
01058   _dbus_assert (_dbus_keyring_validate_context (&context));
01059   
01060   _dbus_string_init_const (&context, "");
01061   _dbus_assert (!_dbus_keyring_validate_context (&context));
01062   _dbus_string_init_const (&context, ".foo");
01063   _dbus_assert (!_dbus_keyring_validate_context (&context));
01064   _dbus_string_init_const (&context, "bar.foo");
01065   _dbus_assert (!_dbus_keyring_validate_context (&context));
01066   _dbus_string_init_const (&context, "bar/foo");
01067   _dbus_assert (!_dbus_keyring_validate_context (&context));
01068   _dbus_string_init_const (&context, "bar\\foo");
01069   _dbus_assert (!_dbus_keyring_validate_context (&context));
01070   _dbus_string_init_const (&context, "foo\xfa\xf0");
01071   _dbus_assert (!_dbus_keyring_validate_context (&context));
01072   _dbus_string_init_const (&context, "foo\x80");
01073   _dbus_assert (!_dbus_keyring_validate_context (&context));
01074   _dbus_string_init_const (&context, "foo\x7f");
01075   _dbus_assert (_dbus_keyring_validate_context (&context));
01076   _dbus_string_init_const (&context, "foo bar");
01077   _dbus_assert (!_dbus_keyring_validate_context (&context));
01078   
01079   if (!_dbus_string_init (&context))
01080     _dbus_assert_not_reached ("no memory");
01081   if (!_dbus_string_append_byte (&context, '\0'))
01082     _dbus_assert_not_reached ("no memory");
01083   _dbus_assert (!_dbus_keyring_validate_context (&context));
01084   _dbus_string_free (&context);
01085 
01086   /* Now verify that if we create a key in keyring 1,
01087    * it is properly loaded in keyring 2
01088    */
01089 
01090   _dbus_string_init_const (&context, "org_freedesktop_dbus_testsuite");
01091   dbus_error_init (&error);
01092   ring1 = _dbus_keyring_new_homedir (NULL, &context,
01093                                      &error);
01094   _dbus_assert (ring1);
01095   _dbus_assert (error.name == NULL);
01096 
01097   id = _dbus_keyring_get_best_key (ring1, &error);
01098   if (id < 0)
01099     {
01100       fprintf (stderr, "Could not load keyring: %s\n", error.message);
01101       dbus_error_free (&error);
01102       goto failure;
01103     }
01104 
01105   ring2 = _dbus_keyring_new_homedir (NULL, &context, &error);
01106   _dbus_assert (ring2);
01107   _dbus_assert (error.name == NULL);
01108   
01109   if (ring1->n_keys != ring2->n_keys)
01110     {
01111       fprintf (stderr, "Different number of keys in keyrings\n");
01112       goto failure;
01113     }
01114 
01115   /* We guarantee we load and save keeping keys in a fixed
01116    * order
01117    */
01118   i = 0;
01119   while (i < ring1->n_keys)
01120     {
01121       if (ring1->keys[i].id != ring2->keys[i].id)
01122         {
01123           fprintf (stderr, "Keyring 1 has first key ID %d and keyring 2 has %d\n",
01124                    ring1->keys[i].id, ring2->keys[i].id);
01125           goto failure;
01126         }      
01127 
01128       if (ring1->keys[i].creation_time != ring2->keys[i].creation_time)
01129         {
01130           fprintf (stderr, "Keyring 1 has first key time %ld and keyring 2 has %ld\n",
01131                    ring1->keys[i].creation_time, ring2->keys[i].creation_time);
01132           goto failure;
01133         }
01134 
01135       if (!_dbus_string_equal (&ring1->keys[i].secret,
01136                                &ring2->keys[i].secret))
01137         {
01138           fprintf (stderr, "Keyrings 1 and 2 have different secrets for same ID/timestamp\n");
01139           goto failure;
01140         }
01141       
01142       ++i;
01143     }
01144 
01145   printf (" %d keys in test\n", ring1->n_keys);
01146 
01147   /* Test ref/unref */
01148   _dbus_keyring_ref (ring1);
01149   _dbus_keyring_ref (ring2);
01150   _dbus_keyring_unref (ring1);
01151   _dbus_keyring_unref (ring2);
01152 
01153 
01154   /* really unref */
01155   _dbus_keyring_unref (ring1);
01156   _dbus_keyring_unref (ring2);
01157   
01158   return TRUE;
01159 
01160  failure:
01161   if (ring1)
01162     _dbus_keyring_unref (ring1);
01163   if (ring2)
01164     _dbus_keyring_unref (ring2);
01165 
01166   return FALSE;
01167 }
01168 
01169 #endif /* DBUS_BUILD_TESTS */
01170      

Generated on Sun Mar 21 03:52:04 2004 for D-BUS by doxygen 1.3.6-20040222