chiark / gitweb /
agent: Serialize access to passphrase cache.
[gnupg2.git] / agent / cache.c
1 /* cache.c - keep a cache of passphrases
2  * Copyright (C) 2002, 2010 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
6  * GnuPG is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GnuPG is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <https://www.gnu.org/licenses/>.
18  */
19
20 #include <config.h>
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <time.h>
26 #include <assert.h>
27 #include <npth.h>
28
29 #include "agent.h"
30
31 /* The size of the encryption key in bytes.  */
32 #define ENCRYPTION_KEYSIZE (128/8)
33
34 /* A mutex used to serialize access to the cache.  */
35 static npth_mutex_t cache_lock;
36 /* The encryption context.  This is the only place where the
37    encryption key for all cached entries is available.  It would be nice
38    to keep this (or just the key) in some hardware device, for example
39    a TPM.  Libgcrypt could be extended to provide such a service.
40    With the current scheme it is easy to retrieve the cached entries
41    if access to Libgcrypt's memory is available.  The encryption
42    merely avoids grepping for clear texts in the memory.  Nevertheless
43    the encryption provides the necessary infrastructure to make it
44    more secure.  */
45 static gcry_cipher_hd_t encryption_handle;
46
47
48 struct secret_data_s {
49   int  totallen; /* This includes the padding and space for AESWRAP. */
50   char data[1];  /* A string.  */
51 };
52
53 typedef struct cache_item_s *ITEM;
54 struct cache_item_s {
55   ITEM next;
56   time_t created;
57   time_t accessed;
58   int ttl;  /* max. lifetime given in seconds, -1 one means infinite */
59   struct secret_data_s *pw;
60   cache_mode_t cache_mode;
61   char key[1];
62 };
63
64 /* The cache himself.  */
65 static ITEM thecache;
66
67 /* NULL or the last cache key stored by agent_store_cache_hit.  */
68 static char *last_stored_cache_key;
69
70
71 /* This function must be called once to initialize this module. It
72    has to be done before a second thread is spawned.  */
73 void
74 initialize_module_cache (void)
75 {
76   int err;
77
78   err = npth_mutex_init (&cache_lock, NULL);
79
80   if (err)
81     log_fatal ("error initializing cache module: %s\n", strerror (err));
82 }
83
84
85 void
86 deinitialize_module_cache (void)
87 {
88   gcry_cipher_close (encryption_handle);
89   encryption_handle = NULL;
90 }
91
92
93 /* We do the encryption init on the fly.  We can't do it in the module
94    init code because that is run before we listen for connections and
95    in case we are started on demand by gpg etc. it will only wait for
96    a few seconds to decide whether the agent may now accept
97    connections.  Thus we should get into listen state as soon as
98    possible.  */
99 static gpg_error_t
100 init_encryption (void)
101 {
102   gpg_error_t err;
103   void *key;
104
105   if (encryption_handle)
106     return 0; /* Shortcut - Already initialized.  */
107
108   err = gcry_cipher_open (&encryption_handle, GCRY_CIPHER_AES128,
109                           GCRY_CIPHER_MODE_AESWRAP, GCRY_CIPHER_SECURE);
110   if (!err)
111     {
112       key = gcry_random_bytes (ENCRYPTION_KEYSIZE, GCRY_STRONG_RANDOM);
113       if (!key)
114         err = gpg_error_from_syserror ();
115       else
116         {
117           err = gcry_cipher_setkey (encryption_handle, key, ENCRYPTION_KEYSIZE);
118           xfree (key);
119         }
120       if (err)
121         {
122           gcry_cipher_close (encryption_handle);
123           encryption_handle = NULL;
124         }
125     }
126   if (err)
127     log_error ("error initializing cache encryption context: %s\n",
128                gpg_strerror (err));
129
130   return err? gpg_error (GPG_ERR_NOT_INITIALIZED) : 0;
131 }
132
133
134
135 static void
136 release_data (struct secret_data_s *data)
137 {
138    xfree (data);
139 }
140
141 static gpg_error_t
142 new_data (const char *string, struct secret_data_s **r_data)
143 {
144   gpg_error_t err;
145   struct secret_data_s *d, *d_enc;
146   size_t length;
147   int total;
148
149   *r_data = NULL;
150
151   err = init_encryption ();
152   if (err)
153     return err;
154
155   length = strlen (string) + 1;
156
157   /* We pad the data to 32 bytes so that it get more complicated
158      finding something out by watching allocation patterns.  This is
159      usually not possible but we better assume nothing about our secure
160      storage provider.  To support the AESWRAP mode we need to add 8
161      extra bytes as well. */
162   total = (length + 8) + 32 - ((length+8) % 32);
163
164   d = xtrymalloc_secure (sizeof *d + total - 1);
165   if (!d)
166     return gpg_error_from_syserror ();
167   memcpy (d->data, string, length);
168
169   d_enc = xtrymalloc (sizeof *d_enc + total - 1);
170   if (!d_enc)
171     {
172       err = gpg_error_from_syserror ();
173       xfree (d);
174       return err;
175     }
176
177   d_enc->totallen = total;
178   err = gcry_cipher_encrypt (encryption_handle, d_enc->data, total,
179                              d->data, total - 8);
180   xfree (d);
181   if (err)
182     {
183       xfree (d_enc);
184       return err;
185     }
186   *r_data = d_enc;
187   return 0;
188 }
189
190
191
192 /* Check whether there are items to expire.  */
193 static void
194 housekeeping (void)
195 {
196   ITEM r, rprev;
197   time_t current = gnupg_get_time ();
198
199   /* First expire the actual data */
200   for (r=thecache; r; r = r->next)
201     {
202       if (r->pw && r->ttl >= 0 && r->accessed + r->ttl < current)
203         {
204           if (DBG_CACHE)
205             log_debug ("  expired '%s' (%ds after last access)\n",
206                        r->key, r->ttl);
207           release_data (r->pw);
208           r->pw = NULL;
209           r->accessed = current;
210         }
211     }
212
213   /* Second, make sure that we also remove them based on the created stamp so
214      that the user has to enter it from time to time. */
215   for (r=thecache; r; r = r->next)
216     {
217       unsigned long maxttl;
218
219       switch (r->cache_mode)
220         {
221         case CACHE_MODE_SSH: maxttl = opt.max_cache_ttl_ssh; break;
222         default: maxttl = opt.max_cache_ttl; break;
223         }
224       if (r->pw && r->created + maxttl < current)
225         {
226           if (DBG_CACHE)
227             log_debug ("  expired '%s' (%lus after creation)\n",
228                        r->key, opt.max_cache_ttl);
229           release_data (r->pw);
230           r->pw = NULL;
231           r->accessed = current;
232         }
233     }
234
235   /* Third, make sure that we don't have too many items in the list.
236      Expire old and unused entries after 30 minutes */
237   for (rprev=NULL, r=thecache; r; )
238     {
239       if (!r->pw && r->ttl >= 0 && r->accessed + 60*30 < current)
240         {
241           ITEM r2 = r->next;
242           if (DBG_CACHE)
243             log_debug ("  removed '%s' (mode %d) (slot not used for 30m)\n",
244                        r->key, r->cache_mode);
245           xfree (r);
246           if (!rprev)
247             thecache = r2;
248           else
249             rprev->next = r2;
250           r = r2;
251         }
252       else
253         {
254           rprev = r;
255           r = r->next;
256         }
257     }
258 }
259
260
261 void
262 agent_flush_cache (void)
263 {
264   ITEM r;
265   int res;
266
267   if (DBG_CACHE)
268     log_debug ("agent_flush_cache\n");
269
270   res = npth_mutex_lock (&cache_lock);
271   if (res)
272     log_fatal ("failed to acquire cache mutex: %s\n", strerror (res));
273
274   for (r=thecache; r; r = r->next)
275     {
276       if (r->pw)
277         {
278           if (DBG_CACHE)
279             log_debug ("  flushing '%s'\n", r->key);
280           release_data (r->pw);
281           r->pw = NULL;
282           r->accessed = 0;
283         }
284     }
285
286   res = npth_mutex_unlock (&cache_lock);
287   if (res)
288     log_fatal ("failed to release cache mutex: %s\n", strerror (res));
289 }
290
291
292 /* Compare two cache modes.  */
293 static int
294 cache_mode_equal (cache_mode_t a, cache_mode_t b)
295 {
296   /* CACHE_MODE_ANY matches any mode other than CACHE_MODE_IGNORE.  */
297   return ((a == CACHE_MODE_ANY && b != CACHE_MODE_IGNORE)
298           || (b == CACHE_MODE_ANY && a != CACHE_MODE_IGNORE) || a == b);
299 }
300
301
302 /* Store the string DATA in the cache under KEY and mark it with a
303    maximum lifetime of TTL seconds.  If there is already data under
304    this key, it will be replaced.  Using a DATA of NULL deletes the
305    entry.  A TTL of 0 is replaced by the default TTL and a TTL of -1
306    set infinite timeout.  CACHE_MODE is stored with the cache entry
307    and used to select different timeouts.  */
308 int
309 agent_put_cache (const char *key, cache_mode_t cache_mode,
310                  const char *data, int ttl)
311 {
312   gpg_error_t err = 0;
313   ITEM r;
314   int res;
315
316   res = npth_mutex_lock (&cache_lock);
317   if (res)
318     log_fatal ("failed to acquire cache mutex: %s\n", strerror (res));
319
320   if (DBG_CACHE)
321     log_debug ("agent_put_cache '%s' (mode %d) requested ttl=%d\n",
322                key, cache_mode, ttl);
323   housekeeping ();
324
325   if (!ttl)
326     {
327       switch(cache_mode)
328         {
329         case CACHE_MODE_SSH: ttl = opt.def_cache_ttl_ssh; break;
330         default: ttl = opt.def_cache_ttl; break;
331         }
332     }
333   if ((!ttl && data) || cache_mode == CACHE_MODE_IGNORE)
334     goto out;
335
336   for (r=thecache; r; r = r->next)
337     {
338       if (((cache_mode != CACHE_MODE_USER
339             && cache_mode != CACHE_MODE_NONCE)
340            || cache_mode_equal (r->cache_mode, cache_mode))
341           && !strcmp (r->key, key))
342         break;
343     }
344   if (r) /* Replace.  */
345     {
346       if (r->pw)
347         {
348           release_data (r->pw);
349           r->pw = NULL;
350         }
351       if (data)
352         {
353           r->created = r->accessed = gnupg_get_time ();
354           r->ttl = ttl;
355           r->cache_mode = cache_mode;
356           err = new_data (data, &r->pw);
357           if (err)
358             log_error ("error replacing cache item: %s\n", gpg_strerror (err));
359         }
360     }
361   else if (data) /* Insert.  */
362     {
363       r = xtrycalloc (1, sizeof *r + strlen (key));
364       if (!r)
365         err = gpg_error_from_syserror ();
366       else
367         {
368           strcpy (r->key, key);
369           r->created = r->accessed = gnupg_get_time ();
370           r->ttl = ttl;
371           r->cache_mode = cache_mode;
372           err = new_data (data, &r->pw);
373           if (err)
374             xfree (r);
375           else
376             {
377               r->next = thecache;
378               thecache = r;
379             }
380         }
381       if (err)
382         log_error ("error inserting cache item: %s\n", gpg_strerror (err));
383     }
384
385  out:
386   res = npth_mutex_unlock (&cache_lock);
387   if (res)
388     log_fatal ("failed to release cache mutex: %s\n", strerror (res));
389
390   return err;
391 }
392
393
394 /* Try to find an item in the cache.  Note that we currently don't
395    make use of CACHE_MODE except for CACHE_MODE_NONCE and
396    CACHE_MODE_USER.  */
397 char *
398 agent_get_cache (const char *key, cache_mode_t cache_mode)
399 {
400   gpg_error_t err;
401   ITEM r;
402   char *value = NULL;
403   int res;
404   int last_stored = 0;
405
406   if (cache_mode == CACHE_MODE_IGNORE)
407     return NULL;
408
409   res = npth_mutex_lock (&cache_lock);
410   if (res)
411     log_fatal ("failed to acquire cache mutex: %s\n", strerror (res));
412
413   if (!key)
414     {
415       key = last_stored_cache_key;
416       if (!key)
417         goto out;
418       last_stored = 1;
419     }
420
421   if (DBG_CACHE)
422     log_debug ("agent_get_cache '%s' (mode %d)%s ...\n",
423                key, cache_mode,
424                last_stored? " (stored cache key)":"");
425   housekeeping ();
426
427   for (r=thecache; r; r = r->next)
428     {
429       if (r->pw
430           && ((cache_mode != CACHE_MODE_USER
431                && cache_mode != CACHE_MODE_NONCE)
432               || cache_mode_equal (r->cache_mode, cache_mode))
433           && !strcmp (r->key, key))
434         {
435           /* Note: To avoid races KEY may not be accessed anymore below.  */
436           r->accessed = gnupg_get_time ();
437           if (DBG_CACHE)
438             log_debug ("... hit\n");
439           if (r->pw->totallen < 32)
440             err = gpg_error (GPG_ERR_INV_LENGTH);
441           else if ((err = init_encryption ()))
442             ;
443           else if (!(value = xtrymalloc_secure (r->pw->totallen - 8)))
444             err = gpg_error_from_syserror ();
445           else
446             {
447               err = gcry_cipher_decrypt (encryption_handle,
448                                          value, r->pw->totallen - 8,
449                                          r->pw->data, r->pw->totallen);
450             }
451           if (err)
452             {
453               xfree (value);
454               value = NULL;
455               log_error ("retrieving cache entry '%s' failed: %s\n",
456                          key, gpg_strerror (err));
457             }
458           break;
459         }
460     }
461   if (DBG_CACHE && value == NULL)
462     log_debug ("... miss\n");
463
464  out:
465   res = npth_mutex_unlock (&cache_lock);
466   if (res)
467     log_fatal ("failed to release cache mutex: %s\n", strerror (res));
468
469   return value;
470 }
471
472
473 /* Store the key for the last successful cache hit.  That value is
474    used by agent_get_cache if the requested KEY is given as NULL.
475    NULL may be used to remove that key. */
476 void
477 agent_store_cache_hit (const char *key)
478 {
479   char *new;
480   char *old;
481
482   /* To make sure the update is atomic under the non-preemptive thread
483    * model, we must make sure not to surrender control to a different
484    * thread.  Therefore, we avoid calling the allocator during the
485    * update.  */
486   new = key ? xtrystrdup (key) : NULL;
487
488   /* Atomic update.  */
489   old = last_stored_cache_key;
490   last_stored_cache_key = new;
491   /* Done.  */
492
493   xfree (old);
494 }