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.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
37 #include "keyserver-internal.h"
38 #include "call-agent.h"
40 #include "mbox-util.h"
42 #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
43 #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
45 #if MAX_PK_CACHE_ENTRIES < 2
46 #error We need the cache for key creation
52 int want_secret; /* The caller requested only secret keys. */
55 KBNODE found_key; /* Pointer into some keyblock. */
56 strlist_t extra_list; /* Will be freed when releasing the context. */
58 KEYDB_HANDLE kr_handle;
61 KEYDB_SEARCH_DESC items[1];
74 typedef struct keyid_list
76 struct keyid_list *next;
77 char fpr[MAX_FINGERPRINT_LEN];
82 #if MAX_PK_CACHE_ENTRIES
83 typedef struct pk_cache_entry
85 struct pk_cache_entry *next;
89 static pk_cache_entry_t pk_cache;
90 static int pk_cache_entries; /* Number of entries in pk cache. */
91 static int pk_cache_disabled;
94 #if MAX_UID_CACHE_ENTRIES < 5
95 #error we really need the userid cache
97 typedef struct user_id_db
99 struct user_id_db *next;
104 static user_id_db_t user_id_db;
105 static int uid_cache_entries; /* Number of entries in uid cache. */
107 static void merge_selfsigs (kbnode_t keyblock);
108 static int lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, int want_secret);
115 for (i = 0; i < DIM (lkup_stats); i++)
117 if (lkup_stats[i].any)
118 es_fprintf (es_stderr,
119 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
121 lkup_stats[i].okay_count,
122 lkup_stats[i].nokey_count, lkup_stats[i].error_count);
129 cache_public_key (PKT_public_key * pk)
131 #if MAX_PK_CACHE_ENTRIES
132 pk_cache_entry_t ce, ce2;
135 if (pk_cache_disabled)
138 if (pk->flags.dont_cache)
141 if (is_ELGAMAL (pk->pubkey_algo)
142 || pk->pubkey_algo == PUBKEY_ALGO_DSA
143 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
144 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
145 || pk->pubkey_algo == PUBKEY_ALGO_ECDH
146 || is_RSA (pk->pubkey_algo))
148 keyid_from_pk (pk, keyid);
151 return; /* Don't know how to get the keyid. */
153 for (ce = pk_cache; ce; ce = ce->next)
154 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
157 log_debug ("cache_public_key: already in cache\n");
161 if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
165 /* Remove the last 50% of the entries. */
166 for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
168 if (ce != pk_cache && ce->next)
176 free_public_key (ce->pk);
181 assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
184 ce = xmalloc (sizeof *ce);
187 ce->pk = copy_public_key (NULL, pk);
188 ce->keyid[0] = keyid[0];
189 ce->keyid[1] = keyid[1];
194 /* Return a const utf-8 string with the text "[User ID not found]".
195 This function is required so that we don't need to switch gettext's
196 encoding temporary. */
198 user_id_not_found_utf8 (void)
203 text = native_to_utf8 (_("[User ID not found]"));
209 /* Return the user ID from the given keyblock.
210 * We use the primary uid flag which has been set by the merge_selfsigs
211 * function. The returned value is only valid as long as then given
212 * keyblock is not changed. */
214 get_primary_uid (KBNODE keyblock, size_t * uidlen)
219 for (k = keyblock; k; k = k->next)
221 if (k->pkt->pkttype == PKT_USER_ID
222 && !k->pkt->pkt.user_id->attrib_data
223 && k->pkt->pkt.user_id->is_primary)
225 *uidlen = k->pkt->pkt.user_id->len;
226 return k->pkt->pkt.user_id->name;
229 s = user_id_not_found_utf8 ();
230 *uidlen = strlen (s);
236 release_keyid_list (keyid_list_t k)
240 keyid_list_t k2 = k->next;
247 * Store the association of keyid and userid
248 * Feed only public keys to this function.
251 cache_user_id (KBNODE keyblock)
256 keyid_list_t keyids = NULL;
259 for (k = keyblock; k; k = k->next)
261 if (k->pkt->pkttype == PKT_PUBLIC_KEY
262 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
264 keyid_list_t a = xmalloc_clear (sizeof *a);
265 /* Hmmm: For a long list of keyids it might be an advantage
266 * to append the keys. */
267 fingerprint_from_pk (k->pkt->pkt.public_key, a->fpr, NULL);
268 keyid_from_pk (k->pkt->pkt.public_key, a->keyid);
269 /* First check for duplicates. */
270 for (r = user_id_db; r; r = r->next)
272 keyid_list_t b = r->keyids;
273 for (b = r->keyids; b; b = b->next)
275 if (!memcmp (b->fpr, a->fpr, MAX_FINGERPRINT_LEN))
278 log_debug ("cache_user_id: already in cache\n");
279 release_keyid_list (keyids);
285 /* Now put it into the cache. */
291 BUG (); /* No key no fun. */
294 uid = get_primary_uid (keyblock, &uidlen);
296 if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES)
298 /* fixme: use another algorithm to free some cache slots */
300 user_id_db = r->next;
301 release_keyid_list (r->keyids);
305 r = xmalloc (sizeof *r + uidlen - 1);
308 memcpy (r->name, uid, r->len);
309 r->next = user_id_db;
316 getkey_disable_caches ()
318 #if MAX_PK_CACHE_ENTRIES
320 pk_cache_entry_t ce, ce2;
322 for (ce = pk_cache; ce; ce = ce2)
325 free_public_key (ce->pk);
328 pk_cache_disabled = 1;
329 pk_cache_entries = 0;
333 /* fixme: disable user id cache ? */
338 pk_from_block (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE keyblock)
340 KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
342 assert (a->pkt->pkttype == PKT_PUBLIC_KEY
343 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
345 copy_public_key (pk, a->pkt->pkt.public_key);
348 /* Get a public key and store it into the allocated pk can be called
349 * with PK set to NULL to just read it into some internal
352 get_pubkey (PKT_public_key * pk, u32 * keyid)
357 #if MAX_PK_CACHE_ENTRIES
360 /* Try to get it from the cache. We don't do this when pk is
361 NULL as it does not guarantee that the user IDs are
364 for (ce = pk_cache; ce; ce = ce->next)
366 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
368 copy_public_key (pk, ce->pk);
374 /* More init stuff. */
377 pk = xmalloc_clear (sizeof *pk);
384 struct getkey_ctx_s ctx;
386 memset (&ctx, 0, sizeof ctx);
387 ctx.exact = 1; /* Use the key ID exactly as given. */
388 ctx.not_allocated = 1;
389 ctx.kr_handle = keydb_new ();
391 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
392 ctx.items[0].u.kid[0] = keyid[0];
393 ctx.items[0].u.kid[1] = keyid[1];
394 ctx.req_usage = pk->req_usage;
395 rc = lookup (&ctx, &kb, 0);
398 pk_from_block (&ctx, pk, kb);
400 get_pubkey_end (&ctx);
406 rc = GPG_ERR_NO_PUBKEY;
410 cache_public_key (pk);
412 free_public_key (pk);
417 /* Get a public key and store it into the allocated pk. This function
418 differs from get_pubkey() in that it does not do a check of the key
419 to avoid recursion. It should be used only in very certain cases.
420 It will only retrieve primary keys. */
422 get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
430 #if MAX_PK_CACHE_ENTRIES
432 /* Try to get it from the cache */
435 for (ce = pk_cache; ce; ce = ce->next)
437 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
440 copy_public_key (pk, ce->pk);
448 rc = keydb_search_kid (hd, keyid);
449 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
452 return GPG_ERR_NO_PUBKEY;
454 rc = keydb_get_keyblock (hd, &keyblock);
458 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
459 return GPG_ERR_NO_PUBKEY;
462 assert (keyblock && keyblock->pkt
463 && (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
464 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY));
466 keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
467 if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
468 copy_public_key (pk, keyblock->pkt->pkt.public_key);
470 rc = GPG_ERR_NO_PUBKEY;
472 release_kbnode (keyblock);
474 /* Not caching key here since it won't have all of the fields
482 get_pubkeyblock (u32 * keyid)
484 struct getkey_ctx_s ctx;
486 KBNODE keyblock = NULL;
488 memset (&ctx, 0, sizeof ctx);
489 /* No need to set exact here because we want the entire block. */
490 ctx.not_allocated = 1;
491 ctx.kr_handle = keydb_new ();
493 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
494 ctx.items[0].u.kid[0] = keyid[0];
495 ctx.items[0].u.kid[1] = keyid[1];
496 rc = lookup (&ctx, &keyblock, 0);
497 get_pubkey_end (&ctx);
499 return rc ? NULL : keyblock;
506 * Get a public key and store it into PK. This functions check that a
507 * corresponding secret key is available. With no secret key it does
511 get_seckey (PKT_public_key *pk, u32 *keyid)
514 struct getkey_ctx_s ctx;
515 kbnode_t keyblock = NULL;
517 memset (&ctx, 0, sizeof ctx);
518 ctx.exact = 1; /* Use the key ID exactly as given. */
519 ctx.not_allocated = 1;
520 ctx.kr_handle = keydb_new ();
522 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
523 ctx.items[0].u.kid[0] = keyid[0];
524 ctx.items[0].u.kid[1] = keyid[1];
525 ctx.req_usage = pk->req_usage;
526 err = lookup (&ctx, &keyblock, 1);
529 pk_from_block (&ctx, pk, keyblock);
531 get_pubkey_end (&ctx);
532 release_kbnode (keyblock);
535 err = agent_probe_secret_key (/*ctrl*/NULL, pk);
542 skip_unusable (void *dummy, u32 * keyid, PKT_user_id * uid)
549 keyblock = get_pubkeyblock (keyid);
552 log_error ("error checking usability status of %s\n", keystr (keyid));
556 /* Is the user ID in question revoked/expired? */
561 for (node = keyblock; node; node = node->next)
563 if (node->pkt->pkttype == PKT_USER_ID)
565 if (cmp_user_ids (uid, node->pkt->pkt.user_id) == 0
566 && (node->pkt->pkt.user_id->is_revoked
567 || node->pkt->pkt.user_id->is_expired))
577 unusable = pk_is_disabled (keyblock->pkt->pkt.public_key);
580 release_kbnode (keyblock);
585 /* Try to get the pubkey by the userid. This function looks for the
586 * first pubkey certificate which has the given name in a user_id. If
587 * PK has the pubkey algo set, the function will only return a pubkey
588 * with that algo. If NAMELIST is NULL, the first key is returned.
589 * The caller should provide storage for the PK or pass NULL if it is
590 * not needed. If RET_KB is not NULL the function stores the entire
591 * keyblock at that address. */
593 key_byname (GETKEY_CTX *retctx, strlist_t namelist,
595 int want_secret, int include_unusable,
596 KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
602 KBNODE help_kb = NULL;
606 /* Reset the returned context in case of error. */
607 assert (!ret_kdbhd); /* Not allowed because the handle is stored
616 ctx = xmalloc_clear (sizeof *ctx);
618 ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
619 if (!include_unusable)
620 ctx->items[0].skipfnc = skip_unusable;
624 /* Build the search context. */
625 for (n = 0, r = namelist; r; r = r->next)
628 ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
631 for (n = 0, r = namelist; r; r = r->next, n++)
635 err = classify_user_id (r->d, &ctx->items[n], 1);
637 if (ctx->items[n].exact)
642 return gpg_err_code (err); /* FIXME: remove gpg_err_code. */
644 if (!include_unusable
645 && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
646 && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
647 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
648 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
649 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
650 ctx->items[n].skipfnc = skip_unusable;
654 ctx->want_secret = want_secret;
655 ctx->kr_handle = keydb_new ();
661 ctx->req_usage = pk->req_usage;
664 rc = lookup (ctx, ret_kb, want_secret);
667 pk_from_block (ctx, pk, *ret_kb);
670 release_kbnode (help_kb);
672 if (retctx) /* Caller wants the context. */
678 *ret_kdbhd = ctx->kr_handle;
679 ctx->kr_handle = NULL;
681 get_pubkey_end (ctx);
689 /* Find a public key from NAME and return the keyblock or the key. If
690 ret_kdb is not NULL, the KEYDB handle used to locate this keyblock
691 is returned and the caller is responsible for closing it. If a key
692 was not found (or if local search has been disabled) and NAME is a
693 valid RFC822 mailbox and --auto-key-locate has been enabled, we try
694 to import the key via the online mechanisms defined by
695 --auto-key-locate. */
697 get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
698 const char *name, KBNODE * ret_keyblock,
699 KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
702 strlist_t namelist = NULL;
706 int anylocalfirst = 0;
711 is_mbox = is_valid_mailbox (name);
713 /* Check whether the default local search has been disabled.
714 This is the case if either the "nodefault" or the "local" keyword
715 are in the list of auto key locate mechanisms.
717 ANYLOCALFIRST is set if the search order has the local method
718 before any other or if "local" is used first by default. This
719 makes sure that if a RETCTX is used it is only set if a local
720 search has precedence over the other search methods and only then
721 a followup call to get_pubkey_next shall succeed. */
724 for (akl = opt.auto_key_locate; akl; akl = akl->next)
725 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
730 for (akl = opt.auto_key_locate; akl; akl = akl->next)
731 if (akl->type != AKL_NODEFAULT)
733 if (akl->type == AKL_LOCAL)
742 if (nodefault && is_mbox)
744 /* Nodefault but a mailbox - let the AKL locate the key. */
745 rc = GPG_ERR_NO_PUBKEY;
749 add_to_strlist (&namelist, name);
750 rc = key_byname (retctx, namelist, pk, 0,
751 include_unusable, ret_keyblock, ret_kdbhd);
754 /* If the requested name resembles a valid mailbox and automatic
755 retrieval has been enabled, we try to import the key. */
756 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && !no_akl && is_mbox)
758 for (akl = opt.auto_key_locate; akl; akl = akl->next)
760 unsigned char *fpr = NULL;
762 int did_key_byname = 0;
763 int no_fingerprint = 0;
764 const char *mechanism = "?";
769 /* This is a dummy mechanism. */
771 rc = GPG_ERR_NO_PUBKEY;
779 get_pubkey_end (*retctx);
782 add_to_strlist (&namelist, name);
783 rc = key_byname (anylocalfirst ? retctx : NULL,
785 include_unusable, ret_keyblock, ret_kdbhd);
789 mechanism = "DNS CERT";
790 glo_ctrl.in_auto_key_retrieve++;
791 rc = keyserver_import_cert (ctrl, name, &fpr, &fpr_len);
792 glo_ctrl.in_auto_key_retrieve--;
797 glo_ctrl.in_auto_key_retrieve++;
798 rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
799 glo_ctrl.in_auto_key_retrieve--;
804 glo_ctrl.in_auto_key_retrieve++;
805 rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
806 glo_ctrl.in_auto_key_retrieve--;
810 /* Strictly speaking, we don't need to only use a valid
811 mailbox for the getname search, but it helps cut down
812 on the problem of searching for something like "john"
813 and getting a whole lot of keys back. */
816 mechanism = opt.keyserver->uri;
817 glo_ctrl.in_auto_key_retrieve++;
818 rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
820 glo_ctrl.in_auto_key_retrieve--;
824 mechanism = "Unconfigured keyserver";
825 rc = GPG_ERR_NO_PUBKEY;
831 struct keyserver_spec *keyserver;
833 mechanism = akl->spec->uri;
834 keyserver = keyserver_match (akl->spec);
835 glo_ctrl.in_auto_key_retrieve++;
836 rc = keyserver_import_name (ctrl,
837 name, &fpr, &fpr_len, keyserver);
838 glo_ctrl.in_auto_key_retrieve--;
843 /* Use the fingerprint of the key that we actually fetched.
844 This helps prevent problems where the key that we fetched
845 doesn't have the same name that we used to fetch it. In
846 the case of CERT and PKA, this is an actual security
847 requirement as the URL might point to a key put in by an
848 attacker. By forcing the use of the fingerprint, we
849 won't use the attacker's key here. */
852 char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
854 assert (fpr_len <= MAX_FINGERPRINT_LEN);
856 free_strlist (namelist);
859 bin2hex (fpr, fpr_len, fpr_string);
862 log_info ("auto-key-locate found fingerprint %s\n",
865 add_to_strlist (&namelist, fpr_string);
867 else if (!rc && !fpr && !did_key_byname)
870 rc = GPG_ERR_NO_PUBKEY;
875 if (!rc && !did_key_byname)
879 get_pubkey_end (*retctx);
882 rc = key_byname (anylocalfirst ? retctx : NULL,
884 include_unusable, ret_keyblock, ret_kdbhd);
889 log_info (_("automatically retrieved '%s' via %s\n"),
893 if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
894 || opt.verbose || no_fingerprint)
895 log_info (_("error retrieving '%s' via %s: %s\n"),
897 no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
904 get_pubkey_end (*retctx);
908 if (retctx && *retctx)
910 assert (!(*retctx)->extra_list);
911 (*retctx)->extra_list = namelist;
914 free_strlist (namelist);
920 get_pubkey_bynames (GETKEY_CTX * retctx, PKT_public_key * pk,
921 strlist_t names, KBNODE * ret_keyblock)
923 return key_byname (retctx, names, pk, 0, 1, ret_keyblock, NULL);
927 get_pubkey_next (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE * ret_keyblock)
929 return gpg_err_code (getkey_next (ctx, pk, ret_keyblock));
933 get_pubkey_end (GETKEY_CTX ctx)
939 /* Search for a key with the given standard fingerprint. In contrast
940 * to get_pubkey_byfprint we assume a right padded fingerprint of the
941 * standard length. PK may be NULL to only put the result into the
942 * internal caches. */
944 get_pubkey_byfpr (PKT_public_key *pk, const byte *fpr)
947 struct getkey_ctx_s ctx;
950 memset (&ctx, 0, sizeof ctx);
952 ctx.not_allocated = 1;
953 ctx.kr_handle = keydb_new ();
955 ctx.items[0].mode = KEYDB_SEARCH_MODE_FPR;
956 memcpy (ctx.items[0].u.fpr, fpr, MAX_FINGERPRINT_LEN);
957 err = lookup (&ctx, &kb, 0);
959 pk_from_block (&ctx, pk, kb);
961 get_pubkey_end (&ctx);
967 /* Search for a key with the given fingerprint. The caller need to
968 * prove an allocated public key object at PK. If R_KEYBLOCK is not
969 * NULL the entire keyblock is stored there and the caller needs to
970 * call release_kbnode() on it. Note that this function does an exact
971 * search and thus the public key stored at PK may be a copy of a
975 * We should replace this with the _byname function. This can be done
976 * by creating a userID conforming to the unified fingerprint style.
979 get_pubkey_byfprint (PKT_public_key *pk, kbnode_t *r_keyblock,
980 const byte * fprint, size_t fprint_len)
987 if (fprint_len == 20 || fprint_len == 16)
989 struct getkey_ctx_s ctx;
992 memset (&ctx, 0, sizeof ctx);
994 ctx.not_allocated = 1;
995 ctx.kr_handle = keydb_new ();
997 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
998 : KEYDB_SEARCH_MODE_FPR20;
999 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1000 rc = lookup (&ctx, &kb, 0);
1003 pk_from_block (&ctx, pk, kb);
1010 release_kbnode (kb);
1011 get_pubkey_end (&ctx);
1014 rc = GPG_ERR_GENERAL; /* Oops */
1019 /* Get a public key and store it into the allocated pk. This function
1020 differs from get_pubkey_byfprint() in that it does not do a check
1021 of the key to avoid recursion. It should be used only in very
1022 certain cases. PK may be NULL to check just for the existance of
1025 get_pubkey_byfprint_fast (PKT_public_key * pk,
1026 const byte * fprint, size_t fprint_len)
1031 byte fprbuf[MAX_FINGERPRINT_LEN];
1034 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1035 fprbuf[i] = fprint[i];
1036 while (i < MAX_FINGERPRINT_LEN)
1040 rc = keydb_search_fpr (hd, fprbuf);
1041 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1044 return GPG_ERR_NO_PUBKEY;
1046 rc = keydb_get_keyblock (hd, &keyblock);
1050 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1051 return GPG_ERR_NO_PUBKEY;
1054 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1055 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1057 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1058 release_kbnode (keyblock);
1060 /* Not caching key here since it won't have all of the fields
1067 /* Search for a key with the given fingerprint and return the
1068 * complete keyblock which may have more than only this key. */
1070 get_keyblock_byfprint (KBNODE * ret_keyblock, const byte * fprint,
1075 if (fprint_len == 20 || fprint_len == 16)
1077 struct getkey_ctx_s ctx;
1079 memset (&ctx, 0, sizeof ctx);
1080 ctx.not_allocated = 1;
1081 ctx.kr_handle = keydb_new ();
1083 ctx.items[0].mode = (fprint_len == 16
1084 ? KEYDB_SEARCH_MODE_FPR16
1085 : KEYDB_SEARCH_MODE_FPR20);
1086 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1087 rc = lookup (&ctx, ret_keyblock, 0);
1088 get_pubkey_end (&ctx);
1091 rc = GPG_ERR_GENERAL; /* Oops */
1097 /* Get a secret key by NAME and store it into PK. If NAME is NULL use
1098 * the default key. This functions checks that a corresponding secret
1099 * key is available. With no secret key it does not succeeed. */
1101 get_seckey_byname (PKT_public_key *pk, const char *name)
1104 strlist_t namelist = NULL;
1105 int include_unusable = 1;
1107 /* If we have no name, try to use the default secret key. If we
1108 have no default, we'll use the first usable one. */
1110 if (!name && opt.def_secret_key && *opt.def_secret_key)
1111 add_to_strlist (&namelist, opt.def_secret_key);
1113 add_to_strlist (&namelist, name);
1115 include_unusable = 0;
1117 err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
1119 free_strlist (namelist);
1126 /* Search for a key with the given fingerprint.
1128 * We should replace this with the _byname function. This can be done
1129 * by creating a userID conforming to the unified fingerprint style. */
1131 get_seckey_byfprint (PKT_public_key *pk, const byte * fprint, size_t fprint_len)
1135 if (fprint_len == 20 || fprint_len == 16)
1137 struct getkey_ctx_s ctx;
1140 memset (&ctx, 0, sizeof ctx);
1142 ctx.not_allocated = 1;
1143 ctx.kr_handle = keydb_new ();
1145 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1146 : KEYDB_SEARCH_MODE_FPR20;
1147 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1148 err = lookup (&ctx, &kb, 1);
1150 pk_from_block (&ctx, pk, kb);
1151 release_kbnode (kb);
1152 get_pubkey_end (&ctx);
1155 err = gpg_error (GPG_ERR_BUG);
1160 /* Search for a secret key with the given fingerprint and return the
1161 complete keyblock which may have more than only this key. Return
1162 an error if no corresponding secret key is available. */
1164 get_seckeyblock_byfprint (kbnode_t *ret_keyblock,
1165 const byte *fprint, size_t fprint_len)
1168 struct getkey_ctx_s ctx;
1170 if (fprint_len != 20 && fprint_len == 16)
1171 return gpg_error (GPG_ERR_BUG);
1173 memset (&ctx, 0, sizeof ctx);
1174 ctx.not_allocated = 1;
1175 ctx.kr_handle = keydb_new ();
1177 ctx.items[0].mode = (fprint_len == 16
1178 ? KEYDB_SEARCH_MODE_FPR16 : KEYDB_SEARCH_MODE_FPR20);
1179 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1180 err = lookup (&ctx, ret_keyblock, 1);
1181 get_pubkey_end (&ctx);
1188 /* The new function to return a key.
1189 FIXME: Document it. */
1191 getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
1192 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
1194 return key_byname (retctx, names, pk, want_secret, 1,
1195 ret_keyblock, NULL);
1199 /* Get a key by name and store it into PK if that is not NULL. If
1200 * RETCTX is not NULL return the search context which needs to be
1201 * released by the caller using getkey_end. If NAME is NULL use the
1202 * default key (see below). On success and if RET_KEYBLOCK is not
1203 * NULL the found keyblock is stored at this address. WANT_SECRET
1204 * passed as true requires that a secret key is available for the
1207 * If WANT_SECRET is true and NAME is NULL and a default key has been
1208 * defined that defined key is used. In all other cases the first
1209 * available key is used.
1211 * FIXME: Explain what is up with unusable keys.
1213 * FIXME: We also have the get_pubkey_byname function which has a
1214 * different semantic. Should be merged with this one.
1217 getkey_byname (getkey_ctx_t *retctx, PKT_public_key *pk,
1218 const char *name, int want_secret, kbnode_t *ret_keyblock)
1221 strlist_t namelist = NULL;
1222 int with_unusable = 1;
1224 if (want_secret && !name && opt.def_secret_key && *opt.def_secret_key)
1225 add_to_strlist (&namelist, opt.def_secret_key);
1227 add_to_strlist (&namelist, name);
1231 err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
1232 ret_keyblock, NULL);
1234 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
1235 WANT_SECRET has been used. */
1237 free_strlist (namelist);
1243 /* The new function to return the next key. */
1245 getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
1247 int rc; /* Fixme: Make sure this is proper gpg_error */
1249 /* We need to disable the caching so that for an exact key search we
1250 won't get the result back from the cache and thus end up in an
1251 endless loop. Disabling this here is sufficient because although
1252 the result has been cached, if won't be used then. */
1253 keydb_disable_caching (ctx->kr_handle);
1255 rc = lookup (ctx, ret_keyblock, ctx->want_secret);
1256 if (!rc && pk && ret_keyblock)
1257 pk_from_block (ctx, pk, *ret_keyblock);
1263 /* The new function to finish a key listing. */
1265 getkey_end (getkey_ctx_t ctx)
1269 memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
1270 keydb_release (ctx->kr_handle);
1271 free_strlist (ctx->extra_list);
1272 if (!ctx->not_allocated)
1279 /************************************************
1280 ************* Merging stuff ********************
1281 ************************************************/
1283 /* Set the mainkey_id fields for all keys in KEYBLOCK. This is
1284 usually done by merge_selfsigs but at some places we only need the
1285 main_kid but the the full merging. The function also guarantees
1286 that all pk->keyids are computed. */
1288 setup_main_keyids (kbnode_t keyblock)
1290 u32 kid[2], mainkid[2];
1291 kbnode_t kbctx, node;
1294 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1296 pk = keyblock->pkt->pkt.public_key;
1298 keyid_from_pk (pk, mainkid);
1299 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1301 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
1302 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1304 pk = node->pkt->pkt.public_key;
1305 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
1306 if (!pk->main_keyid[0] && !pk->main_keyid[1])
1308 pk->main_keyid[0] = mainkid[0];
1309 pk->main_keyid[1] = mainkid[1];
1315 /* Merge all self-signatures with the keys. */
1317 merge_keys_and_selfsig (KBNODE keyblock)
1321 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
1322 merge_selfsigs (keyblock);
1324 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
1329 parse_key_usage (PKT_signature * sig)
1336 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
1339 /* First octet of the keyflags. */
1344 key_usage |= PUBKEY_USAGE_CERT;
1350 key_usage |= PUBKEY_USAGE_SIG;
1354 /* We do not distinguish between encrypting communications and
1355 encrypting storage. */
1356 if (flags & (0x04 | 0x08))
1358 key_usage |= PUBKEY_USAGE_ENC;
1359 flags &= ~(0x04 | 0x08);
1364 key_usage |= PUBKEY_USAGE_AUTH;
1369 key_usage |= PUBKEY_USAGE_UNKNOWN;
1372 key_usage |= PUBKEY_USAGE_NONE;
1374 else if (p) /* Key flags of length zero. */
1375 key_usage |= PUBKEY_USAGE_NONE;
1377 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1378 capability that we do not handle. This serves to distinguish
1379 between a zero key usage which we handle as the default
1380 capabilities for that algorithm, and a usage that we do not
1381 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
1382 key_flags have been given but they do not specify any usage. */
1388 /* Apply information from SIGNODE (which is the valid self-signature
1389 * associated with that UID) to the UIDNODE:
1390 * - wether the UID has been revoked
1391 * - assumed creation date of the UID
1392 * - temporary store the keyflags here
1393 * - temporary store the key expiration time here
1394 * - mark whether the primary user ID flag hat been set.
1395 * - store the preferences
1398 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
1400 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1401 PKT_signature *sig = signode->pkt->pkt.signature;
1402 const byte *p, *sym, *hash, *zip;
1403 size_t n, nsym, nhash, nzip;
1405 sig->flags.chosen_selfsig = 1;/* We chose this one. */
1406 uid->created = 0; /* Not created == invalid. */
1407 if (IS_UID_REV (sig))
1409 uid->is_revoked = 1;
1410 return; /* Has been revoked. */
1413 uid->is_revoked = 0;
1415 uid->expiredate = sig->expiredate;
1417 if (sig->flags.expired)
1419 uid->is_expired = 1;
1420 return; /* Has expired. */
1423 uid->is_expired = 0;
1425 uid->created = sig->timestamp; /* This one is okay. */
1426 uid->selfsigversion = sig->version;
1427 /* If we got this far, it's not expired :) */
1428 uid->is_expired = 0;
1430 /* Store the key flags in the helper variable for later processing. */
1431 uid->help_key_usage = parse_key_usage (sig);
1433 /* Ditto for the key expiration. */
1434 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1435 if (p && buf32_to_u32 (p))
1436 uid->help_key_expire = keycreated + buf32_to_u32 (p);
1438 uid->help_key_expire = 0;
1440 /* Set the primary user ID flag - we will later wipe out some
1441 * of them to only have one in our keyblock. */
1442 uid->is_primary = 0;
1443 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
1445 uid->is_primary = 2;
1447 /* We could also query this from the unhashed area if it is not in
1448 * the hased area and then later try to decide which is the better
1449 * there should be no security problem with this.
1450 * For now we only look at the hashed one. */
1452 /* Now build the preferences list. These must come from the
1453 hashed section so nobody can modify the ciphers a key is
1454 willing to accept. */
1455 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
1458 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
1461 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
1466 n = nsym + nhash + nzip;
1471 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
1473 for (; nsym; nsym--, n++)
1475 uid->prefs[n].type = PREFTYPE_SYM;
1476 uid->prefs[n].value = *sym++;
1478 for (; nhash; nhash--, n++)
1480 uid->prefs[n].type = PREFTYPE_HASH;
1481 uid->prefs[n].value = *hash++;
1483 for (; nzip; nzip--, n++)
1485 uid->prefs[n].type = PREFTYPE_ZIP;
1486 uid->prefs[n].value = *zip++;
1488 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
1489 uid->prefs[n].value = 0;
1492 /* See whether we have the MDC feature. */
1494 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1495 if (p && n && (p[0] & 0x01))
1498 /* And the keyserver modify flag. */
1499 uid->flags.ks_modify = 1;
1500 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1501 if (p && n && (p[0] & 0x80))
1502 uid->flags.ks_modify = 0;
1506 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
1508 rinfo->date = sig->timestamp;
1509 rinfo->algo = sig->pubkey_algo;
1510 rinfo->keyid[0] = sig->keyid[0];
1511 rinfo->keyid[1] = sig->keyid[1];
1515 /* Note that R_REVOKED may be set to 0, 1 or 2. */
1517 merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
1518 struct revoke_info *rinfo)
1520 PKT_public_key *pk = NULL;
1523 u32 sigdate, uiddate, uiddate2;
1524 KBNODE signode, uidnode, uidnode2;
1525 u32 curtime = make_timestamp ();
1526 unsigned int key_usage = 0;
1527 u32 keytimestamp = 0;
1529 int key_expire_seen = 0;
1530 byte sigversion = 0;
1533 memset (rinfo, 0, sizeof (*rinfo));
1535 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1537 pk = keyblock->pkt->pkt.public_key;
1538 keytimestamp = pk->timestamp;
1540 keyid_from_pk (pk, kid);
1541 pk->main_keyid[0] = kid[0];
1542 pk->main_keyid[1] = kid[1];
1544 if (pk->version < 4)
1546 /* Before v4 the key packet itself contains the expiration date
1547 * and there was no way to change it, so we start with the one
1548 * from the key packet. */
1549 key_expire = pk->max_expiredate;
1550 key_expire_seen = 1;
1553 /* First pass: Find the latest direct key self-signature. We assume
1554 * that the newest one overrides all others. */
1556 /* In case this key was already merged. */
1562 sigdate = 0; /* Helper variable to find the latest signature. */
1563 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
1565 if (k->pkt->pkttype == PKT_SIGNATURE)
1567 PKT_signature *sig = k->pkt->pkt.signature;
1568 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1570 if (check_key_signature (keyblock, k, NULL))
1571 ; /* Signature did not verify. */
1572 else if (IS_KEY_REV (sig))
1574 /* Key has been revoked - there is no way to
1575 * override such a revocation, so we theoretically
1576 * can stop now. We should not cope with expiration
1577 * times for revocations here because we have to
1578 * assume that an attacker can generate all kinds of
1579 * signatures. However due to the fact that the key
1580 * has been revoked it does not harm either and by
1581 * continuing we gather some more info on that
1584 sig_to_revoke_info (sig, rinfo);
1586 else if (IS_KEY_SIG (sig))
1588 /* Add any revocation keys onto the pk. This is
1589 particularly interesting since we normally only
1590 get data from the most recent 1F signature, but
1591 you need multiple 1F sigs to properly handle
1592 revocation keys (PGP does it this way, and a
1593 revocation key could be sensitive and hence in a
1594 different signature). */
1600 xrealloc (pk->revkey, sizeof (struct revocation_key) *
1601 (pk->numrevkeys + sig->numrevkeys));
1603 for (i = 0; i < sig->numrevkeys; i++)
1604 memcpy (&pk->revkey[pk->numrevkeys++],
1606 sizeof (struct revocation_key));
1609 if (sig->timestamp >= sigdate)
1611 if (sig->flags.expired)
1612 ; /* Signature has expired - ignore it. */
1615 sigdate = sig->timestamp;
1617 if (sig->version > sigversion)
1618 sigversion = sig->version;
1627 /* Remove dupes from the revocation keys. */
1631 int i, j, x, changed = 0;
1633 for (i = 0; i < pk->numrevkeys; i++)
1635 for (j = i + 1; j < pk->numrevkeys; j++)
1637 if (memcmp (&pk->revkey[i], &pk->revkey[j],
1638 sizeof (struct revocation_key)) == 0)
1642 for (x = j; x < pk->numrevkeys - 1; x++)
1643 pk->revkey[x] = pk->revkey[x + 1];
1653 pk->revkey = xrealloc (pk->revkey,
1655 sizeof (struct revocation_key));
1660 /* Some information from a direct key signature take precedence
1661 * over the same information given in UID sigs. */
1662 PKT_signature *sig = signode->pkt->pkt.signature;
1665 key_usage = parse_key_usage (sig);
1667 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1668 if (p && buf32_to_u32 (p))
1670 key_expire = keytimestamp + buf32_to_u32 (p);
1671 key_expire_seen = 1;
1674 /* Mark that key as valid: One direct key signature should
1675 * render a key as valid. */
1676 pk->flags.valid = 1;
1679 /* Pass 1.5: Look for key revocation signatures that were not made
1680 by the key (i.e. did a revocation key issue a revocation for
1681 us?). Only bother to do this if there is a revocation key in the
1682 first place and we're not revoked already. */
1684 if (!*r_revoked && pk->revkey)
1685 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
1687 if (k->pkt->pkttype == PKT_SIGNATURE)
1689 PKT_signature *sig = k->pkt->pkt.signature;
1691 if (IS_KEY_REV (sig) &&
1692 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
1694 int rc = check_revocation_keys (pk, sig);
1698 sig_to_revoke_info (sig, rinfo);
1699 /* Don't continue checking since we can't be any
1700 more revoked than this. */
1703 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
1704 pk->flags.maybe_revoked = 1;
1706 /* A failure here means the sig did not verify, was
1707 not issued by a revocation key, or a revocation
1708 key loop was broken. If a revocation key isn't
1709 findable, however, the key might be revoked and
1710 we don't know it. */
1712 /* TODO: In the future handle subkey and cert
1713 revocations? PGP doesn't, but it's in 2440. */
1718 /* Second pass: Look at the self-signature of all user IDs. */
1719 signode = uidnode = NULL;
1720 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
1721 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1723 if (k->pkt->pkttype == PKT_USER_ID)
1725 if (uidnode && signode)
1727 fixup_uidnode (uidnode, signode, keytimestamp);
1728 pk->flags.valid = 1;
1734 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1736 PKT_signature *sig = k->pkt->pkt.signature;
1737 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1739 if (check_key_signature (keyblock, k, NULL))
1740 ; /* signature did not verify */
1741 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
1742 && sig->timestamp >= sigdate)
1744 /* Note: we allow to invalidate cert revocations
1745 * by a newer signature. An attacker can't use this
1746 * because a key should be revoced with a key revocation.
1747 * The reason why we have to allow for that is that at
1748 * one time an email address may become invalid but later
1749 * the same email address may become valid again (hired,
1750 * fired, hired again). */
1752 sigdate = sig->timestamp;
1754 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
1755 if (sig->version > sigversion)
1756 sigversion = sig->version;
1761 if (uidnode && signode)
1763 fixup_uidnode (uidnode, signode, keytimestamp);
1764 pk->flags.valid = 1;
1767 /* If the key isn't valid yet, and we have
1768 --allow-non-selfsigned-uid set, then force it valid. */
1769 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
1772 log_info (_("Invalid key %s made valid by"
1773 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
1774 pk->flags.valid = 1;
1777 /* The key STILL isn't valid, so try and find an ultimately
1778 trusted signature. */
1779 if (!pk->flags.valid)
1783 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1786 if (k->pkt->pkttype == PKT_USER_ID)
1788 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1790 PKT_signature *sig = k->pkt->pkt.signature;
1792 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
1794 PKT_public_key *ultimate_pk;
1796 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
1798 /* We don't want to use the full get_pubkey to
1799 avoid infinite recursion in certain cases.
1800 There is no reason to check that an ultimately
1801 trusted key is still valid - if it has been
1802 revoked or the user should also renmove the
1803 ultimate trust flag. */
1804 if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
1805 && check_key_signature2 (keyblock, k, ultimate_pk,
1806 NULL, NULL, NULL, NULL) == 0
1807 && get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
1809 free_public_key (ultimate_pk);
1810 pk->flags.valid = 1;
1814 free_public_key (ultimate_pk);
1820 /* Record the highest selfsig version so we know if this is a v3
1821 key through and through, or a v3 key with a v4 selfsig
1822 somewhere. This is useful in a few places to know if the key
1823 must be treated as PGP2-style or OpenPGP-style. Note that a
1824 selfsig revocation with a higher version number will also raise
1825 this value. This is okay since such a revocation must be
1826 issued by the user (i.e. it cannot be issued by someone else to
1827 modify the key behavior.) */
1829 pk->selfsigversion = sigversion;
1831 /* Now that we had a look at all user IDs we can now get some information
1832 * from those user IDs.
1837 /* Find the latest user ID with key flags set. */
1838 uiddate = 0; /* Helper to find the latest user ID. */
1839 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1842 if (k->pkt->pkttype == PKT_USER_ID)
1844 PKT_user_id *uid = k->pkt->pkt.user_id;
1845 if (uid->help_key_usage && uid->created > uiddate)
1847 key_usage = uid->help_key_usage;
1848 uiddate = uid->created;
1855 /* No key flags at all: get it from the algo. */
1856 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
1860 /* Check that the usage matches the usage as given by the algo. */
1861 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
1862 if (x) /* Mask it down to the actual allowed usage. */
1866 /* Whatever happens, it's a primary key, so it can certify. */
1867 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
1869 if (!key_expire_seen)
1871 /* Find the latest valid user ID with a key expiration set
1872 * Note, that this may be a different one from the above because
1873 * some user IDs may have no expiration date set. */
1875 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1878 if (k->pkt->pkttype == PKT_USER_ID)
1880 PKT_user_id *uid = k->pkt->pkt.user_id;
1881 if (uid->help_key_expire && uid->created > uiddate)
1883 key_expire = uid->help_key_expire;
1884 uiddate = uid->created;
1890 /* Currently only v3 keys have a maximum expiration date, but I'll
1891 bet v5 keys get this feature again. */
1893 || (pk->max_expiredate && key_expire > pk->max_expiredate))
1894 key_expire = pk->max_expiredate;
1896 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
1897 pk->expiredate = key_expire;
1899 /* Fixme: we should see how to get rid of the expiretime fields but
1900 * this needs changes at other places too. */
1902 /* And now find the real primary user ID and delete all others. */
1903 uiddate = uiddate2 = 0;
1904 uidnode = uidnode2 = NULL;
1905 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1907 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
1909 PKT_user_id *uid = k->pkt->pkt.user_id;
1910 if (uid->is_primary)
1912 if (uid->created > uiddate)
1914 uiddate = uid->created;
1917 else if (uid->created == uiddate && uidnode)
1919 /* The dates are equal, so we need to do a
1920 different (and arbitrary) comparison. This
1921 should rarely, if ever, happen. It's good to
1922 try and guarantee that two different GnuPG
1923 users with two different keyrings at least pick
1924 the same primary. */
1925 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
1931 if (uid->created > uiddate2)
1933 uiddate2 = uid->created;
1936 else if (uid->created == uiddate2 && uidnode2)
1938 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
1946 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1949 if (k->pkt->pkttype == PKT_USER_ID &&
1950 !k->pkt->pkt.user_id->attrib_data)
1952 PKT_user_id *uid = k->pkt->pkt.user_id;
1954 uid->is_primary = 0;
1960 /* None is flagged primary - use the latest user ID we have,
1961 and disambiguate with the arbitrary packet comparison. */
1962 uidnode2->pkt->pkt.user_id->is_primary = 1;
1966 /* None of our uids were self-signed, so pick the one that
1967 sorts first to be the primary. This is the best we can do
1968 here since there are no self sigs to date the uids. */
1972 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1975 if (k->pkt->pkttype == PKT_USER_ID
1976 && !k->pkt->pkt.user_id->attrib_data)
1981 uidnode->pkt->pkt.user_id->is_primary = 1;
1986 if (cmp_user_ids (k->pkt->pkt.user_id,
1987 uidnode->pkt->pkt.user_id) > 0)
1989 uidnode->pkt->pkt.user_id->is_primary = 0;
1991 uidnode->pkt->pkt.user_id->is_primary = 1;
1994 k->pkt->pkt.user_id->is_primary = 0; /* just to be
2002 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
2003 Caller must free the signature when they are done. */
2004 static PKT_signature *
2005 buf_to_sig (const byte * buf, size_t len)
2007 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
2008 IOBUF iobuf = iobuf_temp_with_content (buf, len);
2009 int save_mode = set_packet_list_mode (0);
2011 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
2017 set_packet_list_mode (save_mode);
2018 iobuf_close (iobuf);
2024 merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
2026 PKT_public_key *mainpk = NULL, *subpk = NULL;
2032 u32 curtime = make_timestamp ();
2033 unsigned int key_usage = 0;
2034 u32 keytimestamp = 0;
2038 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2040 mainpk = keyblock->pkt->pkt.public_key;
2041 if (mainpk->version < 4)
2042 return;/* (actually this should never happen) */
2043 keyid_from_pk (mainpk, mainkid);
2044 subpk = subnode->pkt->pkt.public_key;
2045 keytimestamp = subpk->timestamp;
2047 subpk->flags.valid = 0;
2048 subpk->main_keyid[0] = mainpk->main_keyid[0];
2049 subpk->main_keyid[1] = mainpk->main_keyid[1];
2051 /* Find the latest key binding self-signature. */
2053 sigdate = 0; /* Helper to find the latest signature. */
2054 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2057 if (k->pkt->pkttype == PKT_SIGNATURE)
2059 sig = k->pkt->pkt.signature;
2060 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
2062 if (check_key_signature (keyblock, k, NULL))
2063 ; /* Signature did not verify. */
2064 else if (IS_SUBKEY_REV (sig))
2066 /* Note that this means that the date on a
2067 revocation sig does not matter - even if the
2068 binding sig is dated after the revocation sig,
2069 the subkey is still marked as revoked. This
2070 seems ok, as it is just as easy to make new
2071 subkeys rather than re-sign old ones as the
2072 problem is in the distribution. Plus, PGP (7)
2073 does this the same way. */
2074 subpk->flags.revoked = 1;
2075 sig_to_revoke_info (sig, &subpk->revoked);
2076 /* Although we could stop now, we continue to
2077 * figure out other information like the old expiration
2080 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
2082 if (sig->flags.expired)
2083 ; /* Signature has expired - ignore it. */
2086 sigdate = sig->timestamp;
2088 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2095 /* No valid key binding. */
2099 sig = signode->pkt->pkt.signature;
2100 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
2102 key_usage = parse_key_usage (sig);
2105 /* No key flags at all: get it from the algo. */
2106 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
2110 /* Check that the usage matches the usage as given by the algo. */
2111 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
2112 if (x) /* Mask it down to the actual allowed usage. */
2116 subpk->pubkey_usage = key_usage;
2118 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2119 if (p && buf32_to_u32 (p))
2120 key_expire = keytimestamp + buf32_to_u32 (p);
2123 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
2124 subpk->expiredate = key_expire;
2126 /* Algo doesn't exist. */
2127 if (openpgp_pk_test_algo (subpk->pubkey_algo))
2130 subpk->flags.valid = 1;
2132 /* Find the most recent 0x19 embedded signature on our self-sig. */
2133 if (!subpk->flags.backsig)
2137 PKT_signature *backsig = NULL;
2141 /* We do this while() since there may be other embedded
2142 signatures in the future. We only want 0x19 here. */
2144 while ((p = enum_sig_subpkt (sig->hashed,
2145 SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
2147 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2149 PKT_signature *tempsig = buf_to_sig (p, n);
2152 if (tempsig->timestamp > sigdate)
2155 free_seckey_enc (backsig);
2158 sigdate = backsig->timestamp;
2161 free_seckey_enc (tempsig);
2167 /* It is safe to have this in the unhashed area since the 0x19
2168 is located on the selfsig for convenience, not security. */
2170 while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
2173 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2175 PKT_signature *tempsig = buf_to_sig (p, n);
2178 if (tempsig->timestamp > sigdate)
2181 free_seckey_enc (backsig);
2184 sigdate = backsig->timestamp;
2187 free_seckey_enc (tempsig);
2193 /* At ths point, backsig contains the most recent 0x19 sig.
2194 Let's see if it is good. */
2196 /* 2==valid, 1==invalid, 0==didn't check */
2197 if (check_backsig (mainpk, subpk, backsig) == 0)
2198 subpk->flags.backsig = 2;
2200 subpk->flags.backsig = 1;
2202 free_seckey_enc (backsig);
2209 * Merge information from the self-signatures with the key, so that
2210 * we can later use them more easy.
2211 * The function works by first applying the self signatures to the
2212 * primary key and the to each subkey.
2213 * Here are the rules we use to decide which inormation from which
2214 * self-signature is used:
2215 * We check all self signatures or validity and ignore all invalid signatures.
2216 * All signatures are then ordered by their creation date ....
2217 * For the primary key:
2221 merge_selfsigs (KBNODE keyblock)
2225 struct revoke_info rinfo;
2226 PKT_public_key *main_pk;
2228 unsigned int mdc_feature;
2230 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2232 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
2234 log_error ("expected public key but found secret key "
2236 /* We better exit here because a public key is expected at
2237 other places too. FIXME: Figure this out earlier and
2238 don't get to here at all */
2244 merge_selfsigs_main (keyblock, &revoked, &rinfo);
2246 /* Now merge in the data from each of the subkeys. */
2247 for (k = keyblock; k; k = k->next)
2249 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2251 merge_selfsigs_subkey (keyblock, k);
2255 main_pk = keyblock->pkt->pkt.public_key;
2256 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
2258 /* If the primary key is revoked, expired, or invalid we
2259 * better set the appropriate flags on that key and all
2261 for (k = keyblock; k; k = k->next)
2263 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2264 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2266 PKT_public_key *pk = k->pkt->pkt.public_key;
2267 if (!main_pk->flags.valid)
2268 pk->flags.valid = 0;
2269 if (revoked && !pk->flags.revoked)
2271 pk->flags.revoked = revoked;
2272 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
2274 if (main_pk->has_expired)
2275 pk->has_expired = main_pk->has_expired;
2281 /* Set the preference list of all keys to those of the primary real
2282 * user ID. Note: we use these preferences when we don't know by
2283 * which user ID the key has been selected.
2284 * fixme: we should keep atoms of commonly used preferences or
2285 * use reference counting to optimize the preference lists storage.
2286 * FIXME: it might be better to use the intersection of
2288 * Do a similar thing for the MDC feature flag. */
2291 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2293 if (k->pkt->pkttype == PKT_USER_ID
2294 && !k->pkt->pkt.user_id->attrib_data
2295 && k->pkt->pkt.user_id->is_primary)
2297 prefs = k->pkt->pkt.user_id->prefs;
2298 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2302 for (k = keyblock; k; k = k->next)
2304 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2305 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2307 PKT_public_key *pk = k->pkt->pkt.public_key;
2310 pk->prefs = copy_prefs (prefs);
2311 pk->flags.mdc = mdc_feature;
2318 /* See whether the key fits our requirements and in case we do not
2319 * request the primary key, select a suitable subkey.
2321 * Returns: True when a suitable key has been found.
2323 * We have to distinguish four cases: FIXME!
2324 * 1. No usage and no primary key requested
2325 * Examples for this case are that we have a keyID to be used
2326 * for decrytion or verification.
2327 * 2. No usage but primary key requested
2328 * This is the case for all functions which work on an
2329 * entire keyblock, e.g. for editing or listing
2330 * 3. Usage and primary key requested
2332 * 4. Usage but no primary key requested
2334 * FIXME: Tell what is going to happen here and something about the rationale
2335 * Note: We don't use this function if no specific usage is requested;
2336 * This way the getkey functions can be used for plain key listings.
2338 * CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
2339 * is the key we actually found by looking at the keyid or a fingerprint and
2340 * may either point to the primary or one of the subkeys. */
2342 finish_lookup (GETKEY_CTX ctx)
2344 KBNODE keyblock = ctx->keyblock;
2346 KBNODE foundk = NULL;
2347 PKT_user_id *foundu = NULL;
2348 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2349 unsigned int req_usage = (ctx->req_usage & USAGE_MASK);
2350 /* Request the primary if we're certifying another key, and also
2351 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2352 do not understand signatures made by a signing subkey. PGP 8
2354 int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2355 ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2358 u32 curtime = make_timestamp ();
2360 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
2362 ctx->found_key = NULL;
2366 for (k = keyblock; k; k = k->next)
2370 assert (k->pkt->pkttype == PKT_PUBLIC_KEY
2371 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
2378 for (k = keyblock; k; k = k->next)
2382 assert (k->pkt->pkttype == PKT_USER_ID);
2383 foundu = k->pkt->pkt.user_id;
2389 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2390 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
2391 foundk ? "one" : "all", req_usage);
2395 latest_key = foundk ? foundk : keyblock;
2401 /* Do not look at subkeys if a certification key is requested. */
2402 if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim)
2405 /* Either start a loop or check just this one subkey. */
2406 for (k = foundk ? foundk : keyblock; k; k = nextk)
2410 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2413 nextk = NULL; /* what a hack */
2414 pk = k->pkt->pkt.public_key;
2416 log_debug ("\tchecking subkey %08lX\n",
2417 (ulong) keyid_from_pk (pk, NULL));
2418 if (!pk->flags.valid)
2421 log_debug ("\tsubkey not valid\n");
2424 if (pk->flags.revoked)
2427 log_debug ("\tsubkey has been revoked\n");
2430 if (pk->has_expired)
2433 log_debug ("\tsubkey has expired\n");
2436 if (pk->timestamp > curtime && !opt.ignore_valid_from)
2439 log_debug ("\tsubkey not yet valid\n");
2443 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2446 log_debug ("\tusage does not match: want=%x have=%x\n",
2447 req_usage, pk->pubkey_usage);
2452 log_debug ("\tsubkey might be fine\n");
2453 /* In case a key has a timestamp of 0 set, we make sure
2454 that it is used. A better change would be to compare
2455 ">=" but that might also change the selected keys and
2456 is as such a more intrusive change. */
2457 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2459 latest_date = pk->timestamp;
2465 /* Okay now try the primary key unless we want an exact
2466 * key ID match on a subkey */
2467 if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim)
2470 if (DBG_LOOKUP && !foundk && !req_prim)
2471 log_debug ("\tno suitable subkeys found - trying primary\n");
2472 pk = keyblock->pkt->pkt.public_key;
2473 if (!pk->flags.valid)
2476 log_debug ("\tprimary key not valid\n");
2478 else if (pk->flags.revoked)
2481 log_debug ("\tprimary key has been revoked\n");
2483 else if (pk->has_expired)
2486 log_debug ("\tprimary key has expired\n");
2488 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2491 log_debug ("\tprimary key usage does not match: "
2492 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
2497 log_debug ("\tprimary key may be used\n");
2498 latest_key = keyblock;
2499 latest_date = pk->timestamp;
2506 log_debug ("\tno suitable key found - giving up\n");
2507 return 0; /* Not found. */
2512 log_debug ("\tusing key %08lX\n",
2513 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
2517 PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2519 free_user_id (pk->user_id);
2520 pk->user_id = scopy_user_id (foundu);
2523 ctx->found_key = latest_key;
2525 if (latest_key != keyblock && opt.verbose)
2528 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
2529 log_info (_("using subkey %s instead of primary key %s\n"),
2530 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
2534 cache_user_id (keyblock);
2536 return 1; /* Found. */
2540 /* Return true if all the search modes are fingerprints. */
2542 search_modes_are_fingerprint (getkey_ctx_t ctx)
2546 for (n=found=0; n < ctx->nitems; n++)
2548 switch (ctx->items[n].mode)
2550 case KEYDB_SEARCH_MODE_FPR16:
2551 case KEYDB_SEARCH_MODE_FPR20:
2552 case KEYDB_SEARCH_MODE_FPR:
2559 return found && found == ctx->nitems;
2563 /* The main function to lookup a key. On success the found keyblock
2564 is stored at RET_KEYBLOCK and also in CTX. If WANT_SECRET is true
2565 a corresponding secret key is required. */
2567 lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, int want_secret)
2570 int no_suitable_key = 0;
2574 rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
2575 /* Skip over all legacy keys but only if they are not requested
2577 Fixme: The lower level keydb code should actually do that but
2578 then it would be harder to report the number of skipped
2579 legacy keys during import. */
2580 if (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY
2581 && !(ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2582 && !search_modes_are_fingerprint (ctx))
2587 /* If we are searching for the first key we have to make sure
2588 that the next iteration does not do an implicit reset.
2589 This can be triggered by an empty key ring. */
2590 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2591 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2593 rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
2596 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
2601 if (want_secret && agent_probe_any_secret_key (NULL, ctx->keyblock))
2602 goto skip; /* No secret key available. */
2604 /* Warning: node flag bits 0 and 1 should be preserved by
2605 * merge_selfsigs. For secret keys, premerge transferred the
2606 * keys to the keyblock. */
2607 merge_selfsigs (ctx->keyblock);
2608 if (finish_lookup (ctx))
2610 no_suitable_key = 0;
2614 no_suitable_key = 1;
2617 /* Release resources and continue search. */
2618 release_kbnode (ctx->keyblock);
2619 ctx->keyblock = NULL;
2620 /* We need to disable the caching so that for an exact key
2621 search we won't get the result back from the cache and thus
2622 end up in an endless loop. Disabling the cache here at this
2623 point is sufficient because even a cached result won't be
2624 used after a call to keydb_disable_caching. */
2625 keydb_disable_caching (ctx->kr_handle);
2629 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND
2630 && gpg_err_code (rc) != GPG_ERR_LEGACY_KEY)
2631 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
2635 *ret_keyblock = ctx->keyblock; /* Return the keyblock. */
2636 ctx->keyblock = NULL;
2638 else if ((gpg_err_code (rc) == GPG_ERR_NOT_FOUND
2639 || gpg_err_code (rc) == GPG_ERR_LEGACY_KEY) && no_suitable_key)
2640 rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
2641 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2642 rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
2644 release_kbnode (ctx->keyblock);
2645 ctx->keyblock = NULL;
2654 * Enumerate certain secret keys. Caller must use these procedure:
2655 * 1) create a void pointer and initialize it to NULL
2656 * 2) pass this void pointer by reference to this function
2657 * and provide space for the secret key (pass a buffer for sk)
2658 * 3) call this function as long as it does not return an error.
2659 * The error code GPG_ERR_EOF indicates the end of the listing.
2660 * 4) Always call this function a last time with SK set to NULL,
2661 * so that can free it's context.
2664 enum_secret_keys (void **context, PKT_public_key *sk)
2666 gpg_error_t err = 0;
2679 /* Make a new context. */
2680 c = xtrycalloc (1, sizeof *c);
2682 return gpg_error_from_syserror ();
2688 /* Free the context. */
2689 release_kbnode (c->keyblock);
2696 return gpg_error (GPG_ERR_EOF);
2700 /* Loop until we have a keyblock. */
2701 while (!c->keyblock)
2703 /* Loop over the list of secret keys. */
2709 case 0: /* First try to use the --default-key. */
2710 if (opt.def_secret_key && *opt.def_secret_key)
2711 name = opt.def_secret_key;
2715 case 1: /* Init list of keys to try. */
2716 c->sl = opt.secret_keys_to_try;
2720 case 2: /* Get next item from list. */
2724 c->sl = c->sl->next;
2730 default: /* No more names to check - stop. */
2732 return gpg_error (GPG_ERR_EOF);
2735 while (!name || !*name);
2737 err = getkey_byname (NULL, NULL, name, 1, &c->keyblock);
2740 /* getkey_byname might return a keyblock even in the
2741 error case - I have not checked. Thus better release
2743 release_kbnode (c->keyblock);
2747 c->node = c->keyblock;
2750 /* Get the next key from the current keyblock. */
2751 for (; c->node; c->node = c->node->next)
2753 if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
2754 || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2756 copy_public_key (sk, c->node->pkt->pkt.public_key);
2757 c->node = c->node->next;
2758 return 0; /* Found. */
2762 /* Dispose the keyblock and continue. */
2763 release_kbnode (c->keyblock);
2769 /*********************************************
2770 *********** User ID printing helpers *******
2771 *********************************************/
2773 /* Return a string with a printable representation of the user_id.
2774 * this string must be freed by xfree. */
2776 get_user_id_string (u32 * keyid, int mode, size_t *r_len)
2783 /* Try it two times; second pass reads from key resources. */
2786 for (r = user_id_db; r; r = r->next)
2788 for (a = r->keyids; a; a = a->next)
2790 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
2794 /* An empty string as user id is possible. Make
2795 sure that the malloc allocates one byte and
2796 does not bail out. */
2797 p = xmalloc (r->len? r->len : 1);
2798 memcpy (p, r->name, r->len);
2805 p = xasprintf ("%08lX%08lX %.*s",
2806 (ulong) keyid[0], (ulong) keyid[1],
2809 p = xasprintf ("%s %.*s", keystr (keyid),
2812 *r_len = strlen (p);
2820 while (++pass < 2 && !get_pubkey (NULL, keyid));
2823 p = xstrdup (user_id_not_found_utf8 ());
2825 p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
2827 p = xasprintf ("%s [?]", keystr (keyid));
2830 *r_len = strlen (p);
2836 get_user_id_string_native (u32 * keyid)
2838 char *p = get_user_id_string (keyid, 0, NULL);
2839 char *p2 = utf8_to_native (p, strlen (p), 0);
2846 get_long_user_id_string (u32 * keyid)
2848 return get_user_id_string (keyid, 1, NULL);
2852 /* Please try to use get_user_byfpr instead of this one. */
2854 get_user_id (u32 * keyid, size_t * rn)
2856 return get_user_id_string (keyid, 2, rn);
2860 /* Please try to use get_user_id_byfpr_native instead of this one. */
2862 get_user_id_native (u32 * keyid)
2865 char *p = get_user_id (keyid, &rn);
2866 char *p2 = utf8_to_native (p, rn, 0);
2872 /* Return a user id from the caching by looking it up using the FPR
2873 which must be of size MAX_FINGERPRINT_LEN. */
2875 get_user_id_byfpr (const byte *fpr, size_t *rn)
2881 /* Try it two times; second pass reads from key resources. */
2884 for (r = user_id_db; r; r = r->next)
2887 for (a = r->keyids; a; a = a->next)
2889 if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
2891 /* An empty string as user id is possible. Make
2892 sure that the malloc allocates one byte and does
2894 p = xmalloc (r->len? r->len : 1);
2895 memcpy (p, r->name, r->len);
2902 while (++pass < 2 && !get_pubkey_byfpr (NULL, fpr));
2903 p = xstrdup (user_id_not_found_utf8 ());
2909 get_user_id_byfpr_native (const byte *fpr)
2912 char *p = get_user_id_byfpr (fpr, &rn);
2913 char *p2 = utf8_to_native (p, rn, 0);
2921 get_ctx_handle (GETKEY_CTX ctx)
2923 return ctx->kr_handle;
2927 free_akl (struct akl *akl)
2933 free_keyserver_spec (akl->spec);
2941 while (opt.auto_key_locate)
2943 struct akl *akl2 = opt.auto_key_locate;
2944 opt.auto_key_locate = opt.auto_key_locate->next;
2949 /* Returns false on error. */
2951 parse_auto_key_locate (char *options)
2955 while ((tok = optsep (&options)))
2957 struct akl *akl, *check, *last = NULL;
2963 akl = xmalloc_clear (sizeof (*akl));
2965 if (ascii_strcasecmp (tok, "clear") == 0)
2968 free_akl (opt.auto_key_locate);
2969 opt.auto_key_locate = NULL;
2972 else if (ascii_strcasecmp (tok, "nodefault") == 0)
2973 akl->type = AKL_NODEFAULT;
2974 else if (ascii_strcasecmp (tok, "local") == 0)
2975 akl->type = AKL_LOCAL;
2976 else if (ascii_strcasecmp (tok, "ldap") == 0)
2977 akl->type = AKL_LDAP;
2978 else if (ascii_strcasecmp (tok, "keyserver") == 0)
2979 akl->type = AKL_KEYSERVER;
2981 else if (ascii_strcasecmp (tok, "cert") == 0)
2982 akl->type = AKL_CERT;
2984 else if (ascii_strcasecmp (tok, "pka") == 0)
2985 akl->type = AKL_PKA;
2986 else if ((akl->spec = parse_keyserver_uri (tok, 1)))
2987 akl->type = AKL_SPEC;
2994 /* We must maintain the order the user gave us */
2995 for (check = opt.auto_key_locate; check;
2996 last = check, check = check->next)
2998 /* Check for duplicates */
2999 if (check->type == akl->type
3000 && (akl->type != AKL_SPEC
3001 || (akl->type == AKL_SPEC
3002 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
3015 opt.auto_key_locate = akl;
3023 /* Return true if a secret key or secret subkey is available for one
3024 of the public keys in KEYBLOCK. */
3026 have_any_secret_key (ctrl_t ctrl, kbnode_t keyblock)
3030 for (node = keyblock; node; node = node->next)
3031 if ((node->pkt->pkttype == PKT_PUBLIC_KEY
3032 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3033 && !agent_probe_secret_key (ctrl, node->pkt->pkt.public_key))
3039 /* Return true if a secret key is available for the public key with
3040 * the given KEYID. This is just a fast check and does not tell us
3041 * whether the secret key is valid. It merely tells os whether there
3042 * is some secret key. */
3044 have_secret_key_with_kid (u32 *keyid)
3048 KEYDB_SEARCH_DESC desc;
3053 kdbhd = keydb_new ();
3054 memset (&desc, 0, sizeof desc);
3055 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
3056 desc.u.kid[0] = keyid[0];
3057 desc.u.kid[1] = keyid[1];
3060 err = keydb_search (kdbhd, &desc, 1, NULL);
3061 if (gpg_err_code (err) == GPG_ERR_LEGACY_KEY)
3066 err = keydb_get_keyblock (kdbhd, &keyblock);
3069 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
3073 for (node = keyblock; node; node = node->next)
3075 /* Bit 0 of the flags is set if the search found the key
3076 using that key or subkey. */
3077 if ((node->flag & 1))
3079 assert (node->pkt->pkttype == PKT_PUBLIC_KEY
3080 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3082 if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
3089 release_kbnode (keyblock);
3092 keydb_release (kdbhd);