1 /* getkey.c - Get a key from the database
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3 * 2007, 2008, 2010 Free Software Foundation, Inc.
4 * Copyright (C) 2015 g10 Code GmbH
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <http://www.gnu.org/licenses/>.
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,
152 for (i = 0; i < DIM (lkup_stats); i++)
154 if (lkup_stats[i].any)
155 es_fprintf (es_stderr,
156 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
158 lkup_stats[i].okay_count,
159 lkup_stats[i].nokey_count, lkup_stats[i].error_count);
165 /* Cache a copy of a public key in the public key cache. PK is not
166 * cached if caching is disabled (via getkey_disable_caches), if
167 * PK->FLAGS.DONT_CACHE is set, we don't know how to derive a key id
168 * from the public key (e.g., unsupported algorithm), or a key with
169 * the key id is already in the cache.
171 * The public key packet is copied into the cache using
172 * copy_public_key. Thus, any secret parts are not copied, for
175 * This cache is filled by get_pubkey and is read by get_pubkey and
176 * get_pubkey_fast. */
178 cache_public_key (PKT_public_key * pk)
180 #if MAX_PK_CACHE_ENTRIES
181 pk_cache_entry_t ce, ce2;
184 if (pk_cache_disabled)
187 if (pk->flags.dont_cache)
190 if (is_ELGAMAL (pk->pubkey_algo)
191 || pk->pubkey_algo == PUBKEY_ALGO_DSA
192 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
193 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
194 || pk->pubkey_algo == PUBKEY_ALGO_ECDH
195 || is_RSA (pk->pubkey_algo))
197 keyid_from_pk (pk, keyid);
200 return; /* Don't know how to get the keyid. */
202 for (ce = pk_cache; ce; ce = ce->next)
203 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
206 log_debug ("cache_public_key: already in cache\n");
210 if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
214 /* Remove the last 50% of the entries. */
215 for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
217 if (ce && ce != pk_cache && ce->next)
225 free_public_key (ce->pk);
230 log_assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
233 ce = xmalloc (sizeof *ce);
236 ce->pk = copy_public_key (NULL, pk);
237 ce->keyid[0] = keyid[0];
238 ce->keyid[1] = keyid[1];
243 /* Return a const utf-8 string with the text "[User ID not found]".
244 This function is required so that we don't need to switch gettext's
245 encoding temporary. */
247 user_id_not_found_utf8 (void)
252 text = native_to_utf8 (_("[User ID not found]"));
258 /* Return the user ID from the given keyblock.
259 * We use the primary uid flag which has been set by the merge_selfsigs
260 * function. The returned value is only valid as long as the given
261 * keyblock is not changed. */
263 get_primary_uid (KBNODE keyblock, size_t * uidlen)
268 for (k = keyblock; k; k = k->next)
270 if (k->pkt->pkttype == PKT_USER_ID
271 && !k->pkt->pkt.user_id->attrib_data
272 && k->pkt->pkt.user_id->is_primary)
274 *uidlen = k->pkt->pkt.user_id->len;
275 return k->pkt->pkt.user_id->name;
278 s = user_id_not_found_utf8 ();
279 *uidlen = strlen (s);
285 release_keyid_list (keyid_list_t k)
289 keyid_list_t k2 = k->next;
296 * Store the association of keyid and userid
297 * Feed only public keys to this function.
300 cache_user_id (KBNODE keyblock)
305 keyid_list_t keyids = NULL;
308 for (k = keyblock; k; k = k->next)
310 if (k->pkt->pkttype == PKT_PUBLIC_KEY
311 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
313 keyid_list_t a = xmalloc_clear (sizeof *a);
314 /* Hmmm: For a long list of keyids it might be an advantage
315 * to append the keys. */
316 fingerprint_from_pk (k->pkt->pkt.public_key, a->fpr, NULL);
317 keyid_from_pk (k->pkt->pkt.public_key, a->keyid);
318 /* First check for duplicates. */
319 for (r = user_id_db; r; r = r->next)
323 for (b = r->keyids; b; b = b->next)
325 if (!memcmp (b->fpr, a->fpr, MAX_FINGERPRINT_LEN))
328 log_debug ("cache_user_id: already in cache\n");
329 release_keyid_list (keyids);
335 /* Now put it into the cache. */
341 BUG (); /* No key no fun. */
344 uid = get_primary_uid (keyblock, &uidlen);
346 if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES)
348 /* fixme: use another algorithm to free some cache slots */
350 user_id_db = r->next;
351 release_keyid_list (r->keyids);
355 r = xmalloc (sizeof *r + uidlen - 1);
358 memcpy (r->name, uid, r->len);
359 r->next = user_id_db;
365 /* Disable and drop the public key cache (which is filled by
366 cache_public_key and get_pubkey). Note: there is currently no way
367 to reenable this cache. */
369 getkey_disable_caches ()
371 #if MAX_PK_CACHE_ENTRIES
373 pk_cache_entry_t ce, ce2;
375 for (ce = pk_cache; ce; ce = ce2)
378 free_public_key (ce->pk);
381 pk_cache_disabled = 1;
382 pk_cache_entries = 0;
386 /* fixme: disable user id cache ? */
391 pubkey_free (pubkey_t key)
396 release_kbnode (key->keyblock);
402 pubkeys_free (pubkey_t keys)
406 pubkey_t next = keys->next;
412 /* Returns all keys that match the search specfication SEARCH_TERMS.
414 This function also checks for and warns about duplicate entries in
415 the keydb, which can occur if the user has configured multiple
416 keyrings or keyboxes or if a keyring or keybox was corrupted.
418 Note: SEARCH_TERMS will not be expanded (i.e., it may not be a
421 USE is the operation for which the key is required. It must be
422 either PUBKEY_USAGE_ENC, PUBKEY_USAGE_SIG, PUBKEY_USAGE_CERT or
425 XXX: Currently, only PUBKEY_USAGE_ENC and PUBKEY_USAGE_SIG are
428 INCLUDE_UNUSABLE indicates whether disabled keys are allowed.
429 (Recipients specified with --encrypt-to and --hidden-encrypt-to may
430 be disabled. It is possible to edit disabled keys.)
432 SOURCE is the context in which SEARCH_TERMS was specified, e.g.,
433 "--encrypt-to", etc. If this function is called interactively,
434 then this should be NULL.
436 If WARN_POSSIBLY_AMBIGUOUS is set, then emits a warning if the user
437 does not specify a long key id or a fingerprint.
439 The results are placed in *KEYS. *KEYS must be NULL! */
441 get_pubkeys (ctrl_t ctrl,
442 char *search_terms, int use, int include_unusable, char *source,
443 int warn_possibly_ambiguous,
446 /* We show a warning when a key appears multiple times in the DB.
447 This can happen for two reasons:
449 - The user has configured multiple keyrings or keyboxes.
451 - The keyring or keybox has been corrupted in some way, e.g., a
452 bug or a random process changing them.
454 For each duplicate, we only want to show the key once. Hence,
456 static strlist_t key_dups;
458 /* USE transformed to a string. */
463 KEYDB_SEARCH_DESC desc;
466 pubkey_t results = NULL;
471 char fingerprint[2 * MAX_FINGERPRINT_LEN + 1];
476 log_debug ("%s: Checking %s=%s\n",
477 __func__, source ? source : "user input", search_terms);
481 log_bug ("%s: KEYS should be NULL!\n", __func__);
485 case PUBKEY_USAGE_ENC: use_str = "encrypt"; break;
486 case PUBKEY_USAGE_SIG: use_str = "sign"; break;
487 case PUBKEY_USAGE_CERT: use_str = "cetify"; break;
488 case PUBKEY_USAGE_AUTH: use_str = "authentication"; break;
489 default: log_bug ("%s: Bad value for USE (%d)\n", __func__, use);
492 if (use == PUBKEY_USAGE_CERT || use == PUBKEY_USAGE_AUTH)
493 log_bug ("%s: use=%s is unimplemented.\n", __func__, use_str);
495 err = classify_user_id (search_terms, &desc, 1);
498 log_info (_("key \"%s\" not found: %s\n"),
499 search_terms, gpg_strerror (err));
500 if (!opt.quiet && source)
501 log_info (_("(check argument of option '%s')\n"), source);
505 if (warn_possibly_ambiguous
506 && ! (desc.mode == KEYDB_SEARCH_MODE_LONG_KID
507 || desc.mode == KEYDB_SEARCH_MODE_FPR16
508 || desc.mode == KEYDB_SEARCH_MODE_FPR20
509 || desc.mode == KEYDB_SEARCH_MODE_FPR))
511 log_info (_("Warning: '%s' should be a long key ID or a fingerprint\n"),
513 if (!opt.quiet && source)
514 log_info (_("(check argument of option '%s')\n"), source);
517 /* Gather all of the results. */
522 PKT_public_key *pk = xmalloc_clear (sizeof *pk);
527 err = get_pubkey_byname (ctrl, &ctx, pk, search_terms, &kb, NULL,
528 include_unusable, 1);
530 err = getkey_next (ctx, pk, &kb);
532 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
533 /* No more results. */
539 /* An error (other than "not found"). */
541 log_error (_("error looking up: %s\n"),
547 /* Another result! */
550 r = xmalloc_clear (sizeof (*r));
561 log_debug ("%s resulted in %d matches.\n", search_terms, count);
562 for (r = results; r; r = r->next)
564 hexfingerprint (r->keyblock->pkt->pkt.public_key,
565 fingerprint, sizeof (fingerprint)));
568 if (! results && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
572 log_debug ("%s: '%s' not found.\n", __func__, search_terms);
574 log_info (_("key \"%s\" not found\n"), search_terms);
575 if (!opt.quiet && source)
576 log_info (_("(check argument of option '%s')\n"), source);
580 else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
581 /* No more matches. */
584 /* Some other error. An error message was already printed
585 out. Free RESULTS and continue. */
588 /* Check for duplicates. */
590 log_debug ("%s: Checking results of %s='%s' for dups\n",
591 __func__, source ? source : "user input", search_terms);
593 for (r = results; r; r = r->next)
604 if (cmp_public_keys (r->keyblock->pkt->pkt.public_key,
605 r2->keyblock->pkt->pkt.public_key) != 0)
616 /* Remove R2 from the list. */
618 release_kbnode (r2->keyblock);
625 hexfingerprint (r->keyblock->pkt->pkt.public_key,
626 fingerprint, sizeof fingerprint);
627 if (! strlist_find (key_dups, fingerprint))
629 char fingerprint_formatted[MAX_FORMATTED_FINGERPRINT_LEN + 1];
631 log_info (_("Warning: %s appears in the keyring %d times\n"),
632 format_hexfingerprint (fingerprint,
633 fingerprint_formatted,
634 sizeof fingerprint_formatted),
636 add_to_strlist (&key_dups, fingerprint);
641 if (DBG_LOOKUP && count)
643 log_debug ("After removing %d dups:\n", count);
644 for (r = results, count = 0; r; r = r->next)
645 log_debug (" %d: %s\n",
647 hexfingerprint (r->keyblock->pkt->pkt.public_key,
648 fingerprint, sizeof fingerprint));
653 pubkeys_free (results);
662 pk_from_block (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE keyblock,
665 KBNODE a = found_key ? found_key : keyblock;
669 log_assert (a->pkt->pkttype == PKT_PUBLIC_KEY
670 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
672 copy_public_key (pk, a->pkt->pkt.public_key);
676 /* Return the public key with the key id KEYID and store it at PK.
677 * The resources in *PK should be released using
678 * release_public_key_parts(). This function also stores a copy of
679 * the public key in the user id cache (see cache_public_key).
681 * If PK is NULL, this function just stores the public key in the
682 * cache and returns the usual return code.
684 * PK->REQ_USAGE (which is a mask of PUBKEY_USAGE_SIG,
685 * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT) is passed through to the
686 * lookup function. If this is non-zero, only keys with the specified
687 * usage will be returned. As such, it is essential that
688 * PK->REQ_USAGE be correctly initialized!
690 * Returns 0 on success, GPG_ERR_NO_PUBKEY if there is no public key
691 * with the specified key id, or another error code if an error
694 * If the data was not read from the cache, then the self-signed data
695 * has definitely been merged into the public key using
698 get_pubkey (PKT_public_key * pk, u32 * keyid)
703 #if MAX_PK_CACHE_ENTRIES
706 /* Try to get it from the cache. We don't do this when pk is
707 NULL as it does not guarantee that the user IDs are
710 for (ce = pk_cache; ce; ce = ce->next)
712 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
713 /* XXX: We don't check PK->REQ_USAGE here, but if we don't
714 read from the cache, we do check it! */
716 copy_public_key (pk, ce->pk);
722 /* More init stuff. */
725 pk = xmalloc_clear (sizeof *pk);
732 struct getkey_ctx_s ctx;
734 KBNODE found_key = NULL;
735 memset (&ctx, 0, sizeof ctx);
736 ctx.exact = 1; /* Use the key ID exactly as given. */
737 ctx.not_allocated = 1;
738 ctx.kr_handle = keydb_new ();
741 rc = gpg_error_from_syserror ();
745 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
746 ctx.items[0].u.kid[0] = keyid[0];
747 ctx.items[0].u.kid[1] = keyid[1];
748 ctx.req_usage = pk->req_usage;
749 rc = lookup (&ctx, &kb, &found_key, 0);
752 pk_from_block (&ctx, pk, kb, found_key);
760 rc = GPG_ERR_NO_PUBKEY;
764 cache_public_key (pk);
766 free_public_key (pk);
771 /* Similar to get_pubkey, but it does not take PK->REQ_USAGE into
772 * account nor does it merge in the self-signed data. This function
773 * also only considers primary keys. It is intended to be used as a
774 * quick check of the key to avoid recursion. It should only be used
775 * in very certain cases. Like get_pubkey and unlike any of the other
776 * lookup functions, this function also consults the user id cache
777 * (see cache_public_key).
779 * Return the public key in *PK. The resources in *PK should be
780 * released using release_public_key_parts(). */
782 get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
790 #if MAX_PK_CACHE_ENTRIES
792 /* Try to get it from the cache */
795 for (ce = pk_cache; ce; ce = ce->next)
797 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]
798 /* Only consider primary keys. */
799 && ce->pk->keyid[0] == ce->pk->main_keyid[0]
800 && ce->pk->keyid[1] == ce->pk->main_keyid[1])
803 copy_public_key (pk, ce->pk);
812 return gpg_error_from_syserror ();
813 rc = keydb_search_kid (hd, keyid);
814 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
817 return GPG_ERR_NO_PUBKEY;
819 rc = keydb_get_keyblock (hd, &keyblock);
823 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
824 return GPG_ERR_NO_PUBKEY;
827 log_assert (keyblock && keyblock->pkt
828 && keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
830 /* We return the primary key. If KEYID matched a subkey, then we
832 keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
833 if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
834 copy_public_key (pk, keyblock->pkt->pkt.public_key);
836 rc = GPG_ERR_NO_PUBKEY;
838 release_kbnode (keyblock);
840 /* Not caching key here since it won't have all of the fields
847 /* Return the key block for the key with key id KEYID or NULL, if an
848 * error occurs. Use release_kbnode() to release the key block.
850 * The self-signed data has already been merged into the public key
851 * using merge_selfsigs. */
853 get_pubkeyblock (u32 * keyid)
855 struct getkey_ctx_s ctx;
857 KBNODE keyblock = NULL;
859 memset (&ctx, 0, sizeof ctx);
860 /* No need to set exact here because we want the entire block. */
861 ctx.not_allocated = 1;
862 ctx.kr_handle = keydb_new ();
866 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
867 ctx.items[0].u.kid[0] = keyid[0];
868 ctx.items[0].u.kid[1] = keyid[1];
869 rc = lookup (&ctx, &keyblock, NULL, 0);
872 return rc ? NULL : keyblock;
876 /* Return the public key with the key id KEYID iff the secret key is
877 * available and store it at PK. The resources should be released
878 * using release_public_key_parts().
880 * Unlike other lookup functions, PK may not be NULL. PK->REQ_USAGE
881 * is passed through to the lookup function and is a mask of
882 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. Thus, it
883 * must be valid! If this is non-zero, only keys with the specified
884 * usage will be returned.
886 * Returns 0 on success. If a public key with the specified key id is
887 * not found or a secret key is not available for that public key, an
888 * error code is returned. Note: this function ignores legacy keys.
889 * An error code is also return if an error occurs.
891 * The self-signed data has already been merged into the public key
892 * using merge_selfsigs. */
894 get_seckey (PKT_public_key *pk, u32 *keyid)
897 struct getkey_ctx_s ctx;
898 kbnode_t keyblock = NULL;
899 kbnode_t found_key = NULL;
901 memset (&ctx, 0, sizeof ctx);
902 ctx.exact = 1; /* Use the key ID exactly as given. */
903 ctx.not_allocated = 1;
904 ctx.kr_handle = keydb_new ();
906 return gpg_error_from_syserror ();
908 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
909 ctx.items[0].u.kid[0] = keyid[0];
910 ctx.items[0].u.kid[1] = keyid[1];
911 ctx.req_usage = pk->req_usage;
912 err = lookup (&ctx, &keyblock, &found_key, 1);
915 pk_from_block (&ctx, pk, keyblock, found_key);
918 release_kbnode (keyblock);
922 err = agent_probe_secret_key (/*ctrl*/NULL, pk);
924 release_public_key_parts (pk);
931 /* Skip unusable keys. A key is unusable if it is revoked, expired or
932 disabled or if the selected user id is revoked or expired. */
934 skip_unusable (void *dummy, u32 * keyid, int uid_no)
942 keyblock = get_pubkeyblock (keyid);
945 log_error ("error checking usability status of %s\n", keystr (keyid));
949 pk = keyblock->pkt->pkt.public_key;
951 /* Is the key revoked or expired? */
952 if (pk->flags.revoked || pk->has_expired)
955 /* Is the user ID in question revoked or expired? */
956 if (!unusable && uid_no)
961 for (node = keyblock; node; node = node->next)
963 if (node->pkt->pkttype == PKT_USER_ID)
965 PKT_user_id *user_id = node->pkt->pkt.user_id;
968 if (uids_seen != uid_no)
971 if (user_id->is_revoked || user_id->is_expired)
978 /* If UID_NO is non-zero, then the keyblock better have at least
980 log_assert (uids_seen == uid_no);
984 unusable = pk_is_disabled (pk);
987 release_kbnode (keyblock);
992 /* Search for keys matching some criteria.
994 If RETCTX is not NULL, then the constructed context is returned in
995 *RETCTX so that getpubkey_next can be used to get subsequent
996 results. In this case, getkey_end() must be used to free the
997 search context. If RETCTX is not NULL, then RET_KDBHD must be
1000 If NAMELIST is not NULL, then a search query is constructed using
1001 classify_user_id on each of the strings in the list. (Recall: the
1002 database does an OR of the terms, not an AND.) If NAMELIST is
1003 NULL, then all results are returned.
1005 If PK is not NULL, the public key of the first result is returned
1006 in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
1007 set, it is used to filter the search results. See the
1008 documentation for finish_lookup to understand exactly how this is
1009 used. Note: The self-signed data has already been merged into the
1010 public key using merge_selfsigs. Free *PK by calling
1011 release_public_key_parts (or, if PK was allocated using xfree, you
1012 can use free_public_key, which calls release_public_key_parts(PK)
1013 and then xfree(PK)).
1015 If WANT_SECRET is set, then only keys with an available secret key
1016 (either locally or via key registered on a smartcard) are returned.
1018 If INCLUDE_UNUSABLE is set, then unusable keys (see the
1019 documentation for skip_unusable for an exact definition) are
1020 skipped unless they are looked up by key id or by fingerprint.
1022 If RET_KB is not NULL, the keyblock is returned in *RET_KB. This
1023 should be freed using release_kbnode().
1025 If RET_KDBHD is not NULL, then the new database handle used to
1026 conduct the search is returned in *RET_KDBHD. This can be used to
1027 get subsequent results using keydb_search_next. Note: in this
1028 case, no advanced filtering is done for subsequent results (e.g.,
1029 WANT_SECRET and PK->REQ_USAGE are not respected).
1031 This function returns 0 on success. Otherwise, an error code is
1032 returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1033 (if want_secret is set) is returned if the key is not found. */
1035 key_byname (GETKEY_CTX *retctx, strlist_t namelist,
1037 int want_secret, int include_unusable,
1038 KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
1044 KBNODE help_kb = NULL;
1045 KBNODE found_key = NULL;
1049 /* Reset the returned context in case of error. */
1050 log_assert (!ret_kdbhd); /* Not allowed because the handle is stored
1058 /* No search terms: iterate over the whole DB. */
1060 ctx = xmalloc_clear (sizeof *ctx);
1062 ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
1063 if (!include_unusable)
1064 ctx->items[0].skipfnc = skip_unusable;
1068 /* Build the search context. */
1069 for (n = 0, r = namelist; r; r = r->next)
1072 /* CTX has space for a single search term at the end. Thus, we
1073 need to allocate sizeof *CTX plus (n - 1) sizeof
1075 ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
1078 for (n = 0, r = namelist; r; r = r->next, n++)
1082 err = classify_user_id (r->d, &ctx->items[n], 1);
1084 if (ctx->items[n].exact)
1089 return gpg_err_code (err); /* FIXME: remove gpg_err_code. */
1091 if (!include_unusable
1092 && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
1093 && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
1094 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
1095 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
1096 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
1097 ctx->items[n].skipfnc = skip_unusable;
1101 ctx->want_secret = want_secret;
1102 ctx->kr_handle = keydb_new ();
1103 if (!ctx->kr_handle)
1105 rc = gpg_error_from_syserror ();
1115 ctx->req_usage = pk->req_usage;
1118 rc = lookup (ctx, ret_kb, &found_key, want_secret);
1121 pk_from_block (ctx, pk, *ret_kb, found_key);
1124 release_kbnode (help_kb);
1126 if (retctx) /* Caller wants the context. */
1132 *ret_kdbhd = ctx->kr_handle;
1133 ctx->kr_handle = NULL;
1142 /* Find a public key identified by NAME.
1144 * If name appears to be a valid valid RFC822 mailbox (i.e., email
1145 * address) and auto key lookup is enabled (no_akl == 0), then the
1146 * specified auto key lookup methods (--auto-key-lookup) are used to
1147 * import the key into the local keyring. Otherwise, just the local
1148 * keyring is consulted.
1150 * If RETCTX is not NULL, then the constructed context is returned in
1151 * *RETCTX so that getpubkey_next can be used to get subsequent
1152 * results. In this case, getkey_end() must be used to free the
1153 * search context. If RETCTX is not NULL, then RET_KDBHD must be
1156 * If PK is not NULL, the public key of the first result is returned
1157 * in *PK. Note: PK->REQ_USAGE must be valid!!! PK->REQ_USAGE is
1158 * passed through to the lookup function and is a mask of
1159 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this
1160 * is non-zero, only keys with the specified usage will be returned.
1161 * Note: The self-signed data has already been merged into the public
1162 * key using merge_selfsigs. Free *PK by calling
1163 * release_public_key_parts (or, if PK was allocated using xfree, you
1164 * can use free_public_key, which calls release_public_key_parts(PK)
1165 * and then xfree(PK)).
1167 * NAME is a string, which is turned into a search query using
1170 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
1171 * *RET_KEYBLOCK. This should be freed using release_kbnode().
1173 * If RET_KDBHD is not NULL, then the new database handle used to
1174 * conduct the search is returned in *RET_KDBHD. This can be used to
1175 * get subsequent results using keydb_search_next or to modify the
1176 * returned record. Note: in this case, no advanced filtering is done
1177 * for subsequent results (e.g., PK->REQ_USAGE is not respected).
1178 * Unlike RETCTX, this is always returned.
1180 * If INCLUDE_UNUSABLE is set, then unusable keys (see the
1181 * documentation for skip_unusable for an exact definition) are
1182 * skipped unless they are looked up by key id or by fingerprint.
1184 * If NO_AKL is set, then the auto key locate functionality is
1185 * disabled and only the local key ring is considered. Note: the
1186 * local key ring is consulted even if local is not in the
1187 * --auto-key-locate option list!
1189 * This function returns 0 on success. Otherwise, an error code is
1190 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1191 * (if want_secret is set) is returned if the key is not found. */
1193 get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
1194 const char *name, KBNODE * ret_keyblock,
1195 KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
1198 strlist_t namelist = NULL;
1202 int anylocalfirst = 0;
1207 /* Does NAME appear to be a mailbox (mail address)? */
1208 is_mbox = is_valid_mailbox (name);
1210 /* The auto-key-locate feature works as follows: there are a number
1211 of methods to look up keys. By default, the local keyring is
1212 tried first. Then, each method listed in the --auto-key-locate is
1213 tried in the order it appears.
1215 This can be changed as follows:
1217 - if nodefault appears anywhere in the list of options, then
1218 the local keyring is not tried first, or,
1220 - if local appears anywhere in the list of options, then the
1221 local keyring is not tried first, but in the order in which
1222 it was listed in the --auto-key-locate option.
1224 Note: we only save the search context in RETCTX if the local
1225 method is the first method tried (either explicitly or
1228 /* auto-key-locate is enabled. */
1230 /* nodefault is true if "nodefault" or "local" appear. */
1231 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1232 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
1237 /* anylocalfirst is true if "local" appears before any other
1238 search methods (except "nodefault"). */
1239 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1240 if (akl->type != AKL_NODEFAULT)
1242 if (akl->type == AKL_LOCAL)
1249 /* "nodefault" didn't occur. Thus, "local" is implicitly the
1250 first method to try. */
1253 if (nodefault && is_mbox)
1254 /* Either "nodefault" or "local" (explicitly) appeared in the auto
1255 key locate list and NAME appears to be an email address. Don't
1256 try the local keyring. */
1258 rc = GPG_ERR_NO_PUBKEY;
1261 /* Either "nodefault" and "local" don't appear in the auto key
1262 locate list (in which case we try the local keyring first) or
1263 NAME does not appear to be an email address (in which case we
1264 only try the local keyring). In this case, lookup NAME in the
1267 add_to_strlist (&namelist, name);
1268 rc = key_byname (retctx, namelist, pk, 0,
1269 include_unusable, ret_keyblock, ret_kdbhd);
1272 /* If the requested name resembles a valid mailbox and automatic
1273 retrieval has been enabled, we try to import the key. */
1274 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && !no_akl && is_mbox)
1275 /* NAME wasn't present in the local keyring (or we didn't try the
1276 local keyring). Since the auto key locate feature is enabled
1277 and NAME appears to be an email address, try the auto locate
1280 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1282 unsigned char *fpr = NULL;
1284 int did_akl_local = 0;
1285 int no_fingerprint = 0;
1286 const char *mechanism = "?";
1291 /* This is a dummy mechanism. */
1293 rc = GPG_ERR_NO_PUBKEY;
1297 mechanism = "Local";
1301 getkey_end (*retctx);
1304 add_to_strlist (&namelist, name);
1305 rc = key_byname (anylocalfirst ? retctx : NULL,
1307 include_unusable, ret_keyblock, ret_kdbhd);
1311 mechanism = "DNS CERT";
1312 glo_ctrl.in_auto_key_retrieve++;
1313 rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len);
1314 glo_ctrl.in_auto_key_retrieve--;
1319 glo_ctrl.in_auto_key_retrieve++;
1320 rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
1321 glo_ctrl.in_auto_key_retrieve--;
1326 glo_ctrl.in_auto_key_retrieve++;
1327 rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len);
1328 glo_ctrl.in_auto_key_retrieve--;
1333 glo_ctrl.in_auto_key_retrieve++;
1334 rc = keyserver_import_wkd (ctrl, name, &fpr, &fpr_len);
1335 glo_ctrl.in_auto_key_retrieve--;
1340 glo_ctrl.in_auto_key_retrieve++;
1341 rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
1342 glo_ctrl.in_auto_key_retrieve--;
1346 /* Strictly speaking, we don't need to only use a valid
1347 mailbox for the getname search, but it helps cut down
1348 on the problem of searching for something like "john"
1349 and getting a whole lot of keys back. */
1350 if (keyserver_any_configured (ctrl))
1352 mechanism = "keyserver";
1353 glo_ctrl.in_auto_key_retrieve++;
1354 rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
1356 glo_ctrl.in_auto_key_retrieve--;
1360 mechanism = "Unconfigured keyserver";
1361 rc = GPG_ERR_NO_PUBKEY;
1367 struct keyserver_spec *keyserver;
1369 mechanism = akl->spec->uri;
1370 keyserver = keyserver_match (akl->spec);
1371 glo_ctrl.in_auto_key_retrieve++;
1372 rc = keyserver_import_name (ctrl,
1373 name, &fpr, &fpr_len, keyserver);
1374 glo_ctrl.in_auto_key_retrieve--;
1379 /* Use the fingerprint of the key that we actually fetched.
1380 This helps prevent problems where the key that we fetched
1381 doesn't have the same name that we used to fetch it. In
1382 the case of CERT and PKA, this is an actual security
1383 requirement as the URL might point to a key put in by an
1384 attacker. By forcing the use of the fingerprint, we
1385 won't use the attacker's key here. */
1388 char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
1390 log_assert (fpr_len <= MAX_FINGERPRINT_LEN);
1392 free_strlist (namelist);
1395 bin2hex (fpr, fpr_len, fpr_string);
1398 log_info ("auto-key-locate found fingerprint %s\n",
1401 add_to_strlist (&namelist, fpr_string);
1403 else if (!rc && !fpr && !did_akl_local)
1404 { /* The acquisition method said no failure occurred, but
1405 it didn't return a fingerprint. That's a failure. */
1407 rc = GPG_ERR_NO_PUBKEY;
1412 if (!rc && !did_akl_local)
1413 { /* There was no error and we didn't do a local lookup.
1414 This means that we imported a key into the local
1415 keyring. Try to read the imported key from the
1419 getkey_end (*retctx);
1422 rc = key_byname (anylocalfirst ? retctx : NULL,
1424 include_unusable, ret_keyblock, ret_kdbhd);
1429 log_info (_("automatically retrieved '%s' via %s\n"),
1433 if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1434 || opt.verbose || no_fingerprint)
1435 log_info (_("error retrieving '%s' via %s: %s\n"),
1437 no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
1444 getkey_end (*retctx);
1448 if (retctx && *retctx)
1450 log_assert (!(*retctx)->extra_list);
1451 (*retctx)->extra_list = namelist;
1454 free_strlist (namelist);
1460 /* Lookup a key with the specified fingerprint.
1462 * If PK is not NULL, the public key of the first result is returned
1463 * in *PK. Note: this function does an exact search and thus the
1464 * returned public key may be a subkey rather than the primary key.
1465 * Note: The self-signed data has already been merged into the public
1466 * key using merge_selfsigs. Free *PK by calling
1467 * release_public_key_parts (or, if PK was allocated using xfree, you
1468 * can use free_public_key, which calls release_public_key_parts(PK)
1469 * and then xfree(PK)).
1471 * If PK->REQ_USAGE is set, it is used to filter the search results.
1472 * (Thus, if PK is not NULL, PK->REQ_USAGE must be valid!!!) See the
1473 * documentation for finish_lookup to understand exactly how this is
1476 * If R_KEYBLOCK is not NULL, then the first result's keyblock is
1477 * returned in *R_KEYBLOCK. This should be freed using
1480 * FPRINT is a byte array whose contents is the fingerprint to use as
1481 * the search term. FPRINT_LEN specifies the length of the
1482 * fingerprint (in bytes). Currently, only 16 and 20-byte
1483 * fingerprints are supported.
1485 * FIXME: We should replace this with the _byname function. This can
1486 * be done by creating a userID conforming to the unified fingerprint
1489 get_pubkey_byfprint (PKT_public_key *pk, kbnode_t *r_keyblock,
1490 const byte * fprint, size_t fprint_len)
1497 if (fprint_len == 20 || fprint_len == 16)
1499 struct getkey_ctx_s ctx;
1501 KBNODE found_key = NULL;
1503 memset (&ctx, 0, sizeof ctx);
1505 ctx.not_allocated = 1;
1506 ctx.kr_handle = keydb_new ();
1508 return gpg_error_from_syserror ();
1511 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1512 : KEYDB_SEARCH_MODE_FPR20;
1513 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1514 rc = lookup (&ctx, &kb, &found_key, 0);
1516 pk_from_block (&ctx, pk, kb, found_key);
1517 if (!rc && r_keyblock)
1522 release_kbnode (kb);
1526 rc = GPG_ERR_GENERAL; /* Oops */
1531 /* This function is similar to get_pubkey_byfprint, but it doesn't
1532 * merge the self-signed data into the public key and subkeys or into
1533 * the user ids. It also doesn't add the key to the user id cache.
1534 * Further, this function ignores PK->REQ_USAGE.
1536 * This function is intended to avoid recursion and, as such, should
1537 * only be used in very specific situations.
1539 * Like get_pubkey_byfprint, PK may be NULL. In that case, this
1540 * function effectively just checks for the existence of the key. */
1542 get_pubkey_byfprint_fast (PKT_public_key * pk,
1543 const byte * fprint, size_t fprint_len)
1548 byte fprbuf[MAX_FINGERPRINT_LEN];
1551 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1552 fprbuf[i] = fprint[i];
1553 while (i < MAX_FINGERPRINT_LEN)
1558 return gpg_error_from_syserror ();
1560 rc = keydb_search_fpr (hd, fprbuf);
1561 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1564 return GPG_ERR_NO_PUBKEY;
1566 rc = keydb_get_keyblock (hd, &keyblock);
1570 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1571 return GPG_ERR_NO_PUBKEY;
1574 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1575 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1577 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1578 release_kbnode (keyblock);
1580 /* Not caching key here since it won't have all of the fields
1587 parse_def_secret_key (ctrl_t ctrl)
1589 KEYDB_HANDLE hd = NULL;
1593 for (t = opt.def_secret_key; t; t = t->next)
1596 KEYDB_SEARCH_DESC desc;
1600 err = classify_user_id (t->d, &desc, 1);
1603 log_error (_("secret key \"%s\" not found: %s\n"),
1604 t->d, gpg_strerror (err));
1606 log_info (_("(check argument of option '%s')\n"), "--default-key");
1617 keydb_search_reset (hd);
1620 err = keydb_search (hd, &desc, 1, NULL);
1621 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1626 log_error (_("key \"%s\" not found: %s\n"), t->d, gpg_strerror (err));
1631 err = keydb_get_keyblock (hd, &kb);
1634 log_error (_("error reading keyblock: %s\n"),
1635 gpg_strerror (err));
1639 merge_selfsigs (kb);
1641 err = gpg_error (GPG_ERR_NO_SECKEY);
1645 PKT_public_key *pk = node->pkt->pkt.public_key;
1647 /* Check that the key has the signing capability. */
1648 if (! (pk->pubkey_usage & PUBKEY_USAGE_SIG))
1651 /* Check if the key is valid. */
1652 if (pk->flags.revoked)
1655 log_debug ("not using %s as default key, %s",
1656 keystr_from_pk (pk), "revoked");
1659 if (pk->has_expired)
1662 log_debug ("not using %s as default key, %s",
1663 keystr_from_pk (pk), "expired");
1666 if (pk_is_disabled (pk))
1669 log_debug ("not using %s as default key, %s",
1670 keystr_from_pk (pk), "disabled");
1674 err = agent_probe_secret_key (ctrl, pk);
1676 /* This is a valid key. */
1679 while ((node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY)));
1681 release_kbnode (kb);
1684 if (! warned && ! opt.quiet)
1686 log_info (_("Warning: not using '%s' as default key: %s\n"),
1687 t->d, gpg_strerror (GPG_ERR_NO_SECKEY));
1688 print_reported_error (err, GPG_ERR_NO_SECKEY);
1693 if (! warned && ! opt.quiet)
1694 log_info (_("using \"%s\" as default secret key for signing\n"),
1700 if (! warned && opt.def_secret_key && ! t)
1701 log_info (_("all values passed to '%s' ignored\n"),
1715 /* Look up a secret key.
1717 * If PK is not NULL, the public key of the first result is returned
1718 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
1719 * set, it is used to filter the search results. See the
1720 * documentation for finish_lookup to understand exactly how this is
1721 * used. Note: The self-signed data has already been merged into the
1722 * public key using merge_selfsigs. Free *PK by calling
1723 * release_public_key_parts (or, if PK was allocated using xfree, you
1724 * can use free_public_key, which calls release_public_key_parts(PK)
1725 * and then xfree(PK)).
1727 * If --default-key was set, then the specified key is looked up. (In
1728 * this case, the default key is returned even if it is considered
1729 * unusable. See the documentation for skip_unusable for exactly what
1732 * Otherwise, this initiates a DB scan that returns all keys that are
1733 * usable (see previous paragraph for exactly what usable means) and
1734 * for which a secret key is available.
1736 * This function returns the first match. Additional results can be
1737 * returned using getkey_next. */
1739 get_seckey_default (ctrl_t ctrl, PKT_public_key *pk)
1742 strlist_t namelist = NULL;
1743 int include_unusable = 1;
1746 const char *def_secret_key = parse_def_secret_key (ctrl);
1748 add_to_strlist (&namelist, def_secret_key);
1750 include_unusable = 0;
1752 err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
1754 free_strlist (namelist);
1761 /* Search for keys matching some criteria.
1763 * If RETCTX is not NULL, then the constructed context is returned in
1764 * *RETCTX so that getpubkey_next can be used to get subsequent
1765 * results. In this case, getkey_end() must be used to free the
1766 * search context. If RETCTX is not NULL, then RET_KDBHD must be
1769 * If PK is not NULL, the public key of the first result is returned
1770 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
1771 * set, it is used to filter the search results. See the
1772 * documentation for finish_lookup to understand exactly how this is
1773 * used. Note: The self-signed data has already been merged into the
1774 * public key using merge_selfsigs. Free *PK by calling
1775 * release_public_key_parts (or, if PK was allocated using xfree, you
1776 * can use free_public_key, which calls release_public_key_parts(PK)
1777 * and then xfree(PK)).
1779 * If NAMES is not NULL, then a search query is constructed using
1780 * classify_user_id on each of the strings in the list. (Recall: the
1781 * database does an OR of the terms, not an AND.) If NAMES is
1782 * NULL, then all results are returned.
1784 * If WANT_SECRET is set, then only keys with an available secret key
1785 * (either locally or via key registered on a smartcard) are returned.
1787 * This function does not skip unusable keys (see the documentation
1788 * for skip_unusable for an exact definition).
1790 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
1791 * *RET_KEYBLOCK. This should be freed using release_kbnode().
1793 * This function returns 0 on success. Otherwise, an error code is
1794 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1795 * (if want_secret is set) is returned if the key is not found. */
1797 getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
1798 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
1800 return key_byname (retctx, names, pk, want_secret, 1,
1801 ret_keyblock, NULL);
1805 /* Search for one key matching some criteria.
1807 * If RETCTX is not NULL, then the constructed context is returned in
1808 * *RETCTX so that getpubkey_next can be used to get subsequent
1809 * results. In this case, getkey_end() must be used to free the
1810 * search context. If RETCTX is not NULL, then RET_KDBHD must be
1813 * If PK is not NULL, the public key of the first result is returned
1814 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
1815 * set, it is used to filter the search results. See the
1816 * documentation for finish_lookup to understand exactly how this is
1817 * used. Note: The self-signed data has already been merged into the
1818 * public key using merge_selfsigs. Free *PK by calling
1819 * release_public_key_parts (or, if PK was allocated using xfree, you
1820 * can use free_public_key, which calls release_public_key_parts(PK)
1821 * and then xfree(PK)).
1823 * If NAME is not NULL, then a search query is constructed using
1824 * classify_user_id on the string. In this case, even unusable keys
1825 * (see the documentation for skip_unusable for an exact definition of
1826 * unusable) are returned. Otherwise, if --default-key was set, then
1827 * that key is returned (even if it is unusable). If neither of these
1828 * conditions holds, then the first usable key is returned.
1830 * If WANT_SECRET is set, then only keys with an available secret key
1831 * (either locally or via key registered on a smartcard) are returned.
1833 * This function does not skip unusable keys (see the documentation
1834 * for skip_unusable for an exact definition).
1836 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
1837 * *RET_KEYBLOCK. This should be freed using release_kbnode().
1839 * This function returns 0 on success. Otherwise, an error code is
1840 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1841 * (if want_secret is set) is returned if the key is not found.
1843 * FIXME: We also have the get_pubkey_byname function which has a
1844 * different semantic. Should be merged with this one. */
1846 getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
1847 const char *name, int want_secret, kbnode_t *ret_keyblock)
1850 strlist_t namelist = NULL;
1851 int with_unusable = 1;
1852 const char *def_secret_key = NULL;
1854 if (want_secret && !name)
1855 def_secret_key = parse_def_secret_key (ctrl);
1857 if (want_secret && !name && def_secret_key)
1858 add_to_strlist (&namelist, def_secret_key);
1860 add_to_strlist (&namelist, name);
1864 err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
1865 ret_keyblock, NULL);
1867 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
1868 WANT_SECRET has been used. */
1870 free_strlist (namelist);
1876 /* Return the next search result.
1878 * If PK is not NULL, the public key of the next result is returned in
1879 * *PK. Note: The self-signed data has already been merged into the
1880 * public key using merge_selfsigs. Free *PK by calling
1881 * release_public_key_parts (or, if PK was allocated using xfree, you
1882 * can use free_public_key, which calls release_public_key_parts(PK)
1883 * and then xfree(PK)).
1885 * RET_KEYBLOCK can be given as NULL; if it is not NULL it the entire
1886 * found keyblock wis retruned hich must be released with
1887 * release_kbnode. If the function returns an error NULL is stored at
1890 * The self-signed data has already been merged into the public key
1891 * using merge_selfsigs. */
1893 getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
1895 int rc; /* Fixme: Make sure this is proper gpg_error */
1896 KBNODE found_key = NULL;
1898 /* We need to disable the caching so that for an exact key search we
1899 won't get the result back from the cache and thus end up in an
1900 endless loop. The endless loop can occur, because the cache is
1901 used without respecting the current file pointer! */
1902 keydb_disable_caching (ctx->kr_handle);
1904 rc = lookup (ctx, ret_keyblock, &found_key, ctx->want_secret);
1905 if (!rc && pk && ret_keyblock)
1906 pk_from_block (ctx, pk, *ret_keyblock, found_key);
1912 /* Release any resources used by a key listing context. This must be
1913 * called on the context returned by, e.g., getkey_byname. */
1915 getkey_end (getkey_ctx_t ctx)
1919 keydb_release (ctx->kr_handle);
1920 free_strlist (ctx->extra_list);
1921 if (!ctx->not_allocated)
1928 /************************************************
1929 ************* Merging stuff ********************
1930 ************************************************/
1932 /* Set the mainkey_id fields for all keys in KEYBLOCK. This is
1933 * usually done by merge_selfsigs but at some places we only need the
1934 * main_kid not a full merge. The function also guarantees that all
1935 * pk->keyids are computed. */
1937 setup_main_keyids (kbnode_t keyblock)
1939 u32 kid[2], mainkid[2];
1940 kbnode_t kbctx, node;
1943 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1945 pk = keyblock->pkt->pkt.public_key;
1947 keyid_from_pk (pk, mainkid);
1948 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1950 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
1951 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1953 pk = node->pkt->pkt.public_key;
1954 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
1955 if (!pk->main_keyid[0] && !pk->main_keyid[1])
1957 pk->main_keyid[0] = mainkid[0];
1958 pk->main_keyid[1] = mainkid[1];
1964 /* KEYBLOCK corresponds to a public key block. This function merges
1965 * much of the information from the self-signed data into the public
1966 * key, public subkey and user id data structures. If you use the
1967 * high-level search API (e.g., get_pubkey) for looking up key blocks,
1968 * then you don't need to call this function. This function is
1969 * useful, however, if you change the keyblock, e.g., by adding or
1970 * removing a self-signed data packet. */
1972 merge_keys_and_selfsig (KBNODE keyblock)
1976 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
1977 merge_selfsigs (keyblock);
1979 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
1984 parse_key_usage (PKT_signature * sig)
1991 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
1994 /* First octet of the keyflags. */
1999 key_usage |= PUBKEY_USAGE_CERT;
2005 key_usage |= PUBKEY_USAGE_SIG;
2009 /* We do not distinguish between encrypting communications and
2010 encrypting storage. */
2011 if (flags & (0x04 | 0x08))
2013 key_usage |= PUBKEY_USAGE_ENC;
2014 flags &= ~(0x04 | 0x08);
2019 key_usage |= PUBKEY_USAGE_AUTH;
2024 key_usage |= PUBKEY_USAGE_UNKNOWN;
2027 key_usage |= PUBKEY_USAGE_NONE;
2029 else if (p) /* Key flags of length zero. */
2030 key_usage |= PUBKEY_USAGE_NONE;
2032 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
2033 capability that we do not handle. This serves to distinguish
2034 between a zero key usage which we handle as the default
2035 capabilities for that algorithm, and a usage that we do not
2036 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
2037 key_flags have been given but they do not specify any usage. */
2043 /* Apply information from SIGNODE (which is the valid self-signature
2044 * associated with that UID) to the UIDNODE:
2045 * - weather the UID has been revoked
2046 * - assumed creation date of the UID
2047 * - temporary store the keyflags here
2048 * - temporary store the key expiration time here
2049 * - mark whether the primary user ID flag hat been set.
2050 * - store the preferences
2053 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
2055 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
2056 PKT_signature *sig = signode->pkt->pkt.signature;
2057 const byte *p, *sym, *hash, *zip;
2058 size_t n, nsym, nhash, nzip;
2060 sig->flags.chosen_selfsig = 1;/* We chose this one. */
2061 uid->created = 0; /* Not created == invalid. */
2062 if (IS_UID_REV (sig))
2064 uid->is_revoked = 1;
2065 return; /* Has been revoked. */
2068 uid->is_revoked = 0;
2070 uid->expiredate = sig->expiredate;
2072 if (sig->flags.expired)
2074 uid->is_expired = 1;
2075 return; /* Has expired. */
2078 uid->is_expired = 0;
2080 uid->created = sig->timestamp; /* This one is okay. */
2081 uid->selfsigversion = sig->version;
2082 /* If we got this far, it's not expired :) */
2083 uid->is_expired = 0;
2085 /* Store the key flags in the helper variable for later processing. */
2086 uid->help_key_usage = parse_key_usage (sig);
2088 /* Ditto for the key expiration. */
2089 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2090 if (p && buf32_to_u32 (p))
2091 uid->help_key_expire = keycreated + buf32_to_u32 (p);
2093 uid->help_key_expire = 0;
2095 /* Set the primary user ID flag - we will later wipe out some
2096 * of them to only have one in our keyblock. */
2097 uid->is_primary = 0;
2098 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
2100 uid->is_primary = 2;
2102 /* We could also query this from the unhashed area if it is not in
2103 * the hased area and then later try to decide which is the better
2104 * there should be no security problem with this.
2105 * For now we only look at the hashed one. */
2107 /* Now build the preferences list. These must come from the
2108 hashed section so nobody can modify the ciphers a key is
2109 willing to accept. */
2110 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
2113 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
2116 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
2121 n = nsym + nhash + nzip;
2126 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
2128 for (; nsym; nsym--, n++)
2130 uid->prefs[n].type = PREFTYPE_SYM;
2131 uid->prefs[n].value = *sym++;
2133 for (; nhash; nhash--, n++)
2135 uid->prefs[n].type = PREFTYPE_HASH;
2136 uid->prefs[n].value = *hash++;
2138 for (; nzip; nzip--, n++)
2140 uid->prefs[n].type = PREFTYPE_ZIP;
2141 uid->prefs[n].value = *zip++;
2143 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
2144 uid->prefs[n].value = 0;
2147 /* See whether we have the MDC feature. */
2149 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
2150 if (p && n && (p[0] & 0x01))
2153 /* And the keyserver modify flag. */
2154 uid->flags.ks_modify = 1;
2155 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
2156 if (p && n && (p[0] & 0x80))
2157 uid->flags.ks_modify = 0;
2161 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
2163 rinfo->date = sig->timestamp;
2164 rinfo->algo = sig->pubkey_algo;
2165 rinfo->keyid[0] = sig->keyid[0];
2166 rinfo->keyid[1] = sig->keyid[1];
2170 /* Given a keyblock, parse the key block and extract various pieces of
2171 information and save them with the primary key packet and the user
2172 id packets. For instance, some information is stored in signature
2173 packets. We find the latest such valid packet (since the user can
2174 change that information) and copy its contents into the
2177 Note that R_REVOKED may be set to 0, 1 or 2.
2179 This function fills in the following fields in the primary key's
2182 main_keyid (computed)
2183 revkey / numrevkeys (derived from self signed key data)
2184 flags.valid (whether we have at least 1 self-sig)
2185 flags.maybe_revoked (whether a designed revoked the key, but
2186 we are missing the key to check the sig)
2187 selfsigversion (highest version of any valid self-sig)
2188 pubkey_usage (derived from most recent self-sig or most
2190 has_expired (various sources)
2191 expiredate (various sources)
2193 See the documentation for fixup_uidnode for how the user id packets
2194 are modified. In addition to that the primary user id's is_primary
2195 field is set to 1 and the other user id's is_primary are set to
2198 merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
2199 struct revoke_info *rinfo)
2201 PKT_public_key *pk = NULL;
2204 u32 sigdate, uiddate, uiddate2;
2205 KBNODE signode, uidnode, uidnode2;
2206 u32 curtime = make_timestamp ();
2207 unsigned int key_usage = 0;
2208 u32 keytimestamp = 0;
2210 int key_expire_seen = 0;
2211 byte sigversion = 0;
2214 memset (rinfo, 0, sizeof (*rinfo));
2216 /* Section 11.1 of RFC 4880 determines the order of packets within a
2217 message. There are three sections, which must occur in the
2218 following order: the public key, the user ids and user attributes
2219 and the subkeys. Within each section, each primary packet (e.g.,
2220 a user id packet) is followed by one or more signature packets,
2221 which modify that packet. */
2223 /* According to Section 11.1 of RFC 4880, the public key must be the
2225 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2226 /* parse_keyblock_image ensures that the first packet is the
2229 pk = keyblock->pkt->pkt.public_key;
2230 keytimestamp = pk->timestamp;
2232 keyid_from_pk (pk, kid);
2233 pk->main_keyid[0] = kid[0];
2234 pk->main_keyid[1] = kid[1];
2236 if (pk->version < 4)
2238 /* Before v4 the key packet itself contains the expiration date
2239 * and there was no way to change it, so we start with the one
2240 * from the key packet. */
2241 key_expire = pk->max_expiredate;
2242 key_expire_seen = 1;
2247 - Find the latest direct key self-signature. We assume that the
2248 newest one overrides all others.
2250 - Determine whether the key has been revoked.
2252 - Gather all revocation keys (unlike other data, we don't just
2253 take them from the latest self-signed packet).
2255 - Determine max (sig[...]->version).
2258 /* Reset this in case this key was already merged. */
2264 sigdate = 0; /* Helper variable to find the latest signature. */
2266 /* According to Section 11.1 of RFC 4880, the public key comes first
2267 and is immediately followed by any signature packets that modify
2270 k && k->pkt->pkttype != PKT_USER_ID
2271 && k->pkt->pkttype != PKT_ATTRIBUTE
2272 && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2275 if (k->pkt->pkttype == PKT_SIGNATURE)
2277 PKT_signature *sig = k->pkt->pkt.signature;
2278 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2281 if (check_key_signature (keyblock, k, NULL))
2282 ; /* Signature did not verify. */
2283 else if (IS_KEY_REV (sig))
2285 /* Key has been revoked - there is no way to
2286 * override such a revocation, so we theoretically
2287 * can stop now. We should not cope with expiration
2288 * times for revocations here because we have to
2289 * assume that an attacker can generate all kinds of
2290 * signatures. However due to the fact that the key
2291 * has been revoked it does not harm either and by
2292 * continuing we gather some more info on that
2295 sig_to_revoke_info (sig, rinfo);
2297 else if (IS_KEY_SIG (sig))
2299 /* Add the indicated revocations keys from all
2300 signatures not just the latest. We do this
2301 because you need multiple 1F sigs to properly
2302 handle revocation keys (PGP does it this way, and
2303 a revocation key could be sensitive and hence in
2304 a different signature). */
2310 xrealloc (pk->revkey, sizeof (struct revocation_key) *
2311 (pk->numrevkeys + sig->numrevkeys));
2313 for (i = 0; i < sig->numrevkeys; i++)
2314 memcpy (&pk->revkey[pk->numrevkeys++],
2316 sizeof (struct revocation_key));
2319 if (sig->timestamp >= sigdate)
2320 /* This is the latest signature so far. */
2322 if (sig->flags.expired)
2323 ; /* Signature has expired - ignore it. */
2326 sigdate = sig->timestamp;
2328 if (sig->version > sigversion)
2329 sigversion = sig->version;
2338 /* Remove dupes from the revocation keys. */
2341 int i, j, x, changed = 0;
2343 for (i = 0; i < pk->numrevkeys; i++)
2345 for (j = i + 1; j < pk->numrevkeys; j++)
2347 if (memcmp (&pk->revkey[i], &pk->revkey[j],
2348 sizeof (struct revocation_key)) == 0)
2352 for (x = j; x < pk->numrevkeys - 1; x++)
2353 pk->revkey[x] = pk->revkey[x + 1];
2363 pk->revkey = xrealloc (pk->revkey,
2365 sizeof (struct revocation_key));
2369 /* SIGNODE is the 1F signature packet with the latest creation
2370 time. Extract some information from it. */
2372 /* Some information from a direct key signature take precedence
2373 * over the same information given in UID sigs. */
2374 PKT_signature *sig = signode->pkt->pkt.signature;
2377 key_usage = parse_key_usage (sig);
2379 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2380 if (p && buf32_to_u32 (p))
2382 key_expire = keytimestamp + buf32_to_u32 (p);
2383 key_expire_seen = 1;
2386 /* Mark that key as valid: One direct key signature should
2387 * render a key as valid. */
2388 pk->flags.valid = 1;
2391 /* Pass 1.5: Look for key revocation signatures that were not made
2392 by the key (i.e. did a revocation key issue a revocation for
2393 us?). Only bother to do this if there is a revocation key in the
2394 first place and we're not revoked already. */
2396 if (!*r_revoked && pk->revkey)
2397 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
2399 if (k->pkt->pkttype == PKT_SIGNATURE)
2401 PKT_signature *sig = k->pkt->pkt.signature;
2403 if (IS_KEY_REV (sig) &&
2404 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
2406 int rc = check_revocation_keys (pk, sig);
2410 sig_to_revoke_info (sig, rinfo);
2411 /* Don't continue checking since we can't be any
2412 more revoked than this. */
2415 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2416 pk->flags.maybe_revoked = 1;
2418 /* A failure here means the sig did not verify, was
2419 not issued by a revocation key, or a revocation
2420 key loop was broken. If a revocation key isn't
2421 findable, however, the key might be revoked and
2422 we don't know it. */
2424 /* TODO: In the future handle subkey and cert
2425 revocations? PGP doesn't, but it's in 2440. */
2430 /* Second pass: Look at the self-signature of all user IDs. */
2432 /* According to RFC 4880 section 11.1, user id and attribute packets
2433 are in the second section, after the public key packet and before
2434 the subkey packets. */
2435 signode = uidnode = NULL;
2436 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
2437 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2439 if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
2440 /* New user id packet. */
2442 if (uidnode && signode)
2443 /* Apply the data from the most recent self-signed packet
2444 to the preceding user id packet. */
2446 fixup_uidnode (uidnode, signode, keytimestamp);
2447 pk->flags.valid = 1;
2449 /* Clear SIGNODE. The only relevant self-signed data for
2450 UIDNODE follows it. */
2451 if (k->pkt->pkttype == PKT_USER_ID)
2458 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2460 PKT_signature *sig = k->pkt->pkt.signature;
2461 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2463 if (check_key_signature (keyblock, k, NULL))
2464 ; /* signature did not verify */
2465 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
2466 && sig->timestamp >= sigdate)
2468 /* Note: we allow to invalidate cert revocations
2469 * by a newer signature. An attacker can't use this
2470 * because a key should be revoked with a key revocation.
2471 * The reason why we have to allow for that is that at
2472 * one time an email address may become invalid but later
2473 * the same email address may become valid again (hired,
2474 * fired, hired again). */
2476 sigdate = sig->timestamp;
2478 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2479 if (sig->version > sigversion)
2480 sigversion = sig->version;
2485 if (uidnode && signode)
2487 fixup_uidnode (uidnode, signode, keytimestamp);
2488 pk->flags.valid = 1;
2491 /* If the key isn't valid yet, and we have
2492 --allow-non-selfsigned-uid set, then force it valid. */
2493 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
2496 log_info (_("Invalid key %s made valid by"
2497 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
2498 pk->flags.valid = 1;
2501 /* The key STILL isn't valid, so try and find an ultimately
2502 trusted signature. */
2503 if (!pk->flags.valid)
2507 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2510 if (k->pkt->pkttype == PKT_USER_ID)
2512 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2514 PKT_signature *sig = k->pkt->pkt.signature;
2516 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
2518 PKT_public_key *ultimate_pk;
2520 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
2522 /* We don't want to use the full get_pubkey to
2523 avoid infinite recursion in certain cases.
2524 There is no reason to check that an ultimately
2525 trusted key is still valid - if it has been
2526 revoked the user should also remove the
2527 ultimate trust flag. */
2528 if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
2529 && check_key_signature2 (keyblock, k, ultimate_pk,
2530 NULL, NULL, NULL, NULL) == 0
2531 && get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
2533 free_public_key (ultimate_pk);
2534 pk->flags.valid = 1;
2538 free_public_key (ultimate_pk);
2544 /* Record the highest selfsig version so we know if this is a v3
2545 key through and through, or a v3 key with a v4 selfsig
2546 somewhere. This is useful in a few places to know if the key
2547 must be treated as PGP2-style or OpenPGP-style. Note that a
2548 selfsig revocation with a higher version number will also raise
2549 this value. This is okay since such a revocation must be
2550 issued by the user (i.e. it cannot be issued by someone else to
2551 modify the key behavior.) */
2553 pk->selfsigversion = sigversion;
2555 /* Now that we had a look at all user IDs we can now get some information
2556 * from those user IDs.
2561 /* Find the latest user ID with key flags set. */
2562 uiddate = 0; /* Helper to find the latest user ID. */
2563 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2566 if (k->pkt->pkttype == PKT_USER_ID)
2568 PKT_user_id *uid = k->pkt->pkt.user_id;
2569 if (uid->help_key_usage && uid->created > uiddate)
2571 key_usage = uid->help_key_usage;
2572 uiddate = uid->created;
2579 /* No key flags at all: get it from the algo. */
2580 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
2584 /* Check that the usage matches the usage as given by the algo. */
2585 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
2586 if (x) /* Mask it down to the actual allowed usage. */
2590 /* Whatever happens, it's a primary key, so it can certify. */
2591 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
2593 if (!key_expire_seen)
2595 /* Find the latest valid user ID with a key expiration set
2596 * Note, that this may be a different one from the above because
2597 * some user IDs may have no expiration date set. */
2599 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2602 if (k->pkt->pkttype == PKT_USER_ID)
2604 PKT_user_id *uid = k->pkt->pkt.user_id;
2605 if (uid->help_key_expire && uid->created > uiddate)
2607 key_expire = uid->help_key_expire;
2608 uiddate = uid->created;
2614 /* Currently only v3 keys have a maximum expiration date, but I'll
2615 bet v5 keys get this feature again. */
2617 || (pk->max_expiredate && key_expire > pk->max_expiredate))
2618 key_expire = pk->max_expiredate;
2620 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
2621 pk->expiredate = key_expire;
2623 /* Fixme: we should see how to get rid of the expiretime fields but
2624 * this needs changes at other places too. */
2626 /* And now find the real primary user ID and delete all others. */
2627 uiddate = uiddate2 = 0;
2628 uidnode = uidnode2 = NULL;
2629 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2631 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
2633 PKT_user_id *uid = k->pkt->pkt.user_id;
2634 if (uid->is_primary)
2636 if (uid->created > uiddate)
2638 uiddate = uid->created;
2641 else if (uid->created == uiddate && uidnode)
2643 /* The dates are equal, so we need to do a
2644 different (and arbitrary) comparison. This
2645 should rarely, if ever, happen. It's good to
2646 try and guarantee that two different GnuPG
2647 users with two different keyrings at least pick
2648 the same primary. */
2649 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
2655 if (uid->created > uiddate2)
2657 uiddate2 = uid->created;
2660 else if (uid->created == uiddate2 && uidnode2)
2662 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
2670 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2673 if (k->pkt->pkttype == PKT_USER_ID &&
2674 !k->pkt->pkt.user_id->attrib_data)
2676 PKT_user_id *uid = k->pkt->pkt.user_id;
2678 uid->is_primary = 0;
2684 /* None is flagged primary - use the latest user ID we have,
2685 and disambiguate with the arbitrary packet comparison. */
2686 uidnode2->pkt->pkt.user_id->is_primary = 1;
2690 /* None of our uids were self-signed, so pick the one that
2691 sorts first to be the primary. This is the best we can do
2692 here since there are no self sigs to date the uids. */
2696 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2699 if (k->pkt->pkttype == PKT_USER_ID
2700 && !k->pkt->pkt.user_id->attrib_data)
2705 uidnode->pkt->pkt.user_id->is_primary = 1;
2710 if (cmp_user_ids (k->pkt->pkt.user_id,
2711 uidnode->pkt->pkt.user_id) > 0)
2713 uidnode->pkt->pkt.user_id->is_primary = 0;
2715 uidnode->pkt->pkt.user_id->is_primary = 1;
2718 k->pkt->pkt.user_id->is_primary = 0; /* just to be
2726 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
2727 Caller must free the signature when they are done. */
2728 static PKT_signature *
2729 buf_to_sig (const byte * buf, size_t len)
2731 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
2732 IOBUF iobuf = iobuf_temp_with_content (buf, len);
2733 int save_mode = set_packet_list_mode (0);
2735 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
2741 set_packet_list_mode (save_mode);
2742 iobuf_close (iobuf);
2747 /* Use the self-signed data to fill in various fields in subkeys.
2749 KEYBLOCK is the whole keyblock. SUBNODE is the subkey to fill in.
2751 Sets the following fields on the subkey:
2754 flags.valid if the subkey has a valid self-sig binding
2761 On this subkey's most revent valid self-signed packet, the
2762 following field is set:
2764 flags.chosen_selfsig
2767 merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
2769 PKT_public_key *mainpk = NULL, *subpk = NULL;
2775 u32 curtime = make_timestamp ();
2776 unsigned int key_usage = 0;
2777 u32 keytimestamp = 0;
2781 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2783 mainpk = keyblock->pkt->pkt.public_key;
2784 if (mainpk->version < 4)
2785 return;/* (actually this should never happen) */
2786 keyid_from_pk (mainpk, mainkid);
2787 subpk = subnode->pkt->pkt.public_key;
2788 keytimestamp = subpk->timestamp;
2790 subpk->flags.valid = 0;
2791 subpk->flags.exact = 0;
2792 subpk->main_keyid[0] = mainpk->main_keyid[0];
2793 subpk->main_keyid[1] = mainpk->main_keyid[1];
2795 /* Find the latest key binding self-signature. */
2797 sigdate = 0; /* Helper to find the latest signature. */
2798 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2801 if (k->pkt->pkttype == PKT_SIGNATURE)
2803 sig = k->pkt->pkt.signature;
2804 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
2806 if (check_key_signature (keyblock, k, NULL))
2807 ; /* Signature did not verify. */
2808 else if (IS_SUBKEY_REV (sig))
2810 /* Note that this means that the date on a
2811 revocation sig does not matter - even if the
2812 binding sig is dated after the revocation sig,
2813 the subkey is still marked as revoked. This
2814 seems ok, as it is just as easy to make new
2815 subkeys rather than re-sign old ones as the
2816 problem is in the distribution. Plus, PGP (7)
2817 does this the same way. */
2818 subpk->flags.revoked = 1;
2819 sig_to_revoke_info (sig, &subpk->revoked);
2820 /* Although we could stop now, we continue to
2821 * figure out other information like the old expiration
2824 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
2826 if (sig->flags.expired)
2827 ; /* Signature has expired - ignore it. */
2830 sigdate = sig->timestamp;
2832 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2839 /* No valid key binding. */
2843 sig = signode->pkt->pkt.signature;
2844 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
2846 key_usage = parse_key_usage (sig);
2849 /* No key flags at all: get it from the algo. */
2850 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
2854 /* Check that the usage matches the usage as given by the algo. */
2855 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
2856 if (x) /* Mask it down to the actual allowed usage. */
2860 subpk->pubkey_usage = key_usage;
2862 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2863 if (p && buf32_to_u32 (p))
2864 key_expire = keytimestamp + buf32_to_u32 (p);
2867 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
2868 subpk->expiredate = key_expire;
2870 /* Algo doesn't exist. */
2871 if (openpgp_pk_test_algo (subpk->pubkey_algo))
2874 subpk->flags.valid = 1;
2876 /* Find the most recent 0x19 embedded signature on our self-sig. */
2877 if (!subpk->flags.backsig)
2881 PKT_signature *backsig = NULL;
2885 /* We do this while() since there may be other embedded
2886 signatures in the future. We only want 0x19 here. */
2888 while ((p = enum_sig_subpkt (sig->hashed,
2889 SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
2891 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2893 PKT_signature *tempsig = buf_to_sig (p, n);
2896 if (tempsig->timestamp > sigdate)
2899 free_seckey_enc (backsig);
2902 sigdate = backsig->timestamp;
2905 free_seckey_enc (tempsig);
2911 /* It is safe to have this in the unhashed area since the 0x19
2912 is located on the selfsig for convenience, not security. */
2914 while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
2917 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2919 PKT_signature *tempsig = buf_to_sig (p, n);
2922 if (tempsig->timestamp > sigdate)
2925 free_seckey_enc (backsig);
2928 sigdate = backsig->timestamp;
2931 free_seckey_enc (tempsig);
2937 /* At this point, backsig contains the most recent 0x19 sig.
2938 Let's see if it is good. */
2940 /* 2==valid, 1==invalid, 0==didn't check */
2941 if (check_backsig (mainpk, subpk, backsig) == 0)
2942 subpk->flags.backsig = 2;
2944 subpk->flags.backsig = 1;
2946 free_seckey_enc (backsig);
2952 /* Merge information from the self-signatures with the public key,
2953 subkeys and user ids to make using them more easy.
2955 See documentation for merge_selfsigs_main, merge_selfsigs_subkey
2956 and fixup_uidnode for exactly which fields are updated. */
2958 merge_selfsigs (KBNODE keyblock)
2962 struct revoke_info rinfo;
2963 PKT_public_key *main_pk;
2965 unsigned int mdc_feature;
2967 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2969 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
2971 log_error ("expected public key but found secret key "
2973 /* We better exit here because a public key is expected at
2974 other places too. FIXME: Figure this out earlier and
2975 don't get to here at all */
2981 merge_selfsigs_main (keyblock, &revoked, &rinfo);
2983 /* Now merge in the data from each of the subkeys. */
2984 for (k = keyblock; k; k = k->next)
2986 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2988 merge_selfsigs_subkey (keyblock, k);
2992 main_pk = keyblock->pkt->pkt.public_key;
2993 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
2995 /* If the primary key is revoked, expired, or invalid we
2996 * better set the appropriate flags on that key and all
2998 for (k = keyblock; k; k = k->next)
3000 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3001 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3003 PKT_public_key *pk = k->pkt->pkt.public_key;
3004 if (!main_pk->flags.valid)
3005 pk->flags.valid = 0;
3006 if (revoked && !pk->flags.revoked)
3008 pk->flags.revoked = revoked;
3009 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
3011 if (main_pk->has_expired)
3012 pk->has_expired = main_pk->has_expired;
3018 /* Set the preference list of all keys to those of the primary real
3019 * user ID. Note: we use these preferences when we don't know by
3020 * which user ID the key has been selected.
3021 * fixme: we should keep atoms of commonly used preferences or
3022 * use reference counting to optimize the preference lists storage.
3023 * FIXME: it might be better to use the intersection of
3025 * Do a similar thing for the MDC feature flag. */
3028 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3030 if (k->pkt->pkttype == PKT_USER_ID
3031 && !k->pkt->pkt.user_id->attrib_data
3032 && k->pkt->pkt.user_id->is_primary)
3034 prefs = k->pkt->pkt.user_id->prefs;
3035 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
3039 for (k = keyblock; k; k = k->next)
3041 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3042 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3044 PKT_public_key *pk = k->pkt->pkt.public_key;
3047 pk->prefs = copy_prefs (prefs);
3048 pk->flags.mdc = mdc_feature;
3055 /* See whether the key satisfies any additional requirements specified
3056 * in CTX. If so, return 1 and set CTX->FOUND_KEY to an appropriate
3057 * key or subkey. Otherwise, return 0 if there was no appropriate
3060 * In case the primary key is not required, select a suitable subkey.
3061 * We need the primary key if PUBKEY_USAGE_CERT is set in
3062 * CTX->REQ_USAGE or we are in PGP6 or PGP7 mode and PUBKEY_USAGE_SIG
3063 * is set in CTX->REQ_USAGE.
3065 * If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
3066 * are set in CTX->REQ_USAGE, we filter by the key's function.
3067 * Concretely, if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then
3068 * we only return a key if it is (at least) either a signing or a
3069 * certification key.
3071 * If CTX->REQ_USAGE is set, then we reject any keys that are not good
3072 * (i.e., valid, not revoked, not expired, etc.). This allows the
3073 * getkey functions to be used for plain key listings.
3075 * Sets the matched key's user id field (pk->user_id) to the user id
3076 * that matched the low-level search criteria or NULL. If R_FLAGS is
3077 * not NULL set certain flags for more detailed error reporting. Used
3079 * - LOOKUP_ALL_SUBKEYS_EXPIRED :: All Subkeys are expired or have
3082 * This function needs to handle several different cases:
3084 * 1. No requested usage and no primary key requested
3085 * Examples for this case are that we have a keyID to be used
3086 * for decrytion or verification.
3087 * 2. No usage but primary key requested
3088 * This is the case for all functions which work on an
3089 * entire keyblock, e.g. for editing or listing
3090 * 3. Usage and primary key requested
3092 * 4. Usage but no primary key requested
3097 finish_lookup (getkey_ctx_t ctx, kbnode_t keyblock, unsigned int *r_flags)
3101 /* If CTX->EXACT is set, the key or subkey that actually matched the
3102 low-level search criteria. */
3103 kbnode_t foundk = NULL;
3104 /* The user id (if any) that matched the low-level search criteria. */
3105 PKT_user_id *foundu = NULL;
3107 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
3108 unsigned int req_usage = (ctx->req_usage & USAGE_MASK);
3110 /* Request the primary if we're certifying another key, and also
3111 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
3112 do not understand signatures made by a signing subkey. PGP 8
3114 int req_prim = ((ctx->req_usage & PUBKEY_USAGE_CERT)
3115 || ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG)));
3117 u32 curtime = make_timestamp ();
3120 kbnode_t latest_key;
3123 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
3128 /* For an exact match mark the primary or subkey that matched the
3129 low-level search criteria. */
3132 for (k = keyblock; k; k = k->next)
3136 log_assert (k->pkt->pkttype == PKT_PUBLIC_KEY
3137 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3139 pk = k->pkt->pkt.public_key;
3140 pk->flags.exact = 1;
3146 /* Get the user id that matched that low-level search criteria. */
3147 for (k = keyblock; k; k = k->next)
3151 log_assert (k->pkt->pkttype == PKT_USER_ID);
3152 foundu = k->pkt->pkt.user_id;
3158 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
3159 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
3160 foundk ? "one" : "all", req_usage);
3164 latest_key = foundk ? foundk : keyblock;
3170 /* Set LATEST_KEY to the latest (the one with the most recent
3171 * timestamp) good (valid, not revoked, not expired, etc.) subkey.
3173 * Don't bother if we are only looking for a primary key or we need
3174 * an exact match and the exact match is not a subkey. */
3175 if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
3181 int n_revoked_or_expired = 0;
3183 /* Either start a loop or check just this one subkey. */
3184 for (k = foundk ? foundk : keyblock; k; k = nextk)
3188 /* If FOUNDK is not NULL, then only consider that exact
3189 key, i.e., don't iterate. */
3195 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3198 pk = k->pkt->pkt.public_key;
3200 log_debug ("\tchecking subkey %08lX\n",
3201 (ulong) keyid_from_pk (pk, NULL));
3203 if (!pk->flags.valid)
3206 log_debug ("\tsubkey not valid\n");
3209 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3212 log_debug ("\tusage does not match: want=%x have=%x\n",
3213 req_usage, pk->pubkey_usage);
3218 if (pk->flags.revoked)
3221 log_debug ("\tsubkey has been revoked\n");
3222 n_revoked_or_expired++;
3225 if (pk->has_expired)
3228 log_debug ("\tsubkey has expired\n");
3229 n_revoked_or_expired++;
3232 if (pk->timestamp > curtime && !opt.ignore_valid_from)
3235 log_debug ("\tsubkey not yet valid\n");
3240 log_debug ("\tsubkey might be fine\n");
3241 /* In case a key has a timestamp of 0 set, we make sure
3242 that it is used. A better change would be to compare
3243 ">=" but that might also change the selected keys and
3244 is as such a more intrusive change. */
3245 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
3247 latest_date = pk->timestamp;
3251 if (n_subkeys == n_revoked_or_expired && r_flags)
3252 *r_flags |= LOOKUP_ALL_SUBKEYS_EXPIRED;
3255 /* Check if the primary key is ok (valid, not revoke, not expire,
3256 * matches requested usage) if:
3258 * - we didn't find an appropriate subkey and we're not doing an
3261 * - we're doing an exact match and the exact match was the
3264 * - we're just considering the primary key. */
3265 if ((!latest_key && !ctx->exact) || foundk == keyblock || req_prim)
3267 if (DBG_LOOKUP && !foundk && !req_prim)
3268 log_debug ("\tno suitable subkeys found - trying primary\n");
3269 pk = keyblock->pkt->pkt.public_key;
3270 if (!pk->flags.valid)
3273 log_debug ("\tprimary key not valid\n");
3275 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3278 log_debug ("\tprimary key usage does not match: "
3279 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
3281 else if (pk->flags.revoked)
3284 log_debug ("\tprimary key has been revoked\n");
3286 else if (pk->has_expired)
3289 log_debug ("\tprimary key has expired\n");
3294 log_debug ("\tprimary key may be used\n");
3295 latest_key = keyblock;
3302 log_debug ("\tno suitable key found - giving up\n");
3303 return NULL; /* Not found. */
3308 log_debug ("\tusing key %08lX\n",
3309 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
3313 pk = latest_key->pkt->pkt.public_key;
3315 free_user_id (pk->user_id);
3316 pk->user_id = scopy_user_id (foundu);
3319 if (latest_key != keyblock && opt.verbose)
3322 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
3323 log_info (_("using subkey %s instead of primary key %s\n"),
3324 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
3328 cache_user_id (keyblock);
3330 return latest_key ? latest_key : keyblock; /* Found. */
3334 /* Print a KEY_CONSIDERED status line. */
3336 print_status_key_considered (kbnode_t keyblock, unsigned int flags)
3338 char hexfpr[2*MAX_FINGERPRINT_LEN + 1];
3342 if (!is_status_enabled ())
3345 for (node=keyblock; node; node = node->next)
3346 if (node->pkt->pkttype == PKT_PUBLIC_KEY
3347 || node->pkt->pkttype == PKT_SECRET_KEY)
3351 log_error ("%s: keyblock w/o primary key\n", __func__);
3355 hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr);
3356 snprintf (flagbuf, sizeof flagbuf, " %u", flags);
3357 write_status_strings (STATUS_KEY_CONSIDERED, hexfpr, flagbuf, NULL);
3362 /* A high-level function to lookup keys.
3364 This function builds on top of the low-level keydb API. It first
3365 searches the database using the description stored in CTX->ITEMS,
3366 then it filters the results using CTX and, finally, if WANT_SECRET
3367 is set, it ignores any keys for which no secret key is available.
3369 Unlike the low-level search functions, this function also merges
3370 all of the self-signed data into the keys, subkeys and user id
3371 packets (see the merge_selfsigs for details).
3373 On success the key's keyblock is stored at *RET_KEYBLOCK. */
3375 lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, kbnode_t *ret_found_key,
3379 int no_suitable_key = 0;
3380 KBNODE keyblock = NULL;
3381 KBNODE found_key = NULL;
3382 unsigned int infoflags;
3385 *ret_keyblock = NULL;
3389 rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
3393 /* If we are iterating over the entire database, then we need to
3394 change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
3395 reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next
3397 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
3398 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
3400 rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
3403 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
3407 if (want_secret && agent_probe_any_secret_key (NULL, keyblock))
3408 goto skip; /* No secret key available. */
3410 /* Warning: node flag bits 0 and 1 should be preserved by
3411 * merge_selfsigs. For secret keys, premerge transferred the
3412 * keys to the keyblock. */
3413 merge_selfsigs (keyblock);
3414 found_key = finish_lookup (ctx, keyblock, &infoflags);
3416 infoflags |= LOOKUP_NOT_SELECTED;
3417 print_status_key_considered (keyblock, infoflags);
3420 no_suitable_key = 0;
3425 no_suitable_key = 1;
3429 /* Release resources and continue search. */
3430 release_kbnode (keyblock);
3432 /* The keyblock cache ignores the current "file position".
3433 Thus, if we request the next result and the cache matches
3434 (and it will since it is what we just looked for), we'll get
3435 the same entry back! We can avoid this infinite loop by
3436 disabling the cache. */
3437 keydb_disable_caching (ctx->kr_handle);
3441 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
3442 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
3447 *ret_keyblock = keyblock; /* Return the keyblock. */
3450 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
3451 rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
3452 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
3453 rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
3455 release_kbnode (keyblock);
3460 *ret_found_key = found_key;
3462 *ret_found_key = NULL;
3469 /* Enumerate some secret keys (specifically, those specified with
3470 * --default-key and --try-secret-key). Use the following procedure:
3472 * 1) Initialize a void pointer to NULL
3473 * 2) Pass a reference to this pointer to this function (content)
3474 * and provide space for the secret key (sk)
3475 * 3) Call this function as long as it does not return an error (or
3476 * until you are done). The error code GPG_ERR_EOF indicates the
3477 * end of the listing.
3478 * 4) Call this function a last time with SK set to NULL,
3479 * so that can free it's context.
3484 * PKT_public_key *sk = xmalloc_clear (sizeof (*sk));
3486 * while ((err = enum_secret_keys (&ctx, sk)))
3490 * free_public_key (sk);
3491 * sk = xmalloc_clear (sizeof (*sk));
3494 * // Release any resources used by CTX.
3495 * enum_secret_keys (&ctx, NULL);
3496 * free_public_key (sk);
3498 * if (gpg_err_code (err) != GPG_ERR_EOF)
3499 * ; // An error occurred.
3502 enum_secret_keys (ctrl_t ctrl, void **context, PKT_public_key *sk)
3504 gpg_error_t err = 0;
3517 /* Make a new context. */
3518 c = xtrycalloc (1, sizeof *c);
3520 return gpg_error_from_syserror ();
3526 /* Free the context. */
3527 release_kbnode (c->keyblock);
3534 return gpg_error (GPG_ERR_EOF);
3538 /* Loop until we have a keyblock. */
3539 while (!c->keyblock)
3541 /* Loop over the list of secret keys. */
3547 case 0: /* First try to use the --default-key. */
3548 name = parse_def_secret_key (ctrl);
3552 case 1: /* Init list of keys to try. */
3553 c->sl = opt.secret_keys_to_try;
3557 case 2: /* Get next item from list. */
3561 c->sl = c->sl->next;
3567 default: /* No more names to check - stop. */
3569 return gpg_error (GPG_ERR_EOF);
3572 while (!name || !*name);
3574 err = getkey_byname (ctrl, NULL, NULL, name, 1, &c->keyblock);
3577 /* getkey_byname might return a keyblock even in the
3578 error case - I have not checked. Thus better release
3580 release_kbnode (c->keyblock);
3584 c->node = c->keyblock;
3587 /* Get the next key from the current keyblock. */
3588 for (; c->node; c->node = c->node->next)
3590 if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
3591 || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3593 copy_public_key (sk, c->node->pkt->pkt.public_key);
3594 c->node = c->node->next;
3595 return 0; /* Found. */
3599 /* Dispose the keyblock and continue. */
3600 release_kbnode (c->keyblock);
3606 /*********************************************
3607 *********** User ID printing helpers *******
3608 *********************************************/
3610 /* Return a string with a printable representation of the user_id.
3611 * this string must be freed by xfree. */
3613 get_user_id_string (u32 * keyid, int mode, size_t *r_len)
3620 /* Try it two times; second pass reads from the database. */
3623 for (r = user_id_db; r; r = r->next)
3625 for (a = r->keyids; a; a = a->next)
3627 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
3631 /* An empty string as user id is possible. Make
3632 sure that the malloc allocates one byte and
3633 does not bail out. */
3634 p = xmalloc (r->len? r->len : 1);
3635 memcpy (p, r->name, r->len);
3642 p = xasprintf ("%08lX%08lX %.*s",
3643 (ulong) keyid[0], (ulong) keyid[1],
3646 p = xasprintf ("%s %.*s", keystr (keyid),
3649 *r_len = strlen (p);
3657 while (++pass < 2 && !get_pubkey (NULL, keyid));
3660 p = xstrdup (user_id_not_found_utf8 ());
3662 p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
3664 p = xasprintf ("%s [?]", keystr (keyid));
3667 *r_len = strlen (p);
3673 get_user_id_string_native (u32 * keyid)
3675 char *p = get_user_id_string (keyid, 0, NULL);
3676 char *p2 = utf8_to_native (p, strlen (p), 0);
3683 get_long_user_id_string (u32 * keyid)
3685 return get_user_id_string (keyid, 1, NULL);
3689 /* Please try to use get_user_byfpr instead of this one. */
3691 get_user_id (u32 * keyid, size_t * rn)
3693 return get_user_id_string (keyid, 2, rn);
3697 /* Please try to use get_user_id_byfpr_native instead of this one. */
3699 get_user_id_native (u32 * keyid)
3702 char *p = get_user_id (keyid, &rn);
3703 char *p2 = utf8_to_native (p, rn, 0);
3709 /* Return the user id for a key designated by its fingerprint, FPR,
3710 which must be MAX_FINGERPRINT_LEN bytes in size. Note: the
3711 returned string, which must be freed using xfree, may not be NUL
3712 terminated. To determine the length of the string, you must use
3715 get_user_id_byfpr (const byte *fpr, size_t *rn)
3721 /* Try it two times; second pass reads from the database. */
3724 for (r = user_id_db; r; r = r->next)
3727 for (a = r->keyids; a; a = a->next)
3729 if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
3731 /* An empty string as user id is possible. Make
3732 sure that the malloc allocates one byte and does
3734 p = xmalloc (r->len? r->len : 1);
3735 memcpy (p, r->name, r->len);
3743 && !get_pubkey_byfprint (NULL, NULL, fpr, MAX_FINGERPRINT_LEN));
3744 p = xstrdup (user_id_not_found_utf8 ());
3749 /* Like get_user_id_byfpr, but convert the string to the native
3750 encoding. The returned string needs to be freed. Unlike
3751 get_user_id_byfpr, the returned string is NUL terminated. */
3753 get_user_id_byfpr_native (const byte *fpr)
3756 char *p = get_user_id_byfpr (fpr, &rn);
3757 char *p2 = utf8_to_native (p, rn, 0);
3763 /* Return the database handle used by this context. The context still
3766 get_ctx_handle (GETKEY_CTX ctx)
3768 return ctx->kr_handle;
3772 free_akl (struct akl *akl)
3778 free_keyserver_spec (akl->spec);
3786 while (opt.auto_key_locate)
3788 struct akl *akl2 = opt.auto_key_locate;
3789 opt.auto_key_locate = opt.auto_key_locate->next;
3794 /* Returns false on error. */
3796 parse_auto_key_locate (char *options)
3800 while ((tok = optsep (&options)))
3802 struct akl *akl, *check, *last = NULL;
3808 akl = xmalloc_clear (sizeof (*akl));
3810 if (ascii_strcasecmp (tok, "clear") == 0)
3813 free_akl (opt.auto_key_locate);
3814 opt.auto_key_locate = NULL;
3817 else if (ascii_strcasecmp (tok, "nodefault") == 0)
3818 akl->type = AKL_NODEFAULT;
3819 else if (ascii_strcasecmp (tok, "local") == 0)
3820 akl->type = AKL_LOCAL;
3821 else if (ascii_strcasecmp (tok, "ldap") == 0)
3822 akl->type = AKL_LDAP;
3823 else if (ascii_strcasecmp (tok, "keyserver") == 0)
3824 akl->type = AKL_KEYSERVER;
3826 else if (ascii_strcasecmp (tok, "cert") == 0)
3827 akl->type = AKL_CERT;
3829 else if (ascii_strcasecmp (tok, "pka") == 0)
3830 akl->type = AKL_PKA;
3831 else if (ascii_strcasecmp (tok, "dane") == 0)
3832 akl->type = AKL_DANE;
3833 else if (ascii_strcasecmp (tok, "wkd") == 0)
3834 akl->type = AKL_WKD;
3835 else if ((akl->spec = parse_keyserver_uri (tok, 1)))
3836 akl->type = AKL_SPEC;
3843 /* We must maintain the order the user gave us */
3844 for (check = opt.auto_key_locate; check;
3845 last = check, check = check->next)
3847 /* Check for duplicates */
3848 if (check->type == akl->type
3849 && (akl->type != AKL_SPEC
3850 || (akl->type == AKL_SPEC
3851 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
3864 opt.auto_key_locate = akl;
3872 /* Returns true if a secret key is available for the public key with
3873 key id KEYID; returns false if not. This function ignores legacy
3874 keys. Note: this is just a fast check and does not tell us whether
3875 the secret key is valid; this check merely indicates whether there
3876 is some secret key with the specified key id. */
3878 have_secret_key_with_kid (u32 *keyid)
3882 KEYDB_SEARCH_DESC desc;
3887 kdbhd = keydb_new ();
3890 memset (&desc, 0, sizeof desc);
3891 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
3892 desc.u.kid[0] = keyid[0];
3893 desc.u.kid[1] = keyid[1];
3896 err = keydb_search (kdbhd, &desc, 1, NULL);
3900 err = keydb_get_keyblock (kdbhd, &keyblock);
3903 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
3907 for (node = keyblock; node; node = node->next)
3909 /* Bit 0 of the flags is set if the search found the key
3910 using that key or subkey. Note: a search will only ever
3911 match a single key or subkey. */
3912 if ((node->flag & 1))
3914 log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY
3915 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3917 if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
3918 result = 1; /* Secret key available. */
3925 release_kbnode (keyblock);
3928 keydb_release (kdbhd);