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 #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
41 #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
43 #if MAX_PK_CACHE_ENTRIES < 2
44 #error We need the cache for key creation
50 int want_secret; /* The caller requested only secret keys. */
53 KBNODE found_key; /* Pointer into some keyblock. */
54 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)
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_algo = pk->req_algo;
395 ctx.req_usage = pk->req_usage;
396 rc = lookup (&ctx, &kb, 0);
399 pk_from_block (&ctx, pk, kb);
401 get_pubkey_end (&ctx);
407 rc = G10ERR_NO_PUBKEY;
411 cache_public_key (pk);
413 free_public_key (pk);
418 /* Get a public key and store it into the allocated pk. This function
419 differs from get_pubkey() in that it does not do a check of the key
420 to avoid recursion. It should be used only in very certain cases.
421 It will only retrieve primary keys. */
423 get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
431 #if MAX_PK_CACHE_ENTRIES
433 /* Try to get it from the cache */
436 for (ce = pk_cache; ce; ce = ce->next)
438 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
441 copy_public_key (pk, ce->pk);
449 rc = keydb_search_kid (hd, keyid);
450 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
453 return G10ERR_NO_PUBKEY;
455 rc = keydb_get_keyblock (hd, &keyblock);
459 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr (rc));
460 return G10ERR_NO_PUBKEY;
463 assert (keyblock && keyblock->pkt
464 && (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
465 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY));
467 keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
468 if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
469 copy_public_key (pk, keyblock->pkt->pkt.public_key);
471 rc = G10ERR_NO_PUBKEY;
473 release_kbnode (keyblock);
475 /* Not caching key here since it won't have all of the fields
483 get_pubkeyblock (u32 * keyid)
485 struct getkey_ctx_s ctx;
487 KBNODE keyblock = NULL;
489 memset (&ctx, 0, sizeof ctx);
490 /* No need to set exact here because we want the entire block. */
491 ctx.not_allocated = 1;
492 ctx.kr_handle = keydb_new ();
494 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
495 ctx.items[0].u.kid[0] = keyid[0];
496 ctx.items[0].u.kid[1] = keyid[1];
497 rc = lookup (&ctx, &keyblock, 0);
498 get_pubkey_end (&ctx);
500 return rc ? NULL : keyblock;
507 * Get a public key and store it into PK. This functions check that a
508 * corresponding secret key is available. With no secret key it does
512 get_seckey (PKT_public_key *pk, u32 *keyid)
515 struct getkey_ctx_s ctx;
516 kbnode_t keyblock = NULL;
518 memset (&ctx, 0, sizeof ctx);
519 ctx.exact = 1; /* Use the key ID exactly as given. */
520 ctx.not_allocated = 1;
521 ctx.kr_handle = keydb_new ();
523 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
524 ctx.items[0].u.kid[0] = keyid[0];
525 ctx.items[0].u.kid[1] = keyid[1];
526 ctx.req_algo = pk->req_algo;
527 ctx.req_usage = pk->req_usage;
528 err = lookup (&ctx, &keyblock, 1);
531 pk_from_block (&ctx, pk, keyblock);
533 get_pubkey_end (&ctx);
534 release_kbnode (keyblock);
537 err = agent_probe_secret_key (/*ctrl*/NULL, pk);
544 skip_unusable (void *dummy, u32 * keyid, PKT_user_id * uid)
551 keyblock = get_pubkeyblock (keyid);
554 log_error ("error checking usability status of %s\n", keystr (keyid));
558 /* Is the user ID in question revoked/expired? */
563 for (node = keyblock; node; node = node->next)
565 if (node->pkt->pkttype == PKT_USER_ID)
567 if (cmp_user_ids (uid, node->pkt->pkt.user_id) == 0
568 && (node->pkt->pkt.user_id->is_revoked
569 || node->pkt->pkt.user_id->is_expired))
579 unusable = pk_is_disabled (keyblock->pkt->pkt.public_key);
582 release_kbnode (keyblock);
587 /* Try to get the pubkey by the userid. This function looks for the
588 * first pubkey certificate which has the given name in a user_id. If
589 * PK has the pubkey algo set, the function will only return a pubkey
590 * with that algo. If NAMELIST is NULL, the first key is returned.
591 * The caller should provide storage for the PK or pass NULL if it is
592 * not needed. If RET_KB is not NULL the function stores the entire
593 * keyblock at that address. */
595 key_byname (GETKEY_CTX *retctx, strlist_t namelist,
597 int want_secret, int include_unusable,
598 KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
604 KBNODE help_kb = NULL;
608 /* Reset the returned context in case of error. */
609 assert (!ret_kdbhd); /* Not allowed because the handle is stored
618 ctx = xmalloc_clear (sizeof *ctx);
620 ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
621 if (!include_unusable)
622 ctx->items[0].skipfnc = skip_unusable;
626 /* Build the search context. */
627 for (n = 0, r = namelist; r; r = r->next)
630 ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
633 for (n = 0, r = namelist; r; r = r->next, n++)
637 err = classify_user_id (r->d, &ctx->items[n], 1);
639 if (ctx->items[n].exact)
644 return gpg_err_code (err); /* FIXME: remove gpg_err_code. */
646 if (!include_unusable
647 && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
648 && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
649 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
650 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
651 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
652 ctx->items[n].skipfnc = skip_unusable;
656 ctx->want_secret = want_secret;
657 ctx->kr_handle = keydb_new ();
663 ctx->req_algo = pk->req_algo;
664 ctx->req_usage = pk->req_usage;
667 rc = lookup (ctx, ret_kb, want_secret);
670 pk_from_block (ctx, pk, *ret_kb);
673 release_kbnode (help_kb);
675 if (retctx) /* Caller wants the context. */
681 *ret_kdbhd = ctx->kr_handle;
682 ctx->kr_handle = NULL;
684 get_pubkey_end (ctx);
692 /* Find a public key from NAME and return the keyblock or the key. If
693 ret_kdb is not NULL, the KEYDB handle used to locate this keyblock
694 is returned and the caller is responsible for closing it. If a key
695 was not found (or if local search has been disabled) and NAME is a
696 valid RFC822 mailbox and --auto-key-locate has been enabled, we try
697 to import the key via the online mechanisms defined by
698 --auto-key-locate. */
700 get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
701 const char *name, KBNODE * ret_keyblock,
702 KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
705 strlist_t namelist = NULL;
709 int anylocalfirst = 0;
714 is_mbox = is_valid_mailbox (name);
716 /* Check whether the default local search has been disabled.
717 This is the case if either the "nodefault" or the "local" keyword
718 are in the list of auto key locate mechanisms.
720 ANYLOCALFIRST is set if the search order has the local method
721 before any other or if "local" is used first by default. This
722 makes sure that if a RETCTX is used it gets only set if a local
723 search has precedence over the other search methods and only then
724 a followup call to get_pubkey_next shall succeed. */
727 for (akl = opt.auto_key_locate; akl; akl = akl->next)
728 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
733 for (akl = opt.auto_key_locate; akl; akl = akl->next)
734 if (akl->type != AKL_NODEFAULT)
736 if (akl->type == AKL_LOCAL)
745 if (nodefault && is_mbox)
747 /* Nodefault but a mailbox - let the AKL locate the key. */
748 rc = G10ERR_NO_PUBKEY;
752 add_to_strlist (&namelist, name);
753 rc = key_byname (retctx, namelist, pk, 0,
754 include_unusable, ret_keyblock, ret_kdbhd);
757 /* If the requested name resembles a valid mailbox and automatic
758 retrieval has been enabled, we try to import the key. */
759 if (gpg_err_code (rc) == G10ERR_NO_PUBKEY && !no_akl && is_mbox)
761 for (akl = opt.auto_key_locate; akl; akl = akl->next)
763 unsigned char *fpr = NULL;
765 int did_key_byname = 0;
766 int no_fingerprint = 0;
767 const char *mechanism = "?";
772 /* This is a dummy mechanism. */
774 rc = G10ERR_NO_PUBKEY;
782 get_pubkey_end (*retctx);
785 add_to_strlist (&namelist, name);
786 rc = key_byname (anylocalfirst ? retctx : NULL,
788 include_unusable, ret_keyblock, ret_kdbhd);
792 mechanism = "DNS CERT";
793 glo_ctrl.in_auto_key_retrieve++;
794 rc = keyserver_import_cert (ctrl, name, &fpr, &fpr_len);
795 glo_ctrl.in_auto_key_retrieve--;
800 glo_ctrl.in_auto_key_retrieve++;
801 rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
802 glo_ctrl.in_auto_key_retrieve--;
807 glo_ctrl.in_auto_key_retrieve++;
808 rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
809 glo_ctrl.in_auto_key_retrieve--;
813 /* Strictly speaking, we don't need to only use a valid
814 mailbox for the getname search, but it helps cut down
815 on the problem of searching for something like "john"
816 and getting a whole lot of keys back. */
819 mechanism = opt.keyserver->uri;
820 glo_ctrl.in_auto_key_retrieve++;
821 rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
823 glo_ctrl.in_auto_key_retrieve--;
827 mechanism = "Unconfigured keyserver";
828 rc = G10ERR_NO_PUBKEY;
834 struct keyserver_spec *keyserver;
836 mechanism = akl->spec->uri;
837 keyserver = keyserver_match (akl->spec);
838 glo_ctrl.in_auto_key_retrieve++;
839 rc = keyserver_import_name (ctrl,
840 name, &fpr, &fpr_len, keyserver);
841 glo_ctrl.in_auto_key_retrieve--;
846 /* Use the fingerprint of the key that we actually fetched.
847 This helps prevent problems where the key that we fetched
848 doesn't have the same name that we used to fetch it. In
849 the case of CERT and PKA, this is an actual security
850 requirement as the URL might point to a key put in by an
851 attacker. By forcing the use of the fingerprint, we
852 won't use the attacker's key here. */
855 char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
857 assert (fpr_len <= MAX_FINGERPRINT_LEN);
859 free_strlist (namelist);
862 bin2hex (fpr, fpr_len, fpr_string);
865 log_info ("auto-key-locate found fingerprint %s\n",
868 add_to_strlist (&namelist, fpr_string);
870 else if (!rc && !fpr && !did_key_byname)
873 rc = G10ERR_NO_PUBKEY;
878 if (!rc && !did_key_byname)
882 get_pubkey_end (*retctx);
885 rc = key_byname (anylocalfirst ? retctx : NULL,
887 include_unusable, ret_keyblock, ret_kdbhd);
892 log_info (_("automatically retrieved '%s' via %s\n"),
896 if (rc != G10ERR_NO_PUBKEY || opt.verbose || no_fingerprint)
897 log_info (_("error retrieving '%s' via %s: %s\n"),
899 no_fingerprint ? _("No fingerprint") : g10_errstr (rc));
906 get_pubkey_end (*retctx);
910 if (retctx && *retctx)
912 assert (!(*retctx)->extra_list);
913 (*retctx)->extra_list = namelist;
916 free_strlist (namelist);
922 get_pubkey_bynames (GETKEY_CTX * retctx, PKT_public_key * pk,
923 strlist_t names, KBNODE * ret_keyblock)
925 return key_byname (retctx, names, pk, 0, 1, ret_keyblock, NULL);
929 get_pubkey_next (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE * ret_keyblock)
931 return gpg_err_code (getkey_next (ctx, pk, ret_keyblock));
935 get_pubkey_end (GETKEY_CTX ctx)
941 /* Search for a key with the given standard fingerprint. In contrast
942 * to get_pubkey_byfprint we assume a right padded fingerprint of the
943 * standard length. PK may be NULL to only put the result into the
944 * internal caches. */
946 get_pubkey_byfpr (PKT_public_key *pk, const byte *fpr)
949 struct getkey_ctx_s ctx;
952 memset (&ctx, 0, sizeof ctx);
954 ctx.not_allocated = 1;
955 ctx.kr_handle = keydb_new ();
957 ctx.items[0].mode = KEYDB_SEARCH_MODE_FPR;
958 memcpy (ctx.items[0].u.fpr, fpr, MAX_FINGERPRINT_LEN);
959 err = lookup (&ctx, &kb, 0);
961 pk_from_block (&ctx, pk, kb);
963 get_pubkey_end (&ctx);
969 /* Search for a key with the given fingerprint.
971 * We should replace this with the _byname function. This can be done
972 * by creating a userID conforming to the unified fingerprint style.
975 get_pubkey_byfprint (PKT_public_key * pk,
976 const byte * fprint, size_t fprint_len)
980 if (fprint_len == 20 || fprint_len == 16)
982 struct getkey_ctx_s ctx;
985 memset (&ctx, 0, sizeof ctx);
987 ctx.not_allocated = 1;
988 ctx.kr_handle = keydb_new ();
990 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
991 : KEYDB_SEARCH_MODE_FPR20;
992 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
993 rc = lookup (&ctx, &kb, 0);
995 pk_from_block (&ctx, pk, kb);
997 get_pubkey_end (&ctx);
1000 rc = G10ERR_GENERAL; /* Oops */
1005 /* Get a public key and store it into the allocated pk. This function
1006 differs from get_pubkey_byfprint() in that it does not do a check
1007 of the key to avoid recursion. It should be used only in very
1008 certain cases. PK may be NULL to check just for the existance of
1011 get_pubkey_byfprint_fast (PKT_public_key * pk,
1012 const byte * fprint, size_t fprint_len)
1017 byte fprbuf[MAX_FINGERPRINT_LEN];
1020 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1021 fprbuf[i] = fprint[i];
1022 while (i < MAX_FINGERPRINT_LEN)
1026 rc = keydb_search_fpr (hd, fprbuf);
1027 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1030 return G10ERR_NO_PUBKEY;
1032 rc = keydb_get_keyblock (hd, &keyblock);
1036 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr (rc));
1037 return G10ERR_NO_PUBKEY;
1040 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1041 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1043 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1044 release_kbnode (keyblock);
1046 /* Not caching key here since it won't have all of the fields
1053 /* Search for a key with the given fingerprint and return the
1054 * complete keyblock which may have more than only this key. */
1056 get_keyblock_byfprint (KBNODE * ret_keyblock, const byte * fprint,
1061 if (fprint_len == 20 || fprint_len == 16)
1063 struct getkey_ctx_s ctx;
1065 memset (&ctx, 0, sizeof ctx);
1066 ctx.not_allocated = 1;
1067 ctx.kr_handle = keydb_new ();
1069 ctx.items[0].mode = (fprint_len == 16
1070 ? KEYDB_SEARCH_MODE_FPR16
1071 : KEYDB_SEARCH_MODE_FPR20);
1072 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1073 rc = lookup (&ctx, ret_keyblock, 0);
1074 get_pubkey_end (&ctx);
1077 rc = G10ERR_GENERAL; /* Oops */
1083 /* Get a secret key by NAME and store it into PK. If NAME is NULL use
1084 * the default key. This functions checks that a corresponding secret
1085 * key is available. With no secret key it does not succeeed. */
1087 get_seckey_byname (PKT_public_key *pk, const char *name)
1090 strlist_t namelist = NULL;
1091 int include_unusable = 1;
1093 /* If we have no name, try to use the default secret key. If we
1094 have no default, we'll use the first usable one. */
1096 if (!name && opt.def_secret_key && *opt.def_secret_key)
1097 add_to_strlist (&namelist, opt.def_secret_key);
1099 add_to_strlist (&namelist, name);
1101 include_unusable = 0;
1103 err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
1105 free_strlist (namelist);
1112 /* Search for a key with the given fingerprint.
1114 * We should replace this with the _byname function. This can be done
1115 * by creating a userID conforming to the unified fingerprint style. */
1117 get_seckey_byfprint (PKT_public_key *pk, const byte * fprint, size_t fprint_len)
1121 if (fprint_len == 20 || fprint_len == 16)
1123 struct getkey_ctx_s ctx;
1126 memset (&ctx, 0, sizeof ctx);
1128 ctx.not_allocated = 1;
1129 ctx.kr_handle = keydb_new ();
1131 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1132 : KEYDB_SEARCH_MODE_FPR20;
1133 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1134 err = lookup (&ctx, &kb, 1);
1136 pk_from_block (&ctx, pk, kb);
1137 release_kbnode (kb);
1138 get_pubkey_end (&ctx);
1141 err = gpg_error (GPG_ERR_BUG);
1146 /* Search for a secret key with the given fingerprint and return the
1147 complete keyblock which may have more than only this key. Return
1148 an error if no corresponding secret key is available. */
1150 get_seckeyblock_byfprint (kbnode_t *ret_keyblock,
1151 const byte *fprint, size_t fprint_len)
1154 struct getkey_ctx_s ctx;
1156 if (fprint_len != 20 && fprint_len == 16)
1157 return gpg_error (GPG_ERR_BUG);
1159 memset (&ctx, 0, sizeof ctx);
1160 ctx.not_allocated = 1;
1161 ctx.kr_handle = keydb_new ();
1163 ctx.items[0].mode = (fprint_len == 16
1164 ? KEYDB_SEARCH_MODE_FPR16 : KEYDB_SEARCH_MODE_FPR20);
1165 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1166 err = lookup (&ctx, ret_keyblock, 1);
1167 get_pubkey_end (&ctx);
1174 /* The new function to return a key.
1175 FIXME: Document it. */
1177 getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
1178 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
1180 return key_byname (retctx, names, pk, want_secret, 1,
1181 ret_keyblock, NULL);
1185 /* Get a key by name and store it into PK if that is not NULL. If
1186 * RETCTX is not NULL return the search context which needs to be
1187 * released by the caller using getkey_end. If NAME is NULL use the
1188 * default key (see below). On success and if RET_KEYBLOCK is not
1189 * NULL the found keyblock is stored at this address. WANT_SECRET
1190 * passed as true requires that a secret key is available for the
1193 * If WANT_SECRET is true and NAME is NULL and a default key has been
1194 * defined that defined key is used. In all other cases the first
1195 * available key is used.
1197 * FIXME: Explain what is up with unusable keys.
1199 * FIXME: We also have the get_pubkey_byname function which has a
1200 * different semantic. Should be merged with this one.
1203 getkey_byname (getkey_ctx_t *retctx, PKT_public_key *pk,
1204 const char *name, int want_secret, kbnode_t *ret_keyblock)
1207 strlist_t namelist = NULL;
1208 int with_unusable = 1;
1210 if (want_secret && !name && opt.def_secret_key && *opt.def_secret_key)
1211 add_to_strlist (&namelist, opt.def_secret_key);
1213 add_to_strlist (&namelist, name);
1217 err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
1218 ret_keyblock, NULL);
1220 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
1221 WANT_SECRET has been used. */
1223 free_strlist (namelist);
1229 /* The new function to return the next key. */
1231 getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
1233 int rc; /* Fixme: Make sure this is proper gpg_error */
1235 /* We need to disable the caching so that for an exact key search we
1236 won't get the result back from the cache and thus end up in an
1237 endless loop. Disabling this here is sufficient because although
1238 the result has been cached, if won't be used then. */
1239 keydb_disable_caching (ctx->kr_handle);
1241 rc = lookup (ctx, ret_keyblock, ctx->want_secret);
1242 if (!rc && pk && ret_keyblock)
1243 pk_from_block (ctx, pk, *ret_keyblock);
1249 /* The new function to finish a key listing. */
1251 getkey_end (getkey_ctx_t ctx)
1255 memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
1256 keydb_release (ctx->kr_handle);
1257 free_strlist (ctx->extra_list);
1258 if (!ctx->not_allocated)
1265 /************************************************
1266 ************* Merging stuff ********************
1267 ************************************************/
1269 /* Set the mainkey_id fields for all keys in KEYBLOCK. This is
1270 usually done by merge_selfsigs but at some places we only need the
1271 main_kid but the the full merging. The function also guarantees
1272 that all pk->keyids are computed. */
1274 setup_main_keyids (kbnode_t keyblock)
1276 u32 kid[2], mainkid[2];
1277 kbnode_t kbctx, node;
1280 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1282 pk = keyblock->pkt->pkt.public_key;
1284 keyid_from_pk (pk, mainkid);
1285 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1287 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
1288 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1290 pk = node->pkt->pkt.public_key;
1291 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
1292 if (!pk->main_keyid[0] && !pk->main_keyid[1])
1294 pk->main_keyid[0] = mainkid[0];
1295 pk->main_keyid[1] = mainkid[1];
1301 /* Merge all self-signatures with the keys. */
1303 merge_keys_and_selfsig (KBNODE keyblock)
1307 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
1308 merge_selfsigs (keyblock);
1310 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
1315 parse_key_usage (PKT_signature * sig)
1322 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
1325 /* First octet of the keyflags. */
1330 key_usage |= PUBKEY_USAGE_CERT;
1336 key_usage |= PUBKEY_USAGE_SIG;
1340 /* We do not distinguish between encrypting communications and
1341 encrypting storage. */
1342 if (flags & (0x04 | 0x08))
1344 key_usage |= PUBKEY_USAGE_ENC;
1345 flags &= ~(0x04 | 0x08);
1350 key_usage |= PUBKEY_USAGE_AUTH;
1355 key_usage |= PUBKEY_USAGE_UNKNOWN;
1358 key_usage |= PUBKEY_USAGE_NONE;
1360 else if (p) /* Key flags of length zero. */
1361 key_usage |= PUBKEY_USAGE_NONE;
1363 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1364 capability that we do not handle. This serves to distinguish
1365 between a zero key usage which we handle as the default
1366 capabilities for that algorithm, and a usage that we do not
1367 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
1368 key_flags have been given but they do not specify any usage. */
1374 /* Apply information from SIGNODE (which is the valid self-signature
1375 * associated with that UID) to the UIDNODE:
1376 * - wether the UID has been revoked
1377 * - assumed creation date of the UID
1378 * - temporary store the keyflags here
1379 * - temporary store the key expiration time here
1380 * - mark whether the primary user ID flag hat been set.
1381 * - store the preferences
1384 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
1386 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1387 PKT_signature *sig = signode->pkt->pkt.signature;
1388 const byte *p, *sym, *hash, *zip;
1389 size_t n, nsym, nhash, nzip;
1391 sig->flags.chosen_selfsig = 1;/* We chose this one. */
1392 uid->created = 0; /* Not created == invalid. */
1393 if (IS_UID_REV (sig))
1395 uid->is_revoked = 1;
1396 return; /* Has been revoked. */
1399 uid->is_revoked = 0;
1401 uid->expiredate = sig->expiredate;
1403 if (sig->flags.expired)
1405 uid->is_expired = 1;
1406 return; /* Has expired. */
1409 uid->is_expired = 0;
1411 uid->created = sig->timestamp; /* This one is okay. */
1412 uid->selfsigversion = sig->version;
1413 /* If we got this far, it's not expired :) */
1414 uid->is_expired = 0;
1416 /* Store the key flags in the helper variable for later processing. */
1417 uid->help_key_usage = parse_key_usage (sig);
1419 /* Ditto for the key expiration. */
1420 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1421 if (p && buffer_to_u32 (p))
1422 uid->help_key_expire = keycreated + buffer_to_u32 (p);
1424 uid->help_key_expire = 0;
1426 /* Set the primary user ID flag - we will later wipe out some
1427 * of them to only have one in our keyblock. */
1428 uid->is_primary = 0;
1429 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
1431 uid->is_primary = 2;
1433 /* We could also query this from the unhashed area if it is not in
1434 * the hased area and then later try to decide which is the better
1435 * there should be no security problem with this.
1436 * For now we only look at the hashed one. */
1438 /* Now build the preferences list. These must come from the
1439 hashed section so nobody can modify the ciphers a key is
1440 willing to accept. */
1441 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
1444 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
1447 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
1452 n = nsym + nhash + nzip;
1457 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
1459 for (; nsym; nsym--, n++)
1461 uid->prefs[n].type = PREFTYPE_SYM;
1462 uid->prefs[n].value = *sym++;
1464 for (; nhash; nhash--, n++)
1466 uid->prefs[n].type = PREFTYPE_HASH;
1467 uid->prefs[n].value = *hash++;
1469 for (; nzip; nzip--, n++)
1471 uid->prefs[n].type = PREFTYPE_ZIP;
1472 uid->prefs[n].value = *zip++;
1474 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
1475 uid->prefs[n].value = 0;
1478 /* See whether we have the MDC feature. */
1480 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1481 if (p && n && (p[0] & 0x01))
1484 /* And the keyserver modify flag. */
1485 uid->flags.ks_modify = 1;
1486 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1487 if (p && n && (p[0] & 0x80))
1488 uid->flags.ks_modify = 0;
1492 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
1494 rinfo->date = sig->timestamp;
1495 rinfo->algo = sig->pubkey_algo;
1496 rinfo->keyid[0] = sig->keyid[0];
1497 rinfo->keyid[1] = sig->keyid[1];
1501 /* Note that R_REVOKED may be set to 0, 1 or 2. */
1503 merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
1504 struct revoke_info *rinfo)
1506 PKT_public_key *pk = NULL;
1509 u32 sigdate, uiddate, uiddate2;
1510 KBNODE signode, uidnode, uidnode2;
1511 u32 curtime = make_timestamp ();
1512 unsigned int key_usage = 0;
1513 u32 keytimestamp = 0;
1515 int key_expire_seen = 0;
1516 byte sigversion = 0;
1519 memset (rinfo, 0, sizeof (*rinfo));
1521 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1523 pk = keyblock->pkt->pkt.public_key;
1524 keytimestamp = pk->timestamp;
1526 keyid_from_pk (pk, kid);
1527 pk->main_keyid[0] = kid[0];
1528 pk->main_keyid[1] = kid[1];
1530 if (pk->version < 4)
1532 /* Before v4 the key packet itself contains the expiration date
1533 * and there was no way to change it, so we start with the one
1534 * from the key packet. */
1535 key_expire = pk->max_expiredate;
1536 key_expire_seen = 1;
1539 /* First pass: Find the latest direct key self-signature. We assume
1540 * that the newest one overrides all others. */
1542 /* In case this key was already merged. */
1548 sigdate = 0; /* Helper variable to find the latest signature. */
1549 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
1551 if (k->pkt->pkttype == PKT_SIGNATURE)
1553 PKT_signature *sig = k->pkt->pkt.signature;
1554 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1556 if (check_key_signature (keyblock, k, NULL))
1557 ; /* Signature did not verify. */
1558 else if (IS_KEY_REV (sig))
1560 /* Key has been revoked - there is no way to
1561 * override such a revocation, so we theoretically
1562 * can stop now. We should not cope with expiration
1563 * times for revocations here because we have to
1564 * assume that an attacker can generate all kinds of
1565 * signatures. However due to the fact that the key
1566 * has been revoked it does not harm either and by
1567 * continuing we gather some more info on that
1570 sig_to_revoke_info (sig, rinfo);
1572 else if (IS_KEY_SIG (sig))
1574 /* Add any revocation keys onto the pk. This is
1575 particularly interesting since we normally only
1576 get data from the most recent 1F signature, but
1577 you need multiple 1F sigs to properly handle
1578 revocation keys (PGP does it this way, and a
1579 revocation key could be sensitive and hence in a
1580 different signature). */
1586 xrealloc (pk->revkey, sizeof (struct revocation_key) *
1587 (pk->numrevkeys + sig->numrevkeys));
1589 for (i = 0; i < sig->numrevkeys; i++)
1590 memcpy (&pk->revkey[pk->numrevkeys++],
1592 sizeof (struct revocation_key));
1595 if (sig->timestamp >= sigdate)
1597 if (sig->flags.expired)
1598 ; /* Signature has expired - ignore it. */
1601 sigdate = sig->timestamp;
1603 if (sig->version > sigversion)
1604 sigversion = sig->version;
1613 /* Remove dupes from the revocation keys. */
1617 int i, j, x, changed = 0;
1619 for (i = 0; i < pk->numrevkeys; i++)
1621 for (j = i + 1; j < pk->numrevkeys; j++)
1623 if (memcmp (&pk->revkey[i], &pk->revkey[j],
1624 sizeof (struct revocation_key)) == 0)
1628 for (x = j; x < pk->numrevkeys - 1; x++)
1629 pk->revkey[x] = pk->revkey[x + 1];
1639 pk->revkey = xrealloc (pk->revkey,
1641 sizeof (struct revocation_key));
1646 /* Some information from a direct key signature take precedence
1647 * over the same information given in UID sigs. */
1648 PKT_signature *sig = signode->pkt->pkt.signature;
1651 key_usage = parse_key_usage (sig);
1653 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1654 if (p && buffer_to_u32 (p))
1656 key_expire = keytimestamp + buffer_to_u32 (p);
1657 key_expire_seen = 1;
1660 /* Mark that key as valid: One direct key signature should
1661 * render a key as valid. */
1662 pk->flags.valid = 1;
1665 /* Pass 1.5: Look for key revocation signatures that were not made
1666 by the key (i.e. did a revocation key issue a revocation for
1667 us?). Only bother to do this if there is a revocation key in the
1668 first place and we're not revoked already. */
1670 if (!*r_revoked && pk->revkey)
1671 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
1673 if (k->pkt->pkttype == PKT_SIGNATURE)
1675 PKT_signature *sig = k->pkt->pkt.signature;
1677 if (IS_KEY_REV (sig) &&
1678 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
1680 int rc = check_revocation_keys (pk, sig);
1684 sig_to_revoke_info (sig, rinfo);
1685 /* Don't continue checking since we can't be any
1686 more revoked than this. */
1689 else if (rc == G10ERR_NO_PUBKEY)
1690 pk->flags.maybe_revoked = 1;
1692 /* A failure here means the sig did not verify, was
1693 not issued by a revocation key, or a revocation
1694 key loop was broken. If a revocation key isn't
1695 findable, however, the key might be revoked and
1696 we don't know it. */
1698 /* TODO: In the future handle subkey and cert
1699 revocations? PGP doesn't, but it's in 2440. */
1704 /* Second pass: Look at the self-signature of all user IDs. */
1705 signode = uidnode = NULL;
1706 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
1707 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1709 if (k->pkt->pkttype == PKT_USER_ID)
1711 if (uidnode && signode)
1713 fixup_uidnode (uidnode, signode, keytimestamp);
1714 pk->flags.valid = 1;
1720 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1722 PKT_signature *sig = k->pkt->pkt.signature;
1723 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1725 if (check_key_signature (keyblock, k, NULL))
1726 ; /* signature did not verify */
1727 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
1728 && sig->timestamp >= sigdate)
1730 /* Note: we allow to invalidate cert revocations
1731 * by a newer signature. An attacker can't use this
1732 * because a key should be revoced with a key revocation.
1733 * The reason why we have to allow for that is that at
1734 * one time an email address may become invalid but later
1735 * the same email address may become valid again (hired,
1736 * fired, hired again). */
1738 sigdate = sig->timestamp;
1740 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
1741 if (sig->version > sigversion)
1742 sigversion = sig->version;
1747 if (uidnode && signode)
1749 fixup_uidnode (uidnode, signode, keytimestamp);
1750 pk->flags.valid = 1;
1753 /* If the key isn't valid yet, and we have
1754 --allow-non-selfsigned-uid set, then force it valid. */
1755 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
1758 log_info (_("Invalid key %s made valid by"
1759 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
1760 pk->flags.valid = 1;
1763 /* The key STILL isn't valid, so try and find an ultimately
1764 trusted signature. */
1765 if (!pk->flags.valid)
1769 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1772 if (k->pkt->pkttype == PKT_USER_ID)
1774 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1776 PKT_signature *sig = k->pkt->pkt.signature;
1778 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
1780 PKT_public_key *ultimate_pk;
1782 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
1784 /* We don't want to use the full get_pubkey to
1785 avoid infinite recursion in certain cases.
1786 There is no reason to check that an ultimately
1787 trusted key is still valid - if it has been
1788 revoked or the user should also renmove the
1789 ultimate trust flag. */
1790 if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
1791 && check_key_signature2 (keyblock, k, ultimate_pk,
1792 NULL, NULL, NULL, NULL) == 0
1793 && get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
1795 free_public_key (ultimate_pk);
1796 pk->flags.valid = 1;
1800 free_public_key (ultimate_pk);
1806 /* Record the highest selfsig version so we know if this is a v3
1807 key through and through, or a v3 key with a v4 selfsig
1808 somewhere. This is useful in a few places to know if the key
1809 must be treated as PGP2-style or OpenPGP-style. Note that a
1810 selfsig revocation with a higher version number will also raise
1811 this value. This is okay since such a revocation must be
1812 issued by the user (i.e. it cannot be issued by someone else to
1813 modify the key behavior.) */
1815 pk->selfsigversion = sigversion;
1817 /* Now that we had a look at all user IDs we can now get some information
1818 * from those user IDs.
1823 /* Find the latest user ID with key flags set. */
1824 uiddate = 0; /* Helper to find the latest user ID. */
1825 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1828 if (k->pkt->pkttype == PKT_USER_ID)
1830 PKT_user_id *uid = k->pkt->pkt.user_id;
1831 if (uid->help_key_usage && uid->created > uiddate)
1833 key_usage = uid->help_key_usage;
1834 uiddate = uid->created;
1841 /* No key flags at all: get it from the algo. */
1842 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
1846 /* Check that the usage matches the usage as given by the algo. */
1847 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
1848 if (x) /* Mask it down to the actual allowed usage. */
1852 /* Whatever happens, it's a primary key, so it can certify. */
1853 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
1855 if (!key_expire_seen)
1857 /* Find the latest valid user ID with a key expiration set
1858 * Note, that this may be a different one from the above because
1859 * some user IDs may have no expiration date set. */
1861 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1864 if (k->pkt->pkttype == PKT_USER_ID)
1866 PKT_user_id *uid = k->pkt->pkt.user_id;
1867 if (uid->help_key_expire && uid->created > uiddate)
1869 key_expire = uid->help_key_expire;
1870 uiddate = uid->created;
1876 /* Currently only v3 keys have a maximum expiration date, but I'll
1877 bet v5 keys get this feature again. */
1879 || (pk->max_expiredate && key_expire > pk->max_expiredate))
1880 key_expire = pk->max_expiredate;
1882 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
1883 pk->expiredate = key_expire;
1885 /* Fixme: we should see how to get rid of the expiretime fields but
1886 * this needs changes at other places too. */
1888 /* And now find the real primary user ID and delete all others. */
1889 uiddate = uiddate2 = 0;
1890 uidnode = uidnode2 = NULL;
1891 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1893 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
1895 PKT_user_id *uid = k->pkt->pkt.user_id;
1896 if (uid->is_primary)
1898 if (uid->created > uiddate)
1900 uiddate = uid->created;
1903 else if (uid->created == uiddate && uidnode)
1905 /* The dates are equal, so we need to do a
1906 different (and arbitrary) comparison. This
1907 should rarely, if ever, happen. It's good to
1908 try and guarantee that two different GnuPG
1909 users with two different keyrings at least pick
1910 the same primary. */
1911 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
1917 if (uid->created > uiddate2)
1919 uiddate2 = uid->created;
1922 else if (uid->created == uiddate2 && uidnode2)
1924 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
1932 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1935 if (k->pkt->pkttype == PKT_USER_ID &&
1936 !k->pkt->pkt.user_id->attrib_data)
1938 PKT_user_id *uid = k->pkt->pkt.user_id;
1940 uid->is_primary = 0;
1946 /* None is flagged primary - use the latest user ID we have,
1947 and disambiguate with the arbitrary packet comparison. */
1948 uidnode2->pkt->pkt.user_id->is_primary = 1;
1952 /* None of our uids were self-signed, so pick the one that
1953 sorts first to be the primary. This is the best we can do
1954 here since there are no self sigs to date the uids. */
1958 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1961 if (k->pkt->pkttype == PKT_USER_ID
1962 && !k->pkt->pkt.user_id->attrib_data)
1967 uidnode->pkt->pkt.user_id->is_primary = 1;
1972 if (cmp_user_ids (k->pkt->pkt.user_id,
1973 uidnode->pkt->pkt.user_id) > 0)
1975 uidnode->pkt->pkt.user_id->is_primary = 0;
1977 uidnode->pkt->pkt.user_id->is_primary = 1;
1980 k->pkt->pkt.user_id->is_primary = 0; /* just to be
1988 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
1989 Caller must free the signature when they are done. */
1990 static PKT_signature *
1991 buf_to_sig (const byte * buf, size_t len)
1993 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
1994 IOBUF iobuf = iobuf_temp_with_content (buf, len);
1995 int save_mode = set_packet_list_mode (0);
1997 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
2003 set_packet_list_mode (save_mode);
2004 iobuf_close (iobuf);
2010 merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
2012 PKT_public_key *mainpk = NULL, *subpk = NULL;
2018 u32 curtime = make_timestamp ();
2019 unsigned int key_usage = 0;
2020 u32 keytimestamp = 0;
2024 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2026 mainpk = keyblock->pkt->pkt.public_key;
2027 if (mainpk->version < 4)
2028 return;/* (actually this should never happen) */
2029 keyid_from_pk (mainpk, mainkid);
2030 subpk = subnode->pkt->pkt.public_key;
2031 keytimestamp = subpk->timestamp;
2033 subpk->flags.valid = 0;
2034 subpk->main_keyid[0] = mainpk->main_keyid[0];
2035 subpk->main_keyid[1] = mainpk->main_keyid[1];
2037 /* Find the latest key binding self-signature. */
2039 sigdate = 0; /* Helper to find the latest signature. */
2040 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2043 if (k->pkt->pkttype == PKT_SIGNATURE)
2045 sig = k->pkt->pkt.signature;
2046 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
2048 if (check_key_signature (keyblock, k, NULL))
2049 ; /* Signature did not verify. */
2050 else if (IS_SUBKEY_REV (sig))
2052 /* Note that this means that the date on a
2053 revocation sig does not matter - even if the
2054 binding sig is dated after the revocation sig,
2055 the subkey is still marked as revoked. This
2056 seems ok, as it is just as easy to make new
2057 subkeys rather than re-sign old ones as the
2058 problem is in the distribution. Plus, PGP (7)
2059 does this the same way. */
2060 subpk->flags.revoked = 1;
2061 sig_to_revoke_info (sig, &subpk->revoked);
2062 /* Although we could stop now, we continue to
2063 * figure out other information like the old expiration
2066 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
2068 if (sig->flags.expired)
2069 ; /* Signature has expired - ignore it. */
2072 sigdate = sig->timestamp;
2074 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2081 /* No valid key binding. */
2085 sig = signode->pkt->pkt.signature;
2086 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
2088 key_usage = parse_key_usage (sig);
2091 /* No key flags at all: get it from the algo. */
2092 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
2096 /* Check that the usage matches the usage as given by the algo. */
2097 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
2098 if (x) /* Mask it down to the actual allowed usage. */
2102 subpk->pubkey_usage = key_usage;
2104 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2105 if (p && buffer_to_u32 (p))
2106 key_expire = keytimestamp + buffer_to_u32 (p);
2109 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
2110 subpk->expiredate = key_expire;
2112 /* Algo doesn't exist. */
2113 if (openpgp_pk_test_algo (subpk->pubkey_algo))
2116 subpk->flags.valid = 1;
2118 /* Find the most recent 0x19 embedded signature on our self-sig. */
2119 if (!subpk->flags.backsig)
2123 PKT_signature *backsig = NULL;
2127 /* We do this while() since there may be other embedded
2128 signatures in the future. We only want 0x19 here. */
2130 while ((p = enum_sig_subpkt (sig->hashed,
2131 SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
2133 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2135 PKT_signature *tempsig = buf_to_sig (p, n);
2138 if (tempsig->timestamp > sigdate)
2141 free_seckey_enc (backsig);
2144 sigdate = backsig->timestamp;
2147 free_seckey_enc (tempsig);
2153 /* It is safe to have this in the unhashed area since the 0x19
2154 is located on the selfsig for convenience, not security. */
2156 while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
2159 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2161 PKT_signature *tempsig = buf_to_sig (p, n);
2164 if (tempsig->timestamp > sigdate)
2167 free_seckey_enc (backsig);
2170 sigdate = backsig->timestamp;
2173 free_seckey_enc (tempsig);
2179 /* At ths point, backsig contains the most recent 0x19 sig.
2180 Let's see if it is good. */
2182 /* 2==valid, 1==invalid, 0==didn't check */
2183 if (check_backsig (mainpk, subpk, backsig) == 0)
2184 subpk->flags.backsig = 2;
2186 subpk->flags.backsig = 1;
2188 free_seckey_enc (backsig);
2195 * Merge information from the self-signatures with the key, so that
2196 * we can later use them more easy.
2197 * The function works by first applying the self signatures to the
2198 * primary key and the to each subkey.
2199 * Here are the rules we use to decide which inormation from which
2200 * self-signature is used:
2201 * We check all self signatures or validity and ignore all invalid signatures.
2202 * All signatures are then ordered by their creation date ....
2203 * For the primary key:
2207 merge_selfsigs (KBNODE keyblock)
2211 struct revoke_info rinfo;
2212 PKT_public_key *main_pk;
2214 unsigned int mdc_feature;
2216 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2218 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
2220 log_error ("expected public key but found secret key "
2222 /* We better exit here because a public key is expected at
2223 other places too. FIXME: Figure this out earlier and
2224 don't get to here at all */
2230 merge_selfsigs_main (keyblock, &revoked, &rinfo);
2232 /* Now merge in the data from each of the subkeys. */
2233 for (k = keyblock; k; k = k->next)
2235 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2237 merge_selfsigs_subkey (keyblock, k);
2241 main_pk = keyblock->pkt->pkt.public_key;
2242 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
2244 /* If the primary key is revoked, expired, or invalid we
2245 * better set the appropriate flags on that key and all
2247 for (k = keyblock; k; k = k->next)
2249 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2250 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2252 PKT_public_key *pk = k->pkt->pkt.public_key;
2253 if (!main_pk->flags.valid)
2254 pk->flags.valid = 0;
2255 if (revoked && !pk->flags.revoked)
2257 pk->flags.revoked = revoked;
2258 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
2260 if (main_pk->has_expired)
2261 pk->has_expired = main_pk->has_expired;
2267 /* Set the preference list of all keys to those of the primary real
2268 * user ID. Note: we use these preferences when we don't know by
2269 * which user ID the key has been selected.
2270 * fixme: we should keep atoms of commonly used preferences or
2271 * use reference counting to optimize the preference lists storage.
2272 * FIXME: it might be better to use the intersection of
2274 * Do a similar thing for the MDC feature flag. */
2277 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2279 if (k->pkt->pkttype == PKT_USER_ID
2280 && !k->pkt->pkt.user_id->attrib_data
2281 && k->pkt->pkt.user_id->is_primary)
2283 prefs = k->pkt->pkt.user_id->prefs;
2284 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2288 for (k = keyblock; k; k = k->next)
2290 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2291 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2293 PKT_public_key *pk = k->pkt->pkt.public_key;
2296 pk->prefs = copy_prefs (prefs);
2297 pk->flags.mdc = mdc_feature;
2304 /* See whether the key fits our requirements and in case we do not
2305 * request the primary key, select a suitable subkey.
2307 * Returns: True when a suitable key has been found.
2309 * We have to distinguish four cases: FIXME!
2310 * 1. No usage and no primary key requested
2311 * Examples for this case are that we have a keyID to be used
2312 * for decrytion or verification.
2313 * 2. No usage but primary key requested
2314 * This is the case for all functions which work on an
2315 * entire keyblock, e.g. for editing or listing
2316 * 3. Usage and primary key requested
2318 * 4. Usage but no primary key requested
2320 * FIXME: Tell what is going to happen here and something about the rationale
2321 * Note: We don't use this function if no specific usage is requested;
2322 * This way the getkey functions can be used for plain key listings.
2324 * CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
2325 * is the key we actually found by looking at the keyid or a fingerprint and
2326 * may either point to the primary or one of the subkeys. */
2328 finish_lookup (GETKEY_CTX ctx)
2330 KBNODE keyblock = ctx->keyblock;
2332 KBNODE foundk = NULL;
2333 PKT_user_id *foundu = NULL;
2334 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2335 unsigned int req_usage = (ctx->req_usage & USAGE_MASK);
2336 /* Request the primary if we're certifying another key, and also
2337 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2338 do not understand signatures made by a signing subkey. PGP 8
2340 int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2341 ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2344 u32 curtime = make_timestamp ();
2346 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
2348 ctx->found_key = NULL;
2352 for (k = keyblock; k; k = k->next)
2356 assert (k->pkt->pkttype == PKT_PUBLIC_KEY
2357 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
2364 for (k = keyblock; k; k = k->next)
2368 assert (k->pkt->pkttype == PKT_USER_ID);
2369 foundu = k->pkt->pkt.user_id;
2375 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2376 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
2377 foundk ? "one" : "all", req_usage);
2381 latest_key = foundk ? foundk : keyblock;
2387 /* Do not look at subkeys if a certification key is requested. */
2388 if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim)
2391 /* Either start a loop or check just this one subkey. */
2392 for (k = foundk ? foundk : keyblock; k; k = nextk)
2396 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2399 nextk = NULL; /* what a hack */
2400 pk = k->pkt->pkt.public_key;
2402 log_debug ("\tchecking subkey %08lX\n",
2403 (ulong) keyid_from_pk (pk, NULL));
2404 if (!pk->flags.valid)
2407 log_debug ("\tsubkey not valid\n");
2410 if (pk->flags.revoked)
2413 log_debug ("\tsubkey has been revoked\n");
2416 if (pk->has_expired)
2419 log_debug ("\tsubkey has expired\n");
2422 if (pk->timestamp > curtime && !opt.ignore_valid_from)
2425 log_debug ("\tsubkey not yet valid\n");
2429 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2432 log_debug ("\tusage does not match: want=%x have=%x\n",
2433 req_usage, pk->pubkey_usage);
2438 log_debug ("\tsubkey might be fine\n");
2439 /* In case a key has a timestamp of 0 set, we make sure
2440 that it is used. A better change would be to compare
2441 ">=" but that might also change the selected keys and
2442 is as such a more intrusive change. */
2443 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2445 latest_date = pk->timestamp;
2451 /* Okay now try the primary key unless we want an exact
2452 * key ID match on a subkey */
2453 if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim)
2456 if (DBG_CACHE && !foundk && !req_prim)
2457 log_debug ("\tno suitable subkeys found - trying primary\n");
2458 pk = keyblock->pkt->pkt.public_key;
2459 if (!pk->flags.valid)
2462 log_debug ("\tprimary key not valid\n");
2464 else if (pk->flags.revoked)
2467 log_debug ("\tprimary key has been revoked\n");
2469 else if (pk->has_expired)
2472 log_debug ("\tprimary key has expired\n");
2474 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2477 log_debug ("\tprimary key usage does not match: "
2478 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
2483 log_debug ("\tprimary key may be used\n");
2484 latest_key = keyblock;
2485 latest_date = pk->timestamp;
2492 log_debug ("\tno suitable key found - giving up\n");
2493 return 0; /* Not found. */
2498 log_debug ("\tusing key %08lX\n",
2499 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
2503 PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2505 free_user_id (pk->user_id);
2506 pk->user_id = scopy_user_id (foundu);
2509 ctx->found_key = latest_key;
2511 if (latest_key != keyblock && opt.verbose)
2514 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
2515 log_info (_("using subkey %s instead of primary key %s\n"),
2516 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
2520 cache_user_id (keyblock);
2522 return 1; /* Found. */
2526 /* The main function to lookup a key. On success the found keyblock
2527 is stored at RET_KEYBLOCK and also in CTX. If WANT_SECRET is true
2528 a corresponding secret key is required. */
2530 lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, int want_secret)
2533 int no_suitable_key = 0;
2536 while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL)))
2538 /* If we are searching for the first key we have to make sure
2539 that the next iteration does not do an implicit reset.
2540 This can be triggered by an empty key ring. */
2541 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2542 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2544 rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
2547 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr (rc));
2552 if (want_secret && agent_probe_any_secret_key (NULL, ctx->keyblock))
2553 goto skip; /* No secret key available. */
2555 /* Warning: node flag bits 0 and 1 should be preserved by
2556 * merge_selfsigs. For secret keys, premerge did tranfer the
2557 * keys to the keyblock. */
2558 merge_selfsigs (ctx->keyblock);
2559 if (finish_lookup (ctx))
2561 no_suitable_key = 0;
2565 no_suitable_key = 1;
2568 /* Release resources and continue search. */
2569 release_kbnode (ctx->keyblock);
2570 ctx->keyblock = NULL;
2574 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
2575 log_error ("keydb_search failed: %s\n", g10_errstr (rc));
2579 *ret_keyblock = ctx->keyblock; /* Return the keyblock. */
2580 ctx->keyblock = NULL;
2582 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
2583 rc = want_secret? G10ERR_UNU_SECKEY : G10ERR_UNU_PUBKEY;
2584 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2585 rc = want_secret? G10ERR_NO_SECKEY : G10ERR_NO_PUBKEY;
2587 release_kbnode (ctx->keyblock);
2588 ctx->keyblock = NULL;
2598 * Enumerate certain secret keys. Caller must use these procedure:
2599 * 1) create a void pointer and initialize it to NULL
2600 * 2) pass this void pointer by reference to this function
2601 * and provide space for the secret key (pass a buffer for sk)
2602 * 3) call this function as long as it does not return an error.
2603 * The error code GPG_ERR_EOF indicates the end of the listing.
2604 * 4) Always call this function a last time with SK set to NULL,
2605 * so that can free it's context.
2608 enum_secret_keys (void **context, PKT_public_key *sk)
2610 gpg_error_t err = 0;
2623 /* Make a new context. */
2624 c = xtrycalloc (1, sizeof *c);
2626 return gpg_error_from_syserror ();
2632 /* Free the context. */
2633 release_kbnode (c->keyblock);
2640 return gpg_error (GPG_ERR_EOF);
2644 /* Loop until we have a keyblock. */
2645 while (!c->keyblock)
2647 /* Loop over the list of secret keys. */
2653 case 0: /* First try to use the --default-key. */
2654 if (opt.def_secret_key && *opt.def_secret_key)
2655 name = opt.def_secret_key;
2659 case 1: /* Init list of keys to try. */
2660 c->sl = opt.secret_keys_to_try;
2664 case 2: /* Get next item from list. */
2668 c->sl = c->sl->next;
2674 default: /* No more names to check - stop. */
2676 return gpg_error (GPG_ERR_EOF);
2679 while (!name || !*name);
2681 err = getkey_byname (NULL, NULL, name, 1, &c->keyblock);
2684 /* getkey_byname might return a keyblock even in the
2685 error case - I have not checked. Thus better release
2687 release_kbnode (c->keyblock);
2691 c->node = c->keyblock;
2694 /* Get the next key from the current keyblock. */
2695 for (; c->node; c->node = c->node->next)
2697 if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
2698 || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2700 copy_public_key (sk, c->node->pkt->pkt.public_key);
2701 c->node = c->node->next;
2702 return 0; /* Found. */
2706 /* Dispose the keyblock and continue. */
2707 release_kbnode (c->keyblock);
2713 /*********************************************
2714 *********** User ID printing helpers *******
2715 *********************************************/
2717 /* Return a string with a printable representation of the user_id.
2718 * this string must be freed by xfree. */
2720 get_user_id_string (u32 * keyid)
2724 /* Try it two times; second pass reads from key resources. */
2727 for (r = user_id_db; r; r = r->next)
2730 for (a = r->keyids; a; a = a->next)
2732 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
2734 return xasprintf ("%s %.*s", keystr (keyid), r->len, r->name);
2739 while (++pass < 2 && !get_pubkey (NULL, keyid));
2740 return xasprintf ("%s [?]", keystr (keyid));
2745 get_user_id_string_native (u32 * keyid)
2747 char *p = get_user_id_string (keyid);
2748 char *p2 = utf8_to_native (p, strlen (p), 0);
2755 get_long_user_id_string (u32 * keyid)
2760 /* Try it two times; second pass reads from key resources. */
2763 for (r = user_id_db; r; r = r->next)
2765 for (a = r->keyids; a; a = a->next)
2767 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
2769 return xasprintf ("%08lX%08lX %.*s",
2770 (ulong) keyid[0], (ulong) keyid[1],
2776 while (++pass < 2 && !get_pubkey (NULL, keyid));
2777 return xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
2781 /* Please try to use get_user_id_native instead of this one. */
2783 get_user_id (u32 * keyid, size_t * rn)
2789 /* Try it two times; second pass reads from key resources. */
2792 for (r = user_id_db; r; r = r->next)
2795 for (a = r->keyids; a; a = a->next)
2797 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
2799 /* An empty string as user id is possible. Make
2800 sure that the malloc allocates one byte and does
2802 p = xmalloc (r->len? r->len : 1);
2803 memcpy (p, r->name, r->len);
2810 while (++pass < 2 && !get_pubkey (NULL, keyid));
2811 p = xstrdup (user_id_not_found_utf8 ());
2816 /* Please try to use get_user_id_byfpr_native instead of this one. */
2818 get_user_id_native (u32 * keyid)
2821 char *p = get_user_id (keyid, &rn);
2822 char *p2 = utf8_to_native (p, rn, 0);
2828 /* Return a user id from the caching by looking it up using the FPR
2829 which mustbe of size MAX_FINGERPRINT_LEN. */
2831 get_user_id_byfpr (const byte *fpr, size_t *rn)
2837 /* Try it two times; second pass reads from key resources. */
2840 for (r = user_id_db; r; r = r->next)
2843 for (a = r->keyids; a; a = a->next)
2845 if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
2847 /* An empty string as user id is possible. Make
2848 sure that the malloc allocates one byte and does
2850 p = xmalloc (r->len? r->len : 1);
2851 memcpy (p, r->name, r->len);
2858 while (++pass < 2 && !get_pubkey_byfpr (NULL, fpr));
2859 p = xstrdup (user_id_not_found_utf8 ());
2865 get_user_id_byfpr_native (const byte *fpr)
2868 char *p = get_user_id_byfpr (fpr, &rn);
2869 char *p2 = utf8_to_native (p, rn, 0);
2877 get_ctx_handle (GETKEY_CTX ctx)
2879 return ctx->kr_handle;
2883 free_akl (struct akl *akl)
2886 free_keyserver_spec (akl->spec);
2894 while (opt.auto_key_locate)
2896 struct akl *akl2 = opt.auto_key_locate;
2897 opt.auto_key_locate = opt.auto_key_locate->next;
2902 /* Returns false on error. */
2904 parse_auto_key_locate (char *options)
2908 while ((tok = optsep (&options)))
2910 struct akl *akl, *check, *last = NULL;
2916 akl = xmalloc_clear (sizeof (*akl));
2918 if (ascii_strcasecmp (tok, "clear") == 0)
2921 free_akl (opt.auto_key_locate);
2922 opt.auto_key_locate = NULL;
2925 else if (ascii_strcasecmp (tok, "nodefault") == 0)
2926 akl->type = AKL_NODEFAULT;
2927 else if (ascii_strcasecmp (tok, "local") == 0)
2928 akl->type = AKL_LOCAL;
2929 else if (ascii_strcasecmp (tok, "ldap") == 0)
2930 akl->type = AKL_LDAP;
2931 else if (ascii_strcasecmp (tok, "keyserver") == 0)
2932 akl->type = AKL_KEYSERVER;
2934 else if (ascii_strcasecmp (tok, "cert") == 0)
2935 akl->type = AKL_CERT;
2938 else if (ascii_strcasecmp (tok, "pka") == 0)
2939 akl->type = AKL_PKA;
2941 else if ((akl->spec = parse_keyserver_uri (tok, 1, NULL, 0)))
2942 akl->type = AKL_SPEC;
2949 /* We must maintain the order the user gave us */
2950 for (check = opt.auto_key_locate; check;
2951 last = check, check = check->next)
2953 /* Check for duplicates */
2954 if (check->type == akl->type
2955 && (akl->type != AKL_SPEC
2956 || (akl->type == AKL_SPEC
2957 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
2970 opt.auto_key_locate = akl;
2978 /* Return true if a secret key or secret subkey is available for one
2979 of the public keys in KEYBLOCK. */
2981 have_any_secret_key (ctrl_t ctrl, kbnode_t keyblock)
2985 for (node = keyblock; node; node = node->next)
2986 if ((node->pkt->pkttype == PKT_PUBLIC_KEY
2987 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2988 && !agent_probe_secret_key (ctrl, node->pkt->pkt.public_key))
2994 /* Return true if a secret key is available for the public key with
2995 * the given KEYID. This is just a fast check and does not tell us
2996 * whether the secret key is valid. It merely tells os whether there
2997 * is some secret key. */
2999 have_secret_key_with_kid (u32 *keyid)
3003 KEYDB_SEARCH_DESC desc;
3008 kdbhd = keydb_new ();
3009 memset (&desc, 0, sizeof desc);
3010 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
3011 desc.u.kid[0] = keyid[0];
3012 desc.u.kid[1] = keyid[1];
3013 while (!result && !(err = keydb_search (kdbhd, &desc, 1, NULL)))
3015 err = keydb_get_keyblock (kdbhd, &keyblock);
3018 log_error (_("error reading keyblock: %s\n"), g10_errstr (err));
3022 for (node = keyblock; node; node = node->next)
3024 /* Bit 0 of the flags is set if the search found the key
3025 using that key or subkey. */
3026 if ((node->flag & 1))
3028 assert (node->pkt->pkttype == PKT_PUBLIC_KEY
3029 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3031 if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
3038 release_kbnode (keyblock);
3040 keydb_release (kdbhd);