1
0
mirror of git://git.gnupg.org/gnupg.git synced 2024-12-22 10:19:57 +01:00
gnupg/agent/cache.c

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

572 lines
16 KiB
C
Raw Permalink Normal View History

/* cache.c - keep a cache of passphrases
* Copyright (C) 2002, 2010 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
2007-07-04 19:49:40 +00:00
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <npth.h>
#include "agent.h"
/* The default TTL for DATA items. This has no configure
* option because it is expected that clients provide a TTL. */
#define DEF_CACHE_TTL_DATA (10 * 60) /* 10 minutes. */
2010-09-02 10:46:23 +00:00
/* The size of the encryption key in bytes. */
#define ENCRYPTION_KEYSIZE (128/8)
/* A mutex used to serialize access to the cache. */
static npth_mutex_t cache_lock;
2010-09-02 10:46:23 +00:00
/* The encryption context. This is the only place where the
encryption key for all cached entries is available. It would be nice
2010-09-02 10:46:23 +00:00
to keep this (or just the key) in some hardware device, for example
a TPM. Libgcrypt could be extended to provide such a service.
With the current scheme it is easy to retrieve the cached entries
if access to Libgcrypt's memory is available. The encryption
merely avoids grepping for clear texts in the memory. Nevertheless
the encryption provides the necessary infrastructure to make it
more secure. */
static gcry_cipher_hd_t encryption_handle;
struct secret_data_s {
2010-09-02 10:46:23 +00:00
int totallen; /* This includes the padding and space for AESWRAP. */
char data[1]; /* A string. */
};
/* The cache object. */
typedef struct cache_item_s *ITEM;
struct cache_item_s {
ITEM next;
time_t created;
time_t accessed; /* Not updated for CACHE_MODE_DATA */
int ttl; /* max. lifetime given in seconds, -1 one means infinite */
struct secret_data_s *pw;
cache_mode_t cache_mode;
int restricted; /* The value of ctrl->restricted is part of the key. */
char key[1];
};
2010-09-02 10:46:23 +00:00
/* The cache himself. */
static ITEM thecache;
/* NULL or the last cache key stored by agent_store_cache_hit. */
static char *last_stored_cache_key;
2010-09-02 10:46:23 +00:00
/* This function must be called once to initialize this module. It
has to be done before a second thread is spawned. */
void
initialize_module_cache (void)
{
int err;
err = npth_mutex_init (&cache_lock, NULL);
if (err)
log_fatal ("error initializing cache module: %s\n", strerror (err));
}
void
deinitialize_module_cache (void)
{
gcry_cipher_close (encryption_handle);
encryption_handle = NULL;
}
/* We do the encryption init on the fly. We can't do it in the module
init code because that is run before we listen for connections and
in case we are started on demand by gpg etc. it will only wait for
a few seconds to decide whether the agent may now accept
connections. Thus we should get into listen state as soon as
possible. */
static gpg_error_t
init_encryption (void)
{
2010-09-02 10:46:23 +00:00
gpg_error_t err;
void *key;
if (encryption_handle)
return 0; /* Shortcut - Already initialized. */
err = gcry_cipher_open (&encryption_handle, GCRY_CIPHER_AES128,
GCRY_CIPHER_MODE_AESWRAP, GCRY_CIPHER_SECURE);
2010-09-02 10:46:23 +00:00
if (!err)
{
key = gcry_random_bytes (ENCRYPTION_KEYSIZE, GCRY_STRONG_RANDOM);
if (!key)
err = gpg_error_from_syserror ();
else
{
err = gcry_cipher_setkey (encryption_handle, key, ENCRYPTION_KEYSIZE);
xfree (key);
}
if (err)
{
gcry_cipher_close (encryption_handle);
encryption_handle = NULL;
}
2010-09-02 10:46:23 +00:00
}
if (err)
log_error ("error initializing cache encryption context: %s\n",
gpg_strerror (err));
return err? gpg_error (GPG_ERR_NOT_INITIALIZED) : 0;
2010-09-02 10:46:23 +00:00
}
static void
release_data (struct secret_data_s *data)
{
xfree (data);
}
2010-09-02 10:46:23 +00:00
static gpg_error_t
new_data (const char *string, struct secret_data_s **r_data)
{
2010-09-02 10:46:23 +00:00
gpg_error_t err;
struct secret_data_s *d, *d_enc;
size_t length;
int total;
2010-09-02 10:46:23 +00:00
*r_data = NULL;
err = init_encryption ();
if (err)
return err;
2010-09-02 10:46:23 +00:00
length = strlen (string) + 1;
2010-09-02 10:46:23 +00:00
/* We pad the data to 32 bytes so that it get more complicated
finding something out by watching allocation patterns. This is
Fix typos found using codespell. * agent/cache.c: Fix typos. * agent/call-pinentry.c: Likewise. * agent/call-scd.c: Likewise. * agent/command-ssh.c: Likewise. * agent/command.c: Likewise. * agent/divert-scd.c: Likewise. * agent/findkey.c: Likewise. * agent/gpg-agent.c: Likewise. * agent/w32main.c: Likewise. * common/argparse.c: Likewise. * common/audit.c: Likewise. * common/audit.h: Likewise. * common/convert.c: Likewise. * common/dotlock.c: Likewise. * common/exechelp-posix.c: Likewise. * common/exechelp-w32.c: Likewise. * common/exechelp-w32ce.c: Likewise. * common/exechelp.h: Likewise. * common/helpfile.c: Likewise. * common/i18n.h: Likewise. * common/iobuf.c: Likewise. * common/iobuf.h: Likewise. * common/localename.c: Likewise. * common/logging.c: Likewise. * common/openpgp-oid.c: Likewise. * common/session-env.c: Likewise. * common/sexputil.c: Likewise. * common/sysutils.c: Likewise. * common/t-sexputil.c: Likewise. * common/ttyio.c: Likewise. * common/util.h: Likewise. * dirmngr/cdblib.c: Likewise. * dirmngr/certcache.c: Likewise. * dirmngr/crlcache.c: Likewise. * dirmngr/dirmngr-client.c: Likewise. * dirmngr/dirmngr.c: Likewise. * dirmngr/dirmngr_ldap.c: Likewise. * dirmngr/dns-stuff.c: Likewise. * dirmngr/http.c: Likewise. * dirmngr/ks-engine-hkp.c: Likewise. * dirmngr/ks-engine-ldap.c: Likewise. * dirmngr/ldap-wrapper.c: Likewise. * dirmngr/ldap.c: Likewise. * dirmngr/misc.c: Likewise. * dirmngr/ocsp.c: Likewise. * dirmngr/validate.c: Likewise. * g10/encrypt.c: Likewise. * g10/getkey.c: Likewise. * g10/gpg.c: Likewise. * g10/gpgv.c: Likewise. * g10/import.c: Likewise. * g10/keydb.c: Likewise. * g10/keydb.h: Likewise. * g10/keygen.c: Likewise. * g10/keyid.c: Likewise. * g10/keylist.c: Likewise. * g10/keyring.c: Likewise. * g10/mainproc.c: Likewise. * g10/misc.c: Likewise. * g10/options.h: Likewise. * g10/packet.h: Likewise. * g10/parse-packet.c: Likewise. * g10/pkclist.c: Likewise. * g10/pkglue.c: Likewise. * g10/plaintext.c: Likewise. * g10/server.c: Likewise. * g10/sig-check.c: Likewise. * g10/sqlite.c: Likewise. * g10/tdbio.c: Likewise. * g10/test-stubs.c: Likewise. * g10/tofu.c: Likewise. * g10/trust.c: Likewise. * g10/trustdb.c: Likewise. * g13/create.c: Likewise. * g13/mountinfo.c: Likewise. * kbx/keybox-blob.c: Likewise. * kbx/keybox-file.c: Likewise. * kbx/keybox-init.c: Likewise. * kbx/keybox-search-desc.h: Likewise. * kbx/keybox-search.c: Likewise. * kbx/keybox-update.c: Likewise. * scd/apdu.c: Likewise. * scd/app-openpgp.c: Likewise. * scd/app-p15.c: Likewise. * scd/app.c: Likewise. * scd/ccid-driver.c: Likewise. * scd/command.c: Likewise. * scd/iso7816.c: Likewise. * sm/base64.c: Likewise. * sm/call-agent.c: Likewise. * sm/call-dirmngr.c: Likewise. * sm/certchain.c: Likewise. * sm/gpgsm.c: Likewise. * sm/import.c: Likewise. * sm/keydb.c: Likewise. * sm/minip12.c: Likewise. * sm/qualified.c: Likewise. * sm/server.c: Likewise. * tools/gpg-check-pattern.c: Likewise. * tools/gpgconf-comp.c: Likewise. * tools/gpgkey2ssh.c: Likewise. * tools/gpgparsemail.c: Likewise. * tools/gpgtar.c: Likewise. * tools/rfc822parse.c: Likewise. * tools/symcryptrun.c: Likewise. Signed-off-by: Justus Winter <justus@g10code.com>
2015-11-16 12:41:46 +01:00
usually not possible but we better assume nothing about our secure
2010-09-02 10:46:23 +00:00
storage provider. To support the AESWRAP mode we need to add 8
extra bytes as well. */
total = (length + 8) + 32 - ((length+8) % 32);
d = xtrymalloc_secure (sizeof *d + total - 1);
if (!d)
return gpg_error_from_syserror ();
memcpy (d->data, string, length);
d_enc = xtrymalloc (sizeof *d_enc + total - 1);
if (!d_enc)
{
err = gpg_error_from_syserror ();
xfree (d);
return err;
}
2010-09-02 10:46:23 +00:00
d_enc->totallen = total;
err = gcry_cipher_encrypt (encryption_handle, d_enc->data, total,
d->data, total - 8);
xfree (d);
if (err)
{
2010-09-02 10:46:23 +00:00
xfree (d_enc);
return err;
}
2010-09-02 10:46:23 +00:00
*r_data = d_enc;
return 0;
}
2010-09-02 10:46:23 +00:00
/* Check whether there are items to expire. */
static void
housekeeping (void)
{
ITEM r, rprev;
time_t current = gnupg_get_time ();
/* First expire the actual data */
for (r=thecache; r; r = r->next)
{
if (r->cache_mode == CACHE_MODE_PIN)
; /* Don't let it expire - scdaemon explicitly flushes them. */
else if (r->pw && r->ttl >= 0 && r->accessed + r->ttl < current)
{
if (DBG_CACHE)
log_debug (" expired '%s'.%d (%ds after last access)\n",
r->key, r->restricted, r->ttl);
release_data (r->pw);
r->pw = NULL;
r->accessed = current;
}
}
/* Second, make sure that we also remove them based on the created
* stamp so that the user has to enter it from time to time. We
* don't do this for data items which are used to storage secrets in
* meory and are not user entered passphrases etc. */
for (r=thecache; r; r = r->next)
{
unsigned long maxttl;
switch (r->cache_mode)
{
case CACHE_MODE_DATA:
case CACHE_MODE_PIN:
continue; /* No MAX TTL here. */
case CACHE_MODE_SSH: maxttl = opt.max_cache_ttl_ssh; break;
default: maxttl = opt.max_cache_ttl; break;
}
2010-09-02 10:46:23 +00:00
if (r->pw && r->created + maxttl < current)
{
if (DBG_CACHE)
log_debug (" expired '%s'.%d (%lus after creation)\n",
r->key, r->restricted, opt.max_cache_ttl);
release_data (r->pw);
r->pw = NULL;
r->accessed = current;
}
}
/* Third, make sure that we don't have too many items in the list.
* Expire old and unused entries after 30 minutes. */
for (rprev=NULL, r=thecache; r; )
{
if (!r->pw && r->ttl >= 0 && r->accessed + 60*30 < current)
{
2010-09-02 10:46:23 +00:00
ITEM r2 = r->next;
if (DBG_CACHE)
log_debug (" removed '%s'.%d (mode %d) (slot not used for 30m)\n",
r->key, r->restricted, r->cache_mode);
2010-09-02 10:46:23 +00:00
xfree (r);
if (!rprev)
thecache = r2;
else
2010-09-02 10:46:23 +00:00
rprev->next = r2;
r = r2;
}
else
{
rprev = r;
r = r->next;
}
}
}
void
agent_cache_housekeeping (void)
{
int res;
if (DBG_CACHE)
log_debug ("agent_cache_housekeeping\n");
res = npth_mutex_lock (&cache_lock);
if (res)
log_fatal ("failed to acquire cache mutex: %s\n", strerror (res));
housekeeping ();
res = npth_mutex_unlock (&cache_lock);
if (res)
log_fatal ("failed to release cache mutex: %s\n", strerror (res));
}
void
agent_flush_cache (int pincache_only)
{
ITEM r;
int res;
if (DBG_CACHE)
log_debug ("agent_flush_cache%s\n", pincache_only?" (pincache only)":"");
res = npth_mutex_lock (&cache_lock);
if (res)
log_fatal ("failed to acquire cache mutex: %s\n", strerror (res));
for (r=thecache; r; r = r->next)
{
if (pincache_only && r->cache_mode != CACHE_MODE_PIN)
continue;
2010-09-02 10:46:23 +00:00
if (r->pw)
{
if (DBG_CACHE)
log_debug (" flushing '%s'.%d\n", r->key, r->restricted);
release_data (r->pw);
r->pw = NULL;
r->accessed = 0;
}
}
res = npth_mutex_unlock (&cache_lock);
if (res)
log_fatal ("failed to release cache mutex: %s\n", strerror (res));
}
/* Compare two cache modes. */
static int
cache_mode_equal (cache_mode_t a, cache_mode_t b)
{
/* CACHE_MODE_ANY matches any mode other than CACHE_MODE_IGNORE. */
return ((a == CACHE_MODE_ANY
&& !(b == CACHE_MODE_IGNORE || b == CACHE_MODE_DATA))
|| (b == CACHE_MODE_ANY
&& !(a == CACHE_MODE_IGNORE || a == CACHE_MODE_DATA))
|| a == b);
}
2010-09-02 10:46:23 +00:00
/* Store the string DATA in the cache under KEY and mark it with a
maximum lifetime of TTL seconds. If there is already data under
this key, it will be replaced. Using a DATA of NULL deletes the
entry. A TTL of 0 is replaced by the default TTL and a TTL of -1
set infinite timeout. CACHE_MODE is stored with the cache entry
and used to select different timeouts. */
int
agent_put_cache (ctrl_t ctrl, const char *key, cache_mode_t cache_mode,
const char *data, int ttl)
{
2010-09-02 10:46:23 +00:00
gpg_error_t err = 0;
ITEM r;
int res;
int restricted = ctrl? ctrl->restricted : -1;
res = npth_mutex_lock (&cache_lock);
if (res)
log_fatal ("failed to acquire cache mutex: %s\n", strerror (res));
if (DBG_CACHE)
log_debug ("agent_put_cache '%s'.%d (mode %d) requested ttl=%d\n",
key, restricted, cache_mode, ttl);
housekeeping ();
if (!ttl)
{
switch(cache_mode)
{
case CACHE_MODE_SSH: ttl = opt.def_cache_ttl_ssh; break;
case CACHE_MODE_DATA: ttl = DEF_CACHE_TTL_DATA; break;
case CACHE_MODE_PIN: ttl = -1; break;
default: ttl = opt.def_cache_ttl; break;
}
}
if ((!ttl && data) || cache_mode == CACHE_MODE_IGNORE)
goto out;
for (r=thecache; r; r = r->next)
{
if (cache_mode == CACHE_MODE_PIN && data)
{
/* PIN mode is special because it is only used by scdaemon. */
if (!strcmp (r->key, key))
break;
}
else if (cache_mode == CACHE_MODE_PIN)
{
/* FIXME: Parse the structure of the key and delete several
* cached PINS. */
if (!strcmp (r->key, key))
break;
}
else if (((cache_mode != CACHE_MODE_USER
&& cache_mode != CACHE_MODE_NONCE)
|| cache_mode_equal (r->cache_mode, cache_mode))
&& r->restricted == restricted
&& !strcmp (r->key, key))
break;
}
2010-09-02 10:46:23 +00:00
if (r) /* Replace. */
{
if (r->pw)
{
release_data (r->pw);
r->pw = NULL;
}
if (data)
{
r->created = r->accessed = gnupg_get_time ();
r->ttl = ttl;
r->cache_mode = cache_mode;
2010-09-02 10:46:23 +00:00
err = new_data (data, &r->pw);
if (err)
log_error ("error replacing cache item: %s\n", gpg_strerror (err));
}
}
2010-09-02 10:46:23 +00:00
else if (data) /* Insert. */
{
r = xtrycalloc (1, sizeof *r + strlen (key));
if (!r)
2010-09-02 10:46:23 +00:00
err = gpg_error_from_syserror ();
else
{
strcpy (r->key, key);
r->restricted = restricted;
r->created = r->accessed = gnupg_get_time ();
r->ttl = ttl;
r->cache_mode = cache_mode;
2010-09-02 10:46:23 +00:00
err = new_data (data, &r->pw);
if (err)
xfree (r);
else
{
r->next = thecache;
thecache = r;
}
}
2010-09-02 10:46:23 +00:00
if (err)
log_error ("error inserting cache item: %s\n", gpg_strerror (err));
}
out:
res = npth_mutex_unlock (&cache_lock);
if (res)
log_fatal ("failed to release cache mutex: %s\n", strerror (res));
2010-09-02 10:46:23 +00:00
return err;
}
/* Try to find an item in the cache. Returns NULL if not found or an
* malloced string with the value. */
2010-09-02 10:46:23 +00:00
char *
agent_get_cache (ctrl_t ctrl, const char *key, cache_mode_t cache_mode)
{
2010-09-02 10:46:23 +00:00
gpg_error_t err;
ITEM r;
2010-09-02 10:46:23 +00:00
char *value = NULL;
int res;
int last_stored = 0;
int restricted = ctrl? ctrl->restricted : -1;
int yes;
if (cache_mode == CACHE_MODE_IGNORE)
return NULL;
res = npth_mutex_lock (&cache_lock);
if (res)
log_fatal ("failed to acquire cache mutex: %s\n", strerror (res));
if (!key)
{
key = last_stored_cache_key;
if (!key)
goto out;
last_stored = 1;
}
if (DBG_CACHE)
log_debug ("agent_get_cache '%s'.%d (mode %d)%s ...\n",
key, restricted, cache_mode,
last_stored? " (stored cache key)":"");
housekeeping ();
for (r=thecache; r; r = r->next)
{
if (cache_mode == CACHE_MODE_PIN)
yes = (r->pw && !strcmp (r->key, key));
else if (r->pw
&& ((cache_mode != CACHE_MODE_USER
&& cache_mode != CACHE_MODE_NONCE)
|| cache_mode_equal (r->cache_mode, cache_mode))
&& r->restricted == restricted
&& !strcmp (r->key, key))
yes = 1;
else
yes = 0;
if (yes)
{
/* Note: To avoid races KEY may not be accessed anymore
* below. Note also that we don't update the accessed time
* for data items. */
if (r->cache_mode != CACHE_MODE_DATA)
r->accessed = gnupg_get_time ();
if (DBG_CACHE)
log_debug ("... hit\n");
2010-09-02 10:46:23 +00:00
if (r->pw->totallen < 32)
err = gpg_error (GPG_ERR_INV_LENGTH);
else if ((err = init_encryption ()))
;
2010-09-02 10:46:23 +00:00
else if (!(value = xtrymalloc_secure (r->pw->totallen - 8)))
err = gpg_error_from_syserror ();
else
{
err = gcry_cipher_decrypt (encryption_handle,
value, r->pw->totallen - 8,
r->pw->data, r->pw->totallen);
}
if (err)
{
xfree (value);
value = NULL;
log_error ("retrieving cache entry '%s'.%d failed: %s\n",
key, restricted, gpg_strerror (err));
2010-09-02 10:46:23 +00:00
}
break;
}
}
if (DBG_CACHE && value == NULL)
log_debug ("... miss\n");
out:
res = npth_mutex_unlock (&cache_lock);
if (res)
log_fatal ("failed to release cache mutex: %s\n", strerror (res));
return value;
}
/* Store the key for the last successful cache hit. That value is
used by agent_get_cache if the requested KEY is given as NULL.
NULL may be used to remove that key. */
void
agent_store_cache_hit (const char *key)
{
char *new;
char *old;
/* To make sure the update is atomic under the non-preemptive thread
* model, we must make sure not to surrender control to a different
* thread. Therefore, we avoid calling the allocator during the
* update.
*
* Background: xtrystrdup uses gcry_strdup which may use the secure
* memory allocator of Libgcrypt. That allocator takes locks and
* since version 1.14 libgpg-error is nPth aware and thus taking a
* lock may now lead to thread switch. Note that this only happens
* when secure memory is _allocated_ (the standard allocator uses
* malloc which is not nPth aware) but not when calling _xfree_
* because gcry_free needs to check whether the pointer is in secure
* memory and thus needs to take a lock.
*/
new = key ? xtrystrdup (key) : NULL;
/* Atomic update. */
old = last_stored_cache_key;
last_stored_cache_key = new;
/* Done. */
xfree (old);
}