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/>.
37 #include "keyserver-internal.h"
38 #include "call-agent.h"
40 #include "mbox-util.h"
43 #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
44 #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
46 #if MAX_PK_CACHE_ENTRIES < 2
47 #error We need the cache for key creation
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 (kbnode_t keyblock);
143 static int lookup (getkey_ctx_t ctx,
144 kbnode_t *ret_keyblock, kbnode_t *ret_found_key,
146 static kbnode_t finish_lookup (kbnode_t keyblock,
147 unsigned int req_usage, int want_exact,
148 unsigned int *r_flags);
149 static void print_status_key_considered (kbnode_t keyblock, unsigned int flags);
157 for (i = 0; i < DIM (lkup_stats); i++)
159 if (lkup_stats[i].any)
160 es_fprintf (es_stderr,
161 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
163 lkup_stats[i].okay_count,
164 lkup_stats[i].nokey_count, lkup_stats[i].error_count);
170 /* Cache a copy of a public key in the public key cache. PK is not
171 * cached if caching is disabled (via getkey_disable_caches), if
172 * PK->FLAGS.DONT_CACHE is set, we don't know how to derive a key id
173 * from the public key (e.g., unsupported algorithm), or a key with
174 * the key id is already in the cache.
176 * The public key packet is copied into the cache using
177 * copy_public_key. Thus, any secret parts are not copied, for
180 * This cache is filled by get_pubkey and is read by get_pubkey and
181 * get_pubkey_fast. */
183 cache_public_key (PKT_public_key * pk)
185 #if MAX_PK_CACHE_ENTRIES
186 pk_cache_entry_t ce, ce2;
189 if (pk_cache_disabled)
192 if (pk->flags.dont_cache)
195 if (is_ELGAMAL (pk->pubkey_algo)
196 || pk->pubkey_algo == PUBKEY_ALGO_DSA
197 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
198 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
199 || pk->pubkey_algo == PUBKEY_ALGO_ECDH
200 || is_RSA (pk->pubkey_algo))
202 keyid_from_pk (pk, keyid);
205 return; /* Don't know how to get the keyid. */
207 for (ce = pk_cache; ce; ce = ce->next)
208 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
211 log_debug ("cache_public_key: already in cache\n");
215 if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
219 /* Remove the last 50% of the entries. */
220 for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
222 if (ce && ce != pk_cache && ce->next)
230 free_public_key (ce->pk);
235 log_assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
238 ce = xmalloc (sizeof *ce);
241 ce->pk = copy_public_key (NULL, pk);
242 ce->keyid[0] = keyid[0];
243 ce->keyid[1] = keyid[1];
248 /* Return a const utf-8 string with the text "[User ID not found]".
249 This function is required so that we don't need to switch gettext's
250 encoding temporary. */
252 user_id_not_found_utf8 (void)
257 text = native_to_utf8 (_("[User ID not found]"));
263 /* Return the user ID from the given keyblock.
264 * We use the primary uid flag which has been set by the merge_selfsigs
265 * function. The returned value is only valid as long as the given
266 * keyblock is not changed. */
268 get_primary_uid (KBNODE keyblock, size_t * uidlen)
273 for (k = keyblock; k; k = k->next)
275 if (k->pkt->pkttype == PKT_USER_ID
276 && !k->pkt->pkt.user_id->attrib_data
277 && k->pkt->pkt.user_id->is_primary)
279 *uidlen = k->pkt->pkt.user_id->len;
280 return k->pkt->pkt.user_id->name;
283 s = user_id_not_found_utf8 ();
284 *uidlen = strlen (s);
290 release_keyid_list (keyid_list_t k)
294 keyid_list_t k2 = k->next;
301 * Store the association of keyid and userid
302 * Feed only public keys to this function.
305 cache_user_id (KBNODE keyblock)
310 keyid_list_t keyids = NULL;
313 for (k = keyblock; k; k = k->next)
315 if (k->pkt->pkttype == PKT_PUBLIC_KEY
316 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
318 keyid_list_t a = xmalloc_clear (sizeof *a);
319 /* Hmmm: For a long list of keyids it might be an advantage
320 * to append the keys. */
321 fingerprint_from_pk (k->pkt->pkt.public_key, a->fpr, NULL);
322 keyid_from_pk (k->pkt->pkt.public_key, a->keyid);
323 /* First check for duplicates. */
324 for (r = user_id_db; r; r = r->next)
328 for (b = r->keyids; b; b = b->next)
330 if (!memcmp (b->fpr, a->fpr, MAX_FINGERPRINT_LEN))
333 log_debug ("cache_user_id: already in cache\n");
334 release_keyid_list (keyids);
340 /* Now put it into the cache. */
346 BUG (); /* No key no fun. */
349 uid = get_primary_uid (keyblock, &uidlen);
351 if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES)
353 /* fixme: use another algorithm to free some cache slots */
355 user_id_db = r->next;
356 release_keyid_list (r->keyids);
360 r = xmalloc (sizeof *r + uidlen - 1);
363 memcpy (r->name, uid, r->len);
364 r->next = user_id_db;
370 /* Disable and drop the public key cache (which is filled by
371 cache_public_key and get_pubkey). Note: there is currently no way
372 to reenable this cache. */
374 getkey_disable_caches ()
376 #if MAX_PK_CACHE_ENTRIES
378 pk_cache_entry_t ce, ce2;
380 for (ce = pk_cache; ce; ce = ce2)
383 free_public_key (ce->pk);
386 pk_cache_disabled = 1;
387 pk_cache_entries = 0;
391 /* fixme: disable user id cache ? */
396 pubkey_free (pubkey_t key)
401 release_kbnode (key->keyblock);
407 pubkeys_free (pubkey_t keys)
411 pubkey_t next = keys->next;
417 /* Returns all keys that match the search specfication SEARCH_TERMS.
419 This function also checks for and warns about duplicate entries in
420 the keydb, which can occur if the user has configured multiple
421 keyrings or keyboxes or if a keyring or keybox was corrupted.
423 Note: SEARCH_TERMS will not be expanded (i.e., it may not be a
426 USE is the operation for which the key is required. It must be
427 either PUBKEY_USAGE_ENC, PUBKEY_USAGE_SIG, PUBKEY_USAGE_CERT or
430 XXX: Currently, only PUBKEY_USAGE_ENC and PUBKEY_USAGE_SIG are
433 INCLUDE_UNUSABLE indicates whether disabled keys are allowed.
434 (Recipients specified with --encrypt-to and --hidden-encrypt-to may
435 be disabled. It is possible to edit disabled keys.)
437 SOURCE is the context in which SEARCH_TERMS was specified, e.g.,
438 "--encrypt-to", etc. If this function is called interactively,
439 then this should be NULL.
441 If WARN_POSSIBLY_AMBIGUOUS is set, then emits a warning if the user
442 does not specify a long key id or a fingerprint.
444 The results are placed in *KEYS. *KEYS must be NULL! */
446 get_pubkeys (ctrl_t ctrl,
447 char *search_terms, int use, int include_unusable, char *source,
448 int warn_possibly_ambiguous,
451 /* We show a warning when a key appears multiple times in the DB.
452 This can happen for two reasons:
454 - The user has configured multiple keyrings or keyboxes.
456 - The keyring or keybox has been corrupted in some way, e.g., a
457 bug or a random process changing them.
459 For each duplicate, we only want to show the key once. Hence,
461 static strlist_t key_dups;
463 /* USE transformed to a string. */
468 KEYDB_SEARCH_DESC desc;
471 pubkey_t results = NULL;
476 char fingerprint[2 * MAX_FINGERPRINT_LEN + 1];
481 log_debug ("%s: Checking %s=%s\n",
482 __func__, source ? source : "user input", search_terms);
486 log_bug ("%s: KEYS should be NULL!\n", __func__);
490 case PUBKEY_USAGE_ENC: use_str = "encrypt"; break;
491 case PUBKEY_USAGE_SIG: use_str = "sign"; break;
492 case PUBKEY_USAGE_CERT: use_str = "cetify"; break;
493 case PUBKEY_USAGE_AUTH: use_str = "authentication"; break;
494 default: log_bug ("%s: Bad value for USE (%d)\n", __func__, use);
497 if (use == PUBKEY_USAGE_CERT || use == PUBKEY_USAGE_AUTH)
498 log_bug ("%s: use=%s is unimplemented.\n", __func__, use_str);
500 err = classify_user_id (search_terms, &desc, 1);
503 log_info (_("key \"%s\" not found: %s\n"),
504 search_terms, gpg_strerror (err));
505 if (!opt.quiet && source)
506 log_info (_("(check argument of option '%s')\n"), source);
510 if (warn_possibly_ambiguous
511 && ! (desc.mode == KEYDB_SEARCH_MODE_LONG_KID
512 || desc.mode == KEYDB_SEARCH_MODE_FPR16
513 || desc.mode == KEYDB_SEARCH_MODE_FPR20
514 || desc.mode == KEYDB_SEARCH_MODE_FPR))
516 log_info (_("Warning: '%s' should be a long key ID or a fingerprint\n"),
518 if (!opt.quiet && source)
519 log_info (_("(check argument of option '%s')\n"), source);
522 /* Gather all of the results. */
527 PKT_public_key *pk = xmalloc_clear (sizeof *pk);
532 err = get_pubkey_byname (ctrl, &ctx, pk, search_terms, &kb, NULL,
533 include_unusable, 1);
535 err = getkey_next (ctx, pk, &kb);
537 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
538 /* No more results. */
544 /* An error (other than "not found"). */
546 log_error (_("error looking up: %s\n"),
552 /* Another result! */
555 r = xmalloc_clear (sizeof (*r));
566 log_debug ("%s resulted in %d matches.\n", search_terms, count);
567 for (r = results; r; r = r->next)
569 hexfingerprint (r->keyblock->pkt->pkt.public_key,
570 fingerprint, sizeof (fingerprint)));
573 if (! results && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
577 log_debug ("%s: '%s' not found.\n", __func__, search_terms);
579 log_info (_("key \"%s\" not found\n"), search_terms);
580 if (!opt.quiet && source)
581 log_info (_("(check argument of option '%s')\n"), source);
585 else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
586 /* No more matches. */
589 /* Some other error. An error message was already printed
590 out. Free RESULTS and continue. */
593 /* Check for duplicates. */
595 log_debug ("%s: Checking results of %s='%s' for dups\n",
596 __func__, source ? source : "user input", search_terms);
598 for (r = results; r; r = r->next)
609 if (cmp_public_keys (r->keyblock->pkt->pkt.public_key,
610 r2->keyblock->pkt->pkt.public_key) != 0)
621 /* Remove R2 from the list. */
623 release_kbnode (r2->keyblock);
630 hexfingerprint (r->keyblock->pkt->pkt.public_key,
631 fingerprint, sizeof fingerprint);
632 if (! strlist_find (key_dups, fingerprint))
634 char fingerprint_formatted[MAX_FORMATTED_FINGERPRINT_LEN + 1];
636 log_info (_("Warning: %s appears in the keyring %d times\n"),
637 format_hexfingerprint (fingerprint,
638 fingerprint_formatted,
639 sizeof fingerprint_formatted),
641 add_to_strlist (&key_dups, fingerprint);
646 if (DBG_LOOKUP && count)
648 log_debug ("After removing %d dups:\n", count);
649 for (r = results, count = 0; r; r = r->next)
650 log_debug (" %d: %s\n",
652 hexfingerprint (r->keyblock->pkt->pkt.public_key,
653 fingerprint, sizeof fingerprint));
658 pubkeys_free (results);
667 pk_from_block (PKT_public_key *pk, kbnode_t keyblock, kbnode_t found_key)
669 kbnode_t a = found_key ? found_key : keyblock;
671 log_assert (a->pkt->pkttype == PKT_PUBLIC_KEY
672 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
674 copy_public_key (pk, a->pkt->pkt.public_key);
678 /* Return the public key with the key id KEYID and store it at PK.
679 * The resources in *PK should be released using
680 * release_public_key_parts(). This function also stores a copy of
681 * the public key in the user id cache (see cache_public_key).
683 * If PK is NULL, this function just stores the public key in the
684 * cache and returns the usual return code.
686 * PK->REQ_USAGE (which is a mask of PUBKEY_USAGE_SIG,
687 * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT) is passed through to the
688 * lookup function. If this is non-zero, only keys with the specified
689 * usage will be returned. As such, it is essential that
690 * PK->REQ_USAGE be correctly initialized!
692 * Returns 0 on success, GPG_ERR_NO_PUBKEY if there is no public key
693 * with the specified key id, or another error code if an error
696 * If the data was not read from the cache, then the self-signed data
697 * has definitely been merged into the public key using
700 get_pubkey (PKT_public_key * pk, u32 * keyid)
705 #if MAX_PK_CACHE_ENTRIES
708 /* Try to get it from the cache. We don't do this when pk is
709 NULL as it does not guarantee that the user IDs are
712 for (ce = pk_cache; ce; ce = ce->next)
714 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
715 /* XXX: We don't check PK->REQ_USAGE here, but if we don't
716 read from the cache, we do check it! */
718 copy_public_key (pk, ce->pk);
724 /* More init stuff. */
727 pk = xmalloc_clear (sizeof *pk);
734 struct getkey_ctx_s ctx;
736 KBNODE found_key = NULL;
737 memset (&ctx, 0, sizeof ctx);
738 ctx.exact = 1; /* Use the key ID exactly as given. */
739 ctx.not_allocated = 1;
740 ctx.kr_handle = keydb_new ();
743 rc = gpg_error_from_syserror ();
747 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
748 ctx.items[0].u.kid[0] = keyid[0];
749 ctx.items[0].u.kid[1] = keyid[1];
750 ctx.req_usage = pk->req_usage;
751 rc = lookup (&ctx, &kb, &found_key, 0);
754 pk_from_block (pk, kb, found_key);
762 rc = GPG_ERR_NO_PUBKEY;
766 cache_public_key (pk);
768 free_public_key (pk);
773 /* Similar to get_pubkey, but it does not take PK->REQ_USAGE into
774 * account nor does it merge in the self-signed data. This function
775 * also only considers primary keys. It is intended to be used as a
776 * quick check of the key to avoid recursion. It should only be used
777 * in very certain cases. Like get_pubkey and unlike any of the other
778 * lookup functions, this function also consults the user id cache
779 * (see cache_public_key).
781 * Return the public key in *PK. The resources in *PK should be
782 * released using release_public_key_parts(). */
784 get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
792 #if MAX_PK_CACHE_ENTRIES
794 /* Try to get it from the cache */
797 for (ce = pk_cache; ce; ce = ce->next)
799 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]
800 /* Only consider primary keys. */
801 && ce->pk->keyid[0] == ce->pk->main_keyid[0]
802 && ce->pk->keyid[1] == ce->pk->main_keyid[1])
805 copy_public_key (pk, ce->pk);
814 return gpg_error_from_syserror ();
815 rc = keydb_search_kid (hd, keyid);
816 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
819 return GPG_ERR_NO_PUBKEY;
821 rc = keydb_get_keyblock (hd, &keyblock);
825 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
826 return GPG_ERR_NO_PUBKEY;
829 log_assert (keyblock && keyblock->pkt
830 && keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
832 /* We return the primary key. If KEYID matched a subkey, then we
834 keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
835 if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
836 copy_public_key (pk, keyblock->pkt->pkt.public_key);
838 rc = GPG_ERR_NO_PUBKEY;
840 release_kbnode (keyblock);
842 /* Not caching key here since it won't have all of the fields
849 /* Return the key block for the key with key id KEYID or NULL, if an
850 * error occurs. Use release_kbnode() to release the key block.
852 * The self-signed data has already been merged into the public key
853 * using merge_selfsigs. */
855 get_pubkeyblock (u32 * keyid)
857 struct getkey_ctx_s ctx;
859 KBNODE keyblock = NULL;
861 memset (&ctx, 0, sizeof ctx);
862 /* No need to set exact here because we want the entire block. */
863 ctx.not_allocated = 1;
864 ctx.kr_handle = keydb_new ();
868 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
869 ctx.items[0].u.kid[0] = keyid[0];
870 ctx.items[0].u.kid[1] = keyid[1];
871 rc = lookup (&ctx, &keyblock, NULL, 0);
874 return rc ? NULL : keyblock;
878 /* Return the public key with the key id KEYID iff the secret key is
879 * available and store it at PK. The resources should be released
880 * using release_public_key_parts().
882 * Unlike other lookup functions, PK may not be NULL. PK->REQ_USAGE
883 * is passed through to the lookup function and is a mask of
884 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. Thus, it
885 * must be valid! If this is non-zero, only keys with the specified
886 * usage will be returned.
888 * Returns 0 on success. If a public key with the specified key id is
889 * not found or a secret key is not available for that public key, an
890 * error code is returned. Note: this function ignores legacy keys.
891 * An error code is also return if an error occurs.
893 * The self-signed data has already been merged into the public key
894 * using merge_selfsigs. */
896 get_seckey (PKT_public_key *pk, u32 *keyid)
899 struct getkey_ctx_s ctx;
900 kbnode_t keyblock = NULL;
901 kbnode_t found_key = NULL;
903 memset (&ctx, 0, sizeof ctx);
904 ctx.exact = 1; /* Use the key ID exactly as given. */
905 ctx.not_allocated = 1;
906 ctx.kr_handle = keydb_new ();
908 return gpg_error_from_syserror ();
910 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
911 ctx.items[0].u.kid[0] = keyid[0];
912 ctx.items[0].u.kid[1] = keyid[1];
913 ctx.req_usage = pk->req_usage;
914 err = lookup (&ctx, &keyblock, &found_key, 1);
917 pk_from_block (pk, keyblock, found_key);
920 release_kbnode (keyblock);
924 err = agent_probe_secret_key (/*ctrl*/NULL, pk);
926 release_public_key_parts (pk);
933 /* Skip unusable keys. A key is unusable if it is revoked, expired or
934 disabled or if the selected user id is revoked or expired. */
936 skip_unusable (void *dummy, u32 * keyid, int uid_no)
944 keyblock = get_pubkeyblock (keyid);
947 log_error ("error checking usability status of %s\n", keystr (keyid));
951 pk = keyblock->pkt->pkt.public_key;
953 /* Is the key revoked or expired? */
954 if (pk->flags.revoked || pk->has_expired)
957 /* Is the user ID in question revoked or expired? */
958 if (!unusable && uid_no)
963 for (node = keyblock; node; node = node->next)
965 if (node->pkt->pkttype == PKT_USER_ID)
967 PKT_user_id *user_id = node->pkt->pkt.user_id;
970 if (uids_seen != uid_no)
973 if (user_id->is_revoked || user_id->is_expired)
980 /* If UID_NO is non-zero, then the keyblock better have at least
982 log_assert (uids_seen == uid_no);
986 unusable = pk_is_disabled (pk);
989 release_kbnode (keyblock);
994 /* Search for keys matching some criteria.
996 If RETCTX is not NULL, then the constructed context is returned in
997 *RETCTX so that getpubkey_next can be used to get subsequent
998 results. In this case, getkey_end() must be used to free the
999 search context. If RETCTX is not NULL, then RET_KDBHD must be
1002 If NAMELIST is not NULL, then a search query is constructed using
1003 classify_user_id on each of the strings in the list. (Recall: the
1004 database does an OR of the terms, not an AND.) If NAMELIST is
1005 NULL, then all results are returned.
1007 If PK is not NULL, the public key of the first result is returned
1008 in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
1009 set, it is used to filter the search results. See the
1010 documentation for finish_lookup to understand exactly how this is
1011 used. Note: The self-signed data has already been merged into the
1012 public key using merge_selfsigs. Free *PK by calling
1013 release_public_key_parts (or, if PK was allocated using xfree, you
1014 can use free_public_key, which calls release_public_key_parts(PK)
1015 and then xfree(PK)).
1017 If WANT_SECRET is set, then only keys with an available secret key
1018 (either locally or via key registered on a smartcard) are returned.
1020 If INCLUDE_UNUSABLE is set, then unusable keys (see the
1021 documentation for skip_unusable for an exact definition) are
1022 skipped unless they are looked up by key id or by fingerprint.
1024 If RET_KB is not NULL, the keyblock is returned in *RET_KB. This
1025 should be freed using release_kbnode().
1027 If RET_KDBHD is not NULL, then the new database handle used to
1028 conduct the search is returned in *RET_KDBHD. This can be used to
1029 get subsequent results using keydb_search_next. Note: in this
1030 case, no advanced filtering is done for subsequent results (e.g.,
1031 WANT_SECRET and PK->REQ_USAGE are not respected).
1033 This function returns 0 on success. Otherwise, an error code is
1034 returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1035 (if want_secret is set) is returned if the key is not found. */
1037 key_byname (GETKEY_CTX *retctx, strlist_t namelist,
1039 int want_secret, int include_unusable,
1040 KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
1046 KBNODE help_kb = NULL;
1047 KBNODE found_key = NULL;
1051 /* Reset the returned context in case of error. */
1052 log_assert (!ret_kdbhd); /* Not allowed because the handle is stored
1060 /* No search terms: iterate over the whole DB. */
1062 ctx = xmalloc_clear (sizeof *ctx);
1064 ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
1065 if (!include_unusable)
1066 ctx->items[0].skipfnc = skip_unusable;
1070 /* Build the search context. */
1071 for (n = 0, r = namelist; r; r = r->next)
1074 /* CTX has space for a single search term at the end. Thus, we
1075 need to allocate sizeof *CTX plus (n - 1) sizeof
1077 ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
1080 for (n = 0, r = namelist; r; r = r->next, n++)
1084 err = classify_user_id (r->d, &ctx->items[n], 1);
1086 if (ctx->items[n].exact)
1091 return gpg_err_code (err); /* FIXME: remove gpg_err_code. */
1093 if (!include_unusable
1094 && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
1095 && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
1096 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
1097 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
1098 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
1099 ctx->items[n].skipfnc = skip_unusable;
1103 ctx->want_secret = want_secret;
1104 ctx->kr_handle = keydb_new ();
1105 if (!ctx->kr_handle)
1107 rc = gpg_error_from_syserror ();
1117 ctx->req_usage = pk->req_usage;
1120 rc = lookup (ctx, ret_kb, &found_key, want_secret);
1123 pk_from_block (pk, *ret_kb, found_key);
1126 release_kbnode (help_kb);
1128 if (retctx) /* Caller wants the context. */
1134 *ret_kdbhd = ctx->kr_handle;
1135 ctx->kr_handle = NULL;
1144 /* Find a public key identified by NAME.
1146 * If name appears to be a valid valid RFC822 mailbox (i.e., email
1147 * address) and auto key lookup is enabled (no_akl == 0), then the
1148 * specified auto key lookup methods (--auto-key-lookup) are used to
1149 * import the key into the local keyring. Otherwise, just the local
1150 * keyring is consulted.
1152 * If RETCTX is not NULL, then the constructed context is returned in
1153 * *RETCTX so that getpubkey_next can be used to get subsequent
1154 * results. In this case, getkey_end() must be used to free the
1155 * search context. If RETCTX is not NULL, then RET_KDBHD must be
1158 * If PK is not NULL, the public key of the first result is returned
1159 * in *PK. Note: PK->REQ_USAGE must be valid!!! PK->REQ_USAGE is
1160 * passed through to the lookup function and is a mask of
1161 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this
1162 * is non-zero, only keys with the specified usage will be returned.
1163 * Note: The self-signed data has already been merged into the public
1164 * key using merge_selfsigs. Free *PK by calling
1165 * release_public_key_parts (or, if PK was allocated using xfree, you
1166 * can use free_public_key, which calls release_public_key_parts(PK)
1167 * and then xfree(PK)).
1169 * NAME is a string, which is turned into a search query using
1172 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
1173 * *RET_KEYBLOCK. This should be freed using release_kbnode().
1175 * If RET_KDBHD is not NULL, then the new database handle used to
1176 * conduct the search is returned in *RET_KDBHD. This can be used to
1177 * get subsequent results using keydb_search_next or to modify the
1178 * returned record. Note: in this case, no advanced filtering is done
1179 * for subsequent results (e.g., PK->REQ_USAGE is not respected).
1180 * Unlike RETCTX, this is always returned.
1182 * If INCLUDE_UNUSABLE is set, then unusable keys (see the
1183 * documentation for skip_unusable for an exact definition) are
1184 * skipped unless they are looked up by key id or by fingerprint.
1186 * If NO_AKL is set, then the auto key locate functionality is
1187 * disabled and only the local key ring is considered. Note: the
1188 * local key ring is consulted even if local is not in the
1189 * --auto-key-locate option list!
1191 * This function returns 0 on success. Otherwise, an error code is
1192 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1193 * (if want_secret is set) is returned if the key is not found. */
1195 get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
1196 const char *name, KBNODE * ret_keyblock,
1197 KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
1200 strlist_t namelist = NULL;
1204 int anylocalfirst = 0;
1206 /* If RETCTX is not NULL, then RET_KDBHD must be NULL. */
1207 log_assert (retctx == NULL || ret_kdbhd == NULL);
1212 /* Does NAME appear to be a mailbox (mail address)? */
1213 is_mbox = is_valid_mailbox (name);
1215 /* The auto-key-locate feature works as follows: there are a number
1216 * of methods to look up keys. By default, the local keyring is
1217 * tried first. Then, each method listed in the --auto-key-locate is
1218 * tried in the order it appears.
1220 * This can be changed as follows:
1222 * - if nodefault appears anywhere in the list of options, then
1223 * the local keyring is not tried first, or,
1225 * - if local appears anywhere in the list of options, then the
1226 * local keyring is not tried first, but in the order in which
1227 * it was listed in the --auto-key-locate option.
1229 * Note: we only save the search context in RETCTX if the local
1230 * method is the first method tried (either explicitly or
1234 /* auto-key-locate is enabled. */
1236 /* nodefault is true if "nodefault" or "local" appear. */
1237 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1238 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
1243 /* anylocalfirst is true if "local" appears before any other
1244 search methods (except "nodefault"). */
1245 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1246 if (akl->type != AKL_NODEFAULT)
1248 if (akl->type == AKL_LOCAL)
1256 /* "nodefault" didn't occur. Thus, "local" is implicitly the
1257 * first method to try. */
1261 if (nodefault && is_mbox)
1263 /* Either "nodefault" or "local" (explicitly) appeared in the
1264 * auto key locate list and NAME appears to be an email address.
1265 * Don't try the local keyring. */
1266 rc = GPG_ERR_NO_PUBKEY;
1270 /* Either "nodefault" and "local" don't appear in the auto key
1271 * locate list (in which case we try the local keyring first) or
1272 * NAME does not appear to be an email address (in which case we
1273 * only try the local keyring). In this case, lookup NAME in
1274 * the local keyring. */
1275 add_to_strlist (&namelist, name);
1276 rc = key_byname (retctx, namelist, pk, 0,
1277 include_unusable, ret_keyblock, ret_kdbhd);
1280 /* If the requested name resembles a valid mailbox and automatic
1281 retrieval has been enabled, we try to import the key. */
1282 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && !no_akl && is_mbox)
1284 /* NAME wasn't present in the local keyring (or we didn't try
1285 * the local keyring). Since the auto key locate feature is
1286 * enabled and NAME appears to be an email address, try the auto
1287 * locate feature. */
1288 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1290 unsigned char *fpr = NULL;
1292 int did_akl_local = 0;
1293 int no_fingerprint = 0;
1294 const char *mechanism = "?";
1299 /* This is a dummy mechanism. */
1301 rc = GPG_ERR_NO_PUBKEY;
1305 mechanism = "Local";
1309 getkey_end (*retctx);
1312 add_to_strlist (&namelist, name);
1313 rc = key_byname (anylocalfirst ? retctx : NULL,
1315 include_unusable, ret_keyblock, ret_kdbhd);
1319 mechanism = "DNS CERT";
1320 glo_ctrl.in_auto_key_retrieve++;
1321 rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len);
1322 glo_ctrl.in_auto_key_retrieve--;
1327 glo_ctrl.in_auto_key_retrieve++;
1328 rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
1329 glo_ctrl.in_auto_key_retrieve--;
1334 glo_ctrl.in_auto_key_retrieve++;
1335 rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len);
1336 glo_ctrl.in_auto_key_retrieve--;
1341 glo_ctrl.in_auto_key_retrieve++;
1342 rc = keyserver_import_wkd (ctrl, name, 0, &fpr, &fpr_len);
1343 glo_ctrl.in_auto_key_retrieve--;
1348 glo_ctrl.in_auto_key_retrieve++;
1349 rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
1350 glo_ctrl.in_auto_key_retrieve--;
1354 /* Strictly speaking, we don't need to only use a valid
1355 * mailbox for the getname search, but it helps cut down
1356 * on the problem of searching for something like "john"
1357 * and getting a whole lot of keys back. */
1358 if (keyserver_any_configured (ctrl))
1360 mechanism = "keyserver";
1361 glo_ctrl.in_auto_key_retrieve++;
1362 rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
1364 glo_ctrl.in_auto_key_retrieve--;
1368 mechanism = "Unconfigured keyserver";
1369 rc = GPG_ERR_NO_PUBKEY;
1375 struct keyserver_spec *keyserver;
1377 mechanism = akl->spec->uri;
1378 keyserver = keyserver_match (akl->spec);
1379 glo_ctrl.in_auto_key_retrieve++;
1380 rc = keyserver_import_name (ctrl,
1381 name, &fpr, &fpr_len, keyserver);
1382 glo_ctrl.in_auto_key_retrieve--;
1387 /* Use the fingerprint of the key that we actually fetched.
1388 * This helps prevent problems where the key that we fetched
1389 * doesn't have the same name that we used to fetch it. In
1390 * the case of CERT and PKA, this is an actual security
1391 * requirement as the URL might point to a key put in by an
1392 * attacker. By forcing the use of the fingerprint, we
1393 * won't use the attacker's key here. */
1396 char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
1398 log_assert (fpr_len <= MAX_FINGERPRINT_LEN);
1400 free_strlist (namelist);
1403 bin2hex (fpr, fpr_len, fpr_string);
1406 log_info ("auto-key-locate found fingerprint %s\n",
1409 add_to_strlist (&namelist, fpr_string);
1411 else if (!rc && !fpr && !did_akl_local)
1412 { /* The acquisition method said no failure occurred, but
1413 * it didn't return a fingerprint. That's a failure. */
1415 rc = GPG_ERR_NO_PUBKEY;
1420 if (!rc && !did_akl_local)
1421 { /* There was no error and we didn't do a local lookup.
1422 * This means that we imported a key into the local
1423 * keyring. Try to read the imported key from the
1427 getkey_end (*retctx);
1430 rc = key_byname (anylocalfirst ? retctx : NULL,
1432 include_unusable, ret_keyblock, ret_kdbhd);
1437 log_info (_("automatically retrieved '%s' via %s\n"),
1441 if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1442 || opt.verbose || no_fingerprint)
1443 log_info (_("error retrieving '%s' via %s: %s\n"),
1445 no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
1452 getkey_end (*retctx);
1456 if (retctx && *retctx)
1458 log_assert (!(*retctx)->extra_list);
1459 (*retctx)->extra_list = namelist;
1462 free_strlist (namelist);
1470 /* Comparison machinery for get_best_pubkey_byname. */
1472 /* First we have a struct to cache computed information about the key
1474 struct pubkey_cmp_cookie
1476 int valid; /* Is this cookie valid? */
1477 PKT_public_key key; /* The key. */
1478 PKT_user_id *uid; /* The matching UID packet. */
1479 unsigned int validity; /* Computed validity of (KEY, UID). */
1480 u32 creation_time; /* Creation time of the newest subkey
1481 capable of encryption. */
1485 /* Then we have a series of helper functions. */
1487 key_is_ok (const PKT_public_key *key)
1489 return (! key->has_expired && ! key->flags.revoked
1490 && key->flags.valid && ! key->flags.disabled);
1495 uid_is_ok (const PKT_public_key *key, const PKT_user_id *uid)
1497 return key_is_ok (key) && ! uid->is_revoked;
1502 subkey_is_ok (const PKT_public_key *sub)
1504 return ! sub->flags.revoked && sub->flags.valid && ! sub->flags.disabled;
1508 /* Finally this function compares a NEW key to the former candidate
1509 * OLD. Returns < 0 if the old key is worse, > 0 if the old key is
1510 * better, == 0 if it is a tie. */
1512 pubkey_cmp (ctrl_t ctrl, const char *name, struct pubkey_cmp_cookie *old,
1513 struct pubkey_cmp_cookie *new, KBNODE new_keyblock)
1517 new->creation_time = 0;
1518 for (n = find_next_kbnode (new_keyblock, PKT_PUBLIC_SUBKEY);
1519 n; n = find_next_kbnode (n, PKT_PUBLIC_SUBKEY))
1521 PKT_public_key *sub = n->pkt->pkt.public_key;
1523 if ((sub->pubkey_usage & PUBKEY_USAGE_ENC) == 0)
1526 if (! subkey_is_ok (sub))
1529 if (sub->timestamp > new->creation_time)
1530 new->creation_time = sub->timestamp;
1533 for (n = find_next_kbnode (new_keyblock, PKT_USER_ID);
1534 n; n = find_next_kbnode (n, PKT_USER_ID))
1536 PKT_user_id *uid = n->pkt->pkt.user_id;
1537 char *mbox = mailbox_from_userid (uid->name);
1538 int match = mbox ? strcasecmp (name, mbox) == 0 : 0;
1544 new->uid = scopy_user_id (uid);
1546 get_validity (ctrl, new_keyblock, &new->key, uid, NULL, 0) & TRUST_MASK;
1550 return -1; /* No OLD key. */
1552 if (! uid_is_ok (&old->key, old->uid) && uid_is_ok (&new->key, uid))
1553 return -1; /* Validity of the NEW key is better. */
1555 if (old->validity < new->validity)
1556 return -1; /* Validity of the NEW key is better. */
1558 if (old->validity == new->validity && uid_is_ok (&new->key, uid)
1559 && old->creation_time < new->creation_time)
1560 return -1; /* Both keys are of the same validity, but the
1561 NEW key is newer. */
1564 /* Stick with the OLD key. */
1569 /* This function works like get_pubkey_byname, but if the name
1570 * resembles a mail address, the results are ranked and only the best
1571 * result is returned. */
1573 get_best_pubkey_byname (ctrl_t ctrl, GETKEY_CTX *retctx, PKT_public_key *pk,
1574 const char *name, KBNODE *ret_keyblock,
1575 int include_unusable, int no_akl)
1578 struct getkey_ctx_s *ctx = NULL;
1583 rc = get_pubkey_byname (ctrl, &ctx, pk, name, ret_keyblock,
1584 NULL, include_unusable, no_akl);
1592 if (is_valid_mailbox (name) && ctx)
1594 /* Rank results and return only the most relevant key. */
1595 struct pubkey_cmp_cookie best = { 0 }, new;
1596 KBNODE new_keyblock;
1597 while (getkey_next (ctx, &new.key, &new_keyblock) == 0)
1599 int diff = pubkey_cmp (ctrl, name, &best, &new, new_keyblock);
1600 release_kbnode (new_keyblock);
1603 /* New key is better. */
1604 release_public_key_parts (&best.key);
1605 free_user_id (best.uid);
1610 /* Old key is better. */
1611 release_public_key_parts (&new.key);
1612 free_user_id (new.uid);
1616 /* A tie. Keep the old key. */
1617 release_public_key_parts (&new.key);
1618 free_user_id (new.uid);
1623 free_user_id (best.uid);
1627 if (retctx || ret_keyblock)
1629 ctx = xtrycalloc (1, sizeof **retctx);
1631 rc = gpg_error_from_syserror ();
1634 ctx->kr_handle = keydb_new ();
1635 if (! ctx->kr_handle)
1639 rc = gpg_error_from_syserror ();
1643 u32 *keyid = pk_keyid (&best.key);
1646 ctx->items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
1647 ctx->items[0].u.kid[0] = keyid[0];
1648 ctx->items[0].u.kid[1] = keyid[1];
1652 release_kbnode (*ret_keyblock);
1653 *ret_keyblock = NULL;
1654 rc = getkey_next (ctx, NULL, ret_keyblock);
1663 release_public_key_parts (&best.key);
1683 /* Get a public key from a file.
1685 * PK is the buffer to store the key. The caller needs to make sure
1686 * that PK->REQ_USAGE is valid. PK->REQ_USAGE is passed through to
1687 * the lookup function and is a mask of PUBKEY_USAGE_SIG,
1688 * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this is non-zero, only
1689 * keys with the specified usage will be returned.
1691 * FNAME is the file name. That file should contain exactly one
1694 * This function returns 0 on success. Otherwise, an error code is
1695 * returned. In particular, GPG_ERR_NO_PUBKEY is returned if the key
1698 * The self-signed data has already been merged into the public key
1699 * using merge_selfsigs. The caller must release the content of PK by
1700 * calling release_public_key_parts (or, if PK was malloced, using
1704 get_pubkey_fromfile (ctrl_t ctrl, PKT_public_key *pk, const char *fname)
1709 unsigned int infoflags;
1711 err = read_key_from_file (ctrl, fname, &keyblock);
1714 /* Warning: node flag bits 0 and 1 should be preserved by
1715 * merge_selfsigs. FIXME: Check whether this still holds. */
1716 merge_selfsigs (keyblock);
1717 found_key = finish_lookup (keyblock, pk->req_usage, 0, &infoflags);
1718 print_status_key_considered (keyblock, infoflags);
1720 pk_from_block (pk, keyblock, found_key);
1722 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
1725 release_kbnode (keyblock);
1730 /* Lookup a key with the specified fingerprint.
1732 * If PK is not NULL, the public key of the first result is returned
1733 * in *PK. Note: this function does an exact search and thus the
1734 * returned public key may be a subkey rather than the primary key.
1735 * Note: The self-signed data has already been merged into the public
1736 * key using merge_selfsigs. Free *PK by calling
1737 * release_public_key_parts (or, if PK was allocated using xfree, you
1738 * can use free_public_key, which calls release_public_key_parts(PK)
1739 * and then xfree(PK)).
1741 * If PK->REQ_USAGE is set, it is used to filter the search results.
1742 * (Thus, if PK is not NULL, PK->REQ_USAGE must be valid!!!) See the
1743 * documentation for finish_lookup to understand exactly how this is
1746 * If R_KEYBLOCK is not NULL, then the first result's keyblock is
1747 * returned in *R_KEYBLOCK. This should be freed using
1750 * FPRINT is a byte array whose contents is the fingerprint to use as
1751 * the search term. FPRINT_LEN specifies the length of the
1752 * fingerprint (in bytes). Currently, only 16 and 20-byte
1753 * fingerprints are supported.
1755 * FIXME: We should replace this with the _byname function. This can
1756 * be done by creating a userID conforming to the unified fingerprint
1759 get_pubkey_byfprint (PKT_public_key *pk, kbnode_t *r_keyblock,
1760 const byte * fprint, size_t fprint_len)
1767 if (fprint_len == 20 || fprint_len == 16)
1769 struct getkey_ctx_s ctx;
1771 KBNODE found_key = NULL;
1773 memset (&ctx, 0, sizeof ctx);
1775 ctx.not_allocated = 1;
1776 ctx.kr_handle = keydb_new ();
1778 return gpg_error_from_syserror ();
1781 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1782 : KEYDB_SEARCH_MODE_FPR20;
1783 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1784 rc = lookup (&ctx, &kb, &found_key, 0);
1786 pk_from_block (pk, kb, found_key);
1787 if (!rc && r_keyblock)
1792 release_kbnode (kb);
1796 rc = GPG_ERR_GENERAL; /* Oops */
1801 /* This function is similar to get_pubkey_byfprint, but it doesn't
1802 * merge the self-signed data into the public key and subkeys or into
1803 * the user ids. It also doesn't add the key to the user id cache.
1804 * Further, this function ignores PK->REQ_USAGE.
1806 * This function is intended to avoid recursion and, as such, should
1807 * only be used in very specific situations.
1809 * Like get_pubkey_byfprint, PK may be NULL. In that case, this
1810 * function effectively just checks for the existence of the key. */
1812 get_pubkey_byfprint_fast (PKT_public_key * pk,
1813 const byte * fprint, size_t fprint_len)
1818 byte fprbuf[MAX_FINGERPRINT_LEN];
1821 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1822 fprbuf[i] = fprint[i];
1823 while (i < MAX_FINGERPRINT_LEN)
1828 return gpg_error_from_syserror ();
1830 rc = keydb_search_fpr (hd, fprbuf);
1831 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1834 return GPG_ERR_NO_PUBKEY;
1836 rc = keydb_get_keyblock (hd, &keyblock);
1840 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1841 return GPG_ERR_NO_PUBKEY;
1844 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1845 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1847 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1848 release_kbnode (keyblock);
1850 /* Not caching key here since it won't have all of the fields
1857 parse_def_secret_key (ctrl_t ctrl)
1859 KEYDB_HANDLE hd = NULL;
1863 for (t = opt.def_secret_key; t; t = t->next)
1866 KEYDB_SEARCH_DESC desc;
1870 err = classify_user_id (t->d, &desc, 1);
1873 log_error (_("secret key \"%s\" not found: %s\n"),
1874 t->d, gpg_strerror (err));
1876 log_info (_("(check argument of option '%s')\n"), "--default-key");
1887 keydb_search_reset (hd);
1890 err = keydb_search (hd, &desc, 1, NULL);
1891 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1896 log_error (_("key \"%s\" not found: %s\n"), t->d, gpg_strerror (err));
1901 err = keydb_get_keyblock (hd, &kb);
1904 log_error (_("error reading keyblock: %s\n"),
1905 gpg_strerror (err));
1909 merge_selfsigs (kb);
1911 err = gpg_error (GPG_ERR_NO_SECKEY);
1915 PKT_public_key *pk = node->pkt->pkt.public_key;
1917 /* Check that the key has the signing capability. */
1918 if (! (pk->pubkey_usage & PUBKEY_USAGE_SIG))
1921 /* Check if the key is valid. */
1922 if (pk->flags.revoked)
1925 log_debug ("not using %s as default key, %s",
1926 keystr_from_pk (pk), "revoked");
1929 if (pk->has_expired)
1932 log_debug ("not using %s as default key, %s",
1933 keystr_from_pk (pk), "expired");
1936 if (pk_is_disabled (pk))
1939 log_debug ("not using %s as default key, %s",
1940 keystr_from_pk (pk), "disabled");
1944 err = agent_probe_secret_key (ctrl, pk);
1946 /* This is a valid key. */
1949 while ((node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY)));
1951 release_kbnode (kb);
1954 if (! warned && ! opt.quiet)
1956 log_info (_("Warning: not using '%s' as default key: %s\n"),
1957 t->d, gpg_strerror (GPG_ERR_NO_SECKEY));
1958 print_reported_error (err, GPG_ERR_NO_SECKEY);
1963 if (! warned && ! opt.quiet)
1964 log_info (_("using \"%s\" as default secret key for signing\n"),
1970 if (! warned && opt.def_secret_key && ! t)
1971 log_info (_("all values passed to '%s' ignored\n"),
1985 /* Look up a secret key.
1987 * If PK is not NULL, the public key of the first result is returned
1988 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
1989 * set, it is used to filter the search results. See the
1990 * documentation for finish_lookup to understand exactly how this is
1991 * used. Note: The self-signed data has already been merged into the
1992 * public key using merge_selfsigs. Free *PK by calling
1993 * release_public_key_parts (or, if PK was allocated using xfree, you
1994 * can use free_public_key, which calls release_public_key_parts(PK)
1995 * and then xfree(PK)).
1997 * If --default-key was set, then the specified key is looked up. (In
1998 * this case, the default key is returned even if it is considered
1999 * unusable. See the documentation for skip_unusable for exactly what
2002 * Otherwise, this initiates a DB scan that returns all keys that are
2003 * usable (see previous paragraph for exactly what usable means) and
2004 * for which a secret key is available.
2006 * This function returns the first match. Additional results can be
2007 * returned using getkey_next. */
2009 get_seckey_default (ctrl_t ctrl, PKT_public_key *pk)
2012 strlist_t namelist = NULL;
2013 int include_unusable = 1;
2016 const char *def_secret_key = parse_def_secret_key (ctrl);
2018 add_to_strlist (&namelist, def_secret_key);
2020 include_unusable = 0;
2022 err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
2024 free_strlist (namelist);
2031 /* Search for keys matching some criteria.
2033 * If RETCTX is not NULL, then the constructed context is returned in
2034 * *RETCTX so that getpubkey_next can be used to get subsequent
2035 * results. In this case, getkey_end() must be used to free the
2036 * search context. If RETCTX is not NULL, then RET_KDBHD must be
2039 * If PK is not NULL, the public key of the first result is returned
2040 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2041 * set, it is used to filter the search results. See the
2042 * documentation for finish_lookup to understand exactly how this is
2043 * used. Note: The self-signed data has already been merged into the
2044 * public key using merge_selfsigs. Free *PK by calling
2045 * release_public_key_parts (or, if PK was allocated using xfree, you
2046 * can use free_public_key, which calls release_public_key_parts(PK)
2047 * and then xfree(PK)).
2049 * If NAMES is not NULL, then a search query is constructed using
2050 * classify_user_id on each of the strings in the list. (Recall: the
2051 * database does an OR of the terms, not an AND.) If NAMES is
2052 * NULL, then all results are returned.
2054 * If WANT_SECRET is set, then only keys with an available secret key
2055 * (either locally or via key registered on a smartcard) are returned.
2057 * This function does not skip unusable keys (see the documentation
2058 * for skip_unusable for an exact definition).
2060 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2061 * *RET_KEYBLOCK. This should be freed using release_kbnode().
2063 * This function returns 0 on success. Otherwise, an error code is
2064 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2065 * (if want_secret is set) is returned if the key is not found. */
2067 getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
2068 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
2070 return key_byname (retctx, names, pk, want_secret, 1,
2071 ret_keyblock, NULL);
2075 /* Search for one key matching some criteria.
2077 * If RETCTX is not NULL, then the constructed context is returned in
2078 * *RETCTX so that getpubkey_next can be used to get subsequent
2079 * results. In this case, getkey_end() must be used to free the
2080 * search context. If RETCTX is not NULL, then RET_KDBHD must be
2083 * If PK is not NULL, the public key of the first result is returned
2084 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2085 * set, it is used to filter the search results. See the
2086 * documentation for finish_lookup to understand exactly how this is
2087 * used. Note: The self-signed data has already been merged into the
2088 * public key using merge_selfsigs. Free *PK by calling
2089 * release_public_key_parts (or, if PK was allocated using xfree, you
2090 * can use free_public_key, which calls release_public_key_parts(PK)
2091 * and then xfree(PK)).
2093 * If NAME is not NULL, then a search query is constructed using
2094 * classify_user_id on the string. In this case, even unusable keys
2095 * (see the documentation for skip_unusable for an exact definition of
2096 * unusable) are returned. Otherwise, if --default-key was set, then
2097 * that key is returned (even if it is unusable). If neither of these
2098 * conditions holds, then the first usable key is returned.
2100 * If WANT_SECRET is set, then only keys with an available secret key
2101 * (either locally or via key registered on a smartcard) are returned.
2103 * This function does not skip unusable keys (see the documentation
2104 * for skip_unusable for an exact definition).
2106 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2107 * *RET_KEYBLOCK. This should be freed using release_kbnode().
2109 * This function returns 0 on success. Otherwise, an error code is
2110 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2111 * (if want_secret is set) is returned if the key is not found.
2113 * FIXME: We also have the get_pubkey_byname function which has a
2114 * different semantic. Should be merged with this one. */
2116 getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2117 const char *name, int want_secret, kbnode_t *ret_keyblock)
2120 strlist_t namelist = NULL;
2121 int with_unusable = 1;
2122 const char *def_secret_key = NULL;
2124 if (want_secret && !name)
2125 def_secret_key = parse_def_secret_key (ctrl);
2127 if (want_secret && !name && def_secret_key)
2128 add_to_strlist (&namelist, def_secret_key);
2130 add_to_strlist (&namelist, name);
2134 err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
2135 ret_keyblock, NULL);
2137 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
2138 WANT_SECRET has been used. */
2140 free_strlist (namelist);
2146 /* Return the next search result.
2148 * If PK is not NULL, the public key of the next result is returned in
2149 * *PK. Note: The self-signed data has already been merged into the
2150 * public key using merge_selfsigs. Free *PK by calling
2151 * release_public_key_parts (or, if PK was allocated using xmalloc, you
2152 * can use free_public_key, which calls release_public_key_parts(PK)
2153 * and then xfree(PK)).
2155 * RET_KEYBLOCK can be given as NULL; if it is not NULL it the entire
2156 * found keyblock is returned which must be released with
2157 * release_kbnode. If the function returns an error NULL is stored at
2160 * The self-signed data has already been merged into the public key
2161 * using merge_selfsigs. */
2163 getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
2165 int rc; /* Fixme: Make sure this is proper gpg_error */
2166 KBNODE keyblock = NULL;
2167 KBNODE found_key = NULL;
2169 /* We need to disable the caching so that for an exact key search we
2170 won't get the result back from the cache and thus end up in an
2171 endless loop. The endless loop can occur, because the cache is
2172 used without respecting the current file pointer! */
2173 keydb_disable_caching (ctx->kr_handle);
2175 /* FOUND_KEY is only valid as long as RET_KEYBLOCK is. If the
2176 * caller wants PK, but not RET_KEYBLOCK, we need hand in our own
2178 if (pk && ret_keyblock == NULL)
2179 ret_keyblock = &keyblock;
2181 rc = lookup (ctx, ret_keyblock, pk ? &found_key : NULL, ctx->want_secret);
2184 log_assert (found_key);
2185 pk_from_block (pk, NULL, found_key);
2186 release_kbnode (keyblock);
2193 /* Release any resources used by a key listing context. This must be
2194 * called on the context returned by, e.g., getkey_byname. */
2196 getkey_end (getkey_ctx_t ctx)
2200 keydb_release (ctx->kr_handle);
2201 free_strlist (ctx->extra_list);
2202 if (!ctx->not_allocated)
2209 /************************************************
2210 ************* Merging stuff ********************
2211 ************************************************/
2213 /* Set the mainkey_id fields for all keys in KEYBLOCK. This is
2214 * usually done by merge_selfsigs but at some places we only need the
2215 * main_kid not a full merge. The function also guarantees that all
2216 * pk->keyids are computed. */
2218 setup_main_keyids (kbnode_t keyblock)
2220 u32 kid[2], mainkid[2];
2221 kbnode_t kbctx, node;
2224 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2226 pk = keyblock->pkt->pkt.public_key;
2228 keyid_from_pk (pk, mainkid);
2229 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
2231 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
2232 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
2234 pk = node->pkt->pkt.public_key;
2235 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
2236 if (!pk->main_keyid[0] && !pk->main_keyid[1])
2238 pk->main_keyid[0] = mainkid[0];
2239 pk->main_keyid[1] = mainkid[1];
2245 /* KEYBLOCK corresponds to a public key block. This function merges
2246 * much of the information from the self-signed data into the public
2247 * key, public subkey and user id data structures. If you use the
2248 * high-level search API (e.g., get_pubkey) for looking up key blocks,
2249 * then you don't need to call this function. This function is
2250 * useful, however, if you change the keyblock, e.g., by adding or
2251 * removing a self-signed data packet. */
2253 merge_keys_and_selfsig (KBNODE keyblock)
2257 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
2258 merge_selfsigs (keyblock);
2260 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
2265 parse_key_usage (PKT_signature * sig)
2272 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
2275 /* First octet of the keyflags. */
2280 key_usage |= PUBKEY_USAGE_CERT;
2286 key_usage |= PUBKEY_USAGE_SIG;
2290 /* We do not distinguish between encrypting communications and
2291 encrypting storage. */
2292 if (flags & (0x04 | 0x08))
2294 key_usage |= PUBKEY_USAGE_ENC;
2295 flags &= ~(0x04 | 0x08);
2300 key_usage |= PUBKEY_USAGE_AUTH;
2305 key_usage |= PUBKEY_USAGE_UNKNOWN;
2308 key_usage |= PUBKEY_USAGE_NONE;
2310 else if (p) /* Key flags of length zero. */
2311 key_usage |= PUBKEY_USAGE_NONE;
2313 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
2314 capability that we do not handle. This serves to distinguish
2315 between a zero key usage which we handle as the default
2316 capabilities for that algorithm, and a usage that we do not
2317 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
2318 key_flags have been given but they do not specify any usage. */
2324 /* Apply information from SIGNODE (which is the valid self-signature
2325 * associated with that UID) to the UIDNODE:
2326 * - weather the UID has been revoked
2327 * - assumed creation date of the UID
2328 * - temporary store the keyflags here
2329 * - temporary store the key expiration time here
2330 * - mark whether the primary user ID flag hat been set.
2331 * - store the preferences
2334 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
2336 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
2337 PKT_signature *sig = signode->pkt->pkt.signature;
2338 const byte *p, *sym, *hash, *zip;
2339 size_t n, nsym, nhash, nzip;
2341 sig->flags.chosen_selfsig = 1;/* We chose this one. */
2342 uid->created = 0; /* Not created == invalid. */
2343 if (IS_UID_REV (sig))
2345 uid->is_revoked = 1;
2346 return; /* Has been revoked. */
2349 uid->is_revoked = 0;
2351 uid->expiredate = sig->expiredate;
2353 if (sig->flags.expired)
2355 uid->is_expired = 1;
2356 return; /* Has expired. */
2359 uid->is_expired = 0;
2361 uid->created = sig->timestamp; /* This one is okay. */
2362 uid->selfsigversion = sig->version;
2363 /* If we got this far, it's not expired :) */
2364 uid->is_expired = 0;
2366 /* Store the key flags in the helper variable for later processing. */
2367 uid->help_key_usage = parse_key_usage (sig);
2369 /* Ditto for the key expiration. */
2370 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2371 if (p && buf32_to_u32 (p))
2372 uid->help_key_expire = keycreated + buf32_to_u32 (p);
2374 uid->help_key_expire = 0;
2376 /* Set the primary user ID flag - we will later wipe out some
2377 * of them to only have one in our keyblock. */
2378 uid->is_primary = 0;
2379 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
2381 uid->is_primary = 2;
2383 /* We could also query this from the unhashed area if it is not in
2384 * the hased area and then later try to decide which is the better
2385 * there should be no security problem with this.
2386 * For now we only look at the hashed one. */
2388 /* Now build the preferences list. These must come from the
2389 hashed section so nobody can modify the ciphers a key is
2390 willing to accept. */
2391 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
2394 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
2397 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
2402 n = nsym + nhash + nzip;
2407 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
2409 for (; nsym; nsym--, n++)
2411 uid->prefs[n].type = PREFTYPE_SYM;
2412 uid->prefs[n].value = *sym++;
2414 for (; nhash; nhash--, n++)
2416 uid->prefs[n].type = PREFTYPE_HASH;
2417 uid->prefs[n].value = *hash++;
2419 for (; nzip; nzip--, n++)
2421 uid->prefs[n].type = PREFTYPE_ZIP;
2422 uid->prefs[n].value = *zip++;
2424 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
2425 uid->prefs[n].value = 0;
2428 /* See whether we have the MDC feature. */
2430 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
2431 if (p && n && (p[0] & 0x01))
2434 /* And the keyserver modify flag. */
2435 uid->flags.ks_modify = 1;
2436 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
2437 if (p && n && (p[0] & 0x80))
2438 uid->flags.ks_modify = 0;
2442 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
2444 rinfo->date = sig->timestamp;
2445 rinfo->algo = sig->pubkey_algo;
2446 rinfo->keyid[0] = sig->keyid[0];
2447 rinfo->keyid[1] = sig->keyid[1];
2451 /* Given a keyblock, parse the key block and extract various pieces of
2452 information and save them with the primary key packet and the user
2453 id packets. For instance, some information is stored in signature
2454 packets. We find the latest such valid packet (since the user can
2455 change that information) and copy its contents into the
2458 Note that R_REVOKED may be set to 0, 1 or 2.
2460 This function fills in the following fields in the primary key's
2463 main_keyid (computed)
2464 revkey / numrevkeys (derived from self signed key data)
2465 flags.valid (whether we have at least 1 self-sig)
2466 flags.maybe_revoked (whether a designed revoked the key, but
2467 we are missing the key to check the sig)
2468 selfsigversion (highest version of any valid self-sig)
2469 pubkey_usage (derived from most recent self-sig or most
2471 has_expired (various sources)
2472 expiredate (various sources)
2474 See the documentation for fixup_uidnode for how the user id packets
2475 are modified. In addition to that the primary user id's is_primary
2476 field is set to 1 and the other user id's is_primary are set to
2479 merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
2480 struct revoke_info *rinfo)
2482 PKT_public_key *pk = NULL;
2485 u32 sigdate, uiddate, uiddate2;
2486 KBNODE signode, uidnode, uidnode2;
2487 u32 curtime = make_timestamp ();
2488 unsigned int key_usage = 0;
2489 u32 keytimestamp = 0;
2491 int key_expire_seen = 0;
2492 byte sigversion = 0;
2495 memset (rinfo, 0, sizeof (*rinfo));
2497 /* Section 11.1 of RFC 4880 determines the order of packets within a
2498 message. There are three sections, which must occur in the
2499 following order: the public key, the user ids and user attributes
2500 and the subkeys. Within each section, each primary packet (e.g.,
2501 a user id packet) is followed by one or more signature packets,
2502 which modify that packet. */
2504 /* According to Section 11.1 of RFC 4880, the public key must be the
2506 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2507 /* parse_keyblock_image ensures that the first packet is the
2510 pk = keyblock->pkt->pkt.public_key;
2511 keytimestamp = pk->timestamp;
2513 keyid_from_pk (pk, kid);
2514 pk->main_keyid[0] = kid[0];
2515 pk->main_keyid[1] = kid[1];
2517 if (pk->version < 4)
2519 /* Before v4 the key packet itself contains the expiration date
2520 * and there was no way to change it, so we start with the one
2521 * from the key packet. */
2522 key_expire = pk->max_expiredate;
2523 key_expire_seen = 1;
2528 - Find the latest direct key self-signature. We assume that the
2529 newest one overrides all others.
2531 - Determine whether the key has been revoked.
2533 - Gather all revocation keys (unlike other data, we don't just
2534 take them from the latest self-signed packet).
2536 - Determine max (sig[...]->version).
2539 /* Reset this in case this key was already merged. */
2545 sigdate = 0; /* Helper variable to find the latest signature. */
2547 /* According to Section 11.1 of RFC 4880, the public key comes first
2548 and is immediately followed by any signature packets that modify
2551 k && k->pkt->pkttype != PKT_USER_ID
2552 && k->pkt->pkttype != PKT_ATTRIBUTE
2553 && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2556 if (k->pkt->pkttype == PKT_SIGNATURE)
2558 PKT_signature *sig = k->pkt->pkt.signature;
2559 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2562 if (check_key_signature (keyblock, k, NULL))
2563 ; /* Signature did not verify. */
2564 else if (IS_KEY_REV (sig))
2566 /* Key has been revoked - there is no way to
2567 * override such a revocation, so we theoretically
2568 * can stop now. We should not cope with expiration
2569 * times for revocations here because we have to
2570 * assume that an attacker can generate all kinds of
2571 * signatures. However due to the fact that the key
2572 * has been revoked it does not harm either and by
2573 * continuing we gather some more info on that
2576 sig_to_revoke_info (sig, rinfo);
2578 else if (IS_KEY_SIG (sig))
2580 /* Add the indicated revocations keys from all
2581 signatures not just the latest. We do this
2582 because you need multiple 1F sigs to properly
2583 handle revocation keys (PGP does it this way, and
2584 a revocation key could be sensitive and hence in
2585 a different signature). */
2591 xrealloc (pk->revkey, sizeof (struct revocation_key) *
2592 (pk->numrevkeys + sig->numrevkeys));
2594 for (i = 0; i < sig->numrevkeys; i++)
2595 memcpy (&pk->revkey[pk->numrevkeys++],
2597 sizeof (struct revocation_key));
2600 if (sig->timestamp >= sigdate)
2601 /* This is the latest signature so far. */
2603 if (sig->flags.expired)
2604 ; /* Signature has expired - ignore it. */
2607 sigdate = sig->timestamp;
2609 if (sig->version > sigversion)
2610 sigversion = sig->version;
2619 /* Remove dupes from the revocation keys. */
2622 int i, j, x, changed = 0;
2624 for (i = 0; i < pk->numrevkeys; i++)
2626 for (j = i + 1; j < pk->numrevkeys; j++)
2628 if (memcmp (&pk->revkey[i], &pk->revkey[j],
2629 sizeof (struct revocation_key)) == 0)
2633 for (x = j; x < pk->numrevkeys - 1; x++)
2634 pk->revkey[x] = pk->revkey[x + 1];
2644 pk->revkey = xrealloc (pk->revkey,
2646 sizeof (struct revocation_key));
2650 /* SIGNODE is the 1F signature packet with the latest creation
2651 time. Extract some information from it. */
2653 /* Some information from a direct key signature take precedence
2654 * over the same information given in UID sigs. */
2655 PKT_signature *sig = signode->pkt->pkt.signature;
2658 key_usage = parse_key_usage (sig);
2660 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2661 if (p && buf32_to_u32 (p))
2663 key_expire = keytimestamp + buf32_to_u32 (p);
2664 key_expire_seen = 1;
2667 /* Mark that key as valid: One direct key signature should
2668 * render a key as valid. */
2669 pk->flags.valid = 1;
2672 /* Pass 1.5: Look for key revocation signatures that were not made
2673 by the key (i.e. did a revocation key issue a revocation for
2674 us?). Only bother to do this if there is a revocation key in the
2675 first place and we're not revoked already. */
2677 if (!*r_revoked && pk->revkey)
2678 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
2680 if (k->pkt->pkttype == PKT_SIGNATURE)
2682 PKT_signature *sig = k->pkt->pkt.signature;
2684 if (IS_KEY_REV (sig) &&
2685 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
2687 int rc = check_revocation_keys (pk, sig);
2691 sig_to_revoke_info (sig, rinfo);
2692 /* Don't continue checking since we can't be any
2693 more revoked than this. */
2696 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2697 pk->flags.maybe_revoked = 1;
2699 /* A failure here means the sig did not verify, was
2700 not issued by a revocation key, or a revocation
2701 key loop was broken. If a revocation key isn't
2702 findable, however, the key might be revoked and
2703 we don't know it. */
2705 /* TODO: In the future handle subkey and cert
2706 revocations? PGP doesn't, but it's in 2440. */
2711 /* Second pass: Look at the self-signature of all user IDs. */
2713 /* According to RFC 4880 section 11.1, user id and attribute packets
2714 are in the second section, after the public key packet and before
2715 the subkey packets. */
2716 signode = uidnode = NULL;
2717 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
2718 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2720 if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
2721 /* New user id packet. */
2723 if (uidnode && signode)
2724 /* Apply the data from the most recent self-signed packet
2725 to the preceding user id packet. */
2727 fixup_uidnode (uidnode, signode, keytimestamp);
2728 pk->flags.valid = 1;
2730 /* Clear SIGNODE. The only relevant self-signed data for
2731 UIDNODE follows it. */
2732 if (k->pkt->pkttype == PKT_USER_ID)
2739 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2741 PKT_signature *sig = k->pkt->pkt.signature;
2742 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2744 if (check_key_signature (keyblock, k, NULL))
2745 ; /* signature did not verify */
2746 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
2747 && sig->timestamp >= sigdate)
2749 /* Note: we allow invalidation of cert revocations
2750 * by a newer signature. An attacker can't use this
2751 * because a key should be revoked with a key revocation.
2752 * The reason why we have to allow for that is that at
2753 * one time an email address may become invalid but later
2754 * the same email address may become valid again (hired,
2755 * fired, hired again). */
2757 sigdate = sig->timestamp;
2759 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2760 if (sig->version > sigversion)
2761 sigversion = sig->version;
2766 if (uidnode && signode)
2768 fixup_uidnode (uidnode, signode, keytimestamp);
2769 pk->flags.valid = 1;
2772 /* If the key isn't valid yet, and we have
2773 --allow-non-selfsigned-uid set, then force it valid. */
2774 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
2777 log_info (_("Invalid key %s made valid by"
2778 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
2779 pk->flags.valid = 1;
2782 /* The key STILL isn't valid, so try and find an ultimately
2783 trusted signature. */
2784 if (!pk->flags.valid)
2788 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2791 if (k->pkt->pkttype == PKT_USER_ID)
2793 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2795 PKT_signature *sig = k->pkt->pkt.signature;
2797 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
2799 PKT_public_key *ultimate_pk;
2801 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
2803 /* We don't want to use the full get_pubkey to
2804 avoid infinite recursion in certain cases.
2805 There is no reason to check that an ultimately
2806 trusted key is still valid - if it has been
2807 revoked the user should also remove the
2808 ultimate trust flag. */
2809 if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
2810 && check_key_signature2 (keyblock, k, ultimate_pk,
2811 NULL, NULL, NULL, NULL) == 0
2812 && get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
2814 free_public_key (ultimate_pk);
2815 pk->flags.valid = 1;
2819 free_public_key (ultimate_pk);
2825 /* Record the highest selfsig version so we know if this is a v3
2826 key through and through, or a v3 key with a v4 selfsig
2827 somewhere. This is useful in a few places to know if the key
2828 must be treated as PGP2-style or OpenPGP-style. Note that a
2829 selfsig revocation with a higher version number will also raise
2830 this value. This is okay since such a revocation must be
2831 issued by the user (i.e. it cannot be issued by someone else to
2832 modify the key behavior.) */
2834 pk->selfsigversion = sigversion;
2836 /* Now that we had a look at all user IDs we can now get some information
2837 * from those user IDs.
2842 /* Find the latest user ID with key flags set. */
2843 uiddate = 0; /* Helper to find the latest user ID. */
2844 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2847 if (k->pkt->pkttype == PKT_USER_ID)
2849 PKT_user_id *uid = k->pkt->pkt.user_id;
2850 if (uid->help_key_usage && uid->created > uiddate)
2852 key_usage = uid->help_key_usage;
2853 uiddate = uid->created;
2860 /* No key flags at all: get it from the algo. */
2861 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
2865 /* Check that the usage matches the usage as given by the algo. */
2866 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
2867 if (x) /* Mask it down to the actual allowed usage. */
2871 /* Whatever happens, it's a primary key, so it can certify. */
2872 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
2874 if (!key_expire_seen)
2876 /* Find the latest valid user ID with a key expiration set
2877 * Note, that this may be a different one from the above because
2878 * some user IDs may have no expiration date set. */
2880 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2883 if (k->pkt->pkttype == PKT_USER_ID)
2885 PKT_user_id *uid = k->pkt->pkt.user_id;
2886 if (uid->help_key_expire && uid->created > uiddate)
2888 key_expire = uid->help_key_expire;
2889 uiddate = uid->created;
2895 /* Currently only v3 keys have a maximum expiration date, but I'll
2896 bet v5 keys get this feature again. */
2898 || (pk->max_expiredate && key_expire > pk->max_expiredate))
2899 key_expire = pk->max_expiredate;
2901 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
2902 pk->expiredate = key_expire;
2904 /* Fixme: we should see how to get rid of the expiretime fields but
2905 * this needs changes at other places too. */
2907 /* And now find the real primary user ID and delete all others. */
2908 uiddate = uiddate2 = 0;
2909 uidnode = uidnode2 = NULL;
2910 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2912 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
2914 PKT_user_id *uid = k->pkt->pkt.user_id;
2915 if (uid->is_primary)
2917 if (uid->created > uiddate)
2919 uiddate = uid->created;
2922 else if (uid->created == uiddate && uidnode)
2924 /* The dates are equal, so we need to do a
2925 different (and arbitrary) comparison. This
2926 should rarely, if ever, happen. It's good to
2927 try and guarantee that two different GnuPG
2928 users with two different keyrings at least pick
2929 the same primary. */
2930 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
2936 if (uid->created > uiddate2)
2938 uiddate2 = uid->created;
2941 else if (uid->created == uiddate2 && uidnode2)
2943 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
2951 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2954 if (k->pkt->pkttype == PKT_USER_ID &&
2955 !k->pkt->pkt.user_id->attrib_data)
2957 PKT_user_id *uid = k->pkt->pkt.user_id;
2959 uid->is_primary = 0;
2965 /* None is flagged primary - use the latest user ID we have,
2966 and disambiguate with the arbitrary packet comparison. */
2967 uidnode2->pkt->pkt.user_id->is_primary = 1;
2971 /* None of our uids were self-signed, so pick the one that
2972 sorts first to be the primary. This is the best we can do
2973 here since there are no self sigs to date the uids. */
2977 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2980 if (k->pkt->pkttype == PKT_USER_ID
2981 && !k->pkt->pkt.user_id->attrib_data)
2986 uidnode->pkt->pkt.user_id->is_primary = 1;
2991 if (cmp_user_ids (k->pkt->pkt.user_id,
2992 uidnode->pkt->pkt.user_id) > 0)
2994 uidnode->pkt->pkt.user_id->is_primary = 0;
2996 uidnode->pkt->pkt.user_id->is_primary = 1;
2999 k->pkt->pkt.user_id->is_primary = 0; /* just to be
3007 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
3008 Caller must free the signature when they are done. */
3009 static PKT_signature *
3010 buf_to_sig (const byte * buf, size_t len)
3012 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
3013 IOBUF iobuf = iobuf_temp_with_content (buf, len);
3014 int save_mode = set_packet_list_mode (0);
3016 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
3022 set_packet_list_mode (save_mode);
3023 iobuf_close (iobuf);
3028 /* Use the self-signed data to fill in various fields in subkeys.
3030 KEYBLOCK is the whole keyblock. SUBNODE is the subkey to fill in.
3032 Sets the following fields on the subkey:
3035 flags.valid if the subkey has a valid self-sig binding
3042 On this subkey's most revent valid self-signed packet, the
3043 following field is set:
3045 flags.chosen_selfsig
3048 merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
3050 PKT_public_key *mainpk = NULL, *subpk = NULL;
3056 u32 curtime = make_timestamp ();
3057 unsigned int key_usage = 0;
3058 u32 keytimestamp = 0;
3062 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3064 mainpk = keyblock->pkt->pkt.public_key;
3065 if (mainpk->version < 4)
3066 return;/* (actually this should never happen) */
3067 keyid_from_pk (mainpk, mainkid);
3068 subpk = subnode->pkt->pkt.public_key;
3069 keytimestamp = subpk->timestamp;
3071 subpk->flags.valid = 0;
3072 subpk->flags.exact = 0;
3073 subpk->main_keyid[0] = mainpk->main_keyid[0];
3074 subpk->main_keyid[1] = mainpk->main_keyid[1];
3076 /* Find the latest key binding self-signature. */
3078 sigdate = 0; /* Helper to find the latest signature. */
3079 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3082 if (k->pkt->pkttype == PKT_SIGNATURE)
3084 sig = k->pkt->pkt.signature;
3085 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
3087 if (check_key_signature (keyblock, k, NULL))
3088 ; /* Signature did not verify. */
3089 else if (IS_SUBKEY_REV (sig))
3091 /* Note that this means that the date on a
3092 revocation sig does not matter - even if the
3093 binding sig is dated after the revocation sig,
3094 the subkey is still marked as revoked. This
3095 seems ok, as it is just as easy to make new
3096 subkeys rather than re-sign old ones as the
3097 problem is in the distribution. Plus, PGP (7)
3098 does this the same way. */
3099 subpk->flags.revoked = 1;
3100 sig_to_revoke_info (sig, &subpk->revoked);
3101 /* Although we could stop now, we continue to
3102 * figure out other information like the old expiration
3105 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
3107 if (sig->flags.expired)
3108 ; /* Signature has expired - ignore it. */
3111 sigdate = sig->timestamp;
3113 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
3120 /* No valid key binding. */
3124 sig = signode->pkt->pkt.signature;
3125 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
3127 key_usage = parse_key_usage (sig);
3130 /* No key flags at all: get it from the algo. */
3131 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
3135 /* Check that the usage matches the usage as given by the algo. */
3136 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
3137 if (x) /* Mask it down to the actual allowed usage. */
3141 subpk->pubkey_usage = key_usage;
3143 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
3144 if (p && buf32_to_u32 (p))
3145 key_expire = keytimestamp + buf32_to_u32 (p);
3148 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
3149 subpk->expiredate = key_expire;
3151 /* Algo doesn't exist. */
3152 if (openpgp_pk_test_algo (subpk->pubkey_algo))
3155 subpk->flags.valid = 1;
3157 /* Find the most recent 0x19 embedded signature on our self-sig. */
3158 if (!subpk->flags.backsig)
3162 PKT_signature *backsig = NULL;
3166 /* We do this while() since there may be other embedded
3167 signatures in the future. We only want 0x19 here. */
3169 while ((p = enum_sig_subpkt (sig->hashed,
3170 SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
3172 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
3174 PKT_signature *tempsig = buf_to_sig (p, n);
3177 if (tempsig->timestamp > sigdate)
3180 free_seckey_enc (backsig);
3183 sigdate = backsig->timestamp;
3186 free_seckey_enc (tempsig);
3192 /* It is safe to have this in the unhashed area since the 0x19
3193 is located on the selfsig for convenience, not security. */
3195 while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
3198 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
3200 PKT_signature *tempsig = buf_to_sig (p, n);
3203 if (tempsig->timestamp > sigdate)
3206 free_seckey_enc (backsig);
3209 sigdate = backsig->timestamp;
3212 free_seckey_enc (tempsig);
3218 /* At this point, backsig contains the most recent 0x19 sig.
3219 Let's see if it is good. */
3221 /* 2==valid, 1==invalid, 0==didn't check */
3222 if (check_backsig (mainpk, subpk, backsig) == 0)
3223 subpk->flags.backsig = 2;
3225 subpk->flags.backsig = 1;
3227 free_seckey_enc (backsig);
3233 /* Merge information from the self-signatures with the public key,
3234 subkeys and user ids to make using them more easy.
3236 See documentation for merge_selfsigs_main, merge_selfsigs_subkey
3237 and fixup_uidnode for exactly which fields are updated. */
3239 merge_selfsigs (KBNODE keyblock)
3243 struct revoke_info rinfo;
3244 PKT_public_key *main_pk;
3246 unsigned int mdc_feature;
3248 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
3250 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
3252 log_error ("expected public key but found secret key "
3254 /* We better exit here because a public key is expected at
3255 other places too. FIXME: Figure this out earlier and
3256 don't get to here at all */
3262 merge_selfsigs_main (keyblock, &revoked, &rinfo);
3264 /* Now merge in the data from each of the subkeys. */
3265 for (k = keyblock; k; k = k->next)
3267 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3269 merge_selfsigs_subkey (keyblock, k);
3273 main_pk = keyblock->pkt->pkt.public_key;
3274 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
3276 /* If the primary key is revoked, expired, or invalid we
3277 * better set the appropriate flags on that key and all
3279 for (k = keyblock; k; k = k->next)
3281 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3282 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3284 PKT_public_key *pk = k->pkt->pkt.public_key;
3285 if (!main_pk->flags.valid)
3286 pk->flags.valid = 0;
3287 if (revoked && !pk->flags.revoked)
3289 pk->flags.revoked = revoked;
3290 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
3292 if (main_pk->has_expired)
3293 pk->has_expired = main_pk->has_expired;
3299 /* Set the preference list of all keys to those of the primary real
3300 * user ID. Note: we use these preferences when we don't know by
3301 * which user ID the key has been selected.
3302 * fixme: we should keep atoms of commonly used preferences or
3303 * use reference counting to optimize the preference lists storage.
3304 * FIXME: it might be better to use the intersection of
3306 * Do a similar thing for the MDC feature flag. */
3309 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3311 if (k->pkt->pkttype == PKT_USER_ID
3312 && !k->pkt->pkt.user_id->attrib_data
3313 && k->pkt->pkt.user_id->is_primary)
3315 prefs = k->pkt->pkt.user_id->prefs;
3316 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
3320 for (k = keyblock; k; k = k->next)
3322 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3323 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3325 PKT_public_key *pk = k->pkt->pkt.public_key;
3328 pk->prefs = copy_prefs (prefs);
3329 pk->flags.mdc = mdc_feature;
3336 /* See whether the key satisfies any additional requirements specified
3337 * in CTX. If so, return the node of an appropriate key or subkey.
3338 * Otherwise, return NULL if there was no appropriate key.
3340 * Note that we do not return a reference, i.e. the result must not be
3341 * freed using 'release_kbnode'.
3343 * In case the primary key is not required, select a suitable subkey.
3344 * We need the primary key if PUBKEY_USAGE_CERT is set in REQ_USAGE or
3345 * we are in PGP6 or PGP7 mode and PUBKEY_USAGE_SIG is set in
3348 * If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
3349 * are set in REQ_USAGE, we filter by the key's function. Concretely,
3350 * if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then we only
3351 * return a key if it is (at least) either a signing or a
3352 * certification key.
3354 * If REQ_USAGE is set, then we reject any keys that are not good
3355 * (i.e., valid, not revoked, not expired, etc.). This allows the
3356 * getkey functions to be used for plain key listings.
3358 * Sets the matched key's user id field (pk->user_id) to the user id
3359 * that matched the low-level search criteria or NULL.
3361 * If R_FLAGS is not NULL set certain flags for more detailed error
3362 * reporting. Used flags are:
3364 * - LOOKUP_ALL_SUBKEYS_EXPIRED :: All Subkeys are expired or have
3366 * - LOOKUP_NOT_SELECTED :: No suitable key found
3368 * This function needs to handle several different cases:
3370 * 1. No requested usage and no primary key requested
3371 * Examples for this case are that we have a keyID to be used
3372 * for decrytion or verification.
3373 * 2. No usage but primary key requested
3374 * This is the case for all functions which work on an
3375 * entire keyblock, e.g. for editing or listing
3376 * 3. Usage and primary key requested
3378 * 4. Usage but no primary key requested
3383 finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact,
3384 unsigned int *r_flags)
3388 /* If WANT_EXACT is set, the key or subkey that actually matched the
3389 low-level search criteria. */
3390 kbnode_t foundk = NULL;
3391 /* The user id (if any) that matched the low-level search criteria. */
3392 PKT_user_id *foundu = NULL;
3395 kbnode_t latest_key;
3398 u32 curtime = make_timestamp ();
3403 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
3404 req_usage &= USAGE_MASK;
3406 /* Request the primary if we're certifying another key, and also if
3407 * signing data while --pgp6 or --pgp7 is on since pgp 6 and 7 do
3408 * not understand signatures made by a signing subkey. PGP 8 does. */
3409 req_prim = ((req_usage & PUBKEY_USAGE_CERT)
3410 || ((PGP6 || PGP7) && (req_usage & PUBKEY_USAGE_SIG)));
3413 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
3415 /* For an exact match mark the primary or subkey that matched the
3416 low-level search criteria. */
3419 for (k = keyblock; k; k = k->next)
3423 log_assert (k->pkt->pkttype == PKT_PUBLIC_KEY
3424 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3426 pk = k->pkt->pkt.public_key;
3427 pk->flags.exact = 1;
3433 /* Get the user id that matched that low-level search criteria. */
3434 for (k = keyblock; k; k = k->next)
3438 log_assert (k->pkt->pkttype == PKT_USER_ID);
3439 foundu = k->pkt->pkt.user_id;
3445 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
3446 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
3447 foundk ? "one" : "all", req_usage);
3451 latest_key = foundk ? foundk : keyblock;
3457 /* Set LATEST_KEY to the latest (the one with the most recent
3458 * timestamp) good (valid, not revoked, not expired, etc.) subkey.
3460 * Don't bother if we are only looking for a primary key or we need
3461 * an exact match and the exact match is not a subkey. */
3462 if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
3468 int n_revoked_or_expired = 0;
3470 /* Either start a loop or check just this one subkey. */
3471 for (k = foundk ? foundk : keyblock; k; k = nextk)
3475 /* If FOUNDK is not NULL, then only consider that exact
3476 key, i.e., don't iterate. */
3482 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3485 pk = k->pkt->pkt.public_key;
3487 log_debug ("\tchecking subkey %08lX\n",
3488 (ulong) keyid_from_pk (pk, NULL));
3490 if (!pk->flags.valid)
3493 log_debug ("\tsubkey not valid\n");
3496 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3499 log_debug ("\tusage does not match: want=%x have=%x\n",
3500 req_usage, pk->pubkey_usage);
3505 if (pk->flags.revoked)
3508 log_debug ("\tsubkey has been revoked\n");
3509 n_revoked_or_expired++;
3512 if (pk->has_expired)
3515 log_debug ("\tsubkey has expired\n");
3516 n_revoked_or_expired++;
3519 if (pk->timestamp > curtime && !opt.ignore_valid_from)
3522 log_debug ("\tsubkey not yet valid\n");
3527 log_debug ("\tsubkey might be fine\n");
3528 /* In case a key has a timestamp of 0 set, we make sure
3529 that it is used. A better change would be to compare
3530 ">=" but that might also change the selected keys and
3531 is as such a more intrusive change. */
3532 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
3534 latest_date = pk->timestamp;
3538 if (n_subkeys == n_revoked_or_expired && r_flags)
3539 *r_flags |= LOOKUP_ALL_SUBKEYS_EXPIRED;
3542 /* Check if the primary key is ok (valid, not revoke, not expire,
3543 * matches requested usage) if:
3545 * - we didn't find an appropriate subkey and we're not doing an
3548 * - we're doing an exact match and the exact match was the
3551 * - we're just considering the primary key. */
3552 if ((!latest_key && !want_exact) || foundk == keyblock || req_prim)
3554 if (DBG_LOOKUP && !foundk && !req_prim)
3555 log_debug ("\tno suitable subkeys found - trying primary\n");
3556 pk = keyblock->pkt->pkt.public_key;
3557 if (!pk->flags.valid)
3560 log_debug ("\tprimary key not valid\n");
3562 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3565 log_debug ("\tprimary key usage does not match: "
3566 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
3568 else if (pk->flags.revoked)
3571 log_debug ("\tprimary key has been revoked\n");
3573 else if (pk->has_expired)
3576 log_debug ("\tprimary key has expired\n");
3581 log_debug ("\tprimary key may be used\n");
3582 latest_key = keyblock;
3589 log_debug ("\tno suitable key found - giving up\n");
3591 *r_flags |= LOOKUP_NOT_SELECTED;
3592 return NULL; /* Not found. */
3597 log_debug ("\tusing key %08lX\n",
3598 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
3602 pk = latest_key->pkt->pkt.public_key;
3603 free_user_id (pk->user_id);
3604 pk->user_id = scopy_user_id (foundu);
3607 if (latest_key != keyblock && opt.verbose)
3610 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
3611 log_info (_("using subkey %s instead of primary key %s\n"),
3612 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
3616 cache_user_id (keyblock);
3618 return latest_key ? latest_key : keyblock; /* Found. */
3622 /* Print a KEY_CONSIDERED status line. */
3624 print_status_key_considered (kbnode_t keyblock, unsigned int flags)
3626 char hexfpr[2*MAX_FINGERPRINT_LEN + 1];
3630 if (!is_status_enabled ())
3633 for (node=keyblock; node; node = node->next)
3634 if (node->pkt->pkttype == PKT_PUBLIC_KEY
3635 || node->pkt->pkttype == PKT_SECRET_KEY)
3639 log_error ("%s: keyblock w/o primary key\n", __func__);
3643 hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr);
3644 snprintf (flagbuf, sizeof flagbuf, " %u", flags);
3645 write_status_strings (STATUS_KEY_CONSIDERED, hexfpr, flagbuf, NULL);
3650 /* A high-level function to lookup keys.
3652 This function builds on top of the low-level keydb API. It first
3653 searches the database using the description stored in CTX->ITEMS,
3654 then it filters the results using CTX and, finally, if WANT_SECRET
3655 is set, it ignores any keys for which no secret key is available.
3657 Unlike the low-level search functions, this function also merges
3658 all of the self-signed data into the keys, subkeys and user id
3659 packets (see the merge_selfsigs for details).
3661 On success the key's keyblock is stored at *RET_KEYBLOCK, and the
3662 specific subkey is stored at *RET_FOUND_KEY. Note that we do not
3663 return a reference in *RET_FOUND_KEY, i.e. the result must not be
3664 freed using 'release_kbnode', and it is only valid until
3665 *RET_KEYBLOCK is deallocated. Therefore, if RET_FOUND_KEY is not
3666 NULL, then RET_KEYBLOCK must not be NULL. */
3668 lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, kbnode_t *ret_found_key,
3672 int no_suitable_key = 0;
3673 KBNODE keyblock = NULL;
3674 KBNODE found_key = NULL;
3675 unsigned int infoflags;
3677 log_assert (ret_found_key == NULL || ret_keyblock != NULL);
3679 *ret_keyblock = NULL;
3683 rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
3687 /* If we are iterating over the entire database, then we need to
3688 change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
3689 reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next
3691 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
3692 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
3694 rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
3697 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
3701 if (want_secret && agent_probe_any_secret_key (NULL, keyblock))
3702 goto skip; /* No secret key available. */
3704 /* Warning: node flag bits 0 and 1 should be preserved by
3705 * merge_selfsigs. */
3706 merge_selfsigs (keyblock);
3707 found_key = finish_lookup (keyblock, ctx->req_usage, ctx->exact,
3709 print_status_key_considered (keyblock, infoflags);
3712 no_suitable_key = 0;
3717 no_suitable_key = 1;
3721 /* Release resources and continue search. */
3722 release_kbnode (keyblock);
3724 /* The keyblock cache ignores the current "file position".
3725 Thus, if we request the next result and the cache matches
3726 (and it will since it is what we just looked for), we'll get
3727 the same entry back! We can avoid this infinite loop by
3728 disabling the cache. */
3729 keydb_disable_caching (ctx->kr_handle);
3733 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
3734 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
3740 *ret_keyblock = keyblock; /* Return the keyblock. */
3744 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
3745 rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
3746 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
3747 rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
3749 release_kbnode (keyblock);
3754 *ret_found_key = found_key;
3756 *ret_found_key = NULL;
3763 /* Enumerate some secret keys (specifically, those specified with
3764 * --default-key and --try-secret-key). Use the following procedure:
3766 * 1) Initialize a void pointer to NULL
3767 * 2) Pass a reference to this pointer to this function (content)
3768 * and provide space for the secret key (sk)
3769 * 3) Call this function as long as it does not return an error (or
3770 * until you are done). The error code GPG_ERR_EOF indicates the
3771 * end of the listing.
3772 * 4) Call this function a last time with SK set to NULL,
3773 * so that can free it's context.
3778 * PKT_public_key *sk = xmalloc_clear (sizeof (*sk));
3780 * while ((err = enum_secret_keys (&ctx, sk)))
3784 * free_public_key (sk);
3785 * sk = xmalloc_clear (sizeof (*sk));
3788 * // Release any resources used by CTX.
3789 * enum_secret_keys (&ctx, NULL);
3790 * free_public_key (sk);
3792 * if (gpg_err_code (err) != GPG_ERR_EOF)
3793 * ; // An error occurred.
3796 enum_secret_keys (ctrl_t ctrl, void **context, PKT_public_key *sk)
3798 gpg_error_t err = 0;
3813 /* Make a new context. */
3814 c = xtrycalloc (1, sizeof *c);
3816 return gpg_error_from_syserror ();
3822 /* Free the context. */
3823 release_kbnode (c->keyblock);
3824 getkey_end (c->ctx);
3831 return gpg_error (GPG_ERR_EOF);
3835 /* Loop until we have a keyblock. */
3836 while (!c->keyblock)
3838 /* Loop over the list of secret keys. */
3845 case 0: /* First try to use the --default-key. */
3846 name = parse_def_secret_key (ctrl);
3850 case 1: /* Init list of keys to try. */
3851 c->sl = opt.secret_keys_to_try;
3855 case 2: /* Get next item from list. */
3859 c->sl = c->sl->next;
3865 case 3: /* Init search context to enum all secret keys. */
3866 err = getkey_bynames (&c->ctx, NULL, NULL, 1, &keyblock);
3869 release_kbnode (keyblock);
3871 getkey_end (c->ctx);
3877 case 4: /* Get next item from the context. */
3880 err = getkey_next (c->ctx, NULL, &keyblock);
3883 release_kbnode (keyblock);
3885 getkey_end (c->ctx);
3893 default: /* No more names to check - stop. */
3895 return gpg_error (GPG_ERR_EOF);
3898 while ((!name || !*name) && !keyblock);
3901 c->node = c->keyblock = keyblock;
3904 err = getkey_byname (ctrl, NULL, NULL, name, 1, &c->keyblock);
3907 /* getkey_byname might return a keyblock even in the
3908 error case - I have not checked. Thus better release
3910 release_kbnode (c->keyblock);
3914 c->node = c->keyblock;
3918 /* Get the next key from the current keyblock. */
3919 for (; c->node; c->node = c->node->next)
3921 if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
3922 || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3924 copy_public_key (sk, c->node->pkt->pkt.public_key);
3925 c->node = c->node->next;
3926 return 0; /* Found. */
3930 /* Dispose the keyblock and continue. */
3931 release_kbnode (c->keyblock);
3937 /*********************************************
3938 *********** User ID printing helpers *******
3939 *********************************************/
3941 /* Return a string with a printable representation of the user_id.
3942 * this string must be freed by xfree. */
3944 get_user_id_string (u32 * keyid, int mode, size_t *r_len)
3951 /* Try it two times; second pass reads from the database. */
3954 for (r = user_id_db; r; r = r->next)
3956 for (a = r->keyids; a; a = a->next)
3958 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
3962 /* An empty string as user id is possible. Make
3963 sure that the malloc allocates one byte and
3964 does not bail out. */
3965 p = xmalloc (r->len? r->len : 1);
3966 memcpy (p, r->name, r->len);
3973 p = xasprintf ("%08lX%08lX %.*s",
3974 (ulong) keyid[0], (ulong) keyid[1],
3977 p = xasprintf ("%s %.*s", keystr (keyid),
3980 *r_len = strlen (p);
3988 while (++pass < 2 && !get_pubkey (NULL, keyid));
3991 p = xstrdup (user_id_not_found_utf8 ());
3993 p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
3995 p = xasprintf ("%s [?]", keystr (keyid));
3998 *r_len = strlen (p);
4004 get_user_id_string_native (u32 * keyid)
4006 char *p = get_user_id_string (keyid, 0, NULL);
4007 char *p2 = utf8_to_native (p, strlen (p), 0);
4014 get_long_user_id_string (u32 * keyid)
4016 return get_user_id_string (keyid, 1, NULL);
4020 /* Please try to use get_user_byfpr instead of this one. */
4022 get_user_id (u32 * keyid, size_t * rn)
4024 return get_user_id_string (keyid, 2, rn);
4028 /* Please try to use get_user_id_byfpr_native instead of this one. */
4030 get_user_id_native (u32 * keyid)
4033 char *p = get_user_id (keyid, &rn);
4034 char *p2 = utf8_to_native (p, rn, 0);
4040 /* Return the user id for a key designated by its fingerprint, FPR,
4041 which must be MAX_FINGERPRINT_LEN bytes in size. Note: the
4042 returned string, which must be freed using xfree, may not be NUL
4043 terminated. To determine the length of the string, you must use
4046 get_user_id_byfpr (const byte *fpr, size_t *rn)
4052 /* Try it two times; second pass reads from the database. */
4055 for (r = user_id_db; r; r = r->next)
4058 for (a = r->keyids; a; a = a->next)
4060 if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
4062 /* An empty string as user id is possible. Make
4063 sure that the malloc allocates one byte and does
4065 p = xmalloc (r->len? r->len : 1);
4066 memcpy (p, r->name, r->len);
4074 && !get_pubkey_byfprint (NULL, NULL, fpr, MAX_FINGERPRINT_LEN));
4075 p = xstrdup (user_id_not_found_utf8 ());
4080 /* Like get_user_id_byfpr, but convert the string to the native
4081 encoding. The returned string needs to be freed. Unlike
4082 get_user_id_byfpr, the returned string is NUL terminated. */
4084 get_user_id_byfpr_native (const byte *fpr)
4087 char *p = get_user_id_byfpr (fpr, &rn);
4088 char *p2 = utf8_to_native (p, rn, 0);
4094 /* Return the database handle used by this context. The context still
4097 get_ctx_handle (GETKEY_CTX ctx)
4099 return ctx->kr_handle;
4103 free_akl (struct akl *akl)
4109 free_keyserver_spec (akl->spec);
4117 while (opt.auto_key_locate)
4119 struct akl *akl2 = opt.auto_key_locate;
4120 opt.auto_key_locate = opt.auto_key_locate->next;
4125 /* Returns false on error. */
4127 parse_auto_key_locate (char *options)
4131 while ((tok = optsep (&options)))
4133 struct akl *akl, *check, *last = NULL;
4139 akl = xmalloc_clear (sizeof (*akl));
4141 if (ascii_strcasecmp (tok, "clear") == 0)
4144 free_akl (opt.auto_key_locate);
4145 opt.auto_key_locate = NULL;
4148 else if (ascii_strcasecmp (tok, "nodefault") == 0)
4149 akl->type = AKL_NODEFAULT;
4150 else if (ascii_strcasecmp (tok, "local") == 0)
4151 akl->type = AKL_LOCAL;
4152 else if (ascii_strcasecmp (tok, "ldap") == 0)
4153 akl->type = AKL_LDAP;
4154 else if (ascii_strcasecmp (tok, "keyserver") == 0)
4155 akl->type = AKL_KEYSERVER;
4156 else if (ascii_strcasecmp (tok, "cert") == 0)
4157 akl->type = AKL_CERT;
4158 else if (ascii_strcasecmp (tok, "pka") == 0)
4159 akl->type = AKL_PKA;
4160 else if (ascii_strcasecmp (tok, "dane") == 0)
4161 akl->type = AKL_DANE;
4162 else if (ascii_strcasecmp (tok, "wkd") == 0)
4163 akl->type = AKL_WKD;
4164 else if ((akl->spec = parse_keyserver_uri (tok, 1)))
4165 akl->type = AKL_SPEC;
4172 /* We must maintain the order the user gave us */
4173 for (check = opt.auto_key_locate; check;
4174 last = check, check = check->next)
4176 /* Check for duplicates */
4177 if (check->type == akl->type
4178 && (akl->type != AKL_SPEC
4179 || (akl->type == AKL_SPEC
4180 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
4193 opt.auto_key_locate = akl;
4201 /* Returns true if a secret key is available for the public key with
4202 key id KEYID; returns false if not. This function ignores legacy
4203 keys. Note: this is just a fast check and does not tell us whether
4204 the secret key is valid; this check merely indicates whether there
4205 is some secret key with the specified key id. */
4207 have_secret_key_with_kid (u32 *keyid)
4211 KEYDB_SEARCH_DESC desc;
4216 kdbhd = keydb_new ();
4219 memset (&desc, 0, sizeof desc);
4220 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
4221 desc.u.kid[0] = keyid[0];
4222 desc.u.kid[1] = keyid[1];
4225 err = keydb_search (kdbhd, &desc, 1, NULL);
4229 err = keydb_get_keyblock (kdbhd, &keyblock);
4232 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
4236 for (node = keyblock; node; node = node->next)
4238 /* Bit 0 of the flags is set if the search found the key
4239 using that key or subkey. Note: a search will only ever
4240 match a single key or subkey. */
4241 if ((node->flag & 1))
4243 log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY
4244 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
4246 if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
4247 result = 1; /* Secret key available. */
4254 release_kbnode (keyblock);
4257 keydb_release (kdbhd);