1 /* getkey.c - Get a key from the database
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3 * 2007, 2008, 2010 Free Software Foundation, Inc.
4 * Copyright (C) 2015, 2016 g10 Code GmbH
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
29 #include "../common/util.h"
31 #include "../common/iobuf.h"
36 #include "../common/i18n.h"
37 #include "keyserver-internal.h"
38 #include "call-agent.h"
40 #include "../common/host2net.h"
41 #include "../common/mbox-util.h"
42 #include "../common/status.h"
44 #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
45 #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
47 #if MAX_PK_CACHE_ENTRIES < 2
48 #error We need the cache for key creation
51 /* Flags values returned by the lookup code. Note that the values are
52 * directly used by the KEY_CONSIDERED status line. */
53 #define LOOKUP_NOT_SELECTED (1<<0)
54 #define LOOKUP_ALL_SUBKEYS_EXPIRED (1<<1) /* or revoked */
57 /* A context object used by the lookup functions. */
60 /* Part of the search criteria: whether the search is an exact
61 search or not. A search that is exact requires that a key or
62 subkey meet all of the specified criteria. A search that is not
63 exact allows selecting a different key or subkey from the
64 keyblock that matched the criteria. Further, an exact search
65 returns the key or subkey that matched whereas a non-exact search
66 typically returns the primary key. See finish_lookup for
70 /* Part of the search criteria: Whether the caller only wants keys
71 with an available secret key. This is used by getkey_next to get
72 the next result with the same initial criteria. */
75 /* Part of the search criteria: The type of the requested key. A
76 mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.
77 If non-zero, then for a key to match, it must implement one of
81 /* The database handle. */
82 KEYDB_HANDLE kr_handle;
84 /* Whether we should call xfree() on the context when the context is
85 released using getkey_end()). */
88 /* This variable is used as backing store for strings which have
89 their address used in ITEMS. */
92 /* Hack to return the mechanism (AKL_foo) used to find the key. */
95 /* Part of the search criteria: The low-level search specification
96 as passed to keydb_search. */
98 /* This must be the last element in the structure. When we allocate
99 the structure, we allocate it so that ITEMS can hold NITEMS. */
100 KEYDB_SEARCH_DESC items[1];
113 typedef struct keyid_list
115 struct keyid_list *next;
117 char fpr[MAX_FINGERPRINT_LEN];
122 #if MAX_PK_CACHE_ENTRIES
123 typedef struct pk_cache_entry
125 struct pk_cache_entry *next;
129 static pk_cache_entry_t pk_cache;
130 static int pk_cache_entries; /* Number of entries in pk cache. */
131 static int pk_cache_disabled;
134 #if MAX_UID_CACHE_ENTRIES < 5
135 #error we really need the userid cache
138 static void merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock);
139 static int lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret,
140 kbnode_t *ret_keyblock, kbnode_t *ret_found_key);
141 static kbnode_t finish_lookup (kbnode_t keyblock,
142 unsigned int req_usage, int want_exact,
143 int want_secret, unsigned int *r_flags);
144 static void print_status_key_considered (kbnode_t keyblock, unsigned int flags);
152 for (i = 0; i < DIM (lkup_stats); i++)
154 if (lkup_stats[i].any)
155 es_fprintf (es_stderr,
156 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
158 lkup_stats[i].okay_count,
159 lkup_stats[i].nokey_count, lkup_stats[i].error_count);
165 /* Cache a copy of a public key in the public key cache. PK is not
166 * cached if caching is disabled (via getkey_disable_caches), if
167 * PK->FLAGS.DONT_CACHE is set, we don't know how to derive a key id
168 * from the public key (e.g., unsupported algorithm), or a key with
169 * the key id is already in the cache.
171 * The public key packet is copied into the cache using
172 * copy_public_key. Thus, any secret parts are not copied, for
175 * This cache is filled by get_pubkey and is read by get_pubkey and
176 * get_pubkey_fast. */
178 cache_public_key (PKT_public_key * pk)
180 #if MAX_PK_CACHE_ENTRIES
181 pk_cache_entry_t ce, ce2;
184 if (pk_cache_disabled)
187 if (pk->flags.dont_cache)
190 if (is_ELGAMAL (pk->pubkey_algo)
191 || pk->pubkey_algo == PUBKEY_ALGO_DSA
192 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
193 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
194 || pk->pubkey_algo == PUBKEY_ALGO_ECDH
195 || is_RSA (pk->pubkey_algo))
197 keyid_from_pk (pk, keyid);
200 return; /* Don't know how to get the keyid. */
202 for (ce = pk_cache; ce; ce = ce->next)
203 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
206 log_debug ("cache_public_key: already in cache\n");
210 if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
214 /* Remove the last 50% of the entries. */
215 for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
217 if (ce && ce != pk_cache && ce->next)
225 free_public_key (ce->pk);
230 log_assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
233 ce = xmalloc (sizeof *ce);
236 ce->pk = copy_public_key (NULL, pk);
237 ce->keyid[0] = keyid[0];
238 ce->keyid[1] = keyid[1];
243 /* Return a const utf-8 string with the text "[User ID not found]".
244 This function is required so that we don't need to switch gettext's
245 encoding temporary. */
247 user_id_not_found_utf8 (void)
252 text = native_to_utf8 (_("[User ID not found]"));
259 /* Disable and drop the public key cache (which is filled by
260 cache_public_key and get_pubkey). Note: there is currently no way
261 to re-enable this cache. */
263 getkey_disable_caches (void)
265 #if MAX_PK_CACHE_ENTRIES
267 pk_cache_entry_t ce, ce2;
269 for (ce = pk_cache; ce; ce = ce2)
272 free_public_key (ce->pk);
275 pk_cache_disabled = 1;
276 pk_cache_entries = 0;
280 /* fixme: disable user id cache ? */
284 /* Free a list of pubkey_t objects. */
286 pubkeys_free (pubkey_t keys)
290 pubkey_t next = keys->next;
292 release_kbnode (keys->keyblock);
300 pk_from_block (PKT_public_key *pk, kbnode_t keyblock, kbnode_t found_key)
302 kbnode_t a = found_key ? found_key : keyblock;
304 log_assert (a->pkt->pkttype == PKT_PUBLIC_KEY
305 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
307 copy_public_key (pk, a->pkt->pkt.public_key);
311 /* Specialized version of get_pubkey which retrieves the key based on
312 * information in SIG. In contrast to get_pubkey PK is required. IF
313 * FORCED_PK is not NULL, this public key is used and copied to PK. */
315 get_pubkey_for_sig (ctrl_t ctrl, PKT_public_key *pk, PKT_signature *sig,
316 PKT_public_key *forced_pk)
323 copy_public_key (pk, forced_pk);
327 /* First try the ISSUER_FPR info. */
328 fpr = issuer_fpr_raw (sig, &fprlen);
329 if (fpr && !get_pubkey_byfprint (ctrl, pk, NULL, fpr, fprlen))
332 /* Fallback to use the ISSUER_KEYID. */
333 return get_pubkey (ctrl, pk, sig->keyid);
337 /* Return the public key with the key id KEYID and store it at PK.
338 * The resources in *PK should be released using
339 * release_public_key_parts(). This function also stores a copy of
340 * the public key in the user id cache (see cache_public_key).
342 * If PK is NULL, this function just stores the public key in the
343 * cache and returns the usual return code.
345 * PK->REQ_USAGE (which is a mask of PUBKEY_USAGE_SIG,
346 * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT) is passed through to the
347 * lookup function. If this is non-zero, only keys with the specified
348 * usage will be returned. As such, it is essential that
349 * PK->REQ_USAGE be correctly initialized!
351 * Returns 0 on success, GPG_ERR_NO_PUBKEY if there is no public key
352 * with the specified key id, or another error code if an error
355 * If the data was not read from the cache, then the self-signed data
356 * has definitely been merged into the public key using
359 get_pubkey (ctrl_t ctrl, PKT_public_key * pk, u32 * keyid)
364 #if MAX_PK_CACHE_ENTRIES
367 /* Try to get it from the cache. We don't do this when pk is
368 NULL as it does not guarantee that the user IDs are
371 for (ce = pk_cache; ce; ce = ce->next)
373 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
374 /* XXX: We don't check PK->REQ_USAGE here, but if we don't
375 read from the cache, we do check it! */
377 copy_public_key (pk, ce->pk);
383 /* More init stuff. */
387 pk = xtrycalloc (1, sizeof *pk);
390 rc = gpg_error_from_syserror ();
398 struct getkey_ctx_s ctx;
400 kbnode_t found_key = NULL;
402 memset (&ctx, 0, sizeof ctx);
403 ctx.exact = 1; /* Use the key ID exactly as given. */
404 ctx.not_allocated = 1;
406 if (ctrl && ctrl->cached_getkey_kdb)
408 ctx.kr_handle = ctrl->cached_getkey_kdb;
409 ctrl->cached_getkey_kdb = NULL;
410 keydb_search_reset (ctx.kr_handle);
414 ctx.kr_handle = keydb_new (ctrl);
417 rc = gpg_error_from_syserror ();
422 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
423 ctx.items[0].u.kid[0] = keyid[0];
424 ctx.items[0].u.kid[1] = keyid[1];
425 ctx.req_usage = pk->req_usage;
426 rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
429 pk_from_block (pk, kb, found_key);
431 getkey_end (ctrl, &ctx);
437 rc = GPG_ERR_NO_PUBKEY;
441 cache_public_key (pk);
443 free_public_key (pk);
448 /* Same as get_pubkey but if the key was not found the function tries
449 * to import it from LDAP. FIXME: We should not need this but swicth
450 * to a fingerprint lookup. */
452 get_pubkey_with_ldap_fallback (ctrl_t ctrl, PKT_public_key *pk, u32 *keyid)
456 err = get_pubkey (ctrl, pk, keyid);
460 if (gpg_err_code (err) != GPG_ERR_NO_PUBKEY)
463 /* Note that this code does not handle the case for two readers
464 * having both openpgp encryption keys. Only one will be tried. */
466 log_debug ("using LDAP to find a public key\n");
467 err = keyserver_import_keyid (ctrl, keyid,
468 opt.keyserver, KEYSERVER_IMPORT_FLAG_LDAP);
469 if (gpg_err_code (err) == GPG_ERR_NO_DATA
470 || gpg_err_code (err) == GPG_ERR_NO_KEYSERVER)
472 /* Dirmngr returns NO DATA is the selected keyserver
473 * does not have the requested key. It returns NO
474 * KEYSERVER if no LDAP keyservers are configured. */
475 err = gpg_error (GPG_ERR_NO_PUBKEY);
480 return get_pubkey (ctrl, pk, keyid);
484 /* Similar to get_pubkey, but it does not take PK->REQ_USAGE into
485 * account nor does it merge in the self-signed data. This function
486 * also only considers primary keys. It is intended to be used as a
487 * quick check of the key to avoid recursion. It should only be used
488 * in very certain cases. Like get_pubkey and unlike any of the other
489 * lookup functions, this function also consults the user id cache
490 * (see cache_public_key).
492 * Return the public key in *PK. The resources in *PK should be
493 * released using release_public_key_parts(). */
495 get_pubkey_fast (ctrl_t ctrl, PKT_public_key * pk, u32 * keyid)
503 #if MAX_PK_CACHE_ENTRIES
505 /* Try to get it from the cache */
508 for (ce = pk_cache; ce; ce = ce->next)
510 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]
511 /* Only consider primary keys. */
512 && ce->pk->keyid[0] == ce->pk->main_keyid[0]
513 && ce->pk->keyid[1] == ce->pk->main_keyid[1])
516 copy_public_key (pk, ce->pk);
523 hd = keydb_new (ctrl);
525 return gpg_error_from_syserror ();
526 rc = keydb_search_kid (hd, keyid);
527 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
530 return GPG_ERR_NO_PUBKEY;
532 rc = keydb_get_keyblock (hd, &keyblock);
536 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
537 return GPG_ERR_NO_PUBKEY;
540 log_assert (keyblock && keyblock->pkt
541 && keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
543 /* We return the primary key. If KEYID matched a subkey, then we
545 keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
546 if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
547 copy_public_key (pk, keyblock->pkt->pkt.public_key);
549 rc = GPG_ERR_NO_PUBKEY;
551 release_kbnode (keyblock);
553 /* Not caching key here since it won't have all of the fields
560 /* Return the entire keyblock used to create SIG. This is a
561 * specialized version of get_pubkeyblock.
563 * FIXME: This is a hack because get_pubkey_for_sig was already called
564 * and it could have used a cache to hold the key. */
566 get_pubkeyblock_for_sig (ctrl_t ctrl, PKT_signature *sig)
572 /* First try the ISSUER_FPR info. */
573 fpr = issuer_fpr_raw (sig, &fprlen);
574 if (fpr && !get_pubkey_byfprint (ctrl, NULL, &keyblock, fpr, fprlen))
577 /* Fallback to use the ISSUER_KEYID. */
578 return get_pubkeyblock (ctrl, sig->keyid);
582 /* Return the key block for the key with key id KEYID or NULL, if an
583 * error occurs. Use release_kbnode() to release the key block.
585 * The self-signed data has already been merged into the public key
586 * using merge_selfsigs. */
588 get_pubkeyblock (ctrl_t ctrl, u32 * keyid)
590 struct getkey_ctx_s ctx;
592 KBNODE keyblock = NULL;
594 memset (&ctx, 0, sizeof ctx);
595 /* No need to set exact here because we want the entire block. */
596 ctx.not_allocated = 1;
597 ctx.kr_handle = keydb_new (ctrl);
601 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
602 ctx.items[0].u.kid[0] = keyid[0];
603 ctx.items[0].u.kid[1] = keyid[1];
604 rc = lookup (ctrl, &ctx, 0, &keyblock, NULL);
605 getkey_end (ctrl, &ctx);
607 return rc ? NULL : keyblock;
611 /* Return the public key with the key id KEYID iff the secret key is
612 * available and store it at PK. The resources should be released
613 * using release_public_key_parts().
615 * Unlike other lookup functions, PK may not be NULL. PK->REQ_USAGE
616 * is passed through to the lookup function and is a mask of
617 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. Thus, it
618 * must be valid! If this is non-zero, only keys with the specified
619 * usage will be returned.
621 * Returns 0 on success. If a public key with the specified key id is
622 * not found or a secret key is not available for that public key, an
623 * error code is returned. Note: this function ignores legacy keys.
624 * An error code is also return if an error occurs.
626 * The self-signed data has already been merged into the public key
627 * using merge_selfsigs. */
629 get_seckey (ctrl_t ctrl, PKT_public_key *pk, u32 *keyid)
632 struct getkey_ctx_s ctx;
633 kbnode_t keyblock = NULL;
634 kbnode_t found_key = NULL;
636 memset (&ctx, 0, sizeof ctx);
637 ctx.exact = 1; /* Use the key ID exactly as given. */
638 ctx.not_allocated = 1;
639 ctx.kr_handle = keydb_new (ctrl);
641 return gpg_error_from_syserror ();
643 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
644 ctx.items[0].u.kid[0] = keyid[0];
645 ctx.items[0].u.kid[1] = keyid[1];
646 ctx.req_usage = pk->req_usage;
647 err = lookup (ctrl, &ctx, 1, &keyblock, &found_key);
650 pk_from_block (pk, keyblock, found_key);
652 getkey_end (ctrl, &ctx);
653 release_kbnode (keyblock);
657 if (!agent_probe_secret_key (/*ctrl*/NULL, pk))
659 release_public_key_parts (pk);
660 err = gpg_error (GPG_ERR_NO_SECKEY);
668 /* Skip unusable keys. A key is unusable if it is revoked, expired or
669 disabled or if the selected user id is revoked or expired. */
671 skip_unusable (void *opaque, u32 * keyid, int uid_no)
673 ctrl_t ctrl = opaque;
678 keyblock = get_pubkeyblock (ctrl, keyid);
681 log_error ("error checking usability status of %s\n", keystr (keyid));
685 pk = keyblock->pkt->pkt.public_key;
687 /* Is the key revoked or expired? */
688 if (pk->flags.revoked || (pk->has_expired && !opt.ignore_expiration))
691 /* Is the user ID in question revoked or expired? */
692 if (!unusable && uid_no)
697 for (node = keyblock; node; node = node->next)
699 if (node->pkt->pkttype == PKT_USER_ID)
701 PKT_user_id *user_id = node->pkt->pkt.user_id;
704 if (uids_seen != uid_no)
707 if (user_id->flags.revoked
708 || (user_id->flags.expired && !opt.ignore_expiration))
715 /* If UID_NO is non-zero, then the keyblock better have at least
717 log_assert (uids_seen == uid_no);
721 unusable = pk_is_disabled (pk);
724 release_kbnode (keyblock);
729 /* Search for keys matching some criteria.
731 If RETCTX is not NULL, then the constructed context is returned in
732 *RETCTX so that getpubkey_next can be used to get subsequent
733 results. In this case, getkey_end() must be used to free the
734 search context. If RETCTX is not NULL, then RET_KDBHD must be
737 If NAMELIST is not NULL, then a search query is constructed using
738 classify_user_id on each of the strings in the list. (Recall: the
739 database does an OR of the terms, not an AND.) If NAMELIST is
740 NULL, then all results are returned.
742 If PK is not NULL, the public key of the first result is returned
743 in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
744 set, it is used to filter the search results. See the
745 documentation for finish_lookup to understand exactly how this is
746 used. Note: The self-signed data has already been merged into the
747 public key using merge_selfsigs. Free *PK by calling
748 release_public_key_parts (or, if PK was allocated using xfree, you
749 can use free_public_key, which calls release_public_key_parts(PK)
752 If WANT_SECRET is set, then only keys with an available secret key
753 (either locally or via key registered on a smartcard) are returned.
755 If INCLUDE_UNUSABLE is set, then unusable keys (see the
756 documentation for skip_unusable for an exact definition) are
757 skipped unless they are looked up by key id or by fingerprint.
759 If RET_KB is not NULL, the keyblock is returned in *RET_KB. This
760 should be freed using release_kbnode().
762 If RET_KDBHD is not NULL, then the new database handle used to
763 conduct the search is returned in *RET_KDBHD. This can be used to
764 get subsequent results using keydb_search_next. Note: in this
765 case, no advanced filtering is done for subsequent results (e.g.,
766 WANT_SECRET and PK->REQ_USAGE are not respected).
768 This function returns 0 on success. Otherwise, an error code is
769 returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
770 (if want_secret is set) is returned if the key is not found. */
772 key_byname (ctrl_t ctrl, GETKEY_CTX *retctx, strlist_t namelist,
774 int want_secret, int include_unusable,
775 KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
780 strlist_t namelist_expanded = NULL;
782 KBNODE help_kb = NULL;
783 KBNODE found_key = NULL;
787 /* Reset the returned context in case of error. */
788 log_assert (!ret_kdbhd); /* Not allowed because the handle is stored
796 /* No search terms: iterate over the whole DB. */
798 ctx = xmalloc_clear (sizeof *ctx);
800 ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
801 if (!include_unusable)
803 ctx->items[0].skipfnc = skip_unusable;
804 ctx->items[0].skipfncvalue = ctrl;
809 namelist_expanded = expand_group (namelist, 1);
810 namelist = namelist_expanded;
812 /* Build the search context. */
813 for (n = 0, r = namelist; r; r = r->next)
816 /* CTX has space for a single search term at the end. Thus, we
817 need to allocate sizeof *CTX plus (n - 1) sizeof
819 ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
822 for (n = 0, r = namelist; r; r = r->next, n++)
826 err = classify_user_id (r->d, &ctx->items[n], 1);
828 if (ctx->items[n].exact)
833 rc = gpg_err_code (err); /* FIXME: remove gpg_err_code. */
836 if (!include_unusable
837 && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
838 && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
839 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
841 ctx->items[n].skipfnc = skip_unusable;
842 ctx->items[n].skipfncvalue = ctrl;
847 ctx->want_secret = want_secret;
848 ctx->kr_handle = keydb_new (ctrl);
851 rc = gpg_error_from_syserror ();
852 getkey_end (ctrl, ctx);
861 ctx->req_usage = pk->req_usage;
864 rc = lookup (ctrl, ctx, want_secret, ret_kb, &found_key);
867 pk_from_block (pk, *ret_kb, found_key);
870 release_kbnode (help_kb);
872 if (retctx) /* Caller wants the context. */
876 for (r=ctx->extra_list; r->next; r = r->next)
878 r->next = namelist_expanded;
881 ctx->extra_list = namelist_expanded;
882 namelist_expanded = NULL;
889 *ret_kdbhd = ctx->kr_handle;
890 ctx->kr_handle = NULL;
892 getkey_end (ctrl, ctx);
896 free_strlist (namelist_expanded);
901 /* Find a public key identified by NAME.
903 * If name appears to be a valid RFC822 mailbox (i.e., email address)
904 * and auto key lookup is enabled (mode != GET_PUBKEY_NO_AKL), then
905 * the specified auto key lookup methods (--auto-key-lookup) are used
906 * to import the key into the local keyring. Otherwise, just the
907 * local keyring is consulted.
909 * MODE can be one of:
910 * GET_PUBKEY_NORMAL - The standard mode
911 * GET_PUBKEY_NO_AKL - The auto key locate functionality is
912 * disabled and only the local key ring is
913 * considered. Note: the local key ring is
914 * consulted even if local is not in the
915 * auto-key-locate option list!
916 * GET_PUBKEY_NO_LOCAL - Only the auto key locate functionality is
917 * used and no local search is done.
919 * If RETCTX is not NULL, then the constructed context is returned in
920 * *RETCTX so that getpubkey_next can be used to get subsequent
921 * results. In this case, getkey_end() must be used to free the
922 * search context. If RETCTX is not NULL, then RET_KDBHD must be
925 * If PK is not NULL, the public key of the first result is returned
926 * in *PK. Note: PK->REQ_USAGE must be valid!!! PK->REQ_USAGE is
927 * passed through to the lookup function and is a mask of
928 * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this
929 * is non-zero, only keys with the specified usage will be returned.
930 * Note: The self-signed data has already been merged into the public
931 * key using merge_selfsigs. Free *PK by calling
932 * release_public_key_parts (or, if PK was allocated using xfree, you
933 * can use free_public_key, which calls release_public_key_parts(PK)
934 * and then xfree(PK)).
936 * NAME is a string, which is turned into a search query using
939 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
940 * *RET_KEYBLOCK. This should be freed using release_kbnode().
942 * If RET_KDBHD is not NULL, then the new database handle used to
943 * conduct the search is returned in *RET_KDBHD. This can be used to
944 * get subsequent results using keydb_search_next or to modify the
945 * returned record. Note: in this case, no advanced filtering is done
946 * for subsequent results (e.g., PK->REQ_USAGE is not respected).
947 * Unlike RETCTX, this is always returned.
949 * If INCLUDE_UNUSABLE is set, then unusable keys (see the
950 * documentation for skip_unusable for an exact definition) are
951 * skipped unless they are looked up by key id or by fingerprint.
953 * This function returns 0 on success. Otherwise, an error code is
954 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
955 * (if want_secret is set) is returned if the key is not found. */
957 get_pubkey_byname (ctrl_t ctrl, enum get_pubkey_modes mode,
958 GETKEY_CTX * retctx, PKT_public_key * pk,
959 const char *name, KBNODE * ret_keyblock,
960 KEYDB_HANDLE * ret_kdbhd, int include_unusable)
963 strlist_t namelist = NULL;
966 KEYDB_SEARCH_DESC fprbuf;
968 int anylocalfirst = 0;
969 int mechanism_type = AKL_NODEFAULT;
972 /* If RETCTX is not NULL, then RET_KDBHD must be NULL. */
973 log_assert (retctx == NULL || ret_kdbhd == NULL);
978 /* Does NAME appear to be a mailbox (mail address)? */
979 is_mbox = is_valid_mailbox (name);
980 if (!is_mbox && *name == '<' && name[1] && name[strlen(name)-1]=='>'
982 && is_valid_mailbox_mem (name+1, strlen (name)-2))
984 /* The mailbox is in the form "<foo@example.org>" which is not
985 * detected by is_valid_mailbox. Set the flag but keep name as
986 * it is because the bracketed name is actual the better
987 * specification for a local search and the other methods
988 * extract the mail address anyway. */
992 /* If we are called due to --locate-external-key Check whether NAME
993 * is a fingerprint and then try to lookup that key by configured
994 * method which support lookup by fingerprint. FPRBUF carries the
995 * parsed fingerpint iff IS_FPR is true. */
997 if (!is_mbox && mode == GET_PUBKEY_NO_LOCAL)
999 if (!classify_user_id (name, &fprbuf, 1)
1000 && fprbuf.mode == KEYDB_SEARCH_MODE_FPR)
1004 /* The auto-key-locate feature works as follows: there are a number
1005 * of methods to look up keys. By default, the local keyring is
1006 * tried first. Then, each method listed in the --auto-key-locate is
1007 * tried in the order it appears.
1009 * This can be changed as follows:
1011 * - if nodefault appears anywhere in the list of options, then
1012 * the local keyring is not tried first, or,
1014 * - if local appears anywhere in the list of options, then the
1015 * local keyring is not tried first, but in the order in which
1016 * it was listed in the --auto-key-locate option.
1018 * Note: we only save the search context in RETCTX if the local
1019 * method is the first method tried (either explicitly or
1021 if (mode == GET_PUBKEY_NO_LOCAL)
1022 nodefault = 1; /* Auto-key-locate but ignore "local". */
1023 else if (mode != GET_PUBKEY_NO_AKL)
1025 /* auto-key-locate is enabled. */
1027 /* nodefault is true if "nodefault" or "local" appear. */
1028 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1029 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
1034 /* anylocalfirst is true if "local" appears before any other
1035 search methods (except "nodefault"). */
1036 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1037 if (akl->type != AKL_NODEFAULT)
1039 if (akl->type == AKL_LOCAL)
1047 /* "nodefault" didn't occur. Thus, "local" is implicitly the
1048 * first method to try. */
1052 if (mode == GET_PUBKEY_NO_LOCAL)
1054 /* Force using the AKL. If IS_MBOX is not set this is the final
1056 rc = GPG_ERR_NO_PUBKEY;
1058 else if (nodefault && is_mbox)
1060 /* Either "nodefault" or "local" (explicitly) appeared in the
1061 * auto key locate list and NAME appears to be an email address.
1062 * Don't try the local keyring. */
1063 rc = GPG_ERR_NO_PUBKEY;
1067 /* Either "nodefault" and "local" don't appear in the auto key
1068 * locate list (in which case we try the local keyring first) or
1069 * NAME does not appear to be an email address (in which case we
1070 * only try the local keyring). In this case, lookup NAME in
1071 * the local keyring. */
1072 add_to_strlist (&namelist, name);
1073 rc = key_byname (ctrl, retctx, namelist, pk, 0,
1074 include_unusable, ret_keyblock, ret_kdbhd);
1077 /* If the requested name resembles a valid mailbox and automatic
1078 retrieval has been enabled, we try to import the key. */
1079 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1080 && mode != GET_PUBKEY_NO_AKL
1081 && (is_mbox || is_fpr))
1083 /* NAME wasn't present in the local keyring (or we didn't try
1084 * the local keyring). Since the auto key locate feature is
1085 * enabled and NAME appears to be an email address, try the auto
1086 * locate feature. */
1087 for (akl = opt.auto_key_locate; akl; akl = akl->next)
1089 unsigned char *fpr = NULL;
1091 int did_akl_local = 0;
1092 int no_fingerprint = 0;
1093 const char *mechanism_string = "?";
1095 mechanism_type = akl->type;
1096 switch (mechanism_type)
1099 /* This is a dummy mechanism. */
1100 mechanism_string = "";
1101 rc = GPG_ERR_NO_PUBKEY;
1105 if (mode == GET_PUBKEY_NO_LOCAL)
1107 /* Note that we get here in is_fpr more, so there is
1108 * no extra check for it required. */
1109 mechanism_string = "";
1110 rc = GPG_ERR_NO_PUBKEY;
1114 mechanism_string = "Local";
1118 getkey_end (ctrl, *retctx);
1121 add_to_strlist (&namelist, name);
1122 rc = key_byname (ctrl, anylocalfirst ? retctx : NULL,
1124 include_unusable, ret_keyblock, ret_kdbhd);
1131 mechanism_string = "";
1132 rc = GPG_ERR_NO_PUBKEY;
1136 mechanism_string = "DNS CERT";
1137 glo_ctrl.in_auto_key_retrieve++;
1138 rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len);
1139 glo_ctrl.in_auto_key_retrieve--;
1144 /* This is now obsolete. */
1150 mechanism_string = "";
1151 rc = GPG_ERR_NO_PUBKEY;
1156 mechanism_string = "DANE";
1157 glo_ctrl.in_auto_key_retrieve++;
1158 rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len);
1159 glo_ctrl.in_auto_key_retrieve--;
1166 mechanism_string = "";
1167 rc = GPG_ERR_NO_PUBKEY;
1171 mechanism_string = "WKD";
1172 glo_ctrl.in_auto_key_retrieve++;
1173 rc = keyserver_import_wkd (ctrl, name, 0, &fpr, &fpr_len);
1174 glo_ctrl.in_auto_key_retrieve--;
1181 mechanism_string = "";
1182 rc = GPG_ERR_NO_PUBKEY;
1186 mechanism_string = "LDAP";
1187 glo_ctrl.in_auto_key_retrieve++;
1188 rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
1189 glo_ctrl.in_auto_key_retrieve--;
1194 mechanism_string = "NTDS";
1195 glo_ctrl.in_auto_key_retrieve++;
1197 rc = keyserver_import_fprint_ntds (ctrl,
1198 fprbuf.u.fpr, fprbuf.fprlen);
1200 rc = keyserver_import_ntds (ctrl, name, &fpr, &fpr_len);
1201 glo_ctrl.in_auto_key_retrieve--;
1205 /* Strictly speaking, we don't need to only use a valid
1206 * mailbox for the getname search, but it helps cut down
1207 * on the problem of searching for something like "john"
1208 * and getting a whole lot of keys back. */
1209 if (keyserver_any_configured (ctrl))
1211 mechanism_string = "keyserver";
1212 glo_ctrl.in_auto_key_retrieve++;
1215 rc = keyserver_import_fprint (ctrl,
1216 fprbuf.u.fpr, fprbuf.fprlen,
1218 KEYSERVER_IMPORT_FLAG_LDAP);
1219 /* Map error codes because Dirmngr returns NO
1220 * DATA if the keyserver does not have the
1221 * requested key. It returns NO KEYSERVER if no
1222 * LDAP keyservers are configured. */
1223 if (gpg_err_code (rc) == GPG_ERR_NO_DATA
1224 || gpg_err_code (rc) == GPG_ERR_NO_KEYSERVER)
1225 rc = gpg_error (GPG_ERR_NO_PUBKEY);
1229 rc = keyserver_import_mbox (ctrl, name, &fpr, &fpr_len,
1232 glo_ctrl.in_auto_key_retrieve--;
1236 mechanism_string = "Unconfigured keyserver";
1237 rc = GPG_ERR_NO_PUBKEY;
1243 struct keyserver_spec *keyserver;
1245 mechanism_string = akl->spec->uri;
1246 keyserver = keyserver_match (akl->spec);
1247 glo_ctrl.in_auto_key_retrieve++;
1250 rc = keyserver_import_fprint (ctrl,
1251 fprbuf.u.fpr, fprbuf.fprlen,
1253 KEYSERVER_IMPORT_FLAG_LDAP);
1254 if (gpg_err_code (rc) == GPG_ERR_NO_DATA
1255 || gpg_err_code (rc) == GPG_ERR_NO_KEYSERVER)
1256 rc = gpg_error (GPG_ERR_NO_PUBKEY);
1260 rc = keyserver_import_mbox (ctrl, name,
1261 &fpr, &fpr_len, keyserver);
1263 glo_ctrl.in_auto_key_retrieve--;
1268 /* Use the fingerprint of the key that we actually fetched.
1269 * This helps prevent problems where the key that we fetched
1270 * doesn't have the same name that we used to fetch it. In
1271 * the case of CERT, this is an actual security
1272 * requirement as the URL might point to a key put in by an
1273 * attacker. By forcing the use of the fingerprint, we
1274 * won't use the attacker's key here. */
1275 if (!rc && (fpr || is_fpr))
1277 char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
1281 log_assert (fprbuf.fprlen <= MAX_FINGERPRINT_LEN);
1282 bin2hex (fprbuf.u.fpr, fprbuf.fprlen, fpr_string);
1286 log_assert (fpr_len <= MAX_FINGERPRINT_LEN);
1287 bin2hex (fpr, fpr_len, fpr_string);
1291 log_info ("auto-key-locate found fingerprint %s\n",
1294 free_strlist (namelist);
1296 add_to_strlist (&namelist, fpr_string);
1298 else if (!rc && !fpr && !did_akl_local)
1299 { /* The acquisition method said no failure occurred, but
1300 * it didn't return a fingerprint. That's a failure. */
1302 rc = GPG_ERR_NO_PUBKEY;
1307 if (!rc && !did_akl_local)
1308 { /* There was no error and we didn't do a local lookup.
1309 * This means that we imported a key into the local
1310 * keyring. Try to read the imported key from the
1314 getkey_end (ctrl, *retctx);
1317 rc = key_byname (ctrl, anylocalfirst ? retctx : NULL,
1319 include_unusable, ret_keyblock, ret_kdbhd);
1325 log_info (_("automatically retrieved '%s' via %s\n"),
1326 name, mechanism_string);
1329 if ((gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1330 || opt.verbose || no_fingerprint) && *mechanism_string)
1331 log_info (_("error retrieving '%s' via %s: %s\n"),
1332 name, mechanism_string,
1333 no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
1339 getkey_end (ctrl, *retctx);
1343 if (retctx && *retctx)
1345 GETKEY_CTX ctx = *retctx;
1348 if (ctx->extra_list)
1350 for (sl=ctx->extra_list; sl->next; sl = sl->next)
1352 sl->next = namelist;
1355 ctx->extra_list = namelist;
1356 (*retctx)->found_via_akl = mechanism_type;
1359 free_strlist (namelist);
1367 /* Comparison machinery for get_best_pubkey_byname. */
1369 /* First we have a struct to cache computed information about the key
1371 struct pubkey_cmp_cookie
1373 int valid; /* Is this cookie valid? */
1374 PKT_public_key key; /* The key. */
1375 PKT_user_id *uid; /* The matching UID packet. */
1376 unsigned int validity; /* Computed validity of (KEY, UID). */
1377 u32 creation_time; /* Creation time of the newest subkey
1378 capable of encryption. */
1382 /* Then we have a series of helper functions. */
1384 key_is_ok (const PKT_public_key *key)
1386 return (! key->has_expired && ! key->flags.revoked
1387 && key->flags.valid && ! key->flags.disabled);
1392 uid_is_ok (const PKT_public_key *key, const PKT_user_id *uid)
1394 return key_is_ok (key) && ! uid->flags.revoked;
1399 subkey_is_ok (const PKT_public_key *sub)
1401 return ! sub->flags.revoked && sub->flags.valid && ! sub->flags.disabled;
1404 /* Return true if KEYBLOCK has only expired encryption subkeys. Note
1405 * that the function returns false if the key has no encryption
1406 * subkeys at all or the subkeys are revoked. */
1408 only_expired_enc_subkeys (kbnode_t keyblock)
1411 PKT_public_key *sub;
1414 for (node = find_next_kbnode (keyblock, PKT_PUBLIC_SUBKEY);
1415 node; node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY))
1417 sub = node->pkt->pkt.public_key;
1419 if (!(sub->pubkey_usage & PUBKEY_USAGE_ENC))
1422 if (!subkey_is_ok (sub))
1426 if (!sub->has_expired)
1433 /* Finally this function compares a NEW key to the former candidate
1434 * OLD. Returns < 0 if the old key is worse, > 0 if the old key is
1435 * better, == 0 if it is a tie. */
1437 pubkey_cmp (ctrl_t ctrl, const char *name, struct pubkey_cmp_cookie *old,
1438 struct pubkey_cmp_cookie *new, KBNODE new_keyblock)
1442 if ((new->key.pubkey_usage & PUBKEY_USAGE_ENC) == 0)
1443 new->creation_time = 0;
1445 new->creation_time = new->key.timestamp;
1447 for (n = find_next_kbnode (new_keyblock, PKT_PUBLIC_SUBKEY);
1448 n; n = find_next_kbnode (n, PKT_PUBLIC_SUBKEY))
1450 PKT_public_key *sub = n->pkt->pkt.public_key;
1452 if ((sub->pubkey_usage & PUBKEY_USAGE_ENC) == 0)
1455 if (! subkey_is_ok (sub))
1458 if (sub->timestamp > new->creation_time)
1459 new->creation_time = sub->timestamp;
1462 /* When new key has no encryption key, use OLD key. */
1463 if (new->creation_time == 0)
1466 for (n = find_next_kbnode (new_keyblock, PKT_USER_ID);
1467 n; n = find_next_kbnode (n, PKT_USER_ID))
1469 PKT_user_id *uid = n->pkt->pkt.user_id;
1470 char *mbox = mailbox_from_userid (uid->name, 0);
1471 int match = mbox ? strcasecmp (name, mbox) == 0 : 0;
1477 new->uid = scopy_user_id (uid);
1479 get_validity (ctrl, new_keyblock, &new->key, uid, NULL, 0) & TRUST_MASK;
1483 return -1; /* No OLD key. */
1485 if (! uid_is_ok (&old->key, old->uid) && uid_is_ok (&new->key, uid))
1486 return -1; /* Validity of the NEW key is better. */
1488 if (new->validity != TRUST_EXPIRED && old->validity < new->validity)
1489 return -1; /* Validity of the NEW key is better. */
1490 if (old->validity == TRUST_EXPIRED && new->validity != TRUST_EXPIRED)
1491 return -1; /* Validity of the NEW key is better. */
1493 if (old->validity == new->validity && uid_is_ok (&new->key, uid)
1494 && old->creation_time < new->creation_time)
1495 return -1; /* Both keys are of the same validity, but the
1496 NEW key is newer. */
1499 /* Stick with the OLD key. */
1504 /* This function works like get_pubkey_byname, but if the name
1505 * resembles a mail address, the results are ranked and only the best
1506 * result is returned. */
1508 get_best_pubkey_byname (ctrl_t ctrl, enum get_pubkey_modes mode,
1509 GETKEY_CTX *retctx, PKT_public_key *pk,
1510 const char *name, KBNODE *ret_keyblock,
1511 int include_unusable)
1514 struct getkey_ctx_s *ctx = NULL;
1519 log_assert (ret_keyblock != NULL);
1524 memset (&pk0, 0, sizeof pk0);
1525 pk0.req_usage = pk? pk->req_usage : 0;
1527 is_mbox = is_valid_mailbox (name);
1528 if (!is_mbox && *name == '<' && name[1] && name[strlen(name)-1]=='>'
1530 && is_valid_mailbox_mem (name+1, strlen (name)-2))
1532 /* The mailbox is in the form "<foo@example.org>" which is not
1533 * detected by is_valid_mailbox. Set the flag but keep name as
1534 * it is because get_pubkey_byname does an is_valid_mailbox_mem
1540 if (ctx) /* Clear in case of a start over. */
1542 release_kbnode (*ret_keyblock);
1543 *ret_keyblock = NULL;
1544 getkey_end (ctrl, ctx);
1547 err = get_pubkey_byname (ctrl, mode,
1548 &ctx, &pk0, name, ret_keyblock,
1549 NULL, include_unusable);
1555 /* If the keyblock was retrieved from the local database and the key
1556 * has expired, do further checks. However, we can do this only if
1557 * the caller requested a keyblock. */
1558 if (is_mbox && ctx && ctx->found_via_akl == AKL_LOCAL)
1560 u32 now = make_timestamp ();
1563 /* If the key has expired and its origin was the WKD then try to
1564 * get a fresh key from the WKD. We also try this if the key
1565 * has any only expired encryption subkeys. In case we checked
1566 * for a fresh copy in the last 3 hours we won't do that again.
1567 * Unfortunately that does not yet work because KEYUPDATE is
1568 * only updated during import iff the key has actually changed
1569 * (see import.c:import_one). */
1570 if (!wkd_tried && pk0.keyorg == KEYORG_WKD
1571 && (pk0.keyupdate + 3*3600) < now
1572 && (pk0.has_expired || only_expired_enc_subkeys (*ret_keyblock)))
1575 log_info (_("checking for a fresh copy of an expired key via %s\n"),
1578 glo_ctrl.in_auto_key_retrieve++;
1579 found = !keyserver_import_wkd (ctrl, name, 0, NULL, NULL);
1580 glo_ctrl.in_auto_key_retrieve--;
1583 release_public_key_parts (&pk0);
1591 /* Rank results and return only the most relevant key for encryption. */
1592 struct pubkey_cmp_cookie best = { 0 };
1593 struct pubkey_cmp_cookie new = { 0 };
1594 kbnode_t new_keyblock;
1596 copy_public_key (&new.key, &pk0);
1597 if (pubkey_cmp (ctrl, name, &best, &new, *ret_keyblock) >= 0)
1599 release_public_key_parts (&new.key);
1600 free_user_id (new.uid);
1606 while (getkey_next (ctrl, ctx, &new.key, &new_keyblock) == 0)
1608 int diff = pubkey_cmp (ctrl, name, &best, &new, new_keyblock);
1609 release_kbnode (new_keyblock);
1612 /* New key is better. */
1613 release_public_key_parts (&best.key);
1614 free_user_id (best.uid);
1619 /* Old key is better. */
1620 release_public_key_parts (&new.key);
1621 free_user_id (new.uid);
1625 /* A tie. Keep the old key. */
1626 release_public_key_parts (&new.key);
1627 free_user_id (new.uid);
1632 getkey_end (ctrl, ctx);
1634 free_user_id (best.uid);
1639 ctx = xtrycalloc (1, sizeof **retctx);
1641 err = gpg_error_from_syserror ();
1644 ctx->kr_handle = keydb_new (ctrl);
1645 if (! ctx->kr_handle)
1647 err = gpg_error_from_syserror ();
1655 u32 *keyid = pk_keyid (&best.key);
1658 ctx->items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
1659 ctx->items[0].u.kid[0] = keyid[0];
1660 ctx->items[0].u.kid[1] = keyid[1];
1662 release_kbnode (*ret_keyblock);
1663 *ret_keyblock = NULL;
1664 err = getkey_next (ctrl, ctx, NULL, ret_keyblock);
1671 release_public_key_parts (&best.key);
1672 release_public_key_parts (&pk0);
1679 release_public_key_parts (&pk0);
1687 release_public_key_parts (&pk0);
1692 getkey_end (ctrl, ctx);
1703 getkey_end (ctrl, ctx);
1709 /* Get a public key from a file.
1711 * PK is the buffer to store the key. The caller needs to make sure
1712 * that PK->REQ_USAGE is valid. PK->REQ_USAGE is passed through to
1713 * the lookup function and is a mask of PUBKEY_USAGE_SIG,
1714 * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this is non-zero, only
1715 * keys with the specified usage will be returned.
1717 * FNAME is the file name. That file should contain exactly one
1720 * This function returns 0 on success. Otherwise, an error code is
1721 * returned. In particular, GPG_ERR_NO_PUBKEY is returned if the key
1722 * is not found. If R_KEYBLOCK is not NULL and a key was found the
1723 * keyblock is stored there; otherwiese NULL is stored there.
1725 * The self-signed data has already been merged into the public key
1726 * using merge_selfsigs. The caller must release the content of PK by
1727 * calling release_public_key_parts (or, if PK was malloced, using
1731 get_pubkey_fromfile (ctrl_t ctrl, PKT_public_key *pk, const char *fname,
1732 kbnode_t *r_keyblock)
1737 unsigned int infoflags;
1742 err = read_key_from_file_or_buffer (ctrl, fname, NULL, 0, &keyblock);
1745 /* Warning: node flag bits 0 and 1 should be preserved by
1746 * merge_selfsigs. FIXME: Check whether this still holds. */
1747 merge_selfsigs (ctrl, keyblock);
1748 found_key = finish_lookup (keyblock, pk->req_usage, 0, 0, &infoflags);
1749 print_status_key_considered (keyblock, infoflags);
1751 pk_from_block (pk, keyblock, found_key);
1753 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
1756 if (!err && r_keyblock)
1757 *r_keyblock = keyblock;
1759 release_kbnode (keyblock);
1764 /* Return a public key from the buffer (BUFFER, BUFLEN). The key is
1765 * onlyretruned if it matches the keyid given in WANT_KEYID. On
1766 * success the key is stored at the caller provided PKBUF structure.
1767 * The caller must release the content of PK by calling
1768 * release_public_key_parts (or, if PKBUF was malloced, using
1769 * free_public_key). If R_KEYBLOCK is not NULL the full keyblock is
1770 * also stored there. */
1772 get_pubkey_from_buffer (ctrl_t ctrl, PKT_public_key *pkbuf,
1773 const void *buffer, size_t buflen, u32 *want_keyid,
1774 kbnode_t *r_keyblock)
1784 err = read_key_from_file_or_buffer (ctrl, NULL, buffer, buflen, &keyblock);
1787 merge_selfsigs (ctrl, keyblock);
1788 for (node = keyblock; node; node = node->next)
1790 if (node->pkt->pkttype == PKT_PUBLIC_KEY
1791 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1793 pk = node->pkt->pkt.public_key;
1794 keyid_from_pk (pk, NULL);
1795 if (pk->keyid[0] == want_keyid[0]
1796 && pk->keyid[1] == want_keyid[1])
1801 copy_public_key (pkbuf, pk);
1803 err = gpg_error (GPG_ERR_NO_PUBKEY);
1806 if (!err && r_keyblock)
1807 *r_keyblock = keyblock;
1809 release_kbnode (keyblock);
1814 /* Lookup a key with the specified fingerprint.
1816 * If PK is not NULL, the public key of the first result is returned
1817 * in *PK. Note: this function does an exact search and thus the
1818 * returned public key may be a subkey rather than the primary key.
1819 * Note: The self-signed data has already been merged into the public
1820 * key using merge_selfsigs. Free *PK by calling
1821 * release_public_key_parts (or, if PK was allocated using xmalloc, you
1822 * can use free_public_key, which calls release_public_key_parts(PK)
1823 * and then xfree(PK)).
1825 * If PK->REQ_USAGE is set, it is used to filter the search results.
1826 * Thus, if PK is not NULL, PK->REQ_USAGE must be valid! See the
1827 * documentation for finish_lookup to understand exactly how this is
1830 * If R_KEYBLOCK is not NULL, then the first result's keyblock is
1831 * returned in *R_KEYBLOCK. This should be freed using
1834 * FPRINT is a byte array whose contents is the fingerprint to use as
1835 * the search term. FPRINT_LEN specifies the length of the
1836 * fingerprint (in bytes). Currently, only 16, 20, and 32-byte
1837 * fingerprints are supported.
1839 * FIXME: We should replace this with the _byname function. This can
1840 * be done by creating a userID conforming to the unified fingerprint
1843 get_pubkey_byfprint (ctrl_t ctrl, PKT_public_key *pk, kbnode_t *r_keyblock,
1844 const byte * fprint, size_t fprint_len)
1851 if (fprint_len == 32 || fprint_len == 20 || fprint_len == 16)
1853 struct getkey_ctx_s ctx;
1855 KBNODE found_key = NULL;
1857 memset (&ctx, 0, sizeof ctx);
1859 ctx.not_allocated = 1;
1860 /* FIXME: We should get the handle from the cache like we do in
1862 ctx.kr_handle = keydb_new (ctrl);
1864 return gpg_error_from_syserror ();
1867 ctx.items[0].mode = KEYDB_SEARCH_MODE_FPR;
1868 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1869 ctx.items[0].fprlen = fprint_len;
1871 ctx.req_usage = pk->req_usage;
1872 rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
1874 pk_from_block (pk, kb, found_key);
1875 if (!rc && r_keyblock)
1880 release_kbnode (kb);
1881 getkey_end (ctrl, &ctx);
1884 rc = GPG_ERR_GENERAL; /* Oops */
1889 /* This function is similar to get_pubkey_byfprint, but it doesn't
1890 * merge the self-signed data into the public key and subkeys or into
1891 * the user ids. It also doesn't add the key to the user id cache.
1892 * Further, this function ignores PK->REQ_USAGE.
1894 * This function is intended to avoid recursion and, as such, should
1895 * only be used in very specific situations.
1897 * Like get_pubkey_byfprint, PK may be NULL. In that case, this
1898 * function effectively just checks for the existence of the key. */
1900 get_pubkey_byfprint_fast (ctrl_t ctrl, PKT_public_key * pk,
1901 const byte * fprint, size_t fprint_len)
1906 err = get_keyblock_byfprint_fast (ctrl,
1907 &keyblock, NULL, fprint, fprint_len, 0);
1911 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1912 release_kbnode (keyblock);
1919 /* This function is similar to get_pubkey_byfprint_fast but returns a
1920 * keydb handle at R_HD and the keyblock at R_KEYBLOCK. R_KEYBLOCK or
1921 * R_HD may be NULL. If LOCK is set the handle has been opend in
1922 * locked mode and keydb_disable_caching () has been called. On error
1923 * R_KEYBLOCK is set to NULL but R_HD must be released by the caller;
1924 * it may have a value of NULL, though. This allows to do an insert
1925 * operation on a locked keydb handle. */
1927 get_keyblock_byfprint_fast (ctrl_t ctrl,
1928 kbnode_t *r_keyblock, KEYDB_HANDLE *r_hd,
1929 const byte *fprint, size_t fprint_len, int lock)
1934 byte fprbuf[MAX_FINGERPRINT_LEN];
1942 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1943 fprbuf[i] = fprint[i];
1945 hd = keydb_new (ctrl);
1947 return gpg_error_from_syserror ();
1951 err = keydb_lock (hd);
1954 /* If locking did not work, we better don't return a handle
1955 * at all - there was a reason that locking has been
1960 keydb_disable_caching (hd);
1963 /* For all other errors we return the handle. */
1967 err = keydb_search_fpr (hd, fprbuf, fprint_len);
1968 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1972 return gpg_error (GPG_ERR_NO_PUBKEY);
1974 err = keydb_get_keyblock (hd, &keyblock);
1977 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (err));
1980 return gpg_error (GPG_ERR_NO_PUBKEY);
1983 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1984 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1986 /* Not caching key here since it won't have all of the fields
1990 *r_keyblock = keyblock;
1992 release_kbnode (keyblock);
2002 parse_def_secret_key (ctrl_t ctrl)
2004 KEYDB_HANDLE hd = NULL;
2008 for (t = opt.def_secret_key; t; t = t->next)
2011 KEYDB_SEARCH_DESC desc;
2015 err = classify_user_id (t->d, &desc, 1);
2018 log_error (_("secret key \"%s\" not found: %s\n"),
2019 t->d, gpg_strerror (err));
2021 log_info (_("(check argument of option '%s')\n"), "--default-key");
2027 hd = keydb_new (ctrl);
2032 keydb_search_reset (hd);
2035 err = keydb_search (hd, &desc, 1, NULL);
2036 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2041 log_error (_("key \"%s\" not found: %s\n"), t->d, gpg_strerror (err));
2046 err = keydb_get_keyblock (hd, &kb);
2049 log_error (_("error reading keyblock: %s\n"),
2050 gpg_strerror (err));
2054 merge_selfsigs (ctrl, kb);
2056 err = gpg_error (GPG_ERR_NO_SECKEY);
2060 PKT_public_key *pk = node->pkt->pkt.public_key;
2062 /* Check if the key is valid. */
2063 if (pk->flags.revoked)
2066 log_debug ("not using %s as default key, %s",
2067 keystr_from_pk (pk), "revoked");
2070 if (pk->has_expired)
2073 log_debug ("not using %s as default key, %s",
2074 keystr_from_pk (pk), "expired");
2077 if (pk_is_disabled (pk))
2080 log_debug ("not using %s as default key, %s",
2081 keystr_from_pk (pk), "disabled");
2085 if (agent_probe_secret_key (ctrl, pk))
2087 /* This is a valid key. */
2092 while ((node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY)));
2094 release_kbnode (kb);
2097 if (! warned && ! opt.quiet)
2099 log_info (_("Warning: not using '%s' as default key: %s\n"),
2100 t->d, gpg_strerror (GPG_ERR_NO_SECKEY));
2101 print_reported_error (err, GPG_ERR_NO_SECKEY);
2106 if (! warned && ! opt.quiet)
2107 log_info (_("using \"%s\" as default secret key for signing\n"),
2113 if (! warned && opt.def_secret_key && ! t)
2114 log_info (_("all values passed to '%s' ignored\n"),
2128 /* Look up a secret key.
2130 * If PK is not NULL, the public key of the first result is returned
2131 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2132 * set, it is used to filter the search results. See the
2133 * documentation for finish_lookup to understand exactly how this is
2134 * used. Note: The self-signed data has already been merged into the
2135 * public key using merge_selfsigs. Free *PK by calling
2136 * release_public_key_parts (or, if PK was allocated using xfree, you
2137 * can use free_public_key, which calls release_public_key_parts(PK)
2138 * and then xfree(PK)).
2140 * If --default-key was set, then the specified key is looked up. (In
2141 * this case, the default key is returned even if it is considered
2142 * unusable. See the documentation for skip_unusable for exactly what
2145 * Otherwise, this initiates a DB scan that returns all keys that are
2146 * usable (see previous paragraph for exactly what usable means) and
2147 * for which a secret key is available.
2149 * This function returns the first match. Additional results can be
2150 * returned using getkey_next. */
2152 get_seckey_default (ctrl_t ctrl, PKT_public_key *pk)
2155 strlist_t namelist = NULL;
2156 int include_unusable = 1;
2159 const char *def_secret_key = parse_def_secret_key (ctrl);
2161 add_to_strlist (&namelist, def_secret_key);
2163 include_unusable = 0;
2165 err = key_byname (ctrl, NULL, namelist, pk, 1, include_unusable, NULL, NULL);
2167 free_strlist (namelist);
2174 /* Search for keys matching some criteria.
2176 * If RETCTX is not NULL, then the constructed context is returned in
2177 * *RETCTX so that getpubkey_next can be used to get subsequent
2178 * results. In this case, getkey_end() must be used to free the
2179 * search context. If RETCTX is not NULL, then RET_KDBHD must be
2182 * If PK is not NULL, the public key of the first result is returned
2183 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2184 * set, it is used to filter the search results. See the
2185 * documentation for finish_lookup to understand exactly how this is
2186 * used. Note: The self-signed data has already been merged into the
2187 * public key using merge_selfsigs. Free *PK by calling
2188 * release_public_key_parts (or, if PK was allocated using xfree, you
2189 * can use free_public_key, which calls release_public_key_parts(PK)
2190 * and then xfree(PK)).
2192 * If NAMES is not NULL, then a search query is constructed using
2193 * classify_user_id on each of the strings in the list. (Recall: the
2194 * database does an OR of the terms, not an AND.) If NAMES is
2195 * NULL, then all results are returned.
2197 * If WANT_SECRET is set, then only keys with an available secret key
2198 * (either locally or via key registered on a smartcard) are returned.
2200 * This function does not skip unusable keys (see the documentation
2201 * for skip_unusable for an exact definition).
2203 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2204 * *RET_KEYBLOCK. This should be freed using release_kbnode().
2206 * This function returns 0 on success. Otherwise, an error code is
2207 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2208 * (if want_secret is set) is returned if the key is not found. */
2210 getkey_bynames (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2211 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
2213 return key_byname (ctrl, retctx, names, pk, want_secret, 1,
2214 ret_keyblock, NULL);
2218 /* Search for one key matching some criteria.
2220 * If RETCTX is not NULL, then the constructed context is returned in
2221 * *RETCTX so that getpubkey_next can be used to get subsequent
2222 * results. In this case, getkey_end() must be used to free the
2223 * search context. If RETCTX is not NULL, then RET_KDBHD must be
2226 * If PK is not NULL, the public key of the first result is returned
2227 * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is
2228 * set, it is used to filter the search results. See the
2229 * documentation for finish_lookup to understand exactly how this is
2230 * used. Note: The self-signed data has already been merged into the
2231 * public key using merge_selfsigs. Free *PK by calling
2232 * release_public_key_parts (or, if PK was allocated using xfree, you
2233 * can use free_public_key, which calls release_public_key_parts(PK)
2234 * and then xfree(PK)).
2236 * If NAME is not NULL, then a search query is constructed using
2237 * classify_user_id on the string. In this case, even unusable keys
2238 * (see the documentation for skip_unusable for an exact definition of
2239 * unusable) are returned. Otherwise, if --default-key was set, then
2240 * that key is returned (even if it is unusable). If neither of these
2241 * conditions holds, then the first usable key is returned.
2243 * If WANT_SECRET is set, then only keys with an available secret key
2244 * (either locally or via key registered on a smartcard) are returned.
2246 * This function does not skip unusable keys (see the documentation
2247 * for skip_unusable for an exact definition).
2249 * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2250 * *RET_KEYBLOCK. This should be freed using release_kbnode().
2252 * This function returns 0 on success. Otherwise, an error code is
2253 * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2254 * (if want_secret is set) is returned if the key is not found.
2256 * FIXME: We also have the get_pubkey_byname function which has a
2257 * different semantic. Should be merged with this one. */
2259 getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2260 const char *name, int want_secret, kbnode_t *ret_keyblock)
2263 strlist_t namelist = NULL;
2264 int with_unusable = 1;
2265 const char *def_secret_key = NULL;
2267 if (want_secret && !name)
2268 def_secret_key = parse_def_secret_key (ctrl);
2270 if (want_secret && !name && def_secret_key)
2271 add_to_strlist (&namelist, def_secret_key);
2273 add_to_strlist (&namelist, name);
2277 err = key_byname (ctrl, retctx, namelist, pk, want_secret, with_unusable,
2278 ret_keyblock, NULL);
2280 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
2281 WANT_SECRET has been used. */
2283 free_strlist (namelist);
2289 /* Return the next search result.
2291 * If PK is not NULL, the public key of the next result is returned in
2292 * *PK. Note: The self-signed data has already been merged into the
2293 * public key using merge_selfsigs. Free *PK by calling
2294 * release_public_key_parts (or, if PK was allocated using xmalloc, you
2295 * can use free_public_key, which calls release_public_key_parts(PK)
2296 * and then xfree(PK)).
2298 * RET_KEYBLOCK can be given as NULL; if it is not NULL it the entire
2299 * found keyblock is returned which must be released with
2300 * release_kbnode. If the function returns an error NULL is stored at
2303 * The self-signed data has already been merged into the public key
2304 * using merge_selfsigs. */
2306 getkey_next (ctrl_t ctrl, getkey_ctx_t ctx,
2307 PKT_public_key *pk, kbnode_t *ret_keyblock)
2309 int rc; /* Fixme: Make sure this is proper gpg_error */
2310 KBNODE keyblock = NULL;
2311 KBNODE found_key = NULL;
2313 /* We need to disable the caching so that for an exact key search we
2314 won't get the result back from the cache and thus end up in an
2315 endless loop. The endless loop can occur, because the cache is
2316 used without respecting the current file pointer! */
2317 keydb_disable_caching (ctx->kr_handle);
2319 /* FOUND_KEY is only valid as long as RET_KEYBLOCK is. If the
2320 * caller wants PK, but not RET_KEYBLOCK, we need hand in our own
2322 if (pk && ret_keyblock == NULL)
2323 ret_keyblock = &keyblock;
2325 rc = lookup (ctrl, ctx, ctx->want_secret,
2326 ret_keyblock, pk ? &found_key : NULL);
2329 log_assert (found_key);
2330 pk_from_block (pk, NULL, found_key);
2331 release_kbnode (keyblock);
2338 /* Release any resources used by a key listing context. This must be
2339 * called on the context returned by, e.g., getkey_byname. */
2341 getkey_end (ctrl_t ctrl, getkey_ctx_t ctx)
2345 #ifdef HAVE_W32_SYSTEM
2347 /* FIXME: This creates a big regression for Windows because the
2348 * keyring is only released after the global ctrl is released.
2349 * So if an operation does a getkey and then tries to modify the
2350 * keyring it will fail on Windows with a sharing violation. We
2351 * need to modify all keyring write operations to also take the
2352 * ctrl and close the cached_getkey_kdb handle to make writing
2353 * work. See: GnuPG-bug-id: 3097 */
2355 keydb_release (ctx->kr_handle);
2357 #else /*!HAVE_W32_SYSTEM*/
2359 if (ctrl && !ctrl->cached_getkey_kdb)
2360 ctrl->cached_getkey_kdb = ctx->kr_handle;
2362 keydb_release (ctx->kr_handle);
2364 #endif /*!HAVE_W32_SYSTEM*/
2366 free_strlist (ctx->extra_list);
2367 if (!ctx->not_allocated)
2374 /************************************************
2375 ************* Merging stuff ********************
2376 ************************************************/
2378 /* Set the mainkey_id fields for all keys in KEYBLOCK. This is
2379 * usually done by merge_selfsigs but at some places we only need the
2380 * main_kid not a full merge. The function also guarantees that all
2381 * pk->keyids are computed. */
2383 setup_main_keyids (kbnode_t keyblock)
2385 u32 kid[2], mainkid[2];
2386 kbnode_t kbctx, node;
2389 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2391 pk = keyblock->pkt->pkt.public_key;
2393 keyid_from_pk (pk, mainkid);
2394 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
2396 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
2397 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
2399 pk = node->pkt->pkt.public_key;
2400 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
2401 if (!pk->main_keyid[0] && !pk->main_keyid[1])
2403 pk->main_keyid[0] = mainkid[0];
2404 pk->main_keyid[1] = mainkid[1];
2410 /* KEYBLOCK corresponds to a public key block. This function merges
2411 * much of the information from the self-signed data into the public
2412 * key, public subkey and user id data structures. If you use the
2413 * high-level search API (e.g., get_pubkey) for looking up key blocks,
2414 * then you don't need to call this function. This function is
2415 * useful, however, if you change the keyblock, e.g., by adding or
2416 * removing a self-signed data packet. */
2418 merge_keys_and_selfsig (ctrl_t ctrl, kbnode_t keyblock)
2422 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
2423 merge_selfsigs (ctrl, keyblock);
2425 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
2429 /* This function parses the key flags and returns PUBKEY_USAGE_ flags. */
2431 parse_key_usage (PKT_signature * sig)
2438 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_FLAGS, &n);
2441 /* First octet of the keyflags. */
2446 key_usage |= PUBKEY_USAGE_CERT;
2452 key_usage |= PUBKEY_USAGE_SIG;
2456 /* We do not distinguish between encrypting communications and
2457 encrypting storage. */
2458 if (flags & (0x04 | 0x08))
2460 key_usage |= PUBKEY_USAGE_ENC;
2461 flags &= ~(0x04 | 0x08);
2466 key_usage |= PUBKEY_USAGE_AUTH;
2472 key_usage |= PUBKEY_USAGE_GROUP;
2477 key_usage |= PUBKEY_USAGE_UNKNOWN;
2485 key_usage |= PUBKEY_USAGE_RENC;
2487 key_usage |= PUBKEY_USAGE_TIME;
2491 key_usage |= PUBKEY_USAGE_NONE;
2494 else if (p) /* Key flags of length zero. */
2495 key_usage |= PUBKEY_USAGE_NONE;
2497 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
2498 capability that we do not handle. This serves to distinguish
2499 between a zero key usage which we handle as the default
2500 capabilities for that algorithm, and a usage that we do not
2501 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
2502 key_flags have been given but they do not specify any usage. */
2508 /* Apply information from SIGNODE (which is the valid self-signature
2509 * associated with that UID) to the UIDNODE:
2510 * - wether the UID has been revoked
2511 * - assumed creation date of the UID
2512 * - temporary store the keyflags here
2513 * - temporary store the key expiration time here
2514 * - mark whether the primary user ID flag hat been set.
2515 * - store the preferences
2518 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
2520 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
2521 PKT_signature *sig = signode->pkt->pkt.signature;
2522 const byte *p, *sym, *aead, *hash, *zip;
2523 size_t n, nsym, naead, nhash, nzip;
2525 sig->flags.chosen_selfsig = 1;/* We chose this one. */
2526 uid->created = 0; /* Not created == invalid. */
2527 if (IS_UID_REV (sig))
2529 uid->flags.revoked = 1;
2530 return; /* Has been revoked. */
2533 uid->flags.revoked = 0;
2535 uid->expiredate = sig->expiredate;
2537 if (sig->flags.expired)
2539 uid->flags.expired = 1;
2540 return; /* Has expired. */
2543 uid->flags.expired = 0;
2545 uid->created = sig->timestamp; /* This one is okay. */
2546 uid->selfsigversion = sig->version;
2547 /* If we got this far, it's not expired :) */
2548 uid->flags.expired = 0;
2550 /* Store the key flags in the helper variable for later processing. */
2551 uid->help_key_usage = parse_key_usage (sig);
2553 /* Ditto for the key expiration. */
2554 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
2555 if (p && buf32_to_u32 (p))
2556 uid->help_key_expire = keycreated + buf32_to_u32 (p);
2558 uid->help_key_expire = 0;
2560 /* Set the primary user ID flag - we will later wipe out some
2561 * of them to only have one in our keyblock. */
2562 uid->flags.primary = 0;
2563 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PRIMARY_UID, NULL);
2565 uid->flags.primary = 2;
2567 /* We could also query this from the unhashed area if it is not in
2568 * the hased area and then later try to decide which is the better
2569 * there should be no security problem with this.
2570 * For now we only look at the hashed one. */
2572 /* Now build the preferences list. These must come from the
2573 hashed section so nobody can modify the ciphers a key is
2574 willing to accept. */
2575 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_SYM, &n);
2578 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_AEAD, &n);
2581 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_HASH, &n);
2584 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_COMPR, &n);
2589 n = nsym + naead + nhash + nzip;
2594 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
2596 for (; nsym; nsym--, n++)
2598 uid->prefs[n].type = PREFTYPE_SYM;
2599 uid->prefs[n].value = *sym++;
2601 for (; naead; naead--, n++)
2603 uid->prefs[n].type = PREFTYPE_AEAD;
2604 uid->prefs[n].value = *aead++;
2606 for (; nhash; nhash--, n++)
2608 uid->prefs[n].type = PREFTYPE_HASH;
2609 uid->prefs[n].value = *hash++;
2611 for (; nzip; nzip--, n++)
2613 uid->prefs[n].type = PREFTYPE_ZIP;
2614 uid->prefs[n].value = *zip++;
2616 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
2617 uid->prefs[n].value = 0;
2620 /* See whether we have the MDC feature. */
2622 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n);
2623 if (p && n && (p[0] & 0x01))
2626 /* See whether we have the AEAD feature. */
2627 uid->flags.aead = 0;
2628 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n);
2629 if (p && n && (p[0] & 0x02))
2630 uid->flags.aead = 1;
2632 /* And the keyserver modify flag. */
2633 uid->flags.ks_modify = 1;
2634 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KS_FLAGS, &n);
2635 if (p && n && (p[0] & 0x80))
2636 uid->flags.ks_modify = 0;
2640 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
2642 rinfo->date = sig->timestamp;
2643 rinfo->algo = sig->pubkey_algo;
2644 rinfo->keyid[0] = sig->keyid[0];
2645 rinfo->keyid[1] = sig->keyid[1];
2649 /* Given a keyblock, parse the key block and extract various pieces of
2650 * information and save them with the primary key packet and the user
2651 * id packets. For instance, some information is stored in signature
2652 * packets. We find the latest such valid packet (since the user can
2653 * change that information) and copy its contents into the
2656 * Note that R_REVOKED may be set to 0, 1 or 2.
2658 * This function fills in the following fields in the primary key's
2661 * main_keyid (computed)
2662 * revkey / numrevkeys (derived from self signed key data)
2663 * flags.valid (whether we have at least 1 self-sig)
2664 * flags.maybe_revoked (whether a designed revoked the key, but
2665 * we are missing the key to check the sig)
2666 * selfsigversion (highest version of any valid self-sig)
2667 * pubkey_usage (derived from most recent self-sig or most
2669 * has_expired (various sources)
2670 * expiredate (various sources)
2672 * See the documentation for fixup_uidnode for how the user id packets
2673 * are modified. In addition to that the primary user id's is_primary
2674 * field is set to 1 and the other user id's is_primary are set to 0.
2677 merge_selfsigs_main (ctrl_t ctrl, kbnode_t keyblock, int *r_revoked,
2678 struct revoke_info *rinfo)
2680 PKT_public_key *pk = NULL;
2683 u32 sigdate, uiddate, uiddate2;
2684 KBNODE signode, uidnode, uidnode2;
2685 u32 curtime = make_timestamp ();
2686 unsigned int key_usage = 0;
2687 u32 keytimestamp = 0; /* Creation time of the key. */
2689 int key_expire_seen = 0;
2690 byte sigversion = 0;
2693 memset (rinfo, 0, sizeof (*rinfo));
2695 /* Section 11.1 of RFC 4880 determines the order of packets within a
2696 * message. There are three sections, which must occur in the
2697 * following order: the public key, the user ids and user attributes
2698 * and the subkeys. Within each section, each primary packet (e.g.,
2699 * a user id packet) is followed by one or more signature packets,
2700 * which modify that packet. */
2702 /* According to Section 11.1 of RFC 4880, the public key must be the
2703 first packet. Note that parse_keyblock_image ensures that the
2704 first packet is the public key. */
2705 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2707 pk = keyblock->pkt->pkt.public_key;
2708 keytimestamp = pk->timestamp;
2710 keyid_from_pk (pk, kid);
2711 pk->main_keyid[0] = kid[0];
2712 pk->main_keyid[1] = kid[1];
2714 if (pk->version < 4)
2716 /* Before v4 the key packet itself contains the expiration date
2717 * and there was no way to change it, so we start with the one
2718 * from the key packet. We do not support v3 keys anymore but
2719 * we keep the code in case a future key versions introduces a
2720 * hard expire time again. */
2721 key_expire = pk->max_expiredate;
2722 key_expire_seen = 1;
2727 * - Find the latest direct key self-signature. We assume that the
2728 * newest one overrides all others.
2730 * - Determine whether the key has been revoked.
2732 * - Gather all revocation keys (unlike other data, we don't just
2733 * take them from the latest self-signed packet).
2735 * - Determine max (sig[...]->version).
2738 /* Reset this in case this key was already merged. */
2744 sigdate = 0; /* Helper variable to find the latest signature. */
2746 /* According to Section 11.1 of RFC 4880, the public key comes first
2747 * and is immediately followed by any signature packets that modify
2750 k && k->pkt->pkttype != PKT_USER_ID
2751 && k->pkt->pkttype != PKT_ATTRIBUTE
2752 && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2755 if (k->pkt->pkttype == PKT_SIGNATURE)
2757 PKT_signature *sig = k->pkt->pkt.signature;
2758 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2761 if (check_key_signature (ctrl, keyblock, k, NULL))
2762 ; /* Signature did not verify. */
2763 else if (IS_KEY_REV (sig))
2765 /* Key has been revoked - there is no way to
2766 * override such a revocation, so we theoretically
2767 * can stop now. We should not cope with expiration
2768 * times for revocations here because we have to
2769 * assume that an attacker can generate all kinds of
2770 * signatures. However due to the fact that the key
2771 * has been revoked it does not harm either and by
2772 * continuing we gather some more info on that
2775 sig_to_revoke_info (sig, rinfo);
2777 else if (IS_KEY_SIG (sig))
2779 /* Add the indicated revocations keys from all
2780 * signatures not just the latest. We do this
2781 * because you need multiple 1F sigs to properly
2782 * handle revocation keys (PGP does it this way, and
2783 * a revocation key could be sensitive and hence in
2784 * a different signature). */
2790 xrealloc (pk->revkey, sizeof (struct revocation_key) *
2791 (pk->numrevkeys + sig->numrevkeys));
2793 for (i = 0; i < sig->numrevkeys; i++, pk->numrevkeys++)
2795 pk->revkey[pk->numrevkeys].class
2796 = sig->revkey[i].class;
2797 pk->revkey[pk->numrevkeys].algid
2798 = sig->revkey[i].algid;
2799 pk->revkey[pk->numrevkeys].fprlen
2800 = sig->revkey[i].fprlen;
2801 memcpy (pk->revkey[pk->numrevkeys].fpr,
2802 sig->revkey[i].fpr, sig->revkey[i].fprlen);
2803 memset (pk->revkey[pk->numrevkeys].fpr
2804 + sig->revkey[i].fprlen,
2806 sizeof (sig->revkey[i].fpr)
2807 - sig->revkey[i].fprlen);
2811 if (sig->timestamp >= sigdate)
2812 { /* This is the latest signature so far. */
2814 if (sig->flags.expired)
2815 ; /* Signature has expired - ignore it. */
2818 sigdate = sig->timestamp;
2820 if (sig->version > sigversion)
2821 sigversion = sig->version;
2830 /* Remove dupes from the revocation keys. */
2833 int i, j, x, changed = 0;
2835 for (i = 0; i < pk->numrevkeys; i++)
2837 for (j = i + 1; j < pk->numrevkeys; j++)
2839 if (memcmp (&pk->revkey[i], &pk->revkey[j],
2840 sizeof (struct revocation_key)) == 0)
2844 for (x = j; x < pk->numrevkeys - 1; x++)
2845 pk->revkey[x] = pk->revkey[x + 1];
2855 pk->revkey = xrealloc (pk->revkey,
2857 sizeof (struct revocation_key));
2860 /* SIGNODE is the direct key signature packet (sigclass 0x1f) with
2861 * the latest creation time. Extract some information from it. */
2864 /* Some information from a direct key signature take precedence
2865 * over the same information given in UID sigs. */
2866 PKT_signature *sig = signode->pkt->pkt.signature;
2869 key_usage = parse_key_usage (sig);
2871 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
2872 if (p && buf32_to_u32 (p))
2874 key_expire = keytimestamp + buf32_to_u32 (p);
2875 key_expire_seen = 1;
2878 /* Mark that key as valid: One direct key signature should
2879 * render a key as valid. */
2880 pk->flags.valid = 1;
2883 /* Pass 1.5: Look for key revocation signatures that were not made
2884 * by the key (i.e. did a revocation key issue a revocation for
2885 * us?). Only bother to do this if there is a revocation key in the
2886 * first place and we're not revoked already. */
2888 if (!*r_revoked && pk->revkey)
2889 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
2891 if (k->pkt->pkttype == PKT_SIGNATURE)
2893 PKT_signature *sig = k->pkt->pkt.signature;
2895 if (IS_KEY_REV (sig) &&
2896 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
2898 int rc = check_revocation_keys (ctrl, pk, sig);
2902 sig_to_revoke_info (sig, rinfo);
2903 /* Don't continue checking since we can't be any
2904 * more revoked than this. */
2907 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2908 pk->flags.maybe_revoked = 1;
2910 /* A failure here means the sig did not verify, was
2911 * not issued by a revocation key, or a revocation
2912 * key loop was broken. If a revocation key isn't
2913 * findable, however, the key might be revoked and
2914 * we don't know it. */
2916 /* Fixme: In the future handle subkey and cert
2917 * revocations? PGP doesn't, but it's in 2440. */
2922 /* Second pass: Look at the self-signature of all user IDs. */
2924 /* According to RFC 4880 section 11.1, user id and attribute packets
2925 * are in the second section, after the public key packet and before
2926 * the subkey packets. */
2927 signode = uidnode = NULL;
2928 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
2929 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2931 if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
2932 { /* New user id packet. */
2934 /* Apply the data from the most recent self-signed packet to
2935 * the preceding user id packet. */
2936 if (uidnode && signode)
2938 fixup_uidnode (uidnode, signode, keytimestamp);
2939 pk->flags.valid = 1;
2942 /* Clear SIGNODE. The only relevant self-signed data for
2943 * UIDNODE follows it. */
2944 if (k->pkt->pkttype == PKT_USER_ID)
2952 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2954 PKT_signature *sig = k->pkt->pkt.signature;
2955 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2957 if (check_key_signature (ctrl, keyblock, k, NULL))
2958 ; /* signature did not verify */
2959 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
2960 && sig->timestamp >= sigdate)
2962 /* Note: we allow invalidation of cert revocations
2963 * by a newer signature. An attacker can't use this
2964 * because a key should be revoked with a key revocation.
2965 * The reason why we have to allow for that is that at
2966 * one time an email address may become invalid but later
2967 * the same email address may become valid again (hired,
2968 * fired, hired again). */
2970 sigdate = sig->timestamp;
2972 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2973 if (sig->version > sigversion)
2974 sigversion = sig->version;
2979 if (uidnode && signode)
2981 fixup_uidnode (uidnode, signode, keytimestamp);
2982 pk->flags.valid = 1;
2985 /* If the key isn't valid yet, and we have
2986 * --allow-non-selfsigned-uid set, then force it valid. */
2987 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
2990 log_info (_("Invalid key %s made valid by"
2991 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
2992 pk->flags.valid = 1;
2995 /* The key STILL isn't valid, so try and find an ultimately
2996 * trusted signature. */
2997 if (!pk->flags.valid)
3001 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3004 if (k->pkt->pkttype == PKT_USER_ID)
3006 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
3008 PKT_signature *sig = k->pkt->pkt.signature;
3010 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
3012 PKT_public_key *ultimate_pk;
3014 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
3016 /* We don't want to use the full get_pubkey to avoid
3017 * infinite recursion in certain cases. There is no
3018 * reason to check that an ultimately trusted key is
3019 * still valid - if it has been revoked the user
3020 * should also remove the ultimate trust flag. */
3021 if (get_pubkey_fast (ctrl, ultimate_pk, sig->keyid) == 0
3022 && check_key_signature2 (ctrl,
3023 keyblock, k, ultimate_pk,
3024 NULL, NULL, NULL, NULL) == 0
3025 && get_ownertrust (ctrl, ultimate_pk) == TRUST_ULTIMATE)
3027 free_public_key (ultimate_pk);
3028 pk->flags.valid = 1;
3032 free_public_key (ultimate_pk);
3038 /* Record the highest selfsig version so we know if this is a v3 key
3039 * through and through, or a v3 key with a v4 selfsig somewhere.
3040 * This is useful in a few places to know if the key must be treated
3041 * as PGP2-style or OpenPGP-style. Note that a selfsig revocation
3042 * with a higher version number will also raise this value. This is
3043 * okay since such a revocation must be issued by the user (i.e. it
3044 * cannot be issued by someone else to modify the key behavior.) */
3046 pk->selfsigversion = sigversion;
3048 /* Now that we had a look at all user IDs we can now get some
3049 * information from those user IDs. */
3053 /* Find the latest user ID with key flags set. */
3054 uiddate = 0; /* Helper to find the latest user ID. */
3055 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3058 if (k->pkt->pkttype == PKT_USER_ID)
3060 PKT_user_id *uid = k->pkt->pkt.user_id;
3062 if (uid->help_key_usage
3063 && (uid->created > uiddate || (!uid->created && !uiddate)))
3065 key_usage = uid->help_key_usage;
3066 uiddate = uid->created;
3074 /* No key flags at all: get it from the algo. */
3075 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
3079 /* Check that the usage matches the usage as given by the algo. */
3080 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
3081 if (x) /* Mask it down to the actual allowed usage. */
3085 /* Whatever happens, it's a primary key, so it can certify. */
3086 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
3088 if (!key_expire_seen)
3090 /* Find the latest valid user ID with a key expiration set.
3091 * This may be a different one than from usage computation above
3092 * because some user IDs may have no expiration date set. */
3094 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3097 if (k->pkt->pkttype == PKT_USER_ID)
3099 PKT_user_id *uid = k->pkt->pkt.user_id;
3100 if (uid->help_key_expire
3101 && (uid->created > uiddate || (!uid->created && !uiddate)))
3103 key_expire = uid->help_key_expire;
3104 uiddate = uid->created;
3110 /* Currently only the not anymore supported v3 keys have a maximum
3111 * expiration date, but future key versions may get this feature again. */
3113 || (pk->max_expiredate && key_expire > pk->max_expiredate))
3114 key_expire = pk->max_expiredate;
3116 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
3117 pk->expiredate = key_expire;
3119 /* Fixme: we should see how to get rid of the expiretime fields but
3120 * this needs changes at other places too. */
3122 /* And now find the real primary user ID and delete all others. */
3123 uiddate = uiddate2 = 0;
3124 uidnode = uidnode2 = NULL;
3125 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3127 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
3129 PKT_user_id *uid = k->pkt->pkt.user_id;
3130 if (uid->flags.primary)
3132 if (uid->created > uiddate)
3134 uiddate = uid->created;
3137 else if (uid->created == uiddate && uidnode)
3139 /* The dates are equal, so we need to do a different
3140 * (and arbitrary) comparison. This should rarely,
3141 * if ever, happen. It's good to try and guarantee
3142 * that two different GnuPG users with two different
3143 * keyrings at least pick the same primary. */
3144 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
3150 if (uid->created > uiddate2)
3152 uiddate2 = uid->created;
3155 else if (uid->created == uiddate2 && uidnode2)
3157 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
3165 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3168 if (k->pkt->pkttype == PKT_USER_ID &&
3169 !k->pkt->pkt.user_id->attrib_data)
3171 PKT_user_id *uid = k->pkt->pkt.user_id;
3173 uid->flags.primary = 0;
3179 /* None is flagged primary - use the latest user ID we have,
3180 * and disambiguate with the arbitrary packet comparison. */
3181 uidnode2->pkt->pkt.user_id->flags.primary = 1;
3185 /* None of our uids were self-signed, so pick the one that
3186 * sorts first to be the primary. This is the best we can do
3187 * here since there are no self sigs to date the uids. */
3191 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3194 if (k->pkt->pkttype == PKT_USER_ID
3195 && !k->pkt->pkt.user_id->attrib_data)
3200 uidnode->pkt->pkt.user_id->flags.primary = 1;
3205 if (cmp_user_ids (k->pkt->pkt.user_id,
3206 uidnode->pkt->pkt.user_id) > 0)
3208 uidnode->pkt->pkt.user_id->flags.primary = 0;
3210 uidnode->pkt->pkt.user_id->flags.primary = 1;
3214 /* just to be safe: */
3215 k->pkt->pkt.user_id->flags.primary = 0;
3224 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
3225 * Caller must free the signature when they are done. */
3226 static PKT_signature *
3227 buf_to_sig (const byte * buf, size_t len)
3229 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
3230 IOBUF iobuf = iobuf_temp_with_content (buf, len);
3231 int save_mode = set_packet_list_mode (0);
3233 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
3235 free_seckey_enc (sig);
3239 set_packet_list_mode (save_mode);
3240 iobuf_close (iobuf);
3246 /* Use the self-signed data to fill in various fields in subkeys.
3248 * KEYBLOCK is the whole keyblock. SUBNODE is the subkey to fill in.
3250 * Sets the following fields on the subkey:
3253 * flags.valid if the subkey has a valid self-sig binding
3260 * On this subkey's most recent valid self-signed packet, the
3261 * following field is set:
3263 * flags.chosen_selfsig
3266 merge_selfsigs_subkey (ctrl_t ctrl, kbnode_t keyblock, kbnode_t subnode)
3268 PKT_public_key *mainpk = NULL, *subpk = NULL;
3274 u32 curtime = make_timestamp ();
3275 unsigned int key_usage = 0;
3276 u32 keytimestamp = 0;
3280 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3282 mainpk = keyblock->pkt->pkt.public_key;
3283 if (mainpk->version < 4)
3284 return;/* (actually this should never happen) */
3285 keyid_from_pk (mainpk, mainkid);
3286 subpk = subnode->pkt->pkt.public_key;
3287 keytimestamp = subpk->timestamp;
3289 subpk->flags.valid = 0;
3290 subpk->flags.exact = 0;
3291 subpk->main_keyid[0] = mainpk->main_keyid[0];
3292 subpk->main_keyid[1] = mainpk->main_keyid[1];
3294 /* Find the latest key binding self-signature. */
3296 sigdate = 0; /* Helper to find the latest signature. */
3297 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3300 if (k->pkt->pkttype == PKT_SIGNATURE)
3302 sig = k->pkt->pkt.signature;
3303 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
3305 if (check_key_signature (ctrl, keyblock, k, NULL))
3306 ; /* Signature did not verify. */
3307 else if (IS_SUBKEY_REV (sig))
3309 /* Note that this means that the date on a
3310 * revocation sig does not matter - even if the
3311 * binding sig is dated after the revocation sig,
3312 * the subkey is still marked as revoked. This
3313 * seems ok, as it is just as easy to make new
3314 * subkeys rather than re-sign old ones as the
3315 * problem is in the distribution. Plus, PGP (7)
3316 * does this the same way. */
3317 subpk->flags.revoked = 1;
3318 sig_to_revoke_info (sig, &subpk->revoked);
3319 /* Although we could stop now, we continue to
3320 * figure out other information like the old expiration
3323 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
3325 if (sig->flags.expired)
3326 ; /* Signature has expired - ignore it. */
3329 sigdate = sig->timestamp;
3331 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
3338 /* No valid key binding. */
3342 sig = signode->pkt->pkt.signature;
3343 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
3345 key_usage = parse_key_usage (sig);
3348 /* No key flags at all: get it from the algo. */
3349 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
3353 /* Check that the usage matches the usage as given by the algo. */
3354 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
3355 if (x) /* Mask it down to the actual allowed usage. */
3359 subpk->pubkey_usage = key_usage;
3361 p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
3362 if (p && buf32_to_u32 (p))
3363 key_expire = keytimestamp + buf32_to_u32 (p);
3367 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
3368 subpk->expiredate = key_expire;
3370 /* Algo doesn't exist. */
3371 if (openpgp_pk_test_algo (subpk->pubkey_algo))
3374 subpk->flags.valid = 1;
3376 /* Find the most recent 0x19 embedded signature on our self-sig. */
3377 if (!subpk->flags.backsig)
3381 PKT_signature *backsig = NULL;
3385 /* We do this while() since there may be other embedded
3386 * signatures in the future. We only want 0x19 here. */
3388 while ((p = enum_sig_subpkt (sig, 1, SIGSUBPKT_SIGNATURE,
3391 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)
3392 || (p[0] == 5 && p[1] == 0x19)))
3394 PKT_signature *tempsig = buf_to_sig (p, n);
3397 if (tempsig->timestamp > sigdate)
3400 free_seckey_enc (backsig);
3403 sigdate = backsig->timestamp;
3406 free_seckey_enc (tempsig);
3412 /* It is safe to have this in the unhashed area since the 0x19
3413 * is located on the selfsig for convenience, not security. */
3414 while ((p = enum_sig_subpkt (sig, 0, SIGSUBPKT_SIGNATURE,
3417 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)
3418 || (p[0] == 5 && p[1] == 0x19)))
3420 PKT_signature *tempsig = buf_to_sig (p, n);
3423 if (tempsig->timestamp > sigdate)
3426 free_seckey_enc (backsig);
3429 sigdate = backsig->timestamp;
3432 free_seckey_enc (tempsig);
3438 /* At this point, backsig contains the most recent 0x19 sig.
3439 * Let's see if it is good. */
3441 /* 2==valid, 1==invalid, 0==didn't check */
3442 if (check_backsig (mainpk, subpk, backsig) == 0)
3443 subpk->flags.backsig = 2;
3445 subpk->flags.backsig = 1;
3447 free_seckey_enc (backsig);
3453 /* Merge information from the self-signatures with the public key,
3454 * subkeys and user ids to make using them more easy.
3456 * See documentation for merge_selfsigs_main, merge_selfsigs_subkey
3457 * and fixup_uidnode for exactly which fields are updated. */
3459 merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock)
3463 struct revoke_info rinfo;
3464 PKT_public_key *main_pk;
3466 unsigned int mdc_feature;
3467 unsigned int aead_feature;
3469 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
3471 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
3473 log_error ("expected public key but found secret key "
3475 /* We better exit here because a public key is expected at
3476 * other places too. FIXME: Figure this out earlier and
3477 * don't get to here at all */
3483 merge_selfsigs_main (ctrl, keyblock, &revoked, &rinfo);
3485 /* Now merge in the data from each of the subkeys. */
3486 for (k = keyblock; k; k = k->next)
3488 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3490 merge_selfsigs_subkey (ctrl, keyblock, k);
3494 main_pk = keyblock->pkt->pkt.public_key;
3495 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
3497 /* If the primary key is revoked, expired, or invalid we
3498 * better set the appropriate flags on that key and all
3500 for (k = keyblock; k; k = k->next)
3502 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3503 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3505 PKT_public_key *pk = k->pkt->pkt.public_key;
3506 if (!main_pk->flags.valid)
3507 pk->flags.valid = 0;
3508 if (revoked && !pk->flags.revoked)
3510 pk->flags.revoked = revoked;
3511 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
3513 if (main_pk->has_expired)
3515 pk->has_expired = main_pk->has_expired;
3516 if (!pk->expiredate || pk->expiredate > main_pk->expiredate)
3517 pk->expiredate = main_pk->expiredate;
3524 /* Set the preference list of all keys to those of the primary real
3525 * user ID. Note: we use these preferences when we don't know by
3526 * which user ID the key has been selected.
3527 * fixme: we should keep atoms of commonly used preferences or
3528 * use reference counting to optimize the preference lists storage.
3529 * FIXME: it might be better to use the intersection of
3531 * Do a similar thing for the MDC feature flag. */
3533 mdc_feature = aead_feature = 0;
3534 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3536 if (k->pkt->pkttype == PKT_USER_ID
3537 && !k->pkt->pkt.user_id->attrib_data
3538 && k->pkt->pkt.user_id->flags.primary)
3540 prefs = k->pkt->pkt.user_id->prefs;
3541 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
3542 aead_feature = k->pkt->pkt.user_id->flags.aead;
3546 for (k = keyblock; k; k = k->next)
3548 if (k->pkt->pkttype == PKT_PUBLIC_KEY
3549 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3551 PKT_public_key *pk = k->pkt->pkt.public_key;
3554 pk->prefs = copy_prefs (prefs);
3555 pk->flags.mdc = mdc_feature;
3556 pk->flags.aead = aead_feature;
3563 /* See whether the key satisfies any additional requirements specified
3564 * in CTX. If so, return the node of an appropriate key or subkey.
3565 * Otherwise, return NULL if there was no appropriate key.
3567 * Note that we do not return a reference, i.e. the result must not be
3568 * freed using 'release_kbnode'.
3570 * In case the primary key is not required, select a suitable subkey.
3571 * We need the primary key if PUBKEY_USAGE_CERT is set in REQ_USAGE or
3572 * we are in PGP7 mode and PUBKEY_USAGE_SIG is set in
3575 * If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
3576 * are set in REQ_USAGE, we filter by the key's function. Concretely,
3577 * if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then we only
3578 * return a key if it is (at least) either a signing or a
3579 * certification key.
3581 * If REQ_USAGE is set, then we reject any keys that are not good
3582 * (i.e., valid, not revoked, not expired, etc.). This allows the
3583 * getkey functions to be used for plain key listings.
3585 * Sets the matched key's user id field (pk->user_id) to the user id
3586 * that matched the low-level search criteria or NULL.
3588 * If R_FLAGS is not NULL set certain flags for more detailed error
3589 * reporting. Used flags are:
3591 * - LOOKUP_ALL_SUBKEYS_EXPIRED :: All Subkeys are expired or have
3593 * - LOOKUP_NOT_SELECTED :: No suitable key found
3595 * This function needs to handle several different cases:
3597 * 1. No requested usage and no primary key requested
3598 * Examples for this case are that we have a keyID to be used
3599 * for decryption or verification.
3600 * 2. No usage but primary key requested
3601 * This is the case for all functions which work on an
3602 * entire keyblock, e.g. for editing or listing
3603 * 3. Usage and primary key requested
3605 * 4. Usage but no primary key requested
3610 finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact,
3611 int want_secret, unsigned int *r_flags)
3615 /* If WANT_EXACT is set, the key or subkey that actually matched the
3616 low-level search criteria. */
3617 kbnode_t foundk = NULL;
3618 /* The user id (if any) that matched the low-level search criteria. */
3619 PKT_user_id *foundu = NULL;
3622 kbnode_t latest_key;
3625 u32 curtime = make_timestamp ();
3630 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
3631 req_usage &= USAGE_MASK;
3633 /* Request the primary if we're certifying another key, and also if
3634 * signing data while --pgp7 is on since pgp 7 do
3635 * not understand signatures made by a signing subkey. PGP 8 does. */
3636 req_prim = ((req_usage & PUBKEY_USAGE_CERT)
3637 || (PGP7 && (req_usage & PUBKEY_USAGE_SIG)));
3640 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
3642 /* For an exact match mark the primary or subkey that matched the
3643 * low-level search criteria. Use this loop also to sort our keys
3644 * found using an ADSK fingerprint. */
3645 for (k = keyblock; k; k = k->next)
3647 if ((k->flag & 1) && (k->pkt->pkttype == PKT_PUBLIC_KEY
3648 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY))
3653 log_debug ("finish_lookup: exact search requested and found\n");
3655 pk = k->pkt->pkt.public_key;
3656 pk->flags.exact = 1;
3659 else if ((k->pkt->pkt.public_key->pubkey_usage == PUBKEY_USAGE_RENC))
3662 log_debug ("finish_lookup: found via ADSK - not selected\n");
3664 *r_flags |= LOOKUP_NOT_SELECTED;
3665 return NULL; /* Not found. */
3670 /* Get the user id that matched that low-level search criteria. */
3671 for (k = keyblock; k; k = k->next)
3675 log_assert (k->pkt->pkttype == PKT_USER_ID);
3676 foundu = k->pkt->pkt.user_id;
3682 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
3683 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
3684 foundk ? "one" : "all", req_usage);
3688 latest_key = foundk ? foundk : keyblock;
3694 /* Set LATEST_KEY to the latest (the one with the most recent
3695 * timestamp) good (valid, not revoked, not expired, etc.) subkey.
3697 * Don't bother if we are only looking for a primary key or we need
3698 * an exact match and the exact match is not a subkey. */
3699 if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
3705 int n_revoked_or_expired = 0;
3706 int last_secret_key_avail = 0;
3708 /* Either start a loop or check just this one subkey. */
3709 for (k = foundk ? foundk : keyblock; k; k = nextk)
3713 /* If FOUNDK is not NULL, then only consider that exact
3714 key, i.e., don't iterate. */
3720 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3723 pk = k->pkt->pkt.public_key;
3725 log_debug ("\tchecking subkey %08lX\n",
3726 (ulong) keyid_from_pk (pk, NULL));
3728 if (!pk->flags.valid)
3731 log_debug ("\tsubkey not valid\n");
3734 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3737 log_debug ("\tusage does not match: want=%x have=%x\n",
3738 req_usage, pk->pubkey_usage);
3743 if (pk->flags.revoked)
3746 log_debug ("\tsubkey has been revoked\n");
3747 n_revoked_or_expired++;
3750 if (pk->has_expired && !opt.ignore_expiration)
3753 log_debug ("\tsubkey has expired\n");
3754 n_revoked_or_expired++;
3757 if (pk->timestamp > curtime && !opt.ignore_valid_from)
3760 log_debug ("\tsubkey not yet valid\n");
3766 int secret_key_avail = agent_probe_secret_key (NULL, pk);
3768 if (!secret_key_avail)
3771 log_debug ("\tno secret key\n");
3775 if (secret_key_avail > last_secret_key_avail)
3778 last_secret_key_avail = secret_key_avail;
3784 log_debug ("\tsubkey might be fine\n");
3785 /* In case a key has a timestamp of 0 set, we make sure
3786 that it is used. A better change would be to compare
3787 ">=" but that might also change the selected keys and
3788 is as such a more intrusive change. */
3789 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
3791 latest_date = pk->timestamp;
3795 if (n_subkeys == n_revoked_or_expired && r_flags)
3796 *r_flags |= LOOKUP_ALL_SUBKEYS_EXPIRED;
3799 /* Check if the primary key is ok (valid, not revoke, not expire,
3800 * matches requested usage) if:
3802 * - we didn't find an appropriate subkey and we're not doing an
3805 * - we're doing an exact match and the exact match was the
3808 * - we're just considering the primary key. */
3809 if ((!latest_key && !want_exact) || foundk == keyblock || req_prim)
3811 if (DBG_LOOKUP && !foundk && !req_prim)
3812 log_debug ("\tno suitable subkeys found - trying primary\n");
3813 pk = keyblock->pkt->pkt.public_key;
3814 if (!pk->flags.valid)
3817 log_debug ("\tprimary key not valid\n");
3819 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3822 log_debug ("\tprimary key usage does not match: "
3823 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
3825 else if (pk->flags.revoked)
3828 log_debug ("\tprimary key has been revoked\n");
3830 else if (pk->has_expired)
3833 log_debug ("\tprimary key has expired\n");
3838 log_debug ("\tprimary key may be used\n");
3839 latest_key = keyblock;
3846 log_debug ("\tno suitable key found - giving up\n");
3848 *r_flags |= LOOKUP_NOT_SELECTED;
3849 return NULL; /* Not found. */
3854 log_debug ("\tusing key %08lX\n",
3855 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
3859 pk = latest_key->pkt->pkt.public_key;
3860 free_user_id (pk->user_id);
3861 pk->user_id = scopy_user_id (foundu);
3864 if (latest_key != keyblock && opt.verbose)
3867 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
3868 log_info (_("using subkey %s instead of primary key %s\n"),
3869 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
3873 cache_put_keyblock (keyblock);
3875 return latest_key ? latest_key : keyblock; /* Found. */
3879 /* Print a KEY_CONSIDERED status line. */
3881 print_status_key_considered (kbnode_t keyblock, unsigned int flags)
3883 char hexfpr[2*MAX_FINGERPRINT_LEN + 1];
3887 if (!is_status_enabled ())
3890 for (node=keyblock; node; node = node->next)
3891 if (node->pkt->pkttype == PKT_PUBLIC_KEY
3892 || node->pkt->pkttype == PKT_SECRET_KEY)
3896 log_error ("%s: keyblock w/o primary key\n", __func__);
3900 hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr);
3901 snprintf (flagbuf, sizeof flagbuf, " %u", flags);
3902 write_status_strings (STATUS_KEY_CONSIDERED, hexfpr, flagbuf, NULL);
3907 /* A high-level function to lookup keys.
3909 * This function builds on top of the low-level keydb API. It first
3910 * searches the database using the description stored in CTX->ITEMS,
3911 * then it filters the results using CTX and, finally, if WANT_SECRET
3912 * is set, it ignores any keys for which no secret key is available.
3914 * Unlike the low-level search functions, this function also merges
3915 * all of the self-signed data into the keys, subkeys and user id
3916 * packets (see the merge_selfsigs for details).
3918 * On success the key's keyblock is stored at *RET_KEYBLOCK, and the
3919 * specific subkey is stored at *RET_FOUND_KEY. Note that we do not
3920 * return a reference in *RET_FOUND_KEY, i.e. the result must not be
3921 * freed using 'release_kbnode', and it is only valid until
3922 * *RET_KEYBLOCK is deallocated. Therefore, if RET_FOUND_KEY is not
3923 * NULL, then RET_KEYBLOCK must not be NULL. */
3925 lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret,
3926 kbnode_t *ret_keyblock, kbnode_t *ret_found_key)
3929 int no_suitable_key = 0;
3930 KBNODE keyblock = NULL;
3931 KBNODE found_key = NULL;
3932 unsigned int infoflags;
3934 log_assert (ret_found_key == NULL || ret_keyblock != NULL);
3936 *ret_keyblock = NULL;
3940 rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
3944 /* If we are iterating over the entire database, then we need to
3945 * change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
3946 * reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next record. */
3947 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
3948 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
3950 rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
3953 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
3959 rc = agent_probe_any_secret_key (ctrl, keyblock);
3960 if (gpg_err_code(rc) == GPG_ERR_NO_SECKEY)
3961 goto skip; /* No secret key available. */
3963 goto found; /* Unexpected error. */
3966 /* Warning: node flag bits 0 and 1 should be preserved by
3967 * merge_selfsigs. */
3968 merge_selfsigs (ctrl, keyblock);
3969 found_key = finish_lookup (keyblock, ctx->req_usage, ctx->exact,
3970 want_secret, &infoflags);
3971 print_status_key_considered (keyblock, infoflags);
3974 no_suitable_key = 0;
3979 no_suitable_key = 1;
3983 /* Release resources and continue search. */
3984 release_kbnode (keyblock);
3986 /* The keyblock cache ignores the current "file position".
3987 * Thus, if we request the next result and the cache matches
3988 * (and it will since it is what we just looked for), we'll get
3989 * the same entry back! We can avoid this infinite loop by
3990 * disabling the cache. */
3991 keydb_disable_caching (ctx->kr_handle);
3995 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
3996 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
4002 *ret_keyblock = keyblock; /* Return the keyblock. */
4006 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
4007 rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
4008 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
4009 rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
4011 release_kbnode (keyblock);
4016 *ret_found_key = found_key;
4018 *ret_found_key = NULL;
4025 /* If a default key has been specified, return that key. If a card
4026 * based key is also available as indicated by FPR_CARD not being
4027 * NULL, return that key if suitable. */
4029 get_seckey_default_or_card (ctrl_t ctrl, PKT_public_key *pk,
4030 const byte *fpr_card, size_t fpr_len)
4033 strlist_t namelist = NULL;
4034 const char *def_secret_key;
4036 def_secret_key = parse_def_secret_key (ctrl);
4039 add_to_strlist (&namelist, def_secret_key);
4042 err = get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len);
4043 if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
4046 log_debug ("using LDAP to find public key for current card\n");
4047 err = keyserver_import_fprint (ctrl, fpr_card, fpr_len,
4049 KEYSERVER_IMPORT_FLAG_LDAP);
4051 err = get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len);
4052 else if (gpg_err_code (err) == GPG_ERR_NO_DATA
4053 || gpg_err_code (err) == GPG_ERR_NO_KEYSERVER)
4055 /* Dirmngr returns NO DATA is the selected keyserver
4056 * does not have the requested key. It returns NO
4057 * KEYSERVER if no LDAP keyservers are configured. */
4058 err = gpg_error (GPG_ERR_NO_PUBKEY);
4062 /* The key on card can be not suitable for requested usage. */
4063 if (gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY)
4064 fpr_card = NULL; /* Fallthrough as no card. */
4066 return err; /* Success or other error. */
4069 if (!fpr_card || (def_secret_key && *def_secret_key
4070 && def_secret_key[strlen (def_secret_key)-1] == '!'))
4072 err = key_byname (ctrl, NULL, namelist, pk, 1, 0, NULL, NULL);
4075 { /* Default key is specified and card key is also available. */
4076 kbnode_t k, keyblock = NULL;
4078 err = key_byname (ctrl, NULL, namelist, pk, 1, 0, &keyblock, NULL);
4081 for (k = keyblock; k; k = k->next)
4083 PKT_public_key *pk_candidate;
4084 char fpr[MAX_FINGERPRINT_LEN];
4086 if (k->pkt->pkttype != PKT_PUBLIC_KEY
4087 &&k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
4090 pk_candidate = k->pkt->pkt.public_key;
4091 if (!pk_candidate->flags.valid)
4093 if (!((pk_candidate->pubkey_usage & USAGE_MASK) & pk->req_usage))
4095 fingerprint_from_pk (pk_candidate, fpr, NULL);
4096 if (!memcmp (fpr_card, fpr, fpr_len))
4098 release_public_key_parts (pk);
4099 copy_public_key (pk, pk_candidate);
4103 release_kbnode (keyblock);
4107 free_strlist (namelist);
4113 /*********************************************
4114 *********** User ID printing helpers *******
4115 *********************************************/
4117 /* Return a string with a printable representation of the user_id.
4118 * this string must be freed by xfree. If R_NOUID is not NULL it is
4119 * set to true if a user id was not found; otherwise to false. */
4121 get_user_id_string (ctrl_t ctrl, u32 * keyid, int mode)
4124 unsigned int namelen;
4127 log_assert (mode != 2);
4129 name = cache_get_uid_bykid (keyid, &namelen);
4132 /* Get it so that the cache will be filled. */
4133 if (!get_pubkey (ctrl, NULL, keyid))
4134 name = cache_get_uid_bykid (keyid, &namelen);
4140 p = xasprintf ("%08lX%08lX %.*s",
4141 (ulong) keyid[0], (ulong) keyid[1], namelen, name);
4143 p = xasprintf ("%s %.*s", keystr (keyid), namelen, name);
4150 p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
4152 p = xasprintf ("%s [?]", keystr (keyid));
4160 get_user_id_string_native (ctrl_t ctrl, u32 * keyid)
4162 char *p = get_user_id_string (ctrl, keyid, 0);
4163 char *p2 = utf8_to_native (p, strlen (p), 0);
4170 get_long_user_id_string (ctrl_t ctrl, u32 * keyid)
4172 return get_user_id_string (ctrl, keyid, 1);
4176 /* Please try to use get_user_byfpr instead of this one. */
4178 get_user_id (ctrl_t ctrl, u32 *keyid, size_t *rn, int *r_nouid)
4181 unsigned int namelen;
4186 name = cache_get_uid_bykid (keyid, &namelen);
4189 /* Get it so that the cache will be filled. */
4190 if (!get_pubkey (ctrl, NULL, keyid))
4191 name = cache_get_uid_bykid (keyid, &namelen);
4196 name = xstrdup (user_id_not_found_utf8 ());
4197 namelen = strlen (name);
4208 /* Please try to use get_user_id_byfpr_native instead of this one. */
4210 get_user_id_native (ctrl_t ctrl, u32 *keyid)
4213 char *p = get_user_id (ctrl, keyid, &rn, NULL);
4214 char *p2 = utf8_to_native (p, rn, 0);
4220 /* Return the user id for a key designated by its fingerprint, FPR,
4221 which must be MAX_FINGERPRINT_LEN bytes in size. Note: the
4222 returned string, which must be freed using xfree, may not be NUL
4223 terminated. To determine the length of the string, you must use
4226 get_user_id_byfpr (ctrl_t ctrl, const byte *fpr, size_t fprlen, size_t *rn)
4230 name = cache_get_uid_byfpr (fpr, fprlen, rn);
4233 /* Get it so that the cache will be filled. */
4234 if (!get_pubkey_byfprint (ctrl, NULL, NULL, fpr, fprlen))
4235 name = cache_get_uid_byfpr (fpr, fprlen, rn);
4240 name = xstrdup (user_id_not_found_utf8 ());
4241 *rn = strlen (name);
4247 /* Like get_user_id_byfpr, but convert the string to the native
4248 encoding. The returned string needs to be freed. Unlike
4249 get_user_id_byfpr, the returned string is NUL terminated. */
4251 get_user_id_byfpr_native (ctrl_t ctrl, const byte *fpr, size_t fprlen)
4254 char *p = get_user_id_byfpr (ctrl, fpr, fprlen, &rn);
4255 char *p2 = utf8_to_native (p, rn, 0);
4261 /* Return the database handle used by this context. The context still
4264 get_ctx_handle (GETKEY_CTX ctx)
4266 return ctx->kr_handle;
4270 free_akl (struct akl *akl)
4276 free_keyserver_spec (akl->spec);
4284 while (opt.auto_key_locate)
4286 struct akl *akl2 = opt.auto_key_locate;
4287 opt.auto_key_locate = opt.auto_key_locate->next;
4293 /* Returns true if the AKL is empty or has only the local method
4296 akl_empty_or_only_local (void)
4301 for (akl = opt.auto_key_locate; akl; akl = akl->next)
4302 if (akl->type != AKL_NODEFAULT && akl->type != AKL_LOCAL)
4312 /* Returns false on error. */
4314 parse_auto_key_locate (const char *options_arg)
4317 char *options, *options_buf;
4319 options = options_buf = xstrdup (options_arg);
4320 while ((tok = optsep (&options)))
4322 struct akl *akl, *check, *last = NULL;
4328 akl = xmalloc_clear (sizeof (*akl));
4330 if (ascii_strcasecmp (tok, "clear") == 0)
4333 free_akl (opt.auto_key_locate);
4334 opt.auto_key_locate = NULL;
4337 else if (ascii_strcasecmp (tok, "nodefault") == 0)
4338 akl->type = AKL_NODEFAULT;
4339 else if (ascii_strcasecmp (tok, "local") == 0)
4340 akl->type = AKL_LOCAL;
4341 else if (ascii_strcasecmp (tok, "ldap") == 0)
4342 akl->type = AKL_LDAP;
4343 else if (ascii_strcasecmp (tok, "keyserver") == 0)
4344 akl->type = AKL_KEYSERVER;
4345 else if (ascii_strcasecmp (tok, "cert") == 0)
4346 akl->type = AKL_CERT;
4347 else if (ascii_strcasecmp (tok, "pka") == 0)
4348 akl->type = AKL_PKA;
4349 else if (ascii_strcasecmp (tok, "dane") == 0)
4350 akl->type = AKL_DANE;
4351 else if (ascii_strcasecmp (tok, "wkd") == 0)
4352 akl->type = AKL_WKD;
4353 else if (ascii_strcasecmp (tok, "ntds") == 0)
4354 akl->type = AKL_NTDS;
4355 else if ((akl->spec = parse_keyserver_uri (tok, 1)))
4356 akl->type = AKL_SPEC;
4360 xfree (options_buf);
4364 /* We must maintain the order the user gave us */
4365 for (check = opt.auto_key_locate; check;
4366 last = check, check = check->next)
4368 /* Check for duplicates */
4369 if (check->type == akl->type
4370 && (akl->type != AKL_SPEC
4371 || (akl->type == AKL_SPEC
4372 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
4385 opt.auto_key_locate = akl;
4389 xfree (options_buf);
4395 /* The list of key origins. */
4399 } key_origin_list[] =
4401 { "self", KEYORG_SELF },
4402 { "file", KEYORG_FILE },
4403 { "url", KEYORG_URL },
4404 { "wkd", KEYORG_WKD },
4405 { "dane", KEYORG_DANE },
4406 { "ks-pref", KEYORG_KS_PREF },
4407 { "ks", KEYORG_KS },
4408 { "unknown", KEYORG_UNKNOWN }
4411 /* Parse the argument for --key-origin. Return false on error. */
4413 parse_key_origin (char *string)
4418 comma = strchr (string, ',');
4422 if (!ascii_strcasecmp (string, "help"))
4424 log_info (_("valid values for option '%s':\n"), "--key-origin");
4425 for (i=0; i < DIM (key_origin_list); i++)
4426 log_info (" %s\n", key_origin_list[i].name);
4430 for (i=0; i < DIM (key_origin_list); i++)
4431 if (!ascii_strcasecmp (string, key_origin_list[i].name))
4433 opt.key_origin = key_origin_list[i].origin;
4434 xfree (opt.key_origin_url);
4435 opt.key_origin_url = NULL;
4436 if (comma && comma[1])
4438 opt.key_origin_url = xstrdup (comma+1);
4439 trim_spaces (opt.key_origin_url);
4450 /* Return a string or "?" for the key ORIGIN. */
4452 key_origin_string (int origin)
4456 for (i=0; i < DIM (key_origin_list); i++)
4457 if (key_origin_list[i].origin == origin)
4458 return key_origin_list[i].name;
4464 /* Returns true if a secret key is available for the public key with
4465 key id KEYID; returns false if not. This function ignores legacy
4466 keys. Note: this is just a fast check and does not tell us whether
4467 the secret key is valid; this check merely indicates whether there
4468 is some secret key with the specified key id. */
4470 have_secret_key_with_kid (ctrl_t ctrl, u32 *keyid)
4474 KEYDB_SEARCH_DESC desc;
4479 kdbhd = keydb_new (ctrl);
4482 memset (&desc, 0, sizeof desc);
4483 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
4484 desc.u.kid[0] = keyid[0];
4485 desc.u.kid[1] = keyid[1];
4488 err = keydb_search (kdbhd, &desc, 1, NULL);
4492 err = keydb_get_keyblock (kdbhd, &keyblock);
4495 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
4499 for (node = keyblock; node; node = node->next)
4501 /* Bit 0 of the flags is set if the search found the key
4502 using that key or subkey. Note: a search will only ever
4503 match a single key or subkey. */
4504 if ((node->flag & 1))
4506 log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY
4507 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
4509 if (agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
4510 result = 1; /* Secret key available. */
4517 release_kbnode (keyblock);
4520 keydb_release (kdbhd);