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"
39 #include "../common/host2net.h"
40 #include "../common/mbox-util.h"
41 #include "../common/status.h"
43 #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
44 #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
46 #if MAX_PK_CACHE_ENTRIES < 2
47 #error We need the cache for key creation
50 /* Flags values returned by the lookup code. Note that the values are
51 * directly used by the KEY_CONSIDERED status line. */
52 #define LOOKUP_NOT_SELECTED (1<<0)
53 #define LOOKUP_ALL_SUBKEYS_EXPIRED (1<<1) /* or revoked */
56 /* A context object used by the lookup functions. */
59 /* Part of the search criteria: whether the search is an exact
60 search or not. A search that is exact requires that a key or
61 subkey meet all of the specified criteria. A search that is not
62 exact allows selecting a different key or subkey from the
63 keyblock that matched the critera. Further, an exact search
64 returns the key or subkey that matched whereas a non-exact search
65 typically returns the primary key. See finish_lookup for
69 /* Part of the search criteria: Whether the caller only wants keys
70 with an available secret key. This is used by getkey_next to get
71 the next result with the same initial criteria. */
74 /* Part of the search criteria: The type of the requested key. A
75 mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.
76 If non-zero, then for a key to match, it must implement one of
80 /* The database handle. */
81 KEYDB_HANDLE kr_handle;
83 /* Whether we should call xfree() on the context when the context is
84 released using getkey_end()). */
87 /* This variable is used as backing store for strings which have
88 their address used in ITEMS. */
91 /* Part of the search criteria: The low-level search specification
92 as passed to keydb_search. */
94 /* This must be the last element in the structure. When we allocate
95 the structure, we allocate it so that ITEMS can hold NITEMS. */
96 KEYDB_SEARCH_DESC items[1];
109 typedef struct keyid_list
111 struct keyid_list *next;
112 char fpr[MAX_FINGERPRINT_LEN];
117 #if MAX_PK_CACHE_ENTRIES
118 typedef struct pk_cache_entry
120 struct pk_cache_entry *next;
124 static pk_cache_entry_t pk_cache;
125 static int pk_cache_entries; /* Number of entries in pk cache. */
126 static int pk_cache_disabled;
129 #if MAX_UID_CACHE_ENTRIES < 5
130 #error we really need the userid cache
132 typedef struct user_id_db
134 struct user_id_db *next;
139 static user_id_db_t user_id_db;
140 static int uid_cache_entries; /* Number of entries in uid cache. */
142 static void merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock);
143 static int lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret,
144 kbnode_t *ret_keyblock, kbnode_t *ret_found_key);
145 static kbnode_t finish_lookup (kbnode_t keyblock,
146 unsigned int req_usage, int want_exact,
147 int want_secret, unsigned int *r_flags);
148 static void print_status_key_considered (kbnode_t keyblock, unsigned int flags);
156 for (i = 0; i < DIM (lkup_stats); i++)
158 if (lkup_stats[i].any)
159 es_fprintf (es_stderr,
160 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
162 lkup_stats[i].okay_count,
163 lkup_stats[i].nokey_count, lkup_stats[i].error_count);
169 /* Cache a copy of a public key in the public key cache. PK is not
170 * cached if caching is disabled (via getkey_disable_caches), if
171 * PK->FLAGS.DONT_CACHE is set, we don't know how to derive a key id
172 * from the public key (e.g., unsupported algorithm), or a key with
173 * the key id is already in the cache.
175 * The public key packet is copied into the cache using
176 * copy_public_key. Thus, any secret parts are not copied, for
179 * This cache is filled by get_pubkey and is read by get_pubkey and
180 * get_pubkey_fast. */
182 cache_public_key (PKT_public_key * pk)
184 #if MAX_PK_CACHE_ENTRIES
185 pk_cache_entry_t ce, ce2;
188 if (pk_cache_disabled)
191 if (pk->flags.dont_cache)
194 if (is_ELGAMAL (pk->pubkey_algo)
195 || pk->pubkey_algo == PUBKEY_ALGO_DSA
196 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
197 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
198 || pk->pubkey_algo == PUBKEY_ALGO_ECDH
199 || is_RSA (pk->pubkey_algo))
201 keyid_from_pk (pk, keyid);
204 return; /* Don't know how to get the keyid. */
206 for (ce = pk_cache; ce; ce = ce->next)
207 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
210 log_debug ("cache_public_key: already in cache\n");
214 if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
218 /* Remove the last 50% of the entries. */
219 for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
221 if (ce && ce != pk_cache && ce->next)
229 free_public_key (ce->pk);
234 log_assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
237 ce = xmalloc (sizeof *ce);
240 ce->pk = copy_public_key (NULL, pk);
241 ce->keyid[0] = keyid[0];
242 ce->keyid[1] = keyid[1];
247 /* Return a const utf-8 string with the text "[User ID not found]".
248 This function is required so that we don't need to switch gettext's
249 encoding temporary. */
251 user_id_not_found_utf8 (void)
256 text = native_to_utf8 (_("[User ID not found]"));
262 /* Return the user ID from the given keyblock.
263 * We use the primary uid flag which has been set by the merge_selfsigs
264 * function. The returned value is only valid as long as the given
265 * keyblock is not changed. */
267 get_primary_uid (KBNODE keyblock, size_t * uidlen)
272 for (k = keyblock; k; k = k->next)
274 if (k->pkt->pkttype == PKT_USER_ID
275 && !k->pkt->pkt.user_id->attrib_data
276 && k->pkt->pkt.user_id->flags.primary)
278 *uidlen = k->pkt->pkt.user_id->len;
279 return k->pkt->pkt.user_id->name;
282 s = user_id_not_found_utf8 ();
283 *uidlen = strlen (s);
289 release_keyid_list (keyid_list_t k)
293 keyid_list_t k2 = k->next;
300 * Store the association of keyid and userid
301 * Feed only public keys to this function.
304 cache_user_id (KBNODE keyblock)
309 keyid_list_t keyids = NULL;
312 for (k = keyblock; k; k = k->next)
314 if (k->pkt->pkttype == PKT_PUBLIC_KEY
315 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
317 keyid_list_t a = xmalloc_clear (sizeof *a);
318 /* Hmmm: For a long list of keyids it might be an advantage
319 * to append the keys. */
320 fingerprint_from_pk (k->pkt->pkt.public_key, a->fpr, NULL);
321 keyid_from_pk (k->pkt->pkt.public_key, a->keyid);
322 /* First check for duplicates. */
323 for (r = user_id_db; r; r = r->next)
327 for (b = r->keyids; b; b = b->next)
329 if (!memcmp (b->fpr, a->fpr, MAX_FINGERPRINT_LEN))
332 log_debug ("cache_user_id: already in cache\n");
333 release_keyid_list (keyids);
339 /* Now put it into the cache. */
345 BUG (); /* No key no fun. */
348 uid = get_primary_uid (keyblock, &uidlen);
350 if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES)
352 /* fixme: use another algorithm to free some cache slots */
354 user_id_db = r->next;
355 release_keyid_list (r->keyids);
359 r = xmalloc (sizeof *r + uidlen - 1);
362 memcpy (r->name, uid, r->len);
363 r->next = user_id_db;
369 /* Disable and drop the public key cache (which is filled by
370 cache_public_key and get_pubkey). Note: there is currently no way
371 to re-enable this cache. */
373 getkey_disable_caches ()
375 #if MAX_PK_CACHE_ENTRIES
377 pk_cache_entry_t ce, ce2;
379 for (ce = pk_cache; ce; ce = ce2)
382 free_public_key (ce->pk);
385 pk_cache_disabled = 1;
386 pk_cache_entries = 0;
390 /* fixme: disable user id cache ? */
395 pubkey_free (pubkey_t key)
400 release_kbnode (key->keyblock);
406 pubkeys_free (pubkey_t keys)
410 pubkey_t next = keys->next;
417 /* Returns all keys that match the search specification SEARCH_TERMS.
419 * This function also checks for and warns about duplicate entries in
420 * the keydb, which can occur if the user has configured multiple
421 * keyrings or keyboxes or if a keyring or keybox was corrupted.
423 * Note: SEARCH_TERMS will not be expanded (i.e., it may not be a
426 * USE is the operation for which the key is required. It must be
427 * either PUBKEY_USAGE_ENC, PUBKEY_USAGE_SIG, PUBKEY_USAGE_CERT or
430 * INCLUDE_UNUSABLE indicates whether disabled keys are allowed.
431 * (Recipients specified with --encrypt-to and --hidden-encrypt-to may
432 * be disabled. It is possible to edit disabled keys.)
434 * SOURCE is the context in which SEARCH_TERMS was specified, e.g.,
435 * "--encrypt-to", etc. If this function is called interactively,
436 * then this should be NULL.
438 * If WARN_POSSIBLY_AMBIGUOUS is set, then emits a warning if the user
439 * does not specify a long key id or a fingerprint.
441 * The results are placed in *KEYS. *KEYS must be NULL!
443 * Fixme: Currently, only PUBKEY_USAGE_ENC and PUBKEY_USAGE_SIG are
446 get_pubkeys (ctrl_t ctrl,
447 char *search_terms, int use, int include_unusable, char *source,
448 int warn_possibly_ambiguous,
451 /* We show a warning when a key appears multiple times in the DB.
452 * This can happen for two reasons:
454 * - The user has configured multiple keyrings or keyboxes.
456 * - The keyring or keybox has been corrupted in some way, e.g., a
457 * bug or a random process changing them.
459 * For each duplicate, we only want to show the key once. Hence,
461 static strlist_t key_dups;
463 char *use_str; /* USE transformed to a string. */
464 KEYDB_SEARCH_DESC desc;
466 pubkey_t results = NULL;
469 char fingerprint[2 * MAX_FINGERPRINT_LEN + 1];
474 log_debug ("%s: Checking %s=%s\n",
475 __func__, source ? source : "user input", search_terms);
479 log_bug ("%s: KEYS should be NULL!\n", __func__);
483 case PUBKEY_USAGE_ENC: use_str = "encrypt"; break;
484 case PUBKEY_USAGE_SIG: use_str = "sign"; break;
485 case PUBKEY_USAGE_CERT: use_str = "cetify"; break;
486 case PUBKEY_USAGE_AUTH: use_str = "authentication"; break;
487 default: log_bug ("%s: Bad value for USE (%d)\n", __func__, use);
490 if (use == PUBKEY_USAGE_CERT || use == PUBKEY_USAGE_AUTH)
491 log_bug ("%s: use=%s is unimplemented.\n", __func__, use_str);
493 err = classify_user_id (search_terms, &desc, 1);
496 log_info (_("key \"%s\" not found: %s\n"),
497 search_terms, gpg_strerror (err));
498 if (!opt.quiet && source)
499 log_info (_("(check argument of option '%s')\n"), source);
503 if (warn_possibly_ambiguous
504 && ! (desc.mode == KEYDB_SEARCH_MODE_LONG_KID
505 || desc.mode == KEYDB_SEARCH_MODE_FPR16
506 || desc.mode == KEYDB_SEARCH_MODE_FPR20
507 || desc.mode == KEYDB_SEARCH_MODE_FPR))
509 log_info (_("Warning: '%s' should be a long key ID or a fingerprint\n"),
511 if (!opt.quiet && source)
512 log_info (_("(check argument of option '%s')\n"), source);
515 /* Gather all of the results. */
523 pk = xtrycalloc (1, sizeof *pk);
526 err = gpg_error_from_syserror ();
533 err = get_pubkey_byname (ctrl, &ctx, pk, search_terms, &kb, NULL,
534 include_unusable, 1);
536 err = getkey_next (ctrl, ctx, pk, &kb);
538 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND) /* No more results. */
543 else if (err) /* An error (other than "not found"). */
545 log_error (_("error looking up: %s\n"), gpg_strerror (err));
550 /* Another result! */
553 r = xtrycalloc (1, sizeof (*r));
556 err = gpg_error_from_syserror ();
566 getkey_end (ctrl, ctx);
570 log_debug ("%s resulted in %d matches.\n", search_terms, count);
571 for (r = results; r; r = r->next)
573 hexfingerprint (r->keyblock->pkt->pkt.public_key,
574 fingerprint, sizeof (fingerprint)));
577 if (! results && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
580 log_debug ("%s: '%s' not found.\n", __func__, search_terms);
582 log_info (_("key \"%s\" not found\n"), search_terms);
583 if (!opt.quiet && source)
584 log_info (_("(check argument of option '%s')\n"), source);
588 else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
589 ; /* No more matches. */
591 { /* Some other error. An error message was already printed out.
592 * Free RESULTS and continue. */
596 /* Check for duplicates. */
598 log_debug ("%s: Checking results of %s='%s' for dups\n",
599 __func__, source ? source : "user input", search_terms);
601 for (r = results; r; r = r->next)
612 if (cmp_public_keys (r->keyblock->pkt->pkt.public_key,
613 r2->keyblock->pkt->pkt.public_key) != 0)
623 /* Remove R2 from the list. */
625 release_kbnode (r2->keyblock);
632 hexfingerprint (r->keyblock->pkt->pkt.public_key,
633 fingerprint, sizeof fingerprint);
634 if (! strlist_find (key_dups, fingerprint))
636 char fingerprint_formatted[MAX_FORMATTED_FINGERPRINT_LEN + 1];
638 log_info (_("Warning: %s appears in the keyring %d times\n"),
639 format_hexfingerprint (fingerprint,
640 fingerprint_formatted,
641 sizeof fingerprint_formatted),
643 add_to_strlist (&key_dups, fingerprint);
648 if (DBG_LOOKUP && count)
650 log_debug ("After removing %d dups:\n", count);
651 for (r = results, count = 0; r; r = r->next)
652 log_debug (" %d: %s\n",
654 hexfingerprint (r->keyblock->pkt->pkt.public_key,
655 fingerprint, sizeof fingerprint));
660 pubkeys_free (results);
669 pk_from_block (PKT_public_key *pk, kbnode_t keyblock, kbnode_t found_key)
671 kbnode_t a = found_key ? found_key : keyblock;
673 log_assert (a->pkt->pkttype == PKT_PUBLIC_KEY
674 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
676 copy_public_key (pk, a->pkt->pkt.public_key);
680 /* Return the public key with the key id KEYID and store it at PK.
681 * The resources in *PK should be released using
682 * release_public_key_parts(). This function also stores a copy of
683 * the public key in the user id cache (see cache_public_key).
685 * If PK is NULL, this function just stores the public key in the
686 * cache and returns the usual return code.
688 * PK->REQ_USAGE (which is a mask of PUBKEY_USAGE_SIG,
689 * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT) is passed through to the
690 * lookup function. If this is non-zero, only keys with the specified
691 * usage will be returned. As such, it is essential that
692 * PK->REQ_USAGE be correctly initialized!
694 * Returns 0 on success, GPG_ERR_NO_PUBKEY if there is no public key
695 * with the specified key id, or another error code if an error
698 * If the data was not read from the cache, then the self-signed data
699 * has definitely been merged into the public key using
702 get_pubkey (ctrl_t ctrl, PKT_public_key * pk, u32 * keyid)
707 #if MAX_PK_CACHE_ENTRIES
710 /* Try to get it from the cache. We don't do this when pk is
711 NULL as it does not guarantee that the user IDs are
714 for (ce = pk_cache; ce; ce = ce->next)
716 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
717 /* XXX: We don't check PK->REQ_USAGE here, but if we don't
718 read from the cache, we do check it! */
720 copy_public_key (pk, ce->pk);
726 /* More init stuff. */
730 pk = xtrycalloc (1, sizeof *pk);
733 rc = gpg_error_from_syserror ();
741 struct getkey_ctx_s ctx;
743 KBNODE found_key = NULL;
744 memset (&ctx, 0, sizeof ctx);
745 ctx.exact = 1; /* Use the key ID exactly as given. */
746 ctx.not_allocated = 1;
748 if (ctrl && ctrl->cached_getkey_kdb)
750 ctx.kr_handle = ctrl->cached_getkey_kdb;
751 ctrl->cached_getkey_kdb = NULL;
752 keydb_search_reset (ctx.kr_handle);
756 ctx.kr_handle = keydb_new ();
759 rc = gpg_error_from_syserror ();
764 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
765 ctx.items[0].u.kid[0] = keyid[0];
766 ctx.items[0].u.kid[1] = keyid[1];
767 ctx.req_usage = pk->req_usage;
768 rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
771 pk_from_block (pk, kb, found_key);
773 getkey_end (ctrl, &ctx);
779 rc = GPG_ERR_NO_PUBKEY;
783 cache_public_key (pk);
785 free_public_key (pk);
790 /* Similar to get_pubkey, but it does not take PK->REQ_USAGE into
791 * account nor does it merge in the self-signed data. This function
792 * also only considers primary keys. It is intended to be used as a
793 * quick check of the key to avoid recursion. It should only be used
794 * in very certain cases. Like get_pubkey and unlike any of the other
795 * lookup functions, this function also consults the user id cache
796 * (see cache_public_key).
798 * Return the public key in *PK. The resources in *PK should be
799 * released using release_public_key_parts(). */
801 get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
809 #if MAX_PK_CACHE_ENTRIES
811 /* Try to get it from the cache */
814 for (ce = pk_cache; ce; ce = ce->next)
816 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]
817 /* Only consider primary keys. */
818 && ce->pk->keyid[0] == ce->pk->main_keyid[0]
819 && ce->pk->keyid[1] == ce->pk->main_keyid[1])
822 copy_public_key (pk, ce->pk);
831 return gpg_error_from_syserror ();
832 rc = keydb_search_kid (hd, keyid);
833 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
836 return GPG_ERR_NO_PUBKEY;
838 rc = keydb_get_keyblock (hd, &keyblock);
842 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
843 return GPG_ERR_NO_PUBKEY;
846 log_assert (keyblock && keyblock->pkt
847 && keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
849 /* We return the primary key. If KEYID matched a subkey, then we
851 keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
852 if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
853 copy_public_key (pk, keyblock->pkt->pkt.public_key);
855 rc = GPG_ERR_NO_PUBKEY;
857 release_kbnode (keyblock);
859 /* Not caching key here since it won't have all of the fields
866 /* Return the key block for the key with key id KEYID or NULL, if an
867 * error occurs. Use release_kbnode() to release the key block.
869 * The self-signed data has already been merged into the public key
870 * using merge_selfsigs. */
872 get_pubkeyblock (ctrl_t ctrl, u32 * keyid)
874 struct getkey_ctx_s ctx;
876 KBNODE keyblock = NULL;
878 memset (&ctx, 0, sizeof ctx);
879 /* No need to set exact here because we want the entire block. */
880 ctx.not_allocated = 1;
881 ctx.kr_handle = keydb_new ();
885 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
886 ctx.items[0].u.kid[0] = keyid[0];
887 ctx.items[0].u.kid[1] = keyid[1];
888 rc = lookup (ctrl, &ctx, 0, &keyblock, NULL);
889 getkey_end (ctrl, &ctx);
891 return rc ? NULL : keyblock;
895 /* Return the public key with the key id KEYID iff the secret key is
896 * available and store it at PK. The resources should be released
897 * using release_public_key_parts().
899 * Unlike other lookup functions, PK may not be NULL. PK->REQ_USAGE
900 * is passed through to the lookup function and is a mask of
901 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. Thus, it
902 * must be valid! If this is non-zero, only keys with the specified
903 * usage will be returned.
905 * Returns 0 on success. If a public key with the specified key id is
906 * not found or a secret key is not available for that public key, an
907 * error code is returned. Note: this function ignores legacy keys.
908 * An error code is also return if an error occurs.
910 * The self-signed data has already been merged into the public key
911 * using merge_selfsigs. */
913 get_seckey (ctrl_t ctrl, PKT_public_key *pk, u32 *keyid)
916 struct getkey_ctx_s ctx;
917 kbnode_t keyblock = NULL;
918 kbnode_t found_key = NULL;
920 memset (&ctx, 0, sizeof ctx);
921 ctx.exact = 1; /* Use the key ID exactly as given. */
922 ctx.not_allocated = 1;
923 ctx.kr_handle = keydb_new ();
925 return gpg_error_from_syserror ();
927 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
928 ctx.items[0].u.kid[0] = keyid[0];
929 ctx.items[0].u.kid[1] = keyid[1];
930 ctx.req_usage = pk->req_usage;
931 err = lookup (ctrl, &ctx, 1, &keyblock, &found_key);
934 pk_from_block (pk, keyblock, found_key);
936 getkey_end (ctrl, &ctx);
937 release_kbnode (keyblock);
941 err = agent_probe_secret_key (/*ctrl*/NULL, pk);
943 release_public_key_parts (pk);
950 /* Skip unusable keys. A key is unusable if it is revoked, expired or
951 disabled or if the selected user id is revoked or expired. */
953 skip_unusable (void *opaque, u32 * keyid, int uid_no)
955 ctrl_t ctrl = opaque;
960 keyblock = get_pubkeyblock (ctrl, keyid);
963 log_error ("error checking usability status of %s\n", keystr (keyid));
967 pk = keyblock->pkt->pkt.public_key;
969 /* Is the key revoked or expired? */
970 if (pk->flags.revoked || pk->has_expired)
973 /* Is the user ID in question revoked or expired? */
974 if (!unusable && uid_no)
979 for (node = keyblock; node; node = node->next)
981 if (node->pkt->pkttype == PKT_USER_ID)
983 PKT_user_id *user_id = node->pkt->pkt.user_id;
986 if (uids_seen != uid_no)
989 if (user_id->flags.revoked || user_id->flags.expired)
996 /* If UID_NO is non-zero, then the keyblock better have at least
998 log_assert (uids_seen == uid_no);
1002 unusable = pk_is_disabled (pk);
1005 release_kbnode (keyblock);
1010 /* Search for keys matching some criteria.
1012 If RETCTX is not NULL, then the constructed context is returned in
1013 *RETCTX so that getpubkey_next can be used to get subsequent
1014 results. In this case, getkey_end() must be used to free the
1015 search context. If RETCTX is not NULL, then RET_KDBHD must be
1018 If NAMELIST is not NULL, then a search query is constructed using
1019 classify_user_id on each of the strings in the list. (Recall: the
1020 database does an OR of the terms, not an AND.) If NAMELIST is
1021 NULL, then all results are returned.
1023 If PK is not NULL, the public key of the first result is returned
1024 in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
1025 set, it is used to filter the search results. See the
1026 documentation for finish_lookup to understand exactly how this is
1027 used. Note: The self-signed data has already been merged into the
1028 public key using merge_selfsigs. Free *PK by calling
1029 release_public_key_parts (or, if PK was allocated using xfree, you
1030 can use free_public_key, which calls release_public_key_parts(PK)
1031 and then xfree(PK)).
1033 If WANT_SECRET is set, then only keys with an available secret key
1034 (either locally or via key registered on a smartcard) are returned.
1036 If INCLUDE_UNUSABLE is set, then unusable keys (see the
1037 documentation for skip_unusable for an exact definition) are
1038 skipped unless they are looked up by key id or by fingerprint.
1040 If RET_KB is not NULL, the keyblock is returned in *RET_KB. This
1041 should be freed using release_kbnode().
1043 If RET_KDBHD is not NULL, then the new database handle used to
1044 conduct the search is returned in *RET_KDBHD. This can be used to
1045 get subsequent results using keydb_search_next. Note: in this
1046 case, no advanced filtering is done for subsequent results (e.g.,
1047 WANT_SECRET and PK->REQ_USAGE are not respected).
1049 This function returns 0 on success. Otherwise, an error code is
1050 returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1051 (if want_secret is set) is returned if the key is not found. */
1053 key_byname (ctrl_t ctrl, GETKEY_CTX *retctx, strlist_t namelist,
1055 int want_secret, int include_unusable,
1056 KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
1062 KBNODE help_kb = NULL;
1063 KBNODE found_key = NULL;
1067 /* Reset the returned context in case of error. */
1068 log_assert (!ret_kdbhd); /* Not allowed because the handle is stored
1076 /* No search terms: iterate over the whole DB. */
1078 ctx = xmalloc_clear (sizeof *ctx);
1080 ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
1081 if (!include_unusable)
1083 ctx->items[0].skipfnc = skip_unusable;
1084 ctx->items[0].skipfncvalue = ctrl;
1089 /* Build the search context. */
1090 for (n = 0, r = namelist; r; r = r->next)
1093 /* CTX has space for a single search term at the end. Thus, we
1094 need to allocate sizeof *CTX plus (n - 1) sizeof
1096 ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
1099 for (n = 0, r = namelist; r; r = r->next, n++)
1103 err = classify_user_id (r->d, &ctx->items[n], 1);
1105 if (ctx->items[n].exact)
1110 return gpg_err_code (err); /* FIXME: remove gpg_err_code. */
1112 if (!include_unusable
1113 && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
1114 && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
1115 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
1116 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
1117 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
1119 ctx->items[n].skipfnc = skip_unusable;
1120 ctx->items[n].skipfncvalue = ctrl;
1125 ctx->want_secret = want_secret;
1126 ctx->kr_handle = keydb_new ();
1127 if (!ctx->kr_handle)
1129 rc = gpg_error_from_syserror ();
1130 getkey_end (ctrl, ctx);
1139 ctx->req_usage = pk->req_usage;
1142 rc = lookup (ctrl, ctx, want_secret, ret_kb, &found_key);
1145 pk_from_block (pk, *ret_kb, found_key);
1148 release_kbnode (help_kb);
1150 if (retctx) /* Caller wants the context. */
1156 *ret_kdbhd = ctx->kr_handle;
1157 ctx->kr_handle = NULL;
1159 getkey_end (ctrl, ctx);
1166 /* Find a public key identified by NAME.
1168 * If name appears to be a valid RFC822 mailbox (i.e., email
1169 * address) and auto key lookup is enabled (no_akl == 0), then the
1170 * specified auto key lookup methods (--auto-key-lookup) are used to
1171 * import the key into the local keyring. Otherwise, just the local
1172 * keyring is consulted.
1174 * If RETCTX is not NULL, then the constructed context is returned in
1175 * *RETCTX so that getpubkey_next can be used to get subsequent
1176 * results. In this case, getkey_end() must be used to free the
1177 * search context. If RETCTX is not NULL, then RET_KDBHD must be
1180 * If PK is not NULL, the public key of the first result is returned
1181 * in *PK. Note: PK->REQ_USAGE must be valid!!! PK->REQ_USAGE is
1182 * passed through to the lookup function and is a mask of
1183 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this
1184 * is non-zero, only keys with the specified usage will be returned.
1185 * Note: The self-signed data has already been merged into the public
1186 * key using merge_selfsigs. Free *PK by calling
1187 * release_public_key_parts (or, if PK was allocated using xfree, you
1188 * can use free_public_key, which calls release_public_key_parts(PK)
1189 * and then xfree(PK)).
1191 * NAME is a string, which is turned into a search query using
1194 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
1195 * *RET_KEYBLOCK. This should be freed using release_kbnode().
1197 * If RET_KDBHD is not NULL, then the new database handle used to
1198 * conduct the search is returned in *RET_KDBHD. This can be used to
1199 * get subsequent results using keydb_search_next or to modify the
1200 * returned record. Note: in this case, no advanced filtering is done
1201 * for subsequent results (e.g., PK->REQ_USAGE is not respected).
1202 * Unlike RETCTX, this is always returned.
1204 * If INCLUDE_UNUSABLE is set, then unusable keys (see the
1205 * documentation for skip_unusable for an exact definition) are
1206 * skipped unless they are looked up by key id or by fingerprint.
1208 * If NO_AKL is set, then the auto key locate functionality is
1209 * disabled and only the local key ring is considered. Note: the
1210 * local key ring is consulted even if local is not in the
1211 * --auto-key-locate option list!
1213 * This function returns 0 on success. Otherwise, an error code is
1214 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1215 * (if want_secret is set) is returned if the key is not found. */
1217 get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
1218 const char *name, KBNODE * ret_keyblock,
1219 KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
1222 strlist_t namelist = NULL;
1226 int anylocalfirst = 0;
1228 /* If RETCTX is not NULL, then RET_KDBHD must be NULL. */
1229 log_assert (retctx == NULL || ret_kdbhd == NULL);
1234 /* Does NAME appear to be a mailbox (mail address)? */
1235 is_mbox = is_valid_mailbox (name);
1237 /* The auto-key-locate feature works as follows: there are a number
1238 * of methods to look up keys. By default, the local keyring is
1239 * tried first. Then, each method listed in the --auto-key-locate is
1240 * tried in the order it appears.
1242 * This can be changed as follows:
1244 * - if nodefault appears anywhere in the list of options, then
1245 * the local keyring is not tried first, or,
1247 * - if local appears anywhere in the list of options, then the
1248 * local keyring is not tried first, but in the order in which
1249 * it was listed in the --auto-key-locate option.
1251 * Note: we only save the search context in RETCTX if the local
1252 * method is the first method tried (either explicitly or
1256 /* auto-key-locate is enabled. */
1258 /* nodefault is true if "nodefault" or "local" appear. */
1259 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1260 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
1265 /* anylocalfirst is true if "local" appears before any other
1266 search methods (except "nodefault"). */
1267 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1268 if (akl->type != AKL_NODEFAULT)
1270 if (akl->type == AKL_LOCAL)
1278 /* "nodefault" didn't occur. Thus, "local" is implicitly the
1279 * first method to try. */
1283 if (nodefault && is_mbox)
1285 /* Either "nodefault" or "local" (explicitly) appeared in the
1286 * auto key locate list and NAME appears to be an email address.
1287 * Don't try the local keyring. */
1288 rc = GPG_ERR_NO_PUBKEY;
1292 /* Either "nodefault" and "local" don't appear in the auto key
1293 * locate list (in which case we try the local keyring first) or
1294 * NAME does not appear to be an email address (in which case we
1295 * only try the local keyring). In this case, lookup NAME in
1296 * the local keyring. */
1297 add_to_strlist (&namelist, name);
1298 rc = key_byname (ctrl, retctx, namelist, pk, 0,
1299 include_unusable, ret_keyblock, ret_kdbhd);
1302 /* If the requested name resembles a valid mailbox and automatic
1303 retrieval has been enabled, we try to import the key. */
1304 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && !no_akl && is_mbox)
1306 /* NAME wasn't present in the local keyring (or we didn't try
1307 * the local keyring). Since the auto key locate feature is
1308 * enabled and NAME appears to be an email address, try the auto
1309 * locate feature. */
1310 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1312 unsigned char *fpr = NULL;
1314 int did_akl_local = 0;
1315 int no_fingerprint = 0;
1316 const char *mechanism = "?";
1321 /* This is a dummy mechanism. */
1323 rc = GPG_ERR_NO_PUBKEY;
1327 mechanism = "Local";
1331 getkey_end (ctrl, *retctx);
1334 add_to_strlist (&namelist, name);
1335 rc = key_byname (ctrl, anylocalfirst ? retctx : NULL,
1337 include_unusable, ret_keyblock, ret_kdbhd);
1341 mechanism = "DNS CERT";
1342 glo_ctrl.in_auto_key_retrieve++;
1343 rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len);
1344 glo_ctrl.in_auto_key_retrieve--;
1349 glo_ctrl.in_auto_key_retrieve++;
1350 rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
1351 glo_ctrl.in_auto_key_retrieve--;
1356 glo_ctrl.in_auto_key_retrieve++;
1357 rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len);
1358 glo_ctrl.in_auto_key_retrieve--;
1363 glo_ctrl.in_auto_key_retrieve++;
1364 rc = keyserver_import_wkd (ctrl, name, 0, &fpr, &fpr_len);
1365 glo_ctrl.in_auto_key_retrieve--;
1370 glo_ctrl.in_auto_key_retrieve++;
1371 rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
1372 glo_ctrl.in_auto_key_retrieve--;
1376 /* Strictly speaking, we don't need to only use a valid
1377 * mailbox for the getname search, but it helps cut down
1378 * on the problem of searching for something like "john"
1379 * and getting a whole lot of keys back. */
1380 if (keyserver_any_configured (ctrl))
1382 mechanism = "keyserver";
1383 glo_ctrl.in_auto_key_retrieve++;
1384 rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
1386 glo_ctrl.in_auto_key_retrieve--;
1390 mechanism = "Unconfigured keyserver";
1391 rc = GPG_ERR_NO_PUBKEY;
1397 struct keyserver_spec *keyserver;
1399 mechanism = akl->spec->uri;
1400 keyserver = keyserver_match (akl->spec);
1401 glo_ctrl.in_auto_key_retrieve++;
1402 rc = keyserver_import_name (ctrl,
1403 name, &fpr, &fpr_len, keyserver);
1404 glo_ctrl.in_auto_key_retrieve--;
1409 /* Use the fingerprint of the key that we actually fetched.
1410 * This helps prevent problems where the key that we fetched
1411 * doesn't have the same name that we used to fetch it. In
1412 * the case of CERT and PKA, this is an actual security
1413 * requirement as the URL might point to a key put in by an
1414 * attacker. By forcing the use of the fingerprint, we
1415 * won't use the attacker's key here. */
1418 char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
1420 log_assert (fpr_len <= MAX_FINGERPRINT_LEN);
1422 free_strlist (namelist);
1425 bin2hex (fpr, fpr_len, fpr_string);
1428 log_info ("auto-key-locate found fingerprint %s\n",
1431 add_to_strlist (&namelist, fpr_string);
1433 else if (!rc && !fpr && !did_akl_local)
1434 { /* The acquisition method said no failure occurred, but
1435 * it didn't return a fingerprint. That's a failure. */
1437 rc = GPG_ERR_NO_PUBKEY;
1442 if (!rc && !did_akl_local)
1443 { /* There was no error and we didn't do a local lookup.
1444 * This means that we imported a key into the local
1445 * keyring. Try to read the imported key from the
1449 getkey_end (ctrl, *retctx);
1452 rc = key_byname (ctrl, anylocalfirst ? retctx : NULL,
1454 include_unusable, ret_keyblock, ret_kdbhd);
1460 log_info (_("automatically retrieved '%s' via %s\n"),
1464 if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1465 || opt.verbose || no_fingerprint)
1466 log_info (_("error retrieving '%s' via %s: %s\n"),
1468 no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
1475 getkey_end (ctrl, *retctx);
1479 if (retctx && *retctx)
1481 log_assert (!(*retctx)->extra_list);
1482 (*retctx)->extra_list = namelist;
1485 free_strlist (namelist);
1493 /* Comparison machinery for get_best_pubkey_byname. */
1495 /* First we have a struct to cache computed information about the key
1497 struct pubkey_cmp_cookie
1499 int valid; /* Is this cookie valid? */
1500 PKT_public_key key; /* The key. */
1501 PKT_user_id *uid; /* The matching UID packet. */
1502 unsigned int validity; /* Computed validity of (KEY, UID). */
1503 u32 creation_time; /* Creation time of the newest subkey
1504 capable of encryption. */
1508 /* Then we have a series of helper functions. */
1510 key_is_ok (const PKT_public_key *key)
1512 return (! key->has_expired && ! key->flags.revoked
1513 && key->flags.valid && ! key->flags.disabled);
1518 uid_is_ok (const PKT_public_key *key, const PKT_user_id *uid)
1520 return key_is_ok (key) && ! uid->flags.revoked;
1525 subkey_is_ok (const PKT_public_key *sub)
1527 return ! sub->flags.revoked && sub->flags.valid && ! sub->flags.disabled;
1531 /* Finally this function compares a NEW key to the former candidate
1532 * OLD. Returns < 0 if the old key is worse, > 0 if the old key is
1533 * better, == 0 if it is a tie. */
1535 pubkey_cmp (ctrl_t ctrl, const char *name, struct pubkey_cmp_cookie *old,
1536 struct pubkey_cmp_cookie *new, KBNODE new_keyblock)
1540 new->creation_time = 0;
1541 for (n = find_next_kbnode (new_keyblock, PKT_PUBLIC_SUBKEY);
1542 n; n = find_next_kbnode (n, PKT_PUBLIC_SUBKEY))
1544 PKT_public_key *sub = n->pkt->pkt.public_key;
1546 if ((sub->pubkey_usage & PUBKEY_USAGE_ENC) == 0)
1549 if (! subkey_is_ok (sub))
1552 if (sub->timestamp > new->creation_time)
1553 new->creation_time = sub->timestamp;
1556 for (n = find_next_kbnode (new_keyblock, PKT_USER_ID);
1557 n; n = find_next_kbnode (n, PKT_USER_ID))
1559 PKT_user_id *uid = n->pkt->pkt.user_id;
1560 char *mbox = mailbox_from_userid (uid->name);
1561 int match = mbox ? strcasecmp (name, mbox) == 0 : 0;
1567 new->uid = scopy_user_id (uid);
1569 get_validity (ctrl, new_keyblock, &new->key, uid, NULL, 0) & TRUST_MASK;
1573 return -1; /* No OLD key. */
1575 if (! uid_is_ok (&old->key, old->uid) && uid_is_ok (&new->key, uid))
1576 return -1; /* Validity of the NEW key is better. */
1578 if (old->validity < new->validity)
1579 return -1; /* Validity of the NEW key is better. */
1581 if (old->validity == new->validity && uid_is_ok (&new->key, uid)
1582 && old->creation_time < new->creation_time)
1583 return -1; /* Both keys are of the same validity, but the
1584 NEW key is newer. */
1587 /* Stick with the OLD key. */
1592 /* This function works like get_pubkey_byname, but if the name
1593 * resembles a mail address, the results are ranked and only the best
1594 * result is returned. */
1596 get_best_pubkey_byname (ctrl_t ctrl, GETKEY_CTX *retctx, PKT_public_key *pk,
1597 const char *name, KBNODE *ret_keyblock,
1598 int include_unusable, int no_akl)
1601 struct getkey_ctx_s *ctx = NULL;
1606 err = get_pubkey_byname (ctrl, &ctx, pk, name, ret_keyblock,
1607 NULL, include_unusable, no_akl);
1610 getkey_end (ctrl, ctx);
1614 if (is_valid_mailbox (name) && ctx)
1616 /* Rank results and return only the most relevant key. */
1617 struct pubkey_cmp_cookie best = { 0 };
1618 struct pubkey_cmp_cookie new = { 0 };
1619 kbnode_t new_keyblock;
1621 while (getkey_next (ctrl, ctx, &new.key, &new_keyblock) == 0)
1623 int diff = pubkey_cmp (ctrl, name, &best, &new, new_keyblock);
1624 release_kbnode (new_keyblock);
1627 /* New key is better. */
1628 release_public_key_parts (&best.key);
1629 free_user_id (best.uid);
1634 /* Old key is better. */
1635 release_public_key_parts (&new.key);
1636 free_user_id (new.uid);
1641 /* A tie. Keep the old key. */
1642 release_public_key_parts (&new.key);
1643 free_user_id (new.uid);
1647 getkey_end (ctrl, ctx);
1649 free_user_id (best.uid);
1654 if (retctx || ret_keyblock)
1656 ctx = xtrycalloc (1, sizeof **retctx);
1658 err = gpg_error_from_syserror ();
1661 ctx->kr_handle = keydb_new ();
1662 if (! ctx->kr_handle)
1664 err = gpg_error_from_syserror ();
1672 u32 *keyid = pk_keyid (&best.key);
1675 ctx->items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
1676 ctx->items[0].u.kid[0] = keyid[0];
1677 ctx->items[0].u.kid[1] = keyid[1];
1681 release_kbnode (*ret_keyblock);
1682 *ret_keyblock = NULL;
1683 err = getkey_next (ctrl, ctx, NULL, ret_keyblock);
1692 release_public_key_parts (&best.key);
1698 getkey_end (ctrl, ctx);
1705 getkey_end (ctrl, ctx);
1712 /* Get a public key from a file.
1714 * PK is the buffer to store the key. The caller needs to make sure
1715 * that PK->REQ_USAGE is valid. PK->REQ_USAGE is passed through to
1716 * the lookup function and is a mask of PUBKEY_USAGE_SIG,
1717 * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this is non-zero, only
1718 * keys with the specified usage will be returned.
1720 * FNAME is the file name. That file should contain exactly one
1723 * This function returns 0 on success. Otherwise, an error code is
1724 * returned. In particular, GPG_ERR_NO_PUBKEY is returned if the key
1727 * The self-signed data has already been merged into the public key
1728 * using merge_selfsigs. The caller must release the content of PK by
1729 * calling release_public_key_parts (or, if PK was malloced, using
1733 get_pubkey_fromfile (ctrl_t ctrl, PKT_public_key *pk, const char *fname)
1738 unsigned int infoflags;
1740 err = read_key_from_file (ctrl, fname, &keyblock);
1743 /* Warning: node flag bits 0 and 1 should be preserved by
1744 * merge_selfsigs. FIXME: Check whether this still holds. */
1745 merge_selfsigs (ctrl, keyblock);
1746 found_key = finish_lookup (keyblock, pk->req_usage, 0, 0, &infoflags);
1747 print_status_key_considered (keyblock, infoflags);
1749 pk_from_block (pk, keyblock, found_key);
1751 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
1754 release_kbnode (keyblock);
1759 /* Lookup a key with the specified fingerprint.
1761 * If PK is not NULL, the public key of the first result is returned
1762 * in *PK. Note: this function does an exact search and thus the
1763 * returned public key may be a subkey rather than the primary key.
1764 * Note: The self-signed data has already been merged into the public
1765 * key using merge_selfsigs. Free *PK by calling
1766 * release_public_key_parts (or, if PK was allocated using xfree, you
1767 * can use free_public_key, which calls release_public_key_parts(PK)
1768 * and then xfree(PK)).
1770 * If PK->REQ_USAGE is set, it is used to filter the search results.
1771 * (Thus, if PK is not NULL, PK->REQ_USAGE must be valid!!!) See the
1772 * documentation for finish_lookup to understand exactly how this is
1775 * If R_KEYBLOCK is not NULL, then the first result's keyblock is
1776 * returned in *R_KEYBLOCK. This should be freed using
1779 * FPRINT is a byte array whose contents is the fingerprint to use as
1780 * the search term. FPRINT_LEN specifies the length of the
1781 * fingerprint (in bytes). Currently, only 16 and 20-byte
1782 * fingerprints are supported.
1784 * FIXME: We should replace this with the _byname function. This can
1785 * be done by creating a userID conforming to the unified fingerprint
1788 get_pubkey_byfprint (ctrl_t ctrl, PKT_public_key *pk, kbnode_t *r_keyblock,
1789 const byte * fprint, size_t fprint_len)
1796 if (fprint_len == 20 || fprint_len == 16)
1798 struct getkey_ctx_s ctx;
1800 KBNODE found_key = NULL;
1802 memset (&ctx, 0, sizeof ctx);
1804 ctx.not_allocated = 1;
1805 ctx.kr_handle = keydb_new ();
1807 return gpg_error_from_syserror ();
1810 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1811 : KEYDB_SEARCH_MODE_FPR20;
1812 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1813 rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
1815 pk_from_block (pk, kb, found_key);
1816 if (!rc && r_keyblock)
1821 release_kbnode (kb);
1822 getkey_end (ctrl, &ctx);
1825 rc = GPG_ERR_GENERAL; /* Oops */
1830 /* This function is similar to get_pubkey_byfprint, but it doesn't
1831 * merge the self-signed data into the public key and subkeys or into
1832 * the user ids. It also doesn't add the key to the user id cache.
1833 * Further, this function ignores PK->REQ_USAGE.
1835 * This function is intended to avoid recursion and, as such, should
1836 * only be used in very specific situations.
1838 * Like get_pubkey_byfprint, PK may be NULL. In that case, this
1839 * function effectively just checks for the existence of the key. */
1841 get_pubkey_byfprint_fast (PKT_public_key * pk,
1842 const byte * fprint, size_t fprint_len)
1847 err = get_keyblock_byfprint_fast (&keyblock, NULL, fprint, fprint_len, 0);
1851 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1852 release_kbnode (keyblock);
1859 /* This function is similar to get_pubkey_byfprint_fast but returns a
1860 * keydb handle at R_HD and the keyblock at R_KEYBLOCK. R_KEYBLOCK or
1861 * R_HD may be NULL. If LOCK is set the handle has been opend in
1862 * locked mode and keydb_disable_caching () has been called. On error
1863 * R_KEYBLOCK is set to NULL but R_HD must be released by the caller;
1864 * it may have a value of NULL, though. This allows to do an insert
1865 * operation on a locked keydb handle. */
1867 get_keyblock_byfprint_fast (kbnode_t *r_keyblock, KEYDB_HANDLE *r_hd,
1868 const byte *fprint, size_t fprint_len, int lock)
1873 byte fprbuf[MAX_FINGERPRINT_LEN];
1881 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1882 fprbuf[i] = fprint[i];
1883 while (i < MAX_FINGERPRINT_LEN)
1888 return gpg_error_from_syserror ();
1892 err = keydb_lock (hd);
1895 /* If locking did not work, we better don't return a handle
1896 * at all - there was a reason that locking has been
1901 keydb_disable_caching (hd);
1904 /* Fo all other errors we return the handle. */
1908 err = keydb_search_fpr (hd, fprbuf);
1909 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1913 return gpg_error (GPG_ERR_NO_PUBKEY);
1915 err = keydb_get_keyblock (hd, &keyblock);
1918 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (err));
1921 return gpg_error (GPG_ERR_NO_PUBKEY);
1924 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1925 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1927 /* Not caching key here since it won't have all of the fields
1931 *r_keyblock = keyblock;
1933 release_kbnode (keyblock);
1943 parse_def_secret_key (ctrl_t ctrl)
1945 KEYDB_HANDLE hd = NULL;
1949 for (t = opt.def_secret_key; t; t = t->next)
1952 KEYDB_SEARCH_DESC desc;
1956 err = classify_user_id (t->d, &desc, 1);
1959 log_error (_("secret key \"%s\" not found: %s\n"),
1960 t->d, gpg_strerror (err));
1962 log_info (_("(check argument of option '%s')\n"), "--default-key");
1973 keydb_search_reset (hd);
1976 err = keydb_search (hd, &desc, 1, NULL);
1977 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1982 log_error (_("key \"%s\" not found: %s\n"), t->d, gpg_strerror (err));
1987 err = keydb_get_keyblock (hd, &kb);
1990 log_error (_("error reading keyblock: %s\n"),
1991 gpg_strerror (err));
1995 merge_selfsigs (ctrl, kb);
1997 err = gpg_error (GPG_ERR_NO_SECKEY);
2001 PKT_public_key *pk = node->pkt->pkt.public_key;
2003 /* Check that the key has the signing capability. */
2004 if (! (pk->pubkey_usage & PUBKEY_USAGE_SIG))
2007 /* Check if the key is valid. */
2008 if (pk->flags.revoked)
2011 log_debug ("not using %s as default key, %s",
2012 keystr_from_pk (pk), "revoked");
2015 if (pk->has_expired)
2018 log_debug ("not using %s as default key, %s",
2019 keystr_from_pk (pk), "expired");
2022 if (pk_is_disabled (pk))
2025 log_debug ("not using %s as default key, %s",
2026 keystr_from_pk (pk), "disabled");
2030 err = agent_probe_secret_key (ctrl, pk);
2032 /* This is a valid key. */
2035 while ((node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY)));
2037 release_kbnode (kb);
2040 if (! warned && ! opt.quiet)
2042 log_info (_("Warning: not using '%s' as default key: %s\n"),
2043 t->d, gpg_strerror (GPG_ERR_NO_SECKEY));
2044 print_reported_error (err, GPG_ERR_NO_SECKEY);
2049 if (! warned && ! opt.quiet)
2050 log_info (_("using \"%s\" as default secret key for signing\n"),
2056 if (! warned && opt.def_secret_key && ! t)
2057 log_info (_("all values passed to '%s' ignored\n"),
2071 /* Look up a secret key.
2073 * If PK is not NULL, the public key of the first result is returned
2074 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2075 * set, it is used to filter the search results. See the
2076 * documentation for finish_lookup to understand exactly how this is
2077 * used. Note: The self-signed data has already been merged into the
2078 * public key using merge_selfsigs. Free *PK by calling
2079 * release_public_key_parts (or, if PK was allocated using xfree, you
2080 * can use free_public_key, which calls release_public_key_parts(PK)
2081 * and then xfree(PK)).
2083 * If --default-key was set, then the specified key is looked up. (In
2084 * this case, the default key is returned even if it is considered
2085 * unusable. See the documentation for skip_unusable for exactly what
2088 * Otherwise, this initiates a DB scan that returns all keys that are
2089 * usable (see previous paragraph for exactly what usable means) and
2090 * for which a secret key is available.
2092 * This function returns the first match. Additional results can be
2093 * returned using getkey_next. */
2095 get_seckey_default (ctrl_t ctrl, PKT_public_key *pk)
2098 strlist_t namelist = NULL;
2099 int include_unusable = 1;
2102 const char *def_secret_key = parse_def_secret_key (ctrl);
2104 add_to_strlist (&namelist, def_secret_key);
2106 include_unusable = 0;
2108 err = key_byname (ctrl, NULL, namelist, pk, 1, include_unusable, NULL, NULL);
2110 free_strlist (namelist);
2117 /* Search for keys matching some criteria.
2119 * If RETCTX is not NULL, then the constructed context is returned in
2120 * *RETCTX so that getpubkey_next can be used to get subsequent
2121 * results. In this case, getkey_end() must be used to free the
2122 * search context. If RETCTX is not NULL, then RET_KDBHD must be
2125 * If PK is not NULL, the public key of the first result is returned
2126 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2127 * set, it is used to filter the search results. See the
2128 * documentation for finish_lookup to understand exactly how this is
2129 * used. Note: The self-signed data has already been merged into the
2130 * public key using merge_selfsigs. Free *PK by calling
2131 * release_public_key_parts (or, if PK was allocated using xfree, you
2132 * can use free_public_key, which calls release_public_key_parts(PK)
2133 * and then xfree(PK)).
2135 * If NAMES is not NULL, then a search query is constructed using
2136 * classify_user_id on each of the strings in the list. (Recall: the
2137 * database does an OR of the terms, not an AND.) If NAMES is
2138 * NULL, then all results are returned.
2140 * If WANT_SECRET is set, then only keys with an available secret key
2141 * (either locally or via key registered on a smartcard) are returned.
2143 * This function does not skip unusable keys (see the documentation
2144 * for skip_unusable for an exact definition).
2146 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2147 * *RET_KEYBLOCK. This should be freed using release_kbnode().
2149 * This function returns 0 on success. Otherwise, an error code is
2150 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2151 * (if want_secret is set) is returned if the key is not found. */
2153 getkey_bynames (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2154 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
2156 return key_byname (ctrl, retctx, names, pk, want_secret, 1,
2157 ret_keyblock, NULL);
2161 /* Search for one key matching some criteria.
2163 * If RETCTX is not NULL, then the constructed context is returned in
2164 * *RETCTX so that getpubkey_next can be used to get subsequent
2165 * results. In this case, getkey_end() must be used to free the
2166 * search context. If RETCTX is not NULL, then RET_KDBHD must be
2169 * If PK is not NULL, the public key of the first result is returned
2170 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2171 * set, it is used to filter the search results. See the
2172 * documentation for finish_lookup to understand exactly how this is
2173 * used. Note: The self-signed data has already been merged into the
2174 * public key using merge_selfsigs. Free *PK by calling
2175 * release_public_key_parts (or, if PK was allocated using xfree, you
2176 * can use free_public_key, which calls release_public_key_parts(PK)
2177 * and then xfree(PK)).
2179 * If NAME is not NULL, then a search query is constructed using
2180 * classify_user_id on the string. In this case, even unusable keys
2181 * (see the documentation for skip_unusable for an exact definition of
2182 * unusable) are returned. Otherwise, if --default-key was set, then
2183 * that key is returned (even if it is unusable). If neither of these
2184 * conditions holds, then the first usable key is returned.
2186 * If WANT_SECRET is set, then only keys with an available secret key
2187 * (either locally or via key registered on a smartcard) are returned.
2189 * This function does not skip unusable keys (see the documentation
2190 * for skip_unusable for an exact definition).
2192 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2193 * *RET_KEYBLOCK. This should be freed using release_kbnode().
2195 * This function returns 0 on success. Otherwise, an error code is
2196 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2197 * (if want_secret is set) is returned if the key is not found.
2199 * FIXME: We also have the get_pubkey_byname function which has a
2200 * different semantic. Should be merged with this one. */
2202 getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2203 const char *name, int want_secret, kbnode_t *ret_keyblock)
2206 strlist_t namelist = NULL;
2207 int with_unusable = 1;
2208 const char *def_secret_key = NULL;
2210 if (want_secret && !name)
2211 def_secret_key = parse_def_secret_key (ctrl);
2213 if (want_secret && !name && def_secret_key)
2214 add_to_strlist (&namelist, def_secret_key);
2216 add_to_strlist (&namelist, name);
2220 err = key_byname (ctrl, retctx, namelist, pk, want_secret, with_unusable,
2221 ret_keyblock, NULL);
2223 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
2224 WANT_SECRET has been used. */
2226 free_strlist (namelist);
2232 /* Return the next search result.
2234 * If PK is not NULL, the public key of the next result is returned in
2235 * *PK. Note: The self-signed data has already been merged into the
2236 * public key using merge_selfsigs. Free *PK by calling
2237 * release_public_key_parts (or, if PK was allocated using xmalloc, you
2238 * can use free_public_key, which calls release_public_key_parts(PK)
2239 * and then xfree(PK)).
2241 * RET_KEYBLOCK can be given as NULL; if it is not NULL it the entire
2242 * found keyblock is returned which must be released with
2243 * release_kbnode. If the function returns an error NULL is stored at
2246 * The self-signed data has already been merged into the public key
2247 * using merge_selfsigs. */
2249 getkey_next (ctrl_t ctrl, getkey_ctx_t ctx,
2250 PKT_public_key *pk, kbnode_t *ret_keyblock)
2252 int rc; /* Fixme: Make sure this is proper gpg_error */
2253 KBNODE keyblock = NULL;
2254 KBNODE found_key = NULL;
2256 /* We need to disable the caching so that for an exact key search we
2257 won't get the result back from the cache and thus end up in an
2258 endless loop. The endless loop can occur, because the cache is
2259 used without respecting the current file pointer! */
2260 keydb_disable_caching (ctx->kr_handle);
2262 /* FOUND_KEY is only valid as long as RET_KEYBLOCK is. If the
2263 * caller wants PK, but not RET_KEYBLOCK, we need hand in our own
2265 if (pk && ret_keyblock == NULL)
2266 ret_keyblock = &keyblock;
2268 rc = lookup (ctrl, ctx, ctx->want_secret,
2269 ret_keyblock, pk ? &found_key : NULL);
2272 log_assert (found_key);
2273 pk_from_block (pk, NULL, found_key);
2274 release_kbnode (keyblock);
2281 /* Release any resources used by a key listing context. This must be
2282 * called on the context returned by, e.g., getkey_byname. */
2284 getkey_end (ctrl_t ctrl, getkey_ctx_t ctx)
2288 #ifdef HAVE_W32_SYSTEM
2290 /* FIXME: This creates a big regression for Windows because the
2291 * keyring is only released after the global ctrl is released.
2292 * So if an operation does a getkey and then tries to modify the
2293 * keyring it will fail on Windows with a sharing violation. We
2294 * need to modify all keyring write operations to also take the
2295 * ctrl and close the cached_getkey_kdb handle to make writing
2296 * work. See: GnuPG-bug-id: 3097 */
2298 keydb_release (ctx->kr_handle);
2300 #else /*!HAVE_W32_SYSTEM*/
2302 if (ctrl && !ctrl->cached_getkey_kdb)
2303 ctrl->cached_getkey_kdb = ctx->kr_handle;
2305 keydb_release (ctx->kr_handle);
2307 #endif /*!HAVE_W32_SYSTEM*/
2309 free_strlist (ctx->extra_list);
2310 if (!ctx->not_allocated)
2317 /************************************************
2318 ************* Merging stuff ********************
2319 ************************************************/
2321 /* Set the mainkey_id fields for all keys in KEYBLOCK. This is
2322 * usually done by merge_selfsigs but at some places we only need the
2323 * main_kid not a full merge. The function also guarantees that all
2324 * pk->keyids are computed. */
2326 setup_main_keyids (kbnode_t keyblock)
2328 u32 kid[2], mainkid[2];
2329 kbnode_t kbctx, node;
2332 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2334 pk = keyblock->pkt->pkt.public_key;
2336 keyid_from_pk (pk, mainkid);
2337 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
2339 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
2340 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
2342 pk = node->pkt->pkt.public_key;
2343 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
2344 if (!pk->main_keyid[0] && !pk->main_keyid[1])
2346 pk->main_keyid[0] = mainkid[0];
2347 pk->main_keyid[1] = mainkid[1];
2353 /* KEYBLOCK corresponds to a public key block. This function merges
2354 * much of the information from the self-signed data into the public
2355 * key, public subkey and user id data structures. If you use the
2356 * high-level search API (e.g., get_pubkey) for looking up key blocks,
2357 * then you don't need to call this function. This function is
2358 * useful, however, if you change the keyblock, e.g., by adding or
2359 * removing a self-signed data packet. */
2361 merge_keys_and_selfsig (ctrl_t ctrl, kbnode_t keyblock)
2365 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
2366 merge_selfsigs (ctrl, keyblock);
2368 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
2373 parse_key_usage (PKT_signature * sig)
2380 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
2383 /* First octet of the keyflags. */
2388 key_usage |= PUBKEY_USAGE_CERT;
2394 key_usage |= PUBKEY_USAGE_SIG;
2398 /* We do not distinguish between encrypting communications and
2399 encrypting storage. */
2400 if (flags & (0x04 | 0x08))
2402 key_usage |= PUBKEY_USAGE_ENC;
2403 flags &= ~(0x04 | 0x08);
2408 key_usage |= PUBKEY_USAGE_AUTH;
2413 key_usage |= PUBKEY_USAGE_UNKNOWN;
2416 key_usage |= PUBKEY_USAGE_NONE;
2418 else if (p) /* Key flags of length zero. */
2419 key_usage |= PUBKEY_USAGE_NONE;
2421 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
2422 capability that we do not handle. This serves to distinguish
2423 between a zero key usage which we handle as the default
2424 capabilities for that algorithm, and a usage that we do not
2425 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
2426 key_flags have been given but they do not specify any usage. */
2432 /* Apply information from SIGNODE (which is the valid self-signature
2433 * associated with that UID) to the UIDNODE:
2434 * - weather the UID has been revoked
2435 * - assumed creation date of the UID
2436 * - temporary store the keyflags here
2437 * - temporary store the key expiration time here
2438 * - mark whether the primary user ID flag hat been set.
2439 * - store the preferences
2442 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
2444 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
2445 PKT_signature *sig = signode->pkt->pkt.signature;
2446 const byte *p, *sym, *hash, *zip;
2447 size_t n, nsym, nhash, nzip;
2449 sig->flags.chosen_selfsig = 1;/* We chose this one. */
2450 uid->created = 0; /* Not created == invalid. */
2451 if (IS_UID_REV (sig))
2453 uid->flags.revoked = 1;
2454 return; /* Has been revoked. */
2457 uid->flags.revoked = 0;
2459 uid->expiredate = sig->expiredate;
2461 if (sig->flags.expired)
2463 uid->flags.expired = 1;
2464 return; /* Has expired. */
2467 uid->flags.expired = 0;
2469 uid->created = sig->timestamp; /* This one is okay. */
2470 uid->selfsigversion = sig->version;
2471 /* If we got this far, it's not expired :) */
2472 uid->flags.expired = 0;
2474 /* Store the key flags in the helper variable for later processing. */
2475 uid->help_key_usage = parse_key_usage (sig);
2477 /* Ditto for the key expiration. */
2478 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2479 if (p && buf32_to_u32 (p))
2480 uid->help_key_expire = keycreated + buf32_to_u32 (p);
2482 uid->help_key_expire = 0;
2484 /* Set the primary user ID flag - we will later wipe out some
2485 * of them to only have one in our keyblock. */
2486 uid->flags.primary = 0;
2487 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
2489 uid->flags.primary = 2;
2491 /* We could also query this from the unhashed area if it is not in
2492 * the hased area and then later try to decide which is the better
2493 * there should be no security problem with this.
2494 * For now we only look at the hashed one. */
2496 /* Now build the preferences list. These must come from the
2497 hashed section so nobody can modify the ciphers a key is
2498 willing to accept. */
2499 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
2502 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
2505 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
2510 n = nsym + nhash + nzip;
2515 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
2517 for (; nsym; nsym--, n++)
2519 uid->prefs[n].type = PREFTYPE_SYM;
2520 uid->prefs[n].value = *sym++;
2522 for (; nhash; nhash--, n++)
2524 uid->prefs[n].type = PREFTYPE_HASH;
2525 uid->prefs[n].value = *hash++;
2527 for (; nzip; nzip--, n++)
2529 uid->prefs[n].type = PREFTYPE_ZIP;
2530 uid->prefs[n].value = *zip++;
2532 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
2533 uid->prefs[n].value = 0;
2536 /* See whether we have the MDC feature. */
2538 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
2539 if (p && n && (p[0] & 0x01))
2542 /* And the keyserver modify flag. */
2543 uid->flags.ks_modify = 1;
2544 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
2545 if (p && n && (p[0] & 0x80))
2546 uid->flags.ks_modify = 0;
2550 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
2552 rinfo->date = sig->timestamp;
2553 rinfo->algo = sig->pubkey_algo;
2554 rinfo->keyid[0] = sig->keyid[0];
2555 rinfo->keyid[1] = sig->keyid[1];
2559 /* Given a keyblock, parse the key block and extract various pieces of
2560 * information and save them with the primary key packet and the user
2561 * id packets. For instance, some information is stored in signature
2562 * packets. We find the latest such valid packet (since the user can
2563 * change that information) and copy its contents into the
2566 * Note that R_REVOKED may be set to 0, 1 or 2.
2568 * This function fills in the following fields in the primary key's
2571 * main_keyid (computed)
2572 * revkey / numrevkeys (derived from self signed key data)
2573 * flags.valid (whether we have at least 1 self-sig)
2574 * flags.maybe_revoked (whether a designed revoked the key, but
2575 * we are missing the key to check the sig)
2576 * selfsigversion (highest version of any valid self-sig)
2577 * pubkey_usage (derived from most recent self-sig or most
2579 * has_expired (various sources)
2580 * expiredate (various sources)
2582 * See the documentation for fixup_uidnode for how the user id packets
2583 * are modified. In addition to that the primary user id's is_primary
2584 * field is set to 1 and the other user id's is_primary are set to 0.
2587 merge_selfsigs_main (ctrl_t ctrl, kbnode_t keyblock, int *r_revoked,
2588 struct revoke_info *rinfo)
2590 PKT_public_key *pk = NULL;
2593 u32 sigdate, uiddate, uiddate2;
2594 KBNODE signode, uidnode, uidnode2;
2595 u32 curtime = make_timestamp ();
2596 unsigned int key_usage = 0;
2597 u32 keytimestamp = 0;
2599 int key_expire_seen = 0;
2600 byte sigversion = 0;
2603 memset (rinfo, 0, sizeof (*rinfo));
2605 /* Section 11.1 of RFC 4880 determines the order of packets within a
2606 * message. There are three sections, which must occur in the
2607 * following order: the public key, the user ids and user attributes
2608 * and the subkeys. Within each section, each primary packet (e.g.,
2609 * a user id packet) is followed by one or more signature packets,
2610 * which modify that packet. */
2612 /* According to Section 11.1 of RFC 4880, the public key must be the
2613 first packet. Note that parse_keyblock_image ensures that the
2614 first packet is the public key. */
2615 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2617 pk = keyblock->pkt->pkt.public_key;
2618 keytimestamp = pk->timestamp;
2620 keyid_from_pk (pk, kid);
2621 pk->main_keyid[0] = kid[0];
2622 pk->main_keyid[1] = kid[1];
2624 if (pk->version < 4)
2626 /* Before v4 the key packet itself contains the expiration date
2627 * and there was no way to change it, so we start with the one
2628 * from the key packet. */
2629 key_expire = pk->max_expiredate;
2630 key_expire_seen = 1;
2635 * - Find the latest direct key self-signature. We assume that the
2636 * newest one overrides all others.
2638 * - Determine whether the key has been revoked.
2640 * - Gather all revocation keys (unlike other data, we don't just
2641 * take them from the latest self-signed packet).
2643 * - Determine max (sig[...]->version).
2646 /* Reset this in case this key was already merged. */
2652 sigdate = 0; /* Helper variable to find the latest signature. */
2654 /* According to Section 11.1 of RFC 4880, the public key comes first
2655 * and is immediately followed by any signature packets that modify
2658 k && k->pkt->pkttype != PKT_USER_ID
2659 && k->pkt->pkttype != PKT_ATTRIBUTE
2660 && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2663 if (k->pkt->pkttype == PKT_SIGNATURE)
2665 PKT_signature *sig = k->pkt->pkt.signature;
2666 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2669 if (check_key_signature (ctrl, keyblock, k, NULL))
2670 ; /* Signature did not verify. */
2671 else if (IS_KEY_REV (sig))
2673 /* Key has been revoked - there is no way to
2674 * override such a revocation, so we theoretically
2675 * can stop now. We should not cope with expiration
2676 * times for revocations here because we have to
2677 * assume that an attacker can generate all kinds of
2678 * signatures. However due to the fact that the key
2679 * has been revoked it does not harm either and by
2680 * continuing we gather some more info on that
2683 sig_to_revoke_info (sig, rinfo);
2685 else if (IS_KEY_SIG (sig))
2687 /* Add the indicated revocations keys from all
2688 * signatures not just the latest. We do this
2689 * because you need multiple 1F sigs to properly
2690 * handle revocation keys (PGP does it this way, and
2691 * a revocation key could be sensitive and hence in
2692 * a different signature). */
2698 xrealloc (pk->revkey, sizeof (struct revocation_key) *
2699 (pk->numrevkeys + sig->numrevkeys));
2701 for (i = 0; i < sig->numrevkeys; i++)
2702 memcpy (&pk->revkey[pk->numrevkeys++],
2704 sizeof (struct revocation_key));
2707 if (sig->timestamp >= sigdate)
2708 { /* This is the latest signature so far. */
2710 if (sig->flags.expired)
2711 ; /* Signature has expired - ignore it. */
2714 sigdate = sig->timestamp;
2716 if (sig->version > sigversion)
2717 sigversion = sig->version;
2726 /* Remove dupes from the revocation keys. */
2729 int i, j, x, changed = 0;
2731 for (i = 0; i < pk->numrevkeys; i++)
2733 for (j = i + 1; j < pk->numrevkeys; j++)
2735 if (memcmp (&pk->revkey[i], &pk->revkey[j],
2736 sizeof (struct revocation_key)) == 0)
2740 for (x = j; x < pk->numrevkeys - 1; x++)
2741 pk->revkey[x] = pk->revkey[x + 1];
2751 pk->revkey = xrealloc (pk->revkey,
2753 sizeof (struct revocation_key));
2756 /* SIGNODE is the 1F signature packet with the latest creation time.
2757 * Extract some information from it. */
2760 /* Some information from a direct key signature take precedence
2761 * over the same information given in UID sigs. */
2762 PKT_signature *sig = signode->pkt->pkt.signature;
2765 key_usage = parse_key_usage (sig);
2767 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2768 if (p && buf32_to_u32 (p))
2770 key_expire = keytimestamp + buf32_to_u32 (p);
2771 key_expire_seen = 1;
2774 /* Mark that key as valid: One direct key signature should
2775 * render a key as valid. */
2776 pk->flags.valid = 1;
2779 /* Pass 1.5: Look for key revocation signatures that were not made
2780 * by the key (i.e. did a revocation key issue a revocation for
2781 * us?). Only bother to do this if there is a revocation key in the
2782 * first place and we're not revoked already. */
2784 if (!*r_revoked && pk->revkey)
2785 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
2787 if (k->pkt->pkttype == PKT_SIGNATURE)
2789 PKT_signature *sig = k->pkt->pkt.signature;
2791 if (IS_KEY_REV (sig) &&
2792 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
2794 int rc = check_revocation_keys (ctrl, pk, sig);
2798 sig_to_revoke_info (sig, rinfo);
2799 /* Don't continue checking since we can't be any
2800 * more revoked than this. */
2803 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2804 pk->flags.maybe_revoked = 1;
2806 /* A failure here means the sig did not verify, was
2807 * not issued by a revocation key, or a revocation
2808 * key loop was broken. If a revocation key isn't
2809 * findable, however, the key might be revoked and
2810 * we don't know it. */
2812 /* Fixme: In the future handle subkey and cert
2813 * revocations? PGP doesn't, but it's in 2440. */
2818 /* Second pass: Look at the self-signature of all user IDs. */
2820 /* According to RFC 4880 section 11.1, user id and attribute packets
2821 * are in the second section, after the public key packet and before
2822 * the subkey packets. */
2823 signode = uidnode = NULL;
2824 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
2825 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2827 if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
2828 { /* New user id packet. */
2830 /* Apply the data from the most recent self-signed packet to
2831 * the preceding user id packet. */
2832 if (uidnode && signode)
2834 fixup_uidnode (uidnode, signode, keytimestamp);
2835 pk->flags.valid = 1;
2838 /* Clear SIGNODE. The only relevant self-signed data for
2839 * UIDNODE follows it. */
2840 if (k->pkt->pkttype == PKT_USER_ID)
2848 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2850 PKT_signature *sig = k->pkt->pkt.signature;
2851 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2853 if (check_key_signature (ctrl, keyblock, k, NULL))
2854 ; /* signature did not verify */
2855 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
2856 && sig->timestamp >= sigdate)
2858 /* Note: we allow invalidation of cert revocations
2859 * by a newer signature. An attacker can't use this
2860 * because a key should be revoked with a key revocation.
2861 * The reason why we have to allow for that is that at
2862 * one time an email address may become invalid but later
2863 * the same email address may become valid again (hired,
2864 * fired, hired again). */
2866 sigdate = sig->timestamp;
2868 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2869 if (sig->version > sigversion)
2870 sigversion = sig->version;
2875 if (uidnode && signode)
2877 fixup_uidnode (uidnode, signode, keytimestamp);
2878 pk->flags.valid = 1;
2881 /* If the key isn't valid yet, and we have
2882 * --allow-non-selfsigned-uid set, then force it valid. */
2883 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
2886 log_info (_("Invalid key %s made valid by"
2887 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
2888 pk->flags.valid = 1;
2891 /* The key STILL isn't valid, so try and find an ultimately
2892 * trusted signature. */
2893 if (!pk->flags.valid)
2897 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2900 if (k->pkt->pkttype == PKT_USER_ID)
2902 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2904 PKT_signature *sig = k->pkt->pkt.signature;
2906 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
2908 PKT_public_key *ultimate_pk;
2910 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
2912 /* We don't want to use the full get_pubkey to avoid
2913 * infinite recursion in certain cases. There is no
2914 * reason to check that an ultimately trusted key is
2915 * still valid - if it has been revoked the user
2916 * should also remove the ultimate trust flag. */
2917 if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
2918 && check_key_signature2 (ctrl,
2919 keyblock, k, ultimate_pk,
2920 NULL, NULL, NULL, NULL) == 0
2921 && get_ownertrust (ctrl, ultimate_pk) == TRUST_ULTIMATE)
2923 free_public_key (ultimate_pk);
2924 pk->flags.valid = 1;
2928 free_public_key (ultimate_pk);
2934 /* Record the highest selfsig version so we know if this is a v3 key
2935 * through and through, or a v3 key with a v4 selfsig somewhere.
2936 * This is useful in a few places to know if the key must be treated
2937 * as PGP2-style or OpenPGP-style. Note that a selfsig revocation
2938 * with a higher version number will also raise this value. This is
2939 * okay since such a revocation must be issued by the user (i.e. it
2940 * cannot be issued by someone else to modify the key behavior.) */
2942 pk->selfsigversion = sigversion;
2944 /* Now that we had a look at all user IDs we can now get some
2945 * information from those user IDs. */
2949 /* Find the latest user ID with key flags set. */
2950 uiddate = 0; /* Helper to find the latest user ID. */
2951 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2954 if (k->pkt->pkttype == PKT_USER_ID)
2956 PKT_user_id *uid = k->pkt->pkt.user_id;
2958 if (uid->help_key_usage && uid->created > uiddate)
2960 key_usage = uid->help_key_usage;
2961 uiddate = uid->created;
2969 /* No key flags at all: get it from the algo. */
2970 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
2974 /* Check that the usage matches the usage as given by the algo. */
2975 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
2976 if (x) /* Mask it down to the actual allowed usage. */
2980 /* Whatever happens, it's a primary key, so it can certify. */
2981 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
2983 if (!key_expire_seen)
2985 /* Find the latest valid user ID with a key expiration set
2986 * Note, that this may be a different one from the above because
2987 * some user IDs may have no expiration date set. */
2989 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2992 if (k->pkt->pkttype == PKT_USER_ID)
2994 PKT_user_id *uid = k->pkt->pkt.user_id;
2995 if (uid->help_key_expire && uid->created > uiddate)
2997 key_expire = uid->help_key_expire;
2998 uiddate = uid->created;
3004 /* Currently only v3 keys have a maximum expiration date, but I'll
3005 * bet v5 keys get this feature again. */
3007 || (pk->max_expiredate && key_expire > pk->max_expiredate))
3008 key_expire = pk->max_expiredate;
3010 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
3011 pk->expiredate = key_expire;
3013 /* Fixme: we should see how to get rid of the expiretime fields but
3014 * this needs changes at other places too. */
3016 /* And now find the real primary user ID and delete all others. */
3017 uiddate = uiddate2 = 0;
3018 uidnode = uidnode2 = NULL;
3019 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3021 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
3023 PKT_user_id *uid = k->pkt->pkt.user_id;
3024 if (uid->flags.primary)
3026 if (uid->created > uiddate)
3028 uiddate = uid->created;
3031 else if (uid->created == uiddate && uidnode)
3033 /* The dates are equal, so we need to do a different
3034 * (and arbitrary) comparison. This should rarely,
3035 * if ever, happen. It's good to try and guarantee
3036 * that two different GnuPG users with two different
3037 * keyrings at least pick the same primary. */
3038 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
3044 if (uid->created > uiddate2)
3046 uiddate2 = uid->created;
3049 else if (uid->created == uiddate2 && uidnode2)
3051 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
3059 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3062 if (k->pkt->pkttype == PKT_USER_ID &&
3063 !k->pkt->pkt.user_id->attrib_data)
3065 PKT_user_id *uid = k->pkt->pkt.user_id;
3067 uid->flags.primary = 0;
3073 /* None is flagged primary - use the latest user ID we have,
3074 * and disambiguate with the arbitrary packet comparison. */
3075 uidnode2->pkt->pkt.user_id->flags.primary = 1;
3079 /* None of our uids were self-signed, so pick the one that
3080 * sorts first to be the primary. This is the best we can do
3081 * here since there are no self sigs to date the uids. */
3085 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3088 if (k->pkt->pkttype == PKT_USER_ID
3089 && !k->pkt->pkt.user_id->attrib_data)
3094 uidnode->pkt->pkt.user_id->flags.primary = 1;
3099 if (cmp_user_ids (k->pkt->pkt.user_id,
3100 uidnode->pkt->pkt.user_id) > 0)
3102 uidnode->pkt->pkt.user_id->flags.primary = 0;
3104 uidnode->pkt->pkt.user_id->flags.primary = 1;
3108 /* just to be safe: */
3109 k->pkt->pkt.user_id->flags.primary = 0;
3118 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
3119 * Caller must free the signature when they are done. */
3120 static PKT_signature *
3121 buf_to_sig (const byte * buf, size_t len)
3123 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
3124 IOBUF iobuf = iobuf_temp_with_content (buf, len);
3125 int save_mode = set_packet_list_mode (0);
3127 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
3133 set_packet_list_mode (save_mode);
3134 iobuf_close (iobuf);
3140 /* Use the self-signed data to fill in various fields in subkeys.
3142 * KEYBLOCK is the whole keyblock. SUBNODE is the subkey to fill in.
3144 * Sets the following fields on the subkey:
3147 * flags.valid if the subkey has a valid self-sig binding
3154 * On this subkey's most revent valid self-signed packet, the
3155 * following field is set:
3157 * flags.chosen_selfsig
3160 merge_selfsigs_subkey (ctrl_t ctrl, kbnode_t keyblock, kbnode_t subnode)
3162 PKT_public_key *mainpk = NULL, *subpk = NULL;
3168 u32 curtime = make_timestamp ();
3169 unsigned int key_usage = 0;
3170 u32 keytimestamp = 0;
3174 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3176 mainpk = keyblock->pkt->pkt.public_key;
3177 if (mainpk->version < 4)
3178 return;/* (actually this should never happen) */
3179 keyid_from_pk (mainpk, mainkid);
3180 subpk = subnode->pkt->pkt.public_key;
3181 keytimestamp = subpk->timestamp;
3183 subpk->flags.valid = 0;
3184 subpk->flags.exact = 0;
3185 subpk->main_keyid[0] = mainpk->main_keyid[0];
3186 subpk->main_keyid[1] = mainpk->main_keyid[1];
3188 /* Find the latest key binding self-signature. */
3190 sigdate = 0; /* Helper to find the latest signature. */
3191 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3194 if (k->pkt->pkttype == PKT_SIGNATURE)
3196 sig = k->pkt->pkt.signature;
3197 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
3199 if (check_key_signature (ctrl, keyblock, k, NULL))
3200 ; /* Signature did not verify. */
3201 else if (IS_SUBKEY_REV (sig))
3203 /* Note that this means that the date on a
3204 * revocation sig does not matter - even if the
3205 * binding sig is dated after the revocation sig,
3206 * the subkey is still marked as revoked. This
3207 * seems ok, as it is just as easy to make new
3208 * subkeys rather than re-sign old ones as the
3209 * problem is in the distribution. Plus, PGP (7)
3210 * does this the same way. */
3211 subpk->flags.revoked = 1;
3212 sig_to_revoke_info (sig, &subpk->revoked);
3213 /* Although we could stop now, we continue to
3214 * figure out other information like the old expiration
3217 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
3219 if (sig->flags.expired)
3220 ; /* Signature has expired - ignore it. */
3223 sigdate = sig->timestamp;
3225 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
3232 /* No valid key binding. */
3236 sig = signode->pkt->pkt.signature;
3237 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
3239 key_usage = parse_key_usage (sig);
3242 /* No key flags at all: get it from the algo. */
3243 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
3247 /* Check that the usage matches the usage as given by the algo. */
3248 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
3249 if (x) /* Mask it down to the actual allowed usage. */
3253 subpk->pubkey_usage = key_usage;
3255 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
3256 if (p && buf32_to_u32 (p))
3257 key_expire = keytimestamp + buf32_to_u32 (p);
3261 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
3262 subpk->expiredate = key_expire;
3264 /* Algo doesn't exist. */
3265 if (openpgp_pk_test_algo (subpk->pubkey_algo))
3268 subpk->flags.valid = 1;
3270 /* Find the most recent 0x19 embedded signature on our self-sig. */
3271 if (!subpk->flags.backsig)
3275 PKT_signature *backsig = NULL;
3279 /* We do this while() since there may be other embedded
3280 * signatures in the future. We only want 0x19 here. */
3282 while ((p = enum_sig_subpkt (sig->hashed,
3283 SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
3285 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
3287 PKT_signature *tempsig = buf_to_sig (p, n);
3290 if (tempsig->timestamp > sigdate)
3293 free_seckey_enc (backsig);
3296 sigdate = backsig->timestamp;
3299 free_seckey_enc (tempsig);
3305 /* It is safe to have this in the unhashed area since the 0x19
3306 * is located on the selfsig for convenience, not security. */
3308 while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
3311 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
3313 PKT_signature *tempsig = buf_to_sig (p, n);
3316 if (tempsig->timestamp > sigdate)
3319 free_seckey_enc (backsig);
3322 sigdate = backsig->timestamp;
3325 free_seckey_enc (tempsig);
3331 /* At this point, backsig contains the most recent 0x19 sig.
3332 * Let's see if it is good. */
3334 /* 2==valid, 1==invalid, 0==didn't check */
3335 if (check_backsig (mainpk, subpk, backsig) == 0)
3336 subpk->flags.backsig = 2;
3338 subpk->flags.backsig = 1;
3340 free_seckey_enc (backsig);
3346 /* Merge information from the self-signatures with the public key,
3347 * subkeys and user ids to make using them more easy.
3349 * See documentation for merge_selfsigs_main, merge_selfsigs_subkey
3350 * and fixup_uidnode for exactly which fields are updated. */
3352 merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock)
3356 struct revoke_info rinfo;
3357 PKT_public_key *main_pk;
3359 unsigned int mdc_feature;
3361 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
3363 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
3365 log_error ("expected public key but found secret key "
3367 /* We better exit here because a public key is expected at
3368 * other places too. FIXME: Figure this out earlier and
3369 * don't get to here at all */
3375 merge_selfsigs_main (ctrl, keyblock, &revoked, &rinfo);
3377 /* Now merge in the data from each of the subkeys. */
3378 for (k = keyblock; k; k = k->next)
3380 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3382 merge_selfsigs_subkey (ctrl, keyblock, k);
3386 main_pk = keyblock->pkt->pkt.public_key;
3387 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
3389 /* If the primary key is revoked, expired, or invalid we
3390 * better set the appropriate flags on that key and all
3392 for (k = keyblock; k; k = k->next)
3394 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3395 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3397 PKT_public_key *pk = k->pkt->pkt.public_key;
3398 if (!main_pk->flags.valid)
3399 pk->flags.valid = 0;
3400 if (revoked && !pk->flags.revoked)
3402 pk->flags.revoked = revoked;
3403 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
3405 if (main_pk->has_expired)
3406 pk->has_expired = main_pk->has_expired;
3412 /* Set the preference list of all keys to those of the primary real
3413 * user ID. Note: we use these preferences when we don't know by
3414 * which user ID the key has been selected.
3415 * fixme: we should keep atoms of commonly used preferences or
3416 * use reference counting to optimize the preference lists storage.
3417 * FIXME: it might be better to use the intersection of
3419 * Do a similar thing for the MDC feature flag. */
3422 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3424 if (k->pkt->pkttype == PKT_USER_ID
3425 && !k->pkt->pkt.user_id->attrib_data
3426 && k->pkt->pkt.user_id->flags.primary)
3428 prefs = k->pkt->pkt.user_id->prefs;
3429 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
3433 for (k = keyblock; k; k = k->next)
3435 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3436 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3438 PKT_public_key *pk = k->pkt->pkt.public_key;
3441 pk->prefs = copy_prefs (prefs);
3442 pk->flags.mdc = mdc_feature;
3449 /* See whether the key satisfies any additional requirements specified
3450 * in CTX. If so, return the node of an appropriate key or subkey.
3451 * Otherwise, return NULL if there was no appropriate key.
3453 * Note that we do not return a reference, i.e. the result must not be
3454 * freed using 'release_kbnode'.
3456 * In case the primary key is not required, select a suitable subkey.
3457 * We need the primary key if PUBKEY_USAGE_CERT is set in REQ_USAGE or
3458 * we are in PGP6 or PGP7 mode and PUBKEY_USAGE_SIG is set in
3461 * If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
3462 * are set in REQ_USAGE, we filter by the key's function. Concretely,
3463 * if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then we only
3464 * return a key if it is (at least) either a signing or a
3465 * certification key.
3467 * If REQ_USAGE is set, then we reject any keys that are not good
3468 * (i.e., valid, not revoked, not expired, etc.). This allows the
3469 * getkey functions to be used for plain key listings.
3471 * Sets the matched key's user id field (pk->user_id) to the user id
3472 * that matched the low-level search criteria or NULL.
3474 * If R_FLAGS is not NULL set certain flags for more detailed error
3475 * reporting. Used flags are:
3477 * - LOOKUP_ALL_SUBKEYS_EXPIRED :: All Subkeys are expired or have
3479 * - LOOKUP_NOT_SELECTED :: No suitable key found
3481 * This function needs to handle several different cases:
3483 * 1. No requested usage and no primary key requested
3484 * Examples for this case are that we have a keyID to be used
3485 * for decrytion or verification.
3486 * 2. No usage but primary key requested
3487 * This is the case for all functions which work on an
3488 * entire keyblock, e.g. for editing or listing
3489 * 3. Usage and primary key requested
3491 * 4. Usage but no primary key requested
3496 finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact,
3497 int want_secret, unsigned int *r_flags)
3501 /* If WANT_EXACT is set, the key or subkey that actually matched the
3502 low-level search criteria. */
3503 kbnode_t foundk = NULL;
3504 /* The user id (if any) that matched the low-level search criteria. */
3505 PKT_user_id *foundu = NULL;
3508 kbnode_t latest_key;
3511 u32 curtime = make_timestamp ();
3516 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
3517 req_usage &= USAGE_MASK;
3519 /* Request the primary if we're certifying another key, and also if
3520 * signing data while --pgp6 or --pgp7 is on since pgp 6 and 7 do
3521 * not understand signatures made by a signing subkey. PGP 8 does. */
3522 req_prim = ((req_usage & PUBKEY_USAGE_CERT)
3523 || ((PGP6 || PGP7) && (req_usage & PUBKEY_USAGE_SIG)));
3526 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
3528 /* For an exact match mark the primary or subkey that matched the
3529 low-level search criteria. */
3532 for (k = keyblock; k; k = k->next)
3536 log_assert (k->pkt->pkttype == PKT_PUBLIC_KEY
3537 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3539 pk = k->pkt->pkt.public_key;
3540 pk->flags.exact = 1;
3546 /* Get the user id that matched that low-level search criteria. */
3547 for (k = keyblock; k; k = k->next)
3551 log_assert (k->pkt->pkttype == PKT_USER_ID);
3552 foundu = k->pkt->pkt.user_id;
3558 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
3559 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
3560 foundk ? "one" : "all", req_usage);
3564 latest_key = foundk ? foundk : keyblock;
3570 /* Set LATEST_KEY to the latest (the one with the most recent
3571 * timestamp) good (valid, not revoked, not expired, etc.) subkey.
3573 * Don't bother if we are only looking for a primary key or we need
3574 * an exact match and the exact match is not a subkey. */
3575 if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
3581 int n_revoked_or_expired = 0;
3583 /* Either start a loop or check just this one subkey. */
3584 for (k = foundk ? foundk : keyblock; k; k = nextk)
3588 /* If FOUNDK is not NULL, then only consider that exact
3589 key, i.e., don't iterate. */
3595 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3598 pk = k->pkt->pkt.public_key;
3600 log_debug ("\tchecking subkey %08lX\n",
3601 (ulong) keyid_from_pk (pk, NULL));
3603 if (!pk->flags.valid)
3606 log_debug ("\tsubkey not valid\n");
3609 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3612 log_debug ("\tusage does not match: want=%x have=%x\n",
3613 req_usage, pk->pubkey_usage);
3618 if (pk->flags.revoked)
3621 log_debug ("\tsubkey has been revoked\n");
3622 n_revoked_or_expired++;
3625 if (pk->has_expired)
3628 log_debug ("\tsubkey has expired\n");
3629 n_revoked_or_expired++;
3632 if (pk->timestamp > curtime && !opt.ignore_valid_from)
3635 log_debug ("\tsubkey not yet valid\n");
3639 if (want_secret && agent_probe_secret_key (NULL, pk))
3642 log_debug ("\tno secret key\n");
3647 log_debug ("\tsubkey might be fine\n");
3648 /* In case a key has a timestamp of 0 set, we make sure
3649 that it is used. A better change would be to compare
3650 ">=" but that might also change the selected keys and
3651 is as such a more intrusive change. */
3652 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
3654 latest_date = pk->timestamp;
3658 if (n_subkeys == n_revoked_or_expired && r_flags)
3659 *r_flags |= LOOKUP_ALL_SUBKEYS_EXPIRED;
3662 /* Check if the primary key is ok (valid, not revoke, not expire,
3663 * matches requested usage) if:
3665 * - we didn't find an appropriate subkey and we're not doing an
3668 * - we're doing an exact match and the exact match was the
3671 * - we're just considering the primary key. */
3672 if ((!latest_key && !want_exact) || foundk == keyblock || req_prim)
3674 if (DBG_LOOKUP && !foundk && !req_prim)
3675 log_debug ("\tno suitable subkeys found - trying primary\n");
3676 pk = keyblock->pkt->pkt.public_key;
3677 if (!pk->flags.valid)
3680 log_debug ("\tprimary key not valid\n");
3682 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3685 log_debug ("\tprimary key usage does not match: "
3686 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
3688 else if (pk->flags.revoked)
3691 log_debug ("\tprimary key has been revoked\n");
3693 else if (pk->has_expired)
3696 log_debug ("\tprimary key has expired\n");
3701 log_debug ("\tprimary key may be used\n");
3702 latest_key = keyblock;
3709 log_debug ("\tno suitable key found - giving up\n");
3711 *r_flags |= LOOKUP_NOT_SELECTED;
3712 return NULL; /* Not found. */
3717 log_debug ("\tusing key %08lX\n",
3718 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
3722 pk = latest_key->pkt->pkt.public_key;
3723 free_user_id (pk->user_id);
3724 pk->user_id = scopy_user_id (foundu);
3727 if (latest_key != keyblock && opt.verbose)
3730 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
3731 log_info (_("using subkey %s instead of primary key %s\n"),
3732 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
3736 cache_user_id (keyblock);
3738 return latest_key ? latest_key : keyblock; /* Found. */
3742 /* Print a KEY_CONSIDERED status line. */
3744 print_status_key_considered (kbnode_t keyblock, unsigned int flags)
3746 char hexfpr[2*MAX_FINGERPRINT_LEN + 1];
3750 if (!is_status_enabled ())
3753 for (node=keyblock; node; node = node->next)
3754 if (node->pkt->pkttype == PKT_PUBLIC_KEY
3755 || node->pkt->pkttype == PKT_SECRET_KEY)
3759 log_error ("%s: keyblock w/o primary key\n", __func__);
3763 hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr);
3764 snprintf (flagbuf, sizeof flagbuf, " %u", flags);
3765 write_status_strings (STATUS_KEY_CONSIDERED, hexfpr, flagbuf, NULL);
3770 /* A high-level function to lookup keys.
3772 * This function builds on top of the low-level keydb API. It first
3773 * searches the database using the description stored in CTX->ITEMS,
3774 * then it filters the results using CTX and, finally, if WANT_SECRET
3775 * is set, it ignores any keys for which no secret key is available.
3777 * Unlike the low-level search functions, this function also merges
3778 * all of the self-signed data into the keys, subkeys and user id
3779 * packets (see the merge_selfsigs for details).
3781 * On success the key's keyblock is stored at *RET_KEYBLOCK, and the
3782 * specific subkey is stored at *RET_FOUND_KEY. Note that we do not
3783 * return a reference in *RET_FOUND_KEY, i.e. the result must not be
3784 * freed using 'release_kbnode', and it is only valid until
3785 * *RET_KEYBLOCK is deallocated. Therefore, if RET_FOUND_KEY is not
3786 * NULL, then RET_KEYBLOCK must not be NULL. */
3788 lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret,
3789 kbnode_t *ret_keyblock, kbnode_t *ret_found_key)
3792 int no_suitable_key = 0;
3793 KBNODE keyblock = NULL;
3794 KBNODE found_key = NULL;
3795 unsigned int infoflags;
3797 log_assert (ret_found_key == NULL || ret_keyblock != NULL);
3799 *ret_keyblock = NULL;
3803 rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
3807 /* If we are iterating over the entire database, then we need to
3808 * change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
3809 * reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next record. */
3810 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
3811 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
3813 rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
3816 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
3822 rc = agent_probe_any_secret_key (NULL, keyblock);
3823 if (gpg_err_code(rc) == GPG_ERR_NO_SECKEY)
3824 goto skip; /* No secret key available. */
3826 goto found; /* Unexpected error. */
3829 /* Warning: node flag bits 0 and 1 should be preserved by
3830 * merge_selfsigs. */
3831 merge_selfsigs (ctrl, keyblock);
3832 found_key = finish_lookup (keyblock, ctx->req_usage, ctx->exact,
3833 want_secret, &infoflags);
3834 print_status_key_considered (keyblock, infoflags);
3837 no_suitable_key = 0;
3842 no_suitable_key = 1;
3846 /* Release resources and continue search. */
3847 release_kbnode (keyblock);
3849 /* The keyblock cache ignores the current "file position".
3850 * Thus, if we request the next result and the cache matches
3851 * (and it will since it is what we just looked for), we'll get
3852 * the same entry back! We can avoid this infinite loop by
3853 * disabling the cache. */
3854 keydb_disable_caching (ctx->kr_handle);
3858 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
3859 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
3865 *ret_keyblock = keyblock; /* Return the keyblock. */
3869 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
3870 rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
3871 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
3872 rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
3874 release_kbnode (keyblock);
3879 *ret_found_key = found_key;
3881 *ret_found_key = NULL;
3888 /* Enumerate some secret keys (specifically, those specified with
3889 * --default-key and --try-secret-key). Use the following procedure:
3891 * 1) Initialize a void pointer to NULL
3892 * 2) Pass a reference to this pointer to this function (content)
3893 * and provide space for the secret key (sk)
3894 * 3) Call this function as long as it does not return an error (or
3895 * until you are done). The error code GPG_ERR_EOF indicates the
3896 * end of the listing.
3897 * 4) Call this function a last time with SK set to NULL,
3898 * so that can free it's context.
3903 * PKT_public_key *sk = xmalloc_clear (sizeof (*sk));
3905 * while ((err = enum_secret_keys (&ctx, sk)))
3909 * free_public_key (sk);
3910 * sk = xmalloc_clear (sizeof (*sk));
3913 * // Release any resources used by CTX.
3914 * enum_secret_keys (&ctx, NULL);
3915 * free_public_key (sk);
3917 * if (gpg_err_code (err) != GPG_ERR_EOF)
3918 * ; // An error occurred.
3921 enum_secret_keys (ctrl_t ctrl, void **context, PKT_public_key *sk)
3923 gpg_error_t err = 0;
3938 /* Make a new context. */
3939 c = xtrycalloc (1, sizeof *c);
3941 return gpg_error_from_syserror ();
3947 /* Free the context. */
3948 release_kbnode (c->keyblock);
3949 getkey_end (ctrl, c->ctx);
3956 return gpg_error (GPG_ERR_EOF);
3960 /* Loop until we have a keyblock. */
3961 while (!c->keyblock)
3963 /* Loop over the list of secret keys. */
3970 case 0: /* First try to use the --default-key. */
3971 name = parse_def_secret_key (ctrl);
3975 case 1: /* Init list of keys to try. */
3976 c->sl = opt.secret_keys_to_try;
3980 case 2: /* Get next item from list. */
3984 c->sl = c->sl->next;
3990 case 3: /* Init search context to enum all secret keys. */
3991 err = getkey_bynames (ctrl, &c->ctx, NULL, NULL, 1,
3995 release_kbnode (keyblock);
3997 getkey_end (ctrl, c->ctx);
4003 case 4: /* Get next item from the context. */
4006 err = getkey_next (ctrl, c->ctx, NULL, &keyblock);
4009 release_kbnode (keyblock);
4011 getkey_end (ctrl, c->ctx);
4019 default: /* No more names to check - stop. */
4021 return gpg_error (GPG_ERR_EOF);
4024 while ((!name || !*name) && !keyblock);
4027 c->node = c->keyblock = keyblock;
4030 err = getkey_byname (ctrl, NULL, NULL, name, 1, &c->keyblock);
4033 /* getkey_byname might return a keyblock even in the
4034 error case - I have not checked. Thus better release
4036 release_kbnode (c->keyblock);
4040 c->node = c->keyblock;
4044 /* Get the next key from the current keyblock. */
4045 for (; c->node; c->node = c->node->next)
4047 if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
4048 || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4050 copy_public_key (sk, c->node->pkt->pkt.public_key);
4051 c->node = c->node->next;
4052 return 0; /* Found. */
4056 /* Dispose the keyblock and continue. */
4057 release_kbnode (c->keyblock);
4063 get_seckey_default_or_card (ctrl_t ctrl, PKT_public_key *pk,
4064 const byte *fpr_card, size_t fpr_len)
4067 strlist_t namelist = NULL;
4069 const char *def_secret_key = parse_def_secret_key (ctrl);
4072 add_to_strlist (&namelist, def_secret_key);
4074 return get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len);
4077 || (def_secret_key && def_secret_key[strlen (def_secret_key)-1] == '!'))
4078 err = key_byname (ctrl, NULL, namelist, pk, 1, 0, NULL, NULL);
4080 { /* Default key is specified and card key is also available. */
4081 kbnode_t k, keyblock = NULL;
4083 err = key_byname (ctrl, NULL, namelist, pk, 1, 0, &keyblock, NULL);
4085 for (k = keyblock; k; k = k->next)
4087 PKT_public_key *pk_candidate;
4088 char fpr[MAX_FINGERPRINT_LEN];
4090 if (k->pkt->pkttype != PKT_PUBLIC_KEY
4091 &&k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
4094 pk_candidate = k->pkt->pkt.public_key;
4095 if (!pk_candidate->flags.valid)
4097 if (!((pk_candidate->pubkey_usage & USAGE_MASK) & pk->req_usage))
4099 fingerprint_from_pk (pk_candidate, fpr, NULL);
4100 if (!memcmp (fpr_card, fpr, fpr_len))
4102 release_public_key_parts (pk);
4103 copy_public_key (pk, pk_candidate);
4107 release_kbnode (keyblock);
4110 free_strlist (namelist);
4115 /*********************************************
4116 *********** User ID printing helpers *******
4117 *********************************************/
4119 /* Return a string with a printable representation of the user_id.
4120 * this string must be freed by xfree. */
4122 get_user_id_string (ctrl_t ctrl, u32 * keyid, int mode, size_t *r_len)
4129 /* Try it two times; second pass reads from the database. */
4132 for (r = user_id_db; r; r = r->next)
4134 for (a = r->keyids; a; a = a->next)
4136 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
4140 /* An empty string as user id is possible. Make
4141 sure that the malloc allocates one byte and
4142 does not bail out. */
4143 p = xmalloc (r->len? r->len : 1);
4144 memcpy (p, r->name, r->len);
4151 p = xasprintf ("%08lX%08lX %.*s",
4152 (ulong) keyid[0], (ulong) keyid[1],
4155 p = xasprintf ("%s %.*s", keystr (keyid),
4158 *r_len = strlen (p);
4166 while (++pass < 2 && !get_pubkey (ctrl, NULL, keyid));
4169 p = xstrdup (user_id_not_found_utf8 ());
4171 p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
4173 p = xasprintf ("%s [?]", keystr (keyid));
4176 *r_len = strlen (p);
4182 get_user_id_string_native (ctrl_t ctrl, u32 * keyid)
4184 char *p = get_user_id_string (ctrl, keyid, 0, NULL);
4185 char *p2 = utf8_to_native (p, strlen (p), 0);
4192 get_long_user_id_string (ctrl_t ctrl, u32 * keyid)
4194 return get_user_id_string (ctrl, keyid, 1, NULL);
4198 /* Please try to use get_user_byfpr instead of this one. */
4200 get_user_id (ctrl_t ctrl, u32 *keyid, size_t *rn)
4202 return get_user_id_string (ctrl, keyid, 2, rn);
4206 /* Please try to use get_user_id_byfpr_native instead of this one. */
4208 get_user_id_native (ctrl_t ctrl, u32 *keyid)
4211 char *p = get_user_id (ctrl, keyid, &rn);
4212 char *p2 = utf8_to_native (p, rn, 0);
4218 /* Return the user id for a key designated by its fingerprint, FPR,
4219 which must be MAX_FINGERPRINT_LEN bytes in size. Note: the
4220 returned string, which must be freed using xfree, may not be NUL
4221 terminated. To determine the length of the string, you must use
4224 get_user_id_byfpr (ctrl_t ctrl, const byte *fpr, size_t *rn)
4230 /* Try it two times; second pass reads from the database. */
4233 for (r = user_id_db; r; r = r->next)
4236 for (a = r->keyids; a; a = a->next)
4238 if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
4240 /* An empty string as user id is possible. Make
4241 sure that the malloc allocates one byte and does
4243 p = xmalloc (r->len? r->len : 1);
4244 memcpy (p, r->name, r->len);
4252 && !get_pubkey_byfprint (ctrl, NULL, NULL, fpr, MAX_FINGERPRINT_LEN));
4253 p = xstrdup (user_id_not_found_utf8 ());
4258 /* Like get_user_id_byfpr, but convert the string to the native
4259 encoding. The returned string needs to be freed. Unlike
4260 get_user_id_byfpr, the returned string is NUL terminated. */
4262 get_user_id_byfpr_native (ctrl_t ctrl, const byte *fpr)
4265 char *p = get_user_id_byfpr (ctrl, fpr, &rn);
4266 char *p2 = utf8_to_native (p, rn, 0);
4272 /* Return the database handle used by this context. The context still
4275 get_ctx_handle (GETKEY_CTX ctx)
4277 return ctx->kr_handle;
4281 free_akl (struct akl *akl)
4287 free_keyserver_spec (akl->spec);
4295 while (opt.auto_key_locate)
4297 struct akl *akl2 = opt.auto_key_locate;
4298 opt.auto_key_locate = opt.auto_key_locate->next;
4303 /* Returns false on error. */
4305 parse_auto_key_locate (const char *options_arg)
4308 char *options, *options_buf;
4310 options = options_buf = xstrdup (options_arg);
4311 while ((tok = optsep (&options)))
4313 struct akl *akl, *check, *last = NULL;
4319 akl = xmalloc_clear (sizeof (*akl));
4321 if (ascii_strcasecmp (tok, "clear") == 0)
4324 free_akl (opt.auto_key_locate);
4325 opt.auto_key_locate = NULL;
4328 else if (ascii_strcasecmp (tok, "nodefault") == 0)
4329 akl->type = AKL_NODEFAULT;
4330 else if (ascii_strcasecmp (tok, "local") == 0)
4331 akl->type = AKL_LOCAL;
4332 else if (ascii_strcasecmp (tok, "ldap") == 0)
4333 akl->type = AKL_LDAP;
4334 else if (ascii_strcasecmp (tok, "keyserver") == 0)
4335 akl->type = AKL_KEYSERVER;
4336 else if (ascii_strcasecmp (tok, "cert") == 0)
4337 akl->type = AKL_CERT;
4338 else if (ascii_strcasecmp (tok, "pka") == 0)
4339 akl->type = AKL_PKA;
4340 else if (ascii_strcasecmp (tok, "dane") == 0)
4341 akl->type = AKL_DANE;
4342 else if (ascii_strcasecmp (tok, "wkd") == 0)
4343 akl->type = AKL_WKD;
4344 else if ((akl->spec = parse_keyserver_uri (tok, 1)))
4345 akl->type = AKL_SPEC;
4349 xfree (options_buf);
4353 /* We must maintain the order the user gave us */
4354 for (check = opt.auto_key_locate; check;
4355 last = check, check = check->next)
4357 /* Check for duplicates */
4358 if (check->type == akl->type
4359 && (akl->type != AKL_SPEC
4360 || (akl->type == AKL_SPEC
4361 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
4374 opt.auto_key_locate = akl;
4378 xfree (options_buf);
4384 /* The list of key origins. */
4388 } key_origin_list[] =
4390 { "self", KEYORG_SELF },
4391 { "file", KEYORG_FILE },
4392 { "url", KEYORG_URL },
4393 { "wkd", KEYORG_WKD },
4394 { "dane", KEYORG_DANE },
4395 { "ks-pref", KEYORG_KS_PREF },
4396 { "ks", KEYORG_KS },
4397 { "unknown", KEYORG_UNKNOWN }
4400 /* Parse the argument for --key-origin. Return false on error. */
4402 parse_key_origin (char *string)
4407 comma = strchr (string, ',');
4411 if (!ascii_strcasecmp (string, "help"))
4413 log_info (_("valid values for option '%s':\n"), "--key-origin");
4414 for (i=0; i < DIM (key_origin_list); i++)
4415 log_info (" %s\n", key_origin_list[i].name);
4419 for (i=0; i < DIM (key_origin_list); i++)
4420 if (!ascii_strcasecmp (string, key_origin_list[i].name))
4422 opt.key_origin = key_origin_list[i].origin;
4423 xfree (opt.key_origin_url);
4424 opt.key_origin_url = NULL;
4425 if (comma && comma[1])
4427 opt.key_origin_url = xstrdup (comma+1);
4428 trim_spaces (opt.key_origin_url);
4439 /* Return a string or "?" for the key ORIGIN. */
4441 key_origin_string (int origin)
4445 for (i=0; i < DIM (key_origin_list); i++)
4446 if (key_origin_list[i].origin == origin)
4447 return key_origin_list[i].name;
4453 /* Returns true if a secret key is available for the public key with
4454 key id KEYID; returns false if not. This function ignores legacy
4455 keys. Note: this is just a fast check and does not tell us whether
4456 the secret key is valid; this check merely indicates whether there
4457 is some secret key with the specified key id. */
4459 have_secret_key_with_kid (u32 *keyid)
4463 KEYDB_SEARCH_DESC desc;
4468 kdbhd = keydb_new ();
4471 memset (&desc, 0, sizeof desc);
4472 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
4473 desc.u.kid[0] = keyid[0];
4474 desc.u.kid[1] = keyid[1];
4477 err = keydb_search (kdbhd, &desc, 1, NULL);
4481 err = keydb_get_keyblock (kdbhd, &keyblock);
4484 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
4488 for (node = keyblock; node; node = node->next)
4490 /* Bit 0 of the flags is set if the search found the key
4491 using that key or subkey. Note: a search will only ever
4492 match a single key or subkey. */
4493 if ((node->flag & 1))
4495 log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY
4496 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
4498 if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
4499 result = 1; /* Secret key available. */
4506 release_kbnode (keyblock);
4509 keydb_release (kdbhd);