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 /* Part of the search criteria: The low-level search specification
81 as passed to keydb_search. */
83 /* This must be the last element in the structure. When we allocate
84 the structure, we allocate it so that ITEMS can hold NITEMS. */
85 KEYDB_SEARCH_DESC items[1];
98 typedef struct keyid_list
100 struct keyid_list *next;
101 char fpr[MAX_FINGERPRINT_LEN];
106 #if MAX_PK_CACHE_ENTRIES
107 typedef struct pk_cache_entry
109 struct pk_cache_entry *next;
113 static pk_cache_entry_t pk_cache;
114 static int pk_cache_entries; /* Number of entries in pk cache. */
115 static int pk_cache_disabled;
118 #if MAX_UID_CACHE_ENTRIES < 5
119 #error we really need the userid cache
121 typedef struct user_id_db
123 struct user_id_db *next;
128 static user_id_db_t user_id_db;
129 static int uid_cache_entries; /* Number of entries in uid cache. */
131 static void merge_selfsigs (kbnode_t keyblock);
132 static int lookup (getkey_ctx_t ctx,
133 kbnode_t *ret_keyblock, kbnode_t *ret_found_key,
141 for (i = 0; i < DIM (lkup_stats); i++)
143 if (lkup_stats[i].any)
144 es_fprintf (es_stderr,
145 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
147 lkup_stats[i].okay_count,
148 lkup_stats[i].nokey_count, lkup_stats[i].error_count);
154 /* For documentation see keydb.h. */
156 cache_public_key (PKT_public_key * pk)
158 #if MAX_PK_CACHE_ENTRIES
159 pk_cache_entry_t ce, ce2;
162 if (pk_cache_disabled)
165 if (pk->flags.dont_cache)
168 if (is_ELGAMAL (pk->pubkey_algo)
169 || pk->pubkey_algo == PUBKEY_ALGO_DSA
170 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
171 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
172 || pk->pubkey_algo == PUBKEY_ALGO_ECDH
173 || is_RSA (pk->pubkey_algo))
175 keyid_from_pk (pk, keyid);
178 return; /* Don't know how to get the keyid. */
180 for (ce = pk_cache; ce; ce = ce->next)
181 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
184 log_debug ("cache_public_key: already in cache\n");
188 if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
192 /* Remove the last 50% of the entries. */
193 for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
195 if (ce != pk_cache && ce->next)
203 free_public_key (ce->pk);
208 assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
211 ce = xmalloc (sizeof *ce);
214 ce->pk = copy_public_key (NULL, pk);
215 ce->keyid[0] = keyid[0];
216 ce->keyid[1] = keyid[1];
221 /* Return a const utf-8 string with the text "[User ID not found]".
222 This function is required so that we don't need to switch gettext's
223 encoding temporary. */
225 user_id_not_found_utf8 (void)
230 text = native_to_utf8 (_("[User ID not found]"));
236 /* Return the user ID from the given keyblock.
237 * We use the primary uid flag which has been set by the merge_selfsigs
238 * function. The returned value is only valid as long as the given
239 * keyblock is not changed. */
241 get_primary_uid (KBNODE keyblock, size_t * uidlen)
246 for (k = keyblock; k; k = k->next)
248 if (k->pkt->pkttype == PKT_USER_ID
249 && !k->pkt->pkt.user_id->attrib_data
250 && k->pkt->pkt.user_id->is_primary)
252 *uidlen = k->pkt->pkt.user_id->len;
253 return k->pkt->pkt.user_id->name;
256 s = user_id_not_found_utf8 ();
257 *uidlen = strlen (s);
263 release_keyid_list (keyid_list_t k)
267 keyid_list_t k2 = k->next;
274 * Store the association of keyid and userid
275 * Feed only public keys to this function.
278 cache_user_id (KBNODE keyblock)
283 keyid_list_t keyids = NULL;
286 for (k = keyblock; k; k = k->next)
288 if (k->pkt->pkttype == PKT_PUBLIC_KEY
289 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
291 keyid_list_t a = xmalloc_clear (sizeof *a);
292 /* Hmmm: For a long list of keyids it might be an advantage
293 * to append the keys. */
294 fingerprint_from_pk (k->pkt->pkt.public_key, a->fpr, NULL);
295 keyid_from_pk (k->pkt->pkt.public_key, a->keyid);
296 /* First check for duplicates. */
297 for (r = user_id_db; r; r = r->next)
299 keyid_list_t b = r->keyids;
300 for (b = r->keyids; b; b = b->next)
302 if (!memcmp (b->fpr, a->fpr, MAX_FINGERPRINT_LEN))
305 log_debug ("cache_user_id: already in cache\n");
306 release_keyid_list (keyids);
312 /* Now put it into the cache. */
318 BUG (); /* No key no fun. */
321 uid = get_primary_uid (keyblock, &uidlen);
323 if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES)
325 /* fixme: use another algorithm to free some cache slots */
327 user_id_db = r->next;
328 release_keyid_list (r->keyids);
332 r = xmalloc (sizeof *r + uidlen - 1);
335 memcpy (r->name, uid, r->len);
336 r->next = user_id_db;
342 /* For documentation see keydb.h. */
344 getkey_disable_caches ()
346 #if MAX_PK_CACHE_ENTRIES
348 pk_cache_entry_t ce, ce2;
350 for (ce = pk_cache; ce; ce = ce2)
353 free_public_key (ce->pk);
356 pk_cache_disabled = 1;
357 pk_cache_entries = 0;
361 /* fixme: disable user id cache ? */
366 pk_from_block (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE keyblock,
369 KBNODE a = found_key ? found_key : keyblock;
373 assert (a->pkt->pkttype == PKT_PUBLIC_KEY
374 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
376 copy_public_key (pk, a->pkt->pkt.public_key);
380 /* For documentation see keydb.h. */
382 get_pubkey (PKT_public_key * pk, u32 * keyid)
387 #if MAX_PK_CACHE_ENTRIES
390 /* Try to get it from the cache. We don't do this when pk is
391 NULL as it does not guarantee that the user IDs are
394 for (ce = pk_cache; ce; ce = ce->next)
396 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
397 /* XXX: We don't check PK->REQ_USAGE here, but if we don't
398 read from the cache, we do check it! */
400 copy_public_key (pk, ce->pk);
406 /* More init stuff. */
409 pk = xmalloc_clear (sizeof *pk);
416 struct getkey_ctx_s ctx;
418 KBNODE found_key = NULL;
419 memset (&ctx, 0, sizeof ctx);
420 ctx.exact = 1; /* Use the key ID exactly as given. */
421 ctx.not_allocated = 1;
422 ctx.kr_handle = keydb_new ();
424 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
425 ctx.items[0].u.kid[0] = keyid[0];
426 ctx.items[0].u.kid[1] = keyid[1];
427 ctx.req_usage = pk->req_usage;
428 rc = lookup (&ctx, &kb, &found_key, 0);
431 pk_from_block (&ctx, pk, kb, found_key);
439 rc = GPG_ERR_NO_PUBKEY;
443 cache_public_key (pk);
445 free_public_key (pk);
450 /* For documentation see keydb.h. */
452 get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
460 #if MAX_PK_CACHE_ENTRIES
462 /* Try to get it from the cache */
465 for (ce = pk_cache; ce; ce = ce->next)
467 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]
468 /* Only consider primary keys. */
469 && ce->pk->keyid[0] == ce->pk->main_keyid[0]
470 && ce->pk->keyid[1] == ce->pk->main_keyid[1])
473 copy_public_key (pk, ce->pk);
481 rc = keydb_search_kid (hd, keyid);
482 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
485 return GPG_ERR_NO_PUBKEY;
487 rc = keydb_get_keyblock (hd, &keyblock);
491 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
492 return GPG_ERR_NO_PUBKEY;
495 assert (keyblock && keyblock->pkt
496 && keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
498 /* We return the primary key. If KEYID matched a subkey, then we
500 keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
501 if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
502 copy_public_key (pk, keyblock->pkt->pkt.public_key);
504 rc = GPG_ERR_NO_PUBKEY;
506 release_kbnode (keyblock);
508 /* Not caching key here since it won't have all of the fields
515 /* For documentation see keydb.h. */
517 get_pubkeyblock (u32 * keyid)
519 struct getkey_ctx_s ctx;
521 KBNODE keyblock = NULL;
523 memset (&ctx, 0, sizeof ctx);
524 /* No need to set exact here because we want the entire block. */
525 ctx.not_allocated = 1;
526 ctx.kr_handle = keydb_new ();
528 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
529 ctx.items[0].u.kid[0] = keyid[0];
530 ctx.items[0].u.kid[1] = keyid[1];
531 rc = lookup (&ctx, &keyblock, NULL, 0);
534 return rc ? NULL : keyblock;
538 /* For documentation see keydb.h. */
540 get_seckey (PKT_public_key *pk, u32 *keyid)
543 struct getkey_ctx_s ctx;
544 kbnode_t keyblock = NULL;
545 kbnode_t found_key = NULL;
547 memset (&ctx, 0, sizeof ctx);
548 ctx.exact = 1; /* Use the key ID exactly as given. */
549 ctx.not_allocated = 1;
550 ctx.kr_handle = keydb_new ();
552 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
553 ctx.items[0].u.kid[0] = keyid[0];
554 ctx.items[0].u.kid[1] = keyid[1];
555 ctx.req_usage = pk->req_usage;
556 err = lookup (&ctx, &keyblock, &found_key, 1);
559 pk_from_block (&ctx, pk, keyblock, found_key);
562 release_kbnode (keyblock);
566 err = agent_probe_secret_key (/*ctrl*/NULL, pk);
568 release_public_key_parts (pk);
575 /* Skip unusable keys. A key is unusable if it is revoked, expired or
576 disabled or if the selected user id is revoked or expired. */
578 skip_unusable (void *dummy, u32 * keyid, int uid_no)
586 keyblock = get_pubkeyblock (keyid);
589 log_error ("error checking usability status of %s\n", keystr (keyid));
593 pk = keyblock->pkt->pkt.public_key;
595 /* Is the key revoked or expired? */
596 if (pk->flags.revoked || pk->has_expired)
599 /* Is the user ID in question revoked or expired? */
600 if (!unusable && uid_no)
605 for (node = keyblock; node; node = node->next)
607 if (node->pkt->pkttype == PKT_USER_ID)
609 PKT_user_id *user_id = node->pkt->pkt.user_id;
612 if (uids_seen != uid_no)
615 if (user_id->is_revoked || user_id->is_expired)
622 /* If UID_NO is non-zero, then the keyblock better have at least
624 assert (uids_seen == uid_no);
628 unusable = pk_is_disabled (pk);
631 release_kbnode (keyblock);
636 /* Search for keys matching some criteria.
638 If RETCTX is not NULL, then the constructed context is returned in
639 *RETCTX so that getpubkey_next can be used to get subsequent
640 results. In this case, getkey_end() must be used to free the
641 search context. If RETCTX is not NULL, then RET_KDBHD must be
644 If NAMELIST is not NULL, then a search query is constructed using
645 classify_user_id on each of the strings in the list. (Recall: the
646 database does an OR of the terms, not an AND.) If NAMELIST is
647 NULL, then all results are returned.
649 If PK is not NULL, the public key of the first result is returned
650 in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
651 set, it is used to filter the search results. See the
652 documentation for finish_lookup to understand exactly how this is
653 used. Note: The self-signed data has already been merged into the
654 public key using merge_selfsigs. Free *PK by calling
655 release_public_key_parts (or, if PK was allocated using xfree, you
656 can use free_public_key, which calls release_public_key_parts(PK)
659 If WANT_SECRET is set, then only keys with an available secret key
660 (either locally or via key registered on a smartcard) are returned.
662 If INCLUDE_UNUSABLE is set, then unusable keys (see the
663 documentation for skip_unusable for an exact definition) are
664 skipped unless they are looked up by key id or by fingerprint.
666 If RET_KB is not NULL, the keyblock is returned in *RET_KB. This
667 should be freed using release_kbnode().
669 If RET_KDBHD is not NULL, then the new database handle used to
670 conduct the search is returned in *RET_KDBHD. This can be used to
671 get subsequent results using keydb_search_next. Note: in this
672 case, no advanced filtering is done for subsequent results (e.g.,
673 WANT_SECRET and PK->REQ_USAGE are not respected).
675 This function returns 0 on success. Otherwise, an error code is
676 returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
677 (if want_secret is set) is returned if the key is not found. */
679 key_byname (GETKEY_CTX *retctx, strlist_t namelist,
681 int want_secret, int include_unusable,
682 KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
688 KBNODE help_kb = NULL;
689 KBNODE found_key = NULL;
693 /* Reset the returned context in case of error. */
694 assert (!ret_kdbhd); /* Not allowed because the handle is stored
702 /* No search terms: iterate over the whole DB. */
704 ctx = xmalloc_clear (sizeof *ctx);
706 ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
707 if (!include_unusable)
708 ctx->items[0].skipfnc = skip_unusable;
712 /* Build the search context. */
713 for (n = 0, r = namelist; r; r = r->next)
716 /* CTX has space for a single search term at the end. Thus, we
717 need to allocate sizeof *CTX plus (n - 1) sizeof
719 ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
722 for (n = 0, r = namelist; r; r = r->next, n++)
726 err = classify_user_id (r->d, &ctx->items[n], 1);
728 if (ctx->items[n].exact)
733 return gpg_err_code (err); /* FIXME: remove gpg_err_code. */
735 if (!include_unusable
736 && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
737 && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
738 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
739 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
740 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
741 ctx->items[n].skipfnc = skip_unusable;
745 ctx->want_secret = want_secret;
746 ctx->kr_handle = keydb_new ();
752 ctx->req_usage = pk->req_usage;
755 rc = lookup (ctx, ret_kb, &found_key, want_secret);
758 pk_from_block (ctx, pk, *ret_kb, found_key);
761 release_kbnode (help_kb);
763 if (retctx) /* Caller wants the context. */
769 *ret_kdbhd = ctx->kr_handle;
770 ctx->kr_handle = NULL;
779 /* For documentation see keydb.h. */
781 get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
782 const char *name, KBNODE * ret_keyblock,
783 KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
786 strlist_t namelist = NULL;
790 int anylocalfirst = 0;
795 /* Does NAME appear to be a mailbox (mail address)? */
796 is_mbox = is_valid_mailbox (name);
798 /* The auto-key-locate feature works as follows: there are a number
799 of methods to look up keys. By default, the local keyring is
800 tried first. Then, each method listed in the --auto-key-locate is
801 tried in the order it appears.
803 This can be changed as follows:
805 - if nodefault appears anywhere in the list of options, then
806 the local keyring is not tried first, or,
808 - if local appears anywhere in the list of options, then the
809 local keyring is not tried first, but in the order in which
810 it was listed in the --auto-key-locate option.
812 Note: we only save the search context in RETCTX if the local
813 method is the first method tried (either explicitly or
816 /* auto-key-locate is enabled. */
818 /* nodefault is true if "nodefault" or "local" appear. */
819 for (akl = opt.auto_key_locate; akl; akl = akl->next)
820 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
825 /* anylocalfirst is true if "local" appears before any other
826 search methods (except "nodefault"). */
827 for (akl = opt.auto_key_locate; akl; akl = akl->next)
828 if (akl->type != AKL_NODEFAULT)
830 if (akl->type == AKL_LOCAL)
837 /* "nodefault" didn't occur. Thus, "local" is implicitly the
838 first method to try. */
841 if (nodefault && is_mbox)
842 /* Either "nodefault" or "local" (explicitly) appeared in the auto
843 key locate list and NAME appears to be an email address. Don't
844 try the local keyring. */
846 rc = GPG_ERR_NO_PUBKEY;
849 /* Either "nodefault" and "local" don't appear in the auto key
850 locate list (in which case we try the local keyring first) or
851 NAME does not appear to be an email address (in which case we
852 only try the local keyring). In this case, lookup NAME in the
855 add_to_strlist (&namelist, name);
856 rc = key_byname (retctx, namelist, pk, 0,
857 include_unusable, ret_keyblock, ret_kdbhd);
860 /* If the requested name resembles a valid mailbox and automatic
861 retrieval has been enabled, we try to import the key. */
862 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && !no_akl && is_mbox)
863 /* NAME wasn't present in the local keyring (or we didn't try the
864 local keyring). Since the auto key locate feature is enabled
865 and NAME appears to be an email address, try the auto locate
868 for (akl = opt.auto_key_locate; akl; akl = akl->next)
870 unsigned char *fpr = NULL;
872 int did_key_byname = 0;
873 int no_fingerprint = 0;
874 const char *mechanism = "?";
879 /* This is a dummy mechanism. */
881 rc = GPG_ERR_NO_PUBKEY;
889 getkey_end (*retctx);
892 add_to_strlist (&namelist, name);
893 rc = key_byname (anylocalfirst ? retctx : NULL,
895 include_unusable, ret_keyblock, ret_kdbhd);
899 mechanism = "DNS CERT";
900 glo_ctrl.in_auto_key_retrieve++;
901 rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len);
902 glo_ctrl.in_auto_key_retrieve--;
907 glo_ctrl.in_auto_key_retrieve++;
908 rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
909 glo_ctrl.in_auto_key_retrieve--;
914 glo_ctrl.in_auto_key_retrieve++;
915 rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len);
916 glo_ctrl.in_auto_key_retrieve--;
921 glo_ctrl.in_auto_key_retrieve++;
922 rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
923 glo_ctrl.in_auto_key_retrieve--;
927 /* Strictly speaking, we don't need to only use a valid
928 mailbox for the getname search, but it helps cut down
929 on the problem of searching for something like "john"
930 and getting a whole lot of keys back. */
933 mechanism = opt.keyserver->uri;
934 glo_ctrl.in_auto_key_retrieve++;
935 rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
937 glo_ctrl.in_auto_key_retrieve--;
941 mechanism = "Unconfigured keyserver";
942 rc = GPG_ERR_NO_PUBKEY;
948 struct keyserver_spec *keyserver;
950 mechanism = akl->spec->uri;
951 keyserver = keyserver_match (akl->spec);
952 glo_ctrl.in_auto_key_retrieve++;
953 rc = keyserver_import_name (ctrl,
954 name, &fpr, &fpr_len, keyserver);
955 glo_ctrl.in_auto_key_retrieve--;
960 /* Use the fingerprint of the key that we actually fetched.
961 This helps prevent problems where the key that we fetched
962 doesn't have the same name that we used to fetch it. In
963 the case of CERT and PKA, this is an actual security
964 requirement as the URL might point to a key put in by an
965 attacker. By forcing the use of the fingerprint, we
966 won't use the attacker's key here. */
969 char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
971 assert (fpr_len <= MAX_FINGERPRINT_LEN);
973 free_strlist (namelist);
976 bin2hex (fpr, fpr_len, fpr_string);
979 log_info ("auto-key-locate found fingerprint %s\n",
982 add_to_strlist (&namelist, fpr_string);
984 else if (!rc && !fpr && !did_key_byname)
985 /* The acquisition method said no failure occured, but it
986 didn't return a fingerprint. That's a failure. */
989 rc = GPG_ERR_NO_PUBKEY;
994 if (!rc && !did_key_byname)
995 /* There was no error and we didn't do a local lookup.
996 This means that we imported a key into the local
997 keyring. Try to read the imported key from the
1002 getkey_end (*retctx);
1005 rc = key_byname (anylocalfirst ? retctx : NULL,
1007 include_unusable, ret_keyblock, ret_kdbhd);
1012 log_info (_("automatically retrieved '%s' via %s\n"),
1016 if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1017 || opt.verbose || no_fingerprint)
1018 log_info (_("error retrieving '%s' via %s: %s\n"),
1020 no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
1027 getkey_end (*retctx);
1031 free_strlist (namelist);
1036 /* For documentation see keydb.h.
1038 FIXME: We should replace this with the _byname function. This can
1039 be done by creating a userID conforming to the unified fingerprint
1042 get_pubkey_byfprint (PKT_public_key *pk, kbnode_t *r_keyblock,
1043 const byte * fprint, size_t fprint_len)
1050 if (fprint_len == 20 || fprint_len == 16)
1052 struct getkey_ctx_s ctx;
1054 KBNODE found_key = NULL;
1056 memset (&ctx, 0, sizeof ctx);
1058 ctx.not_allocated = 1;
1059 ctx.kr_handle = keydb_new ();
1061 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1062 : KEYDB_SEARCH_MODE_FPR20;
1063 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1064 rc = lookup (&ctx, &kb, &found_key, 0);
1066 pk_from_block (&ctx, pk, kb, found_key);
1067 if (!rc && r_keyblock)
1072 release_kbnode (kb);
1076 rc = GPG_ERR_GENERAL; /* Oops */
1081 /* For documentation see keydb.h. */
1083 get_pubkey_byfprint_fast (PKT_public_key * pk,
1084 const byte * fprint, size_t fprint_len)
1089 byte fprbuf[MAX_FINGERPRINT_LEN];
1092 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1093 fprbuf[i] = fprint[i];
1094 while (i < MAX_FINGERPRINT_LEN)
1098 rc = keydb_search_fpr (hd, fprbuf);
1099 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1102 return GPG_ERR_NO_PUBKEY;
1104 rc = keydb_get_keyblock (hd, &keyblock);
1108 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1109 return GPG_ERR_NO_PUBKEY;
1112 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1113 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1115 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1116 release_kbnode (keyblock);
1118 /* Not caching key here since it won't have all of the fields
1125 /* For documentation see keydb.h. */
1127 get_seckey_default (PKT_public_key *pk)
1130 strlist_t namelist = NULL;
1131 int include_unusable = 1;
1133 if (opt.def_secret_key && *opt.def_secret_key)
1134 add_to_strlist (&namelist, opt.def_secret_key);
1136 include_unusable = 0;
1138 err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
1140 free_strlist (namelist);
1145 /* For documentation see keydb.h. */
1147 getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
1148 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
1150 return key_byname (retctx, names, pk, want_secret, 1,
1151 ret_keyblock, NULL);
1155 /* For documentation see keydb.h. */
1157 getkey_byname (getkey_ctx_t *retctx, PKT_public_key *pk,
1158 const char *name, int want_secret, kbnode_t *ret_keyblock)
1161 strlist_t namelist = NULL;
1162 int with_unusable = 1;
1164 if (want_secret && !name && opt.def_secret_key && *opt.def_secret_key)
1165 add_to_strlist (&namelist, opt.def_secret_key);
1167 add_to_strlist (&namelist, name);
1171 err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
1172 ret_keyblock, NULL);
1174 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
1175 WANT_SECRET has been used. */
1177 free_strlist (namelist);
1183 /* For documentation see keydb.h. */
1185 getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
1187 int rc; /* Fixme: Make sure this is proper gpg_error */
1188 KBNODE found_key = NULL;
1190 /* We need to disable the caching so that for an exact key search we
1191 won't get the result back from the cache and thus end up in an
1192 endless loop. The endless loop can occur, because the cache is
1193 used without respecting the current file pointer! */
1194 keydb_disable_caching (ctx->kr_handle);
1196 rc = lookup (ctx, ret_keyblock, &found_key, ctx->want_secret);
1197 if (!rc && pk && ret_keyblock)
1198 pk_from_block (ctx, pk, *ret_keyblock, found_key);
1204 /* For documentation see keydb.h. */
1206 getkey_end (getkey_ctx_t ctx)
1210 keydb_release (ctx->kr_handle);
1211 if (!ctx->not_allocated)
1218 /************************************************
1219 ************* Merging stuff ********************
1220 ************************************************/
1222 /* For documentation see keydb.h. */
1224 setup_main_keyids (kbnode_t keyblock)
1226 u32 kid[2], mainkid[2];
1227 kbnode_t kbctx, node;
1230 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1232 pk = keyblock->pkt->pkt.public_key;
1234 keyid_from_pk (pk, mainkid);
1235 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1237 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
1238 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1240 pk = node->pkt->pkt.public_key;
1241 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
1242 if (!pk->main_keyid[0] && !pk->main_keyid[1])
1244 pk->main_keyid[0] = mainkid[0];
1245 pk->main_keyid[1] = mainkid[1];
1251 /* For documentation see keydb.h. */
1253 merge_keys_and_selfsig (KBNODE keyblock)
1257 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
1258 merge_selfsigs (keyblock);
1260 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
1265 parse_key_usage (PKT_signature * sig)
1272 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
1275 /* First octet of the keyflags. */
1280 key_usage |= PUBKEY_USAGE_CERT;
1286 key_usage |= PUBKEY_USAGE_SIG;
1290 /* We do not distinguish between encrypting communications and
1291 encrypting storage. */
1292 if (flags & (0x04 | 0x08))
1294 key_usage |= PUBKEY_USAGE_ENC;
1295 flags &= ~(0x04 | 0x08);
1300 key_usage |= PUBKEY_USAGE_AUTH;
1305 key_usage |= PUBKEY_USAGE_UNKNOWN;
1308 key_usage |= PUBKEY_USAGE_NONE;
1310 else if (p) /* Key flags of length zero. */
1311 key_usage |= PUBKEY_USAGE_NONE;
1313 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1314 capability that we do not handle. This serves to distinguish
1315 between a zero key usage which we handle as the default
1316 capabilities for that algorithm, and a usage that we do not
1317 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
1318 key_flags have been given but they do not specify any usage. */
1324 /* Apply information from SIGNODE (which is the valid self-signature
1325 * associated with that UID) to the UIDNODE:
1326 * - weather the UID has been revoked
1327 * - assumed creation date of the UID
1328 * - temporary store the keyflags here
1329 * - temporary store the key expiration time here
1330 * - mark whether the primary user ID flag hat been set.
1331 * - store the preferences
1334 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
1336 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1337 PKT_signature *sig = signode->pkt->pkt.signature;
1338 const byte *p, *sym, *hash, *zip;
1339 size_t n, nsym, nhash, nzip;
1341 sig->flags.chosen_selfsig = 1;/* We chose this one. */
1342 uid->created = 0; /* Not created == invalid. */
1343 if (IS_UID_REV (sig))
1345 uid->is_revoked = 1;
1346 return; /* Has been revoked. */
1349 uid->is_revoked = 0;
1351 uid->expiredate = sig->expiredate;
1353 if (sig->flags.expired)
1355 uid->is_expired = 1;
1356 return; /* Has expired. */
1359 uid->is_expired = 0;
1361 uid->created = sig->timestamp; /* This one is okay. */
1362 uid->selfsigversion = sig->version;
1363 /* If we got this far, it's not expired :) */
1364 uid->is_expired = 0;
1366 /* Store the key flags in the helper variable for later processing. */
1367 uid->help_key_usage = parse_key_usage (sig);
1369 /* Ditto for the key expiration. */
1370 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1371 if (p && buf32_to_u32 (p))
1372 uid->help_key_expire = keycreated + buf32_to_u32 (p);
1374 uid->help_key_expire = 0;
1376 /* Set the primary user ID flag - we will later wipe out some
1377 * of them to only have one in our keyblock. */
1378 uid->is_primary = 0;
1379 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
1381 uid->is_primary = 2;
1383 /* We could also query this from the unhashed area if it is not in
1384 * the hased area and then later try to decide which is the better
1385 * there should be no security problem with this.
1386 * For now we only look at the hashed one. */
1388 /* Now build the preferences list. These must come from the
1389 hashed section so nobody can modify the ciphers a key is
1390 willing to accept. */
1391 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
1394 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
1397 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
1402 n = nsym + nhash + nzip;
1407 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
1409 for (; nsym; nsym--, n++)
1411 uid->prefs[n].type = PREFTYPE_SYM;
1412 uid->prefs[n].value = *sym++;
1414 for (; nhash; nhash--, n++)
1416 uid->prefs[n].type = PREFTYPE_HASH;
1417 uid->prefs[n].value = *hash++;
1419 for (; nzip; nzip--, n++)
1421 uid->prefs[n].type = PREFTYPE_ZIP;
1422 uid->prefs[n].value = *zip++;
1424 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
1425 uid->prefs[n].value = 0;
1428 /* See whether we have the MDC feature. */
1430 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1431 if (p && n && (p[0] & 0x01))
1434 /* And the keyserver modify flag. */
1435 uid->flags.ks_modify = 1;
1436 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1437 if (p && n && (p[0] & 0x80))
1438 uid->flags.ks_modify = 0;
1442 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
1444 rinfo->date = sig->timestamp;
1445 rinfo->algo = sig->pubkey_algo;
1446 rinfo->keyid[0] = sig->keyid[0];
1447 rinfo->keyid[1] = sig->keyid[1];
1451 /* Given a keyblock, parse the key block and extract various pieces of
1452 information and save them with the primary key packet and the user
1453 id packets. For instance, some information is stored in signature
1454 packets. We find the latest such valid packet (since the user can
1455 change that information) and copy its contents into the
1458 Note that R_REVOKED may be set to 0, 1 or 2.
1460 This function fills in the following fields in the primary key's
1463 main_keyid (computed)
1464 revkey / numrevkeys (derived from self signed key data)
1465 flags.valid (whether we have at least 1 self-sig)
1466 flags.maybe_revoked (whether a designed revoked the key, but
1467 we are missing the key to check the sig)
1468 selfsigversion (highest version of any valid self-sig)
1469 pubkey_usage (derived from most recent self-sig or most
1471 has_expired (various sources)
1472 expiredate (various sources)
1474 See the documentation for fixup_uidnode for how the user id packets
1475 are modified. In addition to that the primary user id's is_primary
1476 field is set to 1 and the other user id's is_primary are set to
1479 merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
1480 struct revoke_info *rinfo)
1482 PKT_public_key *pk = NULL;
1485 u32 sigdate, uiddate, uiddate2;
1486 KBNODE signode, uidnode, uidnode2;
1487 u32 curtime = make_timestamp ();
1488 unsigned int key_usage = 0;
1489 u32 keytimestamp = 0;
1491 int key_expire_seen = 0;
1492 byte sigversion = 0;
1495 memset (rinfo, 0, sizeof (*rinfo));
1497 /* Section 11.1 of RFC 4880 determines the order of packets within a
1498 message. There are three sections, which must occur in the
1499 following order: the public key, the user ids and user attributes
1500 and the subkeys. Within each section, each primary packet (e.g.,
1501 a user id packet) is followed by one or more signature packets,
1502 which modify that packet. */
1504 /* According to Section 11.1 of RFC 4880, the public key must be the
1506 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1507 /* parse_keyblock_image ensures that the first packet is the
1510 pk = keyblock->pkt->pkt.public_key;
1511 keytimestamp = pk->timestamp;
1513 keyid_from_pk (pk, kid);
1514 pk->main_keyid[0] = kid[0];
1515 pk->main_keyid[1] = kid[1];
1517 if (pk->version < 4)
1519 /* Before v4 the key packet itself contains the expiration date
1520 * and there was no way to change it, so we start with the one
1521 * from the key packet. */
1522 key_expire = pk->max_expiredate;
1523 key_expire_seen = 1;
1528 - Find the latest direct key self-signature. We assume that the
1529 newest one overrides all others.
1531 - Determine whether the key has been revoked.
1533 - Gather all revocation keys (unlike other data, we don't just
1534 take them from the latest self-signed packet).
1536 - Determine max (sig[...]->version).
1539 /* Reset this in case this key was already merged. */
1545 sigdate = 0; /* Helper variable to find the latest signature. */
1547 /* According to Section 11.1 of RFC 4880, the public key comes first
1548 and is immediately followed by any signature packets that modify
1551 k && k->pkt->pkttype != PKT_USER_ID
1552 && k->pkt->pkttype != PKT_ATTRIBUTE
1553 && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1556 if (k->pkt->pkttype == PKT_SIGNATURE)
1558 PKT_signature *sig = k->pkt->pkt.signature;
1559 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1562 if (check_key_signature (keyblock, k, NULL))
1563 ; /* Signature did not verify. */
1564 else if (IS_KEY_REV (sig))
1566 /* Key has been revoked - there is no way to
1567 * override such a revocation, so we theoretically
1568 * can stop now. We should not cope with expiration
1569 * times for revocations here because we have to
1570 * assume that an attacker can generate all kinds of
1571 * signatures. However due to the fact that the key
1572 * has been revoked it does not harm either and by
1573 * continuing we gather some more info on that
1576 sig_to_revoke_info (sig, rinfo);
1578 else if (IS_KEY_SIG (sig))
1580 /* Add the indicated revocations keys from all
1581 signatures not just the latest. We do this
1582 because you need multiple 1F sigs to properly
1583 handle revocation keys (PGP does it this way, and
1584 a revocation key could be sensitive and hence in
1585 a different signature). */
1591 xrealloc (pk->revkey, sizeof (struct revocation_key) *
1592 (pk->numrevkeys + sig->numrevkeys));
1594 for (i = 0; i < sig->numrevkeys; i++)
1595 memcpy (&pk->revkey[pk->numrevkeys++],
1597 sizeof (struct revocation_key));
1600 if (sig->timestamp >= sigdate)
1601 /* This is the latest signature so far. */
1603 if (sig->flags.expired)
1604 ; /* Signature has expired - ignore it. */
1607 sigdate = sig->timestamp;
1609 if (sig->version > sigversion)
1610 sigversion = sig->version;
1619 /* Remove dupes from the revocation keys. */
1622 int i, j, x, changed = 0;
1624 for (i = 0; i < pk->numrevkeys; i++)
1626 for (j = i + 1; j < pk->numrevkeys; j++)
1628 if (memcmp (&pk->revkey[i], &pk->revkey[j],
1629 sizeof (struct revocation_key)) == 0)
1633 for (x = j; x < pk->numrevkeys - 1; x++)
1634 pk->revkey[x] = pk->revkey[x + 1];
1644 pk->revkey = xrealloc (pk->revkey,
1646 sizeof (struct revocation_key));
1650 /* SIGNODE is the 1F signature packet with the latest creation
1651 time. Extract some information from it. */
1653 /* Some information from a direct key signature take precedence
1654 * over the same information given in UID sigs. */
1655 PKT_signature *sig = signode->pkt->pkt.signature;
1658 key_usage = parse_key_usage (sig);
1660 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1661 if (p && buf32_to_u32 (p))
1663 key_expire = keytimestamp + buf32_to_u32 (p);
1664 key_expire_seen = 1;
1667 /* Mark that key as valid: One direct key signature should
1668 * render a key as valid. */
1669 pk->flags.valid = 1;
1672 /* Pass 1.5: Look for key revocation signatures that were not made
1673 by the key (i.e. did a revocation key issue a revocation for
1674 us?). Only bother to do this if there is a revocation key in the
1675 first place and we're not revoked already. */
1677 if (!*r_revoked && pk->revkey)
1678 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
1680 if (k->pkt->pkttype == PKT_SIGNATURE)
1682 PKT_signature *sig = k->pkt->pkt.signature;
1684 if (IS_KEY_REV (sig) &&
1685 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
1687 int rc = check_revocation_keys (pk, sig);
1691 sig_to_revoke_info (sig, rinfo);
1692 /* Don't continue checking since we can't be any
1693 more revoked than this. */
1696 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
1697 pk->flags.maybe_revoked = 1;
1699 /* A failure here means the sig did not verify, was
1700 not issued by a revocation key, or a revocation
1701 key loop was broken. If a revocation key isn't
1702 findable, however, the key might be revoked and
1703 we don't know it. */
1705 /* TODO: In the future handle subkey and cert
1706 revocations? PGP doesn't, but it's in 2440. */
1711 /* Second pass: Look at the self-signature of all user IDs. */
1713 /* According to RFC 4880 section 11.1, user id and attribute packets
1714 are in the second section, after the public key packet and before
1715 the subkey packets. */
1716 signode = uidnode = NULL;
1717 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
1718 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1720 if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
1721 /* New user id packet. */
1723 if (uidnode && signode)
1724 /* Apply the data from the most recent self-signed packet
1725 to the preceding user id packet. */
1727 fixup_uidnode (uidnode, signode, keytimestamp);
1728 pk->flags.valid = 1;
1730 /* Clear SIGNODE. The only relevant self-signed data for
1731 UIDNODE follows it. */
1732 if (k->pkt->pkttype == PKT_USER_ID)
1739 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1741 PKT_signature *sig = k->pkt->pkt.signature;
1742 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1744 if (check_key_signature (keyblock, k, NULL))
1745 ; /* signature did not verify */
1746 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
1747 && sig->timestamp >= sigdate)
1749 /* Note: we allow to invalidate cert revocations
1750 * by a newer signature. An attacker can't use this
1751 * because a key should be revoked with a key revocation.
1752 * The reason why we have to allow for that is that at
1753 * one time an email address may become invalid but later
1754 * the same email address may become valid again (hired,
1755 * fired, hired again). */
1757 sigdate = sig->timestamp;
1759 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
1760 if (sig->version > sigversion)
1761 sigversion = sig->version;
1766 if (uidnode && signode)
1768 fixup_uidnode (uidnode, signode, keytimestamp);
1769 pk->flags.valid = 1;
1772 /* If the key isn't valid yet, and we have
1773 --allow-non-selfsigned-uid set, then force it valid. */
1774 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
1777 log_info (_("Invalid key %s made valid by"
1778 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
1779 pk->flags.valid = 1;
1782 /* The key STILL isn't valid, so try and find an ultimately
1783 trusted signature. */
1784 if (!pk->flags.valid)
1788 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1791 if (k->pkt->pkttype == PKT_USER_ID)
1793 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1795 PKT_signature *sig = k->pkt->pkt.signature;
1797 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
1799 PKT_public_key *ultimate_pk;
1801 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
1803 /* We don't want to use the full get_pubkey to
1804 avoid infinite recursion in certain cases.
1805 There is no reason to check that an ultimately
1806 trusted key is still valid - if it has been
1807 revoked the user should also remove the
1808 ultimate trust flag. */
1809 if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
1810 && check_key_signature2 (keyblock, k, ultimate_pk,
1811 NULL, NULL, NULL, NULL) == 0
1812 && get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
1814 free_public_key (ultimate_pk);
1815 pk->flags.valid = 1;
1819 free_public_key (ultimate_pk);
1825 /* Record the highest selfsig version so we know if this is a v3
1826 key through and through, or a v3 key with a v4 selfsig
1827 somewhere. This is useful in a few places to know if the key
1828 must be treated as PGP2-style or OpenPGP-style. Note that a
1829 selfsig revocation with a higher version number will also raise
1830 this value. This is okay since such a revocation must be
1831 issued by the user (i.e. it cannot be issued by someone else to
1832 modify the key behavior.) */
1834 pk->selfsigversion = sigversion;
1836 /* Now that we had a look at all user IDs we can now get some information
1837 * from those user IDs.
1842 /* Find the latest user ID with key flags set. */
1843 uiddate = 0; /* Helper to find the latest user ID. */
1844 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1847 if (k->pkt->pkttype == PKT_USER_ID)
1849 PKT_user_id *uid = k->pkt->pkt.user_id;
1850 if (uid->help_key_usage && uid->created > uiddate)
1852 key_usage = uid->help_key_usage;
1853 uiddate = uid->created;
1860 /* No key flags at all: get it from the algo. */
1861 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
1865 /* Check that the usage matches the usage as given by the algo. */
1866 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
1867 if (x) /* Mask it down to the actual allowed usage. */
1871 /* Whatever happens, it's a primary key, so it can certify. */
1872 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
1874 if (!key_expire_seen)
1876 /* Find the latest valid user ID with a key expiration set
1877 * Note, that this may be a different one from the above because
1878 * some user IDs may have no expiration date set. */
1880 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1883 if (k->pkt->pkttype == PKT_USER_ID)
1885 PKT_user_id *uid = k->pkt->pkt.user_id;
1886 if (uid->help_key_expire && uid->created > uiddate)
1888 key_expire = uid->help_key_expire;
1889 uiddate = uid->created;
1895 /* Currently only v3 keys have a maximum expiration date, but I'll
1896 bet v5 keys get this feature again. */
1898 || (pk->max_expiredate && key_expire > pk->max_expiredate))
1899 key_expire = pk->max_expiredate;
1901 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
1902 pk->expiredate = key_expire;
1904 /* Fixme: we should see how to get rid of the expiretime fields but
1905 * this needs changes at other places too. */
1907 /* And now find the real primary user ID and delete all others. */
1908 uiddate = uiddate2 = 0;
1909 uidnode = uidnode2 = NULL;
1910 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1912 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
1914 PKT_user_id *uid = k->pkt->pkt.user_id;
1915 if (uid->is_primary)
1917 if (uid->created > uiddate)
1919 uiddate = uid->created;
1922 else if (uid->created == uiddate && uidnode)
1924 /* The dates are equal, so we need to do a
1925 different (and arbitrary) comparison. This
1926 should rarely, if ever, happen. It's good to
1927 try and guarantee that two different GnuPG
1928 users with two different keyrings at least pick
1929 the same primary. */
1930 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
1936 if (uid->created > uiddate2)
1938 uiddate2 = uid->created;
1941 else if (uid->created == uiddate2 && uidnode2)
1943 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
1951 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1954 if (k->pkt->pkttype == PKT_USER_ID &&
1955 !k->pkt->pkt.user_id->attrib_data)
1957 PKT_user_id *uid = k->pkt->pkt.user_id;
1959 uid->is_primary = 0;
1965 /* None is flagged primary - use the latest user ID we have,
1966 and disambiguate with the arbitrary packet comparison. */
1967 uidnode2->pkt->pkt.user_id->is_primary = 1;
1971 /* None of our uids were self-signed, so pick the one that
1972 sorts first to be the primary. This is the best we can do
1973 here since there are no self sigs to date the uids. */
1977 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1980 if (k->pkt->pkttype == PKT_USER_ID
1981 && !k->pkt->pkt.user_id->attrib_data)
1986 uidnode->pkt->pkt.user_id->is_primary = 1;
1991 if (cmp_user_ids (k->pkt->pkt.user_id,
1992 uidnode->pkt->pkt.user_id) > 0)
1994 uidnode->pkt->pkt.user_id->is_primary = 0;
1996 uidnode->pkt->pkt.user_id->is_primary = 1;
1999 k->pkt->pkt.user_id->is_primary = 0; /* just to be
2007 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
2008 Caller must free the signature when they are done. */
2009 static PKT_signature *
2010 buf_to_sig (const byte * buf, size_t len)
2012 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
2013 IOBUF iobuf = iobuf_temp_with_content (buf, len);
2014 int save_mode = set_packet_list_mode (0);
2016 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
2022 set_packet_list_mode (save_mode);
2023 iobuf_close (iobuf);
2028 /* Use the self-signed data to fill in various fields in subkeys.
2030 KEYBLOCK is the whole keyblock. SUBNODE is the subkey to fill in.
2032 Sets the following fields on the subkey:
2035 flags.valid if the subkey has a valid self-sig binding
2042 On this subkey's most revent valid self-signed packet, the
2043 following field is set:
2045 flags.chosen_selfsig
2048 merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
2050 PKT_public_key *mainpk = NULL, *subpk = NULL;
2056 u32 curtime = make_timestamp ();
2057 unsigned int key_usage = 0;
2058 u32 keytimestamp = 0;
2062 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2064 mainpk = keyblock->pkt->pkt.public_key;
2065 if (mainpk->version < 4)
2066 return;/* (actually this should never happen) */
2067 keyid_from_pk (mainpk, mainkid);
2068 subpk = subnode->pkt->pkt.public_key;
2069 keytimestamp = subpk->timestamp;
2071 subpk->flags.valid = 0;
2072 subpk->main_keyid[0] = mainpk->main_keyid[0];
2073 subpk->main_keyid[1] = mainpk->main_keyid[1];
2075 /* Find the latest key binding self-signature. */
2077 sigdate = 0; /* Helper to find the latest signature. */
2078 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2081 if (k->pkt->pkttype == PKT_SIGNATURE)
2083 sig = k->pkt->pkt.signature;
2084 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
2086 if (check_key_signature (keyblock, k, NULL))
2087 ; /* Signature did not verify. */
2088 else if (IS_SUBKEY_REV (sig))
2090 /* Note that this means that the date on a
2091 revocation sig does not matter - even if the
2092 binding sig is dated after the revocation sig,
2093 the subkey is still marked as revoked. This
2094 seems ok, as it is just as easy to make new
2095 subkeys rather than re-sign old ones as the
2096 problem is in the distribution. Plus, PGP (7)
2097 does this the same way. */
2098 subpk->flags.revoked = 1;
2099 sig_to_revoke_info (sig, &subpk->revoked);
2100 /* Although we could stop now, we continue to
2101 * figure out other information like the old expiration
2104 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
2106 if (sig->flags.expired)
2107 ; /* Signature has expired - ignore it. */
2110 sigdate = sig->timestamp;
2112 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2119 /* No valid key binding. */
2123 sig = signode->pkt->pkt.signature;
2124 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
2126 key_usage = parse_key_usage (sig);
2129 /* No key flags at all: get it from the algo. */
2130 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
2134 /* Check that the usage matches the usage as given by the algo. */
2135 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
2136 if (x) /* Mask it down to the actual allowed usage. */
2140 subpk->pubkey_usage = key_usage;
2142 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2143 if (p && buf32_to_u32 (p))
2144 key_expire = keytimestamp + buf32_to_u32 (p);
2147 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
2148 subpk->expiredate = key_expire;
2150 /* Algo doesn't exist. */
2151 if (openpgp_pk_test_algo (subpk->pubkey_algo))
2154 subpk->flags.valid = 1;
2156 /* Find the most recent 0x19 embedded signature on our self-sig. */
2157 if (!subpk->flags.backsig)
2161 PKT_signature *backsig = NULL;
2165 /* We do this while() since there may be other embedded
2166 signatures in the future. We only want 0x19 here. */
2168 while ((p = enum_sig_subpkt (sig->hashed,
2169 SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
2171 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2173 PKT_signature *tempsig = buf_to_sig (p, n);
2176 if (tempsig->timestamp > sigdate)
2179 free_seckey_enc (backsig);
2182 sigdate = backsig->timestamp;
2185 free_seckey_enc (tempsig);
2191 /* It is safe to have this in the unhashed area since the 0x19
2192 is located on the selfsig for convenience, not security. */
2194 while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
2197 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2199 PKT_signature *tempsig = buf_to_sig (p, n);
2202 if (tempsig->timestamp > sigdate)
2205 free_seckey_enc (backsig);
2208 sigdate = backsig->timestamp;
2211 free_seckey_enc (tempsig);
2217 /* At ths point, backsig contains the most recent 0x19 sig.
2218 Let's see if it is good. */
2220 /* 2==valid, 1==invalid, 0==didn't check */
2221 if (check_backsig (mainpk, subpk, backsig) == 0)
2222 subpk->flags.backsig = 2;
2224 subpk->flags.backsig = 1;
2226 free_seckey_enc (backsig);
2232 /* Merge information from the self-signatures with the public key,
2233 subkeys and user ids to make using them more easy.
2235 See documentation for merge_selfsigs_main, merge_selfsigs_subkey
2236 and fixup_uidnode for exactly which fields are updated. */
2238 merge_selfsigs (KBNODE keyblock)
2242 struct revoke_info rinfo;
2243 PKT_public_key *main_pk;
2245 unsigned int mdc_feature;
2247 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2249 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
2251 log_error ("expected public key but found secret key "
2253 /* We better exit here because a public key is expected at
2254 other places too. FIXME: Figure this out earlier and
2255 don't get to here at all */
2261 merge_selfsigs_main (keyblock, &revoked, &rinfo);
2263 /* Now merge in the data from each of the subkeys. */
2264 for (k = keyblock; k; k = k->next)
2266 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2268 merge_selfsigs_subkey (keyblock, k);
2272 main_pk = keyblock->pkt->pkt.public_key;
2273 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
2275 /* If the primary key is revoked, expired, or invalid we
2276 * better set the appropriate flags on that key and all
2278 for (k = keyblock; k; k = k->next)
2280 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2281 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2283 PKT_public_key *pk = k->pkt->pkt.public_key;
2284 if (!main_pk->flags.valid)
2285 pk->flags.valid = 0;
2286 if (revoked && !pk->flags.revoked)
2288 pk->flags.revoked = revoked;
2289 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
2291 if (main_pk->has_expired)
2292 pk->has_expired = main_pk->has_expired;
2298 /* Set the preference list of all keys to those of the primary real
2299 * user ID. Note: we use these preferences when we don't know by
2300 * which user ID the key has been selected.
2301 * fixme: we should keep atoms of commonly used preferences or
2302 * use reference counting to optimize the preference lists storage.
2303 * FIXME: it might be better to use the intersection of
2305 * Do a similar thing for the MDC feature flag. */
2308 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2310 if (k->pkt->pkttype == PKT_USER_ID
2311 && !k->pkt->pkt.user_id->attrib_data
2312 && k->pkt->pkt.user_id->is_primary)
2314 prefs = k->pkt->pkt.user_id->prefs;
2315 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2319 for (k = keyblock; k; k = k->next)
2321 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2322 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2324 PKT_public_key *pk = k->pkt->pkt.public_key;
2327 pk->prefs = copy_prefs (prefs);
2328 pk->flags.mdc = mdc_feature;
2335 /* See whether the key satisfies any additional requirements specified
2336 in CTX. If so, return 1 and set CTX->FOUND_KEY to an appropriate
2337 key or subkey. Otherwise, return 0 if there was no appropriate
2340 In case the primary key is not required, select a suitable subkey.
2341 We need the primary key if PUBKEY_USAGE_CERT is set in
2342 CTX->REQ_USAGE or we are in PGP6 or PGP7 mode and PUBKEY_USAGE_SIG
2343 is set in CTX->REQ_USAGE.
2345 If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
2346 are set in CTX->REQ_USAGE, we filter by the key's function.
2347 Concretely, if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then
2348 we only return a key if it is (at least) either a signing or a
2351 If CTX->REQ_USAGE is set, then we reject any keys that are not good
2352 (i.e., valid, not revoked, not expired, etc.). This allows the
2353 getkey functions to be used for plain key listings.
2355 Sets the matched key's user id field (pk->user_id) to the user id
2356 that matched the low-level search criteria or NULL.
2359 This function needs to handle several different cases:
2361 1. No requested usage and no primary key requested
2362 Examples for this case are that we have a keyID to be used
2363 for decrytion or verification.
2364 2. No usage but primary key requested
2365 This is the case for all functions which work on an
2366 entire keyblock, e.g. for editing or listing
2367 3. Usage and primary key requested
2369 4. Usage but no primary key requested
2374 finish_lookup (GETKEY_CTX ctx, KBNODE keyblock)
2378 /* If CTX->EXACT is set, the key or subkey that actually matched the
2379 low-level search criteria. */
2380 KBNODE foundk = NULL;
2381 /* The user id (if any) that matched the low-level search criteria. */
2382 PKT_user_id *foundu = NULL;
2384 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2385 unsigned int req_usage = (ctx->req_usage & USAGE_MASK);
2387 /* Request the primary if we're certifying another key, and also
2388 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2389 do not understand signatures made by a signing subkey. PGP 8
2391 int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2392 ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2394 u32 curtime = make_timestamp ();
2399 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
2402 /* Get the key or subkey that matched the low-level search
2405 for (k = keyblock; k; k = k->next)
2409 assert (k->pkt->pkttype == PKT_PUBLIC_KEY
2410 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
2417 /* Get the user id that matched that low-level search criteria. */
2418 for (k = keyblock; k; k = k->next)
2422 assert (k->pkt->pkttype == PKT_USER_ID);
2423 foundu = k->pkt->pkt.user_id;
2429 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2430 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
2431 foundk ? "one" : "all", req_usage);
2435 latest_key = foundk ? foundk : keyblock;
2441 /* Set latest_key to the latest (the one with the most recent
2442 timestamp) good (valid, not revoked, not expired, etc.) subkey.
2444 Don't bother if we are only looking for a primary key or we need
2445 an exact match and the exact match is not a subkey. */
2446 if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
2452 /* Either start a loop or check just this one subkey. */
2453 for (k = foundk ? foundk : keyblock; k; k = nextk)
2458 /* If FOUNDK is not NULL, then only consider that exact
2459 key, i.e., don't iterate. */
2464 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2467 pk = k->pkt->pkt.public_key;
2469 log_debug ("\tchecking subkey %08lX\n",
2470 (ulong) keyid_from_pk (pk, NULL));
2471 if (!pk->flags.valid)
2474 log_debug ("\tsubkey not valid\n");
2477 if (pk->flags.revoked)
2480 log_debug ("\tsubkey has been revoked\n");
2483 if (pk->has_expired)
2486 log_debug ("\tsubkey has expired\n");
2489 if (pk->timestamp > curtime && !opt.ignore_valid_from)
2492 log_debug ("\tsubkey not yet valid\n");
2496 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2499 log_debug ("\tusage does not match: want=%x have=%x\n",
2500 req_usage, pk->pubkey_usage);
2505 log_debug ("\tsubkey might be fine\n");
2506 /* In case a key has a timestamp of 0 set, we make sure
2507 that it is used. A better change would be to compare
2508 ">=" but that might also change the selected keys and
2509 is as such a more intrusive change. */
2510 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2512 latest_date = pk->timestamp;
2518 /* Check if the primary key is ok (valid, not revoke, not expire,
2519 matches requested usage) if:
2521 - we didn't find an appropriate subkey and we're not doing an
2524 - we're doing an exact match and the exact match was the
2527 - we're just considering the primary key. */
2528 if ((!latest_key && !ctx->exact) || foundk == keyblock || req_prim)
2531 if (DBG_LOOKUP && !foundk && !req_prim)
2532 log_debug ("\tno suitable subkeys found - trying primary\n");
2533 pk = keyblock->pkt->pkt.public_key;
2534 if (!pk->flags.valid)
2537 log_debug ("\tprimary key not valid\n");
2539 else if (pk->flags.revoked)
2542 log_debug ("\tprimary key has been revoked\n");
2544 else if (pk->has_expired)
2547 log_debug ("\tprimary key has expired\n");
2549 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2552 log_debug ("\tprimary key usage does not match: "
2553 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
2558 log_debug ("\tprimary key may be used\n");
2559 latest_key = keyblock;
2560 latest_date = pk->timestamp;
2567 log_debug ("\tno suitable key found - giving up\n");
2568 return NULL; /* Not found. */
2573 log_debug ("\tusing key %08lX\n",
2574 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
2578 PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2580 free_user_id (pk->user_id);
2581 pk->user_id = scopy_user_id (foundu);
2584 if (latest_key != keyblock && opt.verbose)
2587 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
2588 log_info (_("using subkey %s instead of primary key %s\n"),
2589 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
2593 cache_user_id (keyblock);
2595 return latest_key ? latest_key : keyblock; /* Found. */
2599 /* Return true if all the search modes are fingerprints. */
2601 search_modes_are_fingerprint (getkey_ctx_t ctx)
2605 for (n=found=0; n < ctx->nitems; n++)
2607 switch (ctx->items[n].mode)
2609 case KEYDB_SEARCH_MODE_FPR16:
2610 case KEYDB_SEARCH_MODE_FPR20:
2611 case KEYDB_SEARCH_MODE_FPR:
2618 return found && found == ctx->nitems;
2622 /* A high-level function to lookup keys.
2624 This function builds on top of the low-level keydb API. It first
2625 searches the database using the description stored in CTX->ITEMS,
2626 then it filters the results using CTX and, finally, if WANT_SECRET
2627 is set, it ignores any keys for which no secret key is available.
2629 Note: this function skips any legacy keys unless the search mode is
2630 KEYDB_SEARCH_MODE_FIRST or KEYDB_SEARCH_MODE_NEXT or we are
2631 searching by fingerprint.
2633 Unlike the low-level search functions, this function also merges
2634 all of the self-signed data into the keys, subkeys and user id
2635 packets (see the merge_selfsigs for details).
2637 On success the key's keyblock is stored at *RET_KEYBLOCK. */
2639 lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, kbnode_t *ret_found_key,
2643 int no_suitable_key = 0;
2644 KBNODE keyblock = NULL;
2645 KBNODE found_key = NULL;
2649 rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
2651 /* Skip over all legacy keys unless we are iterating over all
2652 keys in the DB or the key was requested by its fingerprint.
2654 Fixme: The lower level keydb code should actually do that but
2655 then it would be harder to report the number of skipped
2656 legacy keys during import. */
2657 if (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY
2658 && !(ctx->nitems && (ctx->items->mode == KEYDB_SEARCH_MODE_FIRST
2659 || ctx->items->mode == KEYDB_SEARCH_MODE_NEXT))
2660 && !search_modes_are_fingerprint (ctx))
2665 /* If we are iterating over the entire database, then we need to
2666 change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
2667 reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next
2669 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2670 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2672 rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
2675 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
2680 if (want_secret && agent_probe_any_secret_key (NULL, keyblock))
2681 goto skip; /* No secret key available. */
2683 /* Warning: node flag bits 0 and 1 should be preserved by
2684 * merge_selfsigs. For secret keys, premerge transferred the
2685 * keys to the keyblock. */
2686 merge_selfsigs (keyblock);
2687 found_key = finish_lookup (ctx, keyblock);
2690 no_suitable_key = 0;
2694 no_suitable_key = 1;
2697 /* Release resources and continue search. */
2698 release_kbnode (keyblock);
2700 /* The keyblock cache ignores the current "file position".
2701 Thus, if we request the next result and the cache matches
2702 (and it will since it is what we just looked for), we'll get
2703 the same entry back! We can avoid this infinite loop by
2704 disabling the cache. */
2705 keydb_disable_caching (ctx->kr_handle);
2709 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND
2710 && gpg_err_code (rc) != GPG_ERR_LEGACY_KEY)
2711 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
2715 *ret_keyblock = keyblock; /* Return the keyblock. */
2718 else if ((gpg_err_code (rc) == GPG_ERR_NOT_FOUND
2719 || gpg_err_code (rc) == GPG_ERR_LEGACY_KEY) && no_suitable_key)
2720 rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
2721 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2722 rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
2724 release_kbnode (keyblock);
2729 *ret_found_key = found_key;
2731 *ret_found_key = NULL;
2738 /* For documentation see keydb.h. */
2740 enum_secret_keys (void **context, PKT_public_key *sk)
2742 gpg_error_t err = 0;
2755 /* Make a new context. */
2756 c = xtrycalloc (1, sizeof *c);
2758 return gpg_error_from_syserror ();
2764 /* Free the context. */
2765 release_kbnode (c->keyblock);
2772 return gpg_error (GPG_ERR_EOF);
2776 /* Loop until we have a keyblock. */
2777 while (!c->keyblock)
2779 /* Loop over the list of secret keys. */
2785 case 0: /* First try to use the --default-key. */
2786 if (opt.def_secret_key && *opt.def_secret_key)
2787 name = opt.def_secret_key;
2791 case 1: /* Init list of keys to try. */
2792 c->sl = opt.secret_keys_to_try;
2796 case 2: /* Get next item from list. */
2800 c->sl = c->sl->next;
2806 default: /* No more names to check - stop. */
2808 return gpg_error (GPG_ERR_EOF);
2811 while (!name || !*name);
2813 err = getkey_byname (NULL, NULL, name, 1, &c->keyblock);
2816 /* getkey_byname might return a keyblock even in the
2817 error case - I have not checked. Thus better release
2819 release_kbnode (c->keyblock);
2823 c->node = c->keyblock;
2826 /* Get the next key from the current keyblock. */
2827 for (; c->node; c->node = c->node->next)
2829 if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
2830 || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2832 copy_public_key (sk, c->node->pkt->pkt.public_key);
2833 c->node = c->node->next;
2834 return 0; /* Found. */
2838 /* Dispose the keyblock and continue. */
2839 release_kbnode (c->keyblock);
2845 /*********************************************
2846 *********** User ID printing helpers *******
2847 *********************************************/
2849 /* Return a string with a printable representation of the user_id.
2850 * this string must be freed by xfree. */
2852 get_user_id_string (u32 * keyid, int mode, size_t *r_len)
2859 /* Try it two times; second pass reads from the database. */
2862 for (r = user_id_db; r; r = r->next)
2864 for (a = r->keyids; a; a = a->next)
2866 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
2870 /* An empty string as user id is possible. Make
2871 sure that the malloc allocates one byte and
2872 does not bail out. */
2873 p = xmalloc (r->len? r->len : 1);
2874 memcpy (p, r->name, r->len);
2881 p = xasprintf ("%08lX%08lX %.*s",
2882 (ulong) keyid[0], (ulong) keyid[1],
2885 p = xasprintf ("%s %.*s", keystr (keyid),
2888 *r_len = strlen (p);
2896 while (++pass < 2 && !get_pubkey (NULL, keyid));
2899 p = xstrdup (user_id_not_found_utf8 ());
2901 p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
2903 p = xasprintf ("%s [?]", keystr (keyid));
2906 *r_len = strlen (p);
2912 get_user_id_string_native (u32 * keyid)
2914 char *p = get_user_id_string (keyid, 0, NULL);
2915 char *p2 = utf8_to_native (p, strlen (p), 0);
2922 get_long_user_id_string (u32 * keyid)
2924 return get_user_id_string (keyid, 1, NULL);
2928 /* Please try to use get_user_byfpr instead of this one. */
2930 get_user_id (u32 * keyid, size_t * rn)
2932 return get_user_id_string (keyid, 2, rn);
2936 /* Please try to use get_user_id_byfpr_native instead of this one. */
2938 get_user_id_native (u32 * keyid)
2941 char *p = get_user_id (keyid, &rn);
2942 char *p2 = utf8_to_native (p, rn, 0);
2948 /* Return the user id for a key designated by its fingerprint, FPR,
2949 which must be MAX_FINGERPRINT_LEN bytes in size. Note: the
2950 returned string, which must be freed using xfree, may not be NUL
2951 terminated. To determine the length of the string, you must use
2954 get_user_id_byfpr (const byte *fpr, size_t *rn)
2960 /* Try it two times; second pass reads from the database. */
2963 for (r = user_id_db; r; r = r->next)
2966 for (a = r->keyids; a; a = a->next)
2968 if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
2970 /* An empty string as user id is possible. Make
2971 sure that the malloc allocates one byte and does
2973 p = xmalloc (r->len? r->len : 1);
2974 memcpy (p, r->name, r->len);
2982 && !get_pubkey_byfprint (NULL, NULL, fpr, MAX_FINGERPRINT_LEN));
2983 p = xstrdup (user_id_not_found_utf8 ());
2988 /* Like get_user_id_byfpr, but convert the string to the native
2989 encoding. The returned string needs to be freed. Unlike
2990 get_user_id_byfpr, the returned string is NUL terminated. */
2992 get_user_id_byfpr_native (const byte *fpr)
2995 char *p = get_user_id_byfpr (fpr, &rn);
2996 char *p2 = utf8_to_native (p, rn, 0);
3003 /* For documentation see keydb.h. */
3005 get_ctx_handle (GETKEY_CTX ctx)
3007 return ctx->kr_handle;
3011 free_akl (struct akl *akl)
3017 free_keyserver_spec (akl->spec);
3025 while (opt.auto_key_locate)
3027 struct akl *akl2 = opt.auto_key_locate;
3028 opt.auto_key_locate = opt.auto_key_locate->next;
3033 /* Returns false on error. */
3035 parse_auto_key_locate (char *options)
3039 while ((tok = optsep (&options)))
3041 struct akl *akl, *check, *last = NULL;
3047 akl = xmalloc_clear (sizeof (*akl));
3049 if (ascii_strcasecmp (tok, "clear") == 0)
3052 free_akl (opt.auto_key_locate);
3053 opt.auto_key_locate = NULL;
3056 else if (ascii_strcasecmp (tok, "nodefault") == 0)
3057 akl->type = AKL_NODEFAULT;
3058 else if (ascii_strcasecmp (tok, "local") == 0)
3059 akl->type = AKL_LOCAL;
3060 else if (ascii_strcasecmp (tok, "ldap") == 0)
3061 akl->type = AKL_LDAP;
3062 else if (ascii_strcasecmp (tok, "keyserver") == 0)
3063 akl->type = AKL_KEYSERVER;
3065 else if (ascii_strcasecmp (tok, "cert") == 0)
3066 akl->type = AKL_CERT;
3068 else if (ascii_strcasecmp (tok, "pka") == 0)
3069 akl->type = AKL_PKA;
3070 else if (ascii_strcasecmp (tok, "dane") == 0)
3071 akl->type = AKL_DANE;
3072 else if ((akl->spec = parse_keyserver_uri (tok, 1)))
3073 akl->type = AKL_SPEC;
3080 /* We must maintain the order the user gave us */
3081 for (check = opt.auto_key_locate; check;
3082 last = check, check = check->next)
3084 /* Check for duplicates */
3085 if (check->type == akl->type
3086 && (akl->type != AKL_SPEC
3087 || (akl->type == AKL_SPEC
3088 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
3101 opt.auto_key_locate = akl;
3109 /* For documentation see keydb.h. */
3111 have_secret_key_with_kid (u32 *keyid)
3115 KEYDB_SEARCH_DESC desc;
3120 kdbhd = keydb_new ();
3121 memset (&desc, 0, sizeof desc);
3122 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
3123 desc.u.kid[0] = keyid[0];
3124 desc.u.kid[1] = keyid[1];
3127 err = keydb_search (kdbhd, &desc, 1, NULL);
3128 if (gpg_err_code (err) == GPG_ERR_LEGACY_KEY)
3133 err = keydb_get_keyblock (kdbhd, &keyblock);
3136 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
3140 for (node = keyblock; node; node = node->next)
3142 /* Bit 0 of the flags is set if the search found the key
3143 using that key or subkey. Note: a search will only ever
3144 match a single key or subkey. */
3145 if ((node->flag & 1))
3147 assert (node->pkt->pkttype == PKT_PUBLIC_KEY
3148 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3150 if (agent_probe_secret_key (NULL, node->pkt->pkt.public_key) == 0)
3151 /* Not available. */
3159 release_kbnode (keyblock);
3162 keydb_release (kdbhd);