1 /* getkey.c - Get a key from the database
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3 * 2007, 2008, 2010 Free Software Foundation, Inc.
4 * Copyright (C) 2015 g10 Code GmbH
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <http://www.gnu.org/licenses/>.
38 #include "keyserver-internal.h"
39 #include "call-agent.h"
41 #include "mbox-util.h"
43 #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
44 #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
46 #if MAX_PK_CACHE_ENTRIES < 2
47 #error We need the cache for key creation
52 /* Part of the search criteria: whether the search is an exact
53 search or not. A search that is exact requires that a key or
54 subkey meet all of the specified criteria. A search that is not
55 exact allows selecting a different key or subkey from the
56 keyblock that matched the critera. Further, an exact search
57 returns the key or subkey that matched whereas a non-exact search
58 typically returns the primary key. See finish_lookup for
62 /* Part of the search criteria: Whether the caller only wants keys
63 with an available secret key. This is used by getkey_next to get
64 the next result with the same initial criteria. */
67 /* Part of the search criteria: The type of the requested key. A
68 mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.
69 If non-zero, then for a key to match, it must implement one of
73 /* The database handle. */
74 KEYDB_HANDLE kr_handle;
76 /* Whether we should call xfree() on the context when the context is
77 released using getkey_end()). */
80 /* This variable is used as backing store for strings which have
81 their address used in ITEMS. */
84 /* Part of the search criteria: The low-level search specification
85 as passed to keydb_search. */
87 /* This must be the last element in the structure. When we allocate
88 the structure, we allocate it so that ITEMS can hold NITEMS. */
89 KEYDB_SEARCH_DESC items[1];
102 typedef struct keyid_list
104 struct keyid_list *next;
105 char fpr[MAX_FINGERPRINT_LEN];
110 #if MAX_PK_CACHE_ENTRIES
111 typedef struct pk_cache_entry
113 struct pk_cache_entry *next;
117 static pk_cache_entry_t pk_cache;
118 static int pk_cache_entries; /* Number of entries in pk cache. */
119 static int pk_cache_disabled;
122 #if MAX_UID_CACHE_ENTRIES < 5
123 #error we really need the userid cache
125 typedef struct user_id_db
127 struct user_id_db *next;
132 static user_id_db_t user_id_db;
133 static int uid_cache_entries; /* Number of entries in uid cache. */
135 static void merge_selfsigs (kbnode_t keyblock);
136 static int lookup (getkey_ctx_t ctx,
137 kbnode_t *ret_keyblock, kbnode_t *ret_found_key,
145 for (i = 0; i < DIM (lkup_stats); i++)
147 if (lkup_stats[i].any)
148 es_fprintf (es_stderr,
149 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
151 lkup_stats[i].okay_count,
152 lkup_stats[i].nokey_count, lkup_stats[i].error_count);
158 /* For documentation see keydb.h. */
160 cache_public_key (PKT_public_key * pk)
162 #if MAX_PK_CACHE_ENTRIES
163 pk_cache_entry_t ce, ce2;
166 if (pk_cache_disabled)
169 if (pk->flags.dont_cache)
172 if (is_ELGAMAL (pk->pubkey_algo)
173 || pk->pubkey_algo == PUBKEY_ALGO_DSA
174 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
175 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
176 || pk->pubkey_algo == PUBKEY_ALGO_ECDH
177 || is_RSA (pk->pubkey_algo))
179 keyid_from_pk (pk, keyid);
182 return; /* Don't know how to get the keyid. */
184 for (ce = pk_cache; ce; ce = ce->next)
185 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
188 log_debug ("cache_public_key: already in cache\n");
192 if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
196 /* Remove the last 50% of the entries. */
197 for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
199 if (ce != pk_cache && ce->next)
207 free_public_key (ce->pk);
212 assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
215 ce = xmalloc (sizeof *ce);
218 ce->pk = copy_public_key (NULL, pk);
219 ce->keyid[0] = keyid[0];
220 ce->keyid[1] = keyid[1];
225 /* Return a const utf-8 string with the text "[User ID not found]".
226 This function is required so that we don't need to switch gettext's
227 encoding temporary. */
229 user_id_not_found_utf8 (void)
234 text = native_to_utf8 (_("[User ID not found]"));
240 /* Return the user ID from the given keyblock.
241 * We use the primary uid flag which has been set by the merge_selfsigs
242 * function. The returned value is only valid as long as the given
243 * keyblock is not changed. */
245 get_primary_uid (KBNODE keyblock, size_t * uidlen)
250 for (k = keyblock; k; k = k->next)
252 if (k->pkt->pkttype == PKT_USER_ID
253 && !k->pkt->pkt.user_id->attrib_data
254 && k->pkt->pkt.user_id->is_primary)
256 *uidlen = k->pkt->pkt.user_id->len;
257 return k->pkt->pkt.user_id->name;
260 s = user_id_not_found_utf8 ();
261 *uidlen = strlen (s);
267 release_keyid_list (keyid_list_t k)
271 keyid_list_t k2 = k->next;
278 * Store the association of keyid and userid
279 * Feed only public keys to this function.
282 cache_user_id (KBNODE keyblock)
287 keyid_list_t keyids = NULL;
290 for (k = keyblock; k; k = k->next)
292 if (k->pkt->pkttype == PKT_PUBLIC_KEY
293 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
295 keyid_list_t a = xmalloc_clear (sizeof *a);
296 /* Hmmm: For a long list of keyids it might be an advantage
297 * to append the keys. */
298 fingerprint_from_pk (k->pkt->pkt.public_key, a->fpr, NULL);
299 keyid_from_pk (k->pkt->pkt.public_key, a->keyid);
300 /* First check for duplicates. */
301 for (r = user_id_db; r; r = r->next)
303 keyid_list_t b = r->keyids;
304 for (b = r->keyids; b; b = b->next)
306 if (!memcmp (b->fpr, a->fpr, MAX_FINGERPRINT_LEN))
309 log_debug ("cache_user_id: already in cache\n");
310 release_keyid_list (keyids);
316 /* Now put it into the cache. */
322 BUG (); /* No key no fun. */
325 uid = get_primary_uid (keyblock, &uidlen);
327 if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES)
329 /* fixme: use another algorithm to free some cache slots */
331 user_id_db = r->next;
332 release_keyid_list (r->keyids);
336 r = xmalloc (sizeof *r + uidlen - 1);
339 memcpy (r->name, uid, r->len);
340 r->next = user_id_db;
346 /* For documentation see keydb.h. */
348 getkey_disable_caches ()
350 #if MAX_PK_CACHE_ENTRIES
352 pk_cache_entry_t ce, ce2;
354 for (ce = pk_cache; ce; ce = ce2)
357 free_public_key (ce->pk);
360 pk_cache_disabled = 1;
361 pk_cache_entries = 0;
365 /* fixme: disable user id cache ? */
370 pk_from_block (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE keyblock,
373 KBNODE a = found_key ? found_key : keyblock;
377 assert (a->pkt->pkttype == PKT_PUBLIC_KEY
378 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
380 copy_public_key (pk, a->pkt->pkt.public_key);
384 /* For documentation see keydb.h. */
386 get_pubkey (PKT_public_key * pk, u32 * keyid)
391 #if MAX_PK_CACHE_ENTRIES
394 /* Try to get it from the cache. We don't do this when pk is
395 NULL as it does not guarantee that the user IDs are
398 for (ce = pk_cache; ce; ce = ce->next)
400 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
401 /* XXX: We don't check PK->REQ_USAGE here, but if we don't
402 read from the cache, we do check it! */
404 copy_public_key (pk, ce->pk);
410 /* More init stuff. */
413 pk = xmalloc_clear (sizeof *pk);
420 struct getkey_ctx_s ctx;
422 KBNODE found_key = NULL;
423 memset (&ctx, 0, sizeof ctx);
424 ctx.exact = 1; /* Use the key ID exactly as given. */
425 ctx.not_allocated = 1;
426 ctx.kr_handle = keydb_new ();
429 rc = gpg_error_from_syserror ();
433 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
434 ctx.items[0].u.kid[0] = keyid[0];
435 ctx.items[0].u.kid[1] = keyid[1];
436 ctx.req_usage = pk->req_usage;
437 rc = lookup (&ctx, &kb, &found_key, 0);
440 pk_from_block (&ctx, pk, kb, found_key);
448 rc = GPG_ERR_NO_PUBKEY;
452 cache_public_key (pk);
454 free_public_key (pk);
459 /* For documentation see keydb.h. */
461 get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
469 #if MAX_PK_CACHE_ENTRIES
471 /* Try to get it from the cache */
474 for (ce = pk_cache; ce; ce = ce->next)
476 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]
477 /* Only consider primary keys. */
478 && ce->pk->keyid[0] == ce->pk->main_keyid[0]
479 && ce->pk->keyid[1] == ce->pk->main_keyid[1])
482 copy_public_key (pk, ce->pk);
491 return gpg_error_from_syserror ();
492 rc = keydb_search_kid (hd, keyid);
493 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
496 return GPG_ERR_NO_PUBKEY;
498 rc = keydb_get_keyblock (hd, &keyblock);
502 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
503 return GPG_ERR_NO_PUBKEY;
506 assert (keyblock && keyblock->pkt
507 && keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
509 /* We return the primary key. If KEYID matched a subkey, then we
511 keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
512 if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
513 copy_public_key (pk, keyblock->pkt->pkt.public_key);
515 rc = GPG_ERR_NO_PUBKEY;
517 release_kbnode (keyblock);
519 /* Not caching key here since it won't have all of the fields
526 /* For documentation see keydb.h. */
528 get_pubkeyblock (u32 * keyid)
530 struct getkey_ctx_s ctx;
532 KBNODE keyblock = NULL;
534 memset (&ctx, 0, sizeof ctx);
535 /* No need to set exact here because we want the entire block. */
536 ctx.not_allocated = 1;
537 ctx.kr_handle = keydb_new ();
541 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
542 ctx.items[0].u.kid[0] = keyid[0];
543 ctx.items[0].u.kid[1] = keyid[1];
544 rc = lookup (&ctx, &keyblock, NULL, 0);
547 return rc ? NULL : keyblock;
551 /* For documentation see keydb.h. */
553 get_seckey (PKT_public_key *pk, u32 *keyid)
556 struct getkey_ctx_s ctx;
557 kbnode_t keyblock = NULL;
558 kbnode_t found_key = NULL;
560 memset (&ctx, 0, sizeof ctx);
561 ctx.exact = 1; /* Use the key ID exactly as given. */
562 ctx.not_allocated = 1;
563 ctx.kr_handle = keydb_new ();
565 return gpg_error_from_syserror ();
567 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
568 ctx.items[0].u.kid[0] = keyid[0];
569 ctx.items[0].u.kid[1] = keyid[1];
570 ctx.req_usage = pk->req_usage;
571 err = lookup (&ctx, &keyblock, &found_key, 1);
574 pk_from_block (&ctx, pk, keyblock, found_key);
577 release_kbnode (keyblock);
581 err = agent_probe_secret_key (/*ctrl*/NULL, pk);
583 release_public_key_parts (pk);
590 /* Skip unusable keys. A key is unusable if it is revoked, expired or
591 disabled or if the selected user id is revoked or expired. */
593 skip_unusable (void *dummy, u32 * keyid, int uid_no)
601 keyblock = get_pubkeyblock (keyid);
604 log_error ("error checking usability status of %s\n", keystr (keyid));
608 pk = keyblock->pkt->pkt.public_key;
610 /* Is the key revoked or expired? */
611 if (pk->flags.revoked || pk->has_expired)
614 /* Is the user ID in question revoked or expired? */
615 if (!unusable && uid_no)
620 for (node = keyblock; node; node = node->next)
622 if (node->pkt->pkttype == PKT_USER_ID)
624 PKT_user_id *user_id = node->pkt->pkt.user_id;
627 if (uids_seen != uid_no)
630 if (user_id->is_revoked || user_id->is_expired)
637 /* If UID_NO is non-zero, then the keyblock better have at least
639 assert (uids_seen == uid_no);
643 unusable = pk_is_disabled (pk);
646 release_kbnode (keyblock);
651 /* Search for keys matching some criteria.
653 If RETCTX is not NULL, then the constructed context is returned in
654 *RETCTX so that getpubkey_next can be used to get subsequent
655 results. In this case, getkey_end() must be used to free the
656 search context. If RETCTX is not NULL, then RET_KDBHD must be
659 If NAMELIST is not NULL, then a search query is constructed using
660 classify_user_id on each of the strings in the list. (Recall: the
661 database does an OR of the terms, not an AND.) If NAMELIST is
662 NULL, then all results are returned.
664 If PK is not NULL, the public key of the first result is returned
665 in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
666 set, it is used to filter the search results. See the
667 documentation for finish_lookup to understand exactly how this is
668 used. Note: The self-signed data has already been merged into the
669 public key using merge_selfsigs. Free *PK by calling
670 release_public_key_parts (or, if PK was allocated using xfree, you
671 can use free_public_key, which calls release_public_key_parts(PK)
674 If WANT_SECRET is set, then only keys with an available secret key
675 (either locally or via key registered on a smartcard) are returned.
677 If INCLUDE_UNUSABLE is set, then unusable keys (see the
678 documentation for skip_unusable for an exact definition) are
679 skipped unless they are looked up by key id or by fingerprint.
681 If RET_KB is not NULL, the keyblock is returned in *RET_KB. This
682 should be freed using release_kbnode().
684 If RET_KDBHD is not NULL, then the new database handle used to
685 conduct the search is returned in *RET_KDBHD. This can be used to
686 get subsequent results using keydb_search_next. Note: in this
687 case, no advanced filtering is done for subsequent results (e.g.,
688 WANT_SECRET and PK->REQ_USAGE are not respected).
690 This function returns 0 on success. Otherwise, an error code is
691 returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
692 (if want_secret is set) is returned if the key is not found. */
694 key_byname (GETKEY_CTX *retctx, strlist_t namelist,
696 int want_secret, int include_unusable,
697 KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
703 KBNODE help_kb = NULL;
704 KBNODE found_key = NULL;
708 /* Reset the returned context in case of error. */
709 assert (!ret_kdbhd); /* Not allowed because the handle is stored
717 /* No search terms: iterate over the whole DB. */
719 ctx = xmalloc_clear (sizeof *ctx);
721 ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
722 if (!include_unusable)
723 ctx->items[0].skipfnc = skip_unusable;
727 /* Build the search context. */
728 for (n = 0, r = namelist; r; r = r->next)
731 /* CTX has space for a single search term at the end. Thus, we
732 need to allocate sizeof *CTX plus (n - 1) sizeof
734 ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
737 for (n = 0, r = namelist; r; r = r->next, n++)
741 err = classify_user_id (r->d, &ctx->items[n], 1);
743 if (ctx->items[n].exact)
748 return gpg_err_code (err); /* FIXME: remove gpg_err_code. */
750 if (!include_unusable
751 && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
752 && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
753 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
754 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
755 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
756 ctx->items[n].skipfnc = skip_unusable;
760 ctx->want_secret = want_secret;
761 ctx->kr_handle = keydb_new ();
764 rc = gpg_error_from_syserror ();
774 ctx->req_usage = pk->req_usage;
777 rc = lookup (ctx, ret_kb, &found_key, want_secret);
780 pk_from_block (ctx, pk, *ret_kb, found_key);
783 release_kbnode (help_kb);
785 if (retctx) /* Caller wants the context. */
791 *ret_kdbhd = ctx->kr_handle;
792 ctx->kr_handle = NULL;
801 /* For documentation see keydb.h. */
803 get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
804 const char *name, KBNODE * ret_keyblock,
805 KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
808 strlist_t namelist = NULL;
812 int anylocalfirst = 0;
817 /* Does NAME appear to be a mailbox (mail address)? */
818 is_mbox = is_valid_mailbox (name);
820 /* The auto-key-locate feature works as follows: there are a number
821 of methods to look up keys. By default, the local keyring is
822 tried first. Then, each method listed in the --auto-key-locate is
823 tried in the order it appears.
825 This can be changed as follows:
827 - if nodefault appears anywhere in the list of options, then
828 the local keyring is not tried first, or,
830 - if local appears anywhere in the list of options, then the
831 local keyring is not tried first, but in the order in which
832 it was listed in the --auto-key-locate option.
834 Note: we only save the search context in RETCTX if the local
835 method is the first method tried (either explicitly or
838 /* auto-key-locate is enabled. */
840 /* nodefault is true if "nodefault" or "local" appear. */
841 for (akl = opt.auto_key_locate; akl; akl = akl->next)
842 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
847 /* anylocalfirst is true if "local" appears before any other
848 search methods (except "nodefault"). */
849 for (akl = opt.auto_key_locate; akl; akl = akl->next)
850 if (akl->type != AKL_NODEFAULT)
852 if (akl->type == AKL_LOCAL)
859 /* "nodefault" didn't occur. Thus, "local" is implicitly the
860 first method to try. */
863 if (nodefault && is_mbox)
864 /* Either "nodefault" or "local" (explicitly) appeared in the auto
865 key locate list and NAME appears to be an email address. Don't
866 try the local keyring. */
868 rc = GPG_ERR_NO_PUBKEY;
871 /* Either "nodefault" and "local" don't appear in the auto key
872 locate list (in which case we try the local keyring first) or
873 NAME does not appear to be an email address (in which case we
874 only try the local keyring). In this case, lookup NAME in the
877 add_to_strlist (&namelist, name);
878 rc = key_byname (retctx, namelist, pk, 0,
879 include_unusable, ret_keyblock, ret_kdbhd);
882 /* If the requested name resembles a valid mailbox and automatic
883 retrieval has been enabled, we try to import the key. */
884 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && !no_akl && is_mbox)
885 /* NAME wasn't present in the local keyring (or we didn't try the
886 local keyring). Since the auto key locate feature is enabled
887 and NAME appears to be an email address, try the auto locate
890 for (akl = opt.auto_key_locate; akl; akl = akl->next)
892 unsigned char *fpr = NULL;
894 int did_key_byname = 0;
895 int no_fingerprint = 0;
896 const char *mechanism = "?";
901 /* This is a dummy mechanism. */
903 rc = GPG_ERR_NO_PUBKEY;
911 getkey_end (*retctx);
914 add_to_strlist (&namelist, name);
915 rc = key_byname (anylocalfirst ? retctx : NULL,
917 include_unusable, ret_keyblock, ret_kdbhd);
921 mechanism = "DNS CERT";
922 glo_ctrl.in_auto_key_retrieve++;
923 rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len);
924 glo_ctrl.in_auto_key_retrieve--;
929 glo_ctrl.in_auto_key_retrieve++;
930 rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
931 glo_ctrl.in_auto_key_retrieve--;
936 glo_ctrl.in_auto_key_retrieve++;
937 rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len);
938 glo_ctrl.in_auto_key_retrieve--;
943 glo_ctrl.in_auto_key_retrieve++;
944 rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
945 glo_ctrl.in_auto_key_retrieve--;
949 /* Strictly speaking, we don't need to only use a valid
950 mailbox for the getname search, but it helps cut down
951 on the problem of searching for something like "john"
952 and getting a whole lot of keys back. */
955 mechanism = opt.keyserver->uri;
956 glo_ctrl.in_auto_key_retrieve++;
957 rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
959 glo_ctrl.in_auto_key_retrieve--;
963 mechanism = "Unconfigured keyserver";
964 rc = GPG_ERR_NO_PUBKEY;
970 struct keyserver_spec *keyserver;
972 mechanism = akl->spec->uri;
973 keyserver = keyserver_match (akl->spec);
974 glo_ctrl.in_auto_key_retrieve++;
975 rc = keyserver_import_name (ctrl,
976 name, &fpr, &fpr_len, keyserver);
977 glo_ctrl.in_auto_key_retrieve--;
982 /* Use the fingerprint of the key that we actually fetched.
983 This helps prevent problems where the key that we fetched
984 doesn't have the same name that we used to fetch it. In
985 the case of CERT and PKA, this is an actual security
986 requirement as the URL might point to a key put in by an
987 attacker. By forcing the use of the fingerprint, we
988 won't use the attacker's key here. */
991 char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
993 assert (fpr_len <= MAX_FINGERPRINT_LEN);
995 free_strlist (namelist);
998 bin2hex (fpr, fpr_len, fpr_string);
1001 log_info ("auto-key-locate found fingerprint %s\n",
1004 add_to_strlist (&namelist, fpr_string);
1006 else if (!rc && !fpr && !did_key_byname)
1007 /* The acquisition method said no failure occurred, but it
1008 didn't return a fingerprint. That's a failure. */
1011 rc = GPG_ERR_NO_PUBKEY;
1016 if (!rc && !did_key_byname)
1017 /* There was no error and we didn't do a local lookup.
1018 This means that we imported a key into the local
1019 keyring. Try to read the imported key from the
1024 getkey_end (*retctx);
1027 rc = key_byname (anylocalfirst ? retctx : NULL,
1029 include_unusable, ret_keyblock, ret_kdbhd);
1034 log_info (_("automatically retrieved '%s' via %s\n"),
1038 if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1039 || opt.verbose || no_fingerprint)
1040 log_info (_("error retrieving '%s' via %s: %s\n"),
1042 no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
1049 getkey_end (*retctx);
1053 if (retctx && *retctx)
1055 assert (!(*retctx)->extra_list);
1056 (*retctx)->extra_list = namelist;
1059 free_strlist (namelist);
1065 /* For documentation see keydb.h.
1067 FIXME: We should replace this with the _byname function. This can
1068 be done by creating a userID conforming to the unified fingerprint
1071 get_pubkey_byfprint (PKT_public_key *pk, kbnode_t *r_keyblock,
1072 const byte * fprint, size_t fprint_len)
1079 if (fprint_len == 20 || fprint_len == 16)
1081 struct getkey_ctx_s ctx;
1083 KBNODE found_key = NULL;
1085 memset (&ctx, 0, sizeof ctx);
1087 ctx.not_allocated = 1;
1088 ctx.kr_handle = keydb_new ();
1090 return gpg_error_from_syserror ();
1093 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1094 : KEYDB_SEARCH_MODE_FPR20;
1095 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1096 rc = lookup (&ctx, &kb, &found_key, 0);
1098 pk_from_block (&ctx, pk, kb, found_key);
1099 if (!rc && r_keyblock)
1104 release_kbnode (kb);
1108 rc = GPG_ERR_GENERAL; /* Oops */
1113 /* For documentation see keydb.h. */
1115 get_pubkey_byfprint_fast (PKT_public_key * pk,
1116 const byte * fprint, size_t fprint_len)
1121 byte fprbuf[MAX_FINGERPRINT_LEN];
1124 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1125 fprbuf[i] = fprint[i];
1126 while (i < MAX_FINGERPRINT_LEN)
1131 return gpg_error_from_syserror ();
1133 rc = keydb_search_fpr (hd, fprbuf);
1134 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1137 return GPG_ERR_NO_PUBKEY;
1139 rc = keydb_get_keyblock (hd, &keyblock);
1143 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1144 return GPG_ERR_NO_PUBKEY;
1147 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1148 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1150 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1151 release_kbnode (keyblock);
1153 /* Not caching key here since it won't have all of the fields
1160 parse_def_secret_key (ctrl_t ctrl)
1162 KEYDB_HANDLE hd = NULL;
1166 for (t = opt.def_secret_key; t; t = t->next)
1169 KEYDB_SEARCH_DESC desc;
1172 err = classify_user_id (t->d, &desc, 1);
1175 log_error (_("secret key \"%s\" not found: %s\n"),
1176 t->d, gpg_strerror (err));
1178 log_info (_("(check argument of option '%s')\n"), "--default-key");
1189 keydb_search_reset (hd);
1192 err = keydb_search (hd, &desc, 1, NULL);
1193 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1198 log_error (_("key \"%s\" not found: %s\n"), t->d, gpg_strerror (err));
1203 err = keydb_get_keyblock (hd, &kb);
1206 log_error (_("error reading keyblock: %s\n"),
1207 gpg_strerror (err));
1211 err = agent_probe_secret_key (ctrl, kb->pkt->pkt.public_key);
1212 release_kbnode (kb);
1216 log_info (_("using \"%s\" as default secret key\n"), t->d);
1231 /* For documentation see keydb.h. */
1233 get_seckey_default (ctrl_t ctrl, PKT_public_key *pk)
1236 strlist_t namelist = NULL;
1237 int include_unusable = 1;
1240 const char *def_secret_key = parse_def_secret_key (ctrl);
1242 add_to_strlist (&namelist, def_secret_key);
1244 include_unusable = 0;
1246 err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
1248 free_strlist (namelist);
1253 /* For documentation see keydb.h. */
1255 getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
1256 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
1258 return key_byname (retctx, names, pk, want_secret, 1,
1259 ret_keyblock, NULL);
1263 /* For documentation see keydb.h. */
1265 getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
1266 const char *name, int want_secret, kbnode_t *ret_keyblock)
1269 strlist_t namelist = NULL;
1270 int with_unusable = 1;
1271 const char *def_secret_key = NULL;
1273 if (want_secret && !name)
1274 def_secret_key = parse_def_secret_key (ctrl);
1276 if (want_secret && !name && def_secret_key)
1277 add_to_strlist (&namelist, def_secret_key);
1279 add_to_strlist (&namelist, name);
1283 err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
1284 ret_keyblock, NULL);
1286 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
1287 WANT_SECRET has been used. */
1289 free_strlist (namelist);
1295 /* For documentation see keydb.h. */
1297 getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
1299 int rc; /* Fixme: Make sure this is proper gpg_error */
1300 KBNODE found_key = NULL;
1302 /* We need to disable the caching so that for an exact key search we
1303 won't get the result back from the cache and thus end up in an
1304 endless loop. The endless loop can occur, because the cache is
1305 used without respecting the current file pointer! */
1306 keydb_disable_caching (ctx->kr_handle);
1308 rc = lookup (ctx, ret_keyblock, &found_key, ctx->want_secret);
1309 if (!rc && pk && ret_keyblock)
1310 pk_from_block (ctx, pk, *ret_keyblock, found_key);
1316 /* For documentation see keydb.h. */
1318 getkey_end (getkey_ctx_t ctx)
1322 keydb_release (ctx->kr_handle);
1323 free_strlist (ctx->extra_list);
1324 if (!ctx->not_allocated)
1331 /************************************************
1332 ************* Merging stuff ********************
1333 ************************************************/
1335 /* For documentation see keydb.h. */
1337 setup_main_keyids (kbnode_t keyblock)
1339 u32 kid[2], mainkid[2];
1340 kbnode_t kbctx, node;
1343 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1345 pk = keyblock->pkt->pkt.public_key;
1347 keyid_from_pk (pk, mainkid);
1348 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1350 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
1351 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1353 pk = node->pkt->pkt.public_key;
1354 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
1355 if (!pk->main_keyid[0] && !pk->main_keyid[1])
1357 pk->main_keyid[0] = mainkid[0];
1358 pk->main_keyid[1] = mainkid[1];
1364 /* For documentation see keydb.h. */
1366 merge_keys_and_selfsig (KBNODE keyblock)
1370 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
1371 merge_selfsigs (keyblock);
1373 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
1378 parse_key_usage (PKT_signature * sig)
1385 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
1388 /* First octet of the keyflags. */
1393 key_usage |= PUBKEY_USAGE_CERT;
1399 key_usage |= PUBKEY_USAGE_SIG;
1403 /* We do not distinguish between encrypting communications and
1404 encrypting storage. */
1405 if (flags & (0x04 | 0x08))
1407 key_usage |= PUBKEY_USAGE_ENC;
1408 flags &= ~(0x04 | 0x08);
1413 key_usage |= PUBKEY_USAGE_AUTH;
1418 key_usage |= PUBKEY_USAGE_UNKNOWN;
1421 key_usage |= PUBKEY_USAGE_NONE;
1423 else if (p) /* Key flags of length zero. */
1424 key_usage |= PUBKEY_USAGE_NONE;
1426 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1427 capability that we do not handle. This serves to distinguish
1428 between a zero key usage which we handle as the default
1429 capabilities for that algorithm, and a usage that we do not
1430 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
1431 key_flags have been given but they do not specify any usage. */
1437 /* Apply information from SIGNODE (which is the valid self-signature
1438 * associated with that UID) to the UIDNODE:
1439 * - weather the UID has been revoked
1440 * - assumed creation date of the UID
1441 * - temporary store the keyflags here
1442 * - temporary store the key expiration time here
1443 * - mark whether the primary user ID flag hat been set.
1444 * - store the preferences
1447 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
1449 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1450 PKT_signature *sig = signode->pkt->pkt.signature;
1451 const byte *p, *sym, *hash, *zip;
1452 size_t n, nsym, nhash, nzip;
1454 sig->flags.chosen_selfsig = 1;/* We chose this one. */
1455 uid->created = 0; /* Not created == invalid. */
1456 if (IS_UID_REV (sig))
1458 uid->is_revoked = 1;
1459 return; /* Has been revoked. */
1462 uid->is_revoked = 0;
1464 uid->expiredate = sig->expiredate;
1466 if (sig->flags.expired)
1468 uid->is_expired = 1;
1469 return; /* Has expired. */
1472 uid->is_expired = 0;
1474 uid->created = sig->timestamp; /* This one is okay. */
1475 uid->selfsigversion = sig->version;
1476 /* If we got this far, it's not expired :) */
1477 uid->is_expired = 0;
1479 /* Store the key flags in the helper variable for later processing. */
1480 uid->help_key_usage = parse_key_usage (sig);
1482 /* Ditto for the key expiration. */
1483 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1484 if (p && buf32_to_u32 (p))
1485 uid->help_key_expire = keycreated + buf32_to_u32 (p);
1487 uid->help_key_expire = 0;
1489 /* Set the primary user ID flag - we will later wipe out some
1490 * of them to only have one in our keyblock. */
1491 uid->is_primary = 0;
1492 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
1494 uid->is_primary = 2;
1496 /* We could also query this from the unhashed area if it is not in
1497 * the hased area and then later try to decide which is the better
1498 * there should be no security problem with this.
1499 * For now we only look at the hashed one. */
1501 /* Now build the preferences list. These must come from the
1502 hashed section so nobody can modify the ciphers a key is
1503 willing to accept. */
1504 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
1507 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
1510 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
1515 n = nsym + nhash + nzip;
1520 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
1522 for (; nsym; nsym--, n++)
1524 uid->prefs[n].type = PREFTYPE_SYM;
1525 uid->prefs[n].value = *sym++;
1527 for (; nhash; nhash--, n++)
1529 uid->prefs[n].type = PREFTYPE_HASH;
1530 uid->prefs[n].value = *hash++;
1532 for (; nzip; nzip--, n++)
1534 uid->prefs[n].type = PREFTYPE_ZIP;
1535 uid->prefs[n].value = *zip++;
1537 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
1538 uid->prefs[n].value = 0;
1541 /* See whether we have the MDC feature. */
1543 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1544 if (p && n && (p[0] & 0x01))
1547 /* And the keyserver modify flag. */
1548 uid->flags.ks_modify = 1;
1549 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1550 if (p && n && (p[0] & 0x80))
1551 uid->flags.ks_modify = 0;
1555 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
1557 rinfo->date = sig->timestamp;
1558 rinfo->algo = sig->pubkey_algo;
1559 rinfo->keyid[0] = sig->keyid[0];
1560 rinfo->keyid[1] = sig->keyid[1];
1564 /* Given a keyblock, parse the key block and extract various pieces of
1565 information and save them with the primary key packet and the user
1566 id packets. For instance, some information is stored in signature
1567 packets. We find the latest such valid packet (since the user can
1568 change that information) and copy its contents into the
1571 Note that R_REVOKED may be set to 0, 1 or 2.
1573 This function fills in the following fields in the primary key's
1576 main_keyid (computed)
1577 revkey / numrevkeys (derived from self signed key data)
1578 flags.valid (whether we have at least 1 self-sig)
1579 flags.maybe_revoked (whether a designed revoked the key, but
1580 we are missing the key to check the sig)
1581 selfsigversion (highest version of any valid self-sig)
1582 pubkey_usage (derived from most recent self-sig or most
1584 has_expired (various sources)
1585 expiredate (various sources)
1587 See the documentation for fixup_uidnode for how the user id packets
1588 are modified. In addition to that the primary user id's is_primary
1589 field is set to 1 and the other user id's is_primary are set to
1592 merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
1593 struct revoke_info *rinfo)
1595 PKT_public_key *pk = NULL;
1598 u32 sigdate, uiddate, uiddate2;
1599 KBNODE signode, uidnode, uidnode2;
1600 u32 curtime = make_timestamp ();
1601 unsigned int key_usage = 0;
1602 u32 keytimestamp = 0;
1604 int key_expire_seen = 0;
1605 byte sigversion = 0;
1608 memset (rinfo, 0, sizeof (*rinfo));
1610 /* Section 11.1 of RFC 4880 determines the order of packets within a
1611 message. There are three sections, which must occur in the
1612 following order: the public key, the user ids and user attributes
1613 and the subkeys. Within each section, each primary packet (e.g.,
1614 a user id packet) is followed by one or more signature packets,
1615 which modify that packet. */
1617 /* According to Section 11.1 of RFC 4880, the public key must be the
1619 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1620 /* parse_keyblock_image ensures that the first packet is the
1623 pk = keyblock->pkt->pkt.public_key;
1624 keytimestamp = pk->timestamp;
1626 keyid_from_pk (pk, kid);
1627 pk->main_keyid[0] = kid[0];
1628 pk->main_keyid[1] = kid[1];
1630 if (pk->version < 4)
1632 /* Before v4 the key packet itself contains the expiration date
1633 * and there was no way to change it, so we start with the one
1634 * from the key packet. */
1635 key_expire = pk->max_expiredate;
1636 key_expire_seen = 1;
1641 - Find the latest direct key self-signature. We assume that the
1642 newest one overrides all others.
1644 - Determine whether the key has been revoked.
1646 - Gather all revocation keys (unlike other data, we don't just
1647 take them from the latest self-signed packet).
1649 - Determine max (sig[...]->version).
1652 /* Reset this in case this key was already merged. */
1658 sigdate = 0; /* Helper variable to find the latest signature. */
1660 /* According to Section 11.1 of RFC 4880, the public key comes first
1661 and is immediately followed by any signature packets that modify
1664 k && k->pkt->pkttype != PKT_USER_ID
1665 && k->pkt->pkttype != PKT_ATTRIBUTE
1666 && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1669 if (k->pkt->pkttype == PKT_SIGNATURE)
1671 PKT_signature *sig = k->pkt->pkt.signature;
1672 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1675 if (check_key_signature (keyblock, k, NULL))
1676 ; /* Signature did not verify. */
1677 else if (IS_KEY_REV (sig))
1679 /* Key has been revoked - there is no way to
1680 * override such a revocation, so we theoretically
1681 * can stop now. We should not cope with expiration
1682 * times for revocations here because we have to
1683 * assume that an attacker can generate all kinds of
1684 * signatures. However due to the fact that the key
1685 * has been revoked it does not harm either and by
1686 * continuing we gather some more info on that
1689 sig_to_revoke_info (sig, rinfo);
1691 else if (IS_KEY_SIG (sig))
1693 /* Add the indicated revocations keys from all
1694 signatures not just the latest. We do this
1695 because you need multiple 1F sigs to properly
1696 handle revocation keys (PGP does it this way, and
1697 a revocation key could be sensitive and hence in
1698 a different signature). */
1704 xrealloc (pk->revkey, sizeof (struct revocation_key) *
1705 (pk->numrevkeys + sig->numrevkeys));
1707 for (i = 0; i < sig->numrevkeys; i++)
1708 memcpy (&pk->revkey[pk->numrevkeys++],
1710 sizeof (struct revocation_key));
1713 if (sig->timestamp >= sigdate)
1714 /* This is the latest signature so far. */
1716 if (sig->flags.expired)
1717 ; /* Signature has expired - ignore it. */
1720 sigdate = sig->timestamp;
1722 if (sig->version > sigversion)
1723 sigversion = sig->version;
1732 /* Remove dupes from the revocation keys. */
1735 int i, j, x, changed = 0;
1737 for (i = 0; i < pk->numrevkeys; i++)
1739 for (j = i + 1; j < pk->numrevkeys; j++)
1741 if (memcmp (&pk->revkey[i], &pk->revkey[j],
1742 sizeof (struct revocation_key)) == 0)
1746 for (x = j; x < pk->numrevkeys - 1; x++)
1747 pk->revkey[x] = pk->revkey[x + 1];
1757 pk->revkey = xrealloc (pk->revkey,
1759 sizeof (struct revocation_key));
1763 /* SIGNODE is the 1F signature packet with the latest creation
1764 time. Extract some information from it. */
1766 /* Some information from a direct key signature take precedence
1767 * over the same information given in UID sigs. */
1768 PKT_signature *sig = signode->pkt->pkt.signature;
1771 key_usage = parse_key_usage (sig);
1773 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1774 if (p && buf32_to_u32 (p))
1776 key_expire = keytimestamp + buf32_to_u32 (p);
1777 key_expire_seen = 1;
1780 /* Mark that key as valid: One direct key signature should
1781 * render a key as valid. */
1782 pk->flags.valid = 1;
1785 /* Pass 1.5: Look for key revocation signatures that were not made
1786 by the key (i.e. did a revocation key issue a revocation for
1787 us?). Only bother to do this if there is a revocation key in the
1788 first place and we're not revoked already. */
1790 if (!*r_revoked && pk->revkey)
1791 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
1793 if (k->pkt->pkttype == PKT_SIGNATURE)
1795 PKT_signature *sig = k->pkt->pkt.signature;
1797 if (IS_KEY_REV (sig) &&
1798 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
1800 int rc = check_revocation_keys (pk, sig);
1804 sig_to_revoke_info (sig, rinfo);
1805 /* Don't continue checking since we can't be any
1806 more revoked than this. */
1809 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
1810 pk->flags.maybe_revoked = 1;
1812 /* A failure here means the sig did not verify, was
1813 not issued by a revocation key, or a revocation
1814 key loop was broken. If a revocation key isn't
1815 findable, however, the key might be revoked and
1816 we don't know it. */
1818 /* TODO: In the future handle subkey and cert
1819 revocations? PGP doesn't, but it's in 2440. */
1824 /* Second pass: Look at the self-signature of all user IDs. */
1826 /* According to RFC 4880 section 11.1, user id and attribute packets
1827 are in the second section, after the public key packet and before
1828 the subkey packets. */
1829 signode = uidnode = NULL;
1830 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
1831 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1833 if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
1834 /* New user id packet. */
1836 if (uidnode && signode)
1837 /* Apply the data from the most recent self-signed packet
1838 to the preceding user id packet. */
1840 fixup_uidnode (uidnode, signode, keytimestamp);
1841 pk->flags.valid = 1;
1843 /* Clear SIGNODE. The only relevant self-signed data for
1844 UIDNODE follows it. */
1845 if (k->pkt->pkttype == PKT_USER_ID)
1852 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1854 PKT_signature *sig = k->pkt->pkt.signature;
1855 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1857 if (check_key_signature (keyblock, k, NULL))
1858 ; /* signature did not verify */
1859 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
1860 && sig->timestamp >= sigdate)
1862 /* Note: we allow to invalidate cert revocations
1863 * by a newer signature. An attacker can't use this
1864 * because a key should be revoked with a key revocation.
1865 * The reason why we have to allow for that is that at
1866 * one time an email address may become invalid but later
1867 * the same email address may become valid again (hired,
1868 * fired, hired again). */
1870 sigdate = sig->timestamp;
1872 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
1873 if (sig->version > sigversion)
1874 sigversion = sig->version;
1879 if (uidnode && signode)
1881 fixup_uidnode (uidnode, signode, keytimestamp);
1882 pk->flags.valid = 1;
1885 /* If the key isn't valid yet, and we have
1886 --allow-non-selfsigned-uid set, then force it valid. */
1887 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
1890 log_info (_("Invalid key %s made valid by"
1891 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
1892 pk->flags.valid = 1;
1895 /* The key STILL isn't valid, so try and find an ultimately
1896 trusted signature. */
1897 if (!pk->flags.valid)
1901 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1904 if (k->pkt->pkttype == PKT_USER_ID)
1906 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1908 PKT_signature *sig = k->pkt->pkt.signature;
1910 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
1912 PKT_public_key *ultimate_pk;
1914 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
1916 /* We don't want to use the full get_pubkey to
1917 avoid infinite recursion in certain cases.
1918 There is no reason to check that an ultimately
1919 trusted key is still valid - if it has been
1920 revoked the user should also remove the
1921 ultimate trust flag. */
1922 if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
1923 && check_key_signature2 (keyblock, k, ultimate_pk,
1924 NULL, NULL, NULL, NULL) == 0
1925 && get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
1927 free_public_key (ultimate_pk);
1928 pk->flags.valid = 1;
1932 free_public_key (ultimate_pk);
1938 /* Record the highest selfsig version so we know if this is a v3
1939 key through and through, or a v3 key with a v4 selfsig
1940 somewhere. This is useful in a few places to know if the key
1941 must be treated as PGP2-style or OpenPGP-style. Note that a
1942 selfsig revocation with a higher version number will also raise
1943 this value. This is okay since such a revocation must be
1944 issued by the user (i.e. it cannot be issued by someone else to
1945 modify the key behavior.) */
1947 pk->selfsigversion = sigversion;
1949 /* Now that we had a look at all user IDs we can now get some information
1950 * from those user IDs.
1955 /* Find the latest user ID with key flags set. */
1956 uiddate = 0; /* Helper to find the latest user ID. */
1957 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1960 if (k->pkt->pkttype == PKT_USER_ID)
1962 PKT_user_id *uid = k->pkt->pkt.user_id;
1963 if (uid->help_key_usage && uid->created > uiddate)
1965 key_usage = uid->help_key_usage;
1966 uiddate = uid->created;
1973 /* No key flags at all: get it from the algo. */
1974 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
1978 /* Check that the usage matches the usage as given by the algo. */
1979 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
1980 if (x) /* Mask it down to the actual allowed usage. */
1984 /* Whatever happens, it's a primary key, so it can certify. */
1985 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
1987 if (!key_expire_seen)
1989 /* Find the latest valid user ID with a key expiration set
1990 * Note, that this may be a different one from the above because
1991 * some user IDs may have no expiration date set. */
1993 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1996 if (k->pkt->pkttype == PKT_USER_ID)
1998 PKT_user_id *uid = k->pkt->pkt.user_id;
1999 if (uid->help_key_expire && uid->created > uiddate)
2001 key_expire = uid->help_key_expire;
2002 uiddate = uid->created;
2008 /* Currently only v3 keys have a maximum expiration date, but I'll
2009 bet v5 keys get this feature again. */
2011 || (pk->max_expiredate && key_expire > pk->max_expiredate))
2012 key_expire = pk->max_expiredate;
2014 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
2015 pk->expiredate = key_expire;
2017 /* Fixme: we should see how to get rid of the expiretime fields but
2018 * this needs changes at other places too. */
2020 /* And now find the real primary user ID and delete all others. */
2021 uiddate = uiddate2 = 0;
2022 uidnode = uidnode2 = NULL;
2023 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2025 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
2027 PKT_user_id *uid = k->pkt->pkt.user_id;
2028 if (uid->is_primary)
2030 if (uid->created > uiddate)
2032 uiddate = uid->created;
2035 else if (uid->created == uiddate && uidnode)
2037 /* The dates are equal, so we need to do a
2038 different (and arbitrary) comparison. This
2039 should rarely, if ever, happen. It's good to
2040 try and guarantee that two different GnuPG
2041 users with two different keyrings at least pick
2042 the same primary. */
2043 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
2049 if (uid->created > uiddate2)
2051 uiddate2 = uid->created;
2054 else if (uid->created == uiddate2 && uidnode2)
2056 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
2064 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2067 if (k->pkt->pkttype == PKT_USER_ID &&
2068 !k->pkt->pkt.user_id->attrib_data)
2070 PKT_user_id *uid = k->pkt->pkt.user_id;
2072 uid->is_primary = 0;
2078 /* None is flagged primary - use the latest user ID we have,
2079 and disambiguate with the arbitrary packet comparison. */
2080 uidnode2->pkt->pkt.user_id->is_primary = 1;
2084 /* None of our uids were self-signed, so pick the one that
2085 sorts first to be the primary. This is the best we can do
2086 here since there are no self sigs to date the uids. */
2090 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2093 if (k->pkt->pkttype == PKT_USER_ID
2094 && !k->pkt->pkt.user_id->attrib_data)
2099 uidnode->pkt->pkt.user_id->is_primary = 1;
2104 if (cmp_user_ids (k->pkt->pkt.user_id,
2105 uidnode->pkt->pkt.user_id) > 0)
2107 uidnode->pkt->pkt.user_id->is_primary = 0;
2109 uidnode->pkt->pkt.user_id->is_primary = 1;
2112 k->pkt->pkt.user_id->is_primary = 0; /* just to be
2120 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
2121 Caller must free the signature when they are done. */
2122 static PKT_signature *
2123 buf_to_sig (const byte * buf, size_t len)
2125 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
2126 IOBUF iobuf = iobuf_temp_with_content (buf, len);
2127 int save_mode = set_packet_list_mode (0);
2129 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
2135 set_packet_list_mode (save_mode);
2136 iobuf_close (iobuf);
2141 /* Use the self-signed data to fill in various fields in subkeys.
2143 KEYBLOCK is the whole keyblock. SUBNODE is the subkey to fill in.
2145 Sets the following fields on the subkey:
2148 flags.valid if the subkey has a valid self-sig binding
2155 On this subkey's most revent valid self-signed packet, the
2156 following field is set:
2158 flags.chosen_selfsig
2161 merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
2163 PKT_public_key *mainpk = NULL, *subpk = NULL;
2169 u32 curtime = make_timestamp ();
2170 unsigned int key_usage = 0;
2171 u32 keytimestamp = 0;
2175 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2177 mainpk = keyblock->pkt->pkt.public_key;
2178 if (mainpk->version < 4)
2179 return;/* (actually this should never happen) */
2180 keyid_from_pk (mainpk, mainkid);
2181 subpk = subnode->pkt->pkt.public_key;
2182 keytimestamp = subpk->timestamp;
2184 subpk->flags.valid = 0;
2185 subpk->main_keyid[0] = mainpk->main_keyid[0];
2186 subpk->main_keyid[1] = mainpk->main_keyid[1];
2188 /* Find the latest key binding self-signature. */
2190 sigdate = 0; /* Helper to find the latest signature. */
2191 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2194 if (k->pkt->pkttype == PKT_SIGNATURE)
2196 sig = k->pkt->pkt.signature;
2197 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
2199 if (check_key_signature (keyblock, k, NULL))
2200 ; /* Signature did not verify. */
2201 else if (IS_SUBKEY_REV (sig))
2203 /* Note that this means that the date on a
2204 revocation sig does not matter - even if the
2205 binding sig is dated after the revocation sig,
2206 the subkey is still marked as revoked. This
2207 seems ok, as it is just as easy to make new
2208 subkeys rather than re-sign old ones as the
2209 problem is in the distribution. Plus, PGP (7)
2210 does this the same way. */
2211 subpk->flags.revoked = 1;
2212 sig_to_revoke_info (sig, &subpk->revoked);
2213 /* Although we could stop now, we continue to
2214 * figure out other information like the old expiration
2217 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
2219 if (sig->flags.expired)
2220 ; /* Signature has expired - ignore it. */
2223 sigdate = sig->timestamp;
2225 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2232 /* No valid key binding. */
2236 sig = signode->pkt->pkt.signature;
2237 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
2239 key_usage = parse_key_usage (sig);
2242 /* No key flags at all: get it from the algo. */
2243 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
2247 /* Check that the usage matches the usage as given by the algo. */
2248 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
2249 if (x) /* Mask it down to the actual allowed usage. */
2253 subpk->pubkey_usage = key_usage;
2255 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2256 if (p && buf32_to_u32 (p))
2257 key_expire = keytimestamp + buf32_to_u32 (p);
2260 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
2261 subpk->expiredate = key_expire;
2263 /* Algo doesn't exist. */
2264 if (openpgp_pk_test_algo (subpk->pubkey_algo))
2267 subpk->flags.valid = 1;
2269 /* Find the most recent 0x19 embedded signature on our self-sig. */
2270 if (!subpk->flags.backsig)
2274 PKT_signature *backsig = NULL;
2278 /* We do this while() since there may be other embedded
2279 signatures in the future. We only want 0x19 here. */
2281 while ((p = enum_sig_subpkt (sig->hashed,
2282 SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
2284 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2286 PKT_signature *tempsig = buf_to_sig (p, n);
2289 if (tempsig->timestamp > sigdate)
2292 free_seckey_enc (backsig);
2295 sigdate = backsig->timestamp;
2298 free_seckey_enc (tempsig);
2304 /* It is safe to have this in the unhashed area since the 0x19
2305 is located on the selfsig for convenience, not security. */
2307 while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
2310 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2312 PKT_signature *tempsig = buf_to_sig (p, n);
2315 if (tempsig->timestamp > sigdate)
2318 free_seckey_enc (backsig);
2321 sigdate = backsig->timestamp;
2324 free_seckey_enc (tempsig);
2330 /* At this point, backsig contains the most recent 0x19 sig.
2331 Let's see if it is good. */
2333 /* 2==valid, 1==invalid, 0==didn't check */
2334 if (check_backsig (mainpk, subpk, backsig) == 0)
2335 subpk->flags.backsig = 2;
2337 subpk->flags.backsig = 1;
2339 free_seckey_enc (backsig);
2345 /* Merge information from the self-signatures with the public key,
2346 subkeys and user ids to make using them more easy.
2348 See documentation for merge_selfsigs_main, merge_selfsigs_subkey
2349 and fixup_uidnode for exactly which fields are updated. */
2351 merge_selfsigs (KBNODE keyblock)
2355 struct revoke_info rinfo;
2356 PKT_public_key *main_pk;
2358 unsigned int mdc_feature;
2360 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2362 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
2364 log_error ("expected public key but found secret key "
2366 /* We better exit here because a public key is expected at
2367 other places too. FIXME: Figure this out earlier and
2368 don't get to here at all */
2374 merge_selfsigs_main (keyblock, &revoked, &rinfo);
2376 /* Now merge in the data from each of the subkeys. */
2377 for (k = keyblock; k; k = k->next)
2379 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2381 merge_selfsigs_subkey (keyblock, k);
2385 main_pk = keyblock->pkt->pkt.public_key;
2386 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
2388 /* If the primary key is revoked, expired, or invalid we
2389 * better set the appropriate flags on that key and all
2391 for (k = keyblock; k; k = k->next)
2393 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2394 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2396 PKT_public_key *pk = k->pkt->pkt.public_key;
2397 if (!main_pk->flags.valid)
2398 pk->flags.valid = 0;
2399 if (revoked && !pk->flags.revoked)
2401 pk->flags.revoked = revoked;
2402 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
2404 if (main_pk->has_expired)
2405 pk->has_expired = main_pk->has_expired;
2411 /* Set the preference list of all keys to those of the primary real
2412 * user ID. Note: we use these preferences when we don't know by
2413 * which user ID the key has been selected.
2414 * fixme: we should keep atoms of commonly used preferences or
2415 * use reference counting to optimize the preference lists storage.
2416 * FIXME: it might be better to use the intersection of
2418 * Do a similar thing for the MDC feature flag. */
2421 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2423 if (k->pkt->pkttype == PKT_USER_ID
2424 && !k->pkt->pkt.user_id->attrib_data
2425 && k->pkt->pkt.user_id->is_primary)
2427 prefs = k->pkt->pkt.user_id->prefs;
2428 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2432 for (k = keyblock; k; k = k->next)
2434 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2435 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2437 PKT_public_key *pk = k->pkt->pkt.public_key;
2440 pk->prefs = copy_prefs (prefs);
2441 pk->flags.mdc = mdc_feature;
2448 /* See whether the key satisfies any additional requirements specified
2449 in CTX. If so, return 1 and set CTX->FOUND_KEY to an appropriate
2450 key or subkey. Otherwise, return 0 if there was no appropriate
2453 In case the primary key is not required, select a suitable subkey.
2454 We need the primary key if PUBKEY_USAGE_CERT is set in
2455 CTX->REQ_USAGE or we are in PGP6 or PGP7 mode and PUBKEY_USAGE_SIG
2456 is set in CTX->REQ_USAGE.
2458 If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
2459 are set in CTX->REQ_USAGE, we filter by the key's function.
2460 Concretely, if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then
2461 we only return a key if it is (at least) either a signing or a
2464 If CTX->REQ_USAGE is set, then we reject any keys that are not good
2465 (i.e., valid, not revoked, not expired, etc.). This allows the
2466 getkey functions to be used for plain key listings.
2468 Sets the matched key's user id field (pk->user_id) to the user id
2469 that matched the low-level search criteria or NULL.
2472 This function needs to handle several different cases:
2474 1. No requested usage and no primary key requested
2475 Examples for this case are that we have a keyID to be used
2476 for decrytion or verification.
2477 2. No usage but primary key requested
2478 This is the case for all functions which work on an
2479 entire keyblock, e.g. for editing or listing
2480 3. Usage and primary key requested
2482 4. Usage but no primary key requested
2487 finish_lookup (GETKEY_CTX ctx, KBNODE keyblock)
2491 /* If CTX->EXACT is set, the key or subkey that actually matched the
2492 low-level search criteria. */
2493 KBNODE foundk = NULL;
2494 /* The user id (if any) that matched the low-level search criteria. */
2495 PKT_user_id *foundu = NULL;
2497 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2498 unsigned int req_usage = (ctx->req_usage & USAGE_MASK);
2500 /* Request the primary if we're certifying another key, and also
2501 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2502 do not understand signatures made by a signing subkey. PGP 8
2504 int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2505 ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2507 u32 curtime = make_timestamp ();
2512 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
2515 /* Get the key or subkey that matched the low-level search
2518 for (k = keyblock; k; k = k->next)
2522 assert (k->pkt->pkttype == PKT_PUBLIC_KEY
2523 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
2530 /* Get the user id that matched that low-level search criteria. */
2531 for (k = keyblock; k; k = k->next)
2535 assert (k->pkt->pkttype == PKT_USER_ID);
2536 foundu = k->pkt->pkt.user_id;
2542 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2543 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
2544 foundk ? "one" : "all", req_usage);
2548 latest_key = foundk ? foundk : keyblock;
2554 /* Set latest_key to the latest (the one with the most recent
2555 timestamp) good (valid, not revoked, not expired, etc.) subkey.
2557 Don't bother if we are only looking for a primary key or we need
2558 an exact match and the exact match is not a subkey. */
2559 if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
2565 /* Either start a loop or check just this one subkey. */
2566 for (k = foundk ? foundk : keyblock; k; k = nextk)
2571 /* If FOUNDK is not NULL, then only consider that exact
2572 key, i.e., don't iterate. */
2577 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2580 pk = k->pkt->pkt.public_key;
2582 log_debug ("\tchecking subkey %08lX\n",
2583 (ulong) keyid_from_pk (pk, NULL));
2584 if (!pk->flags.valid)
2587 log_debug ("\tsubkey not valid\n");
2590 if (pk->flags.revoked)
2593 log_debug ("\tsubkey has been revoked\n");
2596 if (pk->has_expired)
2599 log_debug ("\tsubkey has expired\n");
2602 if (pk->timestamp > curtime && !opt.ignore_valid_from)
2605 log_debug ("\tsubkey not yet valid\n");
2609 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2612 log_debug ("\tusage does not match: want=%x have=%x\n",
2613 req_usage, pk->pubkey_usage);
2618 log_debug ("\tsubkey might be fine\n");
2619 /* In case a key has a timestamp of 0 set, we make sure
2620 that it is used. A better change would be to compare
2621 ">=" but that might also change the selected keys and
2622 is as such a more intrusive change. */
2623 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2625 latest_date = pk->timestamp;
2631 /* Check if the primary key is ok (valid, not revoke, not expire,
2632 matches requested usage) if:
2634 - we didn't find an appropriate subkey and we're not doing an
2637 - we're doing an exact match and the exact match was the
2640 - we're just considering the primary key. */
2641 if ((!latest_key && !ctx->exact) || foundk == keyblock || req_prim)
2644 if (DBG_LOOKUP && !foundk && !req_prim)
2645 log_debug ("\tno suitable subkeys found - trying primary\n");
2646 pk = keyblock->pkt->pkt.public_key;
2647 if (!pk->flags.valid)
2650 log_debug ("\tprimary key not valid\n");
2652 else if (pk->flags.revoked)
2655 log_debug ("\tprimary key has been revoked\n");
2657 else if (pk->has_expired)
2660 log_debug ("\tprimary key has expired\n");
2662 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2665 log_debug ("\tprimary key usage does not match: "
2666 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
2671 log_debug ("\tprimary key may be used\n");
2672 latest_key = keyblock;
2673 latest_date = pk->timestamp;
2680 log_debug ("\tno suitable key found - giving up\n");
2681 return NULL; /* Not found. */
2686 log_debug ("\tusing key %08lX\n",
2687 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
2691 PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2693 free_user_id (pk->user_id);
2694 pk->user_id = scopy_user_id (foundu);
2697 if (latest_key != keyblock && opt.verbose)
2700 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
2701 log_info (_("using subkey %s instead of primary key %s\n"),
2702 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
2706 cache_user_id (keyblock);
2708 return latest_key ? latest_key : keyblock; /* Found. */
2712 /* A high-level function to lookup keys.
2714 This function builds on top of the low-level keydb API. It first
2715 searches the database using the description stored in CTX->ITEMS,
2716 then it filters the results using CTX and, finally, if WANT_SECRET
2717 is set, it ignores any keys for which no secret key is available.
2719 Unlike the low-level search functions, this function also merges
2720 all of the self-signed data into the keys, subkeys and user id
2721 packets (see the merge_selfsigs for details).
2723 On success the key's keyblock is stored at *RET_KEYBLOCK. */
2725 lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, kbnode_t *ret_found_key,
2729 int no_suitable_key = 0;
2730 KBNODE keyblock = NULL;
2731 KBNODE found_key = NULL;
2735 rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
2739 /* If we are iterating over the entire database, then we need to
2740 change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
2741 reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next
2743 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2744 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2746 rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
2749 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
2754 if (want_secret && agent_probe_any_secret_key (NULL, keyblock))
2755 goto skip; /* No secret key available. */
2757 /* Warning: node flag bits 0 and 1 should be preserved by
2758 * merge_selfsigs. For secret keys, premerge transferred the
2759 * keys to the keyblock. */
2760 merge_selfsigs (keyblock);
2761 found_key = finish_lookup (ctx, keyblock);
2764 no_suitable_key = 0;
2768 no_suitable_key = 1;
2771 /* Release resources and continue search. */
2772 release_kbnode (keyblock);
2774 /* The keyblock cache ignores the current "file position".
2775 Thus, if we request the next result and the cache matches
2776 (and it will since it is what we just looked for), we'll get
2777 the same entry back! We can avoid this infinite loop by
2778 disabling the cache. */
2779 keydb_disable_caching (ctx->kr_handle);
2783 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
2784 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
2788 *ret_keyblock = keyblock; /* Return the keyblock. */
2791 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
2792 rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
2793 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2794 rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
2796 release_kbnode (keyblock);
2801 *ret_found_key = found_key;
2803 *ret_found_key = NULL;
2810 /* For documentation see keydb.h. */
2812 enum_secret_keys (ctrl_t ctrl, void **context, PKT_public_key *sk)
2814 gpg_error_t err = 0;
2827 /* Make a new context. */
2828 c = xtrycalloc (1, sizeof *c);
2830 return gpg_error_from_syserror ();
2836 /* Free the context. */
2837 release_kbnode (c->keyblock);
2844 return gpg_error (GPG_ERR_EOF);
2848 /* Loop until we have a keyblock. */
2849 while (!c->keyblock)
2851 /* Loop over the list of secret keys. */
2857 case 0: /* First try to use the --default-key. */
2858 name = parse_def_secret_key (ctrl);
2862 case 1: /* Init list of keys to try. */
2863 c->sl = opt.secret_keys_to_try;
2867 case 2: /* Get next item from list. */
2871 c->sl = c->sl->next;
2877 default: /* No more names to check - stop. */
2879 return gpg_error (GPG_ERR_EOF);
2882 while (!name || !*name);
2884 err = getkey_byname (ctrl, NULL, NULL, name, 1, &c->keyblock);
2887 /* getkey_byname might return a keyblock even in the
2888 error case - I have not checked. Thus better release
2890 release_kbnode (c->keyblock);
2894 c->node = c->keyblock;
2897 /* Get the next key from the current keyblock. */
2898 for (; c->node; c->node = c->node->next)
2900 if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
2901 || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2903 copy_public_key (sk, c->node->pkt->pkt.public_key);
2904 c->node = c->node->next;
2905 return 0; /* Found. */
2909 /* Dispose the keyblock and continue. */
2910 release_kbnode (c->keyblock);
2916 /*********************************************
2917 *********** User ID printing helpers *******
2918 *********************************************/
2920 /* Return a string with a printable representation of the user_id.
2921 * this string must be freed by xfree. */
2923 get_user_id_string (u32 * keyid, int mode, size_t *r_len)
2930 /* Try it two times; second pass reads from the database. */
2933 for (r = user_id_db; r; r = r->next)
2935 for (a = r->keyids; a; a = a->next)
2937 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
2941 /* An empty string as user id is possible. Make
2942 sure that the malloc allocates one byte and
2943 does not bail out. */
2944 p = xmalloc (r->len? r->len : 1);
2945 memcpy (p, r->name, r->len);
2952 p = xasprintf ("%08lX%08lX %.*s",
2953 (ulong) keyid[0], (ulong) keyid[1],
2956 p = xasprintf ("%s %.*s", keystr (keyid),
2959 *r_len = strlen (p);
2967 while (++pass < 2 && !get_pubkey (NULL, keyid));
2970 p = xstrdup (user_id_not_found_utf8 ());
2972 p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
2974 p = xasprintf ("%s [?]", keystr (keyid));
2977 *r_len = strlen (p);
2983 get_user_id_string_native (u32 * keyid)
2985 char *p = get_user_id_string (keyid, 0, NULL);
2986 char *p2 = utf8_to_native (p, strlen (p), 0);
2993 get_long_user_id_string (u32 * keyid)
2995 return get_user_id_string (keyid, 1, NULL);
2999 /* Please try to use get_user_byfpr instead of this one. */
3001 get_user_id (u32 * keyid, size_t * rn)
3003 return get_user_id_string (keyid, 2, rn);
3007 /* Please try to use get_user_id_byfpr_native instead of this one. */
3009 get_user_id_native (u32 * keyid)
3012 char *p = get_user_id (keyid, &rn);
3013 char *p2 = utf8_to_native (p, rn, 0);
3019 /* Return the user id for a key designated by its fingerprint, FPR,
3020 which must be MAX_FINGERPRINT_LEN bytes in size. Note: the
3021 returned string, which must be freed using xfree, may not be NUL
3022 terminated. To determine the length of the string, you must use
3025 get_user_id_byfpr (const byte *fpr, size_t *rn)
3031 /* Try it two times; second pass reads from the database. */
3034 for (r = user_id_db; r; r = r->next)
3037 for (a = r->keyids; a; a = a->next)
3039 if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
3041 /* An empty string as user id is possible. Make
3042 sure that the malloc allocates one byte and does
3044 p = xmalloc (r->len? r->len : 1);
3045 memcpy (p, r->name, r->len);
3053 && !get_pubkey_byfprint (NULL, NULL, fpr, MAX_FINGERPRINT_LEN));
3054 p = xstrdup (user_id_not_found_utf8 ());
3059 /* Like get_user_id_byfpr, but convert the string to the native
3060 encoding. The returned string needs to be freed. Unlike
3061 get_user_id_byfpr, the returned string is NUL terminated. */
3063 get_user_id_byfpr_native (const byte *fpr)
3066 char *p = get_user_id_byfpr (fpr, &rn);
3067 char *p2 = utf8_to_native (p, rn, 0);
3074 /* For documentation see keydb.h. */
3076 get_ctx_handle (GETKEY_CTX ctx)
3078 return ctx->kr_handle;
3082 free_akl (struct akl *akl)
3088 free_keyserver_spec (akl->spec);
3096 while (opt.auto_key_locate)
3098 struct akl *akl2 = opt.auto_key_locate;
3099 opt.auto_key_locate = opt.auto_key_locate->next;
3104 /* Returns false on error. */
3106 parse_auto_key_locate (char *options)
3110 while ((tok = optsep (&options)))
3112 struct akl *akl, *check, *last = NULL;
3118 akl = xmalloc_clear (sizeof (*akl));
3120 if (ascii_strcasecmp (tok, "clear") == 0)
3123 free_akl (opt.auto_key_locate);
3124 opt.auto_key_locate = NULL;
3127 else if (ascii_strcasecmp (tok, "nodefault") == 0)
3128 akl->type = AKL_NODEFAULT;
3129 else if (ascii_strcasecmp (tok, "local") == 0)
3130 akl->type = AKL_LOCAL;
3131 else if (ascii_strcasecmp (tok, "ldap") == 0)
3132 akl->type = AKL_LDAP;
3133 else if (ascii_strcasecmp (tok, "keyserver") == 0)
3134 akl->type = AKL_KEYSERVER;
3136 else if (ascii_strcasecmp (tok, "cert") == 0)
3137 akl->type = AKL_CERT;
3139 else if (ascii_strcasecmp (tok, "pka") == 0)
3140 akl->type = AKL_PKA;
3141 else if (ascii_strcasecmp (tok, "dane") == 0)
3142 akl->type = AKL_DANE;
3143 else if ((akl->spec = parse_keyserver_uri (tok, 1)))
3144 akl->type = AKL_SPEC;
3151 /* We must maintain the order the user gave us */
3152 for (check = opt.auto_key_locate; check;
3153 last = check, check = check->next)
3155 /* Check for duplicates */
3156 if (check->type == akl->type
3157 && (akl->type != AKL_SPEC
3158 || (akl->type == AKL_SPEC
3159 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
3172 opt.auto_key_locate = akl;
3180 /* Returns true if a secret key is available for the public key with
3181 key id KEYID; returns false if not. This function ignores legacy
3182 keys. Note: this is just a fast check and does not tell us whether
3183 the secret key is valid; this check merely indicates whether there
3184 is some secret key with the specified key id. */
3186 have_secret_key_with_kid (u32 *keyid)
3190 KEYDB_SEARCH_DESC desc;
3195 kdbhd = keydb_new ();
3198 memset (&desc, 0, sizeof desc);
3199 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
3200 desc.u.kid[0] = keyid[0];
3201 desc.u.kid[1] = keyid[1];
3204 err = keydb_search (kdbhd, &desc, 1, NULL);
3208 err = keydb_get_keyblock (kdbhd, &keyblock);
3211 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
3215 for (node = keyblock; node; node = node->next)
3217 /* Bit 0 of the flags is set if the search found the key
3218 using that key or subkey. Note: a search will only ever
3219 match a single key or subkey. */
3220 if ((node->flag & 1))
3222 assert (node->pkt->pkttype == PKT_PUBLIC_KEY
3223 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3225 if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
3226 result = 1; /* Secret key available. */
3233 release_kbnode (keyblock);
3236 keydb_release (kdbhd);