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, 2016 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 <https://www.gnu.org/licenses/>.
29 #include "../common/util.h"
31 #include "../common/iobuf.h"
36 #include "../common/i18n.h"
37 #include "keyserver-internal.h"
38 #include "call-agent.h"
40 #include "../common/host2net.h"
41 #include "../common/mbox-util.h"
42 #include "../common/status.h"
44 #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
45 #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
47 #if MAX_PK_CACHE_ENTRIES < 2
48 #error We need the cache for key creation
51 /* Flags values returned by the lookup code. Note that the values are
52 * directly used by the KEY_CONSIDERED status line. */
53 #define LOOKUP_NOT_SELECTED (1<<0)
54 #define LOOKUP_ALL_SUBKEYS_EXPIRED (1<<1) /* or revoked */
57 /* A context object used by the lookup functions. */
60 /* Part of the search criteria: whether the search is an exact
61 search or not. A search that is exact requires that a key or
62 subkey meet all of the specified criteria. A search that is not
63 exact allows selecting a different key or subkey from the
64 keyblock that matched the criteria. Further, an exact search
65 returns the key or subkey that matched whereas a non-exact search
66 typically returns the primary key. See finish_lookup for
70 /* Part of the search criteria: Whether the caller only wants keys
71 with an available secret key. This is used by getkey_next to get
72 the next result with the same initial criteria. */
75 /* Part of the search criteria: The type of the requested key. A
76 mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.
77 If non-zero, then for a key to match, it must implement one of
81 /* The database handle. */
82 KEYDB_HANDLE kr_handle;
84 /* Whether we should call xfree() on the context when the context is
85 released using getkey_end()). */
88 /* This variable is used as backing store for strings which have
89 their address used in ITEMS. */
92 /* Hack to return the mechanism (AKL_foo) used to find the key. */
95 /* Part of the search criteria: The low-level search specification
96 as passed to keydb_search. */
98 /* This must be the last element in the structure. When we allocate
99 the structure, we allocate it so that ITEMS can hold NITEMS. */
100 KEYDB_SEARCH_DESC items[1];
113 typedef struct keyid_list
115 struct keyid_list *next;
117 char fpr[MAX_FINGERPRINT_LEN];
122 #if MAX_PK_CACHE_ENTRIES
123 typedef struct pk_cache_entry
125 struct pk_cache_entry *next;
129 static pk_cache_entry_t pk_cache;
130 static int pk_cache_entries; /* Number of entries in pk cache. */
131 static int pk_cache_disabled;
134 #if MAX_UID_CACHE_ENTRIES < 5
135 #error we really need the userid cache
138 static void merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock);
139 static int lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret,
140 kbnode_t *ret_keyblock, kbnode_t *ret_found_key);
141 static kbnode_t finish_lookup (kbnode_t keyblock,
142 unsigned int req_usage, int want_exact,
143 int want_secret, unsigned int *r_flags);
144 static void print_status_key_considered (kbnode_t keyblock, unsigned int flags);
152 for (i = 0; i < DIM (lkup_stats); i++)
154 if (lkup_stats[i].any)
155 es_fprintf (es_stderr,
156 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
158 lkup_stats[i].okay_count,
159 lkup_stats[i].nokey_count, lkup_stats[i].error_count);
165 /* Cache a copy of a public key in the public key cache. PK is not
166 * cached if caching is disabled (via getkey_disable_caches), if
167 * PK->FLAGS.DONT_CACHE is set, we don't know how to derive a key id
168 * from the public key (e.g., unsupported algorithm), or a key with
169 * the key id is already in the cache.
171 * The public key packet is copied into the cache using
172 * copy_public_key. Thus, any secret parts are not copied, for
175 * This cache is filled by get_pubkey and is read by get_pubkey and
176 * get_pubkey_fast. */
178 cache_public_key (PKT_public_key * pk)
180 #if MAX_PK_CACHE_ENTRIES
181 pk_cache_entry_t ce, ce2;
184 if (pk_cache_disabled)
187 if (pk->flags.dont_cache)
190 if (is_ELGAMAL (pk->pubkey_algo)
191 || pk->pubkey_algo == PUBKEY_ALGO_DSA
192 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
193 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
194 || pk->pubkey_algo == PUBKEY_ALGO_ECDH
195 || is_RSA (pk->pubkey_algo))
197 keyid_from_pk (pk, keyid);
200 return; /* Don't know how to get the keyid. */
202 for (ce = pk_cache; ce; ce = ce->next)
203 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
206 log_debug ("cache_public_key: already in cache\n");
210 if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
214 /* Remove the last 50% of the entries. */
215 for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
217 if (ce && ce != pk_cache && ce->next)
225 free_public_key (ce->pk);
230 log_assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
233 ce = xmalloc (sizeof *ce);
236 ce->pk = copy_public_key (NULL, pk);
237 ce->keyid[0] = keyid[0];
238 ce->keyid[1] = keyid[1];
243 /* Return a const utf-8 string with the text "[User ID not found]".
244 This function is required so that we don't need to switch gettext's
245 encoding temporary. */
247 user_id_not_found_utf8 (void)
252 text = native_to_utf8 (_("[User ID not found]"));
259 /* Disable and drop the public key cache (which is filled by
260 cache_public_key and get_pubkey). Note: there is currently no way
261 to re-enable this cache. */
263 getkey_disable_caches ()
265 #if MAX_PK_CACHE_ENTRIES
267 pk_cache_entry_t ce, ce2;
269 for (ce = pk_cache; ce; ce = ce2)
272 free_public_key (ce->pk);
275 pk_cache_disabled = 1;
276 pk_cache_entries = 0;
280 /* fixme: disable user id cache ? */
284 /* Free a list of pubkey_t objects. */
286 pubkeys_free (pubkey_t keys)
290 pubkey_t next = keys->next;
292 release_kbnode (keys->keyblock);
300 pk_from_block (PKT_public_key *pk, kbnode_t keyblock, kbnode_t found_key)
302 kbnode_t a = found_key ? found_key : keyblock;
304 log_assert (a->pkt->pkttype == PKT_PUBLIC_KEY
305 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
307 copy_public_key (pk, a->pkt->pkt.public_key);
311 /* Specialized version of get_pubkey which retrieves the key based on
312 * information in SIG. In contrast to get_pubkey PK is required. IF
313 * FORCED_PK is not NULL, this public key is used and copied to PK. */
315 get_pubkey_for_sig (ctrl_t ctrl, PKT_public_key *pk, PKT_signature *sig,
316 PKT_public_key *forced_pk)
323 copy_public_key (pk, forced_pk);
327 /* First try the ISSUER_FPR info. */
328 fpr = issuer_fpr_raw (sig, &fprlen);
329 if (fpr && !get_pubkey_byfprint (ctrl, pk, NULL, fpr, fprlen))
332 /* Fallback to use the ISSUER_KEYID. */
333 return get_pubkey (ctrl, pk, sig->keyid);
337 /* Return the public key with the key id KEYID and store it at PK.
338 * The resources in *PK should be released using
339 * release_public_key_parts(). This function also stores a copy of
340 * the public key in the user id cache (see cache_public_key).
342 * If PK is NULL, this function just stores the public key in the
343 * cache and returns the usual return code.
345 * PK->REQ_USAGE (which is a mask of PUBKEY_USAGE_SIG,
346 * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT) is passed through to the
347 * lookup function. If this is non-zero, only keys with the specified
348 * usage will be returned. As such, it is essential that
349 * PK->REQ_USAGE be correctly initialized!
351 * Returns 0 on success, GPG_ERR_NO_PUBKEY if there is no public key
352 * with the specified key id, or another error code if an error
355 * If the data was not read from the cache, then the self-signed data
356 * has definitely been merged into the public key using
359 get_pubkey (ctrl_t ctrl, PKT_public_key * pk, u32 * keyid)
364 #if MAX_PK_CACHE_ENTRIES
367 /* Try to get it from the cache. We don't do this when pk is
368 NULL as it does not guarantee that the user IDs are
371 for (ce = pk_cache; ce; ce = ce->next)
373 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
374 /* XXX: We don't check PK->REQ_USAGE here, but if we don't
375 read from the cache, we do check it! */
377 copy_public_key (pk, ce->pk);
383 /* More init stuff. */
387 pk = xtrycalloc (1, sizeof *pk);
390 rc = gpg_error_from_syserror ();
398 struct getkey_ctx_s ctx;
400 kbnode_t found_key = NULL;
402 memset (&ctx, 0, sizeof ctx);
403 ctx.exact = 1; /* Use the key ID exactly as given. */
404 ctx.not_allocated = 1;
406 if (ctrl && ctrl->cached_getkey_kdb)
408 ctx.kr_handle = ctrl->cached_getkey_kdb;
409 ctrl->cached_getkey_kdb = NULL;
410 keydb_search_reset (ctx.kr_handle);
414 ctx.kr_handle = keydb_new (ctrl);
417 rc = gpg_error_from_syserror ();
422 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
423 ctx.items[0].u.kid[0] = keyid[0];
424 ctx.items[0].u.kid[1] = keyid[1];
425 ctx.req_usage = pk->req_usage;
426 rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
429 pk_from_block (pk, kb, found_key);
431 getkey_end (ctrl, &ctx);
437 rc = GPG_ERR_NO_PUBKEY;
441 cache_public_key (pk);
443 free_public_key (pk);
448 /* Similar to get_pubkey, but it does not take PK->REQ_USAGE into
449 * account nor does it merge in the self-signed data. This function
450 * also only considers primary keys. It is intended to be used as a
451 * quick check of the key to avoid recursion. It should only be used
452 * in very certain cases. Like get_pubkey and unlike any of the other
453 * lookup functions, this function also consults the user id cache
454 * (see cache_public_key).
456 * Return the public key in *PK. The resources in *PK should be
457 * released using release_public_key_parts(). */
459 get_pubkey_fast (ctrl_t ctrl, PKT_public_key * pk, u32 * keyid)
467 #if MAX_PK_CACHE_ENTRIES
469 /* Try to get it from the cache */
472 for (ce = pk_cache; ce; ce = ce->next)
474 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]
475 /* Only consider primary keys. */
476 && ce->pk->keyid[0] == ce->pk->main_keyid[0]
477 && ce->pk->keyid[1] == ce->pk->main_keyid[1])
480 copy_public_key (pk, ce->pk);
487 hd = keydb_new (ctrl);
489 return gpg_error_from_syserror ();
490 rc = keydb_search_kid (hd, keyid);
491 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
494 return GPG_ERR_NO_PUBKEY;
496 rc = keydb_get_keyblock (hd, &keyblock);
500 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
501 return GPG_ERR_NO_PUBKEY;
504 log_assert (keyblock && keyblock->pkt
505 && keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
507 /* We return the primary key. If KEYID matched a subkey, then we
509 keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
510 if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
511 copy_public_key (pk, keyblock->pkt->pkt.public_key);
513 rc = GPG_ERR_NO_PUBKEY;
515 release_kbnode (keyblock);
517 /* Not caching key here since it won't have all of the fields
524 /* Return the entire keyblock used to create SIG. This is a
525 * specialized version of get_pubkeyblock.
527 * FIXME: This is a hack because get_pubkey_for_sig was already called
528 * and it could have used a cache to hold the key. */
530 get_pubkeyblock_for_sig (ctrl_t ctrl, PKT_signature *sig)
536 /* First try the ISSUER_FPR info. */
537 fpr = issuer_fpr_raw (sig, &fprlen);
538 if (fpr && !get_pubkey_byfprint (ctrl, NULL, &keyblock, fpr, fprlen))
541 /* Fallback to use the ISSUER_KEYID. */
542 return get_pubkeyblock (ctrl, sig->keyid);
546 /* Return the key block for the key with key id KEYID or NULL, if an
547 * error occurs. Use release_kbnode() to release the key block.
549 * The self-signed data has already been merged into the public key
550 * using merge_selfsigs. */
552 get_pubkeyblock (ctrl_t ctrl, u32 * keyid)
554 struct getkey_ctx_s ctx;
556 KBNODE keyblock = NULL;
558 memset (&ctx, 0, sizeof ctx);
559 /* No need to set exact here because we want the entire block. */
560 ctx.not_allocated = 1;
561 ctx.kr_handle = keydb_new (ctrl);
565 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
566 ctx.items[0].u.kid[0] = keyid[0];
567 ctx.items[0].u.kid[1] = keyid[1];
568 rc = lookup (ctrl, &ctx, 0, &keyblock, NULL);
569 getkey_end (ctrl, &ctx);
571 return rc ? NULL : keyblock;
575 /* Return the public key with the key id KEYID iff the secret key is
576 * available and store it at PK. The resources should be released
577 * using release_public_key_parts().
579 * Unlike other lookup functions, PK may not be NULL. PK->REQ_USAGE
580 * is passed through to the lookup function and is a mask of
581 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. Thus, it
582 * must be valid! If this is non-zero, only keys with the specified
583 * usage will be returned.
585 * Returns 0 on success. If a public key with the specified key id is
586 * not found or a secret key is not available for that public key, an
587 * error code is returned. Note: this function ignores legacy keys.
588 * An error code is also return if an error occurs.
590 * The self-signed data has already been merged into the public key
591 * using merge_selfsigs. */
593 get_seckey (ctrl_t ctrl, PKT_public_key *pk, u32 *keyid)
596 struct getkey_ctx_s ctx;
597 kbnode_t keyblock = NULL;
598 kbnode_t found_key = NULL;
600 memset (&ctx, 0, sizeof ctx);
601 ctx.exact = 1; /* Use the key ID exactly as given. */
602 ctx.not_allocated = 1;
603 ctx.kr_handle = keydb_new (ctrl);
605 return gpg_error_from_syserror ();
607 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
608 ctx.items[0].u.kid[0] = keyid[0];
609 ctx.items[0].u.kid[1] = keyid[1];
610 ctx.req_usage = pk->req_usage;
611 err = lookup (ctrl, &ctx, 1, &keyblock, &found_key);
614 pk_from_block (pk, keyblock, found_key);
616 getkey_end (ctrl, &ctx);
617 release_kbnode (keyblock);
621 if (!agent_probe_secret_key (/*ctrl*/NULL, pk))
623 release_public_key_parts (pk);
624 err = gpg_error (GPG_ERR_NO_SECKEY);
632 /* Skip unusable keys. A key is unusable if it is revoked, expired or
633 disabled or if the selected user id is revoked or expired. */
635 skip_unusable (void *opaque, u32 * keyid, int uid_no)
637 ctrl_t ctrl = opaque;
642 keyblock = get_pubkeyblock (ctrl, keyid);
645 log_error ("error checking usability status of %s\n", keystr (keyid));
649 pk = keyblock->pkt->pkt.public_key;
651 /* Is the key revoked or expired? */
652 if (pk->flags.revoked || pk->has_expired)
655 /* Is the user ID in question revoked or expired? */
656 if (!unusable && uid_no)
661 for (node = keyblock; node; node = node->next)
663 if (node->pkt->pkttype == PKT_USER_ID)
665 PKT_user_id *user_id = node->pkt->pkt.user_id;
668 if (uids_seen != uid_no)
671 if (user_id->flags.revoked || user_id->flags.expired)
678 /* If UID_NO is non-zero, then the keyblock better have at least
680 log_assert (uids_seen == uid_no);
684 unusable = pk_is_disabled (pk);
687 release_kbnode (keyblock);
692 /* Search for keys matching some criteria.
694 If RETCTX is not NULL, then the constructed context is returned in
695 *RETCTX so that getpubkey_next can be used to get subsequent
696 results. In this case, getkey_end() must be used to free the
697 search context. If RETCTX is not NULL, then RET_KDBHD must be
700 If NAMELIST is not NULL, then a search query is constructed using
701 classify_user_id on each of the strings in the list. (Recall: the
702 database does an OR of the terms, not an AND.) If NAMELIST is
703 NULL, then all results are returned.
705 If PK is not NULL, the public key of the first result is returned
706 in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
707 set, it is used to filter the search results. See the
708 documentation for finish_lookup to understand exactly how this is
709 used. Note: The self-signed data has already been merged into the
710 public key using merge_selfsigs. Free *PK by calling
711 release_public_key_parts (or, if PK was allocated using xfree, you
712 can use free_public_key, which calls release_public_key_parts(PK)
715 If WANT_SECRET is set, then only keys with an available secret key
716 (either locally or via key registered on a smartcard) are returned.
718 If INCLUDE_UNUSABLE is set, then unusable keys (see the
719 documentation for skip_unusable for an exact definition) are
720 skipped unless they are looked up by key id or by fingerprint.
722 If RET_KB is not NULL, the keyblock is returned in *RET_KB. This
723 should be freed using release_kbnode().
725 If RET_KDBHD is not NULL, then the new database handle used to
726 conduct the search is returned in *RET_KDBHD. This can be used to
727 get subsequent results using keydb_search_next. Note: in this
728 case, no advanced filtering is done for subsequent results (e.g.,
729 WANT_SECRET and PK->REQ_USAGE are not respected).
731 This function returns 0 on success. Otherwise, an error code is
732 returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
733 (if want_secret is set) is returned if the key is not found. */
735 key_byname (ctrl_t ctrl, GETKEY_CTX *retctx, strlist_t namelist,
737 int want_secret, int include_unusable,
738 KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
743 strlist_t namelist_expanded = NULL;
745 KBNODE help_kb = NULL;
746 KBNODE found_key = NULL;
750 /* Reset the returned context in case of error. */
751 log_assert (!ret_kdbhd); /* Not allowed because the handle is stored
759 /* No search terms: iterate over the whole DB. */
761 ctx = xmalloc_clear (sizeof *ctx);
763 ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
764 if (!include_unusable)
766 ctx->items[0].skipfnc = skip_unusable;
767 ctx->items[0].skipfncvalue = ctrl;
772 namelist_expanded = expand_group (namelist, 1);
773 namelist = namelist_expanded;
775 /* Build the search context. */
776 for (n = 0, r = namelist; r; r = r->next)
779 /* CTX has space for a single search term at the end. Thus, we
780 need to allocate sizeof *CTX plus (n - 1) sizeof
782 ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
785 for (n = 0, r = namelist; r; r = r->next, n++)
789 err = classify_user_id (r->d, &ctx->items[n], 1);
791 if (ctx->items[n].exact)
796 rc = gpg_err_code (err); /* FIXME: remove gpg_err_code. */
799 if (!include_unusable
800 && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
801 && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
802 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
804 ctx->items[n].skipfnc = skip_unusable;
805 ctx->items[n].skipfncvalue = ctrl;
810 ctx->want_secret = want_secret;
811 ctx->kr_handle = keydb_new (ctrl);
814 rc = gpg_error_from_syserror ();
815 getkey_end (ctrl, ctx);
824 ctx->req_usage = pk->req_usage;
827 rc = lookup (ctrl, ctx, want_secret, ret_kb, &found_key);
830 pk_from_block (pk, *ret_kb, found_key);
833 release_kbnode (help_kb);
835 if (retctx) /* Caller wants the context. */
839 for (r=ctx->extra_list; r->next; r = r->next)
841 r->next = namelist_expanded;
844 ctx->extra_list = namelist_expanded;
845 namelist_expanded = NULL;
852 *ret_kdbhd = ctx->kr_handle;
853 ctx->kr_handle = NULL;
855 getkey_end (ctrl, ctx);
859 free_strlist (namelist_expanded);
864 /* Find a public key identified by NAME.
866 * If name appears to be a valid RFC822 mailbox (i.e., email address)
867 * and auto key lookup is enabled (mode != GET_PUBKEY_NO_AKL), then
868 * the specified auto key lookup methods (--auto-key-lookup) are used
869 * to import the key into the local keyring. Otherwise, just the
870 * local keyring is consulted.
872 * MODE can be one of:
873 * GET_PUBKEY_NORMAL - The standard mode
874 * GET_PUBKEY_NO_AKL - The auto key locate functionality is
875 * disabled and only the local key ring is
876 * considered. Note: the local key ring is
877 * consulted even if local is not in the
878 * auto-key-locate option list!
879 * GET_PUBKEY_NO_LOCAL - Only the auto key locate functionality is
880 * used and no local search is done.
882 * If RETCTX is not NULL, then the constructed context is returned in
883 * *RETCTX so that getpubkey_next can be used to get subsequent
884 * results. In this case, getkey_end() must be used to free the
885 * search context. If RETCTX is not NULL, then RET_KDBHD must be
888 * If PK is not NULL, the public key of the first result is returned
889 * in *PK. Note: PK->REQ_USAGE must be valid!!! PK->REQ_USAGE is
890 * passed through to the lookup function and is a mask of
891 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this
892 * is non-zero, only keys with the specified usage will be returned.
893 * Note: The self-signed data has already been merged into the public
894 * key using merge_selfsigs. Free *PK by calling
895 * release_public_key_parts (or, if PK was allocated using xfree, you
896 * can use free_public_key, which calls release_public_key_parts(PK)
897 * and then xfree(PK)).
899 * NAME is a string, which is turned into a search query using
902 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
903 * *RET_KEYBLOCK. This should be freed using release_kbnode().
905 * If RET_KDBHD is not NULL, then the new database handle used to
906 * conduct the search is returned in *RET_KDBHD. This can be used to
907 * get subsequent results using keydb_search_next or to modify the
908 * returned record. Note: in this case, no advanced filtering is done
909 * for subsequent results (e.g., PK->REQ_USAGE is not respected).
910 * Unlike RETCTX, this is always returned.
912 * If INCLUDE_UNUSABLE is set, then unusable keys (see the
913 * documentation for skip_unusable for an exact definition) are
914 * skipped unless they are looked up by key id or by fingerprint.
916 * This function returns 0 on success. Otherwise, an error code is
917 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
918 * (if want_secret is set) is returned if the key is not found. */
920 get_pubkey_byname (ctrl_t ctrl, enum get_pubkey_modes mode,
921 GETKEY_CTX * retctx, PKT_public_key * pk,
922 const char *name, KBNODE * ret_keyblock,
923 KEYDB_HANDLE * ret_kdbhd, int include_unusable)
926 strlist_t namelist = NULL;
930 int anylocalfirst = 0;
931 int mechanism_type = AKL_NODEFAULT;
933 /* If RETCTX is not NULL, then RET_KDBHD must be NULL. */
934 log_assert (retctx == NULL || ret_kdbhd == NULL);
939 /* Does NAME appear to be a mailbox (mail address)? */
940 is_mbox = is_valid_mailbox (name);
941 if (!is_mbox && *name == '<' && name[1] && name[strlen(name)-1]=='>'
943 && is_valid_mailbox_mem (name+1, strlen (name)-2))
945 /* The mailbox is in the form "<foo@example.org>" which is not
946 * detected by is_valid_mailbox. Set the flag but keep name as
947 * it is because the bracketed name is actual the better
948 * specification for a local search and the other methods
949 * extract the mail address anyway. */
953 /* The auto-key-locate feature works as follows: there are a number
954 * of methods to look up keys. By default, the local keyring is
955 * tried first. Then, each method listed in the --auto-key-locate is
956 * tried in the order it appears.
958 * This can be changed as follows:
960 * - if nodefault appears anywhere in the list of options, then
961 * the local keyring is not tried first, or,
963 * - if local appears anywhere in the list of options, then the
964 * local keyring is not tried first, but in the order in which
965 * it was listed in the --auto-key-locate option.
967 * Note: we only save the search context in RETCTX if the local
968 * method is the first method tried (either explicitly or
970 if (mode == GET_PUBKEY_NO_LOCAL)
971 nodefault = 1; /* Auto-key-locate but ignore "local". */
972 else if (mode != GET_PUBKEY_NO_AKL)
974 /* auto-key-locate is enabled. */
976 /* nodefault is true if "nodefault" or "local" appear. */
977 for (akl = opt.auto_key_locate; akl; akl = akl->next)
978 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
983 /* anylocalfirst is true if "local" appears before any other
984 search methods (except "nodefault"). */
985 for (akl = opt.auto_key_locate; akl; akl = akl->next)
986 if (akl->type != AKL_NODEFAULT)
988 if (akl->type == AKL_LOCAL)
996 /* "nodefault" didn't occur. Thus, "local" is implicitly the
997 * first method to try. */
1001 if (mode == GET_PUBKEY_NO_LOCAL)
1003 /* Force using the AKL. If IS_MBOX is not set this is the final
1005 rc = GPG_ERR_NO_PUBKEY;
1007 else if (nodefault && is_mbox)
1009 /* Either "nodefault" or "local" (explicitly) appeared in the
1010 * auto key locate list and NAME appears to be an email address.
1011 * Don't try the local keyring. */
1012 rc = GPG_ERR_NO_PUBKEY;
1016 /* Either "nodefault" and "local" don't appear in the auto key
1017 * locate list (in which case we try the local keyring first) or
1018 * NAME does not appear to be an email address (in which case we
1019 * only try the local keyring). In this case, lookup NAME in
1020 * the local keyring. */
1021 add_to_strlist (&namelist, name);
1022 rc = key_byname (ctrl, retctx, namelist, pk, 0,
1023 include_unusable, ret_keyblock, ret_kdbhd);
1026 /* If the requested name resembles a valid mailbox and automatic
1027 retrieval has been enabled, we try to import the key. */
1028 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1029 && mode != GET_PUBKEY_NO_AKL
1032 /* NAME wasn't present in the local keyring (or we didn't try
1033 * the local keyring). Since the auto key locate feature is
1034 * enabled and NAME appears to be an email address, try the auto
1035 * locate feature. */
1036 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1038 unsigned char *fpr = NULL;
1040 int did_akl_local = 0;
1041 int no_fingerprint = 0;
1042 const char *mechanism_string = "?";
1044 mechanism_type = akl->type;
1045 switch (mechanism_type)
1048 /* This is a dummy mechanism. */
1049 mechanism_string = "";
1050 rc = GPG_ERR_NO_PUBKEY;
1054 if (mode == GET_PUBKEY_NO_LOCAL)
1056 mechanism_string = "";
1057 rc = GPG_ERR_NO_PUBKEY;
1061 mechanism_string = "Local";
1065 getkey_end (ctrl, *retctx);
1068 add_to_strlist (&namelist, name);
1069 rc = key_byname (ctrl, anylocalfirst ? retctx : NULL,
1071 include_unusable, ret_keyblock, ret_kdbhd);
1076 mechanism_string = "DNS CERT";
1077 glo_ctrl.in_auto_key_retrieve++;
1078 rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len);
1079 glo_ctrl.in_auto_key_retrieve--;
1083 /* This is now obsolete. */
1087 mechanism_string = "DANE";
1088 glo_ctrl.in_auto_key_retrieve++;
1089 rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len);
1090 glo_ctrl.in_auto_key_retrieve--;
1094 mechanism_string = "WKD";
1095 glo_ctrl.in_auto_key_retrieve++;
1096 rc = keyserver_import_wkd (ctrl, name, 0, &fpr, &fpr_len);
1097 glo_ctrl.in_auto_key_retrieve--;
1101 mechanism_string = "LDAP";
1102 glo_ctrl.in_auto_key_retrieve++;
1103 rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
1104 glo_ctrl.in_auto_key_retrieve--;
1108 mechanism_string = "NTDS";
1109 glo_ctrl.in_auto_key_retrieve++;
1110 rc = keyserver_import_ntds (ctrl, name, &fpr, &fpr_len);
1111 glo_ctrl.in_auto_key_retrieve--;
1115 /* Strictly speaking, we don't need to only use a valid
1116 * mailbox for the getname search, but it helps cut down
1117 * on the problem of searching for something like "john"
1118 * and getting a whole lot of keys back. */
1119 if (keyserver_any_configured (ctrl))
1121 mechanism_string = "keyserver";
1122 glo_ctrl.in_auto_key_retrieve++;
1123 rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
1125 glo_ctrl.in_auto_key_retrieve--;
1129 mechanism_string = "Unconfigured keyserver";
1130 rc = GPG_ERR_NO_PUBKEY;
1136 struct keyserver_spec *keyserver;
1138 mechanism_string = akl->spec->uri;
1139 keyserver = keyserver_match (akl->spec);
1140 glo_ctrl.in_auto_key_retrieve++;
1141 rc = keyserver_import_name (ctrl,
1142 name, &fpr, &fpr_len, keyserver);
1143 glo_ctrl.in_auto_key_retrieve--;
1148 /* Use the fingerprint of the key that we actually fetched.
1149 * This helps prevent problems where the key that we fetched
1150 * doesn't have the same name that we used to fetch it. In
1151 * the case of CERT, this is an actual security
1152 * requirement as the URL might point to a key put in by an
1153 * attacker. By forcing the use of the fingerprint, we
1154 * won't use the attacker's key here. */
1157 char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
1159 log_assert (fpr_len <= MAX_FINGERPRINT_LEN);
1161 free_strlist (namelist);
1164 bin2hex (fpr, fpr_len, fpr_string);
1167 log_info ("auto-key-locate found fingerprint %s\n",
1170 add_to_strlist (&namelist, fpr_string);
1172 else if (!rc && !fpr && !did_akl_local)
1173 { /* The acquisition method said no failure occurred, but
1174 * it didn't return a fingerprint. That's a failure. */
1176 rc = GPG_ERR_NO_PUBKEY;
1181 if (!rc && !did_akl_local)
1182 { /* There was no error and we didn't do a local lookup.
1183 * This means that we imported a key into the local
1184 * keyring. Try to read the imported key from the
1188 getkey_end (ctrl, *retctx);
1191 rc = key_byname (ctrl, anylocalfirst ? retctx : NULL,
1193 include_unusable, ret_keyblock, ret_kdbhd);
1199 log_info (_("automatically retrieved '%s' via %s\n"),
1200 name, mechanism_string);
1203 if ((gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1204 || opt.verbose || no_fingerprint) && *mechanism_string)
1205 log_info (_("error retrieving '%s' via %s: %s\n"),
1206 name, mechanism_string,
1207 no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
1213 getkey_end (ctrl, *retctx);
1217 if (retctx && *retctx)
1219 GETKEY_CTX ctx = *retctx;
1222 if (ctx->extra_list)
1224 for (sl=ctx->extra_list; sl->next; sl = sl->next)
1226 sl->next = namelist;
1229 ctx->extra_list = namelist;
1230 (*retctx)->found_via_akl = mechanism_type;
1233 free_strlist (namelist);
1241 /* Comparison machinery for get_best_pubkey_byname. */
1243 /* First we have a struct to cache computed information about the key
1245 struct pubkey_cmp_cookie
1247 int valid; /* Is this cookie valid? */
1248 PKT_public_key key; /* The key. */
1249 PKT_user_id *uid; /* The matching UID packet. */
1250 unsigned int validity; /* Computed validity of (KEY, UID). */
1251 u32 creation_time; /* Creation time of the newest subkey
1252 capable of encryption. */
1256 /* Then we have a series of helper functions. */
1258 key_is_ok (const PKT_public_key *key)
1260 return (! key->has_expired && ! key->flags.revoked
1261 && key->flags.valid && ! key->flags.disabled);
1266 uid_is_ok (const PKT_public_key *key, const PKT_user_id *uid)
1268 return key_is_ok (key) && ! uid->flags.revoked;
1273 subkey_is_ok (const PKT_public_key *sub)
1275 return ! sub->flags.revoked && sub->flags.valid && ! sub->flags.disabled;
1278 /* Return true if KEYBLOCK has only expired encryption subkeys. Note
1279 * that the function returns false if the key has no encryption
1280 * subkeys at all or the subkeys are revoked. */
1282 only_expired_enc_subkeys (kbnode_t keyblock)
1285 PKT_public_key *sub;
1288 for (node = find_next_kbnode (keyblock, PKT_PUBLIC_SUBKEY);
1289 node; node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY))
1291 sub = node->pkt->pkt.public_key;
1293 if (!(sub->pubkey_usage & PUBKEY_USAGE_ENC))
1296 if (!subkey_is_ok (sub))
1300 if (!sub->has_expired)
1307 /* Finally this function compares a NEW key to the former candidate
1308 * OLD. Returns < 0 if the old key is worse, > 0 if the old key is
1309 * better, == 0 if it is a tie. */
1311 pubkey_cmp (ctrl_t ctrl, const char *name, struct pubkey_cmp_cookie *old,
1312 struct pubkey_cmp_cookie *new, KBNODE new_keyblock)
1316 if ((new->key.pubkey_usage & PUBKEY_USAGE_ENC) == 0)
1317 new->creation_time = 0;
1319 new->creation_time = new->key.timestamp;
1321 for (n = find_next_kbnode (new_keyblock, PKT_PUBLIC_SUBKEY);
1322 n; n = find_next_kbnode (n, PKT_PUBLIC_SUBKEY))
1324 PKT_public_key *sub = n->pkt->pkt.public_key;
1326 if ((sub->pubkey_usage & PUBKEY_USAGE_ENC) == 0)
1329 if (! subkey_is_ok (sub))
1332 if (sub->timestamp > new->creation_time)
1333 new->creation_time = sub->timestamp;
1336 /* When new key has no encryption key, use OLD key. */
1337 if (new->creation_time == 0)
1340 for (n = find_next_kbnode (new_keyblock, PKT_USER_ID);
1341 n; n = find_next_kbnode (n, PKT_USER_ID))
1343 PKT_user_id *uid = n->pkt->pkt.user_id;
1344 char *mbox = mailbox_from_userid (uid->name, 0);
1345 int match = mbox ? strcasecmp (name, mbox) == 0 : 0;
1351 new->uid = scopy_user_id (uid);
1353 get_validity (ctrl, new_keyblock, &new->key, uid, NULL, 0) & TRUST_MASK;
1357 return -1; /* No OLD key. */
1359 if (! uid_is_ok (&old->key, old->uid) && uid_is_ok (&new->key, uid))
1360 return -1; /* Validity of the NEW key is better. */
1362 if (new->validity != TRUST_EXPIRED && old->validity < new->validity)
1363 return -1; /* Validity of the NEW key is better. */
1364 if (old->validity == TRUST_EXPIRED && new->validity != TRUST_EXPIRED)
1365 return -1; /* Validity of the NEW key is better. */
1367 if (old->validity == new->validity && uid_is_ok (&new->key, uid)
1368 && old->creation_time < new->creation_time)
1369 return -1; /* Both keys are of the same validity, but the
1370 NEW key is newer. */
1373 /* Stick with the OLD key. */
1378 /* This function works like get_pubkey_byname, but if the name
1379 * resembles a mail address, the results are ranked and only the best
1380 * result is returned. */
1382 get_best_pubkey_byname (ctrl_t ctrl, enum get_pubkey_modes mode,
1383 GETKEY_CTX *retctx, PKT_public_key *pk,
1384 const char *name, KBNODE *ret_keyblock,
1385 int include_unusable)
1388 struct getkey_ctx_s *ctx = NULL;
1393 log_assert (ret_keyblock != NULL);
1398 memset (&pk0, 0, sizeof pk0);
1399 pk0.req_usage = pk? pk->req_usage : 0;
1401 is_mbox = is_valid_mailbox (name);
1402 if (!is_mbox && *name == '<' && name[1] && name[strlen(name)-1]=='>'
1404 && is_valid_mailbox_mem (name+1, strlen (name)-2))
1406 /* The mailbox is in the form "<foo@example.org>" which is not
1407 * detected by is_valid_mailbox. Set the flag but keep name as
1408 * it is because get_pubkey_byname does an is_valid_mailbox_mem
1414 if (ctx) /* Clear in case of a start over. */
1416 release_kbnode (*ret_keyblock);
1417 *ret_keyblock = NULL;
1418 getkey_end (ctrl, ctx);
1421 err = get_pubkey_byname (ctrl, mode,
1422 &ctx, &pk0, name, ret_keyblock,
1423 NULL, include_unusable);
1429 /* If the keyblock was retrieved from the local database and the key
1430 * has expired, do further checks. However, we can do this only if
1431 * the caller requested a keyblock. */
1432 if (is_mbox && ctx && ctx->found_via_akl == AKL_LOCAL)
1434 u32 now = make_timestamp ();
1437 /* If the key has expired and its origin was the WKD then try to
1438 * get a fresh key from the WKD. We also try this if the key
1439 * has any only expired encryption subkeys. In case we checked
1440 * for a fresh copy in the last 3 hours we won't do that again.
1441 * Unfortunately that does not yet work because KEYUPDATE is
1442 * only updated during import iff the key has actually changed
1443 * (see import.c:import_one). */
1444 if (!wkd_tried && pk0.keyorg == KEYORG_WKD
1445 && (pk0.keyupdate + 3*3600) < now
1446 && (pk0.has_expired || only_expired_enc_subkeys (*ret_keyblock)))
1449 log_info (_("checking for a fresh copy of an expired key via %s\n"),
1452 glo_ctrl.in_auto_key_retrieve++;
1453 found = !keyserver_import_wkd (ctrl, name, 0, NULL, NULL);
1454 glo_ctrl.in_auto_key_retrieve--;
1457 release_public_key_parts (&pk0);
1465 /* Rank results and return only the most relevant key for encryption. */
1466 struct pubkey_cmp_cookie best = { 0 };
1467 struct pubkey_cmp_cookie new = { 0 };
1468 kbnode_t new_keyblock;
1470 copy_public_key (&new.key, &pk0);
1471 if (pubkey_cmp (ctrl, name, &best, &new, *ret_keyblock) >= 0)
1473 release_public_key_parts (&new.key);
1474 free_user_id (new.uid);
1480 while (getkey_next (ctrl, ctx, &new.key, &new_keyblock) == 0)
1482 int diff = pubkey_cmp (ctrl, name, &best, &new, new_keyblock);
1483 release_kbnode (new_keyblock);
1486 /* New key is better. */
1487 release_public_key_parts (&best.key);
1488 free_user_id (best.uid);
1493 /* Old key is better. */
1494 release_public_key_parts (&new.key);
1495 free_user_id (new.uid);
1499 /* A tie. Keep the old key. */
1500 release_public_key_parts (&new.key);
1501 free_user_id (new.uid);
1506 getkey_end (ctrl, ctx);
1508 free_user_id (best.uid);
1513 ctx = xtrycalloc (1, sizeof **retctx);
1515 err = gpg_error_from_syserror ();
1518 ctx->kr_handle = keydb_new (ctrl);
1519 if (! ctx->kr_handle)
1521 err = gpg_error_from_syserror ();
1529 u32 *keyid = pk_keyid (&best.key);
1532 ctx->items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
1533 ctx->items[0].u.kid[0] = keyid[0];
1534 ctx->items[0].u.kid[1] = keyid[1];
1536 release_kbnode (*ret_keyblock);
1537 *ret_keyblock = NULL;
1538 err = getkey_next (ctrl, ctx, NULL, ret_keyblock);
1545 release_public_key_parts (&best.key);
1546 release_public_key_parts (&pk0);
1553 release_public_key_parts (&pk0);
1561 release_public_key_parts (&pk0);
1566 getkey_end (ctrl, ctx);
1577 getkey_end (ctrl, ctx);
1583 /* Get a public key from a file.
1585 * PK is the buffer to store the key. The caller needs to make sure
1586 * that PK->REQ_USAGE is valid. PK->REQ_USAGE is passed through to
1587 * the lookup function and is a mask of PUBKEY_USAGE_SIG,
1588 * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this is non-zero, only
1589 * keys with the specified usage will be returned.
1591 * FNAME is the file name. That file should contain exactly one
1594 * This function returns 0 on success. Otherwise, an error code is
1595 * returned. In particular, GPG_ERR_NO_PUBKEY is returned if the key
1598 * The self-signed data has already been merged into the public key
1599 * using merge_selfsigs. The caller must release the content of PK by
1600 * calling release_public_key_parts (or, if PK was malloced, using
1604 get_pubkey_fromfile (ctrl_t ctrl, PKT_public_key *pk, const char *fname)
1609 unsigned int infoflags;
1611 err = read_key_from_file_or_buffer (ctrl, fname, NULL, 0, &keyblock);
1614 /* Warning: node flag bits 0 and 1 should be preserved by
1615 * merge_selfsigs. FIXME: Check whether this still holds. */
1616 merge_selfsigs (ctrl, keyblock);
1617 found_key = finish_lookup (keyblock, pk->req_usage, 0, 0, &infoflags);
1618 print_status_key_considered (keyblock, infoflags);
1620 pk_from_block (pk, keyblock, found_key);
1622 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
1625 release_kbnode (keyblock);
1630 /* Return a public key from the buffer (BUFFER, BUFLEN). The key is
1631 * onlyretruned if it matches the keyid given in WANT_KEYID. On
1632 * success the key is stored at the caller provided PKBUF structure.
1633 * The caller must release the content of PK by calling
1634 * release_public_key_parts (or, if PKBUF was malloced, using
1635 * free_public_key). If R_KEYBLOCK is not NULL the full keyblock is
1636 * also stored there. */
1638 get_pubkey_from_buffer (ctrl_t ctrl, PKT_public_key *pkbuf,
1639 const void *buffer, size_t buflen, u32 *want_keyid,
1640 kbnode_t *r_keyblock)
1650 err = read_key_from_file_or_buffer (ctrl, NULL, buffer, buflen, &keyblock);
1653 merge_selfsigs (ctrl, keyblock);
1654 for (node = keyblock; node; node = node->next)
1656 if (node->pkt->pkttype == PKT_PUBLIC_KEY
1657 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1659 pk = node->pkt->pkt.public_key;
1660 keyid_from_pk (pk, NULL);
1661 if (pk->keyid[0] == want_keyid[0]
1662 && pk->keyid[1] == want_keyid[1])
1667 copy_public_key (pkbuf, pk);
1669 err = gpg_error (GPG_ERR_NO_PUBKEY);
1672 if (!err && r_keyblock)
1673 *r_keyblock = keyblock;
1675 release_kbnode (keyblock);
1680 /* Lookup a key with the specified fingerprint.
1682 * If PK is not NULL, the public key of the first result is returned
1683 * in *PK. Note: this function does an exact search and thus the
1684 * returned public key may be a subkey rather than the primary key.
1685 * Note: The self-signed data has already been merged into the public
1686 * key using merge_selfsigs. Free *PK by calling
1687 * release_public_key_parts (or, if PK was allocated using xfree, you
1688 * can use free_public_key, which calls release_public_key_parts(PK)
1689 * and then xfree(PK)).
1691 * If PK->REQ_USAGE is set, it is used to filter the search results.
1692 * (Thus, if PK is not NULL, PK->REQ_USAGE must be valid!!!) See the
1693 * documentation for finish_lookup to understand exactly how this is
1696 * If R_KEYBLOCK is not NULL, then the first result's keyblock is
1697 * returned in *R_KEYBLOCK. This should be freed using
1700 * FPRINT is a byte array whose contents is the fingerprint to use as
1701 * the search term. FPRINT_LEN specifies the length of the
1702 * fingerprint (in bytes). Currently, only 16, 20, and 32-byte
1703 * fingerprints are supported.
1705 * FIXME: We should replace this with the _byname function. This can
1706 * be done by creating a userID conforming to the unified fingerprint
1709 get_pubkey_byfprint (ctrl_t ctrl, PKT_public_key *pk, kbnode_t *r_keyblock,
1710 const byte * fprint, size_t fprint_len)
1717 if (fprint_len == 32 || fprint_len == 20 || fprint_len == 16)
1719 struct getkey_ctx_s ctx;
1721 KBNODE found_key = NULL;
1723 memset (&ctx, 0, sizeof ctx);
1725 ctx.not_allocated = 1;
1726 /* FIXME: We should get the handle from the cache like we do in
1728 ctx.kr_handle = keydb_new (ctrl);
1730 return gpg_error_from_syserror ();
1733 ctx.items[0].mode = KEYDB_SEARCH_MODE_FPR;
1734 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1735 ctx.items[0].fprlen = fprint_len;
1737 ctx.req_usage = pk->req_usage;
1738 rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
1740 pk_from_block (pk, kb, found_key);
1741 if (!rc && r_keyblock)
1746 release_kbnode (kb);
1747 getkey_end (ctrl, &ctx);
1750 rc = GPG_ERR_GENERAL; /* Oops */
1755 /* This function is similar to get_pubkey_byfprint, but it doesn't
1756 * merge the self-signed data into the public key and subkeys or into
1757 * the user ids. It also doesn't add the key to the user id cache.
1758 * Further, this function ignores PK->REQ_USAGE.
1760 * This function is intended to avoid recursion and, as such, should
1761 * only be used in very specific situations.
1763 * Like get_pubkey_byfprint, PK may be NULL. In that case, this
1764 * function effectively just checks for the existence of the key. */
1766 get_pubkey_byfprint_fast (ctrl_t ctrl, PKT_public_key * pk,
1767 const byte * fprint, size_t fprint_len)
1772 err = get_keyblock_byfprint_fast (ctrl,
1773 &keyblock, NULL, fprint, fprint_len, 0);
1777 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1778 release_kbnode (keyblock);
1785 /* This function is similar to get_pubkey_byfprint_fast but returns a
1786 * keydb handle at R_HD and the keyblock at R_KEYBLOCK. R_KEYBLOCK or
1787 * R_HD may be NULL. If LOCK is set the handle has been opend in
1788 * locked mode and keydb_disable_caching () has been called. On error
1789 * R_KEYBLOCK is set to NULL but R_HD must be released by the caller;
1790 * it may have a value of NULL, though. This allows to do an insert
1791 * operation on a locked keydb handle. */
1793 get_keyblock_byfprint_fast (ctrl_t ctrl,
1794 kbnode_t *r_keyblock, KEYDB_HANDLE *r_hd,
1795 const byte *fprint, size_t fprint_len, int lock)
1800 byte fprbuf[MAX_FINGERPRINT_LEN];
1808 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1809 fprbuf[i] = fprint[i];
1811 hd = keydb_new (ctrl);
1813 return gpg_error_from_syserror ();
1817 err = keydb_lock (hd);
1820 /* If locking did not work, we better don't return a handle
1821 * at all - there was a reason that locking has been
1826 keydb_disable_caching (hd);
1829 /* For all other errors we return the handle. */
1833 err = keydb_search_fpr (hd, fprbuf, fprint_len);
1834 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1838 return gpg_error (GPG_ERR_NO_PUBKEY);
1840 err = keydb_get_keyblock (hd, &keyblock);
1843 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (err));
1846 return gpg_error (GPG_ERR_NO_PUBKEY);
1849 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1850 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1852 /* Not caching key here since it won't have all of the fields
1856 *r_keyblock = keyblock;
1858 release_kbnode (keyblock);
1868 parse_def_secret_key (ctrl_t ctrl)
1870 KEYDB_HANDLE hd = NULL;
1874 for (t = opt.def_secret_key; t; t = t->next)
1877 KEYDB_SEARCH_DESC desc;
1881 err = classify_user_id (t->d, &desc, 1);
1884 log_error (_("secret key \"%s\" not found: %s\n"),
1885 t->d, gpg_strerror (err));
1887 log_info (_("(check argument of option '%s')\n"), "--default-key");
1893 hd = keydb_new (ctrl);
1898 keydb_search_reset (hd);
1901 err = keydb_search (hd, &desc, 1, NULL);
1902 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1907 log_error (_("key \"%s\" not found: %s\n"), t->d, gpg_strerror (err));
1912 err = keydb_get_keyblock (hd, &kb);
1915 log_error (_("error reading keyblock: %s\n"),
1916 gpg_strerror (err));
1920 merge_selfsigs (ctrl, kb);
1922 err = gpg_error (GPG_ERR_NO_SECKEY);
1926 PKT_public_key *pk = node->pkt->pkt.public_key;
1928 /* Check if the key is valid. */
1929 if (pk->flags.revoked)
1932 log_debug ("not using %s as default key, %s",
1933 keystr_from_pk (pk), "revoked");
1936 if (pk->has_expired)
1939 log_debug ("not using %s as default key, %s",
1940 keystr_from_pk (pk), "expired");
1943 if (pk_is_disabled (pk))
1946 log_debug ("not using %s as default key, %s",
1947 keystr_from_pk (pk), "disabled");
1951 if (agent_probe_secret_key (ctrl, pk))
1953 /* This is a valid key. */
1958 while ((node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY)));
1960 release_kbnode (kb);
1963 if (! warned && ! opt.quiet)
1965 log_info (_("Warning: not using '%s' as default key: %s\n"),
1966 t->d, gpg_strerror (GPG_ERR_NO_SECKEY));
1967 print_reported_error (err, GPG_ERR_NO_SECKEY);
1972 if (! warned && ! opt.quiet)
1973 log_info (_("using \"%s\" as default secret key for signing\n"),
1979 if (! warned && opt.def_secret_key && ! t)
1980 log_info (_("all values passed to '%s' ignored\n"),
1994 /* Look up a secret key.
1996 * If PK is not NULL, the public key of the first result is returned
1997 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
1998 * set, it is used to filter the search results. See the
1999 * documentation for finish_lookup to understand exactly how this is
2000 * used. Note: The self-signed data has already been merged into the
2001 * public key using merge_selfsigs. Free *PK by calling
2002 * release_public_key_parts (or, if PK was allocated using xfree, you
2003 * can use free_public_key, which calls release_public_key_parts(PK)
2004 * and then xfree(PK)).
2006 * If --default-key was set, then the specified key is looked up. (In
2007 * this case, the default key is returned even if it is considered
2008 * unusable. See the documentation for skip_unusable for exactly what
2011 * Otherwise, this initiates a DB scan that returns all keys that are
2012 * usable (see previous paragraph for exactly what usable means) and
2013 * for which a secret key is available.
2015 * This function returns the first match. Additional results can be
2016 * returned using getkey_next. */
2018 get_seckey_default (ctrl_t ctrl, PKT_public_key *pk)
2021 strlist_t namelist = NULL;
2022 int include_unusable = 1;
2025 const char *def_secret_key = parse_def_secret_key (ctrl);
2027 add_to_strlist (&namelist, def_secret_key);
2029 include_unusable = 0;
2031 err = key_byname (ctrl, NULL, namelist, pk, 1, include_unusable, NULL, NULL);
2033 free_strlist (namelist);
2040 /* Search for keys matching some criteria.
2042 * If RETCTX is not NULL, then the constructed context is returned in
2043 * *RETCTX so that getpubkey_next can be used to get subsequent
2044 * results. In this case, getkey_end() must be used to free the
2045 * search context. If RETCTX is not NULL, then RET_KDBHD must be
2048 * If PK is not NULL, the public key of the first result is returned
2049 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2050 * set, it is used to filter the search results. See the
2051 * documentation for finish_lookup to understand exactly how this is
2052 * used. Note: The self-signed data has already been merged into the
2053 * public key using merge_selfsigs. Free *PK by calling
2054 * release_public_key_parts (or, if PK was allocated using xfree, you
2055 * can use free_public_key, which calls release_public_key_parts(PK)
2056 * and then xfree(PK)).
2058 * If NAMES is not NULL, then a search query is constructed using
2059 * classify_user_id on each of the strings in the list. (Recall: the
2060 * database does an OR of the terms, not an AND.) If NAMES is
2061 * NULL, then all results are returned.
2063 * If WANT_SECRET is set, then only keys with an available secret key
2064 * (either locally or via key registered on a smartcard) are returned.
2066 * This function does not skip unusable keys (see the documentation
2067 * for skip_unusable for an exact definition).
2069 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2070 * *RET_KEYBLOCK. This should be freed using release_kbnode().
2072 * This function returns 0 on success. Otherwise, an error code is
2073 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2074 * (if want_secret is set) is returned if the key is not found. */
2076 getkey_bynames (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2077 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
2079 return key_byname (ctrl, retctx, names, pk, want_secret, 1,
2080 ret_keyblock, NULL);
2084 /* Search for one key matching some criteria.
2086 * If RETCTX is not NULL, then the constructed context is returned in
2087 * *RETCTX so that getpubkey_next can be used to get subsequent
2088 * results. In this case, getkey_end() must be used to free the
2089 * search context. If RETCTX is not NULL, then RET_KDBHD must be
2092 * If PK is not NULL, the public key of the first result is returned
2093 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2094 * set, it is used to filter the search results. See the
2095 * documentation for finish_lookup to understand exactly how this is
2096 * used. Note: The self-signed data has already been merged into the
2097 * public key using merge_selfsigs. Free *PK by calling
2098 * release_public_key_parts (or, if PK was allocated using xfree, you
2099 * can use free_public_key, which calls release_public_key_parts(PK)
2100 * and then xfree(PK)).
2102 * If NAME is not NULL, then a search query is constructed using
2103 * classify_user_id on the string. In this case, even unusable keys
2104 * (see the documentation for skip_unusable for an exact definition of
2105 * unusable) are returned. Otherwise, if --default-key was set, then
2106 * that key is returned (even if it is unusable). If neither of these
2107 * conditions holds, then the first usable key is returned.
2109 * If WANT_SECRET is set, then only keys with an available secret key
2110 * (either locally or via key registered on a smartcard) are returned.
2112 * This function does not skip unusable keys (see the documentation
2113 * for skip_unusable for an exact definition).
2115 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2116 * *RET_KEYBLOCK. This should be freed using release_kbnode().
2118 * This function returns 0 on success. Otherwise, an error code is
2119 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2120 * (if want_secret is set) is returned if the key is not found.
2122 * FIXME: We also have the get_pubkey_byname function which has a
2123 * different semantic. Should be merged with this one. */
2125 getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2126 const char *name, int want_secret, kbnode_t *ret_keyblock)
2129 strlist_t namelist = NULL;
2130 int with_unusable = 1;
2131 const char *def_secret_key = NULL;
2133 if (want_secret && !name)
2134 def_secret_key = parse_def_secret_key (ctrl);
2136 if (want_secret && !name && def_secret_key)
2137 add_to_strlist (&namelist, def_secret_key);
2139 add_to_strlist (&namelist, name);
2143 err = key_byname (ctrl, retctx, namelist, pk, want_secret, with_unusable,
2144 ret_keyblock, NULL);
2146 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
2147 WANT_SECRET has been used. */
2149 free_strlist (namelist);
2155 /* Return the next search result.
2157 * If PK is not NULL, the public key of the next result is returned in
2158 * *PK. Note: The self-signed data has already been merged into the
2159 * public key using merge_selfsigs. Free *PK by calling
2160 * release_public_key_parts (or, if PK was allocated using xmalloc, you
2161 * can use free_public_key, which calls release_public_key_parts(PK)
2162 * and then xfree(PK)).
2164 * RET_KEYBLOCK can be given as NULL; if it is not NULL it the entire
2165 * found keyblock is returned which must be released with
2166 * release_kbnode. If the function returns an error NULL is stored at
2169 * The self-signed data has already been merged into the public key
2170 * using merge_selfsigs. */
2172 getkey_next (ctrl_t ctrl, getkey_ctx_t ctx,
2173 PKT_public_key *pk, kbnode_t *ret_keyblock)
2175 int rc; /* Fixme: Make sure this is proper gpg_error */
2176 KBNODE keyblock = NULL;
2177 KBNODE found_key = NULL;
2179 /* We need to disable the caching so that for an exact key search we
2180 won't get the result back from the cache and thus end up in an
2181 endless loop. The endless loop can occur, because the cache is
2182 used without respecting the current file pointer! */
2183 keydb_disable_caching (ctx->kr_handle);
2185 /* FOUND_KEY is only valid as long as RET_KEYBLOCK is. If the
2186 * caller wants PK, but not RET_KEYBLOCK, we need hand in our own
2188 if (pk && ret_keyblock == NULL)
2189 ret_keyblock = &keyblock;
2191 rc = lookup (ctrl, ctx, ctx->want_secret,
2192 ret_keyblock, pk ? &found_key : NULL);
2195 log_assert (found_key);
2196 pk_from_block (pk, NULL, found_key);
2197 release_kbnode (keyblock);
2204 /* Release any resources used by a key listing context. This must be
2205 * called on the context returned by, e.g., getkey_byname. */
2207 getkey_end (ctrl_t ctrl, getkey_ctx_t ctx)
2211 #ifdef HAVE_W32_SYSTEM
2213 /* FIXME: This creates a big regression for Windows because the
2214 * keyring is only released after the global ctrl is released.
2215 * So if an operation does a getkey and then tries to modify the
2216 * keyring it will fail on Windows with a sharing violation. We
2217 * need to modify all keyring write operations to also take the
2218 * ctrl and close the cached_getkey_kdb handle to make writing
2219 * work. See: GnuPG-bug-id: 3097 */
2221 keydb_release (ctx->kr_handle);
2223 #else /*!HAVE_W32_SYSTEM*/
2225 if (ctrl && !ctrl->cached_getkey_kdb)
2226 ctrl->cached_getkey_kdb = ctx->kr_handle;
2228 keydb_release (ctx->kr_handle);
2230 #endif /*!HAVE_W32_SYSTEM*/
2232 free_strlist (ctx->extra_list);
2233 if (!ctx->not_allocated)
2240 /************************************************
2241 ************* Merging stuff ********************
2242 ************************************************/
2244 /* Set the mainkey_id fields for all keys in KEYBLOCK. This is
2245 * usually done by merge_selfsigs but at some places we only need the
2246 * main_kid not a full merge. The function also guarantees that all
2247 * pk->keyids are computed. */
2249 setup_main_keyids (kbnode_t keyblock)
2251 u32 kid[2], mainkid[2];
2252 kbnode_t kbctx, node;
2255 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2257 pk = keyblock->pkt->pkt.public_key;
2259 keyid_from_pk (pk, mainkid);
2260 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
2262 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
2263 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
2265 pk = node->pkt->pkt.public_key;
2266 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
2267 if (!pk->main_keyid[0] && !pk->main_keyid[1])
2269 pk->main_keyid[0] = mainkid[0];
2270 pk->main_keyid[1] = mainkid[1];
2276 /* KEYBLOCK corresponds to a public key block. This function merges
2277 * much of the information from the self-signed data into the public
2278 * key, public subkey and user id data structures. If you use the
2279 * high-level search API (e.g., get_pubkey) for looking up key blocks,
2280 * then you don't need to call this function. This function is
2281 * useful, however, if you change the keyblock, e.g., by adding or
2282 * removing a self-signed data packet. */
2284 merge_keys_and_selfsig (ctrl_t ctrl, kbnode_t keyblock)
2288 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
2289 merge_selfsigs (ctrl, keyblock);
2291 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
2296 parse_key_usage (PKT_signature * sig)
2303 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_FLAGS, &n);
2306 /* First octet of the keyflags. */
2311 key_usage |= PUBKEY_USAGE_CERT;
2317 key_usage |= PUBKEY_USAGE_SIG;
2321 /* We do not distinguish between encrypting communications and
2322 encrypting storage. */
2323 if (flags & (0x04 | 0x08))
2325 key_usage |= PUBKEY_USAGE_ENC;
2326 flags &= ~(0x04 | 0x08);
2331 key_usage |= PUBKEY_USAGE_AUTH;
2336 key_usage |= PUBKEY_USAGE_UNKNOWN;
2339 key_usage |= PUBKEY_USAGE_NONE;
2341 else if (p) /* Key flags of length zero. */
2342 key_usage |= PUBKEY_USAGE_NONE;
2344 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
2345 capability that we do not handle. This serves to distinguish
2346 between a zero key usage which we handle as the default
2347 capabilities for that algorithm, and a usage that we do not
2348 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
2349 key_flags have been given but they do not specify any usage. */
2355 /* Apply information from SIGNODE (which is the valid self-signature
2356 * associated with that UID) to the UIDNODE:
2357 * - wether the UID has been revoked
2358 * - assumed creation date of the UID
2359 * - temporary store the keyflags here
2360 * - temporary store the key expiration time here
2361 * - mark whether the primary user ID flag hat been set.
2362 * - store the preferences
2365 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
2367 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
2368 PKT_signature *sig = signode->pkt->pkt.signature;
2369 const byte *p, *sym, *aead, *hash, *zip;
2370 size_t n, nsym, naead, nhash, nzip;
2372 sig->flags.chosen_selfsig = 1;/* We chose this one. */
2373 uid->created = 0; /* Not created == invalid. */
2374 if (IS_UID_REV (sig))
2376 uid->flags.revoked = 1;
2377 return; /* Has been revoked. */
2380 uid->flags.revoked = 0;
2382 uid->expiredate = sig->expiredate;
2384 if (sig->flags.expired)
2386 uid->flags.expired = 1;
2387 return; /* Has expired. */
2390 uid->flags.expired = 0;
2392 uid->created = sig->timestamp; /* This one is okay. */
2393 uid->selfsigversion = sig->version;
2394 /* If we got this far, it's not expired :) */
2395 uid->flags.expired = 0;
2397 /* Store the key flags in the helper variable for later processing. */
2398 uid->help_key_usage = parse_key_usage (sig);
2400 /* Ditto for the key expiration. */
2401 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
2402 if (p && buf32_to_u32 (p))
2403 uid->help_key_expire = keycreated + buf32_to_u32 (p);
2405 uid->help_key_expire = 0;
2407 /* Set the primary user ID flag - we will later wipe out some
2408 * of them to only have one in our keyblock. */
2409 uid->flags.primary = 0;
2410 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PRIMARY_UID, NULL);
2412 uid->flags.primary = 2;
2414 /* We could also query this from the unhashed area if it is not in
2415 * the hased area and then later try to decide which is the better
2416 * there should be no security problem with this.
2417 * For now we only look at the hashed one. */
2419 /* Now build the preferences list. These must come from the
2420 hashed section so nobody can modify the ciphers a key is
2421 willing to accept. */
2422 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_SYM, &n);
2425 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_AEAD, &n);
2428 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_HASH, &n);
2431 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_COMPR, &n);
2436 n = nsym + naead + nhash + nzip;
2441 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
2443 for (; nsym; nsym--, n++)
2445 uid->prefs[n].type = PREFTYPE_SYM;
2446 uid->prefs[n].value = *sym++;
2448 for (; naead; naead--, n++)
2450 uid->prefs[n].type = PREFTYPE_AEAD;
2451 uid->prefs[n].value = *aead++;
2453 for (; nhash; nhash--, n++)
2455 uid->prefs[n].type = PREFTYPE_HASH;
2456 uid->prefs[n].value = *hash++;
2458 for (; nzip; nzip--, n++)
2460 uid->prefs[n].type = PREFTYPE_ZIP;
2461 uid->prefs[n].value = *zip++;
2463 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
2464 uid->prefs[n].value = 0;
2467 /* See whether we have the MDC feature. */
2469 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n);
2470 if (p && n && (p[0] & 0x01))
2473 /* See whether we have the AEAD feature. */
2474 uid->flags.aead = 0;
2475 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n);
2476 if (p && n && (p[0] & 0x02))
2477 uid->flags.aead = 1;
2479 /* And the keyserver modify flag. */
2480 uid->flags.ks_modify = 1;
2481 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KS_FLAGS, &n);
2482 if (p && n && (p[0] & 0x80))
2483 uid->flags.ks_modify = 0;
2487 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
2489 rinfo->date = sig->timestamp;
2490 rinfo->algo = sig->pubkey_algo;
2491 rinfo->keyid[0] = sig->keyid[0];
2492 rinfo->keyid[1] = sig->keyid[1];
2496 /* Given a keyblock, parse the key block and extract various pieces of
2497 * information and save them with the primary key packet and the user
2498 * id packets. For instance, some information is stored in signature
2499 * packets. We find the latest such valid packet (since the user can
2500 * change that information) and copy its contents into the
2503 * Note that R_REVOKED may be set to 0, 1 or 2.
2505 * This function fills in the following fields in the primary key's
2508 * main_keyid (computed)
2509 * revkey / numrevkeys (derived from self signed key data)
2510 * flags.valid (whether we have at least 1 self-sig)
2511 * flags.maybe_revoked (whether a designed revoked the key, but
2512 * we are missing the key to check the sig)
2513 * selfsigversion (highest version of any valid self-sig)
2514 * pubkey_usage (derived from most recent self-sig or most
2516 * has_expired (various sources)
2517 * expiredate (various sources)
2519 * See the documentation for fixup_uidnode for how the user id packets
2520 * are modified. In addition to that the primary user id's is_primary
2521 * field is set to 1 and the other user id's is_primary are set to 0.
2524 merge_selfsigs_main (ctrl_t ctrl, kbnode_t keyblock, int *r_revoked,
2525 struct revoke_info *rinfo)
2527 PKT_public_key *pk = NULL;
2530 u32 sigdate, uiddate, uiddate2;
2531 KBNODE signode, uidnode, uidnode2;
2532 u32 curtime = make_timestamp ();
2533 unsigned int key_usage = 0;
2534 u32 keytimestamp = 0; /* Creation time of the key. */
2536 int key_expire_seen = 0;
2537 byte sigversion = 0;
2540 memset (rinfo, 0, sizeof (*rinfo));
2542 /* Section 11.1 of RFC 4880 determines the order of packets within a
2543 * message. There are three sections, which must occur in the
2544 * following order: the public key, the user ids and user attributes
2545 * and the subkeys. Within each section, each primary packet (e.g.,
2546 * a user id packet) is followed by one or more signature packets,
2547 * which modify that packet. */
2549 /* According to Section 11.1 of RFC 4880, the public key must be the
2550 first packet. Note that parse_keyblock_image ensures that the
2551 first packet is the public key. */
2552 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2554 pk = keyblock->pkt->pkt.public_key;
2555 keytimestamp = pk->timestamp;
2557 keyid_from_pk (pk, kid);
2558 pk->main_keyid[0] = kid[0];
2559 pk->main_keyid[1] = kid[1];
2561 if (pk->version < 4)
2563 /* Before v4 the key packet itself contains the expiration date
2564 * and there was no way to change it, so we start with the one
2565 * from the key packet. We do not support v3 keys anymore but
2566 * we keep the code in case a future key versions introduces a
2567 * hadr expire time again. */
2568 key_expire = pk->max_expiredate;
2569 key_expire_seen = 1;
2574 * - Find the latest direct key self-signature. We assume that the
2575 * newest one overrides all others.
2577 * - Determine whether the key has been revoked.
2579 * - Gather all revocation keys (unlike other data, we don't just
2580 * take them from the latest self-signed packet).
2582 * - Determine max (sig[...]->version).
2585 /* Reset this in case this key was already merged. */
2591 sigdate = 0; /* Helper variable to find the latest signature. */
2593 /* According to Section 11.1 of RFC 4880, the public key comes first
2594 * and is immediately followed by any signature packets that modify
2597 k && k->pkt->pkttype != PKT_USER_ID
2598 && k->pkt->pkttype != PKT_ATTRIBUTE
2599 && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2602 if (k->pkt->pkttype == PKT_SIGNATURE)
2604 PKT_signature *sig = k->pkt->pkt.signature;
2605 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2608 if (check_key_signature (ctrl, keyblock, k, NULL))
2609 ; /* Signature did not verify. */
2610 else if (IS_KEY_REV (sig))
2612 /* Key has been revoked - there is no way to
2613 * override such a revocation, so we theoretically
2614 * can stop now. We should not cope with expiration
2615 * times for revocations here because we have to
2616 * assume that an attacker can generate all kinds of
2617 * signatures. However due to the fact that the key
2618 * has been revoked it does not harm either and by
2619 * continuing we gather some more info on that
2622 sig_to_revoke_info (sig, rinfo);
2624 else if (IS_KEY_SIG (sig))
2626 /* Add the indicated revocations keys from all
2627 * signatures not just the latest. We do this
2628 * because you need multiple 1F sigs to properly
2629 * handle revocation keys (PGP does it this way, and
2630 * a revocation key could be sensitive and hence in
2631 * a different signature). */
2637 xrealloc (pk->revkey, sizeof (struct revocation_key) *
2638 (pk->numrevkeys + sig->numrevkeys));
2640 for (i = 0; i < sig->numrevkeys; i++, pk->numrevkeys++)
2642 pk->revkey[pk->numrevkeys].class
2643 = sig->revkey[i].class;
2644 pk->revkey[pk->numrevkeys].algid
2645 = sig->revkey[i].algid;
2646 pk->revkey[pk->numrevkeys].fprlen
2647 = sig->revkey[i].fprlen;
2648 memcpy (pk->revkey[pk->numrevkeys].fpr,
2649 sig->revkey[i].fpr, sig->revkey[i].fprlen);
2650 memset (pk->revkey[pk->numrevkeys].fpr
2651 + sig->revkey[i].fprlen,
2653 sizeof (sig->revkey[i].fpr)
2654 - sig->revkey[i].fprlen);
2658 if (sig->timestamp >= sigdate)
2659 { /* This is the latest signature so far. */
2661 if (sig->flags.expired)
2662 ; /* Signature has expired - ignore it. */
2665 sigdate = sig->timestamp;
2667 if (sig->version > sigversion)
2668 sigversion = sig->version;
2677 /* Remove dupes from the revocation keys. */
2680 int i, j, x, changed = 0;
2682 for (i = 0; i < pk->numrevkeys; i++)
2684 for (j = i + 1; j < pk->numrevkeys; j++)
2686 if (memcmp (&pk->revkey[i], &pk->revkey[j],
2687 sizeof (struct revocation_key)) == 0)
2691 for (x = j; x < pk->numrevkeys - 1; x++)
2692 pk->revkey[x] = pk->revkey[x + 1];
2702 pk->revkey = xrealloc (pk->revkey,
2704 sizeof (struct revocation_key));
2707 /* SIGNODE is the direct key signature packet (sigclass 0x1f) with
2708 * the latest creation time. Extract some information from it. */
2711 /* Some information from a direct key signature take precedence
2712 * over the same information given in UID sigs. */
2713 PKT_signature *sig = signode->pkt->pkt.signature;
2716 key_usage = parse_key_usage (sig);
2718 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
2719 if (p && buf32_to_u32 (p))
2721 key_expire = keytimestamp + buf32_to_u32 (p);
2722 key_expire_seen = 1;
2725 /* Mark that key as valid: One direct key signature should
2726 * render a key as valid. */
2727 pk->flags.valid = 1;
2730 /* Pass 1.5: Look for key revocation signatures that were not made
2731 * by the key (i.e. did a revocation key issue a revocation for
2732 * us?). Only bother to do this if there is a revocation key in the
2733 * first place and we're not revoked already. */
2735 if (!*r_revoked && pk->revkey)
2736 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
2738 if (k->pkt->pkttype == PKT_SIGNATURE)
2740 PKT_signature *sig = k->pkt->pkt.signature;
2742 if (IS_KEY_REV (sig) &&
2743 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
2745 int rc = check_revocation_keys (ctrl, pk, sig);
2749 sig_to_revoke_info (sig, rinfo);
2750 /* Don't continue checking since we can't be any
2751 * more revoked than this. */
2754 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2755 pk->flags.maybe_revoked = 1;
2757 /* A failure here means the sig did not verify, was
2758 * not issued by a revocation key, or a revocation
2759 * key loop was broken. If a revocation key isn't
2760 * findable, however, the key might be revoked and
2761 * we don't know it. */
2763 /* Fixme: In the future handle subkey and cert
2764 * revocations? PGP doesn't, but it's in 2440. */
2769 /* Second pass: Look at the self-signature of all user IDs. */
2771 /* According to RFC 4880 section 11.1, user id and attribute packets
2772 * are in the second section, after the public key packet and before
2773 * the subkey packets. */
2774 signode = uidnode = NULL;
2775 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
2776 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2778 if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
2779 { /* New user id packet. */
2781 /* Apply the data from the most recent self-signed packet to
2782 * the preceding user id packet. */
2783 if (uidnode && signode)
2785 fixup_uidnode (uidnode, signode, keytimestamp);
2786 pk->flags.valid = 1;
2789 /* Clear SIGNODE. The only relevant self-signed data for
2790 * UIDNODE follows it. */
2791 if (k->pkt->pkttype == PKT_USER_ID)
2799 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2801 PKT_signature *sig = k->pkt->pkt.signature;
2802 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2804 if (check_key_signature (ctrl, keyblock, k, NULL))
2805 ; /* signature did not verify */
2806 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
2807 && sig->timestamp >= sigdate)
2809 /* Note: we allow invalidation of cert revocations
2810 * by a newer signature. An attacker can't use this
2811 * because a key should be revoked with a key revocation.
2812 * The reason why we have to allow for that is that at
2813 * one time an email address may become invalid but later
2814 * the same email address may become valid again (hired,
2815 * fired, hired again). */
2817 sigdate = sig->timestamp;
2819 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2820 if (sig->version > sigversion)
2821 sigversion = sig->version;
2826 if (uidnode && signode)
2828 fixup_uidnode (uidnode, signode, keytimestamp);
2829 pk->flags.valid = 1;
2832 /* If the key isn't valid yet, and we have
2833 * --allow-non-selfsigned-uid set, then force it valid. */
2834 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
2837 log_info (_("Invalid key %s made valid by"
2838 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
2839 pk->flags.valid = 1;
2842 /* The key STILL isn't valid, so try and find an ultimately
2843 * trusted signature. */
2844 if (!pk->flags.valid)
2848 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2851 if (k->pkt->pkttype == PKT_USER_ID)
2853 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2855 PKT_signature *sig = k->pkt->pkt.signature;
2857 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
2859 PKT_public_key *ultimate_pk;
2861 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
2863 /* We don't want to use the full get_pubkey to avoid
2864 * infinite recursion in certain cases. There is no
2865 * reason to check that an ultimately trusted key is
2866 * still valid - if it has been revoked the user
2867 * should also remove the ultimate trust flag. */
2868 if (get_pubkey_fast (ctrl, ultimate_pk, sig->keyid) == 0
2869 && check_key_signature2 (ctrl,
2870 keyblock, k, ultimate_pk,
2871 NULL, NULL, NULL, NULL) == 0
2872 && get_ownertrust (ctrl, ultimate_pk) == TRUST_ULTIMATE)
2874 free_public_key (ultimate_pk);
2875 pk->flags.valid = 1;
2879 free_public_key (ultimate_pk);
2885 /* Record the highest selfsig version so we know if this is a v3 key
2886 * through and through, or a v3 key with a v4 selfsig somewhere.
2887 * This is useful in a few places to know if the key must be treated
2888 * as PGP2-style or OpenPGP-style. Note that a selfsig revocation
2889 * with a higher version number will also raise this value. This is
2890 * okay since such a revocation must be issued by the user (i.e. it
2891 * cannot be issued by someone else to modify the key behavior.) */
2893 pk->selfsigversion = sigversion;
2895 /* Now that we had a look at all user IDs we can now get some
2896 * information from those user IDs. */
2900 /* Find the latest user ID with key flags set. */
2901 uiddate = 0; /* Helper to find the latest user ID. */
2902 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2905 if (k->pkt->pkttype == PKT_USER_ID)
2907 PKT_user_id *uid = k->pkt->pkt.user_id;
2909 if (uid->help_key_usage
2910 && (uid->created > uiddate || (!uid->created && !uiddate)))
2912 key_usage = uid->help_key_usage;
2913 uiddate = uid->created;
2921 /* No key flags at all: get it from the algo. */
2922 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
2926 /* Check that the usage matches the usage as given by the algo. */
2927 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
2928 if (x) /* Mask it down to the actual allowed usage. */
2932 /* Whatever happens, it's a primary key, so it can certify. */
2933 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
2935 if (!key_expire_seen)
2937 /* Find the latest valid user ID with a key expiration set.
2938 * This may be a different one than from usage computation above
2939 * because some user IDs may have no expiration date set. */
2941 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2944 if (k->pkt->pkttype == PKT_USER_ID)
2946 PKT_user_id *uid = k->pkt->pkt.user_id;
2947 if (uid->help_key_expire
2948 && (uid->created > uiddate || (!uid->created && !uiddate)))
2950 key_expire = uid->help_key_expire;
2951 uiddate = uid->created;
2957 /* Currently only the not anymore supported v3 keys have a maximum
2958 * expiration date, but future key versions may get this feature again. */
2960 || (pk->max_expiredate && key_expire > pk->max_expiredate))
2961 key_expire = pk->max_expiredate;
2963 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
2964 pk->expiredate = key_expire;
2966 /* Fixme: we should see how to get rid of the expiretime fields but
2967 * this needs changes at other places too. */
2969 /* And now find the real primary user ID and delete all others. */
2970 uiddate = uiddate2 = 0;
2971 uidnode = uidnode2 = NULL;
2972 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2974 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
2976 PKT_user_id *uid = k->pkt->pkt.user_id;
2977 if (uid->flags.primary)
2979 if (uid->created > uiddate)
2981 uiddate = uid->created;
2984 else if (uid->created == uiddate && uidnode)
2986 /* The dates are equal, so we need to do a different
2987 * (and arbitrary) comparison. This should rarely,
2988 * if ever, happen. It's good to try and guarantee
2989 * that two different GnuPG users with two different
2990 * keyrings at least pick the same primary. */
2991 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
2997 if (uid->created > uiddate2)
2999 uiddate2 = uid->created;
3002 else if (uid->created == uiddate2 && uidnode2)
3004 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
3012 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3015 if (k->pkt->pkttype == PKT_USER_ID &&
3016 !k->pkt->pkt.user_id->attrib_data)
3018 PKT_user_id *uid = k->pkt->pkt.user_id;
3020 uid->flags.primary = 0;
3026 /* None is flagged primary - use the latest user ID we have,
3027 * and disambiguate with the arbitrary packet comparison. */
3028 uidnode2->pkt->pkt.user_id->flags.primary = 1;
3032 /* None of our uids were self-signed, so pick the one that
3033 * sorts first to be the primary. This is the best we can do
3034 * here since there are no self sigs to date the uids. */
3038 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3041 if (k->pkt->pkttype == PKT_USER_ID
3042 && !k->pkt->pkt.user_id->attrib_data)
3047 uidnode->pkt->pkt.user_id->flags.primary = 1;
3052 if (cmp_user_ids (k->pkt->pkt.user_id,
3053 uidnode->pkt->pkt.user_id) > 0)
3055 uidnode->pkt->pkt.user_id->flags.primary = 0;
3057 uidnode->pkt->pkt.user_id->flags.primary = 1;
3061 /* just to be safe: */
3062 k->pkt->pkt.user_id->flags.primary = 0;
3071 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
3072 * Caller must free the signature when they are done. */
3073 static PKT_signature *
3074 buf_to_sig (const byte * buf, size_t len)
3076 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
3077 IOBUF iobuf = iobuf_temp_with_content (buf, len);
3078 int save_mode = set_packet_list_mode (0);
3080 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
3082 free_seckey_enc (sig);
3086 set_packet_list_mode (save_mode);
3087 iobuf_close (iobuf);
3093 /* Use the self-signed data to fill in various fields in subkeys.
3095 * KEYBLOCK is the whole keyblock. SUBNODE is the subkey to fill in.
3097 * Sets the following fields on the subkey:
3100 * flags.valid if the subkey has a valid self-sig binding
3107 * On this subkey's most revent valid self-signed packet, the
3108 * following field is set:
3110 * flags.chosen_selfsig
3113 merge_selfsigs_subkey (ctrl_t ctrl, kbnode_t keyblock, kbnode_t subnode)
3115 PKT_public_key *mainpk = NULL, *subpk = NULL;
3121 u32 curtime = make_timestamp ();
3122 unsigned int key_usage = 0;
3123 u32 keytimestamp = 0;
3127 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3129 mainpk = keyblock->pkt->pkt.public_key;
3130 if (mainpk->version < 4)
3131 return;/* (actually this should never happen) */
3132 keyid_from_pk (mainpk, mainkid);
3133 subpk = subnode->pkt->pkt.public_key;
3134 keytimestamp = subpk->timestamp;
3136 subpk->flags.valid = 0;
3137 subpk->flags.exact = 0;
3138 subpk->main_keyid[0] = mainpk->main_keyid[0];
3139 subpk->main_keyid[1] = mainpk->main_keyid[1];
3141 /* Find the latest key binding self-signature. */
3143 sigdate = 0; /* Helper to find the latest signature. */
3144 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3147 if (k->pkt->pkttype == PKT_SIGNATURE)
3149 sig = k->pkt->pkt.signature;
3150 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
3152 if (check_key_signature (ctrl, keyblock, k, NULL))
3153 ; /* Signature did not verify. */
3154 else if (IS_SUBKEY_REV (sig))
3156 /* Note that this means that the date on a
3157 * revocation sig does not matter - even if the
3158 * binding sig is dated after the revocation sig,
3159 * the subkey is still marked as revoked. This
3160 * seems ok, as it is just as easy to make new
3161 * subkeys rather than re-sign old ones as the
3162 * problem is in the distribution. Plus, PGP (7)
3163 * does this the same way. */
3164 subpk->flags.revoked = 1;
3165 sig_to_revoke_info (sig, &subpk->revoked);
3166 /* Although we could stop now, we continue to
3167 * figure out other information like the old expiration
3170 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
3172 if (sig->flags.expired)
3173 ; /* Signature has expired - ignore it. */
3176 sigdate = sig->timestamp;
3178 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
3185 /* No valid key binding. */
3189 sig = signode->pkt->pkt.signature;
3190 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
3192 key_usage = parse_key_usage (sig);
3195 /* No key flags at all: get it from the algo. */
3196 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
3200 /* Check that the usage matches the usage as given by the algo. */
3201 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
3202 if (x) /* Mask it down to the actual allowed usage. */
3206 subpk->pubkey_usage = key_usage;
3208 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
3209 if (p && buf32_to_u32 (p))
3210 key_expire = keytimestamp + buf32_to_u32 (p);
3214 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
3215 subpk->expiredate = key_expire;
3217 /* Algo doesn't exist. */
3218 if (openpgp_pk_test_algo (subpk->pubkey_algo))
3221 subpk->flags.valid = 1;
3223 /* Find the most recent 0x19 embedded signature on our self-sig. */
3224 if (!subpk->flags.backsig)
3228 PKT_signature *backsig = NULL;
3232 /* We do this while() since there may be other embedded
3233 * signatures in the future. We only want 0x19 here. */
3235 while ((p = enum_sig_subpkt (sig, 1, SIGSUBPKT_SIGNATURE,
3238 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
3240 PKT_signature *tempsig = buf_to_sig (p, n);
3243 if (tempsig->timestamp > sigdate)
3246 free_seckey_enc (backsig);
3249 sigdate = backsig->timestamp;
3252 free_seckey_enc (tempsig);
3258 /* It is safe to have this in the unhashed area since the 0x19
3259 * is located on the selfsig for convenience, not security. */
3260 while ((p = enum_sig_subpkt (sig, 0, SIGSUBPKT_SIGNATURE,
3263 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
3265 PKT_signature *tempsig = buf_to_sig (p, n);
3268 if (tempsig->timestamp > sigdate)
3271 free_seckey_enc (backsig);
3274 sigdate = backsig->timestamp;
3277 free_seckey_enc (tempsig);
3283 /* At this point, backsig contains the most recent 0x19 sig.
3284 * Let's see if it is good. */
3286 /* 2==valid, 1==invalid, 0==didn't check */
3287 if (check_backsig (mainpk, subpk, backsig) == 0)
3288 subpk->flags.backsig = 2;
3290 subpk->flags.backsig = 1;
3292 free_seckey_enc (backsig);
3298 /* Merge information from the self-signatures with the public key,
3299 * subkeys and user ids to make using them more easy.
3301 * See documentation for merge_selfsigs_main, merge_selfsigs_subkey
3302 * and fixup_uidnode for exactly which fields are updated. */
3304 merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock)
3308 struct revoke_info rinfo;
3309 PKT_public_key *main_pk;
3311 unsigned int mdc_feature;
3312 unsigned int aead_feature;
3314 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
3316 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
3318 log_error ("expected public key but found secret key "
3320 /* We better exit here because a public key is expected at
3321 * other places too. FIXME: Figure this out earlier and
3322 * don't get to here at all */
3328 merge_selfsigs_main (ctrl, keyblock, &revoked, &rinfo);
3330 /* Now merge in the data from each of the subkeys. */
3331 for (k = keyblock; k; k = k->next)
3333 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3335 merge_selfsigs_subkey (ctrl, keyblock, k);
3339 main_pk = keyblock->pkt->pkt.public_key;
3340 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
3342 /* If the primary key is revoked, expired, or invalid we
3343 * better set the appropriate flags on that key and all
3345 for (k = keyblock; k; k = k->next)
3347 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3348 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3350 PKT_public_key *pk = k->pkt->pkt.public_key;
3351 if (!main_pk->flags.valid)
3352 pk->flags.valid = 0;
3353 if (revoked && !pk->flags.revoked)
3355 pk->flags.revoked = revoked;
3356 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
3358 if (main_pk->has_expired)
3360 pk->has_expired = main_pk->has_expired;
3361 if (!pk->expiredate || pk->expiredate > main_pk->expiredate)
3362 pk->expiredate = main_pk->expiredate;
3369 /* Set the preference list of all keys to those of the primary real
3370 * user ID. Note: we use these preferences when we don't know by
3371 * which user ID the key has been selected.
3372 * fixme: we should keep atoms of commonly used preferences or
3373 * use reference counting to optimize the preference lists storage.
3374 * FIXME: it might be better to use the intersection of
3376 * Do a similar thing for the MDC feature flag. */
3378 mdc_feature = aead_feature = 0;
3379 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3381 if (k->pkt->pkttype == PKT_USER_ID
3382 && !k->pkt->pkt.user_id->attrib_data
3383 && k->pkt->pkt.user_id->flags.primary)
3385 prefs = k->pkt->pkt.user_id->prefs;
3386 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
3387 aead_feature = k->pkt->pkt.user_id->flags.aead;
3391 for (k = keyblock; k; k = k->next)
3393 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3394 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3396 PKT_public_key *pk = k->pkt->pkt.public_key;
3399 pk->prefs = copy_prefs (prefs);
3400 pk->flags.mdc = mdc_feature;
3401 pk->flags.aead = aead_feature;
3408 /* See whether the key satisfies any additional requirements specified
3409 * in CTX. If so, return the node of an appropriate key or subkey.
3410 * Otherwise, return NULL if there was no appropriate key.
3412 * Note that we do not return a reference, i.e. the result must not be
3413 * freed using 'release_kbnode'.
3415 * In case the primary key is not required, select a suitable subkey.
3416 * We need the primary key if PUBKEY_USAGE_CERT is set in REQ_USAGE or
3417 * we are in PGP7 mode and PUBKEY_USAGE_SIG is set in
3420 * If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
3421 * are set in REQ_USAGE, we filter by the key's function. Concretely,
3422 * if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then we only
3423 * return a key if it is (at least) either a signing or a
3424 * certification key.
3426 * If REQ_USAGE is set, then we reject any keys that are not good
3427 * (i.e., valid, not revoked, not expired, etc.). This allows the
3428 * getkey functions to be used for plain key listings.
3430 * Sets the matched key's user id field (pk->user_id) to the user id
3431 * that matched the low-level search criteria or NULL.
3433 * If R_FLAGS is not NULL set certain flags for more detailed error
3434 * reporting. Used flags are:
3436 * - LOOKUP_ALL_SUBKEYS_EXPIRED :: All Subkeys are expired or have
3438 * - LOOKUP_NOT_SELECTED :: No suitable key found
3440 * This function needs to handle several different cases:
3442 * 1. No requested usage and no primary key requested
3443 * Examples for this case are that we have a keyID to be used
3444 * for decryption or verification.
3445 * 2. No usage but primary key requested
3446 * This is the case for all functions which work on an
3447 * entire keyblock, e.g. for editing or listing
3448 * 3. Usage and primary key requested
3450 * 4. Usage but no primary key requested
3455 finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact,
3456 int want_secret, unsigned int *r_flags)
3460 /* If WANT_EXACT is set, the key or subkey that actually matched the
3461 low-level search criteria. */
3462 kbnode_t foundk = NULL;
3463 /* The user id (if any) that matched the low-level search criteria. */
3464 PKT_user_id *foundu = NULL;
3467 kbnode_t latest_key;
3470 u32 curtime = make_timestamp ();
3475 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
3476 req_usage &= USAGE_MASK;
3478 /* Request the primary if we're certifying another key, and also if
3479 * signing data while --pgp7 is on since pgp 7 do
3480 * not understand signatures made by a signing subkey. PGP 8 does. */
3481 req_prim = ((req_usage & PUBKEY_USAGE_CERT)
3482 || (PGP7 && (req_usage & PUBKEY_USAGE_SIG)));
3485 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
3487 /* For an exact match mark the primary or subkey that matched the
3488 low-level search criteria. */
3491 for (k = keyblock; k; k = k->next)
3495 log_assert (k->pkt->pkttype == PKT_PUBLIC_KEY
3496 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3498 pk = k->pkt->pkt.public_key;
3499 pk->flags.exact = 1;
3505 /* Get the user id that matched that low-level search criteria. */
3506 for (k = keyblock; k; k = k->next)
3510 log_assert (k->pkt->pkttype == PKT_USER_ID);
3511 foundu = k->pkt->pkt.user_id;
3517 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
3518 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
3519 foundk ? "one" : "all", req_usage);
3523 latest_key = foundk ? foundk : keyblock;
3529 /* Set LATEST_KEY to the latest (the one with the most recent
3530 * timestamp) good (valid, not revoked, not expired, etc.) subkey.
3532 * Don't bother if we are only looking for a primary key or we need
3533 * an exact match and the exact match is not a subkey. */
3534 if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
3540 int n_revoked_or_expired = 0;
3541 int last_secret_key_avail = 0;
3543 /* Either start a loop or check just this one subkey. */
3544 for (k = foundk ? foundk : keyblock; k; k = nextk)
3548 /* If FOUNDK is not NULL, then only consider that exact
3549 key, i.e., don't iterate. */
3555 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3558 pk = k->pkt->pkt.public_key;
3560 log_debug ("\tchecking subkey %08lX\n",
3561 (ulong) keyid_from_pk (pk, NULL));
3563 if (!pk->flags.valid)
3566 log_debug ("\tsubkey not valid\n");
3569 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3572 log_debug ("\tusage does not match: want=%x have=%x\n",
3573 req_usage, pk->pubkey_usage);
3578 if (pk->flags.revoked)
3581 log_debug ("\tsubkey has been revoked\n");
3582 n_revoked_or_expired++;
3585 if (pk->has_expired)
3588 log_debug ("\tsubkey has expired\n");
3589 n_revoked_or_expired++;
3592 if (pk->timestamp > curtime && !opt.ignore_valid_from)
3595 log_debug ("\tsubkey not yet valid\n");
3601 int secret_key_avail = agent_probe_secret_key (NULL, pk);
3603 if (!secret_key_avail)
3606 log_debug ("\tno secret key\n");
3610 if (secret_key_avail > last_secret_key_avail)
3613 last_secret_key_avail = secret_key_avail;
3619 log_debug ("\tsubkey might be fine\n");
3620 /* In case a key has a timestamp of 0 set, we make sure
3621 that it is used. A better change would be to compare
3622 ">=" but that might also change the selected keys and
3623 is as such a more intrusive change. */
3624 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
3626 latest_date = pk->timestamp;
3630 if (n_subkeys == n_revoked_or_expired && r_flags)
3631 *r_flags |= LOOKUP_ALL_SUBKEYS_EXPIRED;
3634 /* Check if the primary key is ok (valid, not revoke, not expire,
3635 * matches requested usage) if:
3637 * - we didn't find an appropriate subkey and we're not doing an
3640 * - we're doing an exact match and the exact match was the
3643 * - we're just considering the primary key. */
3644 if ((!latest_key && !want_exact) || foundk == keyblock || req_prim)
3646 if (DBG_LOOKUP && !foundk && !req_prim)
3647 log_debug ("\tno suitable subkeys found - trying primary\n");
3648 pk = keyblock->pkt->pkt.public_key;
3649 if (!pk->flags.valid)
3652 log_debug ("\tprimary key not valid\n");
3654 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3657 log_debug ("\tprimary key usage does not match: "
3658 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
3660 else if (pk->flags.revoked)
3663 log_debug ("\tprimary key has been revoked\n");
3665 else if (pk->has_expired)
3668 log_debug ("\tprimary key has expired\n");
3673 log_debug ("\tprimary key may be used\n");
3674 latest_key = keyblock;
3681 log_debug ("\tno suitable key found - giving up\n");
3683 *r_flags |= LOOKUP_NOT_SELECTED;
3684 return NULL; /* Not found. */
3689 log_debug ("\tusing key %08lX\n",
3690 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
3694 pk = latest_key->pkt->pkt.public_key;
3695 free_user_id (pk->user_id);
3696 pk->user_id = scopy_user_id (foundu);
3699 if (latest_key != keyblock && opt.verbose)
3702 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
3703 log_info (_("using subkey %s instead of primary key %s\n"),
3704 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
3708 cache_put_keyblock (keyblock);
3710 return latest_key ? latest_key : keyblock; /* Found. */
3714 /* Print a KEY_CONSIDERED status line. */
3716 print_status_key_considered (kbnode_t keyblock, unsigned int flags)
3718 char hexfpr[2*MAX_FINGERPRINT_LEN + 1];
3722 if (!is_status_enabled ())
3725 for (node=keyblock; node; node = node->next)
3726 if (node->pkt->pkttype == PKT_PUBLIC_KEY
3727 || node->pkt->pkttype == PKT_SECRET_KEY)
3731 log_error ("%s: keyblock w/o primary key\n", __func__);
3735 hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr);
3736 snprintf (flagbuf, sizeof flagbuf, " %u", flags);
3737 write_status_strings (STATUS_KEY_CONSIDERED, hexfpr, flagbuf, NULL);
3742 /* A high-level function to lookup keys.
3744 * This function builds on top of the low-level keydb API. It first
3745 * searches the database using the description stored in CTX->ITEMS,
3746 * then it filters the results using CTX and, finally, if WANT_SECRET
3747 * is set, it ignores any keys for which no secret key is available.
3749 * Unlike the low-level search functions, this function also merges
3750 * all of the self-signed data into the keys, subkeys and user id
3751 * packets (see the merge_selfsigs for details).
3753 * On success the key's keyblock is stored at *RET_KEYBLOCK, and the
3754 * specific subkey is stored at *RET_FOUND_KEY. Note that we do not
3755 * return a reference in *RET_FOUND_KEY, i.e. the result must not be
3756 * freed using 'release_kbnode', and it is only valid until
3757 * *RET_KEYBLOCK is deallocated. Therefore, if RET_FOUND_KEY is not
3758 * NULL, then RET_KEYBLOCK must not be NULL. */
3760 lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret,
3761 kbnode_t *ret_keyblock, kbnode_t *ret_found_key)
3764 int no_suitable_key = 0;
3765 KBNODE keyblock = NULL;
3766 KBNODE found_key = NULL;
3767 unsigned int infoflags;
3769 log_assert (ret_found_key == NULL || ret_keyblock != NULL);
3771 *ret_keyblock = NULL;
3775 rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
3779 /* If we are iterating over the entire database, then we need to
3780 * change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
3781 * reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next record. */
3782 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
3783 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
3785 rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
3788 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
3794 rc = agent_probe_any_secret_key (NULL, keyblock);
3795 if (gpg_err_code(rc) == GPG_ERR_NO_SECKEY)
3796 goto skip; /* No secret key available. */
3798 goto found; /* Unexpected error. */
3801 /* Warning: node flag bits 0 and 1 should be preserved by
3802 * merge_selfsigs. */
3803 merge_selfsigs (ctrl, keyblock);
3804 found_key = finish_lookup (keyblock, ctx->req_usage, ctx->exact,
3805 want_secret, &infoflags);
3806 print_status_key_considered (keyblock, infoflags);
3809 no_suitable_key = 0;
3814 no_suitable_key = 1;
3818 /* Release resources and continue search. */
3819 release_kbnode (keyblock);
3821 /* The keyblock cache ignores the current "file position".
3822 * Thus, if we request the next result and the cache matches
3823 * (and it will since it is what we just looked for), we'll get
3824 * the same entry back! We can avoid this infinite loop by
3825 * disabling the cache. */
3826 keydb_disable_caching (ctx->kr_handle);
3830 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
3831 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
3837 *ret_keyblock = keyblock; /* Return the keyblock. */
3841 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
3842 rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
3843 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
3844 rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
3846 release_kbnode (keyblock);
3851 *ret_found_key = found_key;
3853 *ret_found_key = NULL;
3860 /* If a default key has been specified, return that key. If a card
3861 * based key is also available as indicated by FPR_CARD not being
3862 * NULL, return that key if suitable. */
3864 get_seckey_default_or_card (ctrl_t ctrl, PKT_public_key *pk,
3865 const byte *fpr_card, size_t fpr_len)
3868 strlist_t namelist = NULL;
3869 const char *def_secret_key;
3871 def_secret_key = parse_def_secret_key (ctrl);
3874 add_to_strlist (&namelist, def_secret_key);
3877 err = get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len);
3878 if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
3881 log_debug ("using LDAP to find public key for current card\n");
3882 err = keyserver_import_fprint (ctrl, fpr_card, fpr_len,
3884 KEYSERVER_IMPORT_FLAG_LDAP);
3886 err = get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len);
3887 else if (gpg_err_code (err) == GPG_ERR_NO_DATA
3888 || gpg_err_code (err) == GPG_ERR_NO_KEYSERVER)
3890 /* Dirmngr returns NO DATA is the selected keyserver
3891 * does not have the requested key. It returns NO
3892 * KEYSERVER if no LDAP keyservers are configured. */
3893 err = gpg_error (GPG_ERR_NO_PUBKEY);
3897 /* The key on card can be not suitable for requested usage. */
3898 if (gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY)
3899 fpr_card = NULL; /* Fallthrough as no card. */
3901 return err; /* Success or other error. */
3904 if (!fpr_card || (def_secret_key && *def_secret_key
3905 && def_secret_key[strlen (def_secret_key)-1] == '!'))
3907 err = key_byname (ctrl, NULL, namelist, pk, 1, 0, NULL, NULL);
3910 { /* Default key is specified and card key is also available. */
3911 kbnode_t k, keyblock = NULL;
3913 err = key_byname (ctrl, NULL, namelist, pk, 1, 0, &keyblock, NULL);
3916 for (k = keyblock; k; k = k->next)
3918 PKT_public_key *pk_candidate;
3919 char fpr[MAX_FINGERPRINT_LEN];
3921 if (k->pkt->pkttype != PKT_PUBLIC_KEY
3922 &&k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3925 pk_candidate = k->pkt->pkt.public_key;
3926 if (!pk_candidate->flags.valid)
3928 if (!((pk_candidate->pubkey_usage & USAGE_MASK) & pk->req_usage))
3930 fingerprint_from_pk (pk_candidate, fpr, NULL);
3931 if (!memcmp (fpr_card, fpr, fpr_len))
3933 release_public_key_parts (pk);
3934 copy_public_key (pk, pk_candidate);
3938 release_kbnode (keyblock);
3942 free_strlist (namelist);
3948 /*********************************************
3949 *********** User ID printing helpers *******
3950 *********************************************/
3952 /* Return a string with a printable representation of the user_id.
3953 * this string must be freed by xfree. If R_NOUID is not NULL it is
3954 * set to true if a user id was not found; otherwise to false. */
3956 get_user_id_string (ctrl_t ctrl, u32 * keyid, int mode)
3959 unsigned int namelen;
3962 log_assert (mode != 2);
3964 name = cache_get_uid_bykid (keyid, &namelen);
3967 /* Get it so that the cache will be filled. */
3968 if (!get_pubkey (ctrl, NULL, keyid))
3969 name = cache_get_uid_bykid (keyid, &namelen);
3975 p = xasprintf ("%08lX%08lX %.*s",
3976 (ulong) keyid[0], (ulong) keyid[1], namelen, name);
3978 p = xasprintf ("%s %.*s", keystr (keyid), namelen, name);
3985 p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
3987 p = xasprintf ("%s [?]", keystr (keyid));
3995 get_user_id_string_native (ctrl_t ctrl, u32 * keyid)
3997 char *p = get_user_id_string (ctrl, keyid, 0);
3998 char *p2 = utf8_to_native (p, strlen (p), 0);
4005 get_long_user_id_string (ctrl_t ctrl, u32 * keyid)
4007 return get_user_id_string (ctrl, keyid, 1);
4011 /* Please try to use get_user_byfpr instead of this one. */
4013 get_user_id (ctrl_t ctrl, u32 *keyid, size_t *rn, int *r_nouid)
4016 unsigned int namelen;
4021 name = cache_get_uid_bykid (keyid, &namelen);
4024 /* Get it so that the cache will be filled. */
4025 if (!get_pubkey (ctrl, NULL, keyid))
4026 name = cache_get_uid_bykid (keyid, &namelen);
4031 name = xstrdup (user_id_not_found_utf8 ());
4032 namelen = strlen (name);
4043 /* Please try to use get_user_id_byfpr_native instead of this one. */
4045 get_user_id_native (ctrl_t ctrl, u32 *keyid)
4048 char *p = get_user_id (ctrl, keyid, &rn, NULL);
4049 char *p2 = utf8_to_native (p, rn, 0);
4055 /* Return the user id for a key designated by its fingerprint, FPR,
4056 which must be MAX_FINGERPRINT_LEN bytes in size. Note: the
4057 returned string, which must be freed using xfree, may not be NUL
4058 terminated. To determine the length of the string, you must use
4061 get_user_id_byfpr (ctrl_t ctrl, const byte *fpr, size_t fprlen, size_t *rn)
4065 name = cache_get_uid_byfpr (fpr, fprlen, rn);
4068 /* Get it so that the cache will be filled. */
4069 if (!get_pubkey_byfprint (ctrl, NULL, NULL, fpr, fprlen))
4070 name = cache_get_uid_byfpr (fpr, fprlen, rn);
4075 name = xstrdup (user_id_not_found_utf8 ());
4076 *rn = strlen (name);
4082 /* Like get_user_id_byfpr, but convert the string to the native
4083 encoding. The returned string needs to be freed. Unlike
4084 get_user_id_byfpr, the returned string is NUL terminated. */
4086 get_user_id_byfpr_native (ctrl_t ctrl, const byte *fpr, size_t fprlen)
4089 char *p = get_user_id_byfpr (ctrl, fpr, fprlen, &rn);
4090 char *p2 = utf8_to_native (p, rn, 0);
4096 /* Return the database handle used by this context. The context still
4099 get_ctx_handle (GETKEY_CTX ctx)
4101 return ctx->kr_handle;
4105 free_akl (struct akl *akl)
4111 free_keyserver_spec (akl->spec);
4119 while (opt.auto_key_locate)
4121 struct akl *akl2 = opt.auto_key_locate;
4122 opt.auto_key_locate = opt.auto_key_locate->next;
4128 /* Returns true if the AKL is empty or has only the local method
4131 akl_empty_or_only_local (void)
4136 for (akl = opt.auto_key_locate; akl; akl = akl->next)
4137 if (akl->type != AKL_NODEFAULT && akl->type != AKL_LOCAL)
4147 /* Returns false on error. */
4149 parse_auto_key_locate (const char *options_arg)
4152 char *options, *options_buf;
4154 options = options_buf = xstrdup (options_arg);
4155 while ((tok = optsep (&options)))
4157 struct akl *akl, *check, *last = NULL;
4163 akl = xmalloc_clear (sizeof (*akl));
4165 if (ascii_strcasecmp (tok, "clear") == 0)
4168 free_akl (opt.auto_key_locate);
4169 opt.auto_key_locate = NULL;
4172 else if (ascii_strcasecmp (tok, "nodefault") == 0)
4173 akl->type = AKL_NODEFAULT;
4174 else if (ascii_strcasecmp (tok, "local") == 0)
4175 akl->type = AKL_LOCAL;
4176 else if (ascii_strcasecmp (tok, "ldap") == 0)
4177 akl->type = AKL_LDAP;
4178 else if (ascii_strcasecmp (tok, "keyserver") == 0)
4179 akl->type = AKL_KEYSERVER;
4180 else if (ascii_strcasecmp (tok, "cert") == 0)
4181 akl->type = AKL_CERT;
4182 else if (ascii_strcasecmp (tok, "pka") == 0)
4183 akl->type = AKL_PKA;
4184 else if (ascii_strcasecmp (tok, "dane") == 0)
4185 akl->type = AKL_DANE;
4186 else if (ascii_strcasecmp (tok, "wkd") == 0)
4187 akl->type = AKL_WKD;
4188 else if (ascii_strcasecmp (tok, "ntds") == 0)
4189 akl->type = AKL_NTDS;
4190 else if ((akl->spec = parse_keyserver_uri (tok, 1)))
4191 akl->type = AKL_SPEC;
4195 xfree (options_buf);
4199 /* We must maintain the order the user gave us */
4200 for (check = opt.auto_key_locate; check;
4201 last = check, check = check->next)
4203 /* Check for duplicates */
4204 if (check->type == akl->type
4205 && (akl->type != AKL_SPEC
4206 || (akl->type == AKL_SPEC
4207 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
4220 opt.auto_key_locate = akl;
4224 xfree (options_buf);
4230 /* The list of key origins. */
4234 } key_origin_list[] =
4236 { "self", KEYORG_SELF },
4237 { "file", KEYORG_FILE },
4238 { "url", KEYORG_URL },
4239 { "wkd", KEYORG_WKD },
4240 { "dane", KEYORG_DANE },
4241 { "ks-pref", KEYORG_KS_PREF },
4242 { "ks", KEYORG_KS },
4243 { "unknown", KEYORG_UNKNOWN }
4246 /* Parse the argument for --key-origin. Return false on error. */
4248 parse_key_origin (char *string)
4253 comma = strchr (string, ',');
4257 if (!ascii_strcasecmp (string, "help"))
4259 log_info (_("valid values for option '%s':\n"), "--key-origin");
4260 for (i=0; i < DIM (key_origin_list); i++)
4261 log_info (" %s\n", key_origin_list[i].name);
4265 for (i=0; i < DIM (key_origin_list); i++)
4266 if (!ascii_strcasecmp (string, key_origin_list[i].name))
4268 opt.key_origin = key_origin_list[i].origin;
4269 xfree (opt.key_origin_url);
4270 opt.key_origin_url = NULL;
4271 if (comma && comma[1])
4273 opt.key_origin_url = xstrdup (comma+1);
4274 trim_spaces (opt.key_origin_url);
4285 /* Return a string or "?" for the key ORIGIN. */
4287 key_origin_string (int origin)
4291 for (i=0; i < DIM (key_origin_list); i++)
4292 if (key_origin_list[i].origin == origin)
4293 return key_origin_list[i].name;
4299 /* Returns true if a secret key is available for the public key with
4300 key id KEYID; returns false if not. This function ignores legacy
4301 keys. Note: this is just a fast check and does not tell us whether
4302 the secret key is valid; this check merely indicates whether there
4303 is some secret key with the specified key id. */
4305 have_secret_key_with_kid (ctrl_t ctrl, u32 *keyid)
4309 KEYDB_SEARCH_DESC desc;
4314 kdbhd = keydb_new (ctrl);
4317 memset (&desc, 0, sizeof desc);
4318 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
4319 desc.u.kid[0] = keyid[0];
4320 desc.u.kid[1] = keyid[1];
4323 err = keydb_search (kdbhd, &desc, 1, NULL);
4327 err = keydb_get_keyblock (kdbhd, &keyblock);
4330 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
4334 for (node = keyblock; node; node = node->next)
4336 /* Bit 0 of the flags is set if the search found the key
4337 using that key or subkey. Note: a search will only ever
4338 match a single key or subkey. */
4339 if ((node->flag & 1))
4341 log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY
4342 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
4344 if (agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
4345 result = 1; /* Secret key available. */
4352 release_kbnode (keyblock);
4355 keydb_release (kdbhd);