Page MenuHome GnuPG

No OneTemporary

diff --git a/g10/getkey.c b/g10/getkey.c
index 929427302..002a2be2b 100644
--- a/g10/getkey.c
+++ b/g10/getkey.c
@@ -1,3051 +1,3052 @@
/* getkey.c - Get a key from the database
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
* 2007, 2008, 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
* 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 <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include "gpg.h"
#include "util.h"
#include "packet.h"
#include "iobuf.h"
#include "keydb.h"
#include "options.h"
#include "main.h"
#include "trustdb.h"
#include "i18n.h"
#include "keyserver-internal.h"
#include "call-agent.h"
#define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
#define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
#if MAX_PK_CACHE_ENTRIES < 2
#error We need the cache for key creation
#endif
struct getkey_ctx_s
{
int exact;
int want_secret; /* The caller requested only secret keys. */
KBNODE keyblock;
KBPOS kbpos;
KBNODE found_key; /* Pointer into some keyblock. */
strlist_t extra_list; /* Will be freed when releasing the context. */
int last_rc;
int req_usage;
int req_algo;
KEYDB_HANDLE kr_handle;
int not_allocated;
int nitems;
KEYDB_SEARCH_DESC items[1];
};
#if 0
static struct
{
int any;
int okay_count;
int nokey_count;
int error_count;
} lkup_stats[21];
#endif
typedef struct keyid_list
{
struct keyid_list *next;
u32 keyid[2];
} *keyid_list_t;
#if MAX_PK_CACHE_ENTRIES
typedef struct pk_cache_entry
{
struct pk_cache_entry *next;
u32 keyid[2];
PKT_public_key *pk;
} *pk_cache_entry_t;
static pk_cache_entry_t pk_cache;
static int pk_cache_entries; /* Number of entries in pk cache. */
static int pk_cache_disabled;
#endif
#if MAX_UID_CACHE_ENTRIES < 5
#error we really need the userid cache
#endif
typedef struct user_id_db
{
struct user_id_db *next;
keyid_list_t keyids;
int len;
char name[1];
} *user_id_db_t;
static user_id_db_t user_id_db;
static int uid_cache_entries; /* Number of entries in uid cache. */
static void merge_selfsigs (kbnode_t keyblock);
static int lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, int want_secret);
#if 0
static void
print_stats ()
{
int i;
for (i = 0; i < DIM (lkup_stats); i++)
{
if (lkup_stats[i].any)
fprintf (stderr,
"lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
i,
lkup_stats[i].okay_count,
lkup_stats[i].nokey_count, lkup_stats[i].error_count);
}
}
#endif
void
cache_public_key (PKT_public_key * pk)
{
#if MAX_PK_CACHE_ENTRIES
pk_cache_entry_t ce;
u32 keyid[2];
if (pk_cache_disabled)
return;
if (pk->flags.dont_cache)
return;
if (is_ELGAMAL (pk->pubkey_algo)
|| pk->pubkey_algo == PUBKEY_ALGO_DSA
|| pk->pubkey_algo == PUBKEY_ALGO_ECDSA
|| pk->pubkey_algo == PUBKEY_ALGO_ECDH
|| is_RSA (pk->pubkey_algo))
{
keyid_from_pk (pk, keyid);
}
else
return; /* Don't know how to get the keyid. */
for (ce = pk_cache; ce; ce = ce->next)
if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
{
if (DBG_CACHE)
log_debug ("cache_public_key: already in cache\n");
return;
}
if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
{
/* fixme: Use another algorithm to free some cache slots. */
pk_cache_disabled = 1;
if (opt.verbose > 1)
log_info (_("too many entries in pk cache - disabled\n"));
return;
}
pk_cache_entries++;
ce = xmalloc (sizeof *ce);
ce->next = pk_cache;
pk_cache = ce;
ce->pk = copy_public_key (NULL, pk);
ce->keyid[0] = keyid[0];
ce->keyid[1] = keyid[1];
#endif
}
/* Return a const utf-8 string with the text "[User ID not found]".
This function is required so that we don't need to switch gettext's
encoding temporary. */
static const char *
user_id_not_found_utf8 (void)
{
static char *text;
if (!text)
text = native_to_utf8 (_("[User ID not found]"));
return text;
}
/* Return the user ID from the given keyblock.
* We use the primary uid flag which has been set by the merge_selfsigs
* function. The returned value is only valid as long as then given
* keyblock is not changed. */
static const char *
get_primary_uid (KBNODE keyblock, size_t * uidlen)
{
KBNODE k;
const char *s;
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID
&& !k->pkt->pkt.user_id->attrib_data
&& k->pkt->pkt.user_id->is_primary)
{
*uidlen = k->pkt->pkt.user_id->len;
return k->pkt->pkt.user_id->name;
}
}
s = user_id_not_found_utf8 ();
*uidlen = strlen (s);
return s;
}
static void
release_keyid_list (keyid_list_t k)
{
while (k)
{
keyid_list_t k2 = k->next;
xfree (k);
k = k2;
}
}
/****************
* Store the association of keyid and userid
* Feed only public keys to this function.
*/
static void
cache_user_id (KBNODE keyblock)
{
user_id_db_t r;
const char *uid;
size_t uidlen;
keyid_list_t keyids = NULL;
KBNODE k;
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
keyid_list_t a = xmalloc_clear (sizeof *a);
/* Hmmm: For a long list of keyids it might be an advantage
* to append the keys. */
keyid_from_pk (k->pkt->pkt.public_key, a->keyid);
/* First check for duplicates. */
for (r = user_id_db; r; r = r->next)
{
keyid_list_t b = r->keyids;
for (b = r->keyids; b; b = b->next)
{
if (b->keyid[0] == a->keyid[0]
&& b->keyid[1] == a->keyid[1])
{
if (DBG_CACHE)
log_debug ("cache_user_id: already in cache\n");
release_keyid_list (keyids);
xfree (a);
return;
}
}
}
/* Now put it into the cache. */
a->next = keyids;
keyids = a;
}
}
if (!keyids)
BUG (); /* No key no fun. */
uid = get_primary_uid (keyblock, &uidlen);
if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES)
{
/* fixme: use another algorithm to free some cache slots */
r = user_id_db;
user_id_db = r->next;
release_keyid_list (r->keyids);
xfree (r);
uid_cache_entries--;
}
r = xmalloc (sizeof *r + uidlen - 1);
r->keyids = keyids;
r->len = uidlen;
memcpy (r->name, uid, r->len);
r->next = user_id_db;
user_id_db = r;
uid_cache_entries++;
}
void
getkey_disable_caches ()
{
#if MAX_PK_CACHE_ENTRIES
{
pk_cache_entry_t ce, ce2;
for (ce = pk_cache; ce; ce = ce2)
{
ce2 = ce->next;
free_public_key (ce->pk);
xfree (ce);
}
pk_cache_disabled = 1;
pk_cache_entries = 0;
pk_cache = NULL;
}
#endif
/* fixme: disable user id cache ? */
}
static void
pk_from_block (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE keyblock)
{
KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
assert (a->pkt->pkttype == PKT_PUBLIC_KEY
|| a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
copy_public_key (pk, a->pkt->pkt.public_key);
}
/* Get a public key and store it into the allocated pk can be called
* with PK set to NULL to just read it into some internal
* structures. */
int
get_pubkey (PKT_public_key * pk, u32 * keyid)
{
int internal = 0;
int rc = 0;
#if MAX_PK_CACHE_ENTRIES
if (pk)
{
/* Try to get it from the cache. We don't do this when pk is
NULL as it does not guarantee that the user IDs are
cached. */
pk_cache_entry_t ce;
for (ce = pk_cache; ce; ce = ce->next)
{
if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
{
copy_public_key (pk, ce->pk);
return 0;
}
}
}
#endif
/* More init stuff. */
if (!pk)
{
pk = xmalloc_clear (sizeof *pk);
internal++;
}
/* Do a lookup. */
{
struct getkey_ctx_s ctx;
KBNODE kb = NULL;
memset (&ctx, 0, sizeof ctx);
ctx.exact = 1; /* Use the key ID exactly as given. */
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
ctx.items[0].u.kid[0] = keyid[0];
ctx.items[0].u.kid[1] = keyid[1];
ctx.req_algo = pk->req_algo;
ctx.req_usage = pk->req_usage;
rc = lookup (&ctx, &kb, 0);
if (!rc)
{
pk_from_block (&ctx, pk, kb);
}
get_pubkey_end (&ctx);
release_kbnode (kb);
}
if (!rc)
goto leave;
rc = G10ERR_NO_PUBKEY;
leave:
if (!rc)
cache_public_key (pk);
if (internal)
free_public_key (pk);
return rc;
}
/* Get a public key and store it into the allocated pk. This function
differs from get_pubkey() in that it does not do a check of the key
to avoid recursion. It should be used only in very certain cases.
It will only retrieve primary keys. */
int
get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
{
int rc = 0;
KEYDB_HANDLE hd;
KBNODE keyblock;
u32 pkid[2];
assert (pk);
#if MAX_PK_CACHE_ENTRIES
{
/* Try to get it from the cache */
pk_cache_entry_t ce;
for (ce = pk_cache; ce; ce = ce->next)
{
if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
{
if (pk)
copy_public_key (pk, ce->pk);
return 0;
}
}
}
#endif
hd = keydb_new ();
rc = keydb_search_kid (hd, keyid);
if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
{
keydb_release (hd);
return G10ERR_NO_PUBKEY;
}
rc = keydb_get_keyblock (hd, &keyblock);
keydb_release (hd);
if (rc)
{
log_error ("keydb_get_keyblock failed: %s\n", g10_errstr (rc));
return G10ERR_NO_PUBKEY;
}
- assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
- || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
+ assert (keyblock && keyblock->pkt
+ && (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
+ || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY));
keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
copy_public_key (pk, keyblock->pkt->pkt.public_key);
else
rc = G10ERR_NO_PUBKEY;
release_kbnode (keyblock);
/* Not caching key here since it won't have all of the fields
properly set. */
return rc;
}
KBNODE
get_pubkeyblock (u32 * keyid)
{
struct getkey_ctx_s ctx;
int rc = 0;
KBNODE keyblock = NULL;
memset (&ctx, 0, sizeof ctx);
/* No need to set exact here because we want the entire block. */
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
ctx.items[0].u.kid[0] = keyid[0];
ctx.items[0].u.kid[1] = keyid[1];
rc = lookup (&ctx, &keyblock, 0);
get_pubkey_end (&ctx);
return rc ? NULL : keyblock;
}
/*
* Get a public key and store it into PK. This functions check that a
* corresponding secret key is available. With no secret key it does
* not succeeed.
*/
gpg_error_t
get_seckey (PKT_public_key *pk, u32 *keyid)
{
gpg_error_t err;
struct getkey_ctx_s ctx;
kbnode_t keyblock = NULL;
memset (&ctx, 0, sizeof ctx);
ctx.exact = 1; /* Use the key ID exactly as given. */
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
ctx.items[0].u.kid[0] = keyid[0];
ctx.items[0].u.kid[1] = keyid[1];
ctx.req_algo = pk->req_algo;
ctx.req_usage = pk->req_usage;
err = lookup (&ctx, &keyblock, 1);
if (!err)
{
pk_from_block (&ctx, pk, keyblock);
}
get_pubkey_end (&ctx);
release_kbnode (keyblock);
if (!err)
err = agent_probe_secret_key (/*ctrl*/NULL, pk);
return err;
}
static int
skip_unusable (void *dummy, u32 * keyid, PKT_user_id * uid)
{
int unusable = 0;
KBNODE keyblock;
(void) dummy;
keyblock = get_pubkeyblock (keyid);
if (!keyblock)
{
log_error ("error checking usability status of %s\n", keystr (keyid));
goto leave;
}
/* Is the user ID in question revoked/expired? */
if (uid)
{
KBNODE node;
for (node = keyblock; node; node = node->next)
{
if (node->pkt->pkttype == PKT_USER_ID)
{
if (cmp_user_ids (uid, node->pkt->pkt.user_id) == 0
&& (node->pkt->pkt.user_id->is_revoked
|| node->pkt->pkt.user_id->is_expired))
{
unusable = 1;
break;
}
}
}
}
if (!unusable)
unusable = pk_is_disabled (keyblock->pkt->pkt.public_key);
leave:
release_kbnode (keyblock);
return unusable;
}
/* Try to get the pubkey by the userid. This function looks for the
* first pubkey certificate which has the given name in a user_id. If
* PK has the pubkey algo set, the function will only return a pubkey
* with that algo. If NAMELIST is NULL, the first key is returned.
* The caller should provide storage for the PK or pass NULL if it is
* not needed. If RET_KB is not NULL the function stores the entire
* keyblock at that address. */
static int
key_byname (GETKEY_CTX *retctx, strlist_t namelist,
PKT_public_key *pk,
int want_secret, int include_unusable,
KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
{
int rc = 0;
int n;
strlist_t r;
GETKEY_CTX ctx;
KBNODE help_kb = NULL;
if (retctx)
{
/* Reset the returned context in case of error. */
assert (!ret_kdbhd); /* Not allowed because the handle is stored
in the context. */
*retctx = NULL;
}
if (ret_kdbhd)
*ret_kdbhd = NULL;
if (!namelist)
{
ctx = xmalloc_clear (sizeof *ctx);
ctx->nitems = 1;
ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
if (!include_unusable)
ctx->items[0].skipfnc = skip_unusable;
}
else
{
/* Build the search context. */
for (n = 0, r = namelist; r; r = r->next)
n++;
ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
ctx->nitems = n;
for (n = 0, r = namelist; r; r = r->next, n++)
{
gpg_error_t err;
err = classify_user_id (r->d, &ctx->items[n], 1);
if (ctx->items[n].exact)
ctx->exact = 1;
if (err)
{
xfree (ctx);
return gpg_err_code (err); /* FIXME: remove gpg_err_code. */
}
if (!include_unusable
&& ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
&& ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
&& ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
&& ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
&& ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
ctx->items[n].skipfnc = skip_unusable;
}
}
ctx->want_secret = want_secret;
ctx->kr_handle = keydb_new ();
if (!ret_kb)
ret_kb = &help_kb;
if (pk)
{
ctx->req_algo = pk->req_algo;
ctx->req_usage = pk->req_usage;
}
rc = lookup (ctx, ret_kb, want_secret);
if (!rc && pk)
{
pk_from_block (ctx, pk, *ret_kb);
}
release_kbnode (help_kb);
if (retctx) /* Caller wants the context. */
*retctx = ctx;
else
{
if (ret_kdbhd)
{
*ret_kdbhd = ctx->kr_handle;
ctx->kr_handle = NULL;
}
get_pubkey_end (ctx);
}
return rc;
}
/* Find a public key from NAME and return the keyblock or the key. If
ret_kdb is not NULL, the KEYDB handle used to locate this keyblock
is returned and the caller is responsible for closing it. If a key
was not found (or if local search has been disabled) and NAME is a
valid RFC822 mailbox and --auto-key-locate has been enabled, we try
to import the key via the online mechanisms defined by
--auto-key-locate. */
int
get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
const char *name, KBNODE * ret_keyblock,
KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
{
int rc;
strlist_t namelist = NULL;
struct akl *akl;
int is_mbox;
int nodefault = 0;
int anylocalfirst = 0;
if (retctx)
*retctx = NULL;
is_mbox = is_valid_mailbox (name);
/* Check whether we the default local search has been disabled.
This is the case if either the "nodefault" or the "local" keyword
are in the list of auto key locate mechanisms.
ANYLOCALFIRST is set if the search order has the local method
before any other or if "local" is used first by default. This
makes sure that if a RETCTX is used it gets only set if a local
search has precedence over the other search methods and only then
a followup call to get_pubkey_next shall succeed. */
if (!no_akl)
{
for (akl = opt.auto_key_locate; akl; akl = akl->next)
if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
{
nodefault = 1;
break;
}
for (akl = opt.auto_key_locate; akl; akl = akl->next)
if (akl->type != AKL_NODEFAULT)
{
if (akl->type == AKL_LOCAL)
anylocalfirst = 1;
break;
}
}
if (!nodefault)
anylocalfirst = 1;
if (nodefault && is_mbox)
{
/* Nodefault but a mailbox - let the AKL locate the key. */
rc = G10ERR_NO_PUBKEY;
}
else
{
add_to_strlist (&namelist, name);
rc = key_byname (retctx, namelist, pk, 0,
include_unusable, ret_keyblock, ret_kdbhd);
}
/* If the requested name resembles a valid mailbox and automatic
retrieval has been enabled, we try to import the key. */
if (gpg_err_code (rc) == G10ERR_NO_PUBKEY && !no_akl && is_mbox)
{
for (akl = opt.auto_key_locate; akl; akl = akl->next)
{
unsigned char *fpr = NULL;
size_t fpr_len;
int did_key_byname = 0;
int no_fingerprint = 0;
const char *mechanism = "?";
switch (akl->type)
{
case AKL_NODEFAULT:
/* This is a dummy mechanism. */
mechanism = "None";
rc = G10ERR_NO_PUBKEY;
break;
case AKL_LOCAL:
mechanism = "Local";
did_key_byname = 1;
if (retctx)
{
get_pubkey_end (*retctx);
*retctx = NULL;
}
add_to_strlist (&namelist, name);
rc = key_byname (anylocalfirst ? retctx : NULL,
namelist, pk, 0,
include_unusable, ret_keyblock, ret_kdbhd);
break;
case AKL_CERT:
mechanism = "DNS CERT";
glo_ctrl.in_auto_key_retrieve++;
rc = keyserver_import_cert (ctrl, name, &fpr, &fpr_len);
glo_ctrl.in_auto_key_retrieve--;
break;
case AKL_PKA:
mechanism = "PKA";
glo_ctrl.in_auto_key_retrieve++;
rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
glo_ctrl.in_auto_key_retrieve--;
break;
case AKL_LDAP:
mechanism = "LDAP";
glo_ctrl.in_auto_key_retrieve++;
rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
glo_ctrl.in_auto_key_retrieve--;
break;
case AKL_KEYSERVER:
/* Strictly speaking, we don't need to only use a valid
mailbox for the getname search, but it helps cut down
on the problem of searching for something like "john"
and getting a whole lot of keys back. */
if (opt.keyserver)
{
mechanism = opt.keyserver->uri;
glo_ctrl.in_auto_key_retrieve++;
rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
opt.keyserver);
glo_ctrl.in_auto_key_retrieve--;
}
else
{
mechanism = "Unconfigured keyserver";
rc = G10ERR_NO_PUBKEY;
}
break;
case AKL_SPEC:
{
struct keyserver_spec *keyserver;
mechanism = akl->spec->uri;
keyserver = keyserver_match (akl->spec);
glo_ctrl.in_auto_key_retrieve++;
rc = keyserver_import_name (ctrl,
name, &fpr, &fpr_len, keyserver);
glo_ctrl.in_auto_key_retrieve--;
}
break;
}
/* Use the fingerprint of the key that we actually fetched.
This helps prevent problems where the key that we fetched
doesn't have the same name that we used to fetch it. In
the case of CERT and PKA, this is an actual security
requirement as the URL might point to a key put in by an
attacker. By forcing the use of the fingerprint, we
won't use the attacker's key here. */
if (!rc && fpr)
{
char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
assert (fpr_len <= MAX_FINGERPRINT_LEN);
free_strlist (namelist);
namelist = NULL;
bin2hex (fpr, fpr_len, fpr_string);
if (opt.verbose)
log_info ("auto-key-locate found fingerprint %s\n",
fpr_string);
add_to_strlist (&namelist, fpr_string);
}
else if (!rc && !fpr && !did_key_byname)
{
no_fingerprint = 1;
rc = G10ERR_NO_PUBKEY;
}
xfree (fpr);
fpr = NULL;
if (!rc && !did_key_byname)
{
if (retctx)
{
get_pubkey_end (*retctx);
*retctx = NULL;
}
rc = key_byname (anylocalfirst ? retctx : NULL,
namelist, pk, 0,
include_unusable, ret_keyblock, ret_kdbhd);
}
if (!rc)
{
/* Key found. */
log_info (_("automatically retrieved '%s' via %s\n"),
name, mechanism);
break;
}
if (rc != G10ERR_NO_PUBKEY || opt.verbose || no_fingerprint)
log_info (_("error retrieving '%s' via %s: %s\n"),
name, mechanism,
no_fingerprint ? _("No fingerprint") : g10_errstr (rc));
}
}
if (rc && retctx)
{
get_pubkey_end (*retctx);
*retctx = NULL;
}
if (retctx && *retctx)
{
assert (!(*retctx)->extra_list);
(*retctx)->extra_list = namelist;
}
else
free_strlist (namelist);
return rc;
}
int
get_pubkey_bynames (GETKEY_CTX * retctx, PKT_public_key * pk,
strlist_t names, KBNODE * ret_keyblock)
{
return key_byname (retctx, names, pk, 0, 1, ret_keyblock, NULL);
}
int
get_pubkey_next (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE * ret_keyblock)
{
int rc;
rc = lookup (ctx, ret_keyblock, 0);
if (!rc && pk && ret_keyblock)
pk_from_block (ctx, pk, *ret_keyblock);
return rc;
}
void
get_pubkey_end (GETKEY_CTX ctx)
{
if (ctx)
{
memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
keydb_release (ctx->kr_handle);
free_strlist (ctx->extra_list);
if (!ctx->not_allocated)
xfree (ctx);
}
}
/* Search for a key with the given fingerprint.
* FIXME:
* We should replace this with the _byname function. This can be done
* by creating a userID conforming to the unified fingerprint style.
*/
int
get_pubkey_byfprint (PKT_public_key * pk,
const byte * fprint, size_t fprint_len)
{
int rc;
if (fprint_len == 20 || fprint_len == 16)
{
struct getkey_ctx_s ctx;
KBNODE kb = NULL;
memset (&ctx, 0, sizeof ctx);
ctx.exact = 1;
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
: KEYDB_SEARCH_MODE_FPR20;
memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
rc = lookup (&ctx, &kb, 0);
if (!rc && pk)
pk_from_block (&ctx, pk, kb);
release_kbnode (kb);
get_pubkey_end (&ctx);
}
else
rc = G10ERR_GENERAL; /* Oops */
return rc;
}
/* Get a public key and store it into the allocated pk. This function
differs from get_pubkey_byfprint() in that it does not do a check
of the key to avoid recursion. It should be used only in very
certain cases. PK may be NULL to check just for the existance of
the key. */
int
get_pubkey_byfprint_fast (PKT_public_key * pk,
const byte * fprint, size_t fprint_len)
{
int rc = 0;
KEYDB_HANDLE hd;
KBNODE keyblock;
byte fprbuf[MAX_FINGERPRINT_LEN];
int i;
for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
fprbuf[i] = fprint[i];
while (i < MAX_FINGERPRINT_LEN)
fprbuf[i++] = 0;
hd = keydb_new ();
rc = keydb_search_fpr (hd, fprbuf);
if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
{
keydb_release (hd);
return G10ERR_NO_PUBKEY;
}
rc = keydb_get_keyblock (hd, &keyblock);
keydb_release (hd);
if (rc)
{
log_error ("keydb_get_keyblock failed: %s\n", g10_errstr (rc));
return G10ERR_NO_PUBKEY;
}
assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
|| keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
if (pk)
copy_public_key (pk, keyblock->pkt->pkt.public_key);
release_kbnode (keyblock);
/* Not caching key here since it won't have all of the fields
properly set. */
return 0;
}
/* Search for a key with the given fingerprint and return the
* complete keyblock which may have more than only this key. */
int
get_keyblock_byfprint (KBNODE * ret_keyblock, const byte * fprint,
size_t fprint_len)
{
int rc;
if (fprint_len == 20 || fprint_len == 16)
{
struct getkey_ctx_s ctx;
memset (&ctx, 0, sizeof ctx);
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = (fprint_len == 16
? KEYDB_SEARCH_MODE_FPR16
: KEYDB_SEARCH_MODE_FPR20);
memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
rc = lookup (&ctx, ret_keyblock, 0);
get_pubkey_end (&ctx);
}
else
rc = G10ERR_GENERAL; /* Oops */
return rc;
}
/* Get a secret key by NAME and store it into PK. If NAME is NULL use
* the default key. This functions checks that a corresponding secret
* key is available. With no secret key it does not succeeed. */
gpg_error_t
get_seckey_byname (PKT_public_key *pk, const char *name)
{
gpg_error_t err;
strlist_t namelist = NULL;
int include_unusable = 1;
/* If we have no name, try to use the default secret key. If we
have no default, we'll use the first usable one. */
if (!name && opt.def_secret_key && *opt.def_secret_key)
add_to_strlist (&namelist, opt.def_secret_key);
else if (name)
add_to_strlist (&namelist, name);
else
include_unusable = 0;
err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
free_strlist (namelist);
return err;
}
/* Search for a key with the given fingerprint.
* FIXME:
* We should replace this with the _byname function. This can be done
* by creating a userID conforming to the unified fingerprint style. */
gpg_error_t
get_seckey_byfprint (PKT_public_key *pk, const byte * fprint, size_t fprint_len)
{
gpg_error_t err;
if (fprint_len == 20 || fprint_len == 16)
{
struct getkey_ctx_s ctx;
kbnode_t kb = NULL;
memset (&ctx, 0, sizeof ctx);
ctx.exact = 1;
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
: KEYDB_SEARCH_MODE_FPR20;
memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
err = lookup (&ctx, &kb, 1);
if (!err && pk)
pk_from_block (&ctx, pk, kb);
release_kbnode (kb);
get_pubkey_end (&ctx);
}
else
err = gpg_error (GPG_ERR_BUG);
return err;
}
/* Search for a secret key with the given fingerprint and return the
complete keyblock which may have more than only this key. Return
an error if no corresponding secret key is available. */
gpg_error_t
get_seckeyblock_byfprint (kbnode_t *ret_keyblock,
const byte *fprint, size_t fprint_len)
{
gpg_error_t err;
struct getkey_ctx_s ctx;
if (fprint_len != 20 && fprint_len == 16)
return gpg_error (GPG_ERR_BUG);
memset (&ctx, 0, sizeof ctx);
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = (fprint_len == 16
? KEYDB_SEARCH_MODE_FPR16 : KEYDB_SEARCH_MODE_FPR20);
memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
err = lookup (&ctx, ret_keyblock, 1);
get_pubkey_end (&ctx);
return err;
}
/* The new function to return a key.
FIXME: Document it. */
gpg_error_t
getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
strlist_t names, int want_secret, kbnode_t *ret_keyblock)
{
return key_byname (retctx, names, pk, want_secret, 1,
ret_keyblock, NULL);
}
/* Get a key by name and store it into PK if that is not NULL. If
* RETCTX is not NULL return the search context which needs to be
* released by the caller using getkey_end. If NAME is NULL use the
* default key (see below). On success and if RET_KEYBLOCK is not
* NULL the found keyblock is stored at this address. WANT_SECRET
* passed as true requires that a secret key is available for the
* selected key.
*
* If WANT_SECRET is true and NAME is NULL and a default key has been
* defined that defined key is used. In all other cases the first
* available key is used.
*
* FIXME: Explain what is up with unusable keys.
*
* FIXME: We also have the get_pubkey_byname function which has a
* different semantic. Should be merged with this one.
*/
gpg_error_t
getkey_byname (getkey_ctx_t *retctx, PKT_public_key *pk,
const char *name, int want_secret, kbnode_t *ret_keyblock)
{
gpg_error_t err;
strlist_t namelist = NULL;
int with_unusable = 1;
if (want_secret && !name && opt.def_secret_key && *opt.def_secret_key)
add_to_strlist (&namelist, opt.def_secret_key);
else if (name)
add_to_strlist (&namelist, name);
else
with_unusable = 0;
err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
ret_keyblock, NULL);
/* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
WANT_SECRET has been used. */
free_strlist (namelist);
return err;
}
/* The new function to return the next key. */
gpg_error_t
getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
{
int rc; /* Fixme: Make sure this is proper gpg_error */
rc = lookup (ctx, ret_keyblock, ctx->want_secret);
if (!rc && pk && ret_keyblock)
pk_from_block (ctx, pk, *ret_keyblock);
return rc;
}
/* The new function to finish a key listing. */
void
getkey_end (getkey_ctx_t ctx)
{
get_pubkey_end (ctx);
}
/************************************************
************* Merging stuff ********************
************************************************/
/* Merge all self-signatures with the keys. */
void
merge_keys_and_selfsig (KBNODE keyblock)
{
if (!keyblock)
;
else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
merge_selfsigs (keyblock);
else
log_debug ("FIXME: merging secret key blocks is not anymore available\n");
}
static int
parse_key_usage (PKT_signature * sig)
{
int key_usage = 0;
const byte *p;
size_t n;
byte flags;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
if (p && n)
{
/* First octet of the keyflags. */
flags = *p;
if (flags & 1)
{
key_usage |= PUBKEY_USAGE_CERT;
flags &= ~1;
}
if (flags & 2)
{
key_usage |= PUBKEY_USAGE_SIG;
flags &= ~2;
}
/* We do not distinguish between encrypting communications and
encrypting storage. */
if (flags & (0x04 | 0x08))
{
key_usage |= PUBKEY_USAGE_ENC;
flags &= ~(0x04 | 0x08);
}
if (flags & 0x20)
{
key_usage |= PUBKEY_USAGE_AUTH;
flags &= ~0x20;
}
if (flags)
key_usage |= PUBKEY_USAGE_UNKNOWN;
}
/* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
capability that we do not handle. This serves to distinguish
between a zero key usage which we handle as the default
capabilities for that algorithm, and a usage that we do not
handle. */
return key_usage;
}
/* Apply information from SIGNODE (which is the valid self-signature
* associated with that UID) to the UIDNODE:
* - wether the UID has been revoked
* - assumed creation date of the UID
* - temporary store the keyflags here
* - temporary store the key expiration time here
* - mark whether the primary user ID flag hat been set.
* - store the preferences
*/
static void
fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
{
PKT_user_id *uid = uidnode->pkt->pkt.user_id;
PKT_signature *sig = signode->pkt->pkt.signature;
const byte *p, *sym, *hash, *zip;
size_t n, nsym, nhash, nzip;
sig->flags.chosen_selfsig = 1;/* We chose this one. */
uid->created = 0; /* Not created == invalid. */
if (IS_UID_REV (sig))
{
uid->is_revoked = 1;
return; /* Has been revoked. */
}
else
uid->is_revoked = 0;
uid->expiredate = sig->expiredate;
if (sig->flags.expired)
{
uid->is_expired = 1;
return; /* Has expired. */
}
else
uid->is_expired = 0;
uid->created = sig->timestamp; /* This one is okay. */
uid->selfsigversion = sig->version;
/* If we got this far, it's not expired :) */
uid->is_expired = 0;
/* Store the key flags in the helper variable for later processing. */
uid->help_key_usage = parse_key_usage (sig);
/* Ditto for the key expiration. */
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
if (p && buffer_to_u32 (p))
uid->help_key_expire = keycreated + buffer_to_u32 (p);
else
uid->help_key_expire = 0;
/* Set the primary user ID flag - we will later wipe out some
* of them to only have one in our keyblock. */
uid->is_primary = 0;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
if (p && *p)
uid->is_primary = 2;
/* We could also query this from the unhashed area if it is not in
* the hased area and then later try to decide which is the better
* there should be no security problem with this.
* For now we only look at the hashed one. */
/* Now build the preferences list. These must come from the
hashed section so nobody can modify the ciphers a key is
willing to accept. */
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
sym = p;
nsym = p ? n : 0;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
hash = p;
nhash = p ? n : 0;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
zip = p;
nzip = p ? n : 0;
if (uid->prefs)
xfree (uid->prefs);
n = nsym + nhash + nzip;
if (!n)
uid->prefs = NULL;
else
{
uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
n = 0;
for (; nsym; nsym--, n++)
{
uid->prefs[n].type = PREFTYPE_SYM;
uid->prefs[n].value = *sym++;
}
for (; nhash; nhash--, n++)
{
uid->prefs[n].type = PREFTYPE_HASH;
uid->prefs[n].value = *hash++;
}
for (; nzip; nzip--, n++)
{
uid->prefs[n].type = PREFTYPE_ZIP;
uid->prefs[n].value = *zip++;
}
uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
uid->prefs[n].value = 0;
}
/* See whether we have the MDC feature. */
uid->flags.mdc = 0;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
if (p && n && (p[0] & 0x01))
uid->flags.mdc = 1;
/* And the keyserver modify flag. */
uid->flags.ks_modify = 1;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
if (p && n && (p[0] & 0x80))
uid->flags.ks_modify = 0;
}
static void
sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
{
rinfo->date = sig->timestamp;
rinfo->algo = sig->pubkey_algo;
rinfo->keyid[0] = sig->keyid[0];
rinfo->keyid[1] = sig->keyid[1];
}
/* Note that R_REVOKED may be set to 0, 1 or 2. */
static void
merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
struct revoke_info *rinfo)
{
PKT_public_key *pk = NULL;
KBNODE k;
u32 kid[2];
u32 sigdate, uiddate, uiddate2;
KBNODE signode, uidnode, uidnode2;
u32 curtime = make_timestamp ();
unsigned int key_usage = 0;
u32 keytimestamp = 0;
u32 key_expire = 0;
int key_expire_seen = 0;
byte sigversion = 0;
*r_revoked = 0;
memset (rinfo, 0, sizeof (*rinfo));
if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
BUG ();
pk = keyblock->pkt->pkt.public_key;
keytimestamp = pk->timestamp;
keyid_from_pk (pk, kid);
pk->main_keyid[0] = kid[0];
pk->main_keyid[1] = kid[1];
if (pk->version < 4)
{
/* Before v4 the key packet itself contains the expiration date
* and there was no way to change it, so we start with the one
* from the key packet. */
key_expire = pk->max_expiredate;
key_expire_seen = 1;
}
/* First pass: Find the latest direct key self-signature. We assume
* that the newest one overrides all others. */
/* In case this key was already merged. */
xfree (pk->revkey);
pk->revkey = NULL;
pk->numrevkeys = 0;
signode = NULL;
sigdate = 0; /* Helper variable to find the latest signature. */
for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
{
if (k->pkt->pkttype == PKT_SIGNATURE)
{
PKT_signature *sig = k->pkt->pkt.signature;
if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
{
if (check_key_signature (keyblock, k, NULL))
; /* Signature did not verify. */
else if (IS_KEY_REV (sig))
{
/* Key has been revoked - there is no way to
* override such a revocation, so we theoretically
* can stop now. We should not cope with expiration
* times for revocations here because we have to
* assume that an attacker can generate all kinds of
* signatures. However due to the fact that the key
* has been revoked it does not harm either and by
* continuing we gather some more info on that
* key. */
*r_revoked = 1;
sig_to_revoke_info (sig, rinfo);
}
else if (IS_KEY_SIG (sig))
{
/* Add any revocation keys onto the pk. This is
particularly interesting since we normally only
get data from the most recent 1F signature, but
you need multiple 1F sigs to properly handle
revocation keys (PGP does it this way, and a
revocation key could be sensitive and hence in a
different signature). */
if (sig->revkey)
{
int i;
pk->revkey =
xrealloc (pk->revkey, sizeof (struct revocation_key) *
(pk->numrevkeys + sig->numrevkeys));
for (i = 0; i < sig->numrevkeys; i++)
memcpy (&pk->revkey[pk->numrevkeys++],
sig->revkey[i],
sizeof (struct revocation_key));
}
if (sig->timestamp >= sigdate)
{
if (sig->flags.expired)
; /* Signature has expired - ignore it. */
else
{
sigdate = sig->timestamp;
signode = k;
if (sig->version > sigversion)
sigversion = sig->version;
}
}
}
}
}
}
/* Remove dupes from the revocation keys. */
if (pk->revkey)
{
int i, j, x, changed = 0;
for (i = 0; i < pk->numrevkeys; i++)
{
for (j = i + 1; j < pk->numrevkeys; j++)
{
if (memcmp (&pk->revkey[i], &pk->revkey[j],
sizeof (struct revocation_key)) == 0)
{
/* remove j */
for (x = j; x < pk->numrevkeys - 1; x++)
pk->revkey[x] = pk->revkey[x + 1];
pk->numrevkeys--;
j--;
changed = 1;
}
}
}
if (changed)
pk->revkey = xrealloc (pk->revkey,
pk->numrevkeys *
sizeof (struct revocation_key));
}
if (signode)
{
/* Some information from a direct key signature take precedence
* over the same information given in UID sigs. */
PKT_signature *sig = signode->pkt->pkt.signature;
const byte *p;
key_usage = parse_key_usage (sig);
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
if (p && buffer_to_u32 (p))
{
key_expire = keytimestamp + buffer_to_u32 (p);
key_expire_seen = 1;
}
/* Mark that key as valid: One direct key signature should
* render a key as valid. */
pk->flags.valid = 1;
}
/* Pass 1.5: Look for key revocation signatures that were not made
by the key (i.e. did a revocation key issue a revocation for
us?). Only bother to do this if there is a revocation key in the
first place and we're not revoked already. */
if (!*r_revoked && pk->revkey)
for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
{
if (k->pkt->pkttype == PKT_SIGNATURE)
{
PKT_signature *sig = k->pkt->pkt.signature;
if (IS_KEY_REV (sig) &&
(sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
{
int rc = check_revocation_keys (pk, sig);
if (rc == 0)
{
*r_revoked = 2;
sig_to_revoke_info (sig, rinfo);
/* Don't continue checking since we can't be any
more revoked than this. */
break;
}
else if (rc == G10ERR_NO_PUBKEY)
pk->flags.maybe_revoked = 1;
/* A failure here means the sig did not verify, was
not issued by a revocation key, or a revocation
key loop was broken. If a revocation key isn't
findable, however, the key might be revoked and
we don't know it. */
/* TODO: In the future handle subkey and cert
revocations? PGP doesn't, but it's in 2440. */
}
}
}
/* Second pass: Look at the self-signature of all user IDs. */
signode = uidnode = NULL;
sigdate = 0; /* Helper variable to find the latest signature in one UID. */
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID)
{
if (uidnode && signode)
{
fixup_uidnode (uidnode, signode, keytimestamp);
pk->flags.valid = 1;
}
uidnode = k;
signode = NULL;
sigdate = 0;
}
else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
{
PKT_signature *sig = k->pkt->pkt.signature;
if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
{
if (check_key_signature (keyblock, k, NULL))
; /* signature did not verify */
else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
&& sig->timestamp >= sigdate)
{
/* Note: we allow to invalidate cert revocations
* by a newer signature. An attacker can't use this
* because a key should be revoced with a key revocation.
* The reason why we have to allow for that is that at
* one time an email address may become invalid but later
* the same email address may become valid again (hired,
* fired, hired again). */
sigdate = sig->timestamp;
signode = k;
signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
if (sig->version > sigversion)
sigversion = sig->version;
}
}
}
}
if (uidnode && signode)
{
fixup_uidnode (uidnode, signode, keytimestamp);
pk->flags.valid = 1;
}
/* If the key isn't valid yet, and we have
--allow-non-selfsigned-uid set, then force it valid. */
if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
{
if (opt.verbose)
log_info (_("Invalid key %s made valid by"
" --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
pk->flags.valid = 1;
}
/* The key STILL isn't valid, so try and find an ultimately
trusted signature. */
if (!pk->flags.valid)
{
uidnode = NULL;
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID)
uidnode = k;
else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
{
PKT_signature *sig = k->pkt->pkt.signature;
if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
{
PKT_public_key *ultimate_pk;
ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
/* We don't want to use the full get_pubkey to
avoid infinite recursion in certain cases.
There is no reason to check that an ultimately
trusted key is still valid - if it has been
revoked or the user should also renmove the
ultimate trust flag. */
if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
&& check_key_signature2 (keyblock, k, ultimate_pk,
NULL, NULL, NULL, NULL) == 0
&& get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
{
free_public_key (ultimate_pk);
pk->flags.valid = 1;
break;
}
free_public_key (ultimate_pk);
}
}
}
}
/* Record the highest selfsig version so we know if this is a v3
key through and through, or a v3 key with a v4 selfsig
somewhere. This is useful in a few places to know if the key
must be treated as PGP2-style or OpenPGP-style. Note that a
selfsig revocation with a higher version number will also raise
this value. This is okay since such a revocation must be
issued by the user (i.e. it cannot be issued by someone else to
modify the key behavior.) */
pk->selfsigversion = sigversion;
/* Now that we had a look at all user IDs we can now get some information
* from those user IDs.
*/
if (!key_usage)
{
/* Find the latest user ID with key flags set. */
uiddate = 0; /* Helper to find the latest user ID. */
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID)
{
PKT_user_id *uid = k->pkt->pkt.user_id;
if (uid->help_key_usage && uid->created > uiddate)
{
key_usage = uid->help_key_usage;
uiddate = uid->created;
}
}
}
}
if (!key_usage)
{
/* No key flags at all: get it from the algo. */
key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
}
else
{
/* Check that the usage matches the usage as given by the algo. */
int x = openpgp_pk_algo_usage (pk->pubkey_algo);
if (x) /* Mask it down to the actual allowed usage. */
key_usage &= x;
}
/* Whatever happens, it's a primary key, so it can certify. */
pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
if (!key_expire_seen)
{
/* Find the latest valid user ID with a key expiration set
* Note, that this may be a different one from the above because
* some user IDs may have no expiration date set. */
uiddate = 0;
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID)
{
PKT_user_id *uid = k->pkt->pkt.user_id;
if (uid->help_key_expire && uid->created > uiddate)
{
key_expire = uid->help_key_expire;
uiddate = uid->created;
}
}
}
}
/* Currently only v3 keys have a maximum expiration date, but I'll
bet v5 keys get this feature again. */
if (key_expire == 0
|| (pk->max_expiredate && key_expire > pk->max_expiredate))
key_expire = pk->max_expiredate;
pk->has_expired = key_expire >= curtime ? 0 : key_expire;
pk->expiredate = key_expire;
/* Fixme: we should see how to get rid of the expiretime fields but
* this needs changes at other places too. */
/* And now find the real primary user ID and delete all others. */
uiddate = uiddate2 = 0;
uidnode = uidnode2 = NULL;
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
{
PKT_user_id *uid = k->pkt->pkt.user_id;
if (uid->is_primary)
{
if (uid->created > uiddate)
{
uiddate = uid->created;
uidnode = k;
}
else if (uid->created == uiddate && uidnode)
{
/* The dates are equal, so we need to do a
different (and arbitrary) comparison. This
should rarely, if ever, happen. It's good to
try and guarantee that two different GnuPG
users with two different keyrings at least pick
the same primary. */
if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
uidnode = k;
}
}
else
{
if (uid->created > uiddate2)
{
uiddate2 = uid->created;
uidnode2 = k;
}
else if (uid->created == uiddate2 && uidnode2)
{
if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
uidnode2 = k;
}
}
}
}
if (uidnode)
{
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID &&
!k->pkt->pkt.user_id->attrib_data)
{
PKT_user_id *uid = k->pkt->pkt.user_id;
if (k != uidnode)
uid->is_primary = 0;
}
}
}
else if (uidnode2)
{
/* None is flagged primary - use the latest user ID we have,
and disambiguate with the arbitrary packet comparison. */
uidnode2->pkt->pkt.user_id->is_primary = 1;
}
else
{
/* None of our uids were self-signed, so pick the one that
sorts first to be the primary. This is the best we can do
here since there are no self sigs to date the uids. */
uidnode = NULL;
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID
&& !k->pkt->pkt.user_id->attrib_data)
{
if (!uidnode)
{
uidnode = k;
uidnode->pkt->pkt.user_id->is_primary = 1;
continue;
}
else
{
if (cmp_user_ids (k->pkt->pkt.user_id,
uidnode->pkt->pkt.user_id) > 0)
{
uidnode->pkt->pkt.user_id->is_primary = 0;
uidnode = k;
uidnode->pkt->pkt.user_id->is_primary = 1;
}
else
k->pkt->pkt.user_id->is_primary = 0; /* just to be
safe */
}
}
}
}
}
/* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
Caller must free the signature when they are done. */
static PKT_signature *
buf_to_sig (const byte * buf, size_t len)
{
PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
IOBUF iobuf = iobuf_temp_with_content (buf, len);
int save_mode = set_packet_list_mode (0);
if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
{
xfree (sig);
sig = NULL;
}
set_packet_list_mode (save_mode);
iobuf_close (iobuf);
return sig;
}
static void
merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
{
PKT_public_key *mainpk = NULL, *subpk = NULL;
PKT_signature *sig;
KBNODE k;
u32 mainkid[2];
u32 sigdate = 0;
KBNODE signode;
u32 curtime = make_timestamp ();
unsigned int key_usage = 0;
u32 keytimestamp = 0;
u32 key_expire = 0;
const byte *p;
if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
BUG ();
mainpk = keyblock->pkt->pkt.public_key;
if (mainpk->version < 4)
return;/* (actually this should never happen) */
keyid_from_pk (mainpk, mainkid);
subpk = subnode->pkt->pkt.public_key;
keytimestamp = subpk->timestamp;
subpk->flags.valid = 0;
subpk->main_keyid[0] = mainpk->main_keyid[0];
subpk->main_keyid[1] = mainpk->main_keyid[1];
/* Find the latest key binding self-signature. */
signode = NULL;
sigdate = 0; /* Helper to find the latest signature. */
for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_SIGNATURE)
{
sig = k->pkt->pkt.signature;
if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
{
if (check_key_signature (keyblock, k, NULL))
; /* Signature did not verify. */
else if (IS_SUBKEY_REV (sig))
{
/* Note that this means that the date on a
revocation sig does not matter - even if the
binding sig is dated after the revocation sig,
the subkey is still marked as revoked. This
seems ok, as it is just as easy to make new
subkeys rather than re-sign old ones as the
problem is in the distribution. Plus, PGP (7)
does this the same way. */
subpk->flags.revoked = 1;
sig_to_revoke_info (sig, &subpk->revoked);
/* Although we could stop now, we continue to
* figure out other information like the old expiration
* time. */
}
else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
{
if (sig->flags.expired)
; /* Signature has expired - ignore it. */
else
{
sigdate = sig->timestamp;
signode = k;
signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
}
}
}
}
}
/* No valid key binding. */
if (!signode)
return;
sig = signode->pkt->pkt.signature;
sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
key_usage = parse_key_usage (sig);
if (!key_usage)
{
/* No key flags at all: get it from the algo. */
key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
}
else
{
/* Check that the usage matches the usage as given by the algo. */
int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
if (x) /* Mask it down to the actual allowed usage. */
key_usage &= x;
}
subpk->pubkey_usage = key_usage;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
if (p && buffer_to_u32 (p))
key_expire = keytimestamp + buffer_to_u32 (p);
else
key_expire = 0;
subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
subpk->expiredate = key_expire;
/* Algo doesn't exist. */
if (openpgp_pk_test_algo (subpk->pubkey_algo))
return;
subpk->flags.valid = 1;
/* Find the most recent 0x19 embedded signature on our self-sig. */
if (!subpk->flags.backsig)
{
int seq = 0;
size_t n;
PKT_signature *backsig = NULL;
sigdate = 0;
/* We do this while() since there may be other embedded
signatures in the future. We only want 0x19 here. */
while ((p = enum_sig_subpkt (sig->hashed,
SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
if (n > 3
&& ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
{
PKT_signature *tempsig = buf_to_sig (p, n);
if (tempsig)
{
if (tempsig->timestamp > sigdate)
{
if (backsig)
free_seckey_enc (backsig);
backsig = tempsig;
sigdate = backsig->timestamp;
}
else
free_seckey_enc (tempsig);
}
}
seq = 0;
/* It is safe to have this in the unhashed area since the 0x19
is located on the selfsig for convenience, not security. */
while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
&n, &seq, NULL)))
if (n > 3
&& ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
{
PKT_signature *tempsig = buf_to_sig (p, n);
if (tempsig)
{
if (tempsig->timestamp > sigdate)
{
if (backsig)
free_seckey_enc (backsig);
backsig = tempsig;
sigdate = backsig->timestamp;
}
else
free_seckey_enc (tempsig);
}
}
if (backsig)
{
/* At ths point, backsig contains the most recent 0x19 sig.
Let's see if it is good. */
/* 2==valid, 1==invalid, 0==didn't check */
if (check_backsig (mainpk, subpk, backsig) == 0)
subpk->flags.backsig = 2;
else
subpk->flags.backsig = 1;
free_seckey_enc (backsig);
}
}
}
/*
* Merge information from the self-signatures with the key, so that
* we can later use them more easy.
* The function works by first applying the self signatures to the
* primary key and the to each subkey.
* Here are the rules we use to decide which inormation from which
* self-signature is used:
* We check all self signatures or validity and ignore all invalid signatures.
* All signatures are then ordered by their creation date ....
* For the primary key:
* FIXME the docs
*/
static void
merge_selfsigs (KBNODE keyblock)
{
KBNODE k;
int revoked;
struct revoke_info rinfo;
PKT_public_key *main_pk;
prefitem_t *prefs;
unsigned int mdc_feature;
if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
{
if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
{
log_error ("expected public key but found secret key "
"- must stop\n");
/* We better exit here because a public key is expected at
other places too. FIXME: Figure this out earlier and
don't get to here at all */
g10_exit (1);
}
BUG ();
}
merge_selfsigs_main (keyblock, &revoked, &rinfo);
/* Now merge in the data from each of the subkeys. */
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
merge_selfsigs_subkey (keyblock, k);
}
}
main_pk = keyblock->pkt->pkt.public_key;
if (revoked || main_pk->has_expired || !main_pk->flags.valid)
{
/* If the primary key is revoked, expired, or invalid we
* better set the appropriate flags on that key and all
* subkeys. */
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
PKT_public_key *pk = k->pkt->pkt.public_key;
if (!main_pk->flags.valid)
pk->flags.valid = 0;
if (revoked && !pk->flags.revoked)
{
pk->flags.revoked = revoked;
memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
}
if (main_pk->has_expired)
pk->has_expired = main_pk->has_expired;
}
}
return;
}
/* Set the preference list of all keys to those of the primary real
* user ID. Note: we use these preferences when we don't know by
* which user ID the key has been selected.
* fixme: we should keep atoms of commonly used preferences or
* use reference counting to optimize the preference lists storage.
* FIXME: it might be better to use the intersection of
* all preferences.
* Do a similar thing for the MDC feature flag. */
prefs = NULL;
mdc_feature = 0;
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID
&& !k->pkt->pkt.user_id->attrib_data
&& k->pkt->pkt.user_id->is_primary)
{
prefs = k->pkt->pkt.user_id->prefs;
mdc_feature = k->pkt->pkt.user_id->flags.mdc;
break;
}
}
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
PKT_public_key *pk = k->pkt->pkt.public_key;
if (pk->prefs)
xfree (pk->prefs);
pk->prefs = copy_prefs (prefs);
pk->flags.mdc = mdc_feature;
}
}
}
/* See whether the key fits our requirements and in case we do not
* request the primary key, select a suitable subkey.
*
* Returns: True when a suitable key has been found.
*
* We have to distinguish four cases: FIXME!
* 1. No usage and no primary key requested
* Examples for this case are that we have a keyID to be used
* for decrytion or verification.
* 2. No usage but primary key requested
* This is the case for all functions which work on an
* entire keyblock, e.g. for editing or listing
* 3. Usage and primary key requested
* FXME
* 4. Usage but no primary key requested
* FIXME
* FIXME: Tell what is going to happen here and something about the rationale
* Note: We don't use this function if no specific usage is requested;
* This way the getkey functions can be used for plain key listings.
*
* CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
* is the key we actually found by looking at the keyid or a fingerprint and
* may either point to the primary or one of the subkeys. */
static int
finish_lookup (GETKEY_CTX ctx)
{
KBNODE keyblock = ctx->keyblock;
KBNODE k;
KBNODE foundk = NULL;
PKT_user_id *foundu = NULL;
#define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
unsigned int req_usage = (ctx->req_usage & USAGE_MASK);
/* Request the primary if we're certifying another key, and also
if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
do not understand signatures made by a signing subkey. PGP 8
does. */
int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
u32 latest_date;
KBNODE latest_key;
u32 curtime = make_timestamp ();
assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
ctx->found_key = NULL;
if (ctx->exact)
{
for (k = keyblock; k; k = k->next)
{
if ((k->flag & 1))
{
assert (k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
foundk = k;
break;
}
}
}
for (k = keyblock; k; k = k->next)
{
if ((k->flag & 2))
{
assert (k->pkt->pkttype == PKT_USER_ID);
foundu = k->pkt->pkt.user_id;
break;
}
}
if (DBG_CACHE)
log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
(ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
foundk ? "one" : "all", req_usage);
if (!req_usage)
{
latest_key = foundk ? foundk : keyblock;
goto found;
}
latest_date = 0;
latest_key = NULL;
/* Do not look at subkeys if a certification key is requested. */
if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim)
{
KBNODE nextk;
/* Either start a loop or check just this one subkey. */
for (k = foundk ? foundk : keyblock; k; k = nextk)
{
PKT_public_key *pk;
nextk = k->next;
if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
continue;
if (foundk)
nextk = NULL; /* what a hack */
pk = k->pkt->pkt.public_key;
if (DBG_CACHE)
log_debug ("\tchecking subkey %08lX\n",
(ulong) keyid_from_pk (pk, NULL));
if (!pk->flags.valid)
{
if (DBG_CACHE)
log_debug ("\tsubkey not valid\n");
continue;
}
if (pk->flags.revoked)
{
if (DBG_CACHE)
log_debug ("\tsubkey has been revoked\n");
continue;
}
if (pk->has_expired)
{
if (DBG_CACHE)
log_debug ("\tsubkey has expired\n");
continue;
}
if (pk->timestamp > curtime && !opt.ignore_valid_from)
{
if (DBG_CACHE)
log_debug ("\tsubkey not yet valid\n");
continue;
}
if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
{
if (DBG_CACHE)
log_debug ("\tusage does not match: want=%x have=%x\n",
req_usage, pk->pubkey_usage);
continue;
}
if (DBG_CACHE)
log_debug ("\tsubkey might be fine\n");
/* In case a key has a timestamp of 0 set, we make sure
that it is used. A better change would be to compare
">=" but that might also change the selected keys and
is as such a more intrusive change. */
if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
{
latest_date = pk->timestamp;
latest_key = k;
}
}
}
/* Okay now try the primary key unless we want an exact
* key ID match on a subkey */
if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim)
{
PKT_public_key *pk;
if (DBG_CACHE && !foundk && !req_prim)
log_debug ("\tno suitable subkeys found - trying primary\n");
pk = keyblock->pkt->pkt.public_key;
if (!pk->flags.valid)
{
if (DBG_CACHE)
log_debug ("\tprimary key not valid\n");
}
else if (pk->flags.revoked)
{
if (DBG_CACHE)
log_debug ("\tprimary key has been revoked\n");
}
else if (pk->has_expired)
{
if (DBG_CACHE)
log_debug ("\tprimary key has expired\n");
}
else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
{
if (DBG_CACHE)
log_debug ("\tprimary key usage does not match: "
"want=%x have=%x\n", req_usage, pk->pubkey_usage);
}
else /* Okay. */
{
if (DBG_CACHE)
log_debug ("\tprimary key may be used\n");
latest_key = keyblock;
latest_date = pk->timestamp;
}
}
if (!latest_key)
{
if (DBG_CACHE)
log_debug ("\tno suitable key found - giving up\n");
return 0; /* Not found. */
}
found:
if (DBG_CACHE)
log_debug ("\tusing key %08lX\n",
(ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
if (latest_key)
{
PKT_public_key *pk = latest_key->pkt->pkt.public_key;
if (pk->user_id)
free_user_id (pk->user_id);
pk->user_id = scopy_user_id (foundu);
}
ctx->found_key = latest_key;
if (latest_key != keyblock && opt.verbose)
{
char *tempkeystr =
xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
log_info (_("using subkey %s instead of primary key %s\n"),
tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
xfree (tempkeystr);
}
cache_user_id (keyblock);
return 1; /* Found. */
}
/* The main function to lookup a key. On success the found keyblock
is stored at RET_KEYBLOCK and also in CTX. If WANT_SECRET is true
a corresponding secret key is required. */
static int
lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, int want_secret)
{
int rc;
int no_suitable_key = 0;
rc = 0;
while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems)))
{
/* If we are searching for the first key we have to make sure
that the next iteration does not do an implicit reset.
This can be triggered by an empty key ring. */
if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
if (rc)
{
log_error ("keydb_get_keyblock failed: %s\n", g10_errstr (rc));
rc = 0;
goto skip;
}
if (want_secret && agent_probe_any_secret_key (NULL, ctx->keyblock))
goto skip; /* No secret key available. */
/* Warning: node flag bits 0 and 1 should be preserved by
* merge_selfsigs. For secret keys, premerge did tranfer the
* keys to the keyblock. */
merge_selfsigs (ctx->keyblock);
if (finish_lookup (ctx))
{
no_suitable_key = 0;
goto found;
}
else
no_suitable_key = 1;
skip:
/* Release resources and continue search. */
release_kbnode (ctx->keyblock);
ctx->keyblock = NULL;
}
found:
if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
log_error ("keydb_search failed: %s\n", g10_errstr (rc));
if (!rc)
{
*ret_keyblock = ctx->keyblock; /* Return the keyblock. */
ctx->keyblock = NULL;
}
else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
rc = want_secret? G10ERR_UNU_SECKEY : G10ERR_UNU_PUBKEY;
else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
rc = want_secret? G10ERR_NO_SECKEY : G10ERR_NO_PUBKEY;
release_kbnode (ctx->keyblock);
ctx->keyblock = NULL;
ctx->last_rc = rc;
return rc;
}
/*
* Enumerate certain secret keys. Caller must use these procedure:
* 1) create a void pointer and initialize it to NULL
* 2) pass this void pointer by reference to this function
* and provide space for the secret key (pass a buffer for sk)
* 3) call this function as long as it does not return an error.
* The error code GPG_ERR_EOF indicates the end of the listing.
* 4) Always call this function a last time with SK set to NULL,
* so that can free it's context.
*/
gpg_error_t
enum_secret_keys (void **context, PKT_public_key *sk)
{
gpg_error_t err = 0;
const char *name;
struct
{
int eof;
int state;
strlist_t sl;
kbnode_t keyblock;
kbnode_t node;
} *c = *context;
if (!c)
{
/* Make a new context. */
c = xtrycalloc (1, sizeof *c);
if (!c)
return gpg_error_from_syserror ();
*context = c;
}
if (!sk)
{
/* Free the context. */
release_kbnode (c->keyblock);
xfree (c);
*context = NULL;
return 0;
}
if (c->eof)
return gpg_error (GPG_ERR_EOF);
for (;;)
{
/* Loop until we have a keyblock. */
while (!c->keyblock)
{
/* Loop over the list of secret keys. */
do
{
name = NULL;
switch (c->state)
{
case 0: /* First try to use the --default-key. */
if (opt.def_secret_key && *opt.def_secret_key)
name = opt.def_secret_key;
c->state = 1;
break;
case 1: /* Init list of keys to try. */
c->sl = opt.secret_keys_to_try;
c->state++;
break;
case 2: /* Get next item from list. */
if (c->sl)
{
name = c->sl->d;
c->sl = c->sl->next;
}
else
c->state++;
break;
default: /* No more names to check - stop. */
c->eof = 1;
return gpg_error (GPG_ERR_EOF);
}
}
while (!name || !*name);
err = getkey_byname (NULL, NULL, name, 1, &c->keyblock);
if (err)
{
/* getkey_byname might return a keyblock even in the
error case - I have not checked. Thus better release
it. */
release_kbnode (c->keyblock);
c->keyblock = NULL;
}
else
c->node = c->keyblock;
}
/* Get the next key from the current keyblock. */
for (; c->node; c->node = c->node->next)
{
if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
|| c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
copy_public_key (sk, c->node->pkt->pkt.public_key);
c->node = c->node->next;
return 0; /* Found. */
}
}
/* Dispose the keyblock and continue. */
release_kbnode (c->keyblock);
c->keyblock = NULL;
}
}
/*********************************************
*********** User ID printing helpers *******
*********************************************/
/* Return a string with a printable representation of the user_id.
* this string must be freed by xfree. */
char *
get_user_id_string (u32 * keyid)
{
user_id_db_t r;
char *p;
int pass = 0;
/* Try it two times; second pass reads from key resources. */
do
{
for (r = user_id_db; r; r = r->next)
{
keyid_list_t a;
for (a = r->keyids; a; a = a->next)
{
if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
{
p = xmalloc (keystrlen () + 1 + r->len + 1);
sprintf (p, "%s %.*s", keystr (keyid), r->len, r->name);
return p;
}
}
}
}
while (++pass < 2 && !get_pubkey (NULL, keyid));
p = xmalloc (keystrlen () + 5);
sprintf (p, "%s [?]", keystr (keyid));
return p;
}
char *
get_user_id_string_native (u32 * keyid)
{
char *p = get_user_id_string (keyid);
char *p2 = utf8_to_native (p, strlen (p), 0);
xfree (p);
return p2;
}
char *
get_long_user_id_string (u32 * keyid)
{
user_id_db_t r;
char *p;
int pass = 0;
/* Try it two times; second pass reads from key resources. */
do
{
for (r = user_id_db; r; r = r->next)
{
keyid_list_t a;
for (a = r->keyids; a; a = a->next)
{
if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
{
p = xmalloc (r->len + 20);
sprintf (p, "%08lX%08lX %.*s",
(ulong) keyid[0], (ulong) keyid[1],
r->len, r->name);
return p;
}
}
}
}
while (++pass < 2 && !get_pubkey (NULL, keyid));
p = xmalloc (25);
sprintf (p, "%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
return p;
}
char *
get_user_id (u32 * keyid, size_t * rn)
{
user_id_db_t r;
char *p;
int pass = 0;
/* Try it two times; second pass reads from key resources. */
do
{
for (r = user_id_db; r; r = r->next)
{
keyid_list_t a;
for (a = r->keyids; a; a = a->next)
{
if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
{
p = xmalloc (r->len);
memcpy (p, r->name, r->len);
*rn = r->len;
return p;
}
}
}
}
while (++pass < 2 && !get_pubkey (NULL, keyid));
p = xstrdup (user_id_not_found_utf8 ());
*rn = strlen (p);
return p;
}
char *
get_user_id_native (u32 * keyid)
{
size_t rn;
char *p = get_user_id (keyid, &rn);
char *p2 = utf8_to_native (p, rn, 0);
xfree (p);
return p2;
}
KEYDB_HANDLE
get_ctx_handle (GETKEY_CTX ctx)
{
return ctx->kr_handle;
}
static void
free_akl (struct akl *akl)
{
if (akl->spec)
free_keyserver_spec (akl->spec);
xfree (akl);
}
void
release_akl (void)
{
while (opt.auto_key_locate)
{
struct akl *akl2 = opt.auto_key_locate;
opt.auto_key_locate = opt.auto_key_locate->next;
free_akl (akl2);
}
}
/* Returns false on error. */
int
parse_auto_key_locate (char *options)
{
char *tok;
while ((tok = optsep (&options)))
{
struct akl *akl, *check, *last = NULL;
int dupe = 0;
if (tok[0] == '\0')
continue;
akl = xmalloc_clear (sizeof (*akl));
if (ascii_strcasecmp (tok, "nodefault") == 0)
akl->type = AKL_NODEFAULT;
else if (ascii_strcasecmp (tok, "local") == 0)
akl->type = AKL_LOCAL;
else if (ascii_strcasecmp (tok, "ldap") == 0)
akl->type = AKL_LDAP;
else if (ascii_strcasecmp (tok, "keyserver") == 0)
akl->type = AKL_KEYSERVER;
#ifdef USE_DNS_CERT
else if (ascii_strcasecmp (tok, "cert") == 0)
akl->type = AKL_CERT;
#endif
#ifdef USE_DNS_PKA
else if (ascii_strcasecmp (tok, "pka") == 0)
akl->type = AKL_PKA;
#endif
else if ((akl->spec = parse_keyserver_uri (tok, 1, NULL, 0)))
akl->type = AKL_SPEC;
else
{
free_akl (akl);
return 0;
}
/* We must maintain the order the user gave us */
for (check = opt.auto_key_locate; check;
last = check, check = check->next)
{
/* Check for duplicates */
if (check->type == akl->type
&& (akl->type != AKL_SPEC
|| (akl->type == AKL_SPEC
&& strcmp (check->spec->uri, akl->spec->uri) == 0)))
{
dupe = 1;
free_akl (akl);
break;
}
}
if (!dupe)
{
if (last)
last->next = akl;
else
opt.auto_key_locate = akl;
}
}
return 1;
}
/* Return true if a secret key or secret subkey is available for one
of the public keys in KEYBLOCK. */
int
have_any_secret_key (ctrl_t ctrl, kbnode_t keyblock)
{
kbnode_t node;
for (node = keyblock; node; node = node->next)
if ((node->pkt->pkttype == PKT_PUBLIC_KEY
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
&& !agent_probe_secret_key (ctrl, node->pkt->pkt.public_key))
return 1;
return 0;
}
/* Return true if a secret key is available for the public key with
* the given KEYID. This is just a fast check and does not tell us
* whether the secret key is valid. It merely tells os whether there
* is some secret key. */
int
have_secret_key_with_kid (u32 *keyid)
{
gpg_error_t err;
KEYDB_HANDLE kdbhd;
KEYDB_SEARCH_DESC desc;
kbnode_t keyblock;
kbnode_t node;
int result = 0;
kdbhd = keydb_new ();
memset (&desc, 0, sizeof desc);
desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
desc.u.kid[0] = keyid[0];
desc.u.kid[1] = keyid[1];
while (!result && !(err = keydb_search (kdbhd, &desc, 1)))
{
desc.mode = KEYDB_SEARCH_MODE_NEXT;
err = keydb_get_keyblock (kdbhd, &keyblock);
if (err)
{
log_error (_("error reading keyblock: %s\n"), g10_errstr (err));
break;
}
for (node = keyblock; node; node = node->next)
{
/* Bit 0 of the flags is set if the search found the key
using that key or subkey. */
if ((node->flag & 1))
{
assert (node->pkt->pkttype == PKT_PUBLIC_KEY
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
{
result = 1;
break;
}
}
}
release_kbnode (keyblock);
}
keydb_release (kdbhd);
return result;
}
#if 0
/*
* Merge the secret keys from secblock into the pubblock thereby
* replacing the public (sub)keys with their secret counterparts Hmmm:
* It might be better to get away from the concept of entire secret
* keys at all and have a way to store just the real secret parts
* from the key.
*
* FIXME: this is not anymore needed but we keep it as example code for the
* new code we need to write for the import/export feature.
*/
static void
merge_public_with_secret (KBNODE pubblock, KBNODE secblock)
{
KBNODE pub;
assert (pubblock->pkt->pkttype == PKT_PUBLIC_KEY);
assert (secblock->pkt->pkttype == PKT_SECRET_KEY);
for (pub = pubblock; pub; pub = pub->next)
{
if (pub->pkt->pkttype == PKT_PUBLIC_KEY)
{
PKT_public_key *pk = pub->pkt->pkt.public_key;
PKT_secret_key *sk = secblock->pkt->pkt.secret_key;
assert (pub == pubblock); /* Only in the first node. */
/* There is nothing to compare in this case, so just replace
* some information. */
copy_public_parts_to_secret_key (pk, sk);
free_public_key (pk);
pub->pkt->pkttype = PKT_SECRET_KEY;
pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
}
else if (pub->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
KBNODE sec;
PKT_public_key *pk = pub->pkt->pkt.public_key;
/* This is more complicated: It may happen that the sequence
* of the subkeys dosn't match, so we have to find the
* appropriate secret key. */
for (sec = secblock->next; sec; sec = sec->next)
{
if (sec->pkt->pkttype == PKT_SECRET_SUBKEY)
{
PKT_secret_key *sk = sec->pkt->pkt.secret_key;
if (!cmp_public_secret_key (pk, sk))
{
copy_public_parts_to_secret_key (pk, sk);
free_public_key (pk);
pub->pkt->pkttype = PKT_SECRET_SUBKEY;
pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
break;
}
}
}
if (!sec)
BUG (); /* Already checked in premerge. */
}
}
}
/* This function checks that for every public subkey a corresponding
* secret subkey is available and deletes the public subkey otherwise.
* We need this function because we can't delete it later when we
* actually merge the secret parts into the pubring.
* The function also plays some games with the node flags.
*
* FIXME: this is not anymore needed but we keep it as example code for the
* new code we need to write for the import/export feature.
*/
static void
premerge_public_with_secret (KBNODE pubblock, KBNODE secblock)
{
KBNODE last, pub;
assert (pubblock->pkt->pkttype == PKT_PUBLIC_KEY);
assert (secblock->pkt->pkttype == PKT_SECRET_KEY);
for (pub = pubblock, last = NULL; pub; last = pub, pub = pub->next)
{
pub->flag &= ~3; /* Reset bits 0 and 1. */
if (pub->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
KBNODE sec;
PKT_public_key *pk = pub->pkt->pkt.public_key;
for (sec = secblock->next; sec; sec = sec->next)
{
if (sec->pkt->pkttype == PKT_SECRET_SUBKEY)
{
PKT_secret_key *sk = sec->pkt->pkt.secret_key;
if (!cmp_public_secret_key (pk, sk))
{
if (sk->protect.s2k.mode == 1001)
{
/* The secret parts are not available so
we can't use that key for signing etc.
Fix the pubkey usage */
pk->pubkey_usage &= ~(PUBKEY_USAGE_SIG
| PUBKEY_USAGE_AUTH);
}
/* Transfer flag bits 0 and 1 to the pubblock. */
pub->flag |= (sec->flag & 3);
break;
}
}
}
if (!sec)
{
KBNODE next, ll;
if (opt.verbose)
log_info (_("no secret subkey"
" for public subkey %s - ignoring\n"),
keystr_from_pk (pk));
/* We have to remove the subkey in this case. */
assert (last);
/* Find the next subkey. */
for (next = pub->next, ll = pub;
next && next->pkt->pkttype != PKT_PUBLIC_SUBKEY;
ll = next, next = next->next)
;
/* Make new link. */
last->next = next;
/* Release this public subkey with all sigs. */
ll->next = NULL;
release_kbnode (pub);
/* Let the loop continue. */
pub = last;
}
}
}
/* We need to copy the found bits (0 and 1) from the secret key to
the public key. This has already been done for the subkeys but
got lost on the primary key - fix it here. */
pubblock->flag |= (secblock->flag & 3);
}
#endif /*0*/
diff --git a/g10/keydb.c b/g10/keydb.c
index ab727b6c6..acd7f8a43 100644
--- a/g10/keydb.c
+++ b/g10/keydb.c
@@ -1,990 +1,1145 @@
/* keydb.c - key database dispatcher
* Copyright (C) 2001, 2002, 2003, 2004, 2005,
* 2008, 2009, 2011 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
* 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 <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "gpg.h"
#include "util.h"
#include "options.h"
#include "main.h" /*try_make_homedir ()*/
#include "packet.h"
#include "keyring.h"
#include "../kbx/keybox.h"
#include "keydb.h"
#include "i18n.h"
static int active_handles;
typedef enum
{
KEYDB_RESOURCE_TYPE_NONE = 0,
KEYDB_RESOURCE_TYPE_KEYRING,
KEYDB_RESOURCE_TYPE_KEYBOX
} KeydbResourceType;
#define MAX_KEYDB_RESOURCES 40
struct resource_item
{
KeydbResourceType type;
union {
KEYRING_HANDLE kr;
KEYBOX_HANDLE kb;
} u;
void *token;
};
static struct resource_item all_resources[MAX_KEYDB_RESOURCES];
static int used_resources;
static void *primary_keyring=NULL;
struct keydb_handle
{
int locked;
int found;
int current;
int used; /* Number of items in ACTIVE. */
struct resource_item active[MAX_KEYDB_RESOURCES];
};
static int lock_all (KEYDB_HANDLE hd);
static void unlock_all (KEYDB_HANDLE hd);
/* Handle the creation of a keyring or a keybox if it does not yet
exist. Take into acount that other processes might have the
keyring/keybox already locked. This lock check does not work if
the directory itself is not yet available. */
static int
maybe_create_keyring_or_box (char *filename, int is_box, int force)
{
dotlock_t lockhd = NULL;
IOBUF iobuf;
int rc;
mode_t oldmask;
char *last_slash_in_filename;
int save_slash;
/* A quick test whether the filename already exists. */
if (!access (filename, F_OK))
return 0;
/* If we don't want to create a new file at all, there is no need to
go any further - bail out right here. */
if (!force)
return gpg_error (GPG_ERR_ENOENT);
/* First of all we try to create the home directory. Note, that we
don't do any locking here because any sane application of gpg
would create the home directory by itself and not rely on gpg's
tricky auto-creation which is anyway only done for some home
directory name patterns. */
last_slash_in_filename = strrchr (filename, DIRSEP_C);
#if HAVE_W32_SYSTEM
{
/* Windows may either have a slash or a backslash. Take care of it. */
char *p = strrchr (filename, '/');
if (!last_slash_in_filename || p > last_slash_in_filename)
last_slash_in_filename = p;
}
#endif /*HAVE_W32_SYSTEM*/
if (!last_slash_in_filename)
return gpg_error (GPG_ERR_ENOENT); /* No slash at all - should
not happen though. */
save_slash = *last_slash_in_filename;
*last_slash_in_filename = 0;
if (access(filename, F_OK))
{
static int tried;
if (!tried)
{
tried = 1;
try_make_homedir (filename);
}
if (access (filename, F_OK))
{
rc = gpg_error_from_syserror ();
*last_slash_in_filename = save_slash;
goto leave;
}
}
*last_slash_in_filename = save_slash;
/* To avoid races with other instances of gpg trying to create or
update the keyring (it is removed during an update for a short
time), we do the next stuff in a locked state. */
lockhd = dotlock_create (filename, 0);
if (!lockhd)
{
rc = gpg_error_from_syserror ();
/* A reason for this to fail is that the directory is not
writable. However, this whole locking stuff does not make
sense if this is the case. An empty non-writable directory
with no keyring is not really useful at all. */
if (opt.verbose)
log_info ("can't allocate lock for '%s': %s\n",
filename, gpg_strerror (rc));
if (!force)
return gpg_error (GPG_ERR_ENOENT);
else
return rc;
}
if ( dotlock_take (lockhd, -1) )
{
rc = gpg_error_from_syserror ();
/* This is something bad. Probably a stale lockfile. */
log_info ("can't lock '%s': %s\n", filename, gpg_strerror (rc));
goto leave;
}
/* Now the real test while we are locked. */
if (!access (filename, F_OK))
{
rc = 0; /* Okay, we may access the file now. */
goto leave;
}
/* The file does not yet exist, create it now. */
oldmask = umask (077);
if (is_secured_filename (filename))
{
iobuf = NULL;
gpg_err_set_errno (EPERM);
}
else
iobuf = iobuf_create (filename);
umask (oldmask);
if (!iobuf)
{
rc = gpg_error_from_syserror ();
if (is_box)
log_error (_("error creating keybox '%s': %s\n"),
filename, gpg_strerror (rc));
else
log_error (_("error creating keyring '%s': %s\n"),
filename, gpg_strerror (rc));
goto leave;
}
iobuf_close (iobuf);
/* Must invalidate that ugly cache */
iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, filename);
/* Make sure that at least one record is in a new keybox file, so
that the detection magic will work the next time it is used. */
if (is_box)
{
FILE *fp = fopen (filename, "w");
if (!fp)
rc = gpg_error_from_syserror ();
else
{
rc = _keybox_write_header_blob (fp);
fclose (fp);
}
if (rc)
{
if (is_box)
log_error (_("error creating keybox '%s': %s\n"),
filename, gpg_strerror (rc));
else
log_error (_("error creating keyring '%s': %s\n"),
filename, gpg_strerror (rc));
goto leave;
}
}
if (!opt.quiet)
{
if (is_box)
log_info (_("keybox '%s' created\n"), filename);
else
log_info (_("keyring '%s' created\n"), filename);
}
rc = 0;
leave:
if (lockhd)
{
dotlock_release (lockhd);
dotlock_destroy (lockhd);
}
return rc;
}
/*
* Register a resource (keyring or aeybox). The first keyring or
* keybox which is added by this function is created if it does not
* exist. FLAGS are a combination of the KEYDB_RESOURCE_FLAG_
* constants as defined in keydb.h.
*/
gpg_error_t
keydb_add_resource (const char *url, unsigned int flags)
{
static int any_registered;
const char *resname = url;
char *filename = NULL;
int create;
int read_only = !!(flags&KEYDB_RESOURCE_FLAG_READONLY);
int rc = 0;
KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
void *token;
/* Create the resource if it is the first registered one. */
create = (!read_only && !any_registered);
/* Do we have an URL?
* gnupg-ring:filename := this is a plain keyring.
* gnupg-kbx:filename := this is a keybox file.
* filename := See what is is, but create as plain keyring.
*/
if (strlen (resname) > 11 && !strncmp( resname, "gnupg-ring:", 11) )
{
rt = KEYDB_RESOURCE_TYPE_KEYRING;
resname += 11;
}
else if (strlen (resname) > 10 && !strncmp (resname, "gnupg-kbx:", 10) )
{
rt = KEYDB_RESOURCE_TYPE_KEYBOX;
resname += 10;
}
#if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__)
else if (strchr (resname, ':'))
{
log_error ("invalid key resource URL '%s'\n", url );
rc = gpg_error (GPG_ERR_GENERAL);
goto leave;
}
#endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */
if (*resname != DIRSEP_C )
{
/* Do tilde expansion etc. */
if (strchr(resname, DIRSEP_C) )
filename = make_filename (resname, NULL);
else
filename = make_filename (opt.homedir, resname, NULL);
}
else
filename = xstrdup (resname);
/* See whether we can determine the filetype. */
if (rt == KEYDB_RESOURCE_TYPE_NONE)
{
FILE *fp = fopen (filename, "rb");
if (fp)
{
u32 magic;
if (fread (&magic, 4, 1, fp) == 1 )
{
if (magic == 0x13579ace || magic == 0xce9a5713)
; /* GDBM magic - not anymore supported. */
else if (fread (&magic, 4, 1, fp) == 1
&& !memcmp (&magic, "\x01", 1)
&& fread (&magic, 4, 1, fp) == 1
&& !memcmp (&magic, "KBXf", 4))
rt = KEYDB_RESOURCE_TYPE_KEYBOX;
else
rt = KEYDB_RESOURCE_TYPE_KEYRING;
}
else /* Maybe empty: assume keyring. */
rt = KEYDB_RESOURCE_TYPE_KEYRING;
fclose (fp);
}
else /* No file yet: create keybox. */
rt = KEYDB_RESOURCE_TYPE_KEYBOX;
}
switch (rt)
{
case KEYDB_RESOURCE_TYPE_NONE:
log_error ("unknown type of key resource '%s'\n", url );
rc = gpg_error (GPG_ERR_GENERAL);
goto leave;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = maybe_create_keyring_or_box (filename, create, 0);
if (rc)
goto leave;
if (keyring_register_filename (filename, read_only, &token))
{
if (used_resources >= MAX_KEYDB_RESOURCES)
rc = gpg_error (GPG_ERR_RESOURCE_LIMIT);
else
{
if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
primary_keyring = token;
all_resources[used_resources].type = rt;
all_resources[used_resources].u.kr = NULL; /* Not used here */
all_resources[used_resources].token = token;
used_resources++;
}
}
else
{
/* This keyring was already registered, so ignore it.
However, we can still mark it as primary even if it was
already registered. */
if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
primary_keyring = token;
}
break;
case KEYDB_RESOURCE_TYPE_KEYBOX:
{
rc = maybe_create_keyring_or_box (filename, create, 1);
if (rc)
goto leave;
/* FIXME: How do we register a read-only keybox? */
token = keybox_register_file (filename, 0);
if (token)
{
if (used_resources >= MAX_KEYDB_RESOURCES)
rc = gpg_error (GPG_ERR_RESOURCE_LIMIT);
else
{
/* if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY)) */
/* primary_keyring = token; */
all_resources[used_resources].type = rt;
all_resources[used_resources].u.kb = NULL; /* Not used here */
all_resources[used_resources].token = token;
/* FIXME: Do a compress run if needed and no other
user is currently using the keybox. */
used_resources++;
}
}
else
{
/* Already registered. We will mark it as the primary key
if requested. */
/* FIXME: How to do that? Change the keybox interface? */
/* if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY)) */
/* primary_keyring = token; */
}
}
break;
default:
log_error ("resource type of '%s' not supported\n", url);
rc = gpg_error (GPG_ERR_GENERAL);
goto leave;
}
/* fixme: check directory permissions and print a warning */
leave:
if (rc)
log_error (_("keyblock resource '%s': %s\n"), filename, gpg_strerror (rc));
else
any_registered = 1;
xfree (filename);
return rc;
}
KEYDB_HANDLE
keydb_new (void)
{
KEYDB_HANDLE hd;
int i, j;
hd = xmalloc_clear (sizeof *hd);
hd->found = -1;
assert (used_resources <= MAX_KEYDB_RESOURCES);
for (i=j=0; i < used_resources; i++)
{
switch (all_resources[i].type)
{
case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
hd->active[j].type = all_resources[i].type;
hd->active[j].token = all_resources[i].token;
hd->active[j].u.kr = keyring_new (all_resources[i].token);
if (!hd->active[j].u.kr) {
xfree (hd);
return NULL; /* fixme: release all previously allocated handles*/
}
j++;
break;
case KEYDB_RESOURCE_TYPE_KEYBOX:
hd->active[j].type = all_resources[i].type;
hd->active[j].token = all_resources[i].token;
hd->active[j].u.kb = keybox_new (all_resources[i].token, 0);
if (!hd->active[j].u.kb)
{
xfree (hd);
return NULL; /* fixme: release all previously allocated handles*/
}
j++;
break;
}
}
hd->used = j;
active_handles++;
return hd;
}
void
keydb_release (KEYDB_HANDLE hd)
{
int i;
if (!hd)
return;
assert (active_handles > 0);
active_handles--;
unlock_all (hd);
for (i=0; i < hd->used; i++)
{
switch (hd->active[i].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
keyring_release (hd->active[i].u.kr);
break;
case KEYDB_RESOURCE_TYPE_KEYBOX:
keybox_release (hd->active[i].u.kb);
break;
}
}
xfree (hd);
}
/*
* Return the name of the current resource. This is function first
* looks for the last found found, then for the current search
* position, and last returns the first available resource. The
* returned string is only valid as long as the handle exists. This
* function does only return NULL if no handle is specified, in all
* other error cases an empty string is returned.
*/
const char *
keydb_get_resource_name (KEYDB_HANDLE hd)
{
int idx;
const char *s = NULL;
if (!hd)
return NULL;
if ( hd->found >= 0 && hd->found < hd->used)
idx = hd->found;
else if ( hd->current >= 0 && hd->current < hd->used)
idx = hd->current;
else
idx = 0;
switch (hd->active[idx].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
s = NULL;
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
s = keyring_get_resource_name (hd->active[idx].u.kr);
break;
case KEYDB_RESOURCE_TYPE_KEYBOX:
s = keybox_get_resource_name (hd->active[idx].u.kb);
break;
}
return s? s: "";
}
static int
lock_all (KEYDB_HANDLE hd)
{
int i, rc = 0;
/* Fixme: This locking scheme may lead to a deadlock if the resources
are not added in the same order by all processes. We are
currently only allowing one resource so it is not a problem.
[Oops: Who claimed the latter]
To fix this we need to use a lock file to protect lock_all. */
for (i=0; !rc && i < hd->used; i++)
{
switch (hd->active[i].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_lock (hd->active[i].u.kr, 1);
break;
case KEYDB_RESOURCE_TYPE_KEYBOX:
rc = keybox_lock (hd->active[i].u.kb, 1);
break;
}
}
if (rc)
{
/* Revert the already taken locks. */
for (i--; i >= 0; i--)
{
switch (hd->active[i].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
keyring_lock (hd->active[i].u.kr, 0);
break;
case KEYDB_RESOURCE_TYPE_KEYBOX:
rc = keybox_lock (hd->active[i].u.kb, 0);
break;
}
}
}
else
hd->locked = 1;
return rc;
}
static void
unlock_all (KEYDB_HANDLE hd)
{
int i;
if (!hd->locked)
return;
for (i=hd->used-1; i >= 0; i--)
{
switch (hd->active[i].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
keyring_lock (hd->active[i].u.kr, 0);
break;
case KEYDB_RESOURCE_TYPE_KEYBOX:
keybox_lock (hd->active[i].u.kb, 0);
break;
}
}
hd->locked = 0;
}
+static gpg_error_t
+parse_keyblock_image (iobuf_t iobuf, kbnode_t *r_keyblock)
+{
+ gpg_error_t err;
+ PACKET *pkt;
+ kbnode_t keyblock = NULL;
+ kbnode_t node;
+ int in_cert, save_mode;
+
+ *r_keyblock = NULL;
+
+ pkt = xtrymalloc (sizeof *pkt);
+ if (!pkt)
+ return gpg_error_from_syserror ();
+ init_packet (pkt);
+ save_mode = set_packet_list_mode (0);
+ in_cert = 0;
+ while ((err = parse_packet (iobuf, pkt)) != -1)
+ {
+ if (gpg_err_code (err) == GPG_ERR_UNKNOWN_PACKET)
+ {
+ free_packet (pkt);
+ init_packet (pkt);
+ continue;
+ }
+ if (err)
+ {
+ log_error ("parse_keyblock_image: read error: %s\n",
+ gpg_strerror (err));
+ err = gpg_error (GPG_ERR_INV_KEYRING);
+ break;
+ }
+ if (pkt->pkttype == PKT_COMPRESSED)
+ {
+ log_error ("skipped compressed packet in keybox blob\n");
+ free_packet(pkt);
+ init_packet(pkt);
+ continue;
+ }
+ if (pkt->pkttype == PKT_RING_TRUST)
+ {
+ log_info ("skipped ring trust packet in keybox blob\n");
+ free_packet(pkt);
+ init_packet(pkt);
+ continue;
+ }
+
+ if (!in_cert && pkt->pkttype != PKT_PUBLIC_KEY)
+ {
+ log_error ("error: first packet in a keybox blob is not a "
+ "public key packet\n");
+ err = gpg_error (GPG_ERR_INV_KEYRING);
+ break;
+ }
+ if (in_cert && (pkt->pkttype == PKT_PUBLIC_KEY
+ || pkt->pkttype == PKT_SECRET_KEY))
+ {
+ log_error ("error: multiple keyblocks in a keybox blob\n");
+ err = gpg_error (GPG_ERR_INV_KEYRING);
+ break;
+ }
+ in_cert = 1;
+
+ node = new_kbnode (pkt);
+ if (!keyblock)
+ keyblock = node;
+ else
+ add_kbnode (keyblock, node);
+ pkt = xtrymalloc (sizeof *pkt);
+ if (!pkt)
+ {
+ err = gpg_error_from_syserror ();
+ break;
+ }
+ init_packet (pkt);
+ }
+ set_packet_list_mode (save_mode);
+
+ if (err == -1 && keyblock)
+ err = 0; /* Got the entire keyblock. */
+
+ if (err)
+ release_kbnode (keyblock);
+ else
+ *r_keyblock = keyblock;
+ free_packet (pkt);
+ xfree (pkt);
+ return err;
+}
+
+
/*
* Return the last found keyring. Caller must free it.
* The returned keyblock has the kbode flag bit 0 set for the node with
* the public key used to locate the keyblock or flag bit 1 set for
* the user ID node.
*/
gpg_error_t
keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb)
{
gpg_error_t err = 0;
+ *ret_kb = NULL;
+
if (!hd)
return gpg_error (GPG_ERR_INV_ARG);
if (hd->found < 0 || hd->found >= hd->used)
return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
switch (hd->active[hd->found].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
err = gpg_error (GPG_ERR_GENERAL); /* oops */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
err = keyring_get_keyblock (hd->active[hd->found].u.kr, ret_kb);
break;
- /* case KEYDB_RESOURCE_TYPE_KEYBOX: */
- /* err = keybox_get_keyblock (hd->active[hd->found].u.kb, ret_kb); */
- /* if (!err) */
- /* err = parse_keyblock (image, imagelen) */
- /* break; */
+ case KEYDB_RESOURCE_TYPE_KEYBOX:
+ {
+ iobuf_t iobuf;
+
+ err = keybox_get_keyblock (hd->active[hd->found].u.kb, &iobuf);
+ if (!err)
+ {
+ err = parse_keyblock_image (iobuf, ret_kb);
+ iobuf_close (iobuf);
+ }
+ }
+ break;
}
return err;
}
+
+/* Build a keyblock image from KEYBLOCK. Returns 0 on success and
+ only then stores a new iobuf object at R_IOBUF. */
+static gpg_error_t
+build_keyblock_image (kbnode_t keyblock, iobuf_t *r_iobuf)
+{
+ gpg_error_t err;
+ iobuf_t iobuf;
+ kbnode_t kbctx, node;
+
+ *r_iobuf = NULL;
+
+ iobuf = iobuf_temp ();
+ for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
+ {
+ /* Make sure to use only packets valid on a keyblock. */
+ switch (node->pkt->pkttype)
+ {
+ case PKT_PUBLIC_KEY:
+ case PKT_PUBLIC_SUBKEY:
+ case PKT_SIGNATURE:
+ case PKT_USER_ID:
+ case PKT_ATTRIBUTE:
+ /* Note that we don't want the ring trust packets. They are
+ not useful. */
+ break;
+ default:
+ continue;
+ }
+
+ err = build_packet (iobuf, node->pkt);
+ if (err)
+ {
+ iobuf_close (iobuf);
+ return err;
+ }
+ }
+
+ *r_iobuf = iobuf;
+ return 0;
+}
+
+
/*
* Update the current keyblock with the keyblock KB
*/
gpg_error_t
keydb_update_keyblock (KEYDB_HANDLE hd, kbnode_t kb)
{
gpg_error_t rc;
if (!hd)
return gpg_error (GPG_ERR_INV_ARG);
if (hd->found < 0 || hd->found >= hd->used)
return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
if (opt.dry_run)
return 0;
rc = lock_all (hd);
if (rc)
return rc;
switch (hd->active[hd->found].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
rc = gpg_error (GPG_ERR_GENERAL); /* oops */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_update_keyblock (hd->active[hd->found].u.kr, kb);
break;
/* case KEYDB_RESOURCE_TYPE_KEYRING: */
/* rc = build_keyblock (kb, &image, &imagelen); */
/* if (!rc) */
/* rc = keybox_update_keyblock (hd->active[hd->found].u.kb, */
/* image, imagelen); */
/* break; */
}
unlock_all (hd);
return rc;
}
/*
* Insert a new KB into one of the resources.
*/
gpg_error_t
keydb_insert_keyblock (KEYDB_HANDLE hd, kbnode_t kb)
{
- int rc;
+ gpg_error_t err;
int idx;
if (!hd)
return gpg_error (GPG_ERR_INV_ARG);
if (opt.dry_run)
return 0;
if (hd->found >= 0 && hd->found < hd->used)
idx = hd->found;
else if (hd->current >= 0 && hd->current < hd->used)
idx = hd->current;
else
return gpg_error (GPG_ERR_GENERAL);
- rc = lock_all (hd);
- if (rc)
- return rc;
+ err = lock_all (hd);
+ if (err)
+ return err;
switch (hd->active[idx].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
- rc = gpg_error (GPG_ERR_GENERAL); /* oops */
+ err = gpg_error (GPG_ERR_GENERAL); /* oops */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
- rc = keyring_insert_keyblock (hd->active[idx].u.kr, kb);
+ err = keyring_insert_keyblock (hd->active[idx].u.kr, kb);
+ break;
+ case KEYDB_RESOURCE_TYPE_KEYBOX:
+ { /* We need to turn our kbnode_t list of packets into a proper
+ keyblock first. This is required by the OpenPGP key parser
+ included in the keybox code. Eventually we can change this
+ kludge to have the caller pass the image. */
+ iobuf_t iobuf;
+
+ err = build_keyblock_image (kb, &iobuf);
+ if (!err)
+ {
+ err = keybox_insert_keyblock (hd->active[idx].u.kb,
+ iobuf_get_temp_buffer (iobuf),
+ iobuf_get_temp_length (iobuf));
+ iobuf_close (iobuf);
+ }
+ }
break;
- /* case KEYDB_RESOURCE_TYPE_KEYBOX: */
- /* rc = build_keyblock (kb, &image, &imagelen); */
- /* if (!rc) */
- /* rc = keybox_insert_keyblock (hd->active[idx].u.kb, image, imagelen); */
- /* break; */
}
unlock_all (hd);
- return rc;
+ return err;
}
/*
* Delete the current keyblock.
*/
gpg_error_t
keydb_delete_keyblock (KEYDB_HANDLE hd)
{
gpg_error_t rc;
if (!hd)
return gpg_error (GPG_ERR_INV_ARG);
if (hd->found < 0 || hd->found >= hd->used)
return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
if (opt.dry_run)
return 0;
rc = lock_all (hd);
if (rc)
return rc;
switch (hd->active[hd->found].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
rc = gpg_error (GPG_ERR_GENERAL);
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_delete_keyblock (hd->active[hd->found].u.kr);
break;
case KEYDB_RESOURCE_TYPE_KEYBOX:
rc = keybox_delete (hd->active[hd->found].u.kb);
break;
}
unlock_all (hd);
return rc;
}
/*
* Locate the default writable key resource, so that the next
* operation (which is only relevant for inserts) will be done on this
* resource.
*/
gpg_error_t
keydb_locate_writable (KEYDB_HANDLE hd, const char *reserved)
{
gpg_error_t rc;
(void)reserved;
if (!hd)
return G10ERR_INV_ARG;
rc = keydb_search_reset (hd); /* this does reset hd->current */
if (rc)
return rc;
/* If we have a primary set, try that one first */
if (primary_keyring)
{
for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
{
if(hd->active[hd->current].token==primary_keyring)
{
if(keyring_is_writable (hd->active[hd->current].token))
return 0;
else
break;
}
}
rc = keydb_search_reset (hd); /* this does reset hd->current */
if (rc)
return rc;
}
for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
{
switch (hd->active[hd->current].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
BUG();
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
if (keyring_is_writable (hd->active[hd->current].token))
return 0; /* found (hd->current is set to it) */
break;
case KEYDB_RESOURCE_TYPE_KEYBOX:
if (keybox_is_writable (hd->active[hd->current].token))
return 0; /* found (hd->current is set to it) */
break;
}
}
return gpg_error (GPG_ERR_NOT_FOUND);
}
/*
* Rebuild the caches of all key resources.
*/
void
keydb_rebuild_caches (int noisy)
{
int i, rc;
for (i=0; i < used_resources; i++)
{
if (!keyring_is_writable (all_resources[i].token))
continue;
switch (all_resources[i].type)
{
case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_rebuild_cache (all_resources[i].token,noisy);
if (rc)
log_error (_("failed to rebuild keyring cache: %s\n"),
g10_errstr (rc));
break;
}
}
}
/*
* Start the next search on this handle right at the beginning
*/
gpg_error_t
keydb_search_reset (KEYDB_HANDLE hd)
{
gpg_error_t rc = 0;
int i;
if (!hd)
return gpg_error (GPG_ERR_INV_ARG);
hd->current = 0;
hd->found = -1;
/* Now reset all resources. */
for (i=0; !rc && i < hd->used; i++)
{
switch (hd->active[i].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_search_reset (hd->active[i].u.kr);
break;
case KEYDB_RESOURCE_TYPE_KEYBOX:
rc = keybox_search_reset (hd->active[i].u.kb);
break;
}
}
return rc;
}
/*
* Search through all keydb resources, starting at the current
* position, for a keyblock which contains one of the keys described
* in the DESC array. Returns GPG_ERR_NOT_FOUND if no matching
* keyring was found.
*/
gpg_error_t
keydb_search2 (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc,
size_t ndesc, size_t *descindex)
{
gpg_error_t rc;
if (!hd)
return gpg_error (GPG_ERR_INV_ARG);
rc = -1;
while ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
&& hd->current >= 0 && hd->current < hd->used)
{
switch (hd->active[hd->current].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
BUG(); /* we should never see it here */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_search (hd->active[hd->current].u.kr, desc,
ndesc, descindex);
break;
case KEYDB_RESOURCE_TYPE_KEYBOX:
rc = keybox_search (hd->active[hd->current].u.kb, desc, ndesc);
break;
}
if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
{
/* EOF -> switch to next resource */
hd->current++;
}
else if (!rc)
hd->found = hd->current;
}
return ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
? gpg_error (GPG_ERR_NOT_FOUND)
: rc);
}
gpg_error_t
keydb_search_first (KEYDB_HANDLE hd)
{
KEYDB_SEARCH_DESC desc;
memset (&desc, 0, sizeof desc);
desc.mode = KEYDB_SEARCH_MODE_FIRST;
return keydb_search (hd, &desc, 1);
}
gpg_error_t
keydb_search_next (KEYDB_HANDLE hd)
{
KEYDB_SEARCH_DESC desc;
memset (&desc, 0, sizeof desc);
desc.mode = KEYDB_SEARCH_MODE_NEXT;
return keydb_search (hd, &desc, 1);
}
gpg_error_t
keydb_search_kid (KEYDB_HANDLE hd, u32 *kid)
{
KEYDB_SEARCH_DESC desc;
memset (&desc, 0, sizeof desc);
desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
desc.u.kid[0] = kid[0];
desc.u.kid[1] = kid[1];
return keydb_search (hd, &desc, 1);
}
gpg_error_t
keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr)
{
KEYDB_SEARCH_DESC desc;
memset (&desc, 0, sizeof desc);
desc.mode = KEYDB_SEARCH_MODE_FPR;
memcpy (desc.u.fpr, fpr, MAX_FINGERPRINT_LEN);
return keydb_search (hd, &desc, 1);
}
diff --git a/kbx/kbxutil.c b/kbx/kbxutil.c
index fee55705b..cd9d120ff 100644
--- a/kbx/kbxutil.c
+++ b/kbx/kbxutil.c
@@ -1,604 +1,631 @@
/* kbxutil.c - The Keybox utility
* Copyright (C) 2000, 2001, 2004, 2007, 2011 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
* 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 <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include <assert.h>
#define JNLIB_NEED_LOG_LOGV
#include "../common/logging.h"
#include "../common/argparse.h"
#include "../common/stringhelp.h"
#include "../common/utf8conv.h"
#include "i18n.h"
#include "keybox-defs.h"
#include "../common/init.h"
#include <gcrypt.h>
enum cmd_and_opt_values {
aNull = 0,
oArmor = 'a',
oDryRun = 'n',
oOutput = 'o',
oQuiet = 'q',
oVerbose = 'v',
aNoSuchCmd = 500, /* force other values not to be a letter */
aFindByFpr,
aFindByKid,
aFindByUid,
aStats,
aImportOpenPGP,
aFindDups,
aCut,
oDebug,
oDebugAll,
oNoArmor,
oFrom,
oTo,
aTest
};
static ARGPARSE_OPTS opts[] = {
{ 300, NULL, 0, N_("@Commands:\n ") },
/* { aFindByFpr, "find-by-fpr", 0, "|FPR| find key using it's fingerprnt" }, */
/* { aFindByKid, "find-by-kid", 0, "|KID| find key using it's keyid" }, */
/* { aFindByUid, "find-by-uid", 0, "|NAME| find key by user name" }, */
{ aStats, "stats", 0, "show key statistics" },
{ aImportOpenPGP, "import-openpgp", 0, "import OpenPGP keyblocks"},
{ aFindDups, "find-dups", 0, "find duplicates" },
{ aCut, "cut", 0, "export records" },
{ 301, NULL, 0, N_("@\nOptions:\n ") },
{ oFrom, "from", 4, "|N|first record to export" },
{ oTo, "to", 4, "|N|last record to export" },
/* { oArmor, "armor", 0, N_("create ascii armored output")}, */
/* { oArmor, "armour", 0, "@" }, */
/* { oOutput, "output", 2, N_("use as output file")}, */
{ oVerbose, "verbose", 0, N_("verbose") },
{ oQuiet, "quiet", 0, N_("be somewhat more quiet") },
{ oDryRun, "dry-run", 0, N_("do not make any changes") },
{ oDebug, "debug" ,4|16, N_("set debugging flags")},
{ oDebugAll, "debug-all" ,0, N_("enable full debugging")},
{0} /* end of list */
};
void myexit (int rc);
int keybox_errors_seen = 0;
static const char *
my_strusage( int level )
{
const char *p;
switch( level ) {
case 11: p = "kbxutil (GnuPG)";
break;
case 13: p = VERSION; break;
case 17: p = PRINTABLE_OS_NAME; break;
case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
case 1:
case 40: p =
_("Usage: kbxutil [options] [files] (-h for help)");
break;
case 41: p =
_("Syntax: kbxutil [options] [files]\n"
"List, export, import Keybox data\n");
break;
default: p = NULL;
}
return p;
}
/* Used by gcry for logging */
static void
my_gcry_logger (void *dummy, int level, const char *fmt, va_list arg_ptr)
{
(void)dummy;
/* Map the log levels. */
switch (level)
{
case GCRY_LOG_CONT: level = JNLIB_LOG_CONT; break;
case GCRY_LOG_INFO: level = JNLIB_LOG_INFO; break;
case GCRY_LOG_WARN: level = JNLIB_LOG_WARN; break;
case GCRY_LOG_ERROR:level = JNLIB_LOG_ERROR; break;
case GCRY_LOG_FATAL:level = JNLIB_LOG_FATAL; break;
case GCRY_LOG_BUG: level = JNLIB_LOG_BUG; break;
case GCRY_LOG_DEBUG:level = JNLIB_LOG_DEBUG; break;
default: level = JNLIB_LOG_ERROR; break;
}
log_logv (level, fmt, arg_ptr);
}
/* static void */
/* wrong_args( const char *text ) */
/* { */
/* log_error("usage: kbxutil %s\n", text); */
/* myexit ( 1 ); */
/* } */
#if 0
static int
hextobyte( const byte *s )
{
int c;
if( *s >= '0' && *s <= '9' )
c = 16 * (*s - '0');
else if( *s >= 'A' && *s <= 'F' )
c = 16 * (10 + *s - 'A');
else if( *s >= 'a' && *s <= 'f' )
c = 16 * (10 + *s - 'a');
else
return -1;
s++;
if( *s >= '0' && *s <= '9' )
c += *s - '0';
else if( *s >= 'A' && *s <= 'F' )
c += 10 + *s - 'A';
else if( *s >= 'a' && *s <= 'f' )
c += 10 + *s - 'a';
else
return -1;
return c;
}
#endif
#if 0
static char *
format_fingerprint ( const char *s )
{
int i, c;
byte fpr[20];
for (i=0; i < 20 && *s; ) {
if ( *s == ' ' || *s == '\t' ) {
s++;
continue;
}
c = hextobyte(s);
if (c == -1) {
return NULL;
}
fpr[i++] = c;
s += 2;
}
return gcry_xstrdup ( fpr );
}
#endif
#if 0
static int
format_keyid ( const char *s, u32 *kid )
{
char helpbuf[9];
switch ( strlen ( s ) ) {
case 8:
kid[0] = 0;
kid[1] = strtoul( s, NULL, 16 );
return 10;
case 16:
mem2str( helpbuf, s, 9 );
kid[0] = strtoul( helpbuf, NULL, 16 );
kid[1] = strtoul( s+8, NULL, 16 );
return 11;
}
return 0; /* error */
}
#endif
static char *
read_file (const char *fname, size_t *r_length)
{
FILE *fp;
char *buf;
size_t buflen;
if (!strcmp (fname, "-"))
{
size_t nread, bufsize = 0;
fp = stdin;
buf = NULL;
buflen = 0;
#define NCHUNK 8192
do
{
bufsize += NCHUNK;
if (!buf)
buf = xtrymalloc (bufsize);
else
buf = xtryrealloc (buf, bufsize);
if (!buf)
log_fatal ("can't allocate buffer: %s\n", strerror (errno));
nread = fread (buf+buflen, 1, NCHUNK, fp);
if (nread < NCHUNK && ferror (fp))
{
log_error ("error reading '[stdin]': %s\n", strerror (errno));
xfree (buf);
return NULL;
}
buflen += nread;
}
while (nread == NCHUNK);
#undef NCHUNK
}
else
{
struct stat st;
fp = fopen (fname, "rb");
if (!fp)
{
log_error ("can't open '%s': %s\n", fname, strerror (errno));
return NULL;
}
if (fstat (fileno(fp), &st))
{
log_error ("can't stat '%s': %s\n", fname, strerror (errno));
fclose (fp);
return NULL;
}
buflen = st.st_size;
buf = xtrymalloc (buflen+1);
if (!buf)
log_fatal ("can't allocate buffer: %s\n", strerror (errno));
if (fread (buf, buflen, 1, fp) != 1)
{
log_error ("error reading '%s': %s\n", fname, strerror (errno));
fclose (fp);
xfree (buf);
return NULL;
}
fclose (fp);
}
*r_length = buflen;
return buf;
}
static void
dump_fpr (const unsigned char *buffer, size_t len)
{
int i;
for (i=0; i < len; i++, buffer++)
{
if (len == 20)
{
if (i == 10)
putchar (' ');
printf (" %02X%02X", buffer[0], buffer[1]);
i++; buffer++;
}
else
{
if (i && !(i % 8))
putchar (' ');
printf (" %02X", buffer[0]);
}
}
}
static void
dump_openpgp_key (keybox_openpgp_info_t info, const unsigned char *image)
{
printf ("pub %2d %02X%02X%02X%02X",
info->primary.algo,
info->primary.keyid[4], info->primary.keyid[5],
info->primary.keyid[6], info->primary.keyid[7] );
dump_fpr (info->primary.fpr, info->primary.fprlen);
putchar ('\n');
if (info->nsubkeys)
{
struct _keybox_openpgp_key_info *k;
k = &info->subkeys;
do
{
printf ("sub %2d %02X%02X%02X%02X",
k->algo,
k->keyid[4], k->keyid[5],
k->keyid[6], k->keyid[7] );
dump_fpr (k->fpr, k->fprlen);
putchar ('\n');
k = k->next;
}
while (k);
}
if (info->nuids)
{
struct _keybox_openpgp_uid_info *u;
u = &info->uids;
do
{
printf ("uid\t\t%.*s\n", (int)u->len, image + u->off);
u = u->next;
}
while (u);
}
}
static void
-import_openpgp (const char *filename)
+import_openpgp (const char *filename, int dryrun)
{
gpg_error_t err;
char *buffer;
size_t buflen, nparsed;
unsigned char *p;
struct _keybox_openpgp_info info;
+ KEYBOXBLOB blob;
buffer = read_file (filename, &buflen);
if (!buffer)
return;
p = (unsigned char *)buffer;
for (;;)
{
err = _keybox_parse_openpgp (p, buflen, &nparsed, &info);
assert (nparsed <= buflen);
if (err)
{
if (gpg_err_code (err) == GPG_ERR_NO_DATA)
break;
if (gpg_err_code (err) == GPG_ERR_UNSUPPORTED_ALGORITHM)
{
/* This is likely a v3 key packet with a non-RSA
algorithm. These are keys from very early versions
of GnuPG (pre-OpenPGP). */
}
else
{
fflush (stdout);
log_info ("%s: failed to parse OpenPGP keyblock: %s\n",
filename, gpg_strerror (err));
}
}
else
{
- dump_openpgp_key (&info, p);
+ if (dryrun)
+ dump_openpgp_key (&info, p);
+ else
+ {
+ err = _keybox_create_openpgp_blob (&blob, &info, p, nparsed, 0);
+ if (err)
+ {
+ fflush (stdout);
+ log_error ("%s: failed to create OpenPGP keyblock: %s\n",
+ filename, gpg_strerror (err));
+ }
+ else
+ {
+ err = _keybox_write_blob (blob, stdout);
+ _keybox_release_blob (blob);
+ if (err)
+ {
+ fflush (stdout);
+ log_error ("%s: failed to write OpenPGP keyblock: %s\n",
+ filename, gpg_strerror (err));
+ }
+ }
+ }
+
_keybox_destroy_openpgp_info (&info);
}
p += nparsed;
buflen -= nparsed;
}
xfree (buffer);
}
int
main( int argc, char **argv )
{
ARGPARSE_ARGS pargs;
enum cmd_and_opt_values cmd = 0;
unsigned long from = 0, to = ULONG_MAX;
+ int dry_run = 0;
set_strusage( my_strusage );
gcry_control (GCRYCTL_DISABLE_SECMEM);
log_set_prefix ("kbxutil", 1);
/* Make sure that our subsystems are ready. */
i18n_init ();
init_common_subsystems (&argc, &argv);
/* Check that the libraries are suitable. Do it here because
the option parsing may need services of the library. */
if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
{
log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
}
gcry_set_log_handler (my_gcry_logger, NULL);
/*create_dotlock(NULL); register locking cleanup */
/* We need to use the gcry malloc function because jnlib uses them. */
keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags= 1; /* do not remove the args */
while (arg_parse( &pargs, opts) )
{
switch (pargs.r_opt)
{
case oVerbose:
/*opt.verbose++;*/
/*gcry_control( GCRYCTL_SET_VERBOSITY, (int)opt.verbose );*/
break;
case oDebug:
/*opt.debug |= pargs.r.ret_ulong; */
break;
case oDebugAll:
/*opt.debug = ~0;*/
break;
case aFindByFpr:
case aFindByKid:
case aFindByUid:
case aStats:
case aImportOpenPGP:
case aFindDups:
case aCut:
cmd = pargs.r_opt;
break;
case oFrom: from = pargs.r.ret_ulong; break;
case oTo: to = pargs.r.ret_ulong; break;
+ case oDryRun: dry_run = 1; break;
+
default:
pargs.err = 2;
break;
}
}
if (to < from)
log_error ("record number of \"--to\" is lower than \"--from\" one\n");
if (log_get_errorcount(0) )
myexit(2);
if (!cmd)
{ /* Default is to list a KBX file */
if (!argc)
_keybox_dump_file (NULL, 0, stdout);
else
{
for (; argc; argc--, argv++)
_keybox_dump_file (*argv, 0, stdout);
}
}
else if (cmd == aStats )
{
if (!argc)
_keybox_dump_file (NULL, 1, stdout);
else
{
for (; argc; argc--, argv++)
_keybox_dump_file (*argv, 1, stdout);
}
}
else if (cmd == aFindDups )
{
if (!argc)
_keybox_dump_find_dups (NULL, 0, stdout);
else
{
for (; argc; argc--, argv++)
_keybox_dump_find_dups (*argv, 0, stdout);
}
}
else if (cmd == aCut )
{
if (!argc)
_keybox_dump_cut_records (NULL, from, to, stdout);
else
{
for (; argc; argc--, argv++)
_keybox_dump_cut_records (*argv, from, to, stdout);
}
}
else if (cmd == aImportOpenPGP)
{
if (!argc)
- import_openpgp ("-");
+ import_openpgp ("-", dry_run);
else
{
for (; argc; argc--, argv++)
- import_openpgp (*argv);
+ import_openpgp (*argv, dry_run);
}
}
#if 0
else if ( cmd == aFindByFpr )
{
char *fpr;
if ( argc != 2 )
wrong_args ("kbxfile foingerprint");
fpr = format_fingerprint ( argv[1] );
if ( !fpr )
log_error ("invalid formatted fingerprint\n");
else
{
kbxfile_search_by_fpr ( argv[0], fpr );
gcry_free ( fpr );
}
}
else if ( cmd == aFindByKid )
{
u32 kid[2];
int mode;
if ( argc != 2 )
wrong_args ("kbxfile short-or-long-keyid");
mode = format_keyid ( argv[1], kid );
if ( !mode )
log_error ("invalid formatted keyID\n");
else
{
kbxfile_search_by_kid ( argv[0], kid, mode );
}
}
else if ( cmd == aFindByUid )
{
if ( argc != 2 )
wrong_args ("kbxfile userID");
kbxfile_search_by_uid ( argv[0], argv[1] );
}
#endif
else
log_error ("unsupported action\n");
myexit(0);
return 8; /*NEVER REACHED*/
}
void
myexit( int rc )
{
/* if( opt.debug & DBG_MEMSTAT_VALUE ) {*/
/* gcry_control( GCRYCTL_DUMP_MEMORY_STATS ); */
/* gcry_control( GCRYCTL_DUMP_RANDOM_STATS ); */
/* }*/
/* if( opt.debug ) */
/* gcry_control( GCRYCTL_DUMP_SECMEM_STATS ); */
rc = rc? rc : log_get_errorcount(0)? 2 :
keybox_errors_seen? 1 : 0;
exit(rc );
}
diff --git a/kbx/keybox-blob.c b/kbx/keybox-blob.c
index 998a77019..c4a89820b 100644
--- a/kbx/keybox-blob.c
+++ b/kbx/keybox-blob.c
@@ -1,1038 +1,1002 @@
/* keybox-blob.c - KBX Blob handling
* Copyright (C) 2000, 2001, 2002, 2003, 2008 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
* 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 <http://www.gnu.org/licenses/>.
*/
/* The keybox data formats
The KeyBox uses an augmented OpenPGP/X.509 key format. This makes
random access to a keyblock/certificate easier and also gives the
opportunity to store additional information (e.g. the fingerprint)
along with the key. All integers are stored in network byte order,
offsets are counted from the beginning of the Blob.
The first record of a plain KBX file has a special format:
u32 length of the first record
byte Blob type (1)
byte version number (1)
byte reserved
byte reserved
u32 magic 'KBXf'
u32 reserved
u32 file_created_at
u32 last_maintenance_run
u32 reserved
u32 reserved
The OpenPGP and X.509 blob are very similiar, things which are
X.509 specific are noted like [X.509: xxx]
u32 length of this blob (including these 4 bytes)
byte Blob type (2) [X509: 3]
byte version number of this blob type (1)
u16 Blob flags
- bit 0 = contains secret key material
+ bit 0 = contains secret key material (not used)
bit 1 = ephemeral blob (e.g. used while quering external resources)
u32 offset to the OpenPGP keyblock or X509 DER encoded certificate
u32 and its length
u16 number of keys (at least 1!) [X509: always 1]
u16 size of additional key information
n times:
b20 The keys fingerprint
(fingerprints are always 20 bytes, MD5 left padded with zeroes)
u32 offset to the n-th key's keyID (a keyID is always 8 byte)
or 0 if not known which is the case only for X509.
u16 special key flags
bit 0 = qualified signature (not yet implemented}
u16 reserved
u16 size of serialnumber(may be zero)
n u16 (see above) bytes of serial number
u16 number of user IDs
u16 size of additional user ID information
n times:
u32 offset to the n-th user ID
u32 length of this user ID.
u16 special user ID flags.
bit 0 =
byte validity
byte reserved
[For X509, the first user ID is the Issuer, the second the Subject
and the others are subjectAltNames]
u16 number of signatures
u16 size of signature information (4)
u32 expiration time of signature with some special values:
0x00000000 = not checked
0x00000001 = missing key
0x00000002 = bad signature
0x10000000 = valid and expires at some date in 1978.
0xffffffff = valid and does not expire
u8 assigned ownertrust [X509: not used]
u8 all_validity
OpenPGP: see ../g10/trustdb/TRUST_* [not yet used]
X509: Bit 4 set := key has been revoked. Note that this value
matches TRUST_FLAG_REVOKED
u16 reserved
u32 recheck_after
u32 Newest timestamp in the keyblock (useful for KS syncronsiation?)
u32 Blob created at
u32 size of reserved space (not including this field)
reserved space
Here we might want to put other data
Here comes the keyblock
maybe we put a signature here later.
b16 MD5 checksum (useful for KS syncronisation), we might also want to use
a mac here.
b4 reserved
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <time.h>
#include "keybox-defs.h"
#include <gcrypt.h>
-#ifdef KEYBOX_WITH_OPENPGP
-/* include stuff to parse the packets */
-#endif
#ifdef KEYBOX_WITH_X509
#include <ksba.h>
#endif
#include "../common/gettime.h"
/* special values of the signature status */
#define SF_NONE(a) ( !(a) )
#define SF_NOKEY(a) ((a) & (1<<0))
#define SF_BAD(a) ((a) & (1<<1))
#define SF_VALID(a) ((a) & (1<<29))
struct membuf {
size_t len;
size_t size;
char *buf;
int out_of_core;
};
/* #if MAX_FINGERPRINT_LEN < 20 */
/* #error fingerprints are 20 bytes */
/* #endif */
struct keyboxblob_key {
char fpr[20];
u32 off_kid;
ulong off_kid_addr;
u16 flags;
};
struct keyboxblob_uid {
+ u32 off;
ulong off_addr;
char *name; /* used only with x509 */
u32 len;
u16 flags;
byte validity;
};
struct keyid_list {
struct keyid_list *next;
int seqno;
byte kid[8];
};
struct fixup_list {
struct fixup_list *next;
u32 off;
u32 val;
};
struct keyboxblob {
byte *blob;
size_t bloblen;
off_t fileoffset;
/* stuff used only by keybox_create_blob */
unsigned char *serialbuf;
const unsigned char *serial;
size_t seriallen;
int nkeys;
struct keyboxblob_key *keys;
int nuids;
struct keyboxblob_uid *uids;
int nsigs;
u32 *sigs;
struct fixup_list *fixups;
int fixup_out_of_core;
struct keyid_list *temp_kids;
struct membuf bufbuf; /* temporary store for the blob */
struct membuf *buf;
};
/* A simple implemention of a dynamic buffer. Use init_membuf() to
create a buffer, put_membuf to append bytes and get_membuf to
release and return the buffer. Allocation errors are detected but
only returned at the final get_membuf(), this helps not to clutter
the code with out of core checks. */
static void
init_membuf (struct membuf *mb, int initiallen)
{
mb->len = 0;
mb->size = initiallen;
mb->out_of_core = 0;
mb->buf = xtrymalloc (initiallen);
if (!mb->buf)
mb->out_of_core = 1;
}
static void
put_membuf (struct membuf *mb, const void *buf, size_t len)
{
if (mb->out_of_core)
return;
if (mb->len + len >= mb->size)
{
char *p;
mb->size += len + 1024;
p = xtryrealloc (mb->buf, mb->size);
if (!p)
{
mb->out_of_core = 1;
return;
}
mb->buf = p;
}
memcpy (mb->buf + mb->len, buf, len);
mb->len += len;
}
static void *
get_membuf (struct membuf *mb, size_t *len)
{
char *p;
if (mb->out_of_core)
{
xfree (mb->buf);
mb->buf = NULL;
return NULL;
}
p = mb->buf;
*len = mb->len;
mb->buf = NULL;
mb->out_of_core = 1; /* don't allow a reuse */
return p;
}
static void
put8 (struct membuf *mb, byte a )
{
put_membuf (mb, &a, 1);
}
static void
put16 (struct membuf *mb, u16 a )
{
unsigned char tmp[2];
tmp[0] = a>>8;
tmp[1] = a;
put_membuf (mb, tmp, 2);
}
static void
put32 (struct membuf *mb, u32 a )
{
unsigned char tmp[4];
tmp[0] = a>>24;
tmp[1] = a>>16;
tmp[2] = a>>8;
tmp[3] = a;
put_membuf (mb, tmp, 4);
}
/* Store a value in the fixup list */
static void
add_fixup (KEYBOXBLOB blob, u32 off, u32 val)
{
struct fixup_list *fl;
if (blob->fixup_out_of_core)
return;
fl = xtrycalloc(1, sizeof *fl);
if (!fl)
blob->fixup_out_of_core = 1;
else
{
fl->off = off;
fl->val = val;
fl->next = blob->fixups;
blob->fixups = fl;
}
}
-#ifdef KEYBOX_WITH_OPENPGP
/*
OpenPGP specific stuff
*/
-/*
- We must store the keyid at some place because we can't calculate the
- offset yet. This is only used for v3 keyIDs. Function returns an
- index value for later fixup or -1 for out of core. The value must be
- a non-zero value */
+/* We must store the keyid at some place because we can't calculate
+ the offset yet. This is only used for v3 keyIDs. Function returns
+ an index value for later fixup or -1 for out of core. The value
+ must be a non-zero value. */
static int
-pgp_temp_store_kid (KEYBOXBLOB blob, PKT_public_key *pk)
+pgp_temp_store_kid (KEYBOXBLOB blob, struct _keybox_openpgp_key_info *kinfo)
{
struct keyid_list *k, *r;
k = xtrymalloc (sizeof *k);
if (!k)
return -1;
- k->kid[0] = pk->keyid[0] >> 24 ;
- k->kid[1] = pk->keyid[0] >> 16 ;
- k->kid[2] = pk->keyid[0] >> 8 ;
- k->kid[3] = pk->keyid[0] ;
- k->kid[4] = pk->keyid[0] >> 24 ;
- k->kid[5] = pk->keyid[0] >> 16 ;
- k->kid[6] = pk->keyid[0] >> 8 ;
- k->kid[7] = pk->keyid[0] ;
+ memcpy (k->kid, kinfo->keyid, 8);
k->seqno = 0;
k->next = blob->temp_kids;
blob->temp_kids = k;
for (r=k; r; r = r->next)
k->seqno++;
return k->seqno;
}
-static int
-pgp_create_key_part (KEYBOXBLOB blob, KBNODE keyblock)
+
+/* Helper for pgp_create_key_part. */
+static gpg_error_t
+pgp_create_key_part_single (KEYBOXBLOB blob, int n,
+ struct _keybox_openpgp_key_info *kinfo)
{
- KBNODE node;
size_t fprlen;
- int n;
+ int off;
- for (n=0, node = keyblock; node; node = node->next)
+ fprlen = kinfo->fprlen;
+ if (fprlen > 20)
+ fprlen = 20;
+ memcpy (blob->keys[n].fpr, kinfo->fpr, fprlen);
+ if (fprlen != 20) /* v3 fpr - shift right and fill with zeroes. */
{
- if ( node->pkt->pkttype == PKT_PUBLIC_KEY
- || node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
- {
- PKT_public_key *pk = node->pkt->pkt.public_key;
- char tmp[20];
-
- fingerprint_from_pk (pk, tmp , &fprlen);
- memcpy (blob->keys[n].fpr, tmp, 20);
- if ( fprlen != 20 ) /*v3 fpr - shift right and fill with zeroes*/
- {
- assert (fprlen == 16);
- memmove (blob->keys[n].fpr+4, blob->keys[n].fpr, 16);
- memset (blob->keys[n].fpr, 0, 4);
- blob->keys[n].off_kid = pgp_temp_store_kid (blob, pk);
- }
- else
- {
- blob->keys[n].off_kid = 0; /* will be fixed up later */
- }
- blob->keys[n].flags = 0;
- n++;
- }
- else if ( node->pkt->pkttype == PKT_SECRET_KEY
- || node->pkt->pkttype == PKT_SECRET_SUBKEY )
- {
- never_reached (); /* actually not yet implemented */
- }
+ memmove (blob->keys[n].fpr + 20 - fprlen, blob->keys[n].fpr, fprlen);
+ memset (blob->keys[n].fpr, 0, 20 - fprlen);
+ off = pgp_temp_store_kid (blob, kinfo);
+ if (off == -1)
+ return gpg_error_from_syserror ();
+ blob->keys[n].off_kid = off;
}
+ else
+ blob->keys[n].off_kid = 0; /* Will be fixed up later */
+ blob->keys[n].flags = 0;
+ return 0;
+}
+
+
+static gpg_error_t
+pgp_create_key_part (KEYBOXBLOB blob, keybox_openpgp_info_t info)
+{
+ gpg_error_t err;
+ int n = 0;
+ struct _keybox_openpgp_key_info *kinfo;
+
+ err = pgp_create_key_part_single (blob, n++, &info->primary);
+ if (err)
+ return err;
+ if (info->nsubkeys)
+ for (kinfo = &info->subkeys; kinfo; kinfo = kinfo->next)
+ if ((err=pgp_create_key_part_single (blob, n++, kinfo)))
+ return err;
+
assert (n == blob->nkeys);
return 0;
}
-static int
-pgp_create_uid_part (KEYBOXBLOB blob, KBNODE keyblock)
+
+static void
+pgp_create_uid_part (KEYBOXBLOB blob, keybox_openpgp_info_t info)
{
- KBNODE node;
- int n;
+ int n = 0;
+ struct _keybox_openpgp_uid_info *u;
- for (n=0, node = keyblock; node; node = node->next)
+ if (info->nuids)
{
- if (node->pkt->pkttype == PKT_USER_ID)
+ for (u = &info->uids; u; u = u->next)
{
- PKT_user_id *u = node->pkt->pkt.user_id;
-
+ blob->uids[n].off = u->off;
blob->uids[n].len = u->len;
blob->uids[n].flags = 0;
blob->uids[n].validity = 0;
n++;
- }
+ }
}
+
assert (n == blob->nuids);
- return 0;
}
-static int
-pgp_create_sig_part (KEYBOXBLOB blob, KBNODE keyblock)
+
+static void
+pgp_create_sig_part (KEYBOXBLOB blob)
{
- KBNODE node;
int n;
- for (n=0, node = keyblock; node; node = node->next)
+ for (n=0; n < blob->nsigs; n++)
{
- if (node->pkt->pkttype == PKT_SIGNATURE)
- {
- PKT_signature *sig = node->pkt->pkt.signature;
-
- blob->sigs[n] = 0; /* FIXME: check the signature here */
- n++;
- }
+ blob->sigs[n] = 0; /* FIXME: check the signature here */
}
- assert( n == blob->nsigs );
- return 0;
}
+
static int
-pgp_create_blob_keyblock (KEYBOXBLOB blob, KBNODE keyblock)
+pgp_create_blob_keyblock (KEYBOXBLOB blob,
+ const unsigned char *image, size_t imagelen)
{
struct membuf *a = blob->buf;
- KBNODE node;
- int rc;
int n;
u32 kbstart = a->len;
- add_fixup (blob, kbstart);
+ add_fixup (blob, 8, kbstart);
- for (n = 0, node = keyblock; node; node = node->next)
- {
- rc = build_packet ( a, node->pkt );
- if ( rc ) {
- gpg_log_error ("build_packet(%d) for keyboxblob failed: %s\n",
- node->pkt->pkttype, gpg_errstr(rc) );
- return GPGERR_WRITE_FILE;
- }
- if ( node->pkt->pkttype == PKT_USER_ID )
- {
- PKT_user_id *u = node->pkt->pkt.user_id;
- /* build_packet has set the offset of the name into u ;
- * now we can do the fixup */
- add_fixup (blob, blob->uids[n].off_addr, u->stored_at);
- n++;
- }
- }
- assert (n == blob->nuids);
+ for (n = 0; n < blob->nuids; n++)
+ add_fixup (blob, blob->uids[n].off_addr, kbstart + blob->uids[n].off);
+
+ put_membuf (a, image, imagelen);
- add_fixup (blob, a->len - kbstart);
+ add_fixup (blob, 12, a->len - kbstart);
return 0;
}
-#endif /*KEYBOX_WITH_OPENPGP*/
#ifdef KEYBOX_WITH_X509
/*
X.509 specific stuff
*/
/* Write the raw certificate out */
static int
x509_create_blob_cert (KEYBOXBLOB blob, ksba_cert_t cert)
{
struct membuf *a = blob->buf;
const unsigned char *image;
size_t length;
u32 kbstart = a->len;
/* Store our offset for later fixup */
add_fixup (blob, 8, kbstart);
image = ksba_cert_get_image (cert, &length);
if (!image)
return gpg_error (GPG_ERR_GENERAL);
put_membuf (a, image, length);
add_fixup (blob, 12, a->len - kbstart);
return 0;
}
#endif /*KEYBOX_WITH_X509*/
/* Write a stored keyID out to the buffer */
static void
write_stored_kid (KEYBOXBLOB blob, int seqno)
{
struct keyid_list *r;
for ( r = blob->temp_kids; r; r = r->next )
{
if (r->seqno == seqno )
{
put_membuf (blob->buf, r->kid, 8);
return;
}
}
never_reached ();
}
/* Release a list of key IDs */
static void
release_kid_list (struct keyid_list *kl)
{
struct keyid_list *r, *r2;
for ( r = kl; r; r = r2 )
{
r2 = r->next;
xfree (r);
}
}
static int
create_blob_header (KEYBOXBLOB blob, int blobtype, int as_ephemeral)
{
struct membuf *a = blob->buf;
int i;
put32 ( a, 0 ); /* blob length, needs fixup */
put8 ( a, blobtype);
put8 ( a, 1 ); /* blob type version */
put16 ( a, as_ephemeral? 2:0 ); /* blob flags */
put32 ( a, 0 ); /* offset to the raw data, needs fixup */
put32 ( a, 0 ); /* length of the raw data, needs fixup */
put16 ( a, blob->nkeys );
put16 ( a, 20 + 4 + 2 + 2 ); /* size of key info */
for ( i=0; i < blob->nkeys; i++ )
{
put_membuf (a, blob->keys[i].fpr, 20);
blob->keys[i].off_kid_addr = a->len;
put32 ( a, 0 ); /* offset to keyid, fixed up later */
put16 ( a, blob->keys[i].flags );
put16 ( a, 0 ); /* reserved */
}
put16 (a, blob->seriallen); /*fixme: check that it fits into 16 bits*/
if (blob->serial)
put_membuf (a, blob->serial, blob->seriallen);
put16 ( a, blob->nuids );
put16 ( a, 4 + 4 + 2 + 1 + 1 ); /* size of uid info */
for (i=0; i < blob->nuids; i++)
{
blob->uids[i].off_addr = a->len;
put32 ( a, 0 ); /* offset to userid, fixed up later */
put32 ( a, blob->uids[i].len );
put16 ( a, blob->uids[i].flags );
put8 ( a, 0 ); /* validity */
put8 ( a, 0 ); /* reserved */
}
put16 ( a, blob->nsigs );
put16 ( a, 4 ); /* size of sig info */
for (i=0; i < blob->nsigs; i++)
{
put32 ( a, blob->sigs[i]);
}
put8 ( a, 0 ); /* assigned ownertrust */
put8 ( a, 0 ); /* validity of all user IDs */
put16 ( a, 0 ); /* reserved */
put32 ( a, 0 ); /* time of next recheck */
put32 ( a, 0 ); /* newest timestamp (none) */
put32 ( a, make_timestamp() ); /* creation time */
put32 ( a, 0 ); /* size of reserved space */
/* reserved space (which is currently of size 0) */
/* space where we write keyIDs and and other stuff so that the
pointers can actually point to somewhere */
if (blobtype == BLOBTYPE_PGP)
{
/* We need to store the keyids for all pgp v3 keys because those key
IDs are not part of the fingerprint. While we are doing that, we
fixup all the keyID offsets */
for (i=0; i < blob->nkeys; i++ )
{
if (blob->keys[i].off_kid)
{ /* this is a v3 one */
add_fixup (blob, blob->keys[i].off_kid_addr, a->len);
write_stored_kid (blob, blob->keys[i].off_kid);
}
else
{ /* the better v4 key IDs - just store an offset 8 bytes back */
add_fixup (blob, blob->keys[i].off_kid_addr,
blob->keys[i].off_kid_addr - 8);
}
}
}
if (blobtype == BLOBTYPE_X509)
{
/* We don't want to point to ASN.1 encoded UserIDs (DNs) but to
the utf-8 string represenation of them */
for (i=0; i < blob->nuids; i++ )
{
if (blob->uids[i].name)
{ /* this is a v3 one */
add_fixup (blob, blob->uids[i].off_addr, a->len);
put_membuf (blob->buf, blob->uids[i].name, blob->uids[i].len);
}
}
}
return 0;
}
static int
create_blob_trailer (KEYBOXBLOB blob)
{
(void)blob;
return 0;
}
static int
create_blob_finish (KEYBOXBLOB blob)
{
struct membuf *a = blob->buf;
unsigned char *p;
unsigned char *pp;
int i;
size_t n;
/* write a placeholder for the checksum */
for (i = 0; i < 16; i++ )
put32 (a, 0); /* Hmmm: why put32() ?? */
/* get the memory area */
n = 0; /* (Just to avoid compiler warning.) */
p = get_membuf (a, &n);
if (!p)
return gpg_error (GPG_ERR_ENOMEM);
assert (n >= 20);
/* fixup the length */
add_fixup (blob, 0, n);
/* do the fixups */
if (blob->fixup_out_of_core)
return gpg_error (GPG_ERR_ENOMEM);
{
struct fixup_list *fl;
for (fl = blob->fixups; fl; fl = fl->next)
{
assert (fl->off+4 <= n);
p[fl->off+0] = fl->val >> 24;
p[fl->off+1] = fl->val >> 16;
p[fl->off+2] = fl->val >> 8;
p[fl->off+3] = fl->val;
}
}
/* calculate and store the MD5 checksum */
gcry_md_hash_buffer (GCRY_MD_MD5, p + n - 16, p, n - 16);
pp = xtrymalloc (n);
if ( !pp )
return gpg_error_from_syserror ();
memcpy (pp , p, n);
blob->blob = pp;
blob->bloblen = n;
return 0;
}
-#ifdef KEYBOX_WITH_OPENPGP
-
-int
-_keybox_create_pgp_blob (KEYBOXBLOB *r_blob, KBNODE keyblock, int as_ephemeral)
+gpg_error_t
+_keybox_create_openpgp_blob (KEYBOXBLOB *r_blob,
+ keybox_openpgp_info_t info,
+ const unsigned char *image,
+ size_t imagelen,
+ int as_ephemeral)
{
- int rc = 0;
- KBNODE node;
+ gpg_error_t err;
KEYBOXBLOB blob;
*r_blob = NULL;
+
+ if (!info->nuids || !info->nsigs)
+ return gpg_error (GPG_ERR_BAD_PUBKEY);
+
blob = xtrycalloc (1, sizeof *blob);
if (!blob)
return gpg_error_from_syserror ();
- /* fixme: Do some sanity checks on the keyblock */
-
- /* count userids and keys so that we can allocate the arrays */
- for (node = keyblock; node; node = node->next)
+ blob->nkeys = 1 + info->nsubkeys;
+ blob->keys = xtrycalloc (blob->nkeys, sizeof *blob->keys );
+ if (!blob->keys)
{
- switch (node->pkt->pkttype)
- {
- case PKT_PUBLIC_KEY:
- case PKT_SECRET_KEY:
- case PKT_PUBLIC_SUBKEY:
- case PKT_SECRET_SUBKEY: blob->nkeys++; break;
- case PKT_USER_ID: blob->nuids++; break;
- case PKT_SIGNATURE: blob->nsigs++; break;
- default: break;
- }
+ err = gpg_error_from_syserror ();
+ goto leave;
}
-
- blob->keys = xtrycalloc (blob->nkeys, sizeof *blob->keys );
+ blob->nuids = info->nuids;
blob->uids = xtrycalloc (blob->nuids, sizeof *blob->uids );
+ if (!blob->uids)
+ {
+ err = gpg_error_from_syserror ();
+ goto leave;
+ }
+ blob->nsigs = info->nsigs;
blob->sigs = xtrycalloc (blob->nsigs, sizeof *blob->sigs );
- if (!blob->keys || !blob->uids || !blob->sigs)
+ if (!blob->sigs)
{
- rc = gpg_error (GPG_ERR_ENOMEM);
+ err = gpg_error_from_syserror ();
goto leave;
}
- rc = pgp_create_key_part ( blob, keyblock );
- if (rc)
- goto leave;
- rc = pgp_create_uid_part ( blob, keyblock );
- if (rc)
- goto leave;
- rc = pgp_create_sig_part ( blob, keyblock );
- if (rc)
+ err = pgp_create_key_part (blob, info);
+ if (err)
goto leave;
+ pgp_create_uid_part (blob, info);
+ pgp_create_sig_part (blob);
init_membuf (&blob->bufbuf, 1024);
blob->buf = &blob->bufbuf;
- rc = create_blob_header (blob, BLOBTYPE_OPENPGP, as_ephemeral);
- if (rc)
+ err = create_blob_header (blob, BLOBTYPE_PGP, as_ephemeral);
+ if (err)
goto leave;
- rc = pgp_create_blob_keyblock (blob, keyblock);
- if (rc)
+ err = pgp_create_blob_keyblock (blob, image, imagelen);
+ if (err)
goto leave;
- rc = create_blob_trailer (blob);
- if (rc)
+ err = create_blob_trailer (blob);
+ if (err)
goto leave;
- rc = create_blob_finish ( blob );
- if (rc)
+ err = create_blob_finish (blob);
+ if (err)
goto leave;
-
leave:
release_kid_list (blob->temp_kids);
blob->temp_kids = NULL;
- if (rc)
- {
- keybox_release_blob (blob);
- *r_blob = NULL;
- }
+ if (err)
+ _keybox_release_blob (blob);
else
- {
- *r_blob = blob;
- }
- return rc;
+ *r_blob = blob;
+ return err;
}
-#endif /*KEYBOX_WITH_OPENPGP*/
+
#ifdef KEYBOX_WITH_X509
/* Return an allocated string with the email address extracted from a
DN. Note hat we use this code also in ../sm/keylist.c. */
static char *
x509_email_kludge (const char *name)
{
const char *p, *string;
unsigned char *buf;
int n;
string = name;
for (;;)
{
p = strstr (string, "1.2.840.113549.1.9.1=#");
if (!p)
return NULL;
if (p == name || (p > string+1 && p[-1] == ',' && p[-2] != '\\'))
{
name = p + 22;
break;
}
string = p + 22;
}
/* This looks pretty much like an email address in the subject's DN
we use this to add an additional user ID entry. This way,
OpenSSL generated keys get a nicer and usable listing. */
for (n=0, p=name; hexdigitp (p) && hexdigitp (p+1); p +=2, n++)
;
if (!n)
return NULL;
buf = xtrymalloc (n+3);
if (!buf)
return NULL; /* oops, out of core */
*buf = '<';
for (n=1, p=name; hexdigitp (p); p +=2, n++)
buf[n] = xtoi_2 (p);
buf[n++] = '>';
buf[n] = 0;
return (char*)buf;
}
/* Note: We should move calculation of the digest into libksba and
remove that parameter */
int
_keybox_create_x509_blob (KEYBOXBLOB *r_blob, ksba_cert_t cert,
unsigned char *sha1_digest, int as_ephemeral)
{
int i, rc = 0;
KEYBOXBLOB blob;
unsigned char *sn;
char *p;
char **names = NULL;
size_t max_names;
*r_blob = NULL;
blob = xtrycalloc (1, sizeof *blob);
if( !blob )
return gpg_error_from_syserror ();
sn = ksba_cert_get_serial (cert);
if (sn)
{
size_t n, len;
n = gcry_sexp_canon_len (sn, 0, NULL, NULL);
if (n < 2)
{
xfree (sn);
return gpg_error (GPG_ERR_GENERAL);
}
blob->serialbuf = sn;
sn++; n--; /* skip '(' */
for (len=0; n && *sn && *sn != ':' && digitp (sn); n--, sn++)
len = len*10 + atoi_1 (sn);
if (*sn != ':')
{
xfree (blob->serialbuf);
blob->serialbuf = NULL;
return gpg_error (GPG_ERR_GENERAL);
}
sn++;
blob->serial = sn;
blob->seriallen = len;
}
blob->nkeys = 1;
/* create list of names */
blob->nuids = 0;
max_names = 100;
names = xtrymalloc (max_names * sizeof *names);
if (!names)
{
rc = gpg_error_from_syserror ();
goto leave;
}
p = ksba_cert_get_issuer (cert, 0);
if (!p)
{
rc = gpg_error (GPG_ERR_MISSING_VALUE);
goto leave;
}
names[blob->nuids++] = p;
for (i=0; (p = ksba_cert_get_subject (cert, i)); i++)
{
if (blob->nuids >= max_names)
{
char **tmp;
max_names += 100;
tmp = xtryrealloc (names, max_names * sizeof *names);
if (!tmp)
{
rc = gpg_error_from_syserror ();
goto leave;
}
names = tmp;
}
names[blob->nuids++] = p;
if (!i && (p=x509_email_kludge (p)))
names[blob->nuids++] = p; /* due to !i we don't need to check bounds*/
}
/* space for signature information */
blob->nsigs = 1;
blob->keys = xtrycalloc (blob->nkeys, sizeof *blob->keys );
blob->uids = xtrycalloc (blob->nuids, sizeof *blob->uids );
blob->sigs = xtrycalloc (blob->nsigs, sizeof *blob->sigs );
if (!blob->keys || !blob->uids || !blob->sigs)
{
rc = gpg_error (GPG_ERR_ENOMEM);
goto leave;
}
memcpy (blob->keys[0].fpr, sha1_digest, 20);
blob->keys[0].off_kid = 0; /* We don't have keyids */
blob->keys[0].flags = 0;
/* issuer and subject names */
for (i=0; i < blob->nuids; i++)
{
blob->uids[i].name = names[i];
blob->uids[i].len = strlen(names[i]);
names[i] = NULL;
blob->uids[i].flags = 0;
blob->uids[i].validity = 0;
}
xfree (names);
names = NULL;
/* signatures */
blob->sigs[0] = 0; /* not yet checked */
/* Create a temporary buffer for further processing */
init_membuf (&blob->bufbuf, 1024);
blob->buf = &blob->bufbuf;
/* write out what we already have */
rc = create_blob_header (blob, BLOBTYPE_X509, as_ephemeral);
if (rc)
goto leave;
rc = x509_create_blob_cert (blob, cert);
if (rc)
goto leave;
rc = create_blob_trailer (blob);
if (rc)
goto leave;
rc = create_blob_finish ( blob );
if (rc)
goto leave;
leave:
release_kid_list (blob->temp_kids);
blob->temp_kids = NULL;
if (blob && names)
{
for (i=0; i < blob->nuids; i++)
xfree (names[i]);
}
xfree (names);
if (rc)
{
_keybox_release_blob (blob);
*r_blob = NULL;
}
else
{
*r_blob = blob;
}
return rc;
}
#endif /*KEYBOX_WITH_X509*/
int
_keybox_new_blob (KEYBOXBLOB *r_blob,
unsigned char *image, size_t imagelen, off_t off)
{
KEYBOXBLOB blob;
*r_blob = NULL;
blob = xtrycalloc (1, sizeof *blob);
if (!blob)
return gpg_error_from_syserror ();
blob->blob = image;
blob->bloblen = imagelen;
blob->fileoffset = off;
*r_blob = blob;
return 0;
}
void
_keybox_release_blob (KEYBOXBLOB blob)
{
int i;
if (!blob)
return;
/* hmmm: release membuf here?*/
xfree (blob->keys );
xfree (blob->serialbuf);
for (i=0; i < blob->nuids; i++)
xfree (blob->uids[i].name);
xfree (blob->uids );
xfree (blob->sigs );
xfree (blob->blob );
xfree (blob );
}
const unsigned char *
_keybox_get_blob_image ( KEYBOXBLOB blob, size_t *n )
{
*n = blob->bloblen;
return blob->blob;
}
off_t
_keybox_get_blob_fileoffset (KEYBOXBLOB blob)
{
return blob->fileoffset;
}
void
_keybox_update_header_blob (KEYBOXBLOB blob)
{
if (blob->bloblen >= 32 && blob->blob[4] == BLOBTYPE_HEADER)
{
u32 val = make_timestamp ();
/* Update the last maintenance run times tamp. */
blob->blob[20] = (val >> 24);
blob->blob[20+1] = (val >> 16);
blob->blob[20+2] = (val >> 8);
blob->blob[20+3] = (val );
}
}
diff --git a/kbx/keybox-defs.h b/kbx/keybox-defs.h
index c58801638..8fdc54d61 100644
--- a/kbx/keybox-defs.h
+++ b/kbx/keybox-defs.h
@@ -1,262 +1,264 @@
/* keybox-defs.h - interal Keybox defintions
* Copyright (C) 2001, 2004 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
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef KEYBOX_DEFS_H
#define KEYBOX_DEFS_H 1
#ifdef GPG_ERR_SOURCE_DEFAULT
# if GPG_ERR_SOURCE_DEFAULT != GPG_ERR_SOURCE_KEYBOX
# error GPG_ERR_SOURCE_DEFAULT already defined
# endif
#else
# define GPG_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_KEYBOX
#endif
#include <gpg-error.h>
#define map_assuan_err(a) \
map_assuan_err_with_source (GPG_ERR_SOURCE_DEFAULT, (a))
#include <sys/types.h> /* off_t */
/* We include the type defintions from jnlib instead of defining our
owns here. This will not allow us build KBX in a standalone way
but there is currently no need for it anyway. Same goes for
stringhelp.h which for example provides a replacement for stpcpy -
fixme: Better use the LIBOBJ mechnism. */
#include "../common/types.h"
#include "../common/stringhelp.h"
#include "keybox.h"
enum {
BLOBTYPE_EMPTY = 0,
BLOBTYPE_HEADER = 1,
BLOBTYPE_PGP = 2,
BLOBTYPE_X509 = 3
};
typedef struct keyboxblob *KEYBOXBLOB;
typedef struct keybox_name *KB_NAME;
typedef struct keybox_name const *CONST_KB_NAME;
struct keybox_name
{
/* Link to the next resources, so that we can walk all
resources. */
KB_NAME next;
/* True if this is a keybox with secret keys. */
int secret;
/*DOTLOCK lockhd;*/
/* A table with all the handles accessing this resources.
HANDLE_TABLE_SIZE gives the allocated length of this table unused
entrues are set to NULL. HANDLE_TABLE may be NULL. */
KEYBOX_HANDLE *handle_table;
size_t handle_table_size;
/* Not yet used. */
int is_locked;
/* Not yet used. */
int did_full_scan;
/* The name of the resource file. */
char fname[1];
};
struct keybox_handle {
CONST_KB_NAME kb;
int secret; /* this is for a secret keybox */
FILE *fp;
int eof;
int error;
int ephemeral;
struct {
KEYBOXBLOB blob;
off_t offset;
size_t pk_no;
size_t uid_no;
unsigned int n_packets; /*used for delete and update*/
} found;
struct {
char *name;
char *pattern;
} word_match;
};
/* Openpgp helper structures. */
struct _keybox_openpgp_key_info
{
struct _keybox_openpgp_key_info *next;
int algo;
unsigned char keyid[8];
int fprlen; /* Either 16 or 20 */
unsigned char fpr[20];
};
struct _keybox_openpgp_uid_info
{
struct _keybox_openpgp_uid_info *next;
size_t off;
size_t len;
};
struct _keybox_openpgp_info
{
int is_secret; /* True if this is a secret key. */
unsigned int nsubkeys;/* Total number of subkeys. */
unsigned int nuids; /* Total number of user IDs in the keyblock. */
unsigned int nsigs; /* Total number of signatures in the keyblock. */
/* Note, we use 2 structs here to better cope with the most common
use of having one primary and one subkey - this allows us to
statically allocate this structure and only malloc stuff for more
than one subkey. */
struct _keybox_openpgp_key_info primary;
struct _keybox_openpgp_key_info subkeys;
struct _keybox_openpgp_uid_info uids;
};
typedef struct _keybox_openpgp_info *keybox_openpgp_info_t;
/* Don't know whether this is needed: */
/* static struct { */
/* const char *homedir; */
/* int dry_run; */
/* int quiet; */
/* int verbose; */
/* int preserve_permissions; */
/* } keybox_opt; */
/*-- keybox-init.c --*/
void _keybox_close_file (KEYBOX_HANDLE hd);
/*-- keybox-blob.c --*/
-#ifdef KEYBOX_WITH_OPENPGP
- /* fixme */
-#endif /*KEYBOX_WITH_OPENPGP*/
+gpg_error_t _keybox_create_openpgp_blob (KEYBOXBLOB *r_blob,
+ keybox_openpgp_info_t info,
+ const unsigned char *image,
+ size_t imagelen,
+ int as_ephemeral);
#ifdef KEYBOX_WITH_X509
int _keybox_create_x509_blob (KEYBOXBLOB *r_blob, ksba_cert_t cert,
unsigned char *sha1_digest, int as_ephemeral);
#endif /*KEYBOX_WITH_X509*/
int _keybox_new_blob (KEYBOXBLOB *r_blob,
unsigned char *image, size_t imagelen,
off_t off);
void _keybox_release_blob (KEYBOXBLOB blob);
const unsigned char *_keybox_get_blob_image (KEYBOXBLOB blob, size_t *n);
off_t _keybox_get_blob_fileoffset (KEYBOXBLOB blob);
void _keybox_update_header_blob (KEYBOXBLOB blob);
/*-- keybox-openpgp.c --*/
gpg_error_t _keybox_parse_openpgp (const unsigned char *image, size_t imagelen,
size_t *nparsed,
keybox_openpgp_info_t info);
void _keybox_destroy_openpgp_info (keybox_openpgp_info_t info);
/*-- keybox-file.c --*/
int _keybox_read_blob (KEYBOXBLOB *r_blob, FILE *fp);
int _keybox_read_blob2 (KEYBOXBLOB *r_blob, FILE *fp, int *skipped_deleted);
int _keybox_write_blob (KEYBOXBLOB blob, FILE *fp);
/*-- keybox-search.c --*/
gpg_err_code_t _keybox_get_flag_location (const unsigned char *buffer,
size_t length,
int what,
size_t *flag_off, size_t *flag_size);
/*-- keybox-dump.c --*/
int _keybox_dump_blob (KEYBOXBLOB blob, FILE *fp);
int _keybox_dump_file (const char *filename, int stats_only, FILE *outfp);
int _keybox_dump_find_dups (const char *filename, int print_them, FILE *outfp);
int _keybox_dump_cut_records (const char *filename, unsigned long from,
unsigned long to, FILE *outfp);
/*-- keybox-util.c --*/
void *_keybox_malloc (size_t n);
void *_keybox_calloc (size_t n, size_t m);
void *_keybox_realloc (void *p, size_t n);
void _keybox_free (void *p);
#define xtrymalloc(a) _keybox_malloc ((a))
#define xtrycalloc(a,b) _keybox_calloc ((a),(b))
#define xtryrealloc(a,b) _keybox_realloc((a),(b))
#define xfree(a) _keybox_free ((a))
#define DIM(v) (sizeof(v)/sizeof((v)[0]))
#define DIMof(type,member) DIM(((type *)0)->member)
#ifndef STR
# define STR(v) #v
#endif
#define STR2(v) STR(v)
/*
a couple of handy macros
*/
#define return_if_fail(expr) do { \
if (!(expr)) { \
fprintf (stderr, "%s:%d: assertion '%s' failed\n", \
__FILE__, __LINE__, #expr ); \
return; \
} } while (0)
#define return_null_if_fail(expr) do { \
if (!(expr)) { \
fprintf (stderr, "%s:%d: assertion '%s' failed\n", \
__FILE__, __LINE__, #expr ); \
return NULL; \
} } while (0)
#define return_val_if_fail(expr,val) do { \
if (!(expr)) { \
fprintf (stderr, "%s:%d: assertion '%s' failed\n", \
__FILE__, __LINE__, #expr ); \
return (val); \
} } while (0)
#define never_reached() do { \
fprintf (stderr, "%s:%d: oops; should never get here\n", \
__FILE__, __LINE__ ); \
} while (0)
/* some macros to replace ctype ones and avoid locale problems */
#define digitp(p) (*(p) >= '0' && *(p) <= '9')
#define hexdigitp(a) (digitp (a) \
|| (*(a) >= 'A' && *(a) <= 'F') \
|| (*(a) >= 'a' && *(a) <= 'f'))
/* the atoi macros assume that the buffer has only valid digits */
#define atoi_1(p) (*(p) - '0' )
#define atoi_2(p) ((atoi_1(p) * 10) + atoi_1((p)+1))
#define atoi_4(p) ((atoi_2(p) * 100) + atoi_2((p)+2))
#define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \
*(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10))
#define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1))
#endif /*KEYBOX_DEFS_H*/
diff --git a/kbx/keybox-file.c b/kbx/keybox-file.c
index ecfdfbe84..027bcf8d7 100644
--- a/kbx/keybox-file.c
+++ b/kbx/keybox-file.c
@@ -1,161 +1,161 @@
/* keybox-file.c - File operations
* Copyright (C) 2001, 2003 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
* 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 <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include "keybox-defs.h"
#if !defined(HAVE_FTELLO) && !defined(ftello)
static off_t
ftello (FILE *stream)
{
long int off;
off = ftell (stream);
if (off == -1)
return (off_t)-1;
return off;
}
#endif /* !defined(HAVE_FTELLO) && !defined(ftello) */
/* Read a block at the current postion and return it in r_blob.
r_blob may be NULL to simply skip the current block */
int
_keybox_read_blob2 (KEYBOXBLOB *r_blob, FILE *fp, int *skipped_deleted)
{
unsigned char *image;
size_t imagelen = 0;
int c1, c2, c3, c4, type;
int rc;
off_t off;
*skipped_deleted = 0;
again:
*r_blob = NULL;
off = ftello (fp);
if (off == (off_t)-1)
return gpg_error_from_syserror ();
if ((c1 = getc (fp)) == EOF
|| (c2 = getc (fp)) == EOF
|| (c3 = getc (fp)) == EOF
|| (c4 = getc (fp)) == EOF
|| (type = getc (fp)) == EOF)
{
if ( c1 == EOF && !ferror (fp) )
return -1; /* eof */
if (!ferror (fp))
return gpg_error (GPG_ERR_TOO_SHORT);
return gpg_error_from_syserror ();
}
imagelen = (c1 << 24) | (c2 << 16) | (c3 << 8 ) | c4;
- if (imagelen > 500000) /* Sanity check. */
+ if (imagelen > 1000000) /* Sanity check. */
return gpg_error (GPG_ERR_TOO_LARGE);
if (imagelen < 5)
return gpg_error (GPG_ERR_TOO_SHORT);
if (!type)
{
/* Special treatment for empty blobs. */
if (fseek (fp, imagelen-5, SEEK_CUR))
return gpg_error_from_syserror ();
*skipped_deleted = 1;
goto again;
}
image = xtrymalloc (imagelen);
if (!image)
return gpg_error_from_syserror ();
image[0] = c1; image[1] = c2; image[2] = c3; image[3] = c4; image[4] = type;
if (fread (image+5, imagelen-5, 1, fp) != 1)
{
gpg_error_t tmperr = gpg_error_from_syserror ();
xfree (image);
return tmperr;
}
rc = r_blob? _keybox_new_blob (r_blob, image, imagelen, off) : 0;
if (rc || !r_blob)
xfree (image);
return rc;
}
int
_keybox_read_blob (KEYBOXBLOB *r_blob, FILE *fp)
{
int dummy;
return _keybox_read_blob2 (r_blob, fp, &dummy);
}
/* Write the block to the current file position */
int
_keybox_write_blob (KEYBOXBLOB blob, FILE *fp)
{
const unsigned char *image;
size_t length;
image = _keybox_get_blob_image (blob, &length);
if (fwrite (image, length, 1, fp) != 1)
return gpg_error_from_syserror ();
return 0;
}
/* Write a fresh header type blob. */
int
_keybox_write_header_blob (FILE *fp)
{
unsigned char image[32];
u32 val;
memset (image, 0, sizeof image);
/* Length of this blob. */
image[3] = 32;
image[4] = BLOBTYPE_HEADER;
image[5] = 1; /* Version */
memcpy (image+8, "KBXf", 4);
val = time (NULL);
/* created_at and last maintenance run. */
image[16] = (val >> 24);
image[16+1] = (val >> 16);
image[16+2] = (val >> 8);
image[16+3] = (val );
image[20] = (val >> 24);
image[20+1] = (val >> 16);
image[20+2] = (val >> 8);
image[20+3] = (val );
if (fwrite (image, 32, 1, fp) != 1)
return gpg_error_from_syserror ();
return 0;
}
diff --git a/kbx/keybox-search.c b/kbx/keybox-search.c
index ef5cd953e..1e36be968 100644
--- a/kbx/keybox-search.c
+++ b/kbx/keybox-search.c
@@ -1,1044 +1,1078 @@
/* keybox-search.c - Search operations
- * Copyright (C) 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
+ * Copyright (C) 2001, 2002, 2003, 2004, 2012 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
* 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 <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "../common/stringhelp.h" /* ascii_xxxx() */
#include "keybox-defs.h"
#include <gcrypt.h>
#define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \
*(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10))
#define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1))
struct sn_array_s {
int snlen;
unsigned char *sn;
};
static inline ulong
get32 (const byte *buffer)
{
ulong a;
a = *buffer << 24;
a |= buffer[1] << 16;
a |= buffer[2] << 8;
a |= buffer[3];
return a;
}
static inline ulong
get16 (const byte *buffer)
{
ulong a;
a = *buffer << 8;
a |= buffer[1];
return a;
}
static inline int
blob_get_type (KEYBOXBLOB blob)
{
const unsigned char *buffer;
size_t length;
buffer = _keybox_get_blob_image (blob, &length);
if (length < 32)
return -1; /* blob too short */
return buffer[4];
}
static inline unsigned int
blob_get_blob_flags (KEYBOXBLOB blob)
{
const unsigned char *buffer;
size_t length;
buffer = _keybox_get_blob_image (blob, &length);
if (length < 8)
return 0; /* oops */
return get16 (buffer + 6);
}
/* Return information on the flag WHAT within the blob BUFFER,LENGTH.
Return the offset and the length (in bytes) of the flag in
FLAGOFF,FLAG_SIZE. */
gpg_err_code_t
_keybox_get_flag_location (const unsigned char *buffer, size_t length,
int what, size_t *flag_off, size_t *flag_size)
{
size_t pos;
size_t nkeys, keyinfolen;
size_t nuids, uidinfolen;
size_t nserial;
size_t nsigs, siginfolen;
switch (what)
{
case KEYBOX_FLAG_BLOB:
if (length < 8)
return GPG_ERR_INV_OBJ;
*flag_off = 6;
*flag_size = 2;
break;
case KEYBOX_FLAG_OWNERTRUST:
case KEYBOX_FLAG_VALIDITY:
case KEYBOX_FLAG_CREATED_AT:
if (length < 20)
return GPG_ERR_INV_OBJ;
/* Key info. */
nkeys = get16 (buffer + 16);
keyinfolen = get16 (buffer + 18 );
if (keyinfolen < 28)
return GPG_ERR_INV_OBJ;
pos = 20 + keyinfolen*nkeys;
if (pos+2 > length)
return GPG_ERR_INV_OBJ; /* Out of bounds. */
/* Serial number. */
nserial = get16 (buffer+pos);
pos += 2 + nserial;
if (pos+4 > length)
return GPG_ERR_INV_OBJ; /* Out of bounds. */
/* User IDs. */
nuids = get16 (buffer + pos); pos += 2;
uidinfolen = get16 (buffer + pos); pos += 2;
if (uidinfolen < 12 )
return GPG_ERR_INV_OBJ;
pos += uidinfolen*nuids;
if (pos+4 > length)
return GPG_ERR_INV_OBJ ; /* Out of bounds. */
/* Signature info. */
nsigs = get16 (buffer + pos); pos += 2;
siginfolen = get16 (buffer + pos); pos += 2;
if (siginfolen < 4 )
return GPG_ERR_INV_OBJ;
pos += siginfolen*nsigs;
if (pos+1+1+2+4+4+4+4 > length)
return GPG_ERR_INV_OBJ ; /* Out of bounds. */
*flag_size = 1;
*flag_off = pos;
switch (what)
{
case KEYBOX_FLAG_VALIDITY:
*flag_off += 1;
break;
case KEYBOX_FLAG_CREATED_AT:
*flag_size = 4;
*flag_off += 1+2+4+4+4;
break;
default:
break;
}
break;
default:
return GPG_ERR_INV_FLAG;
}
return 0;
}
/* Return one of the flags WHAT in VALUE from teh blob BUFFER of
LENGTH bytes. Return 0 on success or an raw error code. */
static gpg_err_code_t
get_flag_from_image (const unsigned char *buffer, size_t length,
int what, unsigned int *value)
{
gpg_err_code_t ec;
size_t pos, size;
*value = 0;
ec = _keybox_get_flag_location (buffer, length, what, &pos, &size);
if (!ec)
switch (size)
{
case 1: *value = buffer[pos]; break;
case 2: *value = get16 (buffer + pos); break;
case 4: *value = get32 (buffer + pos); break;
default: ec = GPG_ERR_BUG; break;
}
return ec;
}
static int
blob_cmp_sn (KEYBOXBLOB blob, const unsigned char *sn, int snlen)
{
const unsigned char *buffer;
size_t length;
size_t pos, off;
size_t nkeys, keyinfolen;
size_t nserial;
buffer = _keybox_get_blob_image (blob, &length);
if (length < 40)
return 0; /* blob too short */
/*keys*/
nkeys = get16 (buffer + 16);
keyinfolen = get16 (buffer + 18 );
if (keyinfolen < 28)
return 0; /* invalid blob */
pos = 20 + keyinfolen*nkeys;
if (pos+2 > length)
return 0; /* out of bounds */
/*serial*/
nserial = get16 (buffer+pos);
off = pos + 2;
if (off+nserial > length)
return 0; /* out of bounds */
return nserial == snlen && !memcmp (buffer+off, sn, snlen);
}
static int
blob_cmp_fpr (KEYBOXBLOB blob, const unsigned char *fpr)
{
const unsigned char *buffer;
size_t length;
size_t pos, off;
size_t nkeys, keyinfolen;
int idx;
buffer = _keybox_get_blob_image (blob, &length);
if (length < 40)
return 0; /* blob too short */
/*keys*/
nkeys = get16 (buffer + 16);
keyinfolen = get16 (buffer + 18 );
if (keyinfolen < 28)
return 0; /* invalid blob */
pos = 20;
if (pos + keyinfolen*nkeys > length)
return 0; /* out of bounds */
for (idx=0; idx < nkeys; idx++)
{
off = pos + idx*keyinfolen;
if (!memcmp (buffer + off, fpr, 20))
return 1; /* found */
}
return 0; /* not found */
}
static int
blob_cmp_fpr_part (KEYBOXBLOB blob, const unsigned char *fpr,
int fproff, int fprlen)
{
const unsigned char *buffer;
size_t length;
size_t pos, off;
size_t nkeys, keyinfolen;
int idx;
buffer = _keybox_get_blob_image (blob, &length);
if (length < 40)
return 0; /* blob too short */
/*keys*/
nkeys = get16 (buffer + 16);
keyinfolen = get16 (buffer + 18 );
if (keyinfolen < 28)
return 0; /* invalid blob */
pos = 20;
if (pos + keyinfolen*nkeys > length)
return 0; /* out of bounds */
for (idx=0; idx < nkeys; idx++)
{
off = pos + idx*keyinfolen;
if (!memcmp (buffer + off + fproff, fpr, fprlen))
return 1; /* found */
}
return 0; /* not found */
}
static int
blob_cmp_name (KEYBOXBLOB blob, int idx,
const char *name, size_t namelen, int substr)
{
const unsigned char *buffer;
size_t length;
size_t pos, off, len;
size_t nkeys, keyinfolen;
size_t nuids, uidinfolen;
size_t nserial;
buffer = _keybox_get_blob_image (blob, &length);
if (length < 40)
return 0; /* blob too short */
/*keys*/
nkeys = get16 (buffer + 16);
keyinfolen = get16 (buffer + 18 );
if (keyinfolen < 28)
return 0; /* invalid blob */
pos = 20 + keyinfolen*nkeys;
if (pos+2 > length)
return 0; /* out of bounds */
/*serial*/
nserial = get16 (buffer+pos);
pos += 2 + nserial;
if (pos+4 > length)
return 0; /* out of bounds */
/* user ids*/
nuids = get16 (buffer + pos); pos += 2;
uidinfolen = get16 (buffer + pos); pos += 2;
if (uidinfolen < 12 /* should add a: || nuidinfolen > MAX_UIDINFOLEN */)
return 0; /* invalid blob */
if (pos + uidinfolen*nuids > length)
return 0; /* out of bounds */
if (idx < 0)
{ /* compare all names starting with that (negated) index */
idx = -idx;
for ( ;idx < nuids; idx++)
{
size_t mypos = pos;
mypos += idx*uidinfolen;
off = get32 (buffer+mypos);
len = get32 (buffer+mypos+4);
if (off+len > length)
return 0; /* error: better stop here out of bounds */
if (len < 1)
continue; /* empty name */
if (substr)
{
if (ascii_memcasemem (buffer+off, len, name, namelen))
return 1; /* found */
}
else
{
if (len == namelen && !memcmp (buffer+off, name, len))
return 1; /* found */
}
}
return 0; /* not found */
}
else
{
if (idx > nuids)
return 0; /* no user ID with that idx */
pos += idx*uidinfolen;
off = get32 (buffer+pos);
len = get32 (buffer+pos+4);
if (off+len > length)
return 0; /* out of bounds */
if (len < 1)
return 0; /* empty name */
if (substr)
{
return !!ascii_memcasemem (buffer+off, len, name, namelen);
}
else
{
return len == namelen && !memcmp (buffer+off, name, len);
}
}
}
/* compare all email addresses of the subject. With SUBSTR given as
True a substring search is done in the mail address */
static int
blob_cmp_mail (KEYBOXBLOB blob, const char *name, size_t namelen, int substr)
{
const unsigned char *buffer;
size_t length;
size_t pos, off, len;
size_t nkeys, keyinfolen;
size_t nuids, uidinfolen;
size_t nserial;
int idx;
/* fixme: this code is common to blob_cmp_mail */
buffer = _keybox_get_blob_image (blob, &length);
if (length < 40)
return 0; /* blob too short */
/*keys*/
nkeys = get16 (buffer + 16);
keyinfolen = get16 (buffer + 18 );
if (keyinfolen < 28)
return 0; /* invalid blob */
pos = 20 + keyinfolen*nkeys;
if (pos+2 > length)
return 0; /* out of bounds */
/*serial*/
nserial = get16 (buffer+pos);
pos += 2 + nserial;
if (pos+4 > length)
return 0; /* out of bounds */
/* user ids*/
nuids = get16 (buffer + pos); pos += 2;
uidinfolen = get16 (buffer + pos); pos += 2;
if (uidinfolen < 12 /* should add a: || nuidinfolen > MAX_UIDINFOLEN */)
return 0; /* invalid blob */
if (pos + uidinfolen*nuids > length)
return 0; /* out of bounds */
if (namelen < 1)
return 0;
for (idx=1 ;idx < nuids; idx++)
{
size_t mypos = pos;
mypos += idx*uidinfolen;
off = get32 (buffer+mypos);
len = get32 (buffer+mypos+4);
if (off+len > length)
return 0; /* error: better stop here out of bounds */
if (len < 2 || buffer[off] != '<')
continue; /* empty name or trailing 0 not stored */
len--; /* one back */
if ( len < 3 || buffer[off+len] != '>')
continue; /* not a proper email address */
len--;
if (substr)
{
if (ascii_memcasemem (buffer+off+1, len, name, namelen))
return 1; /* found */
}
else
{
if (len == namelen && !ascii_memcasecmp (buffer+off+1, name, len))
return 1; /* found */
}
}
return 0; /* not found */
}
#ifdef KEYBOX_WITH_X509
/* Return true if the key in BLOB matches the 20 bytes keygrip GRIP.
We don't have the keygrips as meta data, thus we need to parse the
certificate. Fixme: We might want to return proper error codes
instead of failing a search for invalid certificates etc. */
static int
blob_x509_has_grip (KEYBOXBLOB blob, const unsigned char *grip)
{
int rc;
const unsigned char *buffer;
size_t length;
size_t cert_off, cert_len;
ksba_reader_t reader = NULL;
ksba_cert_t cert = NULL;
ksba_sexp_t p = NULL;
gcry_sexp_t s_pkey;
unsigned char array[20];
unsigned char *rcp;
size_t n;
buffer = _keybox_get_blob_image (blob, &length);
if (length < 40)
return 0; /* Too short. */
cert_off = get32 (buffer+8);
cert_len = get32 (buffer+12);
if (cert_off+cert_len > length)
return 0; /* Too short. */
rc = ksba_reader_new (&reader);
if (rc)
return 0; /* Problem with ksba. */
rc = ksba_reader_set_mem (reader, buffer+cert_off, cert_len);
if (rc)
goto failed;
rc = ksba_cert_new (&cert);
if (rc)
goto failed;
rc = ksba_cert_read_der (cert, reader);
if (rc)
goto failed;
p = ksba_cert_get_public_key (cert);
if (!p)
goto failed;
n = gcry_sexp_canon_len (p, 0, NULL, NULL);
if (!n)
goto failed;
rc = gcry_sexp_sscan (&s_pkey, NULL, (char*)p, n);
if (rc)
{
gcry_sexp_release (s_pkey);
goto failed;
}
rcp = gcry_pk_get_keygrip (s_pkey, array);
gcry_sexp_release (s_pkey);
if (!rcp)
goto failed; /* Can't calculate keygrip. */
xfree (p);
ksba_cert_release (cert);
ksba_reader_release (reader);
return !memcmp (array, grip, 20);
failed:
xfree (p);
ksba_cert_release (cert);
ksba_reader_release (reader);
return 0;
}
#endif /*KEYBOX_WITH_X509*/
/*
The has_foo functions are used as helpers for search
*/
static inline int
has_short_kid (KEYBOXBLOB blob, u32 lkid)
{
unsigned char buf[4];
buf[0] = lkid >> 24;
buf[1] = lkid >> 16;
buf[2] = lkid >> 8;
buf[3] = lkid;
return blob_cmp_fpr_part (blob, buf, 16, 4);
}
static inline int
has_long_kid (KEYBOXBLOB blob, u32 mkid, u32 lkid)
{
unsigned char buf[8];
buf[0] = mkid >> 24;
buf[1] = mkid >> 16;
buf[2] = mkid >> 8;
buf[3] = mkid;
buf[4] = lkid >> 24;
buf[5] = lkid >> 16;
buf[6] = lkid >> 8;
buf[7] = lkid;
return blob_cmp_fpr_part (blob, buf, 12, 8);
}
static inline int
has_fingerprint (KEYBOXBLOB blob, const unsigned char *fpr)
{
return blob_cmp_fpr (blob, fpr);
}
static inline int
has_keygrip (KEYBOXBLOB blob, const unsigned char *grip)
{
#ifdef KEYBOX_WITH_X509
if (blob_get_type (blob) == BLOBTYPE_X509)
return blob_x509_has_grip (blob, grip);
#endif
return 0;
}
static inline int
has_issuer (KEYBOXBLOB blob, const char *name)
{
size_t namelen;
return_val_if_fail (name, 0);
if (blob_get_type (blob) != BLOBTYPE_X509)
return 0;
namelen = strlen (name);
return blob_cmp_name (blob, 0 /* issuer */, name, namelen, 0);
}
static inline int
has_issuer_sn (KEYBOXBLOB blob, const char *name,
const unsigned char *sn, int snlen)
{
size_t namelen;
return_val_if_fail (name, 0);
return_val_if_fail (sn, 0);
if (blob_get_type (blob) != BLOBTYPE_X509)
return 0;
namelen = strlen (name);
return (blob_cmp_sn (blob, sn, snlen)
&& blob_cmp_name (blob, 0 /* issuer */, name, namelen, 0));
}
static inline int
has_sn (KEYBOXBLOB blob, const unsigned char *sn, int snlen)
{
return_val_if_fail (sn, 0);
if (blob_get_type (blob) != BLOBTYPE_X509)
return 0;
return blob_cmp_sn (blob, sn, snlen);
}
static inline int
has_subject (KEYBOXBLOB blob, const char *name)
{
size_t namelen;
return_val_if_fail (name, 0);
if (blob_get_type (blob) != BLOBTYPE_X509)
return 0;
namelen = strlen (name);
return blob_cmp_name (blob, 1 /* subject */, name, namelen, 0);
}
static inline int
has_subject_or_alt (KEYBOXBLOB blob, const char *name, int substr)
{
size_t namelen;
return_val_if_fail (name, 0);
if (blob_get_type (blob) != BLOBTYPE_X509)
return 0;
namelen = strlen (name);
return blob_cmp_name (blob, -1 /* all subject names*/, name,
namelen, substr);
}
static inline int
has_mail (KEYBOXBLOB blob, const char *name, int substr)
{
size_t namelen;
return_val_if_fail (name, 0);
if (blob_get_type (blob) != BLOBTYPE_X509)
return 0;
namelen = strlen (name);
if (namelen && name[namelen-1] == '>')
namelen--;
return blob_cmp_mail (blob, name, namelen, substr);
}
static void
release_sn_array (struct sn_array_s *array, size_t size)
{
size_t n;
for (n=0; n < size; n++)
xfree (array[n].sn);
xfree (array);
}
/*
The search API
*/
int
keybox_search_reset (KEYBOX_HANDLE hd)
{
if (!hd)
return gpg_error (GPG_ERR_INV_VALUE);
if (hd->found.blob)
{
_keybox_release_blob (hd->found.blob);
hd->found.blob = NULL;
}
if (hd->fp)
{
fclose (hd->fp);
hd->fp = NULL;
}
hd->error = 0;
hd->eof = 0;
return 0;
}
/* Note: When in ephemeral mode the search function does visit all
blobs but in standard mode, blobs flagged as ephemeral are ignored. */
int
keybox_search (KEYBOX_HANDLE hd, KEYBOX_SEARCH_DESC *desc, size_t ndesc)
{
int rc;
size_t n;
int need_words, any_skip;
KEYBOXBLOB blob = NULL;
struct sn_array_s *sn_array = NULL;
if (!hd)
return gpg_error (GPG_ERR_INV_VALUE);
/* clear last found result */
if (hd->found.blob)
{
_keybox_release_blob (hd->found.blob);
hd->found.blob = NULL;
}
if (hd->error)
return hd->error; /* still in error state */
if (hd->eof)
return -1; /* still EOF */
/* figure out what information we need */
need_words = any_skip = 0;
for (n=0; n < ndesc; n++)
{
switch (desc[n].mode)
{
case KEYDB_SEARCH_MODE_WORDS:
need_words = 1;
break;
case KEYDB_SEARCH_MODE_FIRST:
/* always restart the search in this mode */
keybox_search_reset (hd);
break;
default:
break;
}
if (desc[n].skipfnc)
any_skip = 1;
if (desc[n].snlen == -1 && !sn_array)
{
sn_array = xtrycalloc (ndesc, sizeof *sn_array);
if (!sn_array)
return (hd->error = gpg_error_from_syserror ());
}
}
(void)need_words; /* Not yet implemented. */
if (!hd->fp)
{
hd->fp = fopen (hd->kb->fname, "rb");
if (!hd->fp)
{
hd->error = gpg_error_from_syserror ();
xfree (sn_array);
return hd->error;
}
}
/* Kludge: We need to convert an SN given as hexstring to its binary
representation - in some cases we are not able to store it in the
search descriptor, because due to the way we use it, it is not
possible to free allocated memory. */
if (sn_array)
{
const unsigned char *s;
int i, odd;
size_t snlen;
for (n=0; n < ndesc; n++)
{
if (!desc[n].sn)
;
else if (desc[n].snlen == -1)
{
unsigned char *sn;
s = desc[n].sn;
for (i=0; *s && *s != '/'; s++, i++)
;
odd = (i & 1);
snlen = (i+1)/2;
sn_array[n].sn = xtrymalloc (snlen);
if (!sn_array[n].sn)
{
hd->error = gpg_error_from_syserror ();
release_sn_array (sn_array, n);
return hd->error;
}
sn_array[n].snlen = snlen;
sn = sn_array[n].sn;
s = desc[n].sn;
if (odd)
{
*sn++ = xtoi_1 (s);
s++;
}
for (; *s && *s != '/'; s += 2)
*sn++ = xtoi_2 (s);
}
else
{
const unsigned char *sn;
sn = desc[n].sn;
snlen = desc[n].snlen;
sn_array[n].sn = xtrymalloc (snlen);
if (!sn_array[n].sn)
{
hd->error = gpg_error_from_syserror ();
release_sn_array (sn_array, n);
return hd->error;
}
sn_array[n].snlen = snlen;
memcpy (sn_array[n].sn, sn, snlen);
}
}
}
for (;;)
{
unsigned int blobflags;
_keybox_release_blob (blob); blob = NULL;
rc = _keybox_read_blob (&blob, hd->fp);
if (rc)
break;
if (blob_get_type (blob) == BLOBTYPE_HEADER)
continue;
blobflags = blob_get_blob_flags (blob);
if (!hd->ephemeral && (blobflags & 2))
continue; /* Not in ephemeral mode but blob is flagged ephemeral. */
for (n=0; n < ndesc; n++)
{
switch (desc[n].mode)
{
case KEYDB_SEARCH_MODE_NONE:
never_reached ();
break;
case KEYDB_SEARCH_MODE_EXACT:
if (has_subject_or_alt (blob, desc[n].u.name, 0))
goto found;
break;
case KEYDB_SEARCH_MODE_MAIL:
if (has_mail (blob, desc[n].u.name, 0))
goto found;
break;
case KEYDB_SEARCH_MODE_MAILSUB:
if (has_mail (blob, desc[n].u.name, 1))
goto found;
break;
case KEYDB_SEARCH_MODE_SUBSTR:
if (has_subject_or_alt (blob, desc[n].u.name, 1))
goto found;
break;
case KEYDB_SEARCH_MODE_MAILEND:
case KEYDB_SEARCH_MODE_WORDS:
never_reached (); /* not yet implemented */
break;
case KEYDB_SEARCH_MODE_ISSUER:
if (has_issuer (blob, desc[n].u.name))
goto found;
break;
case KEYDB_SEARCH_MODE_ISSUER_SN:
if (has_issuer_sn (blob, desc[n].u.name,
sn_array? sn_array[n].sn : desc[n].sn,
sn_array? sn_array[n].snlen : desc[n].snlen))
goto found;
break;
case KEYDB_SEARCH_MODE_SN:
if (has_sn (blob, sn_array? sn_array[n].sn : desc[n].sn,
sn_array? sn_array[n].snlen : desc[n].snlen))
goto found;
break;
case KEYDB_SEARCH_MODE_SUBJECT:
if (has_subject (blob, desc[n].u.name))
goto found;
break;
case KEYDB_SEARCH_MODE_SHORT_KID:
if (has_short_kid (blob, desc[n].u.kid[1]))
goto found;
break;
case KEYDB_SEARCH_MODE_LONG_KID:
if (has_long_kid (blob, desc[n].u.kid[0], desc[n].u.kid[1]))
goto found;
break;
case KEYDB_SEARCH_MODE_FPR:
case KEYDB_SEARCH_MODE_FPR20:
if (has_fingerprint (blob, desc[n].u.fpr))
goto found;
break;
case KEYDB_SEARCH_MODE_KEYGRIP:
if (has_keygrip (blob, desc[n].u.grip))
goto found;
break;
case KEYDB_SEARCH_MODE_FIRST:
goto found;
break;
case KEYDB_SEARCH_MODE_NEXT:
goto found;
break;
default:
rc = gpg_error (GPG_ERR_INV_VALUE);
goto found;
}
}
continue;
found:
for (n=any_skip?0:ndesc; n < ndesc; n++)
{
/* if (desc[n].skipfnc */
/* && desc[n].skipfnc (desc[n].skipfncvalue, aki, NULL)) */
/* break; */
}
if (n == ndesc)
break; /* got it */
}
if (!rc)
{
hd->found.blob = blob;
}
else if (rc == -1)
{
_keybox_release_blob (blob);
hd->eof = 1;
}
else
{
_keybox_release_blob (blob);
hd->error = rc;
}
if (sn_array)
release_sn_array (sn_array, ndesc);
return rc;
}
/*
Functions to return a certificate or a keyblock. To be used after
a successful search operation.
*/
+
+
+/* Return the last found keyblock. Returns 0 on success and stores a
+ new iobuf at R_IOBUF in that case. */
+gpg_error_t
+keybox_get_keyblock (KEYBOX_HANDLE hd, iobuf_t *r_iobuf)
+{
+ const unsigned char *buffer;
+ size_t length;
+ size_t image_off, image_len;
+
+ *r_iobuf = NULL;
+
+ if (!hd)
+ return gpg_error (GPG_ERR_INV_VALUE);
+ if (!hd->found.blob)
+ return gpg_error (GPG_ERR_NOTHING_FOUND);
+
+ if (blob_get_type (hd->found.blob) != BLOBTYPE_PGP)
+ return gpg_error (GPG_ERR_WRONG_BLOB_TYPE);
+
+ buffer = _keybox_get_blob_image (hd->found.blob, &length);
+ if (length < 40)
+ return gpg_error (GPG_ERR_TOO_SHORT);
+ image_off = get32 (buffer+8);
+ image_len = get32 (buffer+12);
+ if (image_off+image_len > length)
+ return gpg_error (GPG_ERR_TOO_SHORT);
+
+ *r_iobuf = iobuf_temp_with_content (buffer+image_off, image_len);
+ return 0;
+}
+
+
#ifdef KEYBOX_WITH_X509
/*
Return the last found cert. Caller must free it.
*/
int
keybox_get_cert (KEYBOX_HANDLE hd, ksba_cert_t *r_cert)
{
const unsigned char *buffer;
size_t length;
size_t cert_off, cert_len;
ksba_reader_t reader = NULL;
ksba_cert_t cert = NULL;
int rc;
if (!hd)
return gpg_error (GPG_ERR_INV_VALUE);
if (!hd->found.blob)
return gpg_error (GPG_ERR_NOTHING_FOUND);
if (blob_get_type (hd->found.blob) != BLOBTYPE_X509)
return gpg_error (GPG_ERR_WRONG_BLOB_TYPE);
buffer = _keybox_get_blob_image (hd->found.blob, &length);
if (length < 40)
return gpg_error (GPG_ERR_TOO_SHORT);
cert_off = get32 (buffer+8);
cert_len = get32 (buffer+12);
if (cert_off+cert_len > length)
return gpg_error (GPG_ERR_TOO_SHORT);
rc = ksba_reader_new (&reader);
if (rc)
return rc;
rc = ksba_reader_set_mem (reader, buffer+cert_off, cert_len);
if (rc)
{
ksba_reader_release (reader);
/* fixme: need to map the error codes */
return gpg_error (GPG_ERR_GENERAL);
}
rc = ksba_cert_new (&cert);
if (rc)
{
ksba_reader_release (reader);
return rc;
}
rc = ksba_cert_read_der (cert, reader);
if (rc)
{
ksba_cert_release (cert);
ksba_reader_release (reader);
/* fixme: need to map the error codes */
return gpg_error (GPG_ERR_GENERAL);
}
*r_cert = cert;
ksba_reader_release (reader);
return 0;
}
#endif /*KEYBOX_WITH_X509*/
/* Return the flags named WHAT at the address of VALUE. IDX is used
only for certain flags and should be 0 if not required. */
int
keybox_get_flags (KEYBOX_HANDLE hd, int what, int idx, unsigned int *value)
{
const unsigned char *buffer;
size_t length;
gpg_err_code_t ec;
(void)idx; /* Not yet used. */
if (!hd)
return gpg_error (GPG_ERR_INV_VALUE);
if (!hd->found.blob)
return gpg_error (GPG_ERR_NOTHING_FOUND);
buffer = _keybox_get_blob_image (hd->found.blob, &length);
ec = get_flag_from_image (buffer, length, what, value);
return ec? gpg_error (ec):0;
}
diff --git a/kbx/keybox-update.c b/kbx/keybox-update.c
index 0d052c926..a4eedeb6a 100644
--- a/kbx/keybox-update.c
+++ b/kbx/keybox-update.c
@@ -1,721 +1,778 @@
/* keybox-update.c - keybox update operations
- * Copyright (C) 2001, 2003, 2004 Free Software Foundation, Inc.
+ * Copyright (C) 2001, 2003, 2004, 2012 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
* 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 <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
+#include <assert.h>
#include "keybox-defs.h"
#include "../common/sysutils.h"
#define EXTSEP_S "."
#if !defined(HAVE_FSEEKO) && !defined(fseeko)
#ifdef HAVE_LIMITS_H
# include <limits.h>
#endif
#ifndef LONG_MAX
# define LONG_MAX ((long) ((unsigned long) -1 >> 1))
#endif
#ifndef LONG_MIN
# define LONG_MIN (-1 - LONG_MAX)
#endif
/****************
* A substitute for fseeko, for hosts that don't have it.
*/
static int
fseeko (FILE * stream, off_t newpos, int whence)
{
while (newpos != (long) newpos)
{
long pos = newpos < 0 ? LONG_MIN : LONG_MAX;
if (fseek (stream, pos, whence) != 0)
return -1;
newpos -= pos;
whence = SEEK_CUR;
}
return fseek (stream, (long) newpos, whence);
}
#endif /* !defined(HAVE_FSEEKO) && !defined(fseeko) */
static int
create_tmp_file (const char *template,
char **r_bakfname, char **r_tmpfname, FILE **r_fp)
{
char *bakfname, *tmpfname;
*r_bakfname = NULL;
*r_tmpfname = NULL;
# ifdef USE_ONLY_8DOT3
/* Here is another Windoze bug?:
* you cant rename("pubring.kbx.tmp", "pubring.kbx");
* but rename("pubring.kbx.tmp", "pubring.aaa");
* works. So we replace ".kbx" by ".kb_" or ".k__". Note that we
* can't use ".bak" and ".tmp", because these suffixes are used by
* gpg and would lead to a sharing violation or data corruption.
*/
if (strlen (template) > 4
&& !strcmp (template+strlen(template)-4, EXTSEP_S "kbx") )
{
bakfname = xtrymalloc (strlen (template) + 1);
if (!bakfname)
return gpg_error_from_syserror ();
strcpy (bakfname, template);
strcpy (bakfname+strlen(template)-4, EXTSEP_S "kb_");
tmpfname = xtrymalloc (strlen (template) + 1);
if (!tmpfname)
{
gpg_error_t tmperr = gpg_error_from_syserror ();
xfree (bakfname);
return tmperr;
}
strcpy (tmpfname,template);
strcpy (tmpfname + strlen (template)-4, EXTSEP_S "k__");
}
else
{ /* File does not end with kbx, thus we hope we are working on a
modern file system and appending a suffix works. */
bakfname = xtrymalloc ( strlen (template) + 5);
if (!bakfname)
return gpg_error_from_syserror ();
strcpy (stpcpy (bakfname, template), EXTSEP_S "kb_");
tmpfname = xtrymalloc ( strlen (template) + 5);
if (!tmpfname)
{
gpg_error_t tmperr = gpg_error_from_syserror ();
xfree (bakfname);
return tmperr;
}
strcpy (stpcpy (tmpfname, template), EXTSEP_S "k__");
}
# else /* Posix file names */
bakfname = xtrymalloc (strlen (template) + 2);
if (!bakfname)
return gpg_error_from_syserror ();
strcpy (stpcpy (bakfname,template),"~");
tmpfname = xtrymalloc ( strlen (template) + 5);
if (!tmpfname)
{
gpg_error_t tmperr = gpg_error_from_syserror ();
xfree (bakfname);
return tmperr;
}
strcpy (stpcpy (tmpfname,template), EXTSEP_S "tmp");
# endif /* Posix filename */
*r_fp = fopen (tmpfname, "wb");
if (!*r_fp)
{
gpg_error_t tmperr = gpg_error_from_syserror ();
xfree (tmpfname);
xfree (bakfname);
return tmperr;
}
*r_bakfname = bakfname;
*r_tmpfname = tmpfname;
return 0;
}
static int
rename_tmp_file (const char *bakfname, const char *tmpfname,
const char *fname, int secret )
{
int rc=0;
/* restrict the permissions for secret keyboxs */
#ifndef HAVE_DOSISH_SYSTEM
/* if (secret && !opt.preserve_permissions) */
/* { */
/* if (chmod (tmpfname, S_IRUSR | S_IWUSR) ) */
/* { */
/* log_debug ("chmod of '%s' failed: %s\n", */
/* tmpfname, strerror(errno) ); */
/* return KEYBOX_Write_File; */
/* } */
/* } */
#endif
/* fixme: invalidate close caches (not used with stdio)*/
/* iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)tmpfname ); */
/* iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)bakfname ); */
/* iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname ); */
/* First make a backup file except for secret keyboxes. */
if (!secret)
{
#if defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
gnupg_remove (bakfname);
#endif
if (rename (fname, bakfname) )
{
return gpg_error_from_syserror ();
}
}
/* Then rename the file. */
#if defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
gnupg_remove (fname);
#endif
if (rename (tmpfname, fname) )
{
rc = gpg_error_from_syserror ();
if (secret)
{
/* log_info ("WARNING: 2 files with confidential" */
/* " information exists.\n"); */
/* log_info ("%s is the unchanged one\n", fname ); */
/* log_info ("%s is the new one\n", tmpfname ); */
/* log_info ("Please fix this possible security flaw\n"); */
}
return rc;
}
return 0;
}
/* Perform insert/delete/update operation.
mode 1 = insert
2 = delete
3 = update
*/
static int
blob_filecopy (int mode, const char *fname, KEYBOXBLOB blob,
int secret, off_t start_offset)
{
FILE *fp, *newfp;
int rc=0;
char *bakfname = NULL;
char *tmpfname = NULL;
char buffer[4096];
int nread, nbytes;
/* Open the source file. Because we do a rename, we have to check the
permissions of the file */
if (access (fname, W_OK))
return gpg_error_from_syserror ();
fp = fopen (fname, "rb");
if (mode == 1 && !fp && errno == ENOENT)
{
/* Insert mode but file does not exist:
Create a new keybox file. */
newfp = fopen (fname, "wb");
if (!newfp )
return gpg_error_from_syserror ();
rc = _keybox_write_header_blob (newfp);
if (rc)
return rc;
rc = _keybox_write_blob (blob, newfp);
if (rc)
return rc;
if ( fclose (newfp) )
return gpg_error_from_syserror ();
/* if (chmod( fname, S_IRUSR | S_IWUSR )) */
/* { */
/* log_debug ("%s: chmod failed: %s\n", fname, strerror(errno) ); */
/* return KEYBOX_File_Error; */
/* } */
return 0; /* Ready. */
}
if (!fp)
{
rc = gpg_error_from_syserror ();
goto leave;
}
/* Create the new file. */
rc = create_tmp_file (fname, &bakfname, &tmpfname, &newfp);
if (rc)
{
fclose(fp);
goto leave;
}
/* prepare for insert */
if (mode == 1)
{
/* Copy everything to the new file. */
while ( (nread = fread (buffer, 1, DIM(buffer), fp)) > 0 )
{
if (fwrite (buffer, nread, 1, newfp) != 1)
{
rc = gpg_error_from_syserror ();
goto leave;
}
}
if (ferror (fp))
{
rc = gpg_error_from_syserror ();
goto leave;
}
}
/* Prepare for delete or update. */
if ( mode == 2 || mode == 3 )
{
off_t current = 0;
/* Copy first part to the new file. */
while ( current < start_offset )
{
nbytes = DIM(buffer);
if (current + nbytes > start_offset)
nbytes = start_offset - current;
nread = fread (buffer, 1, nbytes, fp);
if (!nread)
break;
current += nread;
if (fwrite (buffer, nread, 1, newfp) != 1)
{
rc = gpg_error_from_syserror ();
goto leave;
}
}
if (ferror (fp))
{
rc = gpg_error_from_syserror ();
goto leave;
}
/* Skip this blob. */
rc = _keybox_read_blob (NULL, fp);
if (rc)
return rc;
}
/* Do an insert or update. */
if ( mode == 1 || mode == 3 )
{
rc = _keybox_write_blob (blob, newfp);
if (rc)
return rc;
}
/* Copy the rest of the packet for an delete or update. */
if (mode == 2 || mode == 3)
{
while ( (nread = fread (buffer, 1, DIM(buffer), fp)) > 0 )
{
if (fwrite (buffer, nread, 1, newfp) != 1)
{
rc = gpg_error_from_syserror ();
goto leave;
}
}
if (ferror (fp))
{
rc = gpg_error_from_syserror ();
goto leave;
}
}
/* Close both files. */
if (fclose(fp))
{
rc = gpg_error_from_syserror ();
fclose (newfp);
goto leave;
}
if (fclose(newfp))
{
rc = gpg_error_from_syserror ();
goto leave;
}
rc = rename_tmp_file (bakfname, tmpfname, fname, secret);
leave:
xfree(bakfname);
xfree(tmpfname);
return rc;
}
+/* Insert the OpenPGP keyblock {IMAGE,IMAGELEN} into HD. */
+gpg_error_t
+keybox_insert_keyblock (KEYBOX_HANDLE hd, const void *image, size_t imagelen)
+{
+ gpg_error_t err;
+ const char *fname;
+ KEYBOXBLOB blob;
+ size_t nparsed;
+ struct _keybox_openpgp_info info;
+
+ if (!hd)
+ return gpg_error (GPG_ERR_INV_HANDLE);
+ if (!hd->kb)
+ return gpg_error (GPG_ERR_INV_HANDLE);
+ fname = hd->kb->fname;
+ if (!fname)
+ return gpg_error (GPG_ERR_INV_HANDLE);
+
+
+ /* Close this one otherwise we will mess up the position for a next
+ search. Fixme: it would be better to adjust the position after
+ the write operation. */
+ _keybox_close_file (hd);
+
+ err = _keybox_parse_openpgp (image, imagelen, &nparsed, &info);
+ if (err)
+ return err;
+ assert (nparsed <= imagelen);
+ err = _keybox_create_openpgp_blob (&blob, &info, image, imagelen,
+ hd->ephemeral);
+ _keybox_destroy_openpgp_info (&info);
+ if (!err)
+ {
+ err = blob_filecopy (1, fname, blob, hd->secret, 0);
+ _keybox_release_blob (blob);
+ /* if (!rc && !hd->secret && kb_offtbl) */
+ /* { */
+ /* update_offset_hash_table_from_kb (kb_offtbl, kb, 0); */
+ /* } */
+ }
+ return err;
+}
+
+
+/* Update the current key at HD with the given OpenPGP keyblock in
+ {IMAGE,IMAGELEN}. */
+gpg_error_t
+keybox_update_keyblock (KEYBOX_HANDLE hd, const void *image, size_t imagelen)
+{
+ (void)hd;
+ (void)image;
+ (void)imagelen;
+ return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
+}
+
+
#ifdef KEYBOX_WITH_X509
int
keybox_insert_cert (KEYBOX_HANDLE hd, ksba_cert_t cert,
unsigned char *sha1_digest)
{
int rc;
const char *fname;
KEYBOXBLOB blob;
if (!hd)
return gpg_error (GPG_ERR_INV_HANDLE);
if (!hd->kb)
return gpg_error (GPG_ERR_INV_HANDLE);
fname = hd->kb->fname;
if (!fname)
return gpg_error (GPG_ERR_INV_HANDLE);
/* Close this one otherwise we will mess up the position for a next
search. Fixme: it would be better to adjust the position after
the write operation. */
_keybox_close_file (hd);
rc = _keybox_create_x509_blob (&blob, cert, sha1_digest, hd->ephemeral);
if (!rc)
{
rc = blob_filecopy (1, fname, blob, hd->secret, 0);
_keybox_release_blob (blob);
/* if (!rc && !hd->secret && kb_offtbl) */
/* { */
/* update_offset_hash_table_from_kb (kb_offtbl, kb, 0); */
/* } */
}
return rc;
}
int
keybox_update_cert (KEYBOX_HANDLE hd, ksba_cert_t cert,
unsigned char *sha1_digest)
{
(void)hd;
(void)cert;
(void)sha1_digest;
return -1;
}
#endif /*KEYBOX_WITH_X509*/
/* Note: We assume that the keybox has been locked before the current
search was executed. This is needed so that we can depend on the
offset information of the flags. */
int
keybox_set_flags (KEYBOX_HANDLE hd, int what, int idx, unsigned int value)
{
off_t off;
const char *fname;
FILE *fp;
gpg_err_code_t ec;
size_t flag_pos, flag_size;
const unsigned char *buffer;
size_t length;
(void)idx; /* Not yet used. */
if (!hd)
return gpg_error (GPG_ERR_INV_VALUE);
if (!hd->found.blob)
return gpg_error (GPG_ERR_NOTHING_FOUND);
if (!hd->kb)
return gpg_error (GPG_ERR_INV_HANDLE);
if (!hd->found.blob)
return gpg_error (GPG_ERR_NOTHING_FOUND);
fname = hd->kb->fname;
if (!fname)
return gpg_error (GPG_ERR_INV_HANDLE);
off = _keybox_get_blob_fileoffset (hd->found.blob);
if (off == (off_t)-1)
return gpg_error (GPG_ERR_GENERAL);
buffer = _keybox_get_blob_image (hd->found.blob, &length);
ec = _keybox_get_flag_location (buffer, length, what, &flag_pos, &flag_size);
if (ec)
return gpg_error (ec);
off += flag_pos;
_keybox_close_file (hd);
fp = fopen (hd->kb->fname, "r+b");
if (!fp)
return gpg_error_from_syserror ();
ec = 0;
if (fseeko (fp, off, SEEK_SET))
ec = gpg_error_from_syserror ();
else
{
unsigned char tmp[4];
tmp[0] = value >> 24;
tmp[1] = value >> 16;
tmp[2] = value >> 8;
tmp[3] = value;
switch (flag_size)
{
case 1:
case 2:
case 4:
if (fwrite (tmp+4-flag_size, flag_size, 1, fp) != 1)
ec = gpg_err_code_from_syserror ();
break;
default:
ec = GPG_ERR_BUG;
break;
}
}
if (fclose (fp))
{
if (!ec)
ec = gpg_err_code_from_syserror ();
}
return gpg_error (ec);
}
int
keybox_delete (KEYBOX_HANDLE hd)
{
off_t off;
const char *fname;
FILE *fp;
int rc;
if (!hd)
return gpg_error (GPG_ERR_INV_VALUE);
if (!hd->found.blob)
return gpg_error (GPG_ERR_NOTHING_FOUND);
if (!hd->kb)
return gpg_error (GPG_ERR_INV_HANDLE);
fname = hd->kb->fname;
if (!fname)
return gpg_error (GPG_ERR_INV_HANDLE);
off = _keybox_get_blob_fileoffset (hd->found.blob);
if (off == (off_t)-1)
return gpg_error (GPG_ERR_GENERAL);
off += 4;
_keybox_close_file (hd);
fp = fopen (hd->kb->fname, "r+b");
if (!fp)
return gpg_error_from_syserror ();
if (fseeko (fp, off, SEEK_SET))
rc = gpg_error_from_syserror ();
else if (putc (0, fp) == EOF)
rc = gpg_error_from_syserror ();
else
rc = 0;
if (fclose (fp))
{
if (!rc)
rc = gpg_error_from_syserror ();
}
return rc;
}
/* Compress the keybox file. This should be run with the file
locked. */
int
keybox_compress (KEYBOX_HANDLE hd)
{
int read_rc, rc;
const char *fname;
FILE *fp, *newfp;
char *bakfname = NULL;
char *tmpfname = NULL;
int first_blob;
KEYBOXBLOB blob = NULL;
u32 cut_time;
int any_changes = 0;
int skipped_deleted;
if (!hd)
return gpg_error (GPG_ERR_INV_HANDLE);
if (!hd->kb)
return gpg_error (GPG_ERR_INV_HANDLE);
if (hd->secret)
return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
fname = hd->kb->fname;
if (!fname)
return gpg_error (GPG_ERR_INV_HANDLE);
_keybox_close_file (hd);
/* Open the source file. Because we do a rename, we have to check the
permissions of the file */
if (access (fname, W_OK))
return gpg_error_from_syserror ();
fp = fopen (fname, "rb");
if (!fp && errno == ENOENT)
return 0; /* Ready. File has been deleted right after the access above. */
if (!fp)
{
rc = gpg_error_from_syserror ();
return rc;
}
/* A quick test to see if we need to compress the file at all. We
schedule a compress run after 3 hours. */
if ( !_keybox_read_blob (&blob, fp) )
{
const unsigned char *buffer;
size_t length;
buffer = _keybox_get_blob_image (blob, &length);
if (length > 4 && buffer[4] == BLOBTYPE_HEADER)
{
u32 last_maint = ((buffer[20] << 24) | (buffer[20+1] << 16)
| (buffer[20+2] << 8) | (buffer[20+3]));
if ( (last_maint + 3*3600) > time (NULL) )
{
fclose (fp);
_keybox_release_blob (blob);
return 0; /* Compress run not yet needed. */
}
}
_keybox_release_blob (blob);
fseek (fp, 0, SEEK_SET);
clearerr (fp);
}
/* Create the new file. */
rc = create_tmp_file (fname, &bakfname, &tmpfname, &newfp);
if (rc)
{
fclose(fp);
return rc;;
}
/* Processing loop. By reading using _keybox_read_blob we
automagically skip any blobs flagged as deleted. Thus what we
only have to do is to check all ephemeral flagged blocks whether
their time has come and write out all other blobs. */
cut_time = time(NULL) - 86400;
first_blob = 1;
skipped_deleted = 0;
for (rc=0; !(read_rc = _keybox_read_blob2 (&blob, fp, &skipped_deleted));
_keybox_release_blob (blob), blob = NULL )
{
unsigned int blobflags;
const unsigned char *buffer;
size_t length, pos, size;
u32 created_at;
if (skipped_deleted)
any_changes = 1;
buffer = _keybox_get_blob_image (blob, &length);
if (first_blob)
{
first_blob = 0;
if (length > 4 && buffer[4] == BLOBTYPE_HEADER)
{
/* Write out the blob with an updated maintenance time stamp. */
_keybox_update_header_blob (blob);
rc = _keybox_write_blob (blob, newfp);
if (rc)
break;
continue;
}
/* The header blob is missing. Insert it. */
rc = _keybox_write_header_blob (newfp);
if (rc)
break;
any_changes = 1;
}
else if (length > 4 && buffer[4] == BLOBTYPE_HEADER)
{
/* Oops: There is another header record - remove it. */
any_changes = 1;
continue;
}
if (_keybox_get_flag_location (buffer, length,
KEYBOX_FLAG_BLOB, &pos, &size)
|| size != 2)
{
rc = gpg_error (GPG_ERR_BUG);
break;
}
blobflags = ((buffer[pos] << 8) | (buffer[pos+1]));
if ((blobflags & KEYBOX_FLAG_BLOB_EPHEMERAL))
{
/* This is an ephemeral blob. */
if (_keybox_get_flag_location (buffer, length,
KEYBOX_FLAG_CREATED_AT, &pos, &size)
|| size != 4)
created_at = 0; /* oops. */
else
created_at = ((buffer[pos] << 24) | (buffer[pos+1] << 16)
| (buffer[pos+2] << 8) | (buffer[pos+3]));
if (created_at && created_at < cut_time)
{
any_changes = 1;
continue; /* Skip this blob. */
}
}
rc = _keybox_write_blob (blob, newfp);
if (rc)
break;
}
if (skipped_deleted)
any_changes = 1;
_keybox_release_blob (blob); blob = NULL;
if (!rc && read_rc == -1)
rc = 0;
else if (!rc)
rc = read_rc;
/* Close both files. */
if (fclose(fp) && !rc)
rc = gpg_error_from_syserror ();
if (fclose(newfp) && !rc)
rc = gpg_error_from_syserror ();
/* Rename or remove the temporary file. */
if (rc || !any_changes)
gnupg_remove (tmpfname);
else
rc = rename_tmp_file (bakfname, tmpfname, fname, hd->secret);
xfree(bakfname);
xfree(tmpfname);
return rc;
}
diff --git a/kbx/keybox.h b/kbx/keybox.h
index 52c16382c..15f05ed81 100644
--- a/kbx/keybox.h
+++ b/kbx/keybox.h
@@ -1,124 +1,131 @@
/* keybox.h - Keybox operations
- * Copyright (C) 2001, 2003 Free Software Foundation, Inc.
+ * Copyright (C) 2001, 2003, 2012 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
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef KEYBOX_H
#define KEYBOX_H 1
#ifdef __cplusplus
extern "C" {
#if 0
}
#endif
#endif
+#include "../common/iobuf.h"
#include "keybox-search-desc.h"
#define KEYBOX_WITH_OPENPGP 1
#define KEYBOX_WITH_X509 1
#ifdef KEYBOX_WITH_OPENPGP
# undef KEYBOX_WITH_OPENPGP
/*#include <lib-to-handle-gpg-data-structs.h>*/
#endif
#ifdef KEYBOX_WITH_X509
# include <ksba.h>
#endif
typedef struct keybox_handle *KEYBOX_HANDLE;
typedef enum
{
KEYBOX_FLAG_BLOB, /* The blob flags. */
KEYBOX_FLAG_VALIDITY, /* The validity of the entire key. */
KEYBOX_FLAG_OWNERTRUST, /* The assigned ownertrust. */
KEYBOX_FLAG_KEY, /* The key flags; requires a key index. */
KEYBOX_FLAG_UID, /* The user ID flags; requires an uid index. */
KEYBOX_FLAG_UID_VALIDITY,/* The validity of a specific uid, requires
an uid index. */
KEYBOX_FLAG_CREATED_AT /* The date the block was created. */
} keybox_flag_t;
/* Flag values used with KEYBOX_FLAG_BLOB. */
#define KEYBOX_FLAG_BLOB_SECRET 1
#define KEYBOX_FLAG_BLOB_EPHEMERAL 2
/*-- keybox-init.c --*/
void *keybox_register_file (const char *fname, int secret);
int keybox_is_writable (void *token);
KEYBOX_HANDLE keybox_new (void *token, int secret);
void keybox_release (KEYBOX_HANDLE hd);
const char *keybox_get_resource_name (KEYBOX_HANDLE hd);
int keybox_set_ephemeral (KEYBOX_HANDLE hd, int yes);
int keybox_lock (KEYBOX_HANDLE hd, int yes);
/*-- keybox-file.c --*/
/* Fixme: This function does not belong here: Provide a better
interface to create a new keybox file. */
int _keybox_write_header_blob (FILE *fp);
/*-- keybox-search.c --*/
+gpg_error_t keybox_get_keyblock (KEYBOX_HANDLE hd, iobuf_t *r_iobuf);
#ifdef KEYBOX_WITH_X509
int keybox_get_cert (KEYBOX_HANDLE hd, ksba_cert_t *ret_cert);
#endif /*KEYBOX_WITH_X509*/
int keybox_get_flags (KEYBOX_HANDLE hd, int what, int idx, unsigned int *value);
int keybox_search_reset (KEYBOX_HANDLE hd);
int keybox_search (KEYBOX_HANDLE hd, KEYBOX_SEARCH_DESC *desc, size_t ndesc);
/*-- keybox-update.c --*/
+gpg_error_t keybox_insert_keyblock (KEYBOX_HANDLE hd,
+ const void *image, size_t imagelen);
+gpg_error_t keybox_update_keyblock (KEYBOX_HANDLE hd,
+ const void *image, size_t imagelen);
+
#ifdef KEYBOX_WITH_X509
int keybox_insert_cert (KEYBOX_HANDLE hd, ksba_cert_t cert,
unsigned char *sha1_digest);
int keybox_update_cert (KEYBOX_HANDLE hd, ksba_cert_t cert,
unsigned char *sha1_digest);
#endif /*KEYBOX_WITH_X509*/
int keybox_set_flags (KEYBOX_HANDLE hd, int what, int idx, unsigned int value);
int keybox_delete (KEYBOX_HANDLE hd);
int keybox_compress (KEYBOX_HANDLE hd);
/*-- --*/
#if 0
int keybox_get_keyblock (KEYBOX_HANDLE hd, KBNODE *ret_kb);
int keybox_locate_writable (KEYBOX_HANDLE hd);
int keybox_search_reset (KEYBOX_HANDLE hd);
int keybox_search (KEYBOX_HANDLE hd, KEYDB_SEARCH_DESC *desc, size_t ndesc);
int keybox_rebuild_cache (void *);
#endif
/*-- keybox-util.c --*/
void keybox_set_malloc_hooks ( void *(*new_alloc_func)(size_t n),
void *(*new_realloc_func)(void *p, size_t n),
void (*new_free_func)(void*) );
#ifdef __cplusplus
}
#endif
#endif /*KEYBOX_H*/

File Metadata

Mime Type
text/x-diff
Expires
Sat, May 10, 9:06 AM (21 h, 47 m)
Storage Engine
local-disk
Storage Format
Raw Data
Storage Handle
3c/43/e40c3f7b8c4b7ce010185844a8c3

Event Timeline