1 /* getkey.c - Get a key from the database
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3 * 2007, 2008, 2010 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
37 #include "keyserver-internal.h"
38 #include "call-agent.h"
40 #include "mbox-util.h"
42 #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
43 #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
45 #if MAX_PK_CACHE_ENTRIES < 2
46 #error We need the cache for key creation
52 int want_secret; /* The caller requested only secret keys. */
55 KBNODE found_key; /* Pointer into some keyblock. */
56 strlist_t extra_list; /* Will be freed when releasing the context. */
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)
119 es_fprintf (es_stderr,
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. The caller need to
972 * prove an allocated public key object at PK. If R_KEYBLOCK is not
973 * NULL the entire keyblock is stored there and the caller needs to
974 * call release_kbnode() on it. Note that this function does an exact
975 * search and thus the public key stored at PK may be a copy of a
979 * We should replace this with the _byname function. This can be done
980 * by creating a userID conforming to the unified fingerprint style.
983 get_pubkey_byfprint (PKT_public_key *pk, kbnode_t *r_keyblock,
984 const byte * fprint, size_t fprint_len)
991 if (fprint_len == 20 || fprint_len == 16)
993 struct getkey_ctx_s ctx;
996 memset (&ctx, 0, sizeof ctx);
998 ctx.not_allocated = 1;
999 ctx.kr_handle = keydb_new ();
1001 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1002 : KEYDB_SEARCH_MODE_FPR20;
1003 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1004 rc = lookup (&ctx, &kb, 0);
1007 pk_from_block (&ctx, pk, kb);
1014 release_kbnode (kb);
1015 get_pubkey_end (&ctx);
1018 rc = GPG_ERR_GENERAL; /* Oops */
1023 /* Get a public key and store it into the allocated pk. This function
1024 differs from get_pubkey_byfprint() in that it does not do a check
1025 of the key to avoid recursion. It should be used only in very
1026 certain cases. PK may be NULL to check just for the existance of
1029 get_pubkey_byfprint_fast (PKT_public_key * pk,
1030 const byte * fprint, size_t fprint_len)
1035 byte fprbuf[MAX_FINGERPRINT_LEN];
1038 for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1039 fprbuf[i] = fprint[i];
1040 while (i < MAX_FINGERPRINT_LEN)
1044 rc = keydb_search_fpr (hd, fprbuf);
1045 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1048 return GPG_ERR_NO_PUBKEY;
1050 rc = keydb_get_keyblock (hd, &keyblock);
1054 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1055 return GPG_ERR_NO_PUBKEY;
1058 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1059 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1061 copy_public_key (pk, keyblock->pkt->pkt.public_key);
1062 release_kbnode (keyblock);
1064 /* Not caching key here since it won't have all of the fields
1071 /* Search for a key with the given fingerprint and return the
1072 * complete keyblock which may have more than only this key. */
1074 get_keyblock_byfprint (KBNODE * ret_keyblock, const byte * fprint,
1079 if (fprint_len == 20 || fprint_len == 16)
1081 struct getkey_ctx_s ctx;
1083 memset (&ctx, 0, sizeof ctx);
1084 ctx.not_allocated = 1;
1085 ctx.kr_handle = keydb_new ();
1087 ctx.items[0].mode = (fprint_len == 16
1088 ? KEYDB_SEARCH_MODE_FPR16
1089 : KEYDB_SEARCH_MODE_FPR20);
1090 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1091 rc = lookup (&ctx, ret_keyblock, 0);
1092 get_pubkey_end (&ctx);
1095 rc = GPG_ERR_GENERAL; /* Oops */
1101 /* Get a secret key by NAME and store it into PK. If NAME is NULL use
1102 * the default key. This functions checks that a corresponding secret
1103 * key is available. With no secret key it does not succeeed. */
1105 get_seckey_byname (PKT_public_key *pk, const char *name)
1108 strlist_t namelist = NULL;
1109 int include_unusable = 1;
1111 /* If we have no name, try to use the default secret key. If we
1112 have no default, we'll use the first usable one. */
1114 if (!name && opt.def_secret_key && *opt.def_secret_key)
1115 add_to_strlist (&namelist, opt.def_secret_key);
1117 add_to_strlist (&namelist, name);
1119 include_unusable = 0;
1121 err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
1123 free_strlist (namelist);
1130 /* Search for a key with the given fingerprint.
1132 * We should replace this with the _byname function. This can be done
1133 * by creating a userID conforming to the unified fingerprint style. */
1135 get_seckey_byfprint (PKT_public_key *pk, const byte * fprint, size_t fprint_len)
1139 if (fprint_len == 20 || fprint_len == 16)
1141 struct getkey_ctx_s ctx;
1144 memset (&ctx, 0, sizeof ctx);
1146 ctx.not_allocated = 1;
1147 ctx.kr_handle = keydb_new ();
1149 ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1150 : KEYDB_SEARCH_MODE_FPR20;
1151 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1152 err = lookup (&ctx, &kb, 1);
1154 pk_from_block (&ctx, pk, kb);
1155 release_kbnode (kb);
1156 get_pubkey_end (&ctx);
1159 err = gpg_error (GPG_ERR_BUG);
1164 /* Search for a secret key with the given fingerprint and return the
1165 complete keyblock which may have more than only this key. Return
1166 an error if no corresponding secret key is available. */
1168 get_seckeyblock_byfprint (kbnode_t *ret_keyblock,
1169 const byte *fprint, size_t fprint_len)
1172 struct getkey_ctx_s ctx;
1174 if (fprint_len != 20 && fprint_len == 16)
1175 return gpg_error (GPG_ERR_BUG);
1177 memset (&ctx, 0, sizeof ctx);
1178 ctx.not_allocated = 1;
1179 ctx.kr_handle = keydb_new ();
1181 ctx.items[0].mode = (fprint_len == 16
1182 ? KEYDB_SEARCH_MODE_FPR16 : KEYDB_SEARCH_MODE_FPR20);
1183 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1184 err = lookup (&ctx, ret_keyblock, 1);
1185 get_pubkey_end (&ctx);
1192 /* The new function to return a key.
1193 FIXME: Document it. */
1195 getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
1196 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
1198 return key_byname (retctx, names, pk, want_secret, 1,
1199 ret_keyblock, NULL);
1203 /* Get a key by name and store it into PK if that is not NULL. If
1204 * RETCTX is not NULL return the search context which needs to be
1205 * released by the caller using getkey_end. If NAME is NULL use the
1206 * default key (see below). On success and if RET_KEYBLOCK is not
1207 * NULL the found keyblock is stored at this address. WANT_SECRET
1208 * passed as true requires that a secret key is available for the
1211 * If WANT_SECRET is true and NAME is NULL and a default key has been
1212 * defined that defined key is used. In all other cases the first
1213 * available key is used.
1215 * FIXME: Explain what is up with unusable keys.
1217 * FIXME: We also have the get_pubkey_byname function which has a
1218 * different semantic. Should be merged with this one.
1221 getkey_byname (getkey_ctx_t *retctx, PKT_public_key *pk,
1222 const char *name, int want_secret, kbnode_t *ret_keyblock)
1225 strlist_t namelist = NULL;
1226 int with_unusable = 1;
1228 if (want_secret && !name && opt.def_secret_key && *opt.def_secret_key)
1229 add_to_strlist (&namelist, opt.def_secret_key);
1231 add_to_strlist (&namelist, name);
1235 err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
1236 ret_keyblock, NULL);
1238 /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
1239 WANT_SECRET has been used. */
1241 free_strlist (namelist);
1247 /* The new function to return the next key. */
1249 getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
1251 int rc; /* Fixme: Make sure this is proper gpg_error */
1253 /* We need to disable the caching so that for an exact key search we
1254 won't get the result back from the cache and thus end up in an
1255 endless loop. Disabling this here is sufficient because although
1256 the result has been cached, if won't be used then. */
1257 keydb_disable_caching (ctx->kr_handle);
1259 rc = lookup (ctx, ret_keyblock, ctx->want_secret);
1260 if (!rc && pk && ret_keyblock)
1261 pk_from_block (ctx, pk, *ret_keyblock);
1267 /* The new function to finish a key listing. */
1269 getkey_end (getkey_ctx_t ctx)
1273 memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
1274 keydb_release (ctx->kr_handle);
1275 free_strlist (ctx->extra_list);
1276 if (!ctx->not_allocated)
1283 /************************************************
1284 ************* Merging stuff ********************
1285 ************************************************/
1287 /* Set the mainkey_id fields for all keys in KEYBLOCK. This is
1288 usually done by merge_selfsigs but at some places we only need the
1289 main_kid but the the full merging. The function also guarantees
1290 that all pk->keyids are computed. */
1292 setup_main_keyids (kbnode_t keyblock)
1294 u32 kid[2], mainkid[2];
1295 kbnode_t kbctx, node;
1298 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1300 pk = keyblock->pkt->pkt.public_key;
1302 keyid_from_pk (pk, mainkid);
1303 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1305 if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
1306 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1308 pk = node->pkt->pkt.public_key;
1309 keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */
1310 if (!pk->main_keyid[0] && !pk->main_keyid[1])
1312 pk->main_keyid[0] = mainkid[0];
1313 pk->main_keyid[1] = mainkid[1];
1319 /* Merge all self-signatures with the keys. */
1321 merge_keys_and_selfsig (KBNODE keyblock)
1325 else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
1326 merge_selfsigs (keyblock);
1328 log_debug ("FIXME: merging secret key blocks is not anymore available\n");
1333 parse_key_usage (PKT_signature * sig)
1340 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
1343 /* First octet of the keyflags. */
1348 key_usage |= PUBKEY_USAGE_CERT;
1354 key_usage |= PUBKEY_USAGE_SIG;
1358 /* We do not distinguish between encrypting communications and
1359 encrypting storage. */
1360 if (flags & (0x04 | 0x08))
1362 key_usage |= PUBKEY_USAGE_ENC;
1363 flags &= ~(0x04 | 0x08);
1368 key_usage |= PUBKEY_USAGE_AUTH;
1373 key_usage |= PUBKEY_USAGE_UNKNOWN;
1376 key_usage |= PUBKEY_USAGE_NONE;
1378 else if (p) /* Key flags of length zero. */
1379 key_usage |= PUBKEY_USAGE_NONE;
1381 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1382 capability that we do not handle. This serves to distinguish
1383 between a zero key usage which we handle as the default
1384 capabilities for that algorithm, and a usage that we do not
1385 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
1386 key_flags have been given but they do not specify any usage. */
1392 /* Apply information from SIGNODE (which is the valid self-signature
1393 * associated with that UID) to the UIDNODE:
1394 * - wether the UID has been revoked
1395 * - assumed creation date of the UID
1396 * - temporary store the keyflags here
1397 * - temporary store the key expiration time here
1398 * - mark whether the primary user ID flag hat been set.
1399 * - store the preferences
1402 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
1404 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1405 PKT_signature *sig = signode->pkt->pkt.signature;
1406 const byte *p, *sym, *hash, *zip;
1407 size_t n, nsym, nhash, nzip;
1409 sig->flags.chosen_selfsig = 1;/* We chose this one. */
1410 uid->created = 0; /* Not created == invalid. */
1411 if (IS_UID_REV (sig))
1413 uid->is_revoked = 1;
1414 return; /* Has been revoked. */
1417 uid->is_revoked = 0;
1419 uid->expiredate = sig->expiredate;
1421 if (sig->flags.expired)
1423 uid->is_expired = 1;
1424 return; /* Has expired. */
1427 uid->is_expired = 0;
1429 uid->created = sig->timestamp; /* This one is okay. */
1430 uid->selfsigversion = sig->version;
1431 /* If we got this far, it's not expired :) */
1432 uid->is_expired = 0;
1434 /* Store the key flags in the helper variable for later processing. */
1435 uid->help_key_usage = parse_key_usage (sig);
1437 /* Ditto for the key expiration. */
1438 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1439 if (p && buf32_to_u32 (p))
1440 uid->help_key_expire = keycreated + buf32_to_u32 (p);
1442 uid->help_key_expire = 0;
1444 /* Set the primary user ID flag - we will later wipe out some
1445 * of them to only have one in our keyblock. */
1446 uid->is_primary = 0;
1447 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
1449 uid->is_primary = 2;
1451 /* We could also query this from the unhashed area if it is not in
1452 * the hased area and then later try to decide which is the better
1453 * there should be no security problem with this.
1454 * For now we only look at the hashed one. */
1456 /* Now build the preferences list. These must come from the
1457 hashed section so nobody can modify the ciphers a key is
1458 willing to accept. */
1459 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
1462 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
1465 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
1470 n = nsym + nhash + nzip;
1475 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
1477 for (; nsym; nsym--, n++)
1479 uid->prefs[n].type = PREFTYPE_SYM;
1480 uid->prefs[n].value = *sym++;
1482 for (; nhash; nhash--, n++)
1484 uid->prefs[n].type = PREFTYPE_HASH;
1485 uid->prefs[n].value = *hash++;
1487 for (; nzip; nzip--, n++)
1489 uid->prefs[n].type = PREFTYPE_ZIP;
1490 uid->prefs[n].value = *zip++;
1492 uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
1493 uid->prefs[n].value = 0;
1496 /* See whether we have the MDC feature. */
1498 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1499 if (p && n && (p[0] & 0x01))
1502 /* And the keyserver modify flag. */
1503 uid->flags.ks_modify = 1;
1504 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1505 if (p && n && (p[0] & 0x80))
1506 uid->flags.ks_modify = 0;
1510 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
1512 rinfo->date = sig->timestamp;
1513 rinfo->algo = sig->pubkey_algo;
1514 rinfo->keyid[0] = sig->keyid[0];
1515 rinfo->keyid[1] = sig->keyid[1];
1519 /* Note that R_REVOKED may be set to 0, 1 or 2. */
1521 merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
1522 struct revoke_info *rinfo)
1524 PKT_public_key *pk = NULL;
1527 u32 sigdate, uiddate, uiddate2;
1528 KBNODE signode, uidnode, uidnode2;
1529 u32 curtime = make_timestamp ();
1530 unsigned int key_usage = 0;
1531 u32 keytimestamp = 0;
1533 int key_expire_seen = 0;
1534 byte sigversion = 0;
1537 memset (rinfo, 0, sizeof (*rinfo));
1539 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1541 pk = keyblock->pkt->pkt.public_key;
1542 keytimestamp = pk->timestamp;
1544 keyid_from_pk (pk, kid);
1545 pk->main_keyid[0] = kid[0];
1546 pk->main_keyid[1] = kid[1];
1548 if (pk->version < 4)
1550 /* Before v4 the key packet itself contains the expiration date
1551 * and there was no way to change it, so we start with the one
1552 * from the key packet. */
1553 key_expire = pk->max_expiredate;
1554 key_expire_seen = 1;
1557 /* First pass: Find the latest direct key self-signature. We assume
1558 * that the newest one overrides all others. */
1560 /* In case this key was already merged. */
1566 sigdate = 0; /* Helper variable to find the latest signature. */
1567 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
1569 if (k->pkt->pkttype == PKT_SIGNATURE)
1571 PKT_signature *sig = k->pkt->pkt.signature;
1572 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1574 if (check_key_signature (keyblock, k, NULL))
1575 ; /* Signature did not verify. */
1576 else if (IS_KEY_REV (sig))
1578 /* Key has been revoked - there is no way to
1579 * override such a revocation, so we theoretically
1580 * can stop now. We should not cope with expiration
1581 * times for revocations here because we have to
1582 * assume that an attacker can generate all kinds of
1583 * signatures. However due to the fact that the key
1584 * has been revoked it does not harm either and by
1585 * continuing we gather some more info on that
1588 sig_to_revoke_info (sig, rinfo);
1590 else if (IS_KEY_SIG (sig))
1592 /* Add any revocation keys onto the pk. This is
1593 particularly interesting since we normally only
1594 get data from the most recent 1F signature, but
1595 you need multiple 1F sigs to properly handle
1596 revocation keys (PGP does it this way, and a
1597 revocation key could be sensitive and hence in a
1598 different signature). */
1604 xrealloc (pk->revkey, sizeof (struct revocation_key) *
1605 (pk->numrevkeys + sig->numrevkeys));
1607 for (i = 0; i < sig->numrevkeys; i++)
1608 memcpy (&pk->revkey[pk->numrevkeys++],
1610 sizeof (struct revocation_key));
1613 if (sig->timestamp >= sigdate)
1615 if (sig->flags.expired)
1616 ; /* Signature has expired - ignore it. */
1619 sigdate = sig->timestamp;
1621 if (sig->version > sigversion)
1622 sigversion = sig->version;
1631 /* Remove dupes from the revocation keys. */
1635 int i, j, x, changed = 0;
1637 for (i = 0; i < pk->numrevkeys; i++)
1639 for (j = i + 1; j < pk->numrevkeys; j++)
1641 if (memcmp (&pk->revkey[i], &pk->revkey[j],
1642 sizeof (struct revocation_key)) == 0)
1646 for (x = j; x < pk->numrevkeys - 1; x++)
1647 pk->revkey[x] = pk->revkey[x + 1];
1657 pk->revkey = xrealloc (pk->revkey,
1659 sizeof (struct revocation_key));
1664 /* Some information from a direct key signature take precedence
1665 * over the same information given in UID sigs. */
1666 PKT_signature *sig = signode->pkt->pkt.signature;
1669 key_usage = parse_key_usage (sig);
1671 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1672 if (p && buf32_to_u32 (p))
1674 key_expire = keytimestamp + buf32_to_u32 (p);
1675 key_expire_seen = 1;
1678 /* Mark that key as valid: One direct key signature should
1679 * render a key as valid. */
1680 pk->flags.valid = 1;
1683 /* Pass 1.5: Look for key revocation signatures that were not made
1684 by the key (i.e. did a revocation key issue a revocation for
1685 us?). Only bother to do this if there is a revocation key in the
1686 first place and we're not revoked already. */
1688 if (!*r_revoked && pk->revkey)
1689 for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
1691 if (k->pkt->pkttype == PKT_SIGNATURE)
1693 PKT_signature *sig = k->pkt->pkt.signature;
1695 if (IS_KEY_REV (sig) &&
1696 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
1698 int rc = check_revocation_keys (pk, sig);
1702 sig_to_revoke_info (sig, rinfo);
1703 /* Don't continue checking since we can't be any
1704 more revoked than this. */
1707 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
1708 pk->flags.maybe_revoked = 1;
1710 /* A failure here means the sig did not verify, was
1711 not issued by a revocation key, or a revocation
1712 key loop was broken. If a revocation key isn't
1713 findable, however, the key might be revoked and
1714 we don't know it. */
1716 /* TODO: In the future handle subkey and cert
1717 revocations? PGP doesn't, but it's in 2440. */
1722 /* Second pass: Look at the self-signature of all user IDs. */
1723 signode = uidnode = NULL;
1724 sigdate = 0; /* Helper variable to find the latest signature in one UID. */
1725 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1727 if (k->pkt->pkttype == PKT_USER_ID)
1729 if (uidnode && signode)
1731 fixup_uidnode (uidnode, signode, keytimestamp);
1732 pk->flags.valid = 1;
1738 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1740 PKT_signature *sig = k->pkt->pkt.signature;
1741 if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1743 if (check_key_signature (keyblock, k, NULL))
1744 ; /* signature did not verify */
1745 else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
1746 && sig->timestamp >= sigdate)
1748 /* Note: we allow to invalidate cert revocations
1749 * by a newer signature. An attacker can't use this
1750 * because a key should be revoced with a key revocation.
1751 * The reason why we have to allow for that is that at
1752 * one time an email address may become invalid but later
1753 * the same email address may become valid again (hired,
1754 * fired, hired again). */
1756 sigdate = sig->timestamp;
1758 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
1759 if (sig->version > sigversion)
1760 sigversion = sig->version;
1765 if (uidnode && signode)
1767 fixup_uidnode (uidnode, signode, keytimestamp);
1768 pk->flags.valid = 1;
1771 /* If the key isn't valid yet, and we have
1772 --allow-non-selfsigned-uid set, then force it valid. */
1773 if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
1776 log_info (_("Invalid key %s made valid by"
1777 " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
1778 pk->flags.valid = 1;
1781 /* The key STILL isn't valid, so try and find an ultimately
1782 trusted signature. */
1783 if (!pk->flags.valid)
1787 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1790 if (k->pkt->pkttype == PKT_USER_ID)
1792 else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1794 PKT_signature *sig = k->pkt->pkt.signature;
1796 if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
1798 PKT_public_key *ultimate_pk;
1800 ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
1802 /* We don't want to use the full get_pubkey to
1803 avoid infinite recursion in certain cases.
1804 There is no reason to check that an ultimately
1805 trusted key is still valid - if it has been
1806 revoked or the user should also renmove the
1807 ultimate trust flag. */
1808 if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
1809 && check_key_signature2 (keyblock, k, ultimate_pk,
1810 NULL, NULL, NULL, NULL) == 0
1811 && get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
1813 free_public_key (ultimate_pk);
1814 pk->flags.valid = 1;
1818 free_public_key (ultimate_pk);
1824 /* Record the highest selfsig version so we know if this is a v3
1825 key through and through, or a v3 key with a v4 selfsig
1826 somewhere. This is useful in a few places to know if the key
1827 must be treated as PGP2-style or OpenPGP-style. Note that a
1828 selfsig revocation with a higher version number will also raise
1829 this value. This is okay since such a revocation must be
1830 issued by the user (i.e. it cannot be issued by someone else to
1831 modify the key behavior.) */
1833 pk->selfsigversion = sigversion;
1835 /* Now that we had a look at all user IDs we can now get some information
1836 * from those user IDs.
1841 /* Find the latest user ID with key flags set. */
1842 uiddate = 0; /* Helper to find the latest user ID. */
1843 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1846 if (k->pkt->pkttype == PKT_USER_ID)
1848 PKT_user_id *uid = k->pkt->pkt.user_id;
1849 if (uid->help_key_usage && uid->created > uiddate)
1851 key_usage = uid->help_key_usage;
1852 uiddate = uid->created;
1859 /* No key flags at all: get it from the algo. */
1860 key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
1864 /* Check that the usage matches the usage as given by the algo. */
1865 int x = openpgp_pk_algo_usage (pk->pubkey_algo);
1866 if (x) /* Mask it down to the actual allowed usage. */
1870 /* Whatever happens, it's a primary key, so it can certify. */
1871 pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
1873 if (!key_expire_seen)
1875 /* Find the latest valid user ID with a key expiration set
1876 * Note, that this may be a different one from the above because
1877 * some user IDs may have no expiration date set. */
1879 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1882 if (k->pkt->pkttype == PKT_USER_ID)
1884 PKT_user_id *uid = k->pkt->pkt.user_id;
1885 if (uid->help_key_expire && uid->created > uiddate)
1887 key_expire = uid->help_key_expire;
1888 uiddate = uid->created;
1894 /* Currently only v3 keys have a maximum expiration date, but I'll
1895 bet v5 keys get this feature again. */
1897 || (pk->max_expiredate && key_expire > pk->max_expiredate))
1898 key_expire = pk->max_expiredate;
1900 pk->has_expired = key_expire >= curtime ? 0 : key_expire;
1901 pk->expiredate = key_expire;
1903 /* Fixme: we should see how to get rid of the expiretime fields but
1904 * this needs changes at other places too. */
1906 /* And now find the real primary user ID and delete all others. */
1907 uiddate = uiddate2 = 0;
1908 uidnode = uidnode2 = NULL;
1909 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1911 if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
1913 PKT_user_id *uid = k->pkt->pkt.user_id;
1914 if (uid->is_primary)
1916 if (uid->created > uiddate)
1918 uiddate = uid->created;
1921 else if (uid->created == uiddate && uidnode)
1923 /* The dates are equal, so we need to do a
1924 different (and arbitrary) comparison. This
1925 should rarely, if ever, happen. It's good to
1926 try and guarantee that two different GnuPG
1927 users with two different keyrings at least pick
1928 the same primary. */
1929 if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
1935 if (uid->created > uiddate2)
1937 uiddate2 = uid->created;
1940 else if (uid->created == uiddate2 && uidnode2)
1942 if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
1950 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1953 if (k->pkt->pkttype == PKT_USER_ID &&
1954 !k->pkt->pkt.user_id->attrib_data)
1956 PKT_user_id *uid = k->pkt->pkt.user_id;
1958 uid->is_primary = 0;
1964 /* None is flagged primary - use the latest user ID we have,
1965 and disambiguate with the arbitrary packet comparison. */
1966 uidnode2->pkt->pkt.user_id->is_primary = 1;
1970 /* None of our uids were self-signed, so pick the one that
1971 sorts first to be the primary. This is the best we can do
1972 here since there are no self sigs to date the uids. */
1976 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1979 if (k->pkt->pkttype == PKT_USER_ID
1980 && !k->pkt->pkt.user_id->attrib_data)
1985 uidnode->pkt->pkt.user_id->is_primary = 1;
1990 if (cmp_user_ids (k->pkt->pkt.user_id,
1991 uidnode->pkt->pkt.user_id) > 0)
1993 uidnode->pkt->pkt.user_id->is_primary = 0;
1995 uidnode->pkt->pkt.user_id->is_primary = 1;
1998 k->pkt->pkt.user_id->is_primary = 0; /* just to be
2006 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
2007 Caller must free the signature when they are done. */
2008 static PKT_signature *
2009 buf_to_sig (const byte * buf, size_t len)
2011 PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
2012 IOBUF iobuf = iobuf_temp_with_content (buf, len);
2013 int save_mode = set_packet_list_mode (0);
2015 if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
2021 set_packet_list_mode (save_mode);
2022 iobuf_close (iobuf);
2028 merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
2030 PKT_public_key *mainpk = NULL, *subpk = NULL;
2036 u32 curtime = make_timestamp ();
2037 unsigned int key_usage = 0;
2038 u32 keytimestamp = 0;
2042 if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2044 mainpk = keyblock->pkt->pkt.public_key;
2045 if (mainpk->version < 4)
2046 return;/* (actually this should never happen) */
2047 keyid_from_pk (mainpk, mainkid);
2048 subpk = subnode->pkt->pkt.public_key;
2049 keytimestamp = subpk->timestamp;
2051 subpk->flags.valid = 0;
2052 subpk->main_keyid[0] = mainpk->main_keyid[0];
2053 subpk->main_keyid[1] = mainpk->main_keyid[1];
2055 /* Find the latest key binding self-signature. */
2057 sigdate = 0; /* Helper to find the latest signature. */
2058 for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2061 if (k->pkt->pkttype == PKT_SIGNATURE)
2063 sig = k->pkt->pkt.signature;
2064 if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
2066 if (check_key_signature (keyblock, k, NULL))
2067 ; /* Signature did not verify. */
2068 else if (IS_SUBKEY_REV (sig))
2070 /* Note that this means that the date on a
2071 revocation sig does not matter - even if the
2072 binding sig is dated after the revocation sig,
2073 the subkey is still marked as revoked. This
2074 seems ok, as it is just as easy to make new
2075 subkeys rather than re-sign old ones as the
2076 problem is in the distribution. Plus, PGP (7)
2077 does this the same way. */
2078 subpk->flags.revoked = 1;
2079 sig_to_revoke_info (sig, &subpk->revoked);
2080 /* Although we could stop now, we continue to
2081 * figure out other information like the old expiration
2084 else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
2086 if (sig->flags.expired)
2087 ; /* Signature has expired - ignore it. */
2090 sigdate = sig->timestamp;
2092 signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2099 /* No valid key binding. */
2103 sig = signode->pkt->pkt.signature;
2104 sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
2106 key_usage = parse_key_usage (sig);
2109 /* No key flags at all: get it from the algo. */
2110 key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
2114 /* Check that the usage matches the usage as given by the algo. */
2115 int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
2116 if (x) /* Mask it down to the actual allowed usage. */
2120 subpk->pubkey_usage = key_usage;
2122 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2123 if (p && buf32_to_u32 (p))
2124 key_expire = keytimestamp + buf32_to_u32 (p);
2127 subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
2128 subpk->expiredate = key_expire;
2130 /* Algo doesn't exist. */
2131 if (openpgp_pk_test_algo (subpk->pubkey_algo))
2134 subpk->flags.valid = 1;
2136 /* Find the most recent 0x19 embedded signature on our self-sig. */
2137 if (!subpk->flags.backsig)
2141 PKT_signature *backsig = NULL;
2145 /* We do this while() since there may be other embedded
2146 signatures in the future. We only want 0x19 here. */
2148 while ((p = enum_sig_subpkt (sig->hashed,
2149 SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
2151 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2153 PKT_signature *tempsig = buf_to_sig (p, n);
2156 if (tempsig->timestamp > sigdate)
2159 free_seckey_enc (backsig);
2162 sigdate = backsig->timestamp;
2165 free_seckey_enc (tempsig);
2171 /* It is safe to have this in the unhashed area since the 0x19
2172 is located on the selfsig for convenience, not security. */
2174 while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
2177 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2179 PKT_signature *tempsig = buf_to_sig (p, n);
2182 if (tempsig->timestamp > sigdate)
2185 free_seckey_enc (backsig);
2188 sigdate = backsig->timestamp;
2191 free_seckey_enc (tempsig);
2197 /* At ths point, backsig contains the most recent 0x19 sig.
2198 Let's see if it is good. */
2200 /* 2==valid, 1==invalid, 0==didn't check */
2201 if (check_backsig (mainpk, subpk, backsig) == 0)
2202 subpk->flags.backsig = 2;
2204 subpk->flags.backsig = 1;
2206 free_seckey_enc (backsig);
2213 * Merge information from the self-signatures with the key, so that
2214 * we can later use them more easy.
2215 * The function works by first applying the self signatures to the
2216 * primary key and the to each subkey.
2217 * Here are the rules we use to decide which inormation from which
2218 * self-signature is used:
2219 * We check all self signatures or validity and ignore all invalid signatures.
2220 * All signatures are then ordered by their creation date ....
2221 * For the primary key:
2225 merge_selfsigs (KBNODE keyblock)
2229 struct revoke_info rinfo;
2230 PKT_public_key *main_pk;
2232 unsigned int mdc_feature;
2234 if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2236 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
2238 log_error ("expected public key but found secret key "
2240 /* We better exit here because a public key is expected at
2241 other places too. FIXME: Figure this out earlier and
2242 don't get to here at all */
2248 merge_selfsigs_main (keyblock, &revoked, &rinfo);
2250 /* Now merge in the data from each of the subkeys. */
2251 for (k = keyblock; k; k = k->next)
2253 if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2255 merge_selfsigs_subkey (keyblock, k);
2259 main_pk = keyblock->pkt->pkt.public_key;
2260 if (revoked || main_pk->has_expired || !main_pk->flags.valid)
2262 /* If the primary key is revoked, expired, or invalid we
2263 * better set the appropriate flags on that key and all
2265 for (k = keyblock; k; k = k->next)
2267 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2268 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2270 PKT_public_key *pk = k->pkt->pkt.public_key;
2271 if (!main_pk->flags.valid)
2272 pk->flags.valid = 0;
2273 if (revoked && !pk->flags.revoked)
2275 pk->flags.revoked = revoked;
2276 memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
2278 if (main_pk->has_expired)
2279 pk->has_expired = main_pk->has_expired;
2285 /* Set the preference list of all keys to those of the primary real
2286 * user ID. Note: we use these preferences when we don't know by
2287 * which user ID the key has been selected.
2288 * fixme: we should keep atoms of commonly used preferences or
2289 * use reference counting to optimize the preference lists storage.
2290 * FIXME: it might be better to use the intersection of
2292 * Do a similar thing for the MDC feature flag. */
2295 for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2297 if (k->pkt->pkttype == PKT_USER_ID
2298 && !k->pkt->pkt.user_id->attrib_data
2299 && k->pkt->pkt.user_id->is_primary)
2301 prefs = k->pkt->pkt.user_id->prefs;
2302 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2306 for (k = keyblock; k; k = k->next)
2308 if (k->pkt->pkttype == PKT_PUBLIC_KEY
2309 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2311 PKT_public_key *pk = k->pkt->pkt.public_key;
2314 pk->prefs = copy_prefs (prefs);
2315 pk->flags.mdc = mdc_feature;
2322 /* See whether the key fits our requirements and in case we do not
2323 * request the primary key, select a suitable subkey.
2325 * Returns: True when a suitable key has been found.
2327 * We have to distinguish four cases: FIXME!
2328 * 1. No usage and no primary key requested
2329 * Examples for this case are that we have a keyID to be used
2330 * for decrytion or verification.
2331 * 2. No usage but primary key requested
2332 * This is the case for all functions which work on an
2333 * entire keyblock, e.g. for editing or listing
2334 * 3. Usage and primary key requested
2336 * 4. Usage but no primary key requested
2338 * FIXME: Tell what is going to happen here and something about the rationale
2339 * Note: We don't use this function if no specific usage is requested;
2340 * This way the getkey functions can be used for plain key listings.
2342 * CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
2343 * is the key we actually found by looking at the keyid or a fingerprint and
2344 * may either point to the primary or one of the subkeys. */
2346 finish_lookup (GETKEY_CTX ctx)
2348 KBNODE keyblock = ctx->keyblock;
2350 KBNODE foundk = NULL;
2351 PKT_user_id *foundu = NULL;
2352 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2353 unsigned int req_usage = (ctx->req_usage & USAGE_MASK);
2354 /* Request the primary if we're certifying another key, and also
2355 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2356 do not understand signatures made by a signing subkey. PGP 8
2358 int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2359 ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2362 u32 curtime = make_timestamp ();
2364 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
2366 ctx->found_key = NULL;
2370 for (k = keyblock; k; k = k->next)
2374 assert (k->pkt->pkttype == PKT_PUBLIC_KEY
2375 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
2382 for (k = keyblock; k; k = k->next)
2386 assert (k->pkt->pkttype == PKT_USER_ID);
2387 foundu = k->pkt->pkt.user_id;
2393 log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2394 (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
2395 foundk ? "one" : "all", req_usage);
2399 latest_key = foundk ? foundk : keyblock;
2405 /* Do not look at subkeys if a certification key is requested. */
2406 if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim)
2409 /* Either start a loop or check just this one subkey. */
2410 for (k = foundk ? foundk : keyblock; k; k = nextk)
2414 if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2417 nextk = NULL; /* what a hack */
2418 pk = k->pkt->pkt.public_key;
2420 log_debug ("\tchecking subkey %08lX\n",
2421 (ulong) keyid_from_pk (pk, NULL));
2422 if (!pk->flags.valid)
2425 log_debug ("\tsubkey not valid\n");
2428 if (pk->flags.revoked)
2431 log_debug ("\tsubkey has been revoked\n");
2434 if (pk->has_expired)
2437 log_debug ("\tsubkey has expired\n");
2440 if (pk->timestamp > curtime && !opt.ignore_valid_from)
2443 log_debug ("\tsubkey not yet valid\n");
2447 if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2450 log_debug ("\tusage does not match: want=%x have=%x\n",
2451 req_usage, pk->pubkey_usage);
2456 log_debug ("\tsubkey might be fine\n");
2457 /* In case a key has a timestamp of 0 set, we make sure
2458 that it is used. A better change would be to compare
2459 ">=" but that might also change the selected keys and
2460 is as such a more intrusive change. */
2461 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2463 latest_date = pk->timestamp;
2469 /* Okay now try the primary key unless we want an exact
2470 * key ID match on a subkey */
2471 if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim)
2474 if (DBG_LOOKUP && !foundk && !req_prim)
2475 log_debug ("\tno suitable subkeys found - trying primary\n");
2476 pk = keyblock->pkt->pkt.public_key;
2477 if (!pk->flags.valid)
2480 log_debug ("\tprimary key not valid\n");
2482 else if (pk->flags.revoked)
2485 log_debug ("\tprimary key has been revoked\n");
2487 else if (pk->has_expired)
2490 log_debug ("\tprimary key has expired\n");
2492 else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2495 log_debug ("\tprimary key usage does not match: "
2496 "want=%x have=%x\n", req_usage, pk->pubkey_usage);
2501 log_debug ("\tprimary key may be used\n");
2502 latest_key = keyblock;
2503 latest_date = pk->timestamp;
2510 log_debug ("\tno suitable key found - giving up\n");
2511 return 0; /* Not found. */
2516 log_debug ("\tusing key %08lX\n",
2517 (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
2521 PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2523 free_user_id (pk->user_id);
2524 pk->user_id = scopy_user_id (foundu);
2527 ctx->found_key = latest_key;
2529 if (latest_key != keyblock && opt.verbose)
2532 xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
2533 log_info (_("using subkey %s instead of primary key %s\n"),
2534 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
2538 cache_user_id (keyblock);
2540 return 1; /* Found. */
2544 /* Return true if all the search modes are fingerprints. */
2546 search_modes_are_fingerprint (getkey_ctx_t ctx)
2550 for (n=found=0; n < ctx->nitems; n++)
2552 switch (ctx->items[n].mode)
2554 case KEYDB_SEARCH_MODE_FPR16:
2555 case KEYDB_SEARCH_MODE_FPR20:
2556 case KEYDB_SEARCH_MODE_FPR:
2563 return found && found == ctx->nitems;
2567 /* The main function to lookup a key. On success the found keyblock
2568 is stored at RET_KEYBLOCK and also in CTX. If WANT_SECRET is true
2569 a corresponding secret key is required. */
2571 lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, int want_secret)
2574 int no_suitable_key = 0;
2578 rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
2579 /* Skip over all legacy keys but only if they are not requested
2581 Fixme: The lower level keydb code should actually do that but
2582 then it would be harder to report the number of skipped
2583 legacy keys during import. */
2584 if (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY
2585 && !(ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2586 && !search_modes_are_fingerprint (ctx))
2591 /* If we are searching for the first key we have to make sure
2592 that the next iteration does not do an implicit reset.
2593 This can be triggered by an empty key ring. */
2594 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2595 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2597 rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
2600 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
2605 if (want_secret && agent_probe_any_secret_key (NULL, ctx->keyblock))
2606 goto skip; /* No secret key available. */
2608 /* Warning: node flag bits 0 and 1 should be preserved by
2609 * merge_selfsigs. For secret keys, premerge did tranfer the
2610 * keys to the keyblock. */
2611 merge_selfsigs (ctx->keyblock);
2612 if (finish_lookup (ctx))
2614 no_suitable_key = 0;
2618 no_suitable_key = 1;
2621 /* Release resources and continue search. */
2622 release_kbnode (ctx->keyblock);
2623 ctx->keyblock = NULL;
2624 /* We need to disable the caching so that for an exact key search we
2625 won't get the result back from the cache and thus end up in an
2626 endless loop. Disabling this here is sufficient because although
2627 the result may have been cached, if won't be used then. */
2628 keydb_disable_caching (ctx->kr_handle);
2632 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND
2633 && gpg_err_code (rc) != GPG_ERR_LEGACY_KEY)
2634 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
2638 *ret_keyblock = ctx->keyblock; /* Return the keyblock. */
2639 ctx->keyblock = NULL;
2641 else if ((gpg_err_code (rc) == GPG_ERR_NOT_FOUND
2642 || gpg_err_code (rc) == GPG_ERR_LEGACY_KEY) && no_suitable_key)
2643 rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
2644 else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2645 rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
2647 release_kbnode (ctx->keyblock);
2648 ctx->keyblock = NULL;
2657 * Enumerate certain secret keys. Caller must use these procedure:
2658 * 1) create a void pointer and initialize it to NULL
2659 * 2) pass this void pointer by reference to this function
2660 * and provide space for the secret key (pass a buffer for sk)
2661 * 3) call this function as long as it does not return an error.
2662 * The error code GPG_ERR_EOF indicates the end of the listing.
2663 * 4) Always call this function a last time with SK set to NULL,
2664 * so that can free it's context.
2667 enum_secret_keys (void **context, PKT_public_key *sk)
2669 gpg_error_t err = 0;
2682 /* Make a new context. */
2683 c = xtrycalloc (1, sizeof *c);
2685 return gpg_error_from_syserror ();
2691 /* Free the context. */
2692 release_kbnode (c->keyblock);
2699 return gpg_error (GPG_ERR_EOF);
2703 /* Loop until we have a keyblock. */
2704 while (!c->keyblock)
2706 /* Loop over the list of secret keys. */
2712 case 0: /* First try to use the --default-key. */
2713 if (opt.def_secret_key && *opt.def_secret_key)
2714 name = opt.def_secret_key;
2718 case 1: /* Init list of keys to try. */
2719 c->sl = opt.secret_keys_to_try;
2723 case 2: /* Get next item from list. */
2727 c->sl = c->sl->next;
2733 default: /* No more names to check - stop. */
2735 return gpg_error (GPG_ERR_EOF);
2738 while (!name || !*name);
2740 err = getkey_byname (NULL, NULL, name, 1, &c->keyblock);
2743 /* getkey_byname might return a keyblock even in the
2744 error case - I have not checked. Thus better release
2746 release_kbnode (c->keyblock);
2750 c->node = c->keyblock;
2753 /* Get the next key from the current keyblock. */
2754 for (; c->node; c->node = c->node->next)
2756 if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
2757 || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2759 copy_public_key (sk, c->node->pkt->pkt.public_key);
2760 c->node = c->node->next;
2761 return 0; /* Found. */
2765 /* Dispose the keyblock and continue. */
2766 release_kbnode (c->keyblock);
2772 /*********************************************
2773 *********** User ID printing helpers *******
2774 *********************************************/
2776 /* Return a string with a printable representation of the user_id.
2777 * this string must be freed by xfree. */
2779 get_user_id_string (u32 * keyid, int mode, size_t *r_len)
2786 /* Try it two times; second pass reads from key resources. */
2789 for (r = user_id_db; r; r = r->next)
2791 for (a = r->keyids; a; a = a->next)
2793 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
2797 /* An empty string as user id is possible. Make
2798 sure that the malloc allocates one byte and
2799 does not bail out. */
2800 p = xmalloc (r->len? r->len : 1);
2801 memcpy (p, r->name, r->len);
2808 p = xasprintf ("%08lX%08lX %.*s",
2809 (ulong) keyid[0], (ulong) keyid[1],
2812 p = xasprintf ("%s %.*s", keystr (keyid),
2815 *r_len = strlen (p);
2823 while (++pass < 2 && !get_pubkey (NULL, keyid));
2826 p = xstrdup (user_id_not_found_utf8 ());
2828 p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
2830 p = xasprintf ("%s [?]", keystr (keyid));
2833 *r_len = strlen (p);
2839 get_user_id_string_native (u32 * keyid)
2841 char *p = get_user_id_string (keyid, 0, NULL);
2842 char *p2 = utf8_to_native (p, strlen (p), 0);
2849 get_long_user_id_string (u32 * keyid)
2851 return get_user_id_string (keyid, 1, NULL);
2855 /* Please try to use get_user_byfpr instead of this one. */
2857 get_user_id (u32 * keyid, size_t * rn)
2859 return get_user_id_string (keyid, 2, rn);
2863 /* Please try to use get_user_id_byfpr_native instead of this one. */
2865 get_user_id_native (u32 * keyid)
2868 char *p = get_user_id (keyid, &rn);
2869 char *p2 = utf8_to_native (p, rn, 0);
2875 /* Return a user id from the caching by looking it up using the FPR
2876 which must be of size MAX_FINGERPRINT_LEN. */
2878 get_user_id_byfpr (const byte *fpr, size_t *rn)
2884 /* Try it two times; second pass reads from key resources. */
2887 for (r = user_id_db; r; r = r->next)
2890 for (a = r->keyids; a; a = a->next)
2892 if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
2894 /* An empty string as user id is possible. Make
2895 sure that the malloc allocates one byte and does
2897 p = xmalloc (r->len? r->len : 1);
2898 memcpy (p, r->name, r->len);
2905 while (++pass < 2 && !get_pubkey_byfpr (NULL, fpr));
2906 p = xstrdup (user_id_not_found_utf8 ());
2912 get_user_id_byfpr_native (const byte *fpr)
2915 char *p = get_user_id_byfpr (fpr, &rn);
2916 char *p2 = utf8_to_native (p, rn, 0);
2924 get_ctx_handle (GETKEY_CTX ctx)
2926 return ctx->kr_handle;
2930 free_akl (struct akl *akl)
2936 free_keyserver_spec (akl->spec);
2944 while (opt.auto_key_locate)
2946 struct akl *akl2 = opt.auto_key_locate;
2947 opt.auto_key_locate = opt.auto_key_locate->next;
2952 /* Returns false on error. */
2954 parse_auto_key_locate (char *options)
2958 while ((tok = optsep (&options)))
2960 struct akl *akl, *check, *last = NULL;
2966 akl = xmalloc_clear (sizeof (*akl));
2968 if (ascii_strcasecmp (tok, "clear") == 0)
2971 free_akl (opt.auto_key_locate);
2972 opt.auto_key_locate = NULL;
2975 else if (ascii_strcasecmp (tok, "nodefault") == 0)
2976 akl->type = AKL_NODEFAULT;
2977 else if (ascii_strcasecmp (tok, "local") == 0)
2978 akl->type = AKL_LOCAL;
2979 else if (ascii_strcasecmp (tok, "ldap") == 0)
2980 akl->type = AKL_LDAP;
2981 else if (ascii_strcasecmp (tok, "keyserver") == 0)
2982 akl->type = AKL_KEYSERVER;
2984 else if (ascii_strcasecmp (tok, "cert") == 0)
2985 akl->type = AKL_CERT;
2987 else if (ascii_strcasecmp (tok, "pka") == 0)
2988 akl->type = AKL_PKA;
2989 else if ((akl->spec = parse_keyserver_uri (tok, 1)))
2990 akl->type = AKL_SPEC;
2997 /* We must maintain the order the user gave us */
2998 for (check = opt.auto_key_locate; check;
2999 last = check, check = check->next)
3001 /* Check for duplicates */
3002 if (check->type == akl->type
3003 && (akl->type != AKL_SPEC
3004 || (akl->type == AKL_SPEC
3005 && strcmp (check->spec->uri, akl->spec->uri) == 0)))
3018 opt.auto_key_locate = akl;
3026 /* Return true if a secret key or secret subkey is available for one
3027 of the public keys in KEYBLOCK. */
3029 have_any_secret_key (ctrl_t ctrl, kbnode_t keyblock)
3033 for (node = keyblock; node; node = node->next)
3034 if ((node->pkt->pkttype == PKT_PUBLIC_KEY
3035 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3036 && !agent_probe_secret_key (ctrl, node->pkt->pkt.public_key))
3042 /* Return true if a secret key is available for the public key with
3043 * the given KEYID. This is just a fast check and does not tell us
3044 * whether the secret key is valid. It merely tells os whether there
3045 * is some secret key. */
3047 have_secret_key_with_kid (u32 *keyid)
3051 KEYDB_SEARCH_DESC desc;
3056 kdbhd = keydb_new ();
3057 memset (&desc, 0, sizeof desc);
3058 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
3059 desc.u.kid[0] = keyid[0];
3060 desc.u.kid[1] = keyid[1];
3063 err = keydb_search (kdbhd, &desc, 1, NULL);
3064 if (gpg_err_code (err) == GPG_ERR_LEGACY_KEY)
3069 err = keydb_get_keyblock (kdbhd, &keyblock);
3072 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
3076 for (node = keyblock; node; node = node->next)
3078 /* Bit 0 of the flags is set if the search found the key
3079 using that key or subkey. */
3080 if ((node->flag & 1))
3082 assert (node->pkt->pkttype == PKT_PUBLIC_KEY
3083 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3085 if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
3092 release_kbnode (keyblock);
3095 keydb_release (kdbhd);