1 /* cache.c - keep a cache of passphrases
2 * Copyright (C) 2002, 2010 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
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.
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.
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/>.
31 /* The size of the encryption key in bytes. */
32 #define ENCRYPTION_KEYSIZE (128/8)
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
45 static gcry_cipher_hd_t encryption_handle;
48 struct secret_data_s {
49 int totallen; /* This includes the padding and space for AESWRAP. */
50 char data[1]; /* A string. */
53 typedef struct cache_item_s *ITEM;
58 int ttl; /* max. lifetime given in seconds, -1 one means infinite */
59 struct secret_data_s *pw;
60 cache_mode_t cache_mode;
64 /* The cache himself. */
67 /* NULL or the last cache key stored by agent_store_cache_hit. */
68 static char *last_stored_cache_key;
71 /* This function must be called once to initialize this module. It
72 has to be done before a second thread is spawned. */
74 initialize_module_cache (void)
78 err = npth_mutex_init (&cache_lock, NULL);
81 log_fatal ("error initializing cache module: %s\n", strerror (err));
86 deinitialize_module_cache (void)
88 gcry_cipher_close (encryption_handle);
89 encryption_handle = NULL;
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
100 init_encryption (void)
105 if (encryption_handle)
106 return 0; /* Shortcut - Already initialized. */
108 err = gcry_cipher_open (&encryption_handle, GCRY_CIPHER_AES128,
109 GCRY_CIPHER_MODE_AESWRAP, GCRY_CIPHER_SECURE);
112 key = gcry_random_bytes (ENCRYPTION_KEYSIZE, GCRY_STRONG_RANDOM);
114 err = gpg_error_from_syserror ();
117 err = gcry_cipher_setkey (encryption_handle, key, ENCRYPTION_KEYSIZE);
122 gcry_cipher_close (encryption_handle);
123 encryption_handle = NULL;
127 log_error ("error initializing cache encryption context: %s\n",
130 return err? gpg_error (GPG_ERR_NOT_INITIALIZED) : 0;
136 release_data (struct secret_data_s *data)
142 new_data (const char *string, struct secret_data_s **r_data)
145 struct secret_data_s *d, *d_enc;
151 err = init_encryption ();
155 length = strlen (string) + 1;
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);
164 d = xtrymalloc_secure (sizeof *d + total - 1);
166 return gpg_error_from_syserror ();
167 memcpy (d->data, string, length);
169 d_enc = xtrymalloc (sizeof *d_enc + total - 1);
172 err = gpg_error_from_syserror ();
177 d_enc->totallen = total;
178 err = gcry_cipher_encrypt (encryption_handle, d_enc->data, total,
192 /* Check whether there are items to expire. */
197 time_t current = gnupg_get_time ();
199 /* First expire the actual data */
200 for (r=thecache; r; r = r->next)
202 if (r->pw && r->ttl >= 0 && r->accessed + r->ttl < current)
205 log_debug (" expired '%s' (%ds after last access)\n",
207 release_data (r->pw);
209 r->accessed = current;
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)
217 unsigned long maxttl;
219 switch (r->cache_mode)
221 case CACHE_MODE_SSH: maxttl = opt.max_cache_ttl_ssh; break;
222 default: maxttl = opt.max_cache_ttl; break;
224 if (r->pw && r->created + maxttl < current)
227 log_debug (" expired '%s' (%lus after creation)\n",
228 r->key, opt.max_cache_ttl);
229 release_data (r->pw);
231 r->accessed = current;
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; )
239 if (!r->pw && r->ttl >= 0 && r->accessed + 60*30 < current)
243 log_debug (" removed '%s' (mode %d) (slot not used for 30m)\n",
244 r->key, r->cache_mode);
262 agent_flush_cache (void)
268 log_debug ("agent_flush_cache\n");
270 res = npth_mutex_lock (&cache_lock);
272 log_fatal ("failed to acquire cache mutex: %s\n", strerror (res));
274 for (r=thecache; r; r = r->next)
279 log_debug (" flushing '%s'\n", r->key);
280 release_data (r->pw);
286 res = npth_mutex_unlock (&cache_lock);
288 log_fatal ("failed to release cache mutex: %s\n", strerror (res));
292 /* Compare two cache modes. */
294 cache_mode_equal (cache_mode_t a, cache_mode_t b)
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);
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. */
309 agent_put_cache (const char *key, cache_mode_t cache_mode,
310 const char *data, int ttl)
316 res = npth_mutex_lock (&cache_lock);
318 log_fatal ("failed to acquire cache mutex: %s\n", strerror (res));
321 log_debug ("agent_put_cache '%s' (mode %d) requested ttl=%d\n",
322 key, cache_mode, ttl);
329 case CACHE_MODE_SSH: ttl = opt.def_cache_ttl_ssh; break;
330 default: ttl = opt.def_cache_ttl; break;
333 if ((!ttl && data) || cache_mode == CACHE_MODE_IGNORE)
336 for (r=thecache; r; r = r->next)
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))
344 if (r) /* Replace. */
348 release_data (r->pw);
353 r->created = r->accessed = gnupg_get_time ();
355 r->cache_mode = cache_mode;
356 err = new_data (data, &r->pw);
358 log_error ("error replacing cache item: %s\n", gpg_strerror (err));
361 else if (data) /* Insert. */
363 r = xtrycalloc (1, sizeof *r + strlen (key));
365 err = gpg_error_from_syserror ();
368 strcpy (r->key, key);
369 r->created = r->accessed = gnupg_get_time ();
371 r->cache_mode = cache_mode;
372 err = new_data (data, &r->pw);
382 log_error ("error inserting cache item: %s\n", gpg_strerror (err));
386 res = npth_mutex_unlock (&cache_lock);
388 log_fatal ("failed to release cache mutex: %s\n", strerror (res));
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
398 agent_get_cache (const char *key, cache_mode_t cache_mode)
406 if (cache_mode == CACHE_MODE_IGNORE)
409 res = npth_mutex_lock (&cache_lock);
411 log_fatal ("failed to acquire cache mutex: %s\n", strerror (res));
415 key = last_stored_cache_key;
422 log_debug ("agent_get_cache '%s' (mode %d)%s ...\n",
424 last_stored? " (stored cache key)":"");
427 for (r=thecache; r; r = r->next)
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))
435 /* Note: To avoid races KEY may not be accessed anymore below. */
436 r->accessed = gnupg_get_time ();
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 ()))
443 else if (!(value = xtrymalloc_secure (r->pw->totallen - 8)))
444 err = gpg_error_from_syserror ();
447 err = gcry_cipher_decrypt (encryption_handle,
448 value, r->pw->totallen - 8,
449 r->pw->data, r->pw->totallen);
455 log_error ("retrieving cache entry '%s' failed: %s\n",
456 key, gpg_strerror (err));
461 if (DBG_CACHE && value == NULL)
462 log_debug ("... miss\n");
465 res = npth_mutex_unlock (&cache_lock);
467 log_fatal ("failed to release cache mutex: %s\n", strerror (res));
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. */
477 agent_store_cache_hit (const char *key)
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
486 new = key ? xtrystrdup (key) : NULL;
489 old = last_stored_cache_key;
490 last_stored_cache_key = new;