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 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;
416 /* Returns all keys that match the search specification SEARCH_TERMS.
418 This function also checks for and warns about duplicate entries in
419 the keydb, which can occur if the user has configured multiple
420 keyrings or keyboxes or if a keyring or keybox was corrupted.
422 Note: SEARCH_TERMS will not be expanded (i.e., it may not be a
425 USE is the operation for which the key is required. It must be
426 either PUBKEY_USAGE_ENC, PUBKEY_USAGE_SIG, PUBKEY_USAGE_CERT or
429 XXX: Currently, only PUBKEY_USAGE_ENC and PUBKEY_USAGE_SIG are
432 INCLUDE_UNUSABLE indicates whether disabled keys are allowed.
433 (Recipients specified with --encrypt-to and --hidden-encrypt-to may
434 be disabled. It is possible to edit disabled keys.)
436 SOURCE is the context in which SEARCH_TERMS was specified, e.g.,
437 "--encrypt-to", etc. If this function is called interactively,
438 then this should be NULL.
440 If WARN_POSSIBLY_AMBIGUOUS is set, then emits a warning if the user
441 does not specify a long key id or a fingerprint.
443 The results are placed in *KEYS. *KEYS must be NULL! */
445 get_pubkeys (ctrl_t ctrl,
446 char *search_terms, int use, int include_unusable, char *source,
447 int warn_possibly_ambiguous,
450 /* We show a warning when a key appears multiple times in the DB.
451 This can happen for two reasons:
453 - The user has configured multiple keyrings or keyboxes.
455 - The keyring or keybox has been corrupted in some way, e.g., a
456 bug or a random process changing them.
458 For each duplicate, we only want to show the key once. Hence,
460 static strlist_t key_dups;
462 /* USE transformed to a string. */
467 KEYDB_SEARCH_DESC desc;
470 pubkey_t results = NULL;
475 char fingerprint[2 * MAX_FINGERPRINT_LEN + 1];
480 log_debug ("%s: Checking %s=%s\n",
481 __func__, source ? source : "user input", search_terms);
485 log_bug ("%s: KEYS should be NULL!\n", __func__);
489 case PUBKEY_USAGE_ENC: use_str = "encrypt"; break;
490 case PUBKEY_USAGE_SIG: use_str = "sign"; break;
491 case PUBKEY_USAGE_CERT: use_str = "cetify"; break;
492 case PUBKEY_USAGE_AUTH: use_str = "authentication"; break;
493 default: log_bug ("%s: Bad value for USE (%d)\n", __func__, use);
496 if (use == PUBKEY_USAGE_CERT || use == PUBKEY_USAGE_AUTH)
497 log_bug ("%s: use=%s is unimplemented.\n", __func__, use_str);
499 err = classify_user_id (search_terms, &desc, 1);
502 log_info (_("key \"%s\" not found: %s\n"),
503 search_terms, gpg_strerror (err));
504 if (!opt.quiet && source)
505 log_info (_("(check argument of option '%s')\n"), source);
509 if (warn_possibly_ambiguous
510 && ! (desc.mode == KEYDB_SEARCH_MODE_LONG_KID
511 || desc.mode == KEYDB_SEARCH_MODE_FPR16
512 || desc.mode == KEYDB_SEARCH_MODE_FPR20
513 || desc.mode == KEYDB_SEARCH_MODE_FPR))
515 log_info (_("Warning: '%s' should be a long key ID or a fingerprint\n"),
517 if (!opt.quiet && source)
518 log_info (_("(check argument of option '%s')\n"), source);
521 /* Gather all of the results. */
526 PKT_public_key *pk = xmalloc_clear (sizeof *pk);
531 err = get_pubkey_byname (ctrl, &ctx, pk, search_terms, &kb, NULL,
532 include_unusable, 1);
534 err = getkey_next (ctrl, ctx, pk, &kb);
536 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
537 /* No more results. */
543 /* An error (other than "not found"). */
545 log_error (_("error looking up: %s\n"),
551 /* Another result! */
554 r = xmalloc_clear (sizeof (*r));
561 getkey_end (ctrl, ctx);
565 log_debug ("%s resulted in %d matches.\n", search_terms, count);
566 for (r = results; r; r = r->next)
568 hexfingerprint (r->keyblock->pkt->pkt.public_key,
569 fingerprint, sizeof (fingerprint)));
572 if (! results && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
576 log_debug ("%s: '%s' not found.\n", __func__, search_terms);
578 log_info (_("key \"%s\" not found\n"), search_terms);
579 if (!opt.quiet && source)
580 log_info (_("(check argument of option '%s')\n"), source);
584 else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
585 /* No more matches. */
588 /* Some other error. An error message was already printed
589 out. Free RESULTS and continue. */
592 /* Check for duplicates. */
594 log_debug ("%s: Checking results of %s='%s' for dups\n",
595 __func__, source ? source : "user input", search_terms);
597 for (r = results; r; r = r->next)
608 if (cmp_public_keys (r->keyblock->pkt->pkt.public_key,
609 r2->keyblock->pkt->pkt.public_key) != 0)
620 /* Remove R2 from the list. */
622 release_kbnode (r2->keyblock);
629 hexfingerprint (r->keyblock->pkt->pkt.public_key,
630 fingerprint, sizeof fingerprint);
631 if (! strlist_find (key_dups, fingerprint))
633 char fingerprint_formatted[MAX_FORMATTED_FINGERPRINT_LEN + 1];
635 log_info (_("Warning: %s appears in the keyring %d times\n"),
636 format_hexfingerprint (fingerprint,
637 fingerprint_formatted,
638 sizeof fingerprint_formatted),
640 add_to_strlist (&key_dups, fingerprint);
645 if (DBG_LOOKUP && count)
647 log_debug ("After removing %d dups:\n", count);
648 for (r = results, count = 0; r; r = r->next)
649 log_debug (" %d: %s\n",
651 hexfingerprint (r->keyblock->pkt->pkt.public_key,
652 fingerprint, sizeof fingerprint));
657 pubkeys_free (results);
666 pk_from_block (PKT_public_key *pk, kbnode_t keyblock, kbnode_t found_key)
668 kbnode_t a = found_key ? found_key : keyblock;
670 log_assert (a->pkt->pkttype == PKT_PUBLIC_KEY
671 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
673 copy_public_key (pk, a->pkt->pkt.public_key);
677 /* Return the public key with the key id KEYID and store it at PK.
678 * The resources in *PK should be released using
679 * release_public_key_parts(). This function also stores a copy of
680 * the public key in the user id cache (see cache_public_key).
682 * If PK is NULL, this function just stores the public key in the
683 * cache and returns the usual return code.
685 * PK->REQ_USAGE (which is a mask of PUBKEY_USAGE_SIG,
686 * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT) is passed through to the
687 * lookup function. If this is non-zero, only keys with the specified
688 * usage will be returned. As such, it is essential that
689 * PK->REQ_USAGE be correctly initialized!
691 * Returns 0 on success, GPG_ERR_NO_PUBKEY if there is no public key
692 * with the specified key id, or another error code if an error
695 * If the data was not read from the cache, then the self-signed data
696 * has definitely been merged into the public key using
699 get_pubkey (ctrl_t ctrl, PKT_public_key * pk, u32 * keyid)
704 #if MAX_PK_CACHE_ENTRIES
707 /* Try to get it from the cache. We don't do this when pk is
708 NULL as it does not guarantee that the user IDs are
711 for (ce = pk_cache; ce; ce = ce->next)
713 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
714 /* XXX: We don't check PK->REQ_USAGE here, but if we don't
715 read from the cache, we do check it! */
717 copy_public_key (pk, ce->pk);
723 /* More init stuff. */
726 pk = xmalloc_clear (sizeof *pk);
733 struct getkey_ctx_s ctx;
735 KBNODE found_key = NULL;
736 memset (&ctx, 0, sizeof ctx);
737 ctx.exact = 1; /* Use the key ID exactly as given. */
738 ctx.not_allocated = 1;
740 if (ctrl && ctrl->cached_getkey_kdb)
742 ctx.kr_handle = ctrl->cached_getkey_kdb;
743 ctrl->cached_getkey_kdb = NULL;
744 keydb_search_reset (ctx.kr_handle);
748 ctx.kr_handle = keydb_new ();
751 rc = gpg_error_from_syserror ();
756 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
757 ctx.items[0].u.kid[0] = keyid[0];
758 ctx.items[0].u.kid[1] = keyid[1];
759 ctx.req_usage = pk->req_usage;
760 rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
763 pk_from_block (pk, kb, found_key);
765 getkey_end (ctrl, &ctx);
771 rc = GPG_ERR_NO_PUBKEY;
775 cache_public_key (pk);
777 free_public_key (pk);
782 /* Similar to get_pubkey, but it does not take PK->REQ_USAGE into
783 * account nor does it merge in the self-signed data. This function
784 * also only considers primary keys. It is intended to be used as a
785 * quick check of the key to avoid recursion. It should only be used
786 * in very certain cases. Like get_pubkey and unlike any of the other
787 * lookup functions, this function also consults the user id cache
788 * (see cache_public_key).
790 * Return the public key in *PK. The resources in *PK should be
791 * released using release_public_key_parts(). */
793 get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
801 #if MAX_PK_CACHE_ENTRIES
803 /* Try to get it from the cache */
806 for (ce = pk_cache; ce; ce = ce->next)
808 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]
809 /* Only consider primary keys. */
810 && ce->pk->keyid[0] == ce->pk->main_keyid[0]
811 && ce->pk->keyid[1] == ce->pk->main_keyid[1])
814 copy_public_key (pk, ce->pk);
823 return gpg_error_from_syserror ();
824 rc = keydb_search_kid (hd, keyid);
825 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
828 return GPG_ERR_NO_PUBKEY;
830 rc = keydb_get_keyblock (hd, &keyblock);
834 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
835 return GPG_ERR_NO_PUBKEY;
838 log_assert (keyblock && keyblock->pkt
839 && keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
841 /* We return the primary key. If KEYID matched a subkey, then we
843 keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
844 if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
845 copy_public_key (pk, keyblock->pkt->pkt.public_key);
847 rc = GPG_ERR_NO_PUBKEY;
849 release_kbnode (keyblock);
851 /* Not caching key here since it won't have all of the fields
858 /* Return the key block for the key with key id KEYID or NULL, if an
859 * error occurs. Use release_kbnode() to release the key block.
861 * The self-signed data has already been merged into the public key
862 * using merge_selfsigs. */
864 get_pubkeyblock (ctrl_t ctrl, u32 * keyid)
866 struct getkey_ctx_s ctx;
868 KBNODE keyblock = NULL;
870 memset (&ctx, 0, sizeof ctx);
871 /* No need to set exact here because we want the entire block. */
872 ctx.not_allocated = 1;
873 ctx.kr_handle = keydb_new ();
877 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
878 ctx.items[0].u.kid[0] = keyid[0];
879 ctx.items[0].u.kid[1] = keyid[1];
880 rc = lookup (ctrl, &ctx, 0, &keyblock, NULL);
881 getkey_end (ctrl, &ctx);
883 return rc ? NULL : keyblock;
887 /* Return the public key with the key id KEYID iff the secret key is
888 * available and store it at PK. The resources should be released
889 * using release_public_key_parts().
891 * Unlike other lookup functions, PK may not be NULL. PK->REQ_USAGE
892 * is passed through to the lookup function and is a mask of
893 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. Thus, it
894 * must be valid! If this is non-zero, only keys with the specified
895 * usage will be returned.
897 * Returns 0 on success. If a public key with the specified key id is
898 * not found or a secret key is not available for that public key, an
899 * error code is returned. Note: this function ignores legacy keys.
900 * An error code is also return if an error occurs.
902 * The self-signed data has already been merged into the public key
903 * using merge_selfsigs. */
905 get_seckey (ctrl_t ctrl, PKT_public_key *pk, u32 *keyid)
908 struct getkey_ctx_s ctx;
909 kbnode_t keyblock = NULL;
910 kbnode_t found_key = NULL;
912 memset (&ctx, 0, sizeof ctx);
913 ctx.exact = 1; /* Use the key ID exactly as given. */
914 ctx.not_allocated = 1;
915 ctx.kr_handle = keydb_new ();
917 return gpg_error_from_syserror ();
919 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
920 ctx.items[0].u.kid[0] = keyid[0];
921 ctx.items[0].u.kid[1] = keyid[1];
922 ctx.req_usage = pk->req_usage;
923 err = lookup (ctrl, &ctx, 1, &keyblock, &found_key);
926 pk_from_block (pk, keyblock, found_key);
928 getkey_end (ctrl, &ctx);
929 release_kbnode (keyblock);
933 err = agent_probe_secret_key (/*ctrl*/NULL, pk);
935 release_public_key_parts (pk);
942 /* Skip unusable keys. A key is unusable if it is revoked, expired or
943 disabled or if the selected user id is revoked or expired. */
945 skip_unusable (void *opaque, u32 * keyid, int uid_no)
947 ctrl_t ctrl = opaque;
952 keyblock = get_pubkeyblock (ctrl, keyid);
955 log_error ("error checking usability status of %s\n", keystr (keyid));
959 pk = keyblock->pkt->pkt.public_key;
961 /* Is the key revoked or expired? */
962 if (pk->flags.revoked || pk->has_expired)
965 /* Is the user ID in question revoked or expired? */
966 if (!unusable && uid_no)
971 for (node = keyblock; node; node = node->next)
973 if (node->pkt->pkttype == PKT_USER_ID)
975 PKT_user_id *user_id = node->pkt->pkt.user_id;
978 if (uids_seen != uid_no)
981 if (user_id->flags.revoked || user_id->flags.expired)
988 /* If UID_NO is non-zero, then the keyblock better have at least
990 log_assert (uids_seen == uid_no);
994 unusable = pk_is_disabled (pk);
997 release_kbnode (keyblock);
1002 /* Search for keys matching some criteria.
1004 If RETCTX is not NULL, then the constructed context is returned in
1005 *RETCTX so that getpubkey_next can be used to get subsequent
1006 results. In this case, getkey_end() must be used to free the
1007 search context. If RETCTX is not NULL, then RET_KDBHD must be
1010 If NAMELIST is not NULL, then a search query is constructed using
1011 classify_user_id on each of the strings in the list. (Recall: the
1012 database does an OR of the terms, not an AND.) If NAMELIST is
1013 NULL, then all results are returned.
1015 If PK is not NULL, the public key of the first result is returned
1016 in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
1017 set, it is used to filter the search results. See the
1018 documentation for finish_lookup to understand exactly how this is
1019 used. Note: The self-signed data has already been merged into the
1020 public key using merge_selfsigs. Free *PK by calling
1021 release_public_key_parts (or, if PK was allocated using xfree, you
1022 can use free_public_key, which calls release_public_key_parts(PK)
1023 and then xfree(PK)).
1025 If WANT_SECRET is set, then only keys with an available secret key
1026 (either locally or via key registered on a smartcard) are returned.
1028 If INCLUDE_UNUSABLE is set, then unusable keys (see the
1029 documentation for skip_unusable for an exact definition) are
1030 skipped unless they are looked up by key id or by fingerprint.
1032 If RET_KB is not NULL, the keyblock is returned in *RET_KB. This
1033 should be freed using release_kbnode().
1035 If RET_KDBHD is not NULL, then the new database handle used to
1036 conduct the search is returned in *RET_KDBHD. This can be used to
1037 get subsequent results using keydb_search_next. Note: in this
1038 case, no advanced filtering is done for subsequent results (e.g.,
1039 WANT_SECRET and PK->REQ_USAGE are not respected).
1041 This function returns 0 on success. Otherwise, an error code is
1042 returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1043 (if want_secret is set) is returned if the key is not found. */
1045 key_byname (ctrl_t ctrl, GETKEY_CTX *retctx, strlist_t namelist,
1047 int want_secret, int include_unusable,
1048 KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
1054 KBNODE help_kb = NULL;
1055 KBNODE found_key = NULL;
1059 /* Reset the returned context in case of error. */
1060 log_assert (!ret_kdbhd); /* Not allowed because the handle is stored
1068 /* No search terms: iterate over the whole DB. */
1070 ctx = xmalloc_clear (sizeof *ctx);
1072 ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
1073 if (!include_unusable)
1075 ctx->items[0].skipfnc = skip_unusable;
1076 ctx->items[0].skipfncvalue = ctrl;
1081 /* Build the search context. */
1082 for (n = 0, r = namelist; r; r = r->next)
1085 /* CTX has space for a single search term at the end. Thus, we
1086 need to allocate sizeof *CTX plus (n - 1) sizeof
1088 ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
1091 for (n = 0, r = namelist; r; r = r->next, n++)
1095 err = classify_user_id (r->d, &ctx->items[n], 1);
1097 if (ctx->items[n].exact)
1102 return gpg_err_code (err); /* FIXME: remove gpg_err_code. */
1104 if (!include_unusable
1105 && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
1106 && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
1107 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
1108 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
1109 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
1111 ctx->items[n].skipfnc = skip_unusable;
1112 ctx->items[n].skipfncvalue = ctrl;
1117 ctx->want_secret = want_secret;
1118 ctx->kr_handle = keydb_new ();
1119 if (!ctx->kr_handle)
1121 rc = gpg_error_from_syserror ();
1122 getkey_end (ctrl, ctx);
1131 ctx->req_usage = pk->req_usage;
1134 rc = lookup (ctrl, ctx, want_secret, ret_kb, &found_key);
1137 pk_from_block (pk, *ret_kb, found_key);
1140 release_kbnode (help_kb);
1142 if (retctx) /* Caller wants the context. */
1148 *ret_kdbhd = ctx->kr_handle;
1149 ctx->kr_handle = NULL;
1151 getkey_end (ctrl, ctx);
1158 /* Find a public key identified by NAME.
1160 * If name appears to be a valid RFC822 mailbox (i.e., email
1161 * address) and auto key lookup is enabled (no_akl == 0), then the
1162 * specified auto key lookup methods (--auto-key-lookup) are used to
1163 * import the key into the local keyring. Otherwise, just the local
1164 * keyring is consulted.
1166 * If RETCTX is not NULL, then the constructed context is returned in
1167 * *RETCTX so that getpubkey_next can be used to get subsequent
1168 * results. In this case, getkey_end() must be used to free the
1169 * search context. If RETCTX is not NULL, then RET_KDBHD must be
1172 * If PK is not NULL, the public key of the first result is returned
1173 * in *PK. Note: PK->REQ_USAGE must be valid!!! PK->REQ_USAGE is
1174 * passed through to the lookup function and is a mask of
1175 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this
1176 * is non-zero, only keys with the specified usage will be returned.
1177 * Note: The self-signed data has already been merged into the public
1178 * key using merge_selfsigs. Free *PK by calling
1179 * release_public_key_parts (or, if PK was allocated using xfree, you
1180 * can use free_public_key, which calls release_public_key_parts(PK)
1181 * and then xfree(PK)).
1183 * NAME is a string, which is turned into a search query using
1186 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
1187 * *RET_KEYBLOCK. This should be freed using release_kbnode().
1189 * If RET_KDBHD is not NULL, then the new database handle used to
1190 * conduct the search is returned in *RET_KDBHD. This can be used to
1191 * get subsequent results using keydb_search_next or to modify the
1192 * returned record. Note: in this case, no advanced filtering is done
1193 * for subsequent results (e.g., PK->REQ_USAGE is not respected).
1194 * Unlike RETCTX, this is always returned.
1196 * If INCLUDE_UNUSABLE is set, then unusable keys (see the
1197 * documentation for skip_unusable for an exact definition) are
1198 * skipped unless they are looked up by key id or by fingerprint.
1200 * If NO_AKL is set, then the auto key locate functionality is
1201 * disabled and only the local key ring is considered. Note: the
1202 * local key ring is consulted even if local is not in the
1203 * --auto-key-locate option list!
1205 * This function returns 0 on success. Otherwise, an error code is
1206 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1207 * (if want_secret is set) is returned if the key is not found. */
1209 get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
1210 const char *name, KBNODE * ret_keyblock,
1211 KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
1214 strlist_t namelist = NULL;
1218 int anylocalfirst = 0;
1220 /* If RETCTX is not NULL, then RET_KDBHD must be NULL. */
1221 log_assert (retctx == NULL || ret_kdbhd == NULL);
1226 /* Does NAME appear to be a mailbox (mail address)? */
1227 is_mbox = is_valid_mailbox (name);
1229 /* The auto-key-locate feature works as follows: there are a number
1230 * of methods to look up keys. By default, the local keyring is
1231 * tried first. Then, each method listed in the --auto-key-locate is
1232 * tried in the order it appears.
1234 * This can be changed as follows:
1236 * - if nodefault appears anywhere in the list of options, then
1237 * the local keyring is not tried first, or,
1239 * - if local appears anywhere in the list of options, then the
1240 * local keyring is not tried first, but in the order in which
1241 * it was listed in the --auto-key-locate option.
1243 * Note: we only save the search context in RETCTX if the local
1244 * method is the first method tried (either explicitly or
1248 /* auto-key-locate is enabled. */
1250 /* nodefault is true if "nodefault" or "local" appear. */
1251 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1252 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
1257 /* anylocalfirst is true if "local" appears before any other
1258 search methods (except "nodefault"). */
1259 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1260 if (akl->type != AKL_NODEFAULT)
1262 if (akl->type == AKL_LOCAL)
1270 /* "nodefault" didn't occur. Thus, "local" is implicitly the
1271 * first method to try. */
1275 if (nodefault && is_mbox)
1277 /* Either "nodefault" or "local" (explicitly) appeared in the
1278 * auto key locate list and NAME appears to be an email address.
1279 * Don't try the local keyring. */
1280 rc = GPG_ERR_NO_PUBKEY;
1284 /* Either "nodefault" and "local" don't appear in the auto key
1285 * locate list (in which case we try the local keyring first) or
1286 * NAME does not appear to be an email address (in which case we
1287 * only try the local keyring). In this case, lookup NAME in
1288 * the local keyring. */
1289 add_to_strlist (&namelist, name);
1290 rc = key_byname (ctrl, retctx, namelist, pk, 0,
1291 include_unusable, ret_keyblock, ret_kdbhd);
1294 /* If the requested name resembles a valid mailbox and automatic
1295 retrieval has been enabled, we try to import the key. */
1296 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && !no_akl && is_mbox)
1298 /* NAME wasn't present in the local keyring (or we didn't try
1299 * the local keyring). Since the auto key locate feature is
1300 * enabled and NAME appears to be an email address, try the auto
1301 * locate feature. */
1302 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1304 unsigned char *fpr = NULL;
1306 int did_akl_local = 0;
1307 int no_fingerprint = 0;
1308 const char *mechanism = "?";
1313 /* This is a dummy mechanism. */
1315 rc = GPG_ERR_NO_PUBKEY;
1319 mechanism = "Local";
1323 getkey_end (ctrl, *retctx);
1326 add_to_strlist (&namelist, name);
1327 rc = key_byname (ctrl, anylocalfirst ? retctx : NULL,
1329 include_unusable, ret_keyblock, ret_kdbhd);
1333 mechanism = "DNS CERT";
1334 glo_ctrl.in_auto_key_retrieve++;
1335 rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len);
1336 glo_ctrl.in_auto_key_retrieve--;
1341 glo_ctrl.in_auto_key_retrieve++;
1342 rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
1343 glo_ctrl.in_auto_key_retrieve--;
1348 glo_ctrl.in_auto_key_retrieve++;
1349 rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len);
1350 glo_ctrl.in_auto_key_retrieve--;
1355 glo_ctrl.in_auto_key_retrieve++;
1356 rc = keyserver_import_wkd (ctrl, name, 0, &fpr, &fpr_len);
1357 glo_ctrl.in_auto_key_retrieve--;
1362 glo_ctrl.in_auto_key_retrieve++;
1363 rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
1364 glo_ctrl.in_auto_key_retrieve--;
1368 /* Strictly speaking, we don't need to only use a valid
1369 * mailbox for the getname search, but it helps cut down
1370 * on the problem of searching for something like "john"
1371 * and getting a whole lot of keys back. */
1372 if (keyserver_any_configured (ctrl))
1374 mechanism = "keyserver";
1375 glo_ctrl.in_auto_key_retrieve++;
1376 rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
1378 glo_ctrl.in_auto_key_retrieve--;
1382 mechanism = "Unconfigured keyserver";
1383 rc = GPG_ERR_NO_PUBKEY;
1389 struct keyserver_spec *keyserver;
1391 mechanism = akl->spec->uri;
1392 keyserver = keyserver_match (akl->spec);
1393 glo_ctrl.in_auto_key_retrieve++;
1394 rc = keyserver_import_name (ctrl,
1395 name, &fpr, &fpr_len, keyserver);
1396 glo_ctrl.in_auto_key_retrieve--;
1401 /* Use the fingerprint of the key that we actually fetched.
1402 * This helps prevent problems where the key that we fetched
1403 * doesn't have the same name that we used to fetch it. In
1404 * the case of CERT and PKA, this is an actual security
1405 * requirement as the URL might point to a key put in by an
1406 * attacker. By forcing the use of the fingerprint, we
1407 * won't use the attacker's key here. */
1410 char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
1412 log_assert (fpr_len <= MAX_FINGERPRINT_LEN);
1414 free_strlist (namelist);
1417 bin2hex (fpr, fpr_len, fpr_string);
1420 log_info ("auto-key-locate found fingerprint %s\n",
1423 add_to_strlist (&namelist, fpr_string);
1425 else if (!rc && !fpr && !did_akl_local)
1426 { /* The acquisition method said no failure occurred, but
1427 * it didn't return a fingerprint. That's a failure. */
1429 rc = GPG_ERR_NO_PUBKEY;
1434 if (!rc && !did_akl_local)
1435 { /* There was no error and we didn't do a local lookup.
1436 * This means that we imported a key into the local
1437 * keyring. Try to read the imported key from the
1441 getkey_end (ctrl, *retctx);
1444 rc = key_byname (ctrl, anylocalfirst ? retctx : NULL,
1446 include_unusable, ret_keyblock, ret_kdbhd);
1451 log_info (_("automatically retrieved '%s' via %s\n"),
1455 if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1456 || opt.verbose || no_fingerprint)
1457 log_info (_("error retrieving '%s' via %s: %s\n"),
1459 no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
1466 getkey_end (ctrl, *retctx);
1470 if (retctx && *retctx)
1472 log_assert (!(*retctx)->extra_list);
1473 (*retctx)->extra_list = namelist;
1476 free_strlist (namelist);
1484 /* Comparison machinery for get_best_pubkey_byname. */
1486 /* First we have a struct to cache computed information about the key
1488 struct pubkey_cmp_cookie
1490 int valid; /* Is this cookie valid? */
1491 PKT_public_key key; /* The key. */
1492 PKT_user_id *uid; /* The matching UID packet. */
1493 unsigned int validity; /* Computed validity of (KEY, UID). */
1494 u32 creation_time; /* Creation time of the newest subkey
1495 capable of encryption. */
1499 /* Then we have a series of helper functions. */
1501 key_is_ok (const PKT_public_key *key)
1503 return (! key->has_expired && ! key->flags.revoked
1504 && key->flags.valid && ! key->flags.disabled);
1509 uid_is_ok (const PKT_public_key *key, const PKT_user_id *uid)
1511 return key_is_ok (key) && ! uid->flags.revoked;
1516 subkey_is_ok (const PKT_public_key *sub)
1518 return ! sub->flags.revoked && sub->flags.valid && ! sub->flags.disabled;
1522 /* Finally this function compares a NEW key to the former candidate
1523 * OLD. Returns < 0 if the old key is worse, > 0 if the old key is
1524 * better, == 0 if it is a tie. */
1526 pubkey_cmp (ctrl_t ctrl, const char *name, struct pubkey_cmp_cookie *old,
1527 struct pubkey_cmp_cookie *new, KBNODE new_keyblock)
1531 new->creation_time = 0;
1532 for (n = find_next_kbnode (new_keyblock, PKT_PUBLIC_SUBKEY);
1533 n; n = find_next_kbnode (n, PKT_PUBLIC_SUBKEY))
1535 PKT_public_key *sub = n->pkt->pkt.public_key;
1537 if ((sub->pubkey_usage & PUBKEY_USAGE_ENC) == 0)
1540 if (! subkey_is_ok (sub))
1543 if (sub->timestamp > new->creation_time)
1544 new->creation_time = sub->timestamp;
1547 for (n = find_next_kbnode (new_keyblock, PKT_USER_ID);
1548 n; n = find_next_kbnode (n, PKT_USER_ID))
1550 PKT_user_id *uid = n->pkt->pkt.user_id;
1551 char *mbox = mailbox_from_userid (uid->name);
1552 int match = mbox ? strcasecmp (name, mbox) == 0 : 0;
1558 new->uid = scopy_user_id (uid);
1560 get_validity (ctrl, new_keyblock, &new->key, uid, NULL, 0) & TRUST_MASK;
1564 return -1; /* No OLD key. */
1566 if (! uid_is_ok (&old->key, old->uid) && uid_is_ok (&new->key, uid))
1567 return -1; /* Validity of the NEW key is better. */
1569 if (old->validity < new->validity)
1570 return -1; /* Validity of the NEW key is better. */
1572 if (old->validity == new->validity && uid_is_ok (&new->key, uid)
1573 && old->creation_time < new->creation_time)
1574 return -1; /* Both keys are of the same validity, but the
1575 NEW key is newer. */
1578 /* Stick with the OLD key. */
1583 /* This function works like get_pubkey_byname, but if the name
1584 * resembles a mail address, the results are ranked and only the best
1585 * result is returned. */
1587 get_best_pubkey_byname (ctrl_t ctrl, GETKEY_CTX *retctx, PKT_public_key *pk,
1588 const char *name, KBNODE *ret_keyblock,
1589 int include_unusable, int no_akl)
1592 struct getkey_ctx_s *ctx = NULL;
1597 err = get_pubkey_byname (ctrl, &ctx, pk, name, ret_keyblock,
1598 NULL, include_unusable, no_akl);
1601 getkey_end (ctrl, ctx);
1605 if (is_valid_mailbox (name) && ctx)
1607 /* Rank results and return only the most relevant key. */
1608 struct pubkey_cmp_cookie best = { 0 };
1609 struct pubkey_cmp_cookie new = { 0 };
1610 kbnode_t new_keyblock;
1612 while (getkey_next (ctrl, ctx, &new.key, &new_keyblock) == 0)
1614 int diff = pubkey_cmp (ctrl, name, &best, &new, new_keyblock);
1615 release_kbnode (new_keyblock);
1618 /* New key is better. */
1619 release_public_key_parts (&best.key);
1620 free_user_id (best.uid);
1625 /* Old key is better. */
1626 release_public_key_parts (&new.key);
1627 free_user_id (new.uid);
1632 /* A tie. Keep the old key. */
1633 release_public_key_parts (&new.key);
1634 free_user_id (new.uid);
1638 getkey_end (ctrl, ctx);
1640 free_user_id (best.uid);
1645 if (retctx || ret_keyblock)
1647 ctx = xtrycalloc (1, sizeof **retctx);
1649 err = gpg_error_from_syserror ();
1652 ctx->kr_handle = keydb_new ();
1653 if (! ctx->kr_handle)
1655 err = gpg_error_from_syserror ();
1663 u32 *keyid = pk_keyid (&best.key);
1666 ctx->items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
1667 ctx->items[0].u.kid[0] = keyid[0];
1668 ctx->items[0].u.kid[1] = keyid[1];
1672 release_kbnode (*ret_keyblock);
1673 *ret_keyblock = NULL;
1674 err = getkey_next (ctrl, ctx, NULL, ret_keyblock);
1683 release_public_key_parts (&best.key);
1689 getkey_end (ctrl, ctx);
1696 getkey_end (ctrl, ctx);
1703 /* Get a public key from a file.
1705 * PK is the buffer to store the key. The caller needs to make sure
1706 * that PK->REQ_USAGE is valid. PK->REQ_USAGE is passed through to
1707 * the lookup function and is a mask of PUBKEY_USAGE_SIG,
1708 * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this is non-zero, only
1709 * keys with the specified usage will be returned.
1711 * FNAME is the file name. That file should contain exactly one
1714 * This function returns 0 on success. Otherwise, an error code is
1715 * returned. In particular, GPG_ERR_NO_PUBKEY is returned if the key
1718 * The self-signed data has already been merged into the public key
1719 * using merge_selfsigs. The caller must release the content of PK by
1720 * calling release_public_key_parts (or, if PK was malloced, using
1724 get_pubkey_fromfile (ctrl_t ctrl, PKT_public_key *pk, const char *fname)
1729 unsigned int infoflags;
1731 err = read_key_from_file (ctrl, fname, &keyblock);
1734 /* Warning: node flag bits 0 and 1 should be preserved by
1735 * merge_selfsigs. FIXME: Check whether this still holds. */
1736 merge_selfsigs (ctrl, keyblock);
1737 found_key = finish_lookup (keyblock, pk->req_usage, 0, &infoflags);
1738 print_status_key_considered (keyblock, infoflags);
1740 pk_from_block (pk, keyblock, found_key);
1742 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
1745 release_kbnode (keyblock);
1750 /* Lookup a key with the specified fingerprint.
1752 * If PK is not NULL, the public key of the first result is returned
1753 * in *PK. Note: this function does an exact search and thus the
1754 * returned public key may be a subkey rather than the primary key.
1755 * Note: The self-signed data has already been merged into the public
1756 * key using merge_selfsigs. Free *PK by calling
1757 * release_public_key_parts (or, if PK was allocated using xfree, you
1758 * can use free_public_key, which calls release_public_key_parts(PK)
1759 * and then xfree(PK)).
1761 * If PK->REQ_USAGE is set, it is used to filter the search results.
1762 * (Thus, if PK is not NULL, PK->REQ_USAGE must be valid!!!) See the
1763 * documentation for finish_lookup to understand exactly how this is
1766 * If R_KEYBLOCK is not NULL, then the first result's keyblock is
1767 * returned in *R_KEYBLOCK. This should be freed using
1770 * FPRINT is a byte array whose contents is the fingerprint to use as
1771 * the search term. FPRINT_LEN specifies the length of the
1772 * fingerprint (in bytes). Currently, only 16 and 20-byte
1773 * fingerprints are supported.
1775 * FIXME: We should replace this with the _byname function. This can
1776 * be done by creating a userID conforming to the unified fingerprint
1779 get_pubkey_byfprint (ctrl_t ctrl, PKT_public_key *pk, kbnode_t *r_keyblock,
1780 const byte * fprint, size_t fprint_len)
1787 if (fprint_len == 20 || fprint_len == 16)
1789 struct getkey_ctx_s ctx;
1791 KBNODE found_key = NULL;
1793 memset (&ctx, 0, sizeof ctx);
1795 ctx.not_allocated = 1;
1796 ctx.kr_handle = keydb_new ();
1798 return gpg_error_from_syserror ();
1801 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1802 : KEYDB_SEARCH_MODE_FPR20;
1803 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1804 rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
1806 pk_from_block (pk, kb, found_key);
1807 if (!rc && r_keyblock)
1812 release_kbnode (kb);
1813 getkey_end (ctrl, &ctx);
1816 rc = GPG_ERR_GENERAL; /* Oops */
1821 /* This function is similar to get_pubkey_byfprint, but it doesn't
1822 * merge the self-signed data into the public key and subkeys or into
1823 * the user ids. It also doesn't add the key to the user id cache.
1824 * Further, this function ignores PK->REQ_USAGE.
1826 * This function is intended to avoid recursion and, as such, should
1827 * only be used in very specific situations.
1829 * Like get_pubkey_byfprint, PK may be NULL. In that case, this
1830 * function effectively just checks for the existence of the key. */
1832 get_pubkey_byfprint_fast (PKT_public_key * pk,
1833 const byte * fprint, size_t fprint_len)
1838 err = get_keyblock_byfprint_fast (&keyblock, NULL, fprint, fprint_len, 0);
1842 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1843 release_kbnode (keyblock);
1850 /* This function is similar to get_pubkey_byfprint_fast but returns a
1851 * keydb handle at R_HD and the keyblock at R_KEYBLOCK. R_KEYBLOCK or
1852 * R_HD may be NULL. If LOCK is set the handle has been opend in
1853 * locked mode and keydb_disable_caching () has been called. On error
1854 * R_KEYBLOCK is set to NULL but R_HD must be released by the caller;
1855 * it may have a value of NULL, though. This allows to do an insert
1856 * operation on a locked keydb handle. */
1858 get_keyblock_byfprint_fast (kbnode_t *r_keyblock, KEYDB_HANDLE *r_hd,
1859 const byte *fprint, size_t fprint_len, int lock)
1864 byte fprbuf[MAX_FINGERPRINT_LEN];
1872 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1873 fprbuf[i] = fprint[i];
1874 while (i < MAX_FINGERPRINT_LEN)
1879 return gpg_error_from_syserror ();
1883 err = keydb_lock (hd);
1886 /* If locking did not work, we better don't return a handle
1887 * at all - there was a reason that locking has been
1892 keydb_disable_caching (hd);
1895 /* Fo all other errors we return the handle. */
1899 err = keydb_search_fpr (hd, fprbuf);
1900 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1904 return gpg_error (GPG_ERR_NO_PUBKEY);
1906 err = keydb_get_keyblock (hd, &keyblock);
1909 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (err));
1912 return gpg_error (GPG_ERR_NO_PUBKEY);
1915 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1916 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1918 /* Not caching key here since it won't have all of the fields
1922 *r_keyblock = keyblock;
1924 release_kbnode (keyblock);
1934 parse_def_secret_key (ctrl_t ctrl)
1936 KEYDB_HANDLE hd = NULL;
1940 for (t = opt.def_secret_key; t; t = t->next)
1943 KEYDB_SEARCH_DESC desc;
1947 err = classify_user_id (t->d, &desc, 1);
1950 log_error (_("secret key \"%s\" not found: %s\n"),
1951 t->d, gpg_strerror (err));
1953 log_info (_("(check argument of option '%s')\n"), "--default-key");
1964 keydb_search_reset (hd);
1967 err = keydb_search (hd, &desc, 1, NULL);
1968 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1973 log_error (_("key \"%s\" not found: %s\n"), t->d, gpg_strerror (err));
1978 err = keydb_get_keyblock (hd, &kb);
1981 log_error (_("error reading keyblock: %s\n"),
1982 gpg_strerror (err));
1986 merge_selfsigs (ctrl, kb);
1988 err = gpg_error (GPG_ERR_NO_SECKEY);
1992 PKT_public_key *pk = node->pkt->pkt.public_key;
1994 /* Check that the key has the signing capability. */
1995 if (! (pk->pubkey_usage & PUBKEY_USAGE_SIG))
1998 /* Check if the key is valid. */
1999 if (pk->flags.revoked)
2002 log_debug ("not using %s as default key, %s",
2003 keystr_from_pk (pk), "revoked");
2006 if (pk->has_expired)
2009 log_debug ("not using %s as default key, %s",
2010 keystr_from_pk (pk), "expired");
2013 if (pk_is_disabled (pk))
2016 log_debug ("not using %s as default key, %s",
2017 keystr_from_pk (pk), "disabled");
2021 err = agent_probe_secret_key (ctrl, pk);
2023 /* This is a valid key. */
2026 while ((node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY)));
2028 release_kbnode (kb);
2031 if (! warned && ! opt.quiet)
2033 log_info (_("Warning: not using '%s' as default key: %s\n"),
2034 t->d, gpg_strerror (GPG_ERR_NO_SECKEY));
2035 print_reported_error (err, GPG_ERR_NO_SECKEY);
2040 if (! warned && ! opt.quiet)
2041 log_info (_("using \"%s\" as default secret key for signing\n"),
2047 if (! warned && opt.def_secret_key && ! t)
2048 log_info (_("all values passed to '%s' ignored\n"),
2062 /* Look up a secret key.
2064 * If PK is not NULL, the public key of the first result is returned
2065 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2066 * set, it is used to filter the search results. See the
2067 * documentation for finish_lookup to understand exactly how this is
2068 * used. Note: The self-signed data has already been merged into the
2069 * public key using merge_selfsigs. Free *PK by calling
2070 * release_public_key_parts (or, if PK was allocated using xfree, you
2071 * can use free_public_key, which calls release_public_key_parts(PK)
2072 * and then xfree(PK)).
2074 * If --default-key was set, then the specified key is looked up. (In
2075 * this case, the default key is returned even if it is considered
2076 * unusable. See the documentation for skip_unusable for exactly what
2079 * Otherwise, this initiates a DB scan that returns all keys that are
2080 * usable (see previous paragraph for exactly what usable means) and
2081 * for which a secret key is available.
2083 * This function returns the first match. Additional results can be
2084 * returned using getkey_next. */
2086 get_seckey_default (ctrl_t ctrl, PKT_public_key *pk)
2089 strlist_t namelist = NULL;
2090 int include_unusable = 1;
2093 const char *def_secret_key = parse_def_secret_key (ctrl);
2095 add_to_strlist (&namelist, def_secret_key);
2097 include_unusable = 0;
2099 err = key_byname (ctrl, NULL, namelist, pk, 1, include_unusable, NULL, NULL);
2101 free_strlist (namelist);
2108 /* Search for keys matching some criteria.
2110 * If RETCTX is not NULL, then the constructed context is returned in
2111 * *RETCTX so that getpubkey_next can be used to get subsequent
2112 * results. In this case, getkey_end() must be used to free the
2113 * search context. If RETCTX is not NULL, then RET_KDBHD must be
2116 * If PK is not NULL, the public key of the first result is returned
2117 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2118 * set, it is used to filter the search results. See the
2119 * documentation for finish_lookup to understand exactly how this is
2120 * used. Note: The self-signed data has already been merged into the
2121 * public key using merge_selfsigs. Free *PK by calling
2122 * release_public_key_parts (or, if PK was allocated using xfree, you
2123 * can use free_public_key, which calls release_public_key_parts(PK)
2124 * and then xfree(PK)).
2126 * If NAMES is not NULL, then a search query is constructed using
2127 * classify_user_id on each of the strings in the list. (Recall: the
2128 * database does an OR of the terms, not an AND.) If NAMES is
2129 * NULL, then all results are returned.
2131 * If WANT_SECRET is set, then only keys with an available secret key
2132 * (either locally or via key registered on a smartcard) are returned.
2134 * This function does not skip unusable keys (see the documentation
2135 * for skip_unusable for an exact definition).
2137 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2138 * *RET_KEYBLOCK. This should be freed using release_kbnode().
2140 * This function returns 0 on success. Otherwise, an error code is
2141 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2142 * (if want_secret is set) is returned if the key is not found. */
2144 getkey_bynames (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2145 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
2147 return key_byname (ctrl, retctx, names, pk, want_secret, 1,
2148 ret_keyblock, NULL);
2152 /* Search for one key matching some criteria.
2154 * If RETCTX is not NULL, then the constructed context is returned in
2155 * *RETCTX so that getpubkey_next can be used to get subsequent
2156 * results. In this case, getkey_end() must be used to free the
2157 * search context. If RETCTX is not NULL, then RET_KDBHD must be
2160 * If PK is not NULL, the public key of the first result is returned
2161 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2162 * set, it is used to filter the search results. See the
2163 * documentation for finish_lookup to understand exactly how this is
2164 * used. Note: The self-signed data has already been merged into the
2165 * public key using merge_selfsigs. Free *PK by calling
2166 * release_public_key_parts (or, if PK was allocated using xfree, you
2167 * can use free_public_key, which calls release_public_key_parts(PK)
2168 * and then xfree(PK)).
2170 * If NAME is not NULL, then a search query is constructed using
2171 * classify_user_id on the string. In this case, even unusable keys
2172 * (see the documentation for skip_unusable for an exact definition of
2173 * unusable) are returned. Otherwise, if --default-key was set, then
2174 * that key is returned (even if it is unusable). If neither of these
2175 * conditions holds, then the first usable key is returned.
2177 * If WANT_SECRET is set, then only keys with an available secret key
2178 * (either locally or via key registered on a smartcard) are returned.
2180 * This function does not skip unusable keys (see the documentation
2181 * for skip_unusable for an exact definition).
2183 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2184 * *RET_KEYBLOCK. This should be freed using release_kbnode().
2186 * This function returns 0 on success. Otherwise, an error code is
2187 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2188 * (if want_secret is set) is returned if the key is not found.
2190 * FIXME: We also have the get_pubkey_byname function which has a
2191 * different semantic. Should be merged with this one. */
2193 getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2194 const char *name, int want_secret, kbnode_t *ret_keyblock)
2197 strlist_t namelist = NULL;
2198 int with_unusable = 1;
2199 const char *def_secret_key = NULL;
2201 if (want_secret && !name)
2202 def_secret_key = parse_def_secret_key (ctrl);
2204 if (want_secret && !name && def_secret_key)
2205 add_to_strlist (&namelist, def_secret_key);
2207 add_to_strlist (&namelist, name);
2211 err = key_byname (ctrl, retctx, namelist, pk, want_secret, with_unusable,
2212 ret_keyblock, NULL);
2214 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
2215 WANT_SECRET has been used. */
2217 free_strlist (namelist);
2223 /* Return the next search result.
2225 * If PK is not NULL, the public key of the next result is returned in
2226 * *PK. Note: The self-signed data has already been merged into the
2227 * public key using merge_selfsigs. Free *PK by calling
2228 * release_public_key_parts (or, if PK was allocated using xmalloc, you
2229 * can use free_public_key, which calls release_public_key_parts(PK)
2230 * and then xfree(PK)).
2232 * RET_KEYBLOCK can be given as NULL; if it is not NULL it the entire
2233 * found keyblock is returned which must be released with
2234 * release_kbnode. If the function returns an error NULL is stored at
2237 * The self-signed data has already been merged into the public key
2238 * using merge_selfsigs. */
2240 getkey_next (ctrl_t ctrl, getkey_ctx_t ctx,
2241 PKT_public_key *pk, kbnode_t *ret_keyblock)
2243 int rc; /* Fixme: Make sure this is proper gpg_error */
2244 KBNODE keyblock = NULL;
2245 KBNODE found_key = NULL;
2247 /* We need to disable the caching so that for an exact key search we
2248 won't get the result back from the cache and thus end up in an
2249 endless loop. The endless loop can occur, because the cache is
2250 used without respecting the current file pointer! */
2251 keydb_disable_caching (ctx->kr_handle);
2253 /* FOUND_KEY is only valid as long as RET_KEYBLOCK is. If the
2254 * caller wants PK, but not RET_KEYBLOCK, we need hand in our own
2256 if (pk && ret_keyblock == NULL)
2257 ret_keyblock = &keyblock;
2259 rc = lookup (ctrl, ctx, ctx->want_secret,
2260 ret_keyblock, pk ? &found_key : NULL);
2263 log_assert (found_key);
2264 pk_from_block (pk, NULL, found_key);
2265 release_kbnode (keyblock);
2272 /* Release any resources used by a key listing context. This must be
2273 * called on the context returned by, e.g., getkey_byname. */
2275 getkey_end (ctrl_t ctrl, getkey_ctx_t ctx)
2279 #ifdef HAVE_W32_SYSTEM
2281 /* FIXME: This creates a big regression for Windows because the
2282 * keyring is only released after the global ctrl is released.
2283 * So if an operation does a getkey and then tries to modify the
2284 * keyring it will fail on Windows with a sharing violation. We
2285 * need to modify all keyring write operations to also take the
2286 * ctrl and close the cached_getkey_kdb handle to make writing
2287 * work. See: GnuPG-bug-id: 3097 */
2289 keydb_release (ctx->kr_handle);
2291 #else /*!HAVE_W32_SYSTEM*/
2293 if (ctrl && !ctrl->cached_getkey_kdb)
2294 ctrl->cached_getkey_kdb = ctx->kr_handle;
2296 keydb_release (ctx->kr_handle);
2298 #endif /*!HAVE_W32_SYSTEM*/
2300 free_strlist (ctx->extra_list);
2301 if (!ctx->not_allocated)
2308 /************************************************
2309 ************* Merging stuff ********************
2310 ************************************************/
2312 /* Set the mainkey_id fields for all keys in KEYBLOCK. This is
2313 * usually done by merge_selfsigs but at some places we only need the
2314 * main_kid not a full merge. The function also guarantees that all
2315 * pk->keyids are computed. */
2317 setup_main_keyids (kbnode_t keyblock)
2319 u32 kid[2], mainkid[2];
2320 kbnode_t kbctx, node;
2323 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2325 pk = keyblock->pkt->pkt.public_key;
2327 keyid_from_pk (pk, mainkid);
2328 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
2330 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
2331 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
2333 pk = node->pkt->pkt.public_key;
2334 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
2335 if (!pk->main_keyid[0] && !pk->main_keyid[1])
2337 pk->main_keyid[0] = mainkid[0];
2338 pk->main_keyid[1] = mainkid[1];
2344 /* KEYBLOCK corresponds to a public key block. This function merges
2345 * much of the information from the self-signed data into the public
2346 * key, public subkey and user id data structures. If you use the
2347 * high-level search API (e.g., get_pubkey) for looking up key blocks,
2348 * then you don't need to call this function. This function is
2349 * useful, however, if you change the keyblock, e.g., by adding or
2350 * removing a self-signed data packet. */
2352 merge_keys_and_selfsig (ctrl_t ctrl, kbnode_t keyblock)
2356 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
2357 merge_selfsigs (ctrl, keyblock);
2359 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
2364 parse_key_usage (PKT_signature * sig)
2371 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
2374 /* First octet of the keyflags. */
2379 key_usage |= PUBKEY_USAGE_CERT;
2385 key_usage |= PUBKEY_USAGE_SIG;
2389 /* We do not distinguish between encrypting communications and
2390 encrypting storage. */
2391 if (flags & (0x04 | 0x08))
2393 key_usage |= PUBKEY_USAGE_ENC;
2394 flags &= ~(0x04 | 0x08);
2399 key_usage |= PUBKEY_USAGE_AUTH;
2404 key_usage |= PUBKEY_USAGE_UNKNOWN;
2407 key_usage |= PUBKEY_USAGE_NONE;
2409 else if (p) /* Key flags of length zero. */
2410 key_usage |= PUBKEY_USAGE_NONE;
2412 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
2413 capability that we do not handle. This serves to distinguish
2414 between a zero key usage which we handle as the default
2415 capabilities for that algorithm, and a usage that we do not
2416 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
2417 key_flags have been given but they do not specify any usage. */
2423 /* Apply information from SIGNODE (which is the valid self-signature
2424 * associated with that UID) to the UIDNODE:
2425 * - weather the UID has been revoked
2426 * - assumed creation date of the UID
2427 * - temporary store the keyflags here
2428 * - temporary store the key expiration time here
2429 * - mark whether the primary user ID flag hat been set.
2430 * - store the preferences
2433 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
2435 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
2436 PKT_signature *sig = signode->pkt->pkt.signature;
2437 const byte *p, *sym, *hash, *zip;
2438 size_t n, nsym, nhash, nzip;
2440 sig->flags.chosen_selfsig = 1;/* We chose this one. */
2441 uid->created = 0; /* Not created == invalid. */
2442 if (IS_UID_REV (sig))
2444 uid->flags.revoked = 1;
2445 return; /* Has been revoked. */
2448 uid->flags.revoked = 0;
2450 uid->expiredate = sig->expiredate;
2452 if (sig->flags.expired)
2454 uid->flags.expired = 1;
2455 return; /* Has expired. */
2458 uid->flags.expired = 0;
2460 uid->created = sig->timestamp; /* This one is okay. */
2461 uid->selfsigversion = sig->version;
2462 /* If we got this far, it's not expired :) */
2463 uid->flags.expired = 0;
2465 /* Store the key flags in the helper variable for later processing. */
2466 uid->help_key_usage = parse_key_usage (sig);
2468 /* Ditto for the key expiration. */
2469 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2470 if (p && buf32_to_u32 (p))
2471 uid->help_key_expire = keycreated + buf32_to_u32 (p);
2473 uid->help_key_expire = 0;
2475 /* Set the primary user ID flag - we will later wipe out some
2476 * of them to only have one in our keyblock. */
2477 uid->flags.primary = 0;
2478 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
2480 uid->flags.primary = 2;
2482 /* We could also query this from the unhashed area if it is not in
2483 * the hased area and then later try to decide which is the better
2484 * there should be no security problem with this.
2485 * For now we only look at the hashed one. */
2487 /* Now build the preferences list. These must come from the
2488 hashed section so nobody can modify the ciphers a key is
2489 willing to accept. */
2490 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
2493 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
2496 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
2501 n = nsym + nhash + nzip;
2506 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
2508 for (; nsym; nsym--, n++)
2510 uid->prefs[n].type = PREFTYPE_SYM;
2511 uid->prefs[n].value = *sym++;
2513 for (; nhash; nhash--, n++)
2515 uid->prefs[n].type = PREFTYPE_HASH;
2516 uid->prefs[n].value = *hash++;
2518 for (; nzip; nzip--, n++)
2520 uid->prefs[n].type = PREFTYPE_ZIP;
2521 uid->prefs[n].value = *zip++;
2523 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
2524 uid->prefs[n].value = 0;
2527 /* See whether we have the MDC feature. */
2529 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
2530 if (p && n && (p[0] & 0x01))
2533 /* And the keyserver modify flag. */
2534 uid->flags.ks_modify = 1;
2535 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
2536 if (p && n && (p[0] & 0x80))
2537 uid->flags.ks_modify = 0;
2541 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
2543 rinfo->date = sig->timestamp;
2544 rinfo->algo = sig->pubkey_algo;
2545 rinfo->keyid[0] = sig->keyid[0];
2546 rinfo->keyid[1] = sig->keyid[1];
2550 /* Given a keyblock, parse the key block and extract various pieces of
2551 * information and save them with the primary key packet and the user
2552 * id packets. For instance, some information is stored in signature
2553 * packets. We find the latest such valid packet (since the user can
2554 * change that information) and copy its contents into the
2557 * Note that R_REVOKED may be set to 0, 1 or 2.
2559 * This function fills in the following fields in the primary key's
2562 * main_keyid (computed)
2563 * revkey / numrevkeys (derived from self signed key data)
2564 * flags.valid (whether we have at least 1 self-sig)
2565 * flags.maybe_revoked (whether a designed revoked the key, but
2566 * we are missing the key to check the sig)
2567 * selfsigversion (highest version of any valid self-sig)
2568 * pubkey_usage (derived from most recent self-sig or most
2570 * has_expired (various sources)
2571 * expiredate (various sources)
2573 * See the documentation for fixup_uidnode for how the user id packets
2574 * are modified. In addition to that the primary user id's is_primary
2575 * field is set to 1 and the other user id's is_primary are set to 0.
2578 merge_selfsigs_main (ctrl_t ctrl, kbnode_t keyblock, int *r_revoked,
2579 struct revoke_info *rinfo)
2581 PKT_public_key *pk = NULL;
2584 u32 sigdate, uiddate, uiddate2;
2585 KBNODE signode, uidnode, uidnode2;
2586 u32 curtime = make_timestamp ();
2587 unsigned int key_usage = 0;
2588 u32 keytimestamp = 0;
2590 int key_expire_seen = 0;
2591 byte sigversion = 0;
2594 memset (rinfo, 0, sizeof (*rinfo));
2596 /* Section 11.1 of RFC 4880 determines the order of packets within a
2597 * message. There are three sections, which must occur in the
2598 * following order: the public key, the user ids and user attributes
2599 * and the subkeys. Within each section, each primary packet (e.g.,
2600 * a user id packet) is followed by one or more signature packets,
2601 * which modify that packet. */
2603 /* According to Section 11.1 of RFC 4880, the public key must be the
2604 first packet. Note that parse_keyblock_image ensures that the
2605 first packet is the public key. */
2606 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2608 pk = keyblock->pkt->pkt.public_key;
2609 keytimestamp = pk->timestamp;
2611 keyid_from_pk (pk, kid);
2612 pk->main_keyid[0] = kid[0];
2613 pk->main_keyid[1] = kid[1];
2615 if (pk->version < 4)
2617 /* Before v4 the key packet itself contains the expiration date
2618 * and there was no way to change it, so we start with the one
2619 * from the key packet. */
2620 key_expire = pk->max_expiredate;
2621 key_expire_seen = 1;
2626 * - Find the latest direct key self-signature. We assume that the
2627 * newest one overrides all others.
2629 * - Determine whether the key has been revoked.
2631 * - Gather all revocation keys (unlike other data, we don't just
2632 * take them from the latest self-signed packet).
2634 * - Determine max (sig[...]->version).
2637 /* Reset this in case this key was already merged. */
2643 sigdate = 0; /* Helper variable to find the latest signature. */
2645 /* According to Section 11.1 of RFC 4880, the public key comes first
2646 * and is immediately followed by any signature packets that modify
2649 k && k->pkt->pkttype != PKT_USER_ID
2650 && k->pkt->pkttype != PKT_ATTRIBUTE
2651 && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2654 if (k->pkt->pkttype == PKT_SIGNATURE)
2656 PKT_signature *sig = k->pkt->pkt.signature;
2657 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2660 if (check_key_signature (ctrl, keyblock, k, NULL))
2661 ; /* Signature did not verify. */
2662 else if (IS_KEY_REV (sig))
2664 /* Key has been revoked - there is no way to
2665 * override such a revocation, so we theoretically
2666 * can stop now. We should not cope with expiration
2667 * times for revocations here because we have to
2668 * assume that an attacker can generate all kinds of
2669 * signatures. However due to the fact that the key
2670 * has been revoked it does not harm either and by
2671 * continuing we gather some more info on that
2674 sig_to_revoke_info (sig, rinfo);
2676 else if (IS_KEY_SIG (sig))
2678 /* Add the indicated revocations keys from all
2679 * signatures not just the latest. We do this
2680 * because you need multiple 1F sigs to properly
2681 * handle revocation keys (PGP does it this way, and
2682 * a revocation key could be sensitive and hence in
2683 * a different signature). */
2689 xrealloc (pk->revkey, sizeof (struct revocation_key) *
2690 (pk->numrevkeys + sig->numrevkeys));
2692 for (i = 0; i < sig->numrevkeys; i++)
2693 memcpy (&pk->revkey[pk->numrevkeys++],
2695 sizeof (struct revocation_key));
2698 if (sig->timestamp >= sigdate)
2699 { /* This is the latest signature so far. */
2701 if (sig->flags.expired)
2702 ; /* Signature has expired - ignore it. */
2705 sigdate = sig->timestamp;
2707 if (sig->version > sigversion)
2708 sigversion = sig->version;
2717 /* Remove dupes from the revocation keys. */
2720 int i, j, x, changed = 0;
2722 for (i = 0; i < pk->numrevkeys; i++)
2724 for (j = i + 1; j < pk->numrevkeys; j++)
2726 if (memcmp (&pk->revkey[i], &pk->revkey[j],
2727 sizeof (struct revocation_key)) == 0)
2731 for (x = j; x < pk->numrevkeys - 1; x++)
2732 pk->revkey[x] = pk->revkey[x + 1];
2742 pk->revkey = xrealloc (pk->revkey,
2744 sizeof (struct revocation_key));
2747 /* SIGNODE is the 1F signature packet with the latest creation time.
2748 * Extract some information from it. */
2751 /* Some information from a direct key signature take precedence
2752 * over the same information given in UID sigs. */
2753 PKT_signature *sig = signode->pkt->pkt.signature;
2756 key_usage = parse_key_usage (sig);
2758 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2759 if (p && buf32_to_u32 (p))
2761 key_expire = keytimestamp + buf32_to_u32 (p);
2762 key_expire_seen = 1;
2765 /* Mark that key as valid: One direct key signature should
2766 * render a key as valid. */
2767 pk->flags.valid = 1;
2770 /* Pass 1.5: Look for key revocation signatures that were not made
2771 * by the key (i.e. did a revocation key issue a revocation for
2772 * us?). Only bother to do this if there is a revocation key in the
2773 * first place and we're not revoked already. */
2775 if (!*r_revoked && pk->revkey)
2776 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
2778 if (k->pkt->pkttype == PKT_SIGNATURE)
2780 PKT_signature *sig = k->pkt->pkt.signature;
2782 if (IS_KEY_REV (sig) &&
2783 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
2785 int rc = check_revocation_keys (ctrl, pk, sig);
2789 sig_to_revoke_info (sig, rinfo);
2790 /* Don't continue checking since we can't be any
2791 * more revoked than this. */
2794 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2795 pk->flags.maybe_revoked = 1;
2797 /* A failure here means the sig did not verify, was
2798 * not issued by a revocation key, or a revocation
2799 * key loop was broken. If a revocation key isn't
2800 * findable, however, the key might be revoked and
2801 * we don't know it. */
2803 /* Fixme: In the future handle subkey and cert
2804 * revocations? PGP doesn't, but it's in 2440. */
2809 /* Second pass: Look at the self-signature of all user IDs. */
2811 /* According to RFC 4880 section 11.1, user id and attribute packets
2812 * are in the second section, after the public key packet and before
2813 * the subkey packets. */
2814 signode = uidnode = NULL;
2815 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
2816 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2818 if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
2819 { /* New user id packet. */
2821 /* Apply the data from the most recent self-signed packet to
2822 * the preceding user id packet. */
2823 if (uidnode && signode)
2825 fixup_uidnode (uidnode, signode, keytimestamp);
2826 pk->flags.valid = 1;
2829 /* Clear SIGNODE. The only relevant self-signed data for
2830 * UIDNODE follows it. */
2831 if (k->pkt->pkttype == PKT_USER_ID)
2839 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2841 PKT_signature *sig = k->pkt->pkt.signature;
2842 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2844 if (check_key_signature (ctrl, keyblock, k, NULL))
2845 ; /* signature did not verify */
2846 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
2847 && sig->timestamp >= sigdate)
2849 /* Note: we allow invalidation of cert revocations
2850 * by a newer signature. An attacker can't use this
2851 * because a key should be revoked with a key revocation.
2852 * The reason why we have to allow for that is that at
2853 * one time an email address may become invalid but later
2854 * the same email address may become valid again (hired,
2855 * fired, hired again). */
2857 sigdate = sig->timestamp;
2859 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2860 if (sig->version > sigversion)
2861 sigversion = sig->version;
2866 if (uidnode && signode)
2868 fixup_uidnode (uidnode, signode, keytimestamp);
2869 pk->flags.valid = 1;
2872 /* If the key isn't valid yet, and we have
2873 * --allow-non-selfsigned-uid set, then force it valid. */
2874 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
2877 log_info (_("Invalid key %s made valid by"
2878 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
2879 pk->flags.valid = 1;
2882 /* The key STILL isn't valid, so try and find an ultimately
2883 * trusted signature. */
2884 if (!pk->flags.valid)
2888 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2891 if (k->pkt->pkttype == PKT_USER_ID)
2893 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2895 PKT_signature *sig = k->pkt->pkt.signature;
2897 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
2899 PKT_public_key *ultimate_pk;
2901 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
2903 /* We don't want to use the full get_pubkey to avoid
2904 * infinite recursion in certain cases. There is no
2905 * reason to check that an ultimately trusted key is
2906 * still valid - if it has been revoked the user
2907 * should also remove the ultimate trust flag. */
2908 if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
2909 && check_key_signature2 (ctrl,
2910 keyblock, k, ultimate_pk,
2911 NULL, NULL, NULL, NULL) == 0
2912 && get_ownertrust (ctrl, ultimate_pk) == TRUST_ULTIMATE)
2914 free_public_key (ultimate_pk);
2915 pk->flags.valid = 1;
2919 free_public_key (ultimate_pk);
2925 /* Record the highest selfsig version so we know if this is a v3 key
2926 * through and through, or a v3 key with a v4 selfsig somewhere.
2927 * This is useful in a few places to know if the key must be treated
2928 * as PGP2-style or OpenPGP-style. Note that a selfsig revocation
2929 * with a higher version number will also raise this value. This is
2930 * okay since such a revocation must be issued by the user (i.e. it
2931 * cannot be issued by someone else to modify the key behavior.) */
2933 pk->selfsigversion = sigversion;
2935 /* Now that we had a look at all user IDs we can now get some
2936 * information from those user IDs. */
2940 /* Find the latest user ID with key flags set. */
2941 uiddate = 0; /* Helper to find the latest user ID. */
2942 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2945 if (k->pkt->pkttype == PKT_USER_ID)
2947 PKT_user_id *uid = k->pkt->pkt.user_id;
2949 if (uid->help_key_usage && uid->created > uiddate)
2951 key_usage = uid->help_key_usage;
2952 uiddate = uid->created;
2960 /* No key flags at all: get it from the algo. */
2961 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
2965 /* Check that the usage matches the usage as given by the algo. */
2966 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
2967 if (x) /* Mask it down to the actual allowed usage. */
2971 /* Whatever happens, it's a primary key, so it can certify. */
2972 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
2974 if (!key_expire_seen)
2976 /* Find the latest valid user ID with a key expiration set
2977 * Note, that this may be a different one from the above because
2978 * some user IDs may have no expiration date set. */
2980 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2983 if (k->pkt->pkttype == PKT_USER_ID)
2985 PKT_user_id *uid = k->pkt->pkt.user_id;
2986 if (uid->help_key_expire && uid->created > uiddate)
2988 key_expire = uid->help_key_expire;
2989 uiddate = uid->created;
2995 /* Currently only v3 keys have a maximum expiration date, but I'll
2996 * bet v5 keys get this feature again. */
2998 || (pk->max_expiredate && key_expire > pk->max_expiredate))
2999 key_expire = pk->max_expiredate;
3001 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
3002 pk->expiredate = key_expire;
3004 /* Fixme: we should see how to get rid of the expiretime fields but
3005 * this needs changes at other places too. */
3007 /* And now find the real primary user ID and delete all others. */
3008 uiddate = uiddate2 = 0;
3009 uidnode = uidnode2 = NULL;
3010 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3012 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
3014 PKT_user_id *uid = k->pkt->pkt.user_id;
3015 if (uid->flags.primary)
3017 if (uid->created > uiddate)
3019 uiddate = uid->created;
3022 else if (uid->created == uiddate && uidnode)
3024 /* The dates are equal, so we need to do a different
3025 * (and arbitrary) comparison. This should rarely,
3026 * if ever, happen. It's good to try and guarantee
3027 * that two different GnuPG users with two different
3028 * keyrings at least pick the same primary. */
3029 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
3035 if (uid->created > uiddate2)
3037 uiddate2 = uid->created;
3040 else if (uid->created == uiddate2 && uidnode2)
3042 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
3050 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3053 if (k->pkt->pkttype == PKT_USER_ID &&
3054 !k->pkt->pkt.user_id->attrib_data)
3056 PKT_user_id *uid = k->pkt->pkt.user_id;
3058 uid->flags.primary = 0;
3064 /* None is flagged primary - use the latest user ID we have,
3065 * and disambiguate with the arbitrary packet comparison. */
3066 uidnode2->pkt->pkt.user_id->flags.primary = 1;
3070 /* None of our uids were self-signed, so pick the one that
3071 * sorts first to be the primary. This is the best we can do
3072 * here since there are no self sigs to date the uids. */
3076 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3079 if (k->pkt->pkttype == PKT_USER_ID
3080 && !k->pkt->pkt.user_id->attrib_data)
3085 uidnode->pkt->pkt.user_id->flags.primary = 1;
3090 if (cmp_user_ids (k->pkt->pkt.user_id,
3091 uidnode->pkt->pkt.user_id) > 0)
3093 uidnode->pkt->pkt.user_id->flags.primary = 0;
3095 uidnode->pkt->pkt.user_id->flags.primary = 1;
3099 /* just to be safe: */
3100 k->pkt->pkt.user_id->flags.primary = 0;
3109 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
3110 * Caller must free the signature when they are done. */
3111 static PKT_signature *
3112 buf_to_sig (const byte * buf, size_t len)
3114 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
3115 IOBUF iobuf = iobuf_temp_with_content (buf, len);
3116 int save_mode = set_packet_list_mode (0);
3118 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
3124 set_packet_list_mode (save_mode);
3125 iobuf_close (iobuf);
3131 /* Use the self-signed data to fill in various fields in subkeys.
3133 * KEYBLOCK is the whole keyblock. SUBNODE is the subkey to fill in.
3135 * Sets the following fields on the subkey:
3138 * flags.valid if the subkey has a valid self-sig binding
3145 * On this subkey's most revent valid self-signed packet, the
3146 * following field is set:
3148 * flags.chosen_selfsig
3151 merge_selfsigs_subkey (ctrl_t ctrl, kbnode_t keyblock, kbnode_t subnode)
3153 PKT_public_key *mainpk = NULL, *subpk = NULL;
3159 u32 curtime = make_timestamp ();
3160 unsigned int key_usage = 0;
3161 u32 keytimestamp = 0;
3165 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3167 mainpk = keyblock->pkt->pkt.public_key;
3168 if (mainpk->version < 4)
3169 return;/* (actually this should never happen) */
3170 keyid_from_pk (mainpk, mainkid);
3171 subpk = subnode->pkt->pkt.public_key;
3172 keytimestamp = subpk->timestamp;
3174 subpk->flags.valid = 0;
3175 subpk->flags.exact = 0;
3176 subpk->main_keyid[0] = mainpk->main_keyid[0];
3177 subpk->main_keyid[1] = mainpk->main_keyid[1];
3179 /* Find the latest key binding self-signature. */
3181 sigdate = 0; /* Helper to find the latest signature. */
3182 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3185 if (k->pkt->pkttype == PKT_SIGNATURE)
3187 sig = k->pkt->pkt.signature;
3188 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
3190 if (check_key_signature (ctrl, keyblock, k, NULL))
3191 ; /* Signature did not verify. */
3192 else if (IS_SUBKEY_REV (sig))
3194 /* Note that this means that the date on a
3195 * revocation sig does not matter - even if the
3196 * binding sig is dated after the revocation sig,
3197 * the subkey is still marked as revoked. This
3198 * seems ok, as it is just as easy to make new
3199 * subkeys rather than re-sign old ones as the
3200 * problem is in the distribution. Plus, PGP (7)
3201 * does this the same way. */
3202 subpk->flags.revoked = 1;
3203 sig_to_revoke_info (sig, &subpk->revoked);
3204 /* Although we could stop now, we continue to
3205 * figure out other information like the old expiration
3208 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
3210 if (sig->flags.expired)
3211 ; /* Signature has expired - ignore it. */
3214 sigdate = sig->timestamp;
3216 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
3223 /* No valid key binding. */
3227 sig = signode->pkt->pkt.signature;
3228 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
3230 key_usage = parse_key_usage (sig);
3233 /* No key flags at all: get it from the algo. */
3234 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
3238 /* Check that the usage matches the usage as given by the algo. */
3239 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
3240 if (x) /* Mask it down to the actual allowed usage. */
3244 subpk->pubkey_usage = key_usage;
3246 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
3247 if (p && buf32_to_u32 (p))
3248 key_expire = keytimestamp + buf32_to_u32 (p);
3252 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
3253 subpk->expiredate = key_expire;
3255 /* Algo doesn't exist. */
3256 if (openpgp_pk_test_algo (subpk->pubkey_algo))
3259 subpk->flags.valid = 1;
3261 /* Find the most recent 0x19 embedded signature on our self-sig. */
3262 if (!subpk->flags.backsig)
3266 PKT_signature *backsig = NULL;
3270 /* We do this while() since there may be other embedded
3271 * signatures in the future. We only want 0x19 here. */
3273 while ((p = enum_sig_subpkt (sig->hashed,
3274 SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
3276 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
3278 PKT_signature *tempsig = buf_to_sig (p, n);
3281 if (tempsig->timestamp > sigdate)
3284 free_seckey_enc (backsig);
3287 sigdate = backsig->timestamp;
3290 free_seckey_enc (tempsig);
3296 /* It is safe to have this in the unhashed area since the 0x19
3297 * is located on the selfsig for convenience, not security. */
3299 while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
3302 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
3304 PKT_signature *tempsig = buf_to_sig (p, n);
3307 if (tempsig->timestamp > sigdate)
3310 free_seckey_enc (backsig);
3313 sigdate = backsig->timestamp;
3316 free_seckey_enc (tempsig);
3322 /* At this point, backsig contains the most recent 0x19 sig.
3323 * Let's see if it is good. */
3325 /* 2==valid, 1==invalid, 0==didn't check */
3326 if (check_backsig (mainpk, subpk, backsig) == 0)
3327 subpk->flags.backsig = 2;
3329 subpk->flags.backsig = 1;
3331 free_seckey_enc (backsig);
3337 /* Merge information from the self-signatures with the public key,
3338 * subkeys and user ids to make using them more easy.
3340 * See documentation for merge_selfsigs_main, merge_selfsigs_subkey
3341 * and fixup_uidnode for exactly which fields are updated. */
3343 merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock)
3347 struct revoke_info rinfo;
3348 PKT_public_key *main_pk;
3350 unsigned int mdc_feature;
3352 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
3354 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
3356 log_error ("expected public key but found secret key "
3358 /* We better exit here because a public key is expected at
3359 * other places too. FIXME: Figure this out earlier and
3360 * don't get to here at all */
3366 merge_selfsigs_main (ctrl, keyblock, &revoked, &rinfo);
3368 /* Now merge in the data from each of the subkeys. */
3369 for (k = keyblock; k; k = k->next)
3371 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3373 merge_selfsigs_subkey (ctrl, keyblock, k);
3377 main_pk = keyblock->pkt->pkt.public_key;
3378 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
3380 /* If the primary key is revoked, expired, or invalid we
3381 * better set the appropriate flags on that key and all
3383 for (k = keyblock; k; k = k->next)
3385 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3386 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3388 PKT_public_key *pk = k->pkt->pkt.public_key;
3389 if (!main_pk->flags.valid)
3390 pk->flags.valid = 0;
3391 if (revoked && !pk->flags.revoked)
3393 pk->flags.revoked = revoked;
3394 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
3396 if (main_pk->has_expired)
3397 pk->has_expired = main_pk->has_expired;
3403 /* Set the preference list of all keys to those of the primary real
3404 * user ID. Note: we use these preferences when we don't know by
3405 * which user ID the key has been selected.
3406 * fixme: we should keep atoms of commonly used preferences or
3407 * use reference counting to optimize the preference lists storage.
3408 * FIXME: it might be better to use the intersection of
3410 * Do a similar thing for the MDC feature flag. */
3413 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3415 if (k->pkt->pkttype == PKT_USER_ID
3416 && !k->pkt->pkt.user_id->attrib_data
3417 && k->pkt->pkt.user_id->flags.primary)
3419 prefs = k->pkt->pkt.user_id->prefs;
3420 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
3424 for (k = keyblock; k; k = k->next)
3426 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3427 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3429 PKT_public_key *pk = k->pkt->pkt.public_key;
3432 pk->prefs = copy_prefs (prefs);
3433 pk->flags.mdc = mdc_feature;
3440 /* See whether the key satisfies any additional requirements specified
3441 * in CTX. If so, return the node of an appropriate key or subkey.
3442 * Otherwise, return NULL if there was no appropriate key.
3444 * Note that we do not return a reference, i.e. the result must not be
3445 * freed using 'release_kbnode'.
3447 * In case the primary key is not required, select a suitable subkey.
3448 * We need the primary key if PUBKEY_USAGE_CERT is set in REQ_USAGE or
3449 * we are in PGP6 or PGP7 mode and PUBKEY_USAGE_SIG is set in
3452 * If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
3453 * are set in REQ_USAGE, we filter by the key's function. Concretely,
3454 * if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then we only
3455 * return a key if it is (at least) either a signing or a
3456 * certification key.
3458 * If REQ_USAGE is set, then we reject any keys that are not good
3459 * (i.e., valid, not revoked, not expired, etc.). This allows the
3460 * getkey functions to be used for plain key listings.
3462 * Sets the matched key's user id field (pk->user_id) to the user id
3463 * that matched the low-level search criteria or NULL.
3465 * If R_FLAGS is not NULL set certain flags for more detailed error
3466 * reporting. Used flags are:
3468 * - LOOKUP_ALL_SUBKEYS_EXPIRED :: All Subkeys are expired or have
3470 * - LOOKUP_NOT_SELECTED :: No suitable key found
3472 * This function needs to handle several different cases:
3474 * 1. No requested usage and no primary key requested
3475 * Examples for this case are that we have a keyID to be used
3476 * for decrytion or verification.
3477 * 2. No usage but primary key requested
3478 * This is the case for all functions which work on an
3479 * entire keyblock, e.g. for editing or listing
3480 * 3. Usage and primary key requested
3482 * 4. Usage but no primary key requested
3487 finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact,
3488 unsigned int *r_flags)
3492 /* If WANT_EXACT is set, the key or subkey that actually matched the
3493 low-level search criteria. */
3494 kbnode_t foundk = NULL;
3495 /* The user id (if any) that matched the low-level search criteria. */
3496 PKT_user_id *foundu = NULL;
3499 kbnode_t latest_key;
3502 u32 curtime = make_timestamp ();
3507 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
3508 req_usage &= USAGE_MASK;
3510 /* Request the primary if we're certifying another key, and also if
3511 * signing data while --pgp6 or --pgp7 is on since pgp 6 and 7 do
3512 * not understand signatures made by a signing subkey. PGP 8 does. */
3513 req_prim = ((req_usage & PUBKEY_USAGE_CERT)
3514 || ((PGP6 || PGP7) && (req_usage & PUBKEY_USAGE_SIG)));
3517 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
3519 /* For an exact match mark the primary or subkey that matched the
3520 low-level search criteria. */
3523 for (k = keyblock; k; k = k->next)
3527 log_assert (k->pkt->pkttype == PKT_PUBLIC_KEY
3528 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3530 pk = k->pkt->pkt.public_key;
3531 pk->flags.exact = 1;
3537 /* Get the user id that matched that low-level search criteria. */
3538 for (k = keyblock; k; k = k->next)
3542 log_assert (k->pkt->pkttype == PKT_USER_ID);
3543 foundu = k->pkt->pkt.user_id;
3549 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
3550 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
3551 foundk ? "one" : "all", req_usage);
3555 latest_key = foundk ? foundk : keyblock;
3561 /* Set LATEST_KEY to the latest (the one with the most recent
3562 * timestamp) good (valid, not revoked, not expired, etc.) subkey.
3564 * Don't bother if we are only looking for a primary key or we need
3565 * an exact match and the exact match is not a subkey. */
3566 if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
3572 int n_revoked_or_expired = 0;
3574 /* Either start a loop or check just this one subkey. */
3575 for (k = foundk ? foundk : keyblock; k; k = nextk)
3579 /* If FOUNDK is not NULL, then only consider that exact
3580 key, i.e., don't iterate. */
3586 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3589 pk = k->pkt->pkt.public_key;
3591 log_debug ("\tchecking subkey %08lX\n",
3592 (ulong) keyid_from_pk (pk, NULL));
3594 if (!pk->flags.valid)
3597 log_debug ("\tsubkey not valid\n");
3600 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3603 log_debug ("\tusage does not match: want=%x have=%x\n",
3604 req_usage, pk->pubkey_usage);
3609 if (pk->flags.revoked)
3612 log_debug ("\tsubkey has been revoked\n");
3613 n_revoked_or_expired++;
3616 if (pk->has_expired)
3619 log_debug ("\tsubkey has expired\n");
3620 n_revoked_or_expired++;
3623 if (pk->timestamp > curtime && !opt.ignore_valid_from)
3626 log_debug ("\tsubkey not yet valid\n");
3631 log_debug ("\tsubkey might be fine\n");
3632 /* In case a key has a timestamp of 0 set, we make sure
3633 that it is used. A better change would be to compare
3634 ">=" but that might also change the selected keys and
3635 is as such a more intrusive change. */
3636 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
3638 latest_date = pk->timestamp;
3642 if (n_subkeys == n_revoked_or_expired && r_flags)
3643 *r_flags |= LOOKUP_ALL_SUBKEYS_EXPIRED;
3646 /* Check if the primary key is ok (valid, not revoke, not expire,
3647 * matches requested usage) if:
3649 * - we didn't find an appropriate subkey and we're not doing an
3652 * - we're doing an exact match and the exact match was the
3655 * - we're just considering the primary key. */
3656 if ((!latest_key && !want_exact) || foundk == keyblock || req_prim)
3658 if (DBG_LOOKUP && !foundk && !req_prim)
3659 log_debug ("\tno suitable subkeys found - trying primary\n");
3660 pk = keyblock->pkt->pkt.public_key;
3661 if (!pk->flags.valid)
3664 log_debug ("\tprimary key not valid\n");
3666 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3669 log_debug ("\tprimary key usage does not match: "
3670 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
3672 else if (pk->flags.revoked)
3675 log_debug ("\tprimary key has been revoked\n");
3677 else if (pk->has_expired)
3680 log_debug ("\tprimary key has expired\n");
3685 log_debug ("\tprimary key may be used\n");
3686 latest_key = keyblock;
3693 log_debug ("\tno suitable key found - giving up\n");
3695 *r_flags |= LOOKUP_NOT_SELECTED;
3696 return NULL; /* Not found. */
3701 log_debug ("\tusing key %08lX\n",
3702 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
3706 pk = latest_key->pkt->pkt.public_key;
3707 free_user_id (pk->user_id);
3708 pk->user_id = scopy_user_id (foundu);
3711 if (latest_key != keyblock && opt.verbose)
3714 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
3715 log_info (_("using subkey %s instead of primary key %s\n"),
3716 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
3720 cache_user_id (keyblock);
3722 return latest_key ? latest_key : keyblock; /* Found. */
3726 /* Print a KEY_CONSIDERED status line. */
3728 print_status_key_considered (kbnode_t keyblock, unsigned int flags)
3730 char hexfpr[2*MAX_FINGERPRINT_LEN + 1];
3734 if (!is_status_enabled ())
3737 for (node=keyblock; node; node = node->next)
3738 if (node->pkt->pkttype == PKT_PUBLIC_KEY
3739 || node->pkt->pkttype == PKT_SECRET_KEY)
3743 log_error ("%s: keyblock w/o primary key\n", __func__);
3747 hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr);
3748 snprintf (flagbuf, sizeof flagbuf, " %u", flags);
3749 write_status_strings (STATUS_KEY_CONSIDERED, hexfpr, flagbuf, NULL);
3754 /* A high-level function to lookup keys.
3756 * This function builds on top of the low-level keydb API. It first
3757 * searches the database using the description stored in CTX->ITEMS,
3758 * then it filters the results using CTX and, finally, if WANT_SECRET
3759 * is set, it ignores any keys for which no secret key is available.
3761 * Unlike the low-level search functions, this function also merges
3762 * all of the self-signed data into the keys, subkeys and user id
3763 * packets (see the merge_selfsigs for details).
3765 * On success the key's keyblock is stored at *RET_KEYBLOCK, and the
3766 * specific subkey is stored at *RET_FOUND_KEY. Note that we do not
3767 * return a reference in *RET_FOUND_KEY, i.e. the result must not be
3768 * freed using 'release_kbnode', and it is only valid until
3769 * *RET_KEYBLOCK is deallocated. Therefore, if RET_FOUND_KEY is not
3770 * NULL, then RET_KEYBLOCK must not be NULL. */
3772 lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret,
3773 kbnode_t *ret_keyblock, kbnode_t *ret_found_key)
3776 int no_suitable_key = 0;
3777 KBNODE keyblock = NULL;
3778 KBNODE found_key = NULL;
3779 unsigned int infoflags;
3781 log_assert (ret_found_key == NULL || ret_keyblock != NULL);
3783 *ret_keyblock = NULL;
3787 rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
3791 /* If we are iterating over the entire database, then we need to
3792 * change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
3793 * reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next record. */
3794 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
3795 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
3797 rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
3800 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
3806 rc = agent_probe_any_secret_key (NULL, keyblock);
3807 if (gpg_err_code(rc) == GPG_ERR_NO_SECKEY)
3808 goto skip; /* No secret key available. */
3810 goto found; /* Unexpected error. */
3813 /* Warning: node flag bits 0 and 1 should be preserved by
3814 * merge_selfsigs. */
3815 merge_selfsigs (ctrl, keyblock);
3816 found_key = finish_lookup (keyblock, ctx->req_usage, ctx->exact,
3818 print_status_key_considered (keyblock, infoflags);
3821 no_suitable_key = 0;
3826 no_suitable_key = 1;
3830 /* Release resources and continue search. */
3831 release_kbnode (keyblock);
3833 /* The keyblock cache ignores the current "file position".
3834 * Thus, if we request the next result and the cache matches
3835 * (and it will since it is what we just looked for), we'll get
3836 * the same entry back! We can avoid this infinite loop by
3837 * disabling the cache. */
3838 keydb_disable_caching (ctx->kr_handle);
3842 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
3843 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
3849 *ret_keyblock = keyblock; /* Return the keyblock. */
3853 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
3854 rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
3855 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
3856 rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
3858 release_kbnode (keyblock);
3863 *ret_found_key = found_key;
3865 *ret_found_key = NULL;
3872 /* Enumerate some secret keys (specifically, those specified with
3873 * --default-key and --try-secret-key). Use the following procedure:
3875 * 1) Initialize a void pointer to NULL
3876 * 2) Pass a reference to this pointer to this function (content)
3877 * and provide space for the secret key (sk)
3878 * 3) Call this function as long as it does not return an error (or
3879 * until you are done). The error code GPG_ERR_EOF indicates the
3880 * end of the listing.
3881 * 4) Call this function a last time with SK set to NULL,
3882 * so that can free it's context.
3887 * PKT_public_key *sk = xmalloc_clear (sizeof (*sk));
3889 * while ((err = enum_secret_keys (&ctx, sk)))
3893 * free_public_key (sk);
3894 * sk = xmalloc_clear (sizeof (*sk));
3897 * // Release any resources used by CTX.
3898 * enum_secret_keys (&ctx, NULL);
3899 * free_public_key (sk);
3901 * if (gpg_err_code (err) != GPG_ERR_EOF)
3902 * ; // An error occurred.
3905 enum_secret_keys (ctrl_t ctrl, void **context, PKT_public_key *sk)
3907 gpg_error_t err = 0;
3922 /* Make a new context. */
3923 c = xtrycalloc (1, sizeof *c);
3925 return gpg_error_from_syserror ();
3931 /* Free the context. */
3932 release_kbnode (c->keyblock);
3933 getkey_end (ctrl, c->ctx);
3940 return gpg_error (GPG_ERR_EOF);
3944 /* Loop until we have a keyblock. */
3945 while (!c->keyblock)
3947 /* Loop over the list of secret keys. */
3954 case 0: /* First try to use the --default-key. */
3955 name = parse_def_secret_key (ctrl);
3959 case 1: /* Init list of keys to try. */
3960 c->sl = opt.secret_keys_to_try;
3964 case 2: /* Get next item from list. */
3968 c->sl = c->sl->next;
3974 case 3: /* Init search context to enum all secret keys. */
3975 err = getkey_bynames (ctrl, &c->ctx, NULL, NULL, 1,
3979 release_kbnode (keyblock);
3981 getkey_end (ctrl, c->ctx);
3987 case 4: /* Get next item from the context. */
3990 err = getkey_next (ctrl, c->ctx, NULL, &keyblock);
3993 release_kbnode (keyblock);
3995 getkey_end (ctrl, c->ctx);
4003 default: /* No more names to check - stop. */
4005 return gpg_error (GPG_ERR_EOF);
4008 while ((!name || !*name) && !keyblock);
4011 c->node = c->keyblock = keyblock;
4014 err = getkey_byname (ctrl, NULL, NULL, name, 1, &c->keyblock);
4017 /* getkey_byname might return a keyblock even in the
4018 error case - I have not checked. Thus better release
4020 release_kbnode (c->keyblock);
4024 c->node = c->keyblock;
4028 /* Get the next key from the current keyblock. */
4029 for (; c->node; c->node = c->node->next)
4031 if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
4032 || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4034 copy_public_key (sk, c->node->pkt->pkt.public_key);
4035 c->node = c->node->next;
4036 return 0; /* Found. */
4040 /* Dispose the keyblock and continue. */
4041 release_kbnode (c->keyblock);
4047 get_seckey_default_or_card (ctrl_t ctrl, PKT_public_key *pk,
4048 const byte *fpr_card, size_t fpr_len)
4051 strlist_t namelist = NULL;
4053 const char *def_secret_key = parse_def_secret_key (ctrl);
4056 add_to_strlist (&namelist, def_secret_key);
4058 return get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len);
4061 || (def_secret_key && def_secret_key[strlen (def_secret_key)-1] == '!'))
4062 err = key_byname (ctrl, NULL, namelist, pk, 1, 0, NULL, NULL);
4064 { /* Default key is specified and card key is also available. */
4065 kbnode_t k, keyblock = NULL;
4067 err = key_byname (ctrl, NULL, namelist, pk, 1, 0, &keyblock, NULL);
4069 for (k = keyblock; k; k = k->next)
4071 PKT_public_key *pk_candidate;
4072 char fpr[MAX_FINGERPRINT_LEN];
4074 if (k->pkt->pkttype != PKT_PUBLIC_KEY
4075 &&k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
4078 pk_candidate = k->pkt->pkt.public_key;
4079 if (!pk_candidate->flags.valid)
4081 if (!((pk_candidate->pubkey_usage & USAGE_MASK) & pk->req_usage))
4083 fingerprint_from_pk (pk_candidate, fpr, NULL);
4084 if (!memcmp (fpr_card, fpr, fpr_len))
4086 release_public_key_parts (pk);
4087 copy_public_key (pk, pk_candidate);
4091 release_kbnode (keyblock);
4094 free_strlist (namelist);
4099 /*********************************************
4100 *********** User ID printing helpers *******
4101 *********************************************/
4103 /* Return a string with a printable representation of the user_id.
4104 * this string must be freed by xfree. */
4106 get_user_id_string (ctrl_t ctrl, u32 * keyid, int mode, size_t *r_len)
4113 /* Try it two times; second pass reads from the database. */
4116 for (r = user_id_db; r; r = r->next)
4118 for (a = r->keyids; a; a = a->next)
4120 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
4124 /* An empty string as user id is possible. Make
4125 sure that the malloc allocates one byte and
4126 does not bail out. */
4127 p = xmalloc (r->len? r->len : 1);
4128 memcpy (p, r->name, r->len);
4135 p = xasprintf ("%08lX%08lX %.*s",
4136 (ulong) keyid[0], (ulong) keyid[1],
4139 p = xasprintf ("%s %.*s", keystr (keyid),
4142 *r_len = strlen (p);
4150 while (++pass < 2 && !get_pubkey (ctrl, NULL, keyid));
4153 p = xstrdup (user_id_not_found_utf8 ());
4155 p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
4157 p = xasprintf ("%s [?]", keystr (keyid));
4160 *r_len = strlen (p);
4166 get_user_id_string_native (ctrl_t ctrl, u32 * keyid)
4168 char *p = get_user_id_string (ctrl, keyid, 0, NULL);
4169 char *p2 = utf8_to_native (p, strlen (p), 0);
4176 get_long_user_id_string (ctrl_t ctrl, u32 * keyid)
4178 return get_user_id_string (ctrl, keyid, 1, NULL);
4182 /* Please try to use get_user_byfpr instead of this one. */
4184 get_user_id (ctrl_t ctrl, u32 *keyid, size_t *rn)
4186 return get_user_id_string (ctrl, keyid, 2, rn);
4190 /* Please try to use get_user_id_byfpr_native instead of this one. */
4192 get_user_id_native (ctrl_t ctrl, u32 *keyid)
4195 char *p = get_user_id (ctrl, keyid, &rn);
4196 char *p2 = utf8_to_native (p, rn, 0);
4202 /* Return the user id for a key designated by its fingerprint, FPR,
4203 which must be MAX_FINGERPRINT_LEN bytes in size. Note: the
4204 returned string, which must be freed using xfree, may not be NUL
4205 terminated. To determine the length of the string, you must use
4208 get_user_id_byfpr (ctrl_t ctrl, const byte *fpr, size_t *rn)
4214 /* Try it two times; second pass reads from the database. */
4217 for (r = user_id_db; r; r = r->next)
4220 for (a = r->keyids; a; a = a->next)
4222 if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
4224 /* An empty string as user id is possible. Make
4225 sure that the malloc allocates one byte and does
4227 p = xmalloc (r->len? r->len : 1);
4228 memcpy (p, r->name, r->len);
4236 && !get_pubkey_byfprint (ctrl, NULL, NULL, fpr, MAX_FINGERPRINT_LEN));
4237 p = xstrdup (user_id_not_found_utf8 ());
4242 /* Like get_user_id_byfpr, but convert the string to the native
4243 encoding. The returned string needs to be freed. Unlike
4244 get_user_id_byfpr, the returned string is NUL terminated. */
4246 get_user_id_byfpr_native (ctrl_t ctrl, const byte *fpr)
4249 char *p = get_user_id_byfpr (ctrl, fpr, &rn);
4250 char *p2 = utf8_to_native (p, rn, 0);
4256 /* Return the database handle used by this context. The context still
4259 get_ctx_handle (GETKEY_CTX ctx)
4261 return ctx->kr_handle;
4265 free_akl (struct akl *akl)
4271 free_keyserver_spec (akl->spec);
4279 while (opt.auto_key_locate)
4281 struct akl *akl2 = opt.auto_key_locate;
4282 opt.auto_key_locate = opt.auto_key_locate->next;
4287 /* Returns false on error. */
4289 parse_auto_key_locate (const char *options_arg)
4292 char *options, *options_buf;
4294 options = options_buf = xstrdup (options_arg);
4295 while ((tok = optsep (&options)))
4297 struct akl *akl, *check, *last = NULL;
4303 akl = xmalloc_clear (sizeof (*akl));
4305 if (ascii_strcasecmp (tok, "clear") == 0)
4308 free_akl (opt.auto_key_locate);
4309 opt.auto_key_locate = NULL;
4312 else if (ascii_strcasecmp (tok, "nodefault") == 0)
4313 akl->type = AKL_NODEFAULT;
4314 else if (ascii_strcasecmp (tok, "local") == 0)
4315 akl->type = AKL_LOCAL;
4316 else if (ascii_strcasecmp (tok, "ldap") == 0)
4317 akl->type = AKL_LDAP;
4318 else if (ascii_strcasecmp (tok, "keyserver") == 0)
4319 akl->type = AKL_KEYSERVER;
4320 else if (ascii_strcasecmp (tok, "cert") == 0)
4321 akl->type = AKL_CERT;
4322 else if (ascii_strcasecmp (tok, "pka") == 0)
4323 akl->type = AKL_PKA;
4324 else if (ascii_strcasecmp (tok, "dane") == 0)
4325 akl->type = AKL_DANE;
4326 else if (ascii_strcasecmp (tok, "wkd") == 0)
4327 akl->type = AKL_WKD;
4328 else if ((akl->spec = parse_keyserver_uri (tok, 1)))
4329 akl->type = AKL_SPEC;
4333 xfree (options_buf);
4337 /* We must maintain the order the user gave us */
4338 for (check = opt.auto_key_locate; check;
4339 last = check, check = check->next)
4341 /* Check for duplicates */
4342 if (check->type == akl->type
4343 && (akl->type != AKL_SPEC
4344 || (akl->type == AKL_SPEC
4345 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
4358 opt.auto_key_locate = akl;
4362 xfree (options_buf);
4368 /* The list of key origins. */
4372 } key_origin_list[] =
4374 { "self", KEYORG_SELF },
4375 { "file", KEYORG_FILE },
4376 { "url", KEYORG_URL },
4377 { "wkd", KEYORG_WKD },
4378 { "dane", KEYORG_DANE },
4379 { "ks-pref", KEYORG_KS_PREF },
4380 { "ks", KEYORG_KS },
4381 { "unknown", KEYORG_UNKNOWN }
4384 /* Parse the argument for --key-origin. Return false on error. */
4386 parse_key_origin (char *string)
4391 comma = strchr (string, ',');
4395 if (!ascii_strcasecmp (string, "help"))
4397 log_info (_("valid values for option '%s':\n"), "--key-origin");
4398 for (i=0; i < DIM (key_origin_list); i++)
4399 log_info (" %s\n", key_origin_list[i].name);
4403 for (i=0; i < DIM (key_origin_list); i++)
4404 if (!ascii_strcasecmp (string, key_origin_list[i].name))
4406 opt.key_origin = key_origin_list[i].origin;
4407 xfree (opt.key_origin_url);
4408 opt.key_origin_url = NULL;
4409 if (comma && comma[1])
4411 opt.key_origin_url = xstrdup (comma+1);
4412 trim_spaces (opt.key_origin_url);
4423 /* Return a string or "?" for the key ORIGIN. */
4425 key_origin_string (int origin)
4429 for (i=0; i < DIM (key_origin_list); i++)
4430 if (key_origin_list[i].origin == origin)
4431 return key_origin_list[i].name;
4437 /* Returns true if a secret key is available for the public key with
4438 key id KEYID; returns false if not. This function ignores legacy
4439 keys. Note: this is just a fast check and does not tell us whether
4440 the secret key is valid; this check merely indicates whether there
4441 is some secret key with the specified key id. */
4443 have_secret_key_with_kid (u32 *keyid)
4447 KEYDB_SEARCH_DESC desc;
4452 kdbhd = keydb_new ();
4455 memset (&desc, 0, sizeof desc);
4456 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
4457 desc.u.kid[0] = keyid[0];
4458 desc.u.kid[1] = keyid[1];
4461 err = keydb_search (kdbhd, &desc, 1, NULL);
4465 err = keydb_get_keyblock (kdbhd, &keyblock);
4468 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
4472 for (node = keyblock; node; node = node->next)
4474 /* Bit 0 of the flags is set if the search found the key
4475 using that key or subkey. Note: a search will only ever
4476 match a single key or subkey. */
4477 if ((node->flag & 1))
4479 log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY
4480 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
4482 if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
4483 result = 1; /* Secret key available. */
4490 release_kbnode (keyblock);
4493 keydb_release (kdbhd);