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"
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. */
59 KEYDB_HANDLE kr_handle;
62 KEYDB_SEARCH_DESC items[1];
75 typedef struct keyid_list
77 struct keyid_list *next;
78 char fpr[MAX_FINGERPRINT_LEN];
83 #if MAX_PK_CACHE_ENTRIES
84 typedef struct pk_cache_entry
86 struct pk_cache_entry *next;
90 static pk_cache_entry_t pk_cache;
91 static int pk_cache_entries; /* Number of entries in pk cache. */
92 static int pk_cache_disabled;
95 #if MAX_UID_CACHE_ENTRIES < 5
96 #error we really need the userid cache
98 typedef struct user_id_db
100 struct user_id_db *next;
105 static user_id_db_t user_id_db;
106 static int uid_cache_entries; /* Number of entries in uid cache. */
108 static void merge_selfsigs (kbnode_t keyblock);
109 static int lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, int want_secret);
116 for (i = 0; i < DIM (lkup_stats); i++)
118 if (lkup_stats[i].any)
120 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
122 lkup_stats[i].okay_count,
123 lkup_stats[i].nokey_count, lkup_stats[i].error_count);
130 cache_public_key (PKT_public_key * pk)
132 #if MAX_PK_CACHE_ENTRIES
133 pk_cache_entry_t ce, ce2;
136 if (pk_cache_disabled)
139 if (pk->flags.dont_cache)
142 if (is_ELGAMAL (pk->pubkey_algo)
143 || pk->pubkey_algo == PUBKEY_ALGO_DSA
144 || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
145 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
146 || pk->pubkey_algo == PUBKEY_ALGO_ECDH
147 || is_RSA (pk->pubkey_algo))
149 keyid_from_pk (pk, keyid);
152 return; /* Don't know how to get the keyid. */
154 for (ce = pk_cache; ce; ce = ce->next)
155 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
158 log_debug ("cache_public_key: already in cache\n");
162 if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
166 /* Remove the last 50% of the entries. */
167 for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
169 if (ce != pk_cache && ce->next)
177 free_public_key (ce->pk);
182 assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
185 ce = xmalloc (sizeof *ce);
188 ce->pk = copy_public_key (NULL, pk);
189 ce->keyid[0] = keyid[0];
190 ce->keyid[1] = keyid[1];
195 /* Return a const utf-8 string with the text "[User ID not found]".
196 This function is required so that we don't need to switch gettext's
197 encoding temporary. */
199 user_id_not_found_utf8 (void)
204 text = native_to_utf8 (_("[User ID not found]"));
210 /* Return the user ID from the given keyblock.
211 * We use the primary uid flag which has been set by the merge_selfsigs
212 * function. The returned value is only valid as long as then given
213 * keyblock is not changed. */
215 get_primary_uid (KBNODE keyblock, size_t * uidlen)
220 for (k = keyblock; k; k = k->next)
222 if (k->pkt->pkttype == PKT_USER_ID
223 && !k->pkt->pkt.user_id->attrib_data
224 && k->pkt->pkt.user_id->is_primary)
226 *uidlen = k->pkt->pkt.user_id->len;
227 return k->pkt->pkt.user_id->name;
230 s = user_id_not_found_utf8 ();
231 *uidlen = strlen (s);
237 release_keyid_list (keyid_list_t k)
241 keyid_list_t k2 = k->next;
248 * Store the association of keyid and userid
249 * Feed only public keys to this function.
252 cache_user_id (KBNODE keyblock)
257 keyid_list_t keyids = NULL;
260 for (k = keyblock; k; k = k->next)
262 if (k->pkt->pkttype == PKT_PUBLIC_KEY
263 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
265 keyid_list_t a = xmalloc_clear (sizeof *a);
266 /* Hmmm: For a long list of keyids it might be an advantage
267 * to append the keys. */
268 fingerprint_from_pk (k->pkt->pkt.public_key, a->fpr, NULL);
269 keyid_from_pk (k->pkt->pkt.public_key, a->keyid);
270 /* First check for duplicates. */
271 for (r = user_id_db; r; r = r->next)
273 keyid_list_t b = r->keyids;
274 for (b = r->keyids; b; b = b->next)
276 if (!memcmp (b->fpr, a->fpr, MAX_FINGERPRINT_LEN))
279 log_debug ("cache_user_id: already in cache\n");
280 release_keyid_list (keyids);
286 /* Now put it into the cache. */
292 BUG (); /* No key no fun. */
295 uid = get_primary_uid (keyblock, &uidlen);
297 if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES)
299 /* fixme: use another algorithm to free some cache slots */
301 user_id_db = r->next;
302 release_keyid_list (r->keyids);
306 r = xmalloc (sizeof *r + uidlen - 1);
309 memcpy (r->name, uid, r->len);
310 r->next = user_id_db;
317 getkey_disable_caches ()
319 #if MAX_PK_CACHE_ENTRIES
321 pk_cache_entry_t ce, ce2;
323 for (ce = pk_cache; ce; ce = ce2)
326 free_public_key (ce->pk);
329 pk_cache_disabled = 1;
330 pk_cache_entries = 0;
334 /* fixme: disable user id cache ? */
339 pk_from_block (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE keyblock)
341 KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
343 assert (a->pkt->pkttype == PKT_PUBLIC_KEY
344 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
346 copy_public_key (pk, a->pkt->pkt.public_key);
349 /* Get a public key and store it into the allocated pk can be called
350 * with PK set to NULL to just read it into some internal
353 get_pubkey (PKT_public_key * pk, u32 * keyid)
358 #if MAX_PK_CACHE_ENTRIES
361 /* Try to get it from the cache. We don't do this when pk is
362 NULL as it does not guarantee that the user IDs are
365 for (ce = pk_cache; ce; ce = ce->next)
367 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
369 copy_public_key (pk, ce->pk);
375 /* More init stuff. */
378 pk = xmalloc_clear (sizeof *pk);
385 struct getkey_ctx_s ctx;
387 memset (&ctx, 0, sizeof ctx);
388 ctx.exact = 1; /* Use the key ID exactly as given. */
389 ctx.not_allocated = 1;
390 ctx.kr_handle = keydb_new ();
392 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
393 ctx.items[0].u.kid[0] = keyid[0];
394 ctx.items[0].u.kid[1] = keyid[1];
395 ctx.req_algo = pk->req_algo;
396 ctx.req_usage = pk->req_usage;
397 rc = lookup (&ctx, &kb, 0);
400 pk_from_block (&ctx, pk, kb);
402 get_pubkey_end (&ctx);
408 rc = GPG_ERR_NO_PUBKEY;
412 cache_public_key (pk);
414 free_public_key (pk);
419 /* Get a public key and store it into the allocated pk. This function
420 differs from get_pubkey() in that it does not do a check of the key
421 to avoid recursion. It should be used only in very certain cases.
422 It will only retrieve primary keys. */
424 get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
432 #if MAX_PK_CACHE_ENTRIES
434 /* Try to get it from the cache */
437 for (ce = pk_cache; ce; ce = ce->next)
439 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
442 copy_public_key (pk, ce->pk);
450 rc = keydb_search_kid (hd, keyid);
451 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
454 return GPG_ERR_NO_PUBKEY;
456 rc = keydb_get_keyblock (hd, &keyblock);
460 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
461 return GPG_ERR_NO_PUBKEY;
464 assert (keyblock && keyblock->pkt
465 && (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
466 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY));
468 keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
469 if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
470 copy_public_key (pk, keyblock->pkt->pkt.public_key);
472 rc = GPG_ERR_NO_PUBKEY;
474 release_kbnode (keyblock);
476 /* Not caching key here since it won't have all of the fields
484 get_pubkeyblock (u32 * keyid)
486 struct getkey_ctx_s ctx;
488 KBNODE keyblock = NULL;
490 memset (&ctx, 0, sizeof ctx);
491 /* No need to set exact here because we want the entire block. */
492 ctx.not_allocated = 1;
493 ctx.kr_handle = keydb_new ();
495 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
496 ctx.items[0].u.kid[0] = keyid[0];
497 ctx.items[0].u.kid[1] = keyid[1];
498 rc = lookup (&ctx, &keyblock, 0);
499 get_pubkey_end (&ctx);
501 return rc ? NULL : keyblock;
508 * Get a public key and store it into PK. This functions check that a
509 * corresponding secret key is available. With no secret key it does
513 get_seckey (PKT_public_key *pk, u32 *keyid)
516 struct getkey_ctx_s ctx;
517 kbnode_t keyblock = NULL;
519 memset (&ctx, 0, sizeof ctx);
520 ctx.exact = 1; /* Use the key ID exactly as given. */
521 ctx.not_allocated = 1;
522 ctx.kr_handle = keydb_new ();
524 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
525 ctx.items[0].u.kid[0] = keyid[0];
526 ctx.items[0].u.kid[1] = keyid[1];
527 ctx.req_algo = pk->req_algo;
528 ctx.req_usage = pk->req_usage;
529 err = lookup (&ctx, &keyblock, 1);
532 pk_from_block (&ctx, pk, keyblock);
534 get_pubkey_end (&ctx);
535 release_kbnode (keyblock);
538 err = agent_probe_secret_key (/*ctrl*/NULL, pk);
545 skip_unusable (void *dummy, u32 * keyid, PKT_user_id * uid)
552 keyblock = get_pubkeyblock (keyid);
555 log_error ("error checking usability status of %s\n", keystr (keyid));
559 /* Is the user ID in question revoked/expired? */
564 for (node = keyblock; node; node = node->next)
566 if (node->pkt->pkttype == PKT_USER_ID)
568 if (cmp_user_ids (uid, node->pkt->pkt.user_id) == 0
569 && (node->pkt->pkt.user_id->is_revoked
570 || node->pkt->pkt.user_id->is_expired))
580 unusable = pk_is_disabled (keyblock->pkt->pkt.public_key);
583 release_kbnode (keyblock);
588 /* Try to get the pubkey by the userid. This function looks for the
589 * first pubkey certificate which has the given name in a user_id. If
590 * PK has the pubkey algo set, the function will only return a pubkey
591 * with that algo. If NAMELIST is NULL, the first key is returned.
592 * The caller should provide storage for the PK or pass NULL if it is
593 * not needed. If RET_KB is not NULL the function stores the entire
594 * keyblock at that address. */
596 key_byname (GETKEY_CTX *retctx, strlist_t namelist,
598 int want_secret, int include_unusable,
599 KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
605 KBNODE help_kb = NULL;
609 /* Reset the returned context in case of error. */
610 assert (!ret_kdbhd); /* Not allowed because the handle is stored
619 ctx = xmalloc_clear (sizeof *ctx);
621 ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
622 if (!include_unusable)
623 ctx->items[0].skipfnc = skip_unusable;
627 /* Build the search context. */
628 for (n = 0, r = namelist; r; r = r->next)
631 ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
634 for (n = 0, r = namelist; r; r = r->next, n++)
638 err = classify_user_id (r->d, &ctx->items[n], 1);
640 if (ctx->items[n].exact)
645 return gpg_err_code (err); /* FIXME: remove gpg_err_code. */
647 if (!include_unusable
648 && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
649 && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
650 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
651 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
652 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
653 ctx->items[n].skipfnc = skip_unusable;
657 ctx->want_secret = want_secret;
658 ctx->kr_handle = keydb_new ();
664 ctx->req_algo = pk->req_algo;
665 ctx->req_usage = pk->req_usage;
668 rc = lookup (ctx, ret_kb, want_secret);
671 pk_from_block (ctx, pk, *ret_kb);
674 release_kbnode (help_kb);
676 if (retctx) /* Caller wants the context. */
682 *ret_kdbhd = ctx->kr_handle;
683 ctx->kr_handle = NULL;
685 get_pubkey_end (ctx);
693 /* Find a public key from NAME and return the keyblock or the key. If
694 ret_kdb is not NULL, the KEYDB handle used to locate this keyblock
695 is returned and the caller is responsible for closing it. If a key
696 was not found (or if local search has been disabled) and NAME is a
697 valid RFC822 mailbox and --auto-key-locate has been enabled, we try
698 to import the key via the online mechanisms defined by
699 --auto-key-locate. */
701 get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
702 const char *name, KBNODE * ret_keyblock,
703 KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
706 strlist_t namelist = NULL;
710 int anylocalfirst = 0;
715 is_mbox = is_valid_mailbox (name);
717 /* Check whether the default local search has been disabled.
718 This is the case if either the "nodefault" or the "local" keyword
719 are in the list of auto key locate mechanisms.
721 ANYLOCALFIRST is set if the search order has the local method
722 before any other or if "local" is used first by default. This
723 makes sure that if a RETCTX is used it gets only set if a local
724 search has precedence over the other search methods and only then
725 a followup call to get_pubkey_next shall succeed. */
728 for (akl = opt.auto_key_locate; akl; akl = akl->next)
729 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
734 for (akl = opt.auto_key_locate; akl; akl = akl->next)
735 if (akl->type != AKL_NODEFAULT)
737 if (akl->type == AKL_LOCAL)
746 if (nodefault && is_mbox)
748 /* Nodefault but a mailbox - let the AKL locate the key. */
749 rc = GPG_ERR_NO_PUBKEY;
753 add_to_strlist (&namelist, name);
754 rc = key_byname (retctx, namelist, pk, 0,
755 include_unusable, ret_keyblock, ret_kdbhd);
758 /* If the requested name resembles a valid mailbox and automatic
759 retrieval has been enabled, we try to import the key. */
760 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && !no_akl && is_mbox)
762 for (akl = opt.auto_key_locate; akl; akl = akl->next)
764 unsigned char *fpr = NULL;
766 int did_key_byname = 0;
767 int no_fingerprint = 0;
768 const char *mechanism = "?";
773 /* This is a dummy mechanism. */
775 rc = GPG_ERR_NO_PUBKEY;
783 get_pubkey_end (*retctx);
786 add_to_strlist (&namelist, name);
787 rc = key_byname (anylocalfirst ? retctx : NULL,
789 include_unusable, ret_keyblock, ret_kdbhd);
793 mechanism = "DNS CERT";
794 glo_ctrl.in_auto_key_retrieve++;
795 rc = keyserver_import_cert (ctrl, name, &fpr, &fpr_len);
796 glo_ctrl.in_auto_key_retrieve--;
801 glo_ctrl.in_auto_key_retrieve++;
802 rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
803 glo_ctrl.in_auto_key_retrieve--;
808 glo_ctrl.in_auto_key_retrieve++;
809 rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
810 glo_ctrl.in_auto_key_retrieve--;
814 /* Strictly speaking, we don't need to only use a valid
815 mailbox for the getname search, but it helps cut down
816 on the problem of searching for something like "john"
817 and getting a whole lot of keys back. */
820 mechanism = opt.keyserver->uri;
821 glo_ctrl.in_auto_key_retrieve++;
822 rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
824 glo_ctrl.in_auto_key_retrieve--;
828 mechanism = "Unconfigured keyserver";
829 rc = GPG_ERR_NO_PUBKEY;
835 struct keyserver_spec *keyserver;
837 mechanism = akl->spec->uri;
838 keyserver = keyserver_match (akl->spec);
839 glo_ctrl.in_auto_key_retrieve++;
840 rc = keyserver_import_name (ctrl,
841 name, &fpr, &fpr_len, keyserver);
842 glo_ctrl.in_auto_key_retrieve--;
847 /* Use the fingerprint of the key that we actually fetched.
848 This helps prevent problems where the key that we fetched
849 doesn't have the same name that we used to fetch it. In
850 the case of CERT and PKA, this is an actual security
851 requirement as the URL might point to a key put in by an
852 attacker. By forcing the use of the fingerprint, we
853 won't use the attacker's key here. */
856 char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
858 assert (fpr_len <= MAX_FINGERPRINT_LEN);
860 free_strlist (namelist);
863 bin2hex (fpr, fpr_len, fpr_string);
866 log_info ("auto-key-locate found fingerprint %s\n",
869 add_to_strlist (&namelist, fpr_string);
871 else if (!rc && !fpr && !did_key_byname)
874 rc = GPG_ERR_NO_PUBKEY;
879 if (!rc && !did_key_byname)
883 get_pubkey_end (*retctx);
886 rc = key_byname (anylocalfirst ? retctx : NULL,
888 include_unusable, ret_keyblock, ret_kdbhd);
893 log_info (_("automatically retrieved '%s' via %s\n"),
897 if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
898 || opt.verbose || no_fingerprint)
899 log_info (_("error retrieving '%s' via %s: %s\n"),
901 no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
908 get_pubkey_end (*retctx);
912 if (retctx && *retctx)
914 assert (!(*retctx)->extra_list);
915 (*retctx)->extra_list = namelist;
918 free_strlist (namelist);
924 get_pubkey_bynames (GETKEY_CTX * retctx, PKT_public_key * pk,
925 strlist_t names, KBNODE * ret_keyblock)
927 return key_byname (retctx, names, pk, 0, 1, ret_keyblock, NULL);
931 get_pubkey_next (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE * ret_keyblock)
933 return gpg_err_code (getkey_next (ctx, pk, ret_keyblock));
937 get_pubkey_end (GETKEY_CTX ctx)
943 /* Search for a key with the given standard fingerprint. In contrast
944 * to get_pubkey_byfprint we assume a right padded fingerprint of the
945 * standard length. PK may be NULL to only put the result into the
946 * internal caches. */
948 get_pubkey_byfpr (PKT_public_key *pk, const byte *fpr)
951 struct getkey_ctx_s ctx;
954 memset (&ctx, 0, sizeof ctx);
956 ctx.not_allocated = 1;
957 ctx.kr_handle = keydb_new ();
959 ctx.items[0].mode = KEYDB_SEARCH_MODE_FPR;
960 memcpy (ctx.items[0].u.fpr, fpr, MAX_FINGERPRINT_LEN);
961 err = lookup (&ctx, &kb, 0);
963 pk_from_block (&ctx, pk, kb);
965 get_pubkey_end (&ctx);
971 /* Search for a key with the given fingerprint.
973 * We should replace this with the _byname function. This can be done
974 * by creating a userID conforming to the unified fingerprint style.
977 get_pubkey_byfprint (PKT_public_key * pk,
978 const byte * fprint, size_t fprint_len)
982 if (fprint_len == 20 || fprint_len == 16)
984 struct getkey_ctx_s ctx;
987 memset (&ctx, 0, sizeof ctx);
989 ctx.not_allocated = 1;
990 ctx.kr_handle = keydb_new ();
992 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
993 : KEYDB_SEARCH_MODE_FPR20;
994 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
995 rc = lookup (&ctx, &kb, 0);
997 pk_from_block (&ctx, pk, kb);
999 get_pubkey_end (&ctx);
1002 rc = GPG_ERR_GENERAL; /* Oops */
1007 /* Get a public key and store it into the allocated pk. This function
1008 differs from get_pubkey_byfprint() in that it does not do a check
1009 of the key to avoid recursion. It should be used only in very
1010 certain cases. PK may be NULL to check just for the existance of
1013 get_pubkey_byfprint_fast (PKT_public_key * pk,
1014 const byte * fprint, size_t fprint_len)
1019 byte fprbuf[MAX_FINGERPRINT_LEN];
1022 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1023 fprbuf[i] = fprint[i];
1024 while (i < MAX_FINGERPRINT_LEN)
1028 rc = keydb_search_fpr (hd, fprbuf);
1029 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1032 return GPG_ERR_NO_PUBKEY;
1034 rc = keydb_get_keyblock (hd, &keyblock);
1038 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1039 return GPG_ERR_NO_PUBKEY;
1042 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1043 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1045 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1046 release_kbnode (keyblock);
1048 /* Not caching key here since it won't have all of the fields
1055 /* Search for a key with the given fingerprint and return the
1056 * complete keyblock which may have more than only this key. */
1058 get_keyblock_byfprint (KBNODE * ret_keyblock, const byte * fprint,
1063 if (fprint_len == 20 || fprint_len == 16)
1065 struct getkey_ctx_s ctx;
1067 memset (&ctx, 0, sizeof ctx);
1068 ctx.not_allocated = 1;
1069 ctx.kr_handle = keydb_new ();
1071 ctx.items[0].mode = (fprint_len == 16
1072 ? KEYDB_SEARCH_MODE_FPR16
1073 : KEYDB_SEARCH_MODE_FPR20);
1074 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1075 rc = lookup (&ctx, ret_keyblock, 0);
1076 get_pubkey_end (&ctx);
1079 rc = GPG_ERR_GENERAL; /* Oops */
1085 /* Get a secret key by NAME and store it into PK. If NAME is NULL use
1086 * the default key. This functions checks that a corresponding secret
1087 * key is available. With no secret key it does not succeeed. */
1089 get_seckey_byname (PKT_public_key *pk, const char *name)
1092 strlist_t namelist = NULL;
1093 int include_unusable = 1;
1095 /* If we have no name, try to use the default secret key. If we
1096 have no default, we'll use the first usable one. */
1098 if (!name && opt.def_secret_key && *opt.def_secret_key)
1099 add_to_strlist (&namelist, opt.def_secret_key);
1101 add_to_strlist (&namelist, name);
1103 include_unusable = 0;
1105 err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
1107 free_strlist (namelist);
1114 /* Search for a key with the given fingerprint.
1116 * We should replace this with the _byname function. This can be done
1117 * by creating a userID conforming to the unified fingerprint style. */
1119 get_seckey_byfprint (PKT_public_key *pk, const byte * fprint, size_t fprint_len)
1123 if (fprint_len == 20 || fprint_len == 16)
1125 struct getkey_ctx_s ctx;
1128 memset (&ctx, 0, sizeof ctx);
1130 ctx.not_allocated = 1;
1131 ctx.kr_handle = keydb_new ();
1133 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1134 : KEYDB_SEARCH_MODE_FPR20;
1135 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1136 err = lookup (&ctx, &kb, 1);
1138 pk_from_block (&ctx, pk, kb);
1139 release_kbnode (kb);
1140 get_pubkey_end (&ctx);
1143 err = gpg_error (GPG_ERR_BUG);
1148 /* Search for a secret key with the given fingerprint and return the
1149 complete keyblock which may have more than only this key. Return
1150 an error if no corresponding secret key is available. */
1152 get_seckeyblock_byfprint (kbnode_t *ret_keyblock,
1153 const byte *fprint, size_t fprint_len)
1156 struct getkey_ctx_s ctx;
1158 if (fprint_len != 20 && fprint_len == 16)
1159 return gpg_error (GPG_ERR_BUG);
1161 memset (&ctx, 0, sizeof ctx);
1162 ctx.not_allocated = 1;
1163 ctx.kr_handle = keydb_new ();
1165 ctx.items[0].mode = (fprint_len == 16
1166 ? KEYDB_SEARCH_MODE_FPR16 : KEYDB_SEARCH_MODE_FPR20);
1167 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1168 err = lookup (&ctx, ret_keyblock, 1);
1169 get_pubkey_end (&ctx);
1176 /* The new function to return a key.
1177 FIXME: Document it. */
1179 getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
1180 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
1182 return key_byname (retctx, names, pk, want_secret, 1,
1183 ret_keyblock, NULL);
1187 /* Get a key by name and store it into PK if that is not NULL. If
1188 * RETCTX is not NULL return the search context which needs to be
1189 * released by the caller using getkey_end. If NAME is NULL use the
1190 * default key (see below). On success and if RET_KEYBLOCK is not
1191 * NULL the found keyblock is stored at this address. WANT_SECRET
1192 * passed as true requires that a secret key is available for the
1195 * If WANT_SECRET is true and NAME is NULL and a default key has been
1196 * defined that defined key is used. In all other cases the first
1197 * available key is used.
1199 * FIXME: Explain what is up with unusable keys.
1201 * FIXME: We also have the get_pubkey_byname function which has a
1202 * different semantic. Should be merged with this one.
1205 getkey_byname (getkey_ctx_t *retctx, PKT_public_key *pk,
1206 const char *name, int want_secret, kbnode_t *ret_keyblock)
1209 strlist_t namelist = NULL;
1210 int with_unusable = 1;
1212 if (want_secret && !name && opt.def_secret_key && *opt.def_secret_key)
1213 add_to_strlist (&namelist, opt.def_secret_key);
1215 add_to_strlist (&namelist, name);
1219 err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
1220 ret_keyblock, NULL);
1222 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
1223 WANT_SECRET has been used. */
1225 free_strlist (namelist);
1231 /* The new function to return the next key. */
1233 getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
1235 int rc; /* Fixme: Make sure this is proper gpg_error */
1237 /* We need to disable the caching so that for an exact key search we
1238 won't get the result back from the cache and thus end up in an
1239 endless loop. Disabling this here is sufficient because although
1240 the result has been cached, if won't be used then. */
1241 keydb_disable_caching (ctx->kr_handle);
1243 rc = lookup (ctx, ret_keyblock, ctx->want_secret);
1244 if (!rc && pk && ret_keyblock)
1245 pk_from_block (ctx, pk, *ret_keyblock);
1251 /* The new function to finish a key listing. */
1253 getkey_end (getkey_ctx_t ctx)
1257 memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
1258 keydb_release (ctx->kr_handle);
1259 free_strlist (ctx->extra_list);
1260 if (!ctx->not_allocated)
1267 /************************************************
1268 ************* Merging stuff ********************
1269 ************************************************/
1271 /* Set the mainkey_id fields for all keys in KEYBLOCK. This is
1272 usually done by merge_selfsigs but at some places we only need the
1273 main_kid but the the full merging. The function also guarantees
1274 that all pk->keyids are computed. */
1276 setup_main_keyids (kbnode_t keyblock)
1278 u32 kid[2], mainkid[2];
1279 kbnode_t kbctx, node;
1282 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1284 pk = keyblock->pkt->pkt.public_key;
1286 keyid_from_pk (pk, mainkid);
1287 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1289 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
1290 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1292 pk = node->pkt->pkt.public_key;
1293 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
1294 if (!pk->main_keyid[0] && !pk->main_keyid[1])
1296 pk->main_keyid[0] = mainkid[0];
1297 pk->main_keyid[1] = mainkid[1];
1303 /* Merge all self-signatures with the keys. */
1305 merge_keys_and_selfsig (KBNODE keyblock)
1309 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
1310 merge_selfsigs (keyblock);
1312 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
1317 parse_key_usage (PKT_signature * sig)
1324 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
1327 /* First octet of the keyflags. */
1332 key_usage |= PUBKEY_USAGE_CERT;
1338 key_usage |= PUBKEY_USAGE_SIG;
1342 /* We do not distinguish between encrypting communications and
1343 encrypting storage. */
1344 if (flags & (0x04 | 0x08))
1346 key_usage |= PUBKEY_USAGE_ENC;
1347 flags &= ~(0x04 | 0x08);
1352 key_usage |= PUBKEY_USAGE_AUTH;
1357 key_usage |= PUBKEY_USAGE_UNKNOWN;
1360 key_usage |= PUBKEY_USAGE_NONE;
1362 else if (p) /* Key flags of length zero. */
1363 key_usage |= PUBKEY_USAGE_NONE;
1365 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1366 capability that we do not handle. This serves to distinguish
1367 between a zero key usage which we handle as the default
1368 capabilities for that algorithm, and a usage that we do not
1369 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
1370 key_flags have been given but they do not specify any usage. */
1376 /* Apply information from SIGNODE (which is the valid self-signature
1377 * associated with that UID) to the UIDNODE:
1378 * - wether the UID has been revoked
1379 * - assumed creation date of the UID
1380 * - temporary store the keyflags here
1381 * - temporary store the key expiration time here
1382 * - mark whether the primary user ID flag hat been set.
1383 * - store the preferences
1386 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
1388 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1389 PKT_signature *sig = signode->pkt->pkt.signature;
1390 const byte *p, *sym, *hash, *zip;
1391 size_t n, nsym, nhash, nzip;
1393 sig->flags.chosen_selfsig = 1;/* We chose this one. */
1394 uid->created = 0; /* Not created == invalid. */
1395 if (IS_UID_REV (sig))
1397 uid->is_revoked = 1;
1398 return; /* Has been revoked. */
1401 uid->is_revoked = 0;
1403 uid->expiredate = sig->expiredate;
1405 if (sig->flags.expired)
1407 uid->is_expired = 1;
1408 return; /* Has expired. */
1411 uid->is_expired = 0;
1413 uid->created = sig->timestamp; /* This one is okay. */
1414 uid->selfsigversion = sig->version;
1415 /* If we got this far, it's not expired :) */
1416 uid->is_expired = 0;
1418 /* Store the key flags in the helper variable for later processing. */
1419 uid->help_key_usage = parse_key_usage (sig);
1421 /* Ditto for the key expiration. */
1422 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1423 if (p && buf32_to_u32 (p))
1424 uid->help_key_expire = keycreated + buf32_to_u32 (p);
1426 uid->help_key_expire = 0;
1428 /* Set the primary user ID flag - we will later wipe out some
1429 * of them to only have one in our keyblock. */
1430 uid->is_primary = 0;
1431 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
1433 uid->is_primary = 2;
1435 /* We could also query this from the unhashed area if it is not in
1436 * the hased area and then later try to decide which is the better
1437 * there should be no security problem with this.
1438 * For now we only look at the hashed one. */
1440 /* Now build the preferences list. These must come from the
1441 hashed section so nobody can modify the ciphers a key is
1442 willing to accept. */
1443 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
1446 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
1449 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
1454 n = nsym + nhash + nzip;
1459 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
1461 for (; nsym; nsym--, n++)
1463 uid->prefs[n].type = PREFTYPE_SYM;
1464 uid->prefs[n].value = *sym++;
1466 for (; nhash; nhash--, n++)
1468 uid->prefs[n].type = PREFTYPE_HASH;
1469 uid->prefs[n].value = *hash++;
1471 for (; nzip; nzip--, n++)
1473 uid->prefs[n].type = PREFTYPE_ZIP;
1474 uid->prefs[n].value = *zip++;
1476 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
1477 uid->prefs[n].value = 0;
1480 /* See whether we have the MDC feature. */
1482 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1483 if (p && n && (p[0] & 0x01))
1486 /* And the keyserver modify flag. */
1487 uid->flags.ks_modify = 1;
1488 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1489 if (p && n && (p[0] & 0x80))
1490 uid->flags.ks_modify = 0;
1494 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
1496 rinfo->date = sig->timestamp;
1497 rinfo->algo = sig->pubkey_algo;
1498 rinfo->keyid[0] = sig->keyid[0];
1499 rinfo->keyid[1] = sig->keyid[1];
1503 /* Note that R_REVOKED may be set to 0, 1 or 2. */
1505 merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
1506 struct revoke_info *rinfo)
1508 PKT_public_key *pk = NULL;
1511 u32 sigdate, uiddate, uiddate2;
1512 KBNODE signode, uidnode, uidnode2;
1513 u32 curtime = make_timestamp ();
1514 unsigned int key_usage = 0;
1515 u32 keytimestamp = 0;
1517 int key_expire_seen = 0;
1518 byte sigversion = 0;
1521 memset (rinfo, 0, sizeof (*rinfo));
1523 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1525 pk = keyblock->pkt->pkt.public_key;
1526 keytimestamp = pk->timestamp;
1528 keyid_from_pk (pk, kid);
1529 pk->main_keyid[0] = kid[0];
1530 pk->main_keyid[1] = kid[1];
1532 if (pk->version < 4)
1534 /* Before v4 the key packet itself contains the expiration date
1535 * and there was no way to change it, so we start with the one
1536 * from the key packet. */
1537 key_expire = pk->max_expiredate;
1538 key_expire_seen = 1;
1541 /* First pass: Find the latest direct key self-signature. We assume
1542 * that the newest one overrides all others. */
1544 /* In case this key was already merged. */
1550 sigdate = 0; /* Helper variable to find the latest signature. */
1551 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
1553 if (k->pkt->pkttype == PKT_SIGNATURE)
1555 PKT_signature *sig = k->pkt->pkt.signature;
1556 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1558 if (check_key_signature (keyblock, k, NULL))
1559 ; /* Signature did not verify. */
1560 else if (IS_KEY_REV (sig))
1562 /* Key has been revoked - there is no way to
1563 * override such a revocation, so we theoretically
1564 * can stop now. We should not cope with expiration
1565 * times for revocations here because we have to
1566 * assume that an attacker can generate all kinds of
1567 * signatures. However due to the fact that the key
1568 * has been revoked it does not harm either and by
1569 * continuing we gather some more info on that
1572 sig_to_revoke_info (sig, rinfo);
1574 else if (IS_KEY_SIG (sig))
1576 /* Add any revocation keys onto the pk. This is
1577 particularly interesting since we normally only
1578 get data from the most recent 1F signature, but
1579 you need multiple 1F sigs to properly handle
1580 revocation keys (PGP does it this way, and a
1581 revocation key could be sensitive and hence in a
1582 different signature). */
1588 xrealloc (pk->revkey, sizeof (struct revocation_key) *
1589 (pk->numrevkeys + sig->numrevkeys));
1591 for (i = 0; i < sig->numrevkeys; i++)
1592 memcpy (&pk->revkey[pk->numrevkeys++],
1594 sizeof (struct revocation_key));
1597 if (sig->timestamp >= sigdate)
1599 if (sig->flags.expired)
1600 ; /* Signature has expired - ignore it. */
1603 sigdate = sig->timestamp;
1605 if (sig->version > sigversion)
1606 sigversion = sig->version;
1615 /* Remove dupes from the revocation keys. */
1619 int i, j, x, changed = 0;
1621 for (i = 0; i < pk->numrevkeys; i++)
1623 for (j = i + 1; j < pk->numrevkeys; j++)
1625 if (memcmp (&pk->revkey[i], &pk->revkey[j],
1626 sizeof (struct revocation_key)) == 0)
1630 for (x = j; x < pk->numrevkeys - 1; x++)
1631 pk->revkey[x] = pk->revkey[x + 1];
1641 pk->revkey = xrealloc (pk->revkey,
1643 sizeof (struct revocation_key));
1648 /* Some information from a direct key signature take precedence
1649 * over the same information given in UID sigs. */
1650 PKT_signature *sig = signode->pkt->pkt.signature;
1653 key_usage = parse_key_usage (sig);
1655 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1656 if (p && buf32_to_u32 (p))
1658 key_expire = keytimestamp + buf32_to_u32 (p);
1659 key_expire_seen = 1;
1662 /* Mark that key as valid: One direct key signature should
1663 * render a key as valid. */
1664 pk->flags.valid = 1;
1667 /* Pass 1.5: Look for key revocation signatures that were not made
1668 by the key (i.e. did a revocation key issue a revocation for
1669 us?). Only bother to do this if there is a revocation key in the
1670 first place and we're not revoked already. */
1672 if (!*r_revoked && pk->revkey)
1673 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
1675 if (k->pkt->pkttype == PKT_SIGNATURE)
1677 PKT_signature *sig = k->pkt->pkt.signature;
1679 if (IS_KEY_REV (sig) &&
1680 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
1682 int rc = check_revocation_keys (pk, sig);
1686 sig_to_revoke_info (sig, rinfo);
1687 /* Don't continue checking since we can't be any
1688 more revoked than this. */
1691 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
1692 pk->flags.maybe_revoked = 1;
1694 /* A failure here means the sig did not verify, was
1695 not issued by a revocation key, or a revocation
1696 key loop was broken. If a revocation key isn't
1697 findable, however, the key might be revoked and
1698 we don't know it. */
1700 /* TODO: In the future handle subkey and cert
1701 revocations? PGP doesn't, but it's in 2440. */
1706 /* Second pass: Look at the self-signature of all user IDs. */
1707 signode = uidnode = NULL;
1708 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
1709 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1711 if (k->pkt->pkttype == PKT_USER_ID)
1713 if (uidnode && signode)
1715 fixup_uidnode (uidnode, signode, keytimestamp);
1716 pk->flags.valid = 1;
1722 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1724 PKT_signature *sig = k->pkt->pkt.signature;
1725 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1727 if (check_key_signature (keyblock, k, NULL))
1728 ; /* signature did not verify */
1729 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
1730 && sig->timestamp >= sigdate)
1732 /* Note: we allow to invalidate cert revocations
1733 * by a newer signature. An attacker can't use this
1734 * because a key should be revoced with a key revocation.
1735 * The reason why we have to allow for that is that at
1736 * one time an email address may become invalid but later
1737 * the same email address may become valid again (hired,
1738 * fired, hired again). */
1740 sigdate = sig->timestamp;
1742 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
1743 if (sig->version > sigversion)
1744 sigversion = sig->version;
1749 if (uidnode && signode)
1751 fixup_uidnode (uidnode, signode, keytimestamp);
1752 pk->flags.valid = 1;
1755 /* If the key isn't valid yet, and we have
1756 --allow-non-selfsigned-uid set, then force it valid. */
1757 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
1760 log_info (_("Invalid key %s made valid by"
1761 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
1762 pk->flags.valid = 1;
1765 /* The key STILL isn't valid, so try and find an ultimately
1766 trusted signature. */
1767 if (!pk->flags.valid)
1771 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1774 if (k->pkt->pkttype == PKT_USER_ID)
1776 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1778 PKT_signature *sig = k->pkt->pkt.signature;
1780 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
1782 PKT_public_key *ultimate_pk;
1784 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
1786 /* We don't want to use the full get_pubkey to
1787 avoid infinite recursion in certain cases.
1788 There is no reason to check that an ultimately
1789 trusted key is still valid - if it has been
1790 revoked or the user should also renmove the
1791 ultimate trust flag. */
1792 if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
1793 && check_key_signature2 (keyblock, k, ultimate_pk,
1794 NULL, NULL, NULL, NULL) == 0
1795 && get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
1797 free_public_key (ultimate_pk);
1798 pk->flags.valid = 1;
1802 free_public_key (ultimate_pk);
1808 /* Record the highest selfsig version so we know if this is a v3
1809 key through and through, or a v3 key with a v4 selfsig
1810 somewhere. This is useful in a few places to know if the key
1811 must be treated as PGP2-style or OpenPGP-style. Note that a
1812 selfsig revocation with a higher version number will also raise
1813 this value. This is okay since such a revocation must be
1814 issued by the user (i.e. it cannot be issued by someone else to
1815 modify the key behavior.) */
1817 pk->selfsigversion = sigversion;
1819 /* Now that we had a look at all user IDs we can now get some information
1820 * from those user IDs.
1825 /* Find the latest user ID with key flags set. */
1826 uiddate = 0; /* Helper to find the latest user ID. */
1827 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1830 if (k->pkt->pkttype == PKT_USER_ID)
1832 PKT_user_id *uid = k->pkt->pkt.user_id;
1833 if (uid->help_key_usage && uid->created > uiddate)
1835 key_usage = uid->help_key_usage;
1836 uiddate = uid->created;
1843 /* No key flags at all: get it from the algo. */
1844 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
1848 /* Check that the usage matches the usage as given by the algo. */
1849 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
1850 if (x) /* Mask it down to the actual allowed usage. */
1854 /* Whatever happens, it's a primary key, so it can certify. */
1855 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
1857 if (!key_expire_seen)
1859 /* Find the latest valid user ID with a key expiration set
1860 * Note, that this may be a different one from the above because
1861 * some user IDs may have no expiration date set. */
1863 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1866 if (k->pkt->pkttype == PKT_USER_ID)
1868 PKT_user_id *uid = k->pkt->pkt.user_id;
1869 if (uid->help_key_expire && uid->created > uiddate)
1871 key_expire = uid->help_key_expire;
1872 uiddate = uid->created;
1878 /* Currently only v3 keys have a maximum expiration date, but I'll
1879 bet v5 keys get this feature again. */
1881 || (pk->max_expiredate && key_expire > pk->max_expiredate))
1882 key_expire = pk->max_expiredate;
1884 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
1885 pk->expiredate = key_expire;
1887 /* Fixme: we should see how to get rid of the expiretime fields but
1888 * this needs changes at other places too. */
1890 /* And now find the real primary user ID and delete all others. */
1891 uiddate = uiddate2 = 0;
1892 uidnode = uidnode2 = NULL;
1893 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1895 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
1897 PKT_user_id *uid = k->pkt->pkt.user_id;
1898 if (uid->is_primary)
1900 if (uid->created > uiddate)
1902 uiddate = uid->created;
1905 else if (uid->created == uiddate && uidnode)
1907 /* The dates are equal, so we need to do a
1908 different (and arbitrary) comparison. This
1909 should rarely, if ever, happen. It's good to
1910 try and guarantee that two different GnuPG
1911 users with two different keyrings at least pick
1912 the same primary. */
1913 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
1919 if (uid->created > uiddate2)
1921 uiddate2 = uid->created;
1924 else if (uid->created == uiddate2 && uidnode2)
1926 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
1934 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1937 if (k->pkt->pkttype == PKT_USER_ID &&
1938 !k->pkt->pkt.user_id->attrib_data)
1940 PKT_user_id *uid = k->pkt->pkt.user_id;
1942 uid->is_primary = 0;
1948 /* None is flagged primary - use the latest user ID we have,
1949 and disambiguate with the arbitrary packet comparison. */
1950 uidnode2->pkt->pkt.user_id->is_primary = 1;
1954 /* None of our uids were self-signed, so pick the one that
1955 sorts first to be the primary. This is the best we can do
1956 here since there are no self sigs to date the uids. */
1960 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1963 if (k->pkt->pkttype == PKT_USER_ID
1964 && !k->pkt->pkt.user_id->attrib_data)
1969 uidnode->pkt->pkt.user_id->is_primary = 1;
1974 if (cmp_user_ids (k->pkt->pkt.user_id,
1975 uidnode->pkt->pkt.user_id) > 0)
1977 uidnode->pkt->pkt.user_id->is_primary = 0;
1979 uidnode->pkt->pkt.user_id->is_primary = 1;
1982 k->pkt->pkt.user_id->is_primary = 0; /* just to be
1990 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
1991 Caller must free the signature when they are done. */
1992 static PKT_signature *
1993 buf_to_sig (const byte * buf, size_t len)
1995 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
1996 IOBUF iobuf = iobuf_temp_with_content (buf, len);
1997 int save_mode = set_packet_list_mode (0);
1999 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
2005 set_packet_list_mode (save_mode);
2006 iobuf_close (iobuf);
2012 merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
2014 PKT_public_key *mainpk = NULL, *subpk = NULL;
2020 u32 curtime = make_timestamp ();
2021 unsigned int key_usage = 0;
2022 u32 keytimestamp = 0;
2026 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2028 mainpk = keyblock->pkt->pkt.public_key;
2029 if (mainpk->version < 4)
2030 return;/* (actually this should never happen) */
2031 keyid_from_pk (mainpk, mainkid);
2032 subpk = subnode->pkt->pkt.public_key;
2033 keytimestamp = subpk->timestamp;
2035 subpk->flags.valid = 0;
2036 subpk->main_keyid[0] = mainpk->main_keyid[0];
2037 subpk->main_keyid[1] = mainpk->main_keyid[1];
2039 /* Find the latest key binding self-signature. */
2041 sigdate = 0; /* Helper to find the latest signature. */
2042 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2045 if (k->pkt->pkttype == PKT_SIGNATURE)
2047 sig = k->pkt->pkt.signature;
2048 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
2050 if (check_key_signature (keyblock, k, NULL))
2051 ; /* Signature did not verify. */
2052 else if (IS_SUBKEY_REV (sig))
2054 /* Note that this means that the date on a
2055 revocation sig does not matter - even if the
2056 binding sig is dated after the revocation sig,
2057 the subkey is still marked as revoked. This
2058 seems ok, as it is just as easy to make new
2059 subkeys rather than re-sign old ones as the
2060 problem is in the distribution. Plus, PGP (7)
2061 does this the same way. */
2062 subpk->flags.revoked = 1;
2063 sig_to_revoke_info (sig, &subpk->revoked);
2064 /* Although we could stop now, we continue to
2065 * figure out other information like the old expiration
2068 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
2070 if (sig->flags.expired)
2071 ; /* Signature has expired - ignore it. */
2074 sigdate = sig->timestamp;
2076 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2083 /* No valid key binding. */
2087 sig = signode->pkt->pkt.signature;
2088 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
2090 key_usage = parse_key_usage (sig);
2093 /* No key flags at all: get it from the algo. */
2094 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
2098 /* Check that the usage matches the usage as given by the algo. */
2099 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
2100 if (x) /* Mask it down to the actual allowed usage. */
2104 subpk->pubkey_usage = key_usage;
2106 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2107 if (p && buf32_to_u32 (p))
2108 key_expire = keytimestamp + buf32_to_u32 (p);
2111 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
2112 subpk->expiredate = key_expire;
2114 /* Algo doesn't exist. */
2115 if (openpgp_pk_test_algo (subpk->pubkey_algo))
2118 subpk->flags.valid = 1;
2120 /* Find the most recent 0x19 embedded signature on our self-sig. */
2121 if (!subpk->flags.backsig)
2125 PKT_signature *backsig = NULL;
2129 /* We do this while() since there may be other embedded
2130 signatures in the future. We only want 0x19 here. */
2132 while ((p = enum_sig_subpkt (sig->hashed,
2133 SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
2135 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2137 PKT_signature *tempsig = buf_to_sig (p, n);
2140 if (tempsig->timestamp > sigdate)
2143 free_seckey_enc (backsig);
2146 sigdate = backsig->timestamp;
2149 free_seckey_enc (tempsig);
2155 /* It is safe to have this in the unhashed area since the 0x19
2156 is located on the selfsig for convenience, not security. */
2158 while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
2161 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2163 PKT_signature *tempsig = buf_to_sig (p, n);
2166 if (tempsig->timestamp > sigdate)
2169 free_seckey_enc (backsig);
2172 sigdate = backsig->timestamp;
2175 free_seckey_enc (tempsig);
2181 /* At ths point, backsig contains the most recent 0x19 sig.
2182 Let's see if it is good. */
2184 /* 2==valid, 1==invalid, 0==didn't check */
2185 if (check_backsig (mainpk, subpk, backsig) == 0)
2186 subpk->flags.backsig = 2;
2188 subpk->flags.backsig = 1;
2190 free_seckey_enc (backsig);
2197 * Merge information from the self-signatures with the key, so that
2198 * we can later use them more easy.
2199 * The function works by first applying the self signatures to the
2200 * primary key and the to each subkey.
2201 * Here are the rules we use to decide which inormation from which
2202 * self-signature is used:
2203 * We check all self signatures or validity and ignore all invalid signatures.
2204 * All signatures are then ordered by their creation date ....
2205 * For the primary key:
2209 merge_selfsigs (KBNODE keyblock)
2213 struct revoke_info rinfo;
2214 PKT_public_key *main_pk;
2216 unsigned int mdc_feature;
2218 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2220 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
2222 log_error ("expected public key but found secret key "
2224 /* We better exit here because a public key is expected at
2225 other places too. FIXME: Figure this out earlier and
2226 don't get to here at all */
2232 merge_selfsigs_main (keyblock, &revoked, &rinfo);
2234 /* Now merge in the data from each of the subkeys. */
2235 for (k = keyblock; k; k = k->next)
2237 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2239 merge_selfsigs_subkey (keyblock, k);
2243 main_pk = keyblock->pkt->pkt.public_key;
2244 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
2246 /* If the primary key is revoked, expired, or invalid we
2247 * better set the appropriate flags on that key and all
2249 for (k = keyblock; k; k = k->next)
2251 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2252 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2254 PKT_public_key *pk = k->pkt->pkt.public_key;
2255 if (!main_pk->flags.valid)
2256 pk->flags.valid = 0;
2257 if (revoked && !pk->flags.revoked)
2259 pk->flags.revoked = revoked;
2260 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
2262 if (main_pk->has_expired)
2263 pk->has_expired = main_pk->has_expired;
2269 /* Set the preference list of all keys to those of the primary real
2270 * user ID. Note: we use these preferences when we don't know by
2271 * which user ID the key has been selected.
2272 * fixme: we should keep atoms of commonly used preferences or
2273 * use reference counting to optimize the preference lists storage.
2274 * FIXME: it might be better to use the intersection of
2276 * Do a similar thing for the MDC feature flag. */
2279 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2281 if (k->pkt->pkttype == PKT_USER_ID
2282 && !k->pkt->pkt.user_id->attrib_data
2283 && k->pkt->pkt.user_id->is_primary)
2285 prefs = k->pkt->pkt.user_id->prefs;
2286 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2290 for (k = keyblock; k; k = k->next)
2292 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2293 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2295 PKT_public_key *pk = k->pkt->pkt.public_key;
2298 pk->prefs = copy_prefs (prefs);
2299 pk->flags.mdc = mdc_feature;
2306 /* See whether the key fits our requirements and in case we do not
2307 * request the primary key, select a suitable subkey.
2309 * Returns: True when a suitable key has been found.
2311 * We have to distinguish four cases: FIXME!
2312 * 1. No usage and no primary key requested
2313 * Examples for this case are that we have a keyID to be used
2314 * for decrytion or verification.
2315 * 2. No usage but primary key requested
2316 * This is the case for all functions which work on an
2317 * entire keyblock, e.g. for editing or listing
2318 * 3. Usage and primary key requested
2320 * 4. Usage but no primary key requested
2322 * FIXME: Tell what is going to happen here and something about the rationale
2323 * Note: We don't use this function if no specific usage is requested;
2324 * This way the getkey functions can be used for plain key listings.
2326 * CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
2327 * is the key we actually found by looking at the keyid or a fingerprint and
2328 * may either point to the primary or one of the subkeys. */
2330 finish_lookup (GETKEY_CTX ctx)
2332 KBNODE keyblock = ctx->keyblock;
2334 KBNODE foundk = NULL;
2335 PKT_user_id *foundu = NULL;
2336 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2337 unsigned int req_usage = (ctx->req_usage & USAGE_MASK);
2338 /* Request the primary if we're certifying another key, and also
2339 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2340 do not understand signatures made by a signing subkey. PGP 8
2342 int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2343 ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2346 u32 curtime = make_timestamp ();
2348 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
2350 ctx->found_key = NULL;
2354 for (k = keyblock; k; k = k->next)
2358 assert (k->pkt->pkttype == PKT_PUBLIC_KEY
2359 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
2366 for (k = keyblock; k; k = k->next)
2370 assert (k->pkt->pkttype == PKT_USER_ID);
2371 foundu = k->pkt->pkt.user_id;
2377 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2378 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
2379 foundk ? "one" : "all", req_usage);
2383 latest_key = foundk ? foundk : keyblock;
2389 /* Do not look at subkeys if a certification key is requested. */
2390 if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim)
2393 /* Either start a loop or check just this one subkey. */
2394 for (k = foundk ? foundk : keyblock; k; k = nextk)
2398 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2401 nextk = NULL; /* what a hack */
2402 pk = k->pkt->pkt.public_key;
2404 log_debug ("\tchecking subkey %08lX\n",
2405 (ulong) keyid_from_pk (pk, NULL));
2406 if (!pk->flags.valid)
2409 log_debug ("\tsubkey not valid\n");
2412 if (pk->flags.revoked)
2415 log_debug ("\tsubkey has been revoked\n");
2418 if (pk->has_expired)
2421 log_debug ("\tsubkey has expired\n");
2424 if (pk->timestamp > curtime && !opt.ignore_valid_from)
2427 log_debug ("\tsubkey not yet valid\n");
2431 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2434 log_debug ("\tusage does not match: want=%x have=%x\n",
2435 req_usage, pk->pubkey_usage);
2440 log_debug ("\tsubkey might be fine\n");
2441 /* In case a key has a timestamp of 0 set, we make sure
2442 that it is used. A better change would be to compare
2443 ">=" but that might also change the selected keys and
2444 is as such a more intrusive change. */
2445 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2447 latest_date = pk->timestamp;
2453 /* Okay now try the primary key unless we want an exact
2454 * key ID match on a subkey */
2455 if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim)
2458 if (DBG_CACHE && !foundk && !req_prim)
2459 log_debug ("\tno suitable subkeys found - trying primary\n");
2460 pk = keyblock->pkt->pkt.public_key;
2461 if (!pk->flags.valid)
2464 log_debug ("\tprimary key not valid\n");
2466 else if (pk->flags.revoked)
2469 log_debug ("\tprimary key has been revoked\n");
2471 else if (pk->has_expired)
2474 log_debug ("\tprimary key has expired\n");
2476 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2479 log_debug ("\tprimary key usage does not match: "
2480 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
2485 log_debug ("\tprimary key may be used\n");
2486 latest_key = keyblock;
2487 latest_date = pk->timestamp;
2494 log_debug ("\tno suitable key found - giving up\n");
2495 return 0; /* Not found. */
2500 log_debug ("\tusing key %08lX\n",
2501 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
2505 PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2507 free_user_id (pk->user_id);
2508 pk->user_id = scopy_user_id (foundu);
2511 ctx->found_key = latest_key;
2513 if (latest_key != keyblock && opt.verbose)
2516 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
2517 log_info (_("using subkey %s instead of primary key %s\n"),
2518 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
2522 cache_user_id (keyblock);
2524 return 1; /* Found. */
2528 /* The main function to lookup a key. On success the found keyblock
2529 is stored at RET_KEYBLOCK and also in CTX. If WANT_SECRET is true
2530 a corresponding secret key is required. */
2532 lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, int want_secret)
2535 int no_suitable_key = 0;
2538 while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL)))
2540 /* If we are searching for the first key we have to make sure
2541 that the next iteration does not do an implicit reset.
2542 This can be triggered by an empty key ring. */
2543 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2544 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2546 rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
2549 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
2554 if (want_secret && agent_probe_any_secret_key (NULL, ctx->keyblock))
2555 goto skip; /* No secret key available. */
2557 /* Warning: node flag bits 0 and 1 should be preserved by
2558 * merge_selfsigs. For secret keys, premerge did tranfer the
2559 * keys to the keyblock. */
2560 merge_selfsigs (ctx->keyblock);
2561 if (finish_lookup (ctx))
2563 no_suitable_key = 0;
2567 no_suitable_key = 1;
2570 /* Release resources and continue search. */
2571 release_kbnode (ctx->keyblock);
2572 ctx->keyblock = NULL;
2576 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND
2577 && gpg_err_code (rc) != GPG_ERR_LEGACY_KEY)
2578 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
2582 *ret_keyblock = ctx->keyblock; /* Return the keyblock. */
2583 ctx->keyblock = NULL;
2585 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
2586 rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
2587 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2588 rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
2590 release_kbnode (ctx->keyblock);
2591 ctx->keyblock = NULL;
2600 * Enumerate certain secret keys. Caller must use these procedure:
2601 * 1) create a void pointer and initialize it to NULL
2602 * 2) pass this void pointer by reference to this function
2603 * and provide space for the secret key (pass a buffer for sk)
2604 * 3) call this function as long as it does not return an error.
2605 * The error code GPG_ERR_EOF indicates the end of the listing.
2606 * 4) Always call this function a last time with SK set to NULL,
2607 * so that can free it's context.
2610 enum_secret_keys (void **context, PKT_public_key *sk)
2612 gpg_error_t err = 0;
2625 /* Make a new context. */
2626 c = xtrycalloc (1, sizeof *c);
2628 return gpg_error_from_syserror ();
2634 /* Free the context. */
2635 release_kbnode (c->keyblock);
2642 return gpg_error (GPG_ERR_EOF);
2646 /* Loop until we have a keyblock. */
2647 while (!c->keyblock)
2649 /* Loop over the list of secret keys. */
2655 case 0: /* First try to use the --default-key. */
2656 if (opt.def_secret_key && *opt.def_secret_key)
2657 name = opt.def_secret_key;
2661 case 1: /* Init list of keys to try. */
2662 c->sl = opt.secret_keys_to_try;
2666 case 2: /* Get next item from list. */
2670 c->sl = c->sl->next;
2676 default: /* No more names to check - stop. */
2678 return gpg_error (GPG_ERR_EOF);
2681 while (!name || !*name);
2683 err = getkey_byname (NULL, NULL, name, 1, &c->keyblock);
2686 /* getkey_byname might return a keyblock even in the
2687 error case - I have not checked. Thus better release
2689 release_kbnode (c->keyblock);
2693 c->node = c->keyblock;
2696 /* Get the next key from the current keyblock. */
2697 for (; c->node; c->node = c->node->next)
2699 if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
2700 || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2702 copy_public_key (sk, c->node->pkt->pkt.public_key);
2703 c->node = c->node->next;
2704 return 0; /* Found. */
2708 /* Dispose the keyblock and continue. */
2709 release_kbnode (c->keyblock);
2715 /*********************************************
2716 *********** User ID printing helpers *******
2717 *********************************************/
2719 /* Return a string with a printable representation of the user_id.
2720 * this string must be freed by xfree. */
2722 get_user_id_string (u32 * keyid)
2726 /* Try it two times; second pass reads from key resources. */
2729 for (r = user_id_db; r; r = r->next)
2732 for (a = r->keyids; a; a = a->next)
2734 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
2736 return xasprintf ("%s %.*s", keystr (keyid), r->len, r->name);
2741 while (++pass < 2 && !get_pubkey (NULL, keyid));
2742 return xasprintf ("%s [?]", keystr (keyid));
2747 get_user_id_string_native (u32 * keyid)
2749 char *p = get_user_id_string (keyid);
2750 char *p2 = utf8_to_native (p, strlen (p), 0);
2757 get_long_user_id_string (u32 * keyid)
2762 /* Try it two times; second pass reads from key resources. */
2765 for (r = user_id_db; r; r = r->next)
2767 for (a = r->keyids; a; a = a->next)
2769 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
2771 return xasprintf ("%08lX%08lX %.*s",
2772 (ulong) keyid[0], (ulong) keyid[1],
2778 while (++pass < 2 && !get_pubkey (NULL, keyid));
2779 return xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
2783 /* Please try to use get_user_id_native instead of this one. */
2785 get_user_id (u32 * keyid, size_t * rn)
2791 /* Try it two times; second pass reads from key resources. */
2794 for (r = user_id_db; r; r = r->next)
2797 for (a = r->keyids; a; a = a->next)
2799 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
2801 /* An empty string as user id is possible. Make
2802 sure that the malloc allocates one byte and does
2804 p = xmalloc (r->len? r->len : 1);
2805 memcpy (p, r->name, r->len);
2812 while (++pass < 2 && !get_pubkey (NULL, keyid));
2813 p = xstrdup (user_id_not_found_utf8 ());
2818 /* Please try to use get_user_id_byfpr_native instead of this one. */
2820 get_user_id_native (u32 * keyid)
2823 char *p = get_user_id (keyid, &rn);
2824 char *p2 = utf8_to_native (p, rn, 0);
2830 /* Return a user id from the caching by looking it up using the FPR
2831 which mustbe of size MAX_FINGERPRINT_LEN. */
2833 get_user_id_byfpr (const byte *fpr, size_t *rn)
2839 /* Try it two times; second pass reads from key resources. */
2842 for (r = user_id_db; r; r = r->next)
2845 for (a = r->keyids; a; a = a->next)
2847 if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
2849 /* An empty string as user id is possible. Make
2850 sure that the malloc allocates one byte and does
2852 p = xmalloc (r->len? r->len : 1);
2853 memcpy (p, r->name, r->len);
2860 while (++pass < 2 && !get_pubkey_byfpr (NULL, fpr));
2861 p = xstrdup (user_id_not_found_utf8 ());
2867 get_user_id_byfpr_native (const byte *fpr)
2870 char *p = get_user_id_byfpr (fpr, &rn);
2871 char *p2 = utf8_to_native (p, rn, 0);
2879 get_ctx_handle (GETKEY_CTX ctx)
2881 return ctx->kr_handle;
2885 free_akl (struct akl *akl)
2888 free_keyserver_spec (akl->spec);
2896 while (opt.auto_key_locate)
2898 struct akl *akl2 = opt.auto_key_locate;
2899 opt.auto_key_locate = opt.auto_key_locate->next;
2904 /* Returns false on error. */
2906 parse_auto_key_locate (char *options)
2910 while ((tok = optsep (&options)))
2912 struct akl *akl, *check, *last = NULL;
2918 akl = xmalloc_clear (sizeof (*akl));
2920 if (ascii_strcasecmp (tok, "clear") == 0)
2923 free_akl (opt.auto_key_locate);
2924 opt.auto_key_locate = NULL;
2927 else if (ascii_strcasecmp (tok, "nodefault") == 0)
2928 akl->type = AKL_NODEFAULT;
2929 else if (ascii_strcasecmp (tok, "local") == 0)
2930 akl->type = AKL_LOCAL;
2931 else if (ascii_strcasecmp (tok, "ldap") == 0)
2932 akl->type = AKL_LDAP;
2933 else if (ascii_strcasecmp (tok, "keyserver") == 0)
2934 akl->type = AKL_KEYSERVER;
2936 else if (ascii_strcasecmp (tok, "cert") == 0)
2937 akl->type = AKL_CERT;
2940 else if (ascii_strcasecmp (tok, "pka") == 0)
2941 akl->type = AKL_PKA;
2943 else if ((akl->spec = parse_keyserver_uri (tok, 1)))
2944 akl->type = AKL_SPEC;
2951 /* We must maintain the order the user gave us */
2952 for (check = opt.auto_key_locate; check;
2953 last = check, check = check->next)
2955 /* Check for duplicates */
2956 if (check->type == akl->type
2957 && (akl->type != AKL_SPEC
2958 || (akl->type == AKL_SPEC
2959 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
2972 opt.auto_key_locate = akl;
2980 /* Return true if a secret key or secret subkey is available for one
2981 of the public keys in KEYBLOCK. */
2983 have_any_secret_key (ctrl_t ctrl, kbnode_t keyblock)
2987 for (node = keyblock; node; node = node->next)
2988 if ((node->pkt->pkttype == PKT_PUBLIC_KEY
2989 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2990 && !agent_probe_secret_key (ctrl, node->pkt->pkt.public_key))
2996 /* Return true if a secret key is available for the public key with
2997 * the given KEYID. This is just a fast check and does not tell us
2998 * whether the secret key is valid. It merely tells os whether there
2999 * is some secret key. */
3001 have_secret_key_with_kid (u32 *keyid)
3005 KEYDB_SEARCH_DESC desc;
3010 kdbhd = keydb_new ();
3011 memset (&desc, 0, sizeof desc);
3012 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
3013 desc.u.kid[0] = keyid[0];
3014 desc.u.kid[1] = keyid[1];
3015 while (!result && !(err = keydb_search (kdbhd, &desc, 1, NULL)))
3017 err = keydb_get_keyblock (kdbhd, &keyblock);
3020 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
3024 for (node = keyblock; node; node = node->next)
3026 /* Bit 0 of the flags is set if the search found the key
3027 using that key or subkey. */
3028 if ((node->flag & 1))
3030 assert (node->pkt->pkttype == PKT_PUBLIC_KEY
3031 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3033 if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
3040 release_kbnode (keyblock);
3042 keydb_release (kdbhd);