Bump to 2.4.3
[platform/upstream/gpg2.git] / g10 / getkey.c
1 /* getkey.c -  Get a key from the database
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3  *               2007, 2008, 2010  Free Software Foundation, Inc.
4  * Copyright (C) 2015, 2016 g10 Code GmbH
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27
28 #include "gpg.h"
29 #include "../common/util.h"
30 #include "packet.h"
31 #include "../common/iobuf.h"
32 #include "keydb.h"
33 #include "options.h"
34 #include "main.h"
35 #include "trustdb.h"
36 #include "../common/i18n.h"
37 #include "keyserver-internal.h"
38 #include "call-agent.h"
39 #include "objcache.h"
40 #include "../common/host2net.h"
41 #include "../common/mbox-util.h"
42 #include "../common/status.h"
43
44 #define MAX_PK_CACHE_ENTRIES   PK_UID_CACHE_SIZE
45 #define MAX_UID_CACHE_ENTRIES  PK_UID_CACHE_SIZE
46
47 #if MAX_PK_CACHE_ENTRIES < 2
48 #error We need the cache for key creation
49 #endif
50
51 /* Flags values returned by the lookup code.  Note that the values are
52  * directly used by the KEY_CONSIDERED status line.  */
53 #define LOOKUP_NOT_SELECTED        (1<<0)
54 #define LOOKUP_ALL_SUBKEYS_EXPIRED (1<<1)  /* or revoked */
55
56
57 /* A context object used by the lookup functions.  */
58 struct getkey_ctx_s
59 {
60   /* Part of the search criteria: whether the search is an exact
61      search or not.  A search that is exact requires that a key or
62      subkey meet all of the specified criteria.  A search that is not
63      exact allows selecting a different key or subkey from the
64      keyblock that matched the criteria.  Further, an exact search
65      returns the key or subkey that matched whereas a non-exact search
66      typically returns the primary key.  See finish_lookup for
67      details.  */
68   int exact;
69
70   /* Part of the search criteria: Whether the caller only wants keys
71      with an available secret key.  This is used by getkey_next to get
72      the next result with the same initial criteria.  */
73   int want_secret;
74
75   /* Part of the search criteria: The type of the requested key.  A
76      mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.
77      If non-zero, then for a key to match, it must implement one of
78      the required uses.  */
79   int req_usage;
80
81   /* The database handle.  */
82   KEYDB_HANDLE kr_handle;
83
84   /* Whether we should call xfree() on the context when the context is
85      released using getkey_end()).  */
86   int not_allocated;
87
88   /* This variable is used as backing store for strings which have
89      their address used in ITEMS.  */
90   strlist_t extra_list;
91
92   /* Hack to return the mechanism (AKL_foo) used to find the key.  */
93   int found_via_akl;
94
95   /* Part of the search criteria: The low-level search specification
96      as passed to keydb_search.  */
97   int nitems;
98   /* This must be the last element in the structure.  When we allocate
99      the structure, we allocate it so that ITEMS can hold NITEMS.  */
100   KEYDB_SEARCH_DESC items[1];
101 };
102
103 #if 0
104 static struct
105 {
106   int any;
107   int okay_count;
108   int nokey_count;
109   int error_count;
110 } lkup_stats[21];
111 #endif
112
113 typedef struct keyid_list
114 {
115   struct keyid_list *next;
116   byte fprlen;
117   char fpr[MAX_FINGERPRINT_LEN];
118   u32 keyid[2];
119 } *keyid_list_t;
120
121
122 #if MAX_PK_CACHE_ENTRIES
123 typedef struct pk_cache_entry
124 {
125   struct pk_cache_entry *next;
126   u32 keyid[2];
127   PKT_public_key *pk;
128 } *pk_cache_entry_t;
129 static pk_cache_entry_t pk_cache;
130 static int pk_cache_entries;    /* Number of entries in pk cache.  */
131 static int pk_cache_disabled;
132 #endif
133
134 #if MAX_UID_CACHE_ENTRIES < 5
135 #error we really need the userid cache
136 #endif
137
138 static void merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock);
139 static int lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret,
140                    kbnode_t *ret_keyblock, kbnode_t *ret_found_key);
141 static kbnode_t finish_lookup (kbnode_t keyblock,
142                                unsigned int req_usage, int want_exact,
143                                int want_secret, unsigned int *r_flags);
144 static void print_status_key_considered (kbnode_t keyblock, unsigned int flags);
145
146
147 #if 0
148 static void
149 print_stats ()
150 {
151   int i;
152   for (i = 0; i < DIM (lkup_stats); i++)
153     {
154       if (lkup_stats[i].any)
155         es_fprintf (es_stderr,
156                  "lookup stats: mode=%-2d  ok=%-6d  nokey=%-6d  err=%-6d\n",
157                  i,
158                  lkup_stats[i].okay_count,
159                  lkup_stats[i].nokey_count, lkup_stats[i].error_count);
160     }
161 }
162 #endif
163
164
165 /* Cache a copy of a public key in the public key cache.  PK is not
166  * cached if caching is disabled (via getkey_disable_caches), if
167  * PK->FLAGS.DONT_CACHE is set, we don't know how to derive a key id
168  * from the public key (e.g., unsupported algorithm), or a key with
169  * the key id is already in the cache.
170  *
171  * The public key packet is copied into the cache using
172  * copy_public_key.  Thus, any secret parts are not copied, for
173  * instance.
174  *
175  * This cache is filled by get_pubkey and is read by get_pubkey and
176  * get_pubkey_fast.  */
177 void
178 cache_public_key (PKT_public_key * pk)
179 {
180 #if MAX_PK_CACHE_ENTRIES
181   pk_cache_entry_t ce, ce2;
182   u32 keyid[2];
183
184   if (pk_cache_disabled)
185     return;
186
187   if (pk->flags.dont_cache)
188     return;
189
190   if (is_ELGAMAL (pk->pubkey_algo)
191       || pk->pubkey_algo == PUBKEY_ALGO_DSA
192       || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
193       || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
194       || pk->pubkey_algo == PUBKEY_ALGO_ECDH
195       || is_RSA (pk->pubkey_algo))
196     {
197       keyid_from_pk (pk, keyid);
198     }
199   else
200     return; /* Don't know how to get the keyid.  */
201
202   for (ce = pk_cache; ce; ce = ce->next)
203     if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
204       {
205         if (DBG_CACHE)
206           log_debug ("cache_public_key: already in cache\n");
207         return;
208       }
209
210   if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
211     {
212       int n;
213
214       /* Remove the last 50% of the entries.  */
215       for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
216         ce = ce->next;
217       if (ce && ce != pk_cache && ce->next)
218         {
219           ce2 = ce->next;
220           ce->next = NULL;
221           ce = ce2;
222           for (; ce; ce = ce2)
223             {
224               ce2 = ce->next;
225               free_public_key (ce->pk);
226               xfree (ce);
227               pk_cache_entries--;
228             }
229         }
230       log_assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
231     }
232   pk_cache_entries++;
233   ce = xmalloc (sizeof *ce);
234   ce->next = pk_cache;
235   pk_cache = ce;
236   ce->pk = copy_public_key (NULL, pk);
237   ce->keyid[0] = keyid[0];
238   ce->keyid[1] = keyid[1];
239 #endif
240 }
241
242
243 /* Return a const utf-8 string with the text "[User ID not found]".
244    This function is required so that we don't need to switch gettext's
245    encoding temporary.  */
246 static const char *
247 user_id_not_found_utf8 (void)
248 {
249   static char *text;
250
251   if (!text)
252     text = native_to_utf8 (_("[User ID not found]"));
253   return text;
254 }
255
256
257
258
259 /* Disable and drop the public key cache (which is filled by
260    cache_public_key and get_pubkey).  Note: there is currently no way
261    to re-enable this cache.  */
262 void
263 getkey_disable_caches (void)
264 {
265 #if MAX_PK_CACHE_ENTRIES
266   {
267     pk_cache_entry_t ce, ce2;
268
269     for (ce = pk_cache; ce; ce = ce2)
270       {
271         ce2 = ce->next;
272         free_public_key (ce->pk);
273         xfree (ce);
274       }
275     pk_cache_disabled = 1;
276     pk_cache_entries = 0;
277     pk_cache = NULL;
278   }
279 #endif
280   /* fixme: disable user id cache ? */
281 }
282
283
284 /* Free a list of pubkey_t objects.  */
285 void
286 pubkeys_free (pubkey_t keys)
287 {
288   while (keys)
289     {
290       pubkey_t next = keys->next;
291       xfree (keys->pk);
292       release_kbnode (keys->keyblock);
293       xfree (keys);
294       keys = next;
295     }
296 }
297
298
299 static void
300 pk_from_block (PKT_public_key *pk, kbnode_t keyblock, kbnode_t found_key)
301 {
302   kbnode_t a = found_key ? found_key : keyblock;
303
304   log_assert (a->pkt->pkttype == PKT_PUBLIC_KEY
305               || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
306
307   copy_public_key (pk, a->pkt->pkt.public_key);
308 }
309
310
311 /* Specialized version of get_pubkey which retrieves the key based on
312  * information in SIG.  In contrast to get_pubkey PK is required.  IF
313  * FORCED_PK is not NULL, this public key is used and copied to PK. */
314 gpg_error_t
315 get_pubkey_for_sig (ctrl_t ctrl, PKT_public_key *pk, PKT_signature *sig,
316                     PKT_public_key *forced_pk)
317 {
318   const byte *fpr;
319   size_t fprlen;
320
321   if (forced_pk)
322     {
323       copy_public_key (pk, forced_pk);
324       return 0;
325     }
326
327   /* First try the ISSUER_FPR info.  */
328   fpr = issuer_fpr_raw (sig, &fprlen);
329   if (fpr && !get_pubkey_byfprint (ctrl, pk, NULL, fpr, fprlen))
330     return 0;
331
332   /* Fallback to use the ISSUER_KEYID.  */
333   return get_pubkey (ctrl, pk, sig->keyid);
334 }
335
336
337 /* Return the public key with the key id KEYID and store it at PK.
338  * The resources in *PK should be released using
339  * release_public_key_parts().  This function also stores a copy of
340  * the public key in the user id cache (see cache_public_key).
341  *
342  * If PK is NULL, this function just stores the public key in the
343  * cache and returns the usual return code.
344  *
345  * PK->REQ_USAGE (which is a mask of PUBKEY_USAGE_SIG,
346  * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT) is passed through to the
347  * lookup function.  If this is non-zero, only keys with the specified
348  * usage will be returned.  As such, it is essential that
349  * PK->REQ_USAGE be correctly initialized!
350  *
351  * Returns 0 on success, GPG_ERR_NO_PUBKEY if there is no public key
352  * with the specified key id, or another error code if an error
353  * occurs.
354  *
355  * If the data was not read from the cache, then the self-signed data
356  * has definitely been merged into the public key using
357  * merge_selfsigs.  */
358 int
359 get_pubkey (ctrl_t ctrl, PKT_public_key * pk, u32 * keyid)
360 {
361   int internal = 0;
362   int rc = 0;
363
364 #if MAX_PK_CACHE_ENTRIES
365   if (pk)
366     {
367       /* Try to get it from the cache.  We don't do this when pk is
368          NULL as it does not guarantee that the user IDs are
369          cached. */
370       pk_cache_entry_t ce;
371       for (ce = pk_cache; ce; ce = ce->next)
372         {
373           if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
374             /* XXX: We don't check PK->REQ_USAGE here, but if we don't
375                read from the cache, we do check it!  */
376             {
377               copy_public_key (pk, ce->pk);
378               return 0;
379             }
380         }
381     }
382 #endif
383   /* More init stuff.  */
384   if (!pk)
385     {
386       internal++;
387       pk = xtrycalloc (1, sizeof *pk);
388       if (!pk)
389         {
390           rc = gpg_error_from_syserror ();
391           goto leave;
392         }
393     }
394
395
396   /* Do a lookup.  */
397   {
398     struct getkey_ctx_s ctx;
399     kbnode_t kb = NULL;
400     kbnode_t found_key = NULL;
401
402     memset (&ctx, 0, sizeof ctx);
403     ctx.exact = 1; /* Use the key ID exactly as given.  */
404     ctx.not_allocated = 1;
405
406     if (ctrl && ctrl->cached_getkey_kdb)
407       {
408         ctx.kr_handle = ctrl->cached_getkey_kdb;
409         ctrl->cached_getkey_kdb = NULL;
410         keydb_search_reset (ctx.kr_handle);
411       }
412     else
413       {
414         ctx.kr_handle = keydb_new (ctrl);
415         if (!ctx.kr_handle)
416           {
417             rc = gpg_error_from_syserror ();
418             goto leave;
419           }
420       }
421     ctx.nitems = 1;
422     ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
423     ctx.items[0].u.kid[0] = keyid[0];
424     ctx.items[0].u.kid[1] = keyid[1];
425     ctx.req_usage = pk->req_usage;
426     rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
427     if (!rc)
428       {
429         pk_from_block (pk, kb, found_key);
430       }
431     getkey_end (ctrl, &ctx);
432     release_kbnode (kb);
433   }
434   if (!rc)
435     goto leave;
436
437   rc = GPG_ERR_NO_PUBKEY;
438
439 leave:
440   if (!rc)
441     cache_public_key (pk);
442   if (internal)
443     free_public_key (pk);
444   return rc;
445 }
446
447
448 /* Same as get_pubkey but if the key was not found the function tries
449  * to import it from LDAP.  FIXME: We should not need this but swicth
450  * to a fingerprint lookup.  */
451 gpg_error_t
452 get_pubkey_with_ldap_fallback (ctrl_t ctrl, PKT_public_key *pk, u32 *keyid)
453 {
454   gpg_error_t err;
455
456   err = get_pubkey (ctrl, pk, keyid);
457   if (!err)
458     return 0;
459
460   if (gpg_err_code (err) != GPG_ERR_NO_PUBKEY)
461     return err;
462
463   /* Note that this code does not handle the case for two readers
464    * having both openpgp encryption keys.  Only one will be tried.  */
465   if (opt.debug)
466     log_debug ("using LDAP to find a public key\n");
467   err = keyserver_import_keyid (ctrl, keyid,
468                                 opt.keyserver, KEYSERVER_IMPORT_FLAG_LDAP);
469   if (gpg_err_code (err) == GPG_ERR_NO_DATA
470       || gpg_err_code (err) == GPG_ERR_NO_KEYSERVER)
471     {
472       /* Dirmngr returns NO DATA is the selected keyserver
473        * does not have the requested key.  It returns NO
474        * KEYSERVER if no LDAP keyservers are configured.  */
475       err = gpg_error (GPG_ERR_NO_PUBKEY);
476     }
477   if (err)
478     return err;
479
480   return get_pubkey (ctrl, pk, keyid);
481 }
482
483
484 /* Similar to get_pubkey, but it does not take PK->REQ_USAGE into
485  * account nor does it merge in the self-signed data.  This function
486  * also only considers primary keys.  It is intended to be used as a
487  * quick check of the key to avoid recursion.  It should only be used
488  * in very certain cases.  Like get_pubkey and unlike any of the other
489  * lookup functions, this function also consults the user id cache
490  * (see cache_public_key).
491  *
492  * Return the public key in *PK.  The resources in *PK should be
493  * released using release_public_key_parts().  */
494 int
495 get_pubkey_fast (ctrl_t ctrl, PKT_public_key * pk, u32 * keyid)
496 {
497   int rc = 0;
498   KEYDB_HANDLE hd;
499   KBNODE keyblock;
500   u32 pkid[2];
501
502   log_assert (pk);
503 #if MAX_PK_CACHE_ENTRIES
504   {
505     /* Try to get it from the cache */
506     pk_cache_entry_t ce;
507
508     for (ce = pk_cache; ce; ce = ce->next)
509       {
510         if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]
511             /* Only consider primary keys.  */
512             && ce->pk->keyid[0] == ce->pk->main_keyid[0]
513             && ce->pk->keyid[1] == ce->pk->main_keyid[1])
514           {
515             if (pk)
516               copy_public_key (pk, ce->pk);
517             return 0;
518           }
519       }
520   }
521 #endif
522
523   hd = keydb_new (ctrl);
524   if (!hd)
525     return gpg_error_from_syserror ();
526   rc = keydb_search_kid (hd, keyid);
527   if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
528     {
529       keydb_release (hd);
530       return GPG_ERR_NO_PUBKEY;
531     }
532   rc = keydb_get_keyblock (hd, &keyblock);
533   keydb_release (hd);
534   if (rc)
535     {
536       log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
537       return GPG_ERR_NO_PUBKEY;
538     }
539
540   log_assert (keyblock && keyblock->pkt
541               && keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
542
543   /* We return the primary key.  If KEYID matched a subkey, then we
544      return an error.  */
545   keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
546   if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
547     copy_public_key (pk, keyblock->pkt->pkt.public_key);
548   else
549     rc = GPG_ERR_NO_PUBKEY;
550
551   release_kbnode (keyblock);
552
553   /* Not caching key here since it won't have all of the fields
554      properly set. */
555
556   return rc;
557 }
558
559
560 /* Return the entire keyblock used to create SIG.  This is a
561  * specialized version of get_pubkeyblock.
562  *
563  * FIXME: This is a hack because get_pubkey_for_sig was already called
564  * and it could have used a cache to hold the key.  */
565 kbnode_t
566 get_pubkeyblock_for_sig (ctrl_t ctrl, PKT_signature *sig)
567 {
568   const byte *fpr;
569   size_t fprlen;
570   kbnode_t keyblock;
571
572   /* First try the ISSUER_FPR info.  */
573   fpr = issuer_fpr_raw (sig, &fprlen);
574   if (fpr && !get_pubkey_byfprint (ctrl, NULL, &keyblock, fpr, fprlen))
575     return keyblock;
576
577   /* Fallback to use the ISSUER_KEYID.  */
578   return get_pubkeyblock (ctrl, sig->keyid);
579 }
580
581
582 /* Return the key block for the key with key id KEYID or NULL, if an
583  * error occurs.  Use release_kbnode() to release the key block.
584  *
585  * The self-signed data has already been merged into the public key
586  * using merge_selfsigs.  */
587 kbnode_t
588 get_pubkeyblock (ctrl_t ctrl, u32 * keyid)
589 {
590   struct getkey_ctx_s ctx;
591   int rc = 0;
592   KBNODE keyblock = NULL;
593
594   memset (&ctx, 0, sizeof ctx);
595   /* No need to set exact here because we want the entire block.  */
596   ctx.not_allocated = 1;
597   ctx.kr_handle = keydb_new (ctrl);
598   if (!ctx.kr_handle)
599     return NULL;
600   ctx.nitems = 1;
601   ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
602   ctx.items[0].u.kid[0] = keyid[0];
603   ctx.items[0].u.kid[1] = keyid[1];
604   rc = lookup (ctrl, &ctx, 0, &keyblock, NULL);
605   getkey_end (ctrl, &ctx);
606
607   return rc ? NULL : keyblock;
608 }
609
610
611 /* Return the public key with the key id KEYID iff the secret key is
612  * available and store it at PK.  The resources should be released
613  * using release_public_key_parts().
614  *
615  * Unlike other lookup functions, PK may not be NULL.  PK->REQ_USAGE
616  * is passed through to the lookup function and is a mask of
617  * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.  Thus, it
618  * must be valid!  If this is non-zero, only keys with the specified
619  * usage will be returned.
620  *
621  * Returns 0 on success.  If a public key with the specified key id is
622  * not found or a secret key is not available for that public key, an
623  * error code is returned.  Note: this function ignores legacy keys.
624  * An error code is also return if an error occurs.
625  *
626  * The self-signed data has already been merged into the public key
627  * using merge_selfsigs.  */
628 gpg_error_t
629 get_seckey (ctrl_t ctrl, PKT_public_key *pk, u32 *keyid)
630 {
631   gpg_error_t err;
632   struct getkey_ctx_s ctx;
633   kbnode_t keyblock = NULL;
634   kbnode_t found_key = NULL;
635
636   memset (&ctx, 0, sizeof ctx);
637   ctx.exact = 1; /* Use the key ID exactly as given.  */
638   ctx.not_allocated = 1;
639   ctx.kr_handle = keydb_new (ctrl);
640   if (!ctx.kr_handle)
641     return gpg_error_from_syserror ();
642   ctx.nitems = 1;
643   ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
644   ctx.items[0].u.kid[0] = keyid[0];
645   ctx.items[0].u.kid[1] = keyid[1];
646   ctx.req_usage = pk->req_usage;
647   err = lookup (ctrl, &ctx, 1, &keyblock, &found_key);
648   if (!err)
649     {
650       pk_from_block (pk, keyblock, found_key);
651     }
652   getkey_end (ctrl, &ctx);
653   release_kbnode (keyblock);
654
655   if (!err)
656     {
657       if (!agent_probe_secret_key (/*ctrl*/NULL, pk))
658         {
659           release_public_key_parts (pk);
660           err = gpg_error (GPG_ERR_NO_SECKEY);
661         }
662     }
663
664   return err;
665 }
666
667
668 /* Skip unusable keys.  A key is unusable if it is revoked, expired or
669    disabled or if the selected user id is revoked or expired.  */
670 static int
671 skip_unusable (void *opaque, u32 * keyid, int uid_no)
672 {
673   ctrl_t ctrl = opaque;
674   int unusable = 0;
675   KBNODE keyblock;
676   PKT_public_key *pk;
677
678   keyblock = get_pubkeyblock (ctrl, keyid);
679   if (!keyblock)
680     {
681       log_error ("error checking usability status of %s\n", keystr (keyid));
682       goto leave;
683     }
684
685   pk = keyblock->pkt->pkt.public_key;
686
687   /* Is the key revoked or expired?  */
688   if (pk->flags.revoked || (pk->has_expired && !opt.ignore_expiration))
689     unusable = 1;
690
691   /* Is the user ID in question revoked or expired? */
692   if (!unusable && uid_no)
693     {
694       KBNODE node;
695       int uids_seen = 0;
696
697       for (node = keyblock; node; node = node->next)
698         {
699           if (node->pkt->pkttype == PKT_USER_ID)
700             {
701               PKT_user_id *user_id = node->pkt->pkt.user_id;
702
703               uids_seen ++;
704               if (uids_seen != uid_no)
705                 continue;
706
707               if (user_id->flags.revoked
708                   || (user_id->flags.expired && !opt.ignore_expiration))
709                 unusable = 1;
710
711               break;
712             }
713         }
714
715       /* If UID_NO is non-zero, then the keyblock better have at least
716          that many UIDs.  */
717       log_assert (uids_seen == uid_no);
718     }
719
720   if (!unusable)
721     unusable = pk_is_disabled (pk);
722
723 leave:
724   release_kbnode (keyblock);
725   return unusable;
726 }
727
728
729 /* Search for keys matching some criteria.
730
731    If RETCTX is not NULL, then the constructed context is returned in
732    *RETCTX so that getpubkey_next can be used to get subsequent
733    results.  In this case, getkey_end() must be used to free the
734    search context.  If RETCTX is not NULL, then RET_KDBHD must be
735    NULL.
736
737    If NAMELIST is not NULL, then a search query is constructed using
738    classify_user_id on each of the strings in the list.  (Recall: the
739    database does an OR of the terms, not an AND.)  If NAMELIST is
740    NULL, then all results are returned.
741
742    If PK is not NULL, the public key of the first result is returned
743    in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
744    set, it is used to filter the search results.  See the
745    documentation for finish_lookup to understand exactly how this is
746    used.  Note: The self-signed data has already been merged into the
747    public key using merge_selfsigs.  Free *PK by calling
748    release_public_key_parts (or, if PK was allocated using xfree, you
749    can use free_public_key, which calls release_public_key_parts(PK)
750    and then xfree(PK)).
751
752    If WANT_SECRET is set, then only keys with an available secret key
753    (either locally or via key registered on a smartcard) are returned.
754
755    If INCLUDE_UNUSABLE is set, then unusable keys (see the
756    documentation for skip_unusable for an exact definition) are
757    skipped unless they are looked up by key id or by fingerprint.
758
759    If RET_KB is not NULL, the keyblock is returned in *RET_KB.  This
760    should be freed using release_kbnode().
761
762    If RET_KDBHD is not NULL, then the new database handle used to
763    conduct the search is returned in *RET_KDBHD.  This can be used to
764    get subsequent results using keydb_search_next.  Note: in this
765    case, no advanced filtering is done for subsequent results (e.g.,
766    WANT_SECRET and PK->REQ_USAGE are not respected).
767
768    This function returns 0 on success.  Otherwise, an error code is
769    returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
770    (if want_secret is set) is returned if the key is not found.  */
771 static int
772 key_byname (ctrl_t ctrl, GETKEY_CTX *retctx, strlist_t namelist,
773             PKT_public_key *pk,
774             int want_secret, int include_unusable,
775             KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
776 {
777   int rc = 0;
778   int n;
779   strlist_t r;
780   strlist_t namelist_expanded = NULL;
781   GETKEY_CTX ctx;
782   KBNODE help_kb = NULL;
783   KBNODE found_key = NULL;
784
785   if (retctx)
786     {
787       /* Reset the returned context in case of error.  */
788       log_assert (!ret_kdbhd); /* Not allowed because the handle is stored
789                                   in the context.  */
790       *retctx = NULL;
791     }
792   if (ret_kdbhd)
793     *ret_kdbhd = NULL;
794
795   if (!namelist)
796     /* No search terms: iterate over the whole DB.  */
797     {
798       ctx = xmalloc_clear (sizeof *ctx);
799       ctx->nitems = 1;
800       ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
801       if (!include_unusable)
802         {
803           ctx->items[0].skipfnc = skip_unusable;
804           ctx->items[0].skipfncvalue = ctrl;
805         }
806     }
807   else
808     {
809       namelist_expanded = expand_group (namelist, 1);
810       namelist = namelist_expanded;
811
812       /* Build the search context.  */
813       for (n = 0, r = namelist; r; r = r->next)
814         n++;
815
816       /* CTX has space for a single search term at the end.  Thus, we
817          need to allocate sizeof *CTX plus (n - 1) sizeof
818          CTX->ITEMS.  */
819       ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
820       ctx->nitems = n;
821
822       for (n = 0, r = namelist; r; r = r->next, n++)
823         {
824           gpg_error_t err;
825
826           err = classify_user_id (r->d, &ctx->items[n], 1);
827
828           if (ctx->items[n].exact)
829             ctx->exact = 1;
830           if (err)
831             {
832               xfree (ctx);
833               rc = gpg_err_code (err); /* FIXME: remove gpg_err_code.  */
834               goto leave;
835             }
836           if (!include_unusable
837               && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
838               && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
839               && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
840             {
841               ctx->items[n].skipfnc = skip_unusable;
842               ctx->items[n].skipfncvalue = ctrl;
843             }
844         }
845     }
846
847   ctx->want_secret = want_secret;
848   ctx->kr_handle = keydb_new (ctrl);
849   if (!ctx->kr_handle)
850     {
851       rc = gpg_error_from_syserror ();
852       getkey_end (ctrl, ctx);
853       goto leave;
854     }
855
856   if (!ret_kb)
857     ret_kb = &help_kb;
858
859   if (pk)
860     {
861       ctx->req_usage = pk->req_usage;
862     }
863
864   rc = lookup (ctrl, ctx, want_secret, ret_kb, &found_key);
865   if (!rc && pk)
866     {
867       pk_from_block (pk, *ret_kb, found_key);
868     }
869
870   release_kbnode (help_kb);
871
872   if (retctx) /* Caller wants the context.  */
873     {
874       if (ctx->extra_list)
875         {
876           for (r=ctx->extra_list; r->next; r = r->next)
877             ;
878           r->next = namelist_expanded;
879         }
880       else
881         ctx->extra_list = namelist_expanded;
882       namelist_expanded = NULL;
883       *retctx = ctx;
884     }
885   else
886     {
887       if (ret_kdbhd)
888         {
889           *ret_kdbhd = ctx->kr_handle;
890           ctx->kr_handle = NULL;
891         }
892       getkey_end (ctrl, ctx);
893     }
894
895  leave:
896   free_strlist (namelist_expanded);
897   return rc;
898 }
899
900
901 /* Find a public key identified by NAME.
902  *
903  * If name appears to be a valid RFC822 mailbox (i.e., email address)
904  * and auto key lookup is enabled (mode != GET_PUBKEY_NO_AKL), then
905  * the specified auto key lookup methods (--auto-key-lookup) are used
906  * to import the key into the local keyring.  Otherwise, just the
907  * local keyring is consulted.
908  *
909  * MODE can be one of:
910  *    GET_PUBKEY_NORMAL   - The standard mode
911  *    GET_PUBKEY_NO_AKL   - The auto key locate functionality is
912  *                          disabled and only the local key ring is
913  *                          considered.  Note: the local key ring is
914  *                          consulted even if local is not in the
915  *                          auto-key-locate option list!
916  *    GET_PUBKEY_NO_LOCAL - Only the auto key locate functionality is
917  *                          used and no local search is done.
918  *
919  * If RETCTX is not NULL, then the constructed context is returned in
920  * *RETCTX so that getpubkey_next can be used to get subsequent
921  * results.  In this case, getkey_end() must be used to free the
922  * search context.  If RETCTX is not NULL, then RET_KDBHD must be
923  * NULL.
924  *
925  * If PK is not NULL, the public key of the first result is returned
926  * in *PK.  Note: PK->REQ_USAGE must be valid!!!  PK->REQ_USAGE is
927  * passed through to the lookup function and is a mask of
928  * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.  If this
929  * is non-zero, only keys with the specified usage will be returned.
930  * Note: The self-signed data has already been merged into the public
931  * key using merge_selfsigs.  Free *PK by calling
932  * release_public_key_parts (or, if PK was allocated using xfree, you
933  * can use free_public_key, which calls release_public_key_parts(PK)
934  * and then xfree(PK)).
935  *
936  * NAME is a string, which is turned into a search query using
937  * classify_user_id.
938  *
939  * If RET_KEYBLOCK is not NULL, the keyblock is returned in
940  * *RET_KEYBLOCK.  This should be freed using release_kbnode().
941  *
942  * If RET_KDBHD is not NULL, then the new database handle used to
943  * conduct the search is returned in *RET_KDBHD.  This can be used to
944  * get subsequent results using keydb_search_next or to modify the
945  * returned record.  Note: in this case, no advanced filtering is done
946  * for subsequent results (e.g., PK->REQ_USAGE is not respected).
947  * Unlike RETCTX, this is always returned.
948  *
949  * If INCLUDE_UNUSABLE is set, then unusable keys (see the
950  * documentation for skip_unusable for an exact definition) are
951  * skipped unless they are looked up by key id or by fingerprint.
952  *
953  * This function returns 0 on success.  Otherwise, an error code is
954  * returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
955  * (if want_secret is set) is returned if the key is not found.  */
956 int
957 get_pubkey_byname (ctrl_t ctrl, enum get_pubkey_modes mode,
958                    GETKEY_CTX * retctx, PKT_public_key * pk,
959                    const char *name, KBNODE * ret_keyblock,
960                    KEYDB_HANDLE * ret_kdbhd, int include_unusable)
961 {
962   int rc;
963   strlist_t namelist = NULL;
964   struct akl *akl;
965   int is_mbox, is_fpr;
966   KEYDB_SEARCH_DESC fprbuf;
967   int nodefault = 0;
968   int anylocalfirst = 0;
969   int mechanism_type = AKL_NODEFAULT;
970
971
972   /* If RETCTX is not NULL, then RET_KDBHD must be NULL.  */
973   log_assert (retctx == NULL || ret_kdbhd == NULL);
974
975   if (retctx)
976     *retctx = NULL;
977
978   /* Does NAME appear to be a mailbox (mail address)?  */
979   is_mbox = is_valid_mailbox (name);
980   if (!is_mbox && *name == '<' && name[1] && name[strlen(name)-1]=='>'
981       && name[1] != '>'
982       && is_valid_mailbox_mem (name+1, strlen (name)-2))
983     {
984       /* The mailbox is in the form "<foo@example.org>" which is not
985        * detected by is_valid_mailbox.  Set the flag but keep name as
986        * it is because the bracketed name is actual the better
987        * specification for a local search and the other methods
988        * extract the mail address anyway.  */
989       is_mbox = 1;
990     }
991
992   /* If we are called due to --locate-external-key Check whether NAME
993    * is a fingerprint and then try to lookup that key by configured
994    * method which support lookup by fingerprint.  FPRBUF carries the
995    * parsed fingerpint iff IS_FPR is true.  */
996   is_fpr = 0;
997   if (!is_mbox && mode == GET_PUBKEY_NO_LOCAL)
998     {
999       if (!classify_user_id (name, &fprbuf, 1)
1000           && fprbuf.mode == KEYDB_SEARCH_MODE_FPR)
1001         is_fpr = 1;
1002     }
1003
1004   /* The auto-key-locate feature works as follows: there are a number
1005    * of methods to look up keys.  By default, the local keyring is
1006    * tried first.  Then, each method listed in the --auto-key-locate is
1007    * tried in the order it appears.
1008    *
1009    * This can be changed as follows:
1010    *
1011    *   - if nodefault appears anywhere in the list of options, then
1012    *     the local keyring is not tried first, or,
1013    *
1014    *   - if local appears anywhere in the list of options, then the
1015    *     local keyring is not tried first, but in the order in which
1016    *     it was listed in the --auto-key-locate option.
1017    *
1018    * Note: we only save the search context in RETCTX if the local
1019    * method is the first method tried (either explicitly or
1020    * implicitly).  */
1021   if (mode == GET_PUBKEY_NO_LOCAL)
1022     nodefault = 1;  /* Auto-key-locate but ignore "local".  */
1023   else if (mode != GET_PUBKEY_NO_AKL)
1024     {
1025       /* auto-key-locate is enabled.  */
1026
1027       /* nodefault is true if "nodefault" or "local" appear.  */
1028       for (akl = opt.auto_key_locate; akl; akl = akl->next)
1029         if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
1030           {
1031             nodefault = 1;
1032             break;
1033           }
1034       /* anylocalfirst is true if "local" appears before any other
1035          search methods (except "nodefault").  */
1036       for (akl = opt.auto_key_locate; akl; akl = akl->next)
1037         if (akl->type != AKL_NODEFAULT)
1038           {
1039             if (akl->type == AKL_LOCAL)
1040               anylocalfirst = 1;
1041             break;
1042           }
1043     }
1044
1045   if (!nodefault)
1046     {
1047       /* "nodefault" didn't occur.  Thus, "local" is implicitly the
1048        *  first method to try.  */
1049       anylocalfirst = 1;
1050     }
1051
1052   if (mode == GET_PUBKEY_NO_LOCAL)
1053     {
1054       /* Force using the AKL.  If IS_MBOX is not set this is the final
1055        * error code.  */
1056       rc = GPG_ERR_NO_PUBKEY;
1057     }
1058   else if (nodefault && is_mbox)
1059     {
1060       /* Either "nodefault" or "local" (explicitly) appeared in the
1061        * auto key locate list and NAME appears to be an email address.
1062        * Don't try the local keyring.  */
1063       rc = GPG_ERR_NO_PUBKEY;
1064     }
1065   else
1066     {
1067       /* Either "nodefault" and "local" don't appear in the auto key
1068        * locate list (in which case we try the local keyring first) or
1069        * NAME does not appear to be an email address (in which case we
1070        * only try the local keyring).  In this case, lookup NAME in
1071        * the local keyring.  */
1072       add_to_strlist (&namelist, name);
1073       rc = key_byname (ctrl, retctx, namelist, pk, 0,
1074                        include_unusable, ret_keyblock, ret_kdbhd);
1075     }
1076
1077   /* If the requested name resembles a valid mailbox and automatic
1078      retrieval has been enabled, we try to import the key. */
1079   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1080       && mode != GET_PUBKEY_NO_AKL
1081       && (is_mbox || is_fpr))
1082     {
1083       /* NAME wasn't present in the local keyring (or we didn't try
1084        * the local keyring).  Since the auto key locate feature is
1085        * enabled and NAME appears to be an email address, try the auto
1086        * locate feature.  */
1087       for (akl = opt.auto_key_locate; akl; akl = akl->next)
1088         {
1089           unsigned char *fpr = NULL;
1090           size_t fpr_len;
1091           int did_akl_local = 0;
1092           int no_fingerprint = 0;
1093           const char *mechanism_string = "?";
1094
1095           mechanism_type = akl->type;
1096           switch (mechanism_type)
1097             {
1098             case AKL_NODEFAULT:
1099               /* This is a dummy mechanism.  */
1100               mechanism_string = "";
1101               rc = GPG_ERR_NO_PUBKEY;
1102               break;
1103
1104             case AKL_LOCAL:
1105               if (mode == GET_PUBKEY_NO_LOCAL)
1106                 {
1107                   /* Note that we get here in is_fpr more, so there is
1108                    * no extra check for it required.  */
1109                   mechanism_string = "";
1110                   rc = GPG_ERR_NO_PUBKEY;
1111                 }
1112               else
1113                 {
1114                   mechanism_string = "Local";
1115                   did_akl_local = 1;
1116                   if (retctx)
1117                     {
1118                       getkey_end (ctrl, *retctx);
1119                       *retctx = NULL;
1120                     }
1121                   add_to_strlist (&namelist, name);
1122                   rc = key_byname (ctrl, anylocalfirst ? retctx : NULL,
1123                                    namelist, pk, 0,
1124                                    include_unusable, ret_keyblock, ret_kdbhd);
1125                 }
1126               break;
1127
1128             case AKL_CERT:
1129               if (is_fpr)
1130                 {
1131                   mechanism_string = "";
1132                   rc = GPG_ERR_NO_PUBKEY;
1133                 }
1134               else
1135                 {
1136                   mechanism_string = "DNS CERT";
1137                   glo_ctrl.in_auto_key_retrieve++;
1138                   rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len);
1139                   glo_ctrl.in_auto_key_retrieve--;
1140                 }
1141               break;
1142
1143             case AKL_PKA:
1144               /* This is now obsolete.  */
1145               break;
1146
1147             case AKL_DANE:
1148               if (is_fpr)
1149                 {
1150                   mechanism_string = "";
1151                   rc = GPG_ERR_NO_PUBKEY;
1152                   break;
1153                 }
1154               else
1155                 {
1156                   mechanism_string = "DANE";
1157                   glo_ctrl.in_auto_key_retrieve++;
1158                   rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len);
1159                   glo_ctrl.in_auto_key_retrieve--;
1160                 }
1161               break;
1162
1163             case AKL_WKD:
1164               if (is_fpr)
1165                 {
1166                   mechanism_string = "";
1167                   rc = GPG_ERR_NO_PUBKEY;
1168                 }
1169               else
1170                 {
1171                   mechanism_string = "WKD";
1172                   glo_ctrl.in_auto_key_retrieve++;
1173                   rc = keyserver_import_wkd (ctrl, name, 0, &fpr, &fpr_len);
1174                   glo_ctrl.in_auto_key_retrieve--;
1175                 }
1176               break;
1177
1178             case AKL_LDAP:
1179               if (is_fpr)
1180                 {
1181                   mechanism_string = "";
1182                   rc = GPG_ERR_NO_PUBKEY;
1183                 }
1184               else
1185                 {
1186                   mechanism_string = "LDAP";
1187                   glo_ctrl.in_auto_key_retrieve++;
1188                   rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
1189                   glo_ctrl.in_auto_key_retrieve--;
1190                 }
1191               break;
1192
1193             case AKL_NTDS:
1194               mechanism_string = "NTDS";
1195               glo_ctrl.in_auto_key_retrieve++;
1196               if (is_fpr)
1197                 rc = keyserver_import_fprint_ntds (ctrl,
1198                                                    fprbuf.u.fpr, fprbuf.fprlen);
1199               else
1200                 rc = keyserver_import_ntds (ctrl, name, &fpr, &fpr_len);
1201               glo_ctrl.in_auto_key_retrieve--;
1202               break;
1203
1204             case AKL_KEYSERVER:
1205               /* Strictly speaking, we don't need to only use a valid
1206                * mailbox for the getname search, but it helps cut down
1207                * on the problem of searching for something like "john"
1208                * and getting a whole lot of keys back. */
1209               if (keyserver_any_configured (ctrl))
1210                 {
1211                   mechanism_string = "keyserver";
1212                   glo_ctrl.in_auto_key_retrieve++;
1213                   if (is_fpr)
1214                     {
1215                       rc = keyserver_import_fprint (ctrl,
1216                                                     fprbuf.u.fpr, fprbuf.fprlen,
1217                                                     opt.keyserver,
1218                                                     KEYSERVER_IMPORT_FLAG_LDAP);
1219                       /* Map error codes because Dirmngr returns NO
1220                        * DATA if the keyserver does not have the
1221                        * requested key.  It returns NO KEYSERVER if no
1222                        * LDAP keyservers are configured.  */
1223                       if (gpg_err_code (rc) == GPG_ERR_NO_DATA
1224                           || gpg_err_code (rc) == GPG_ERR_NO_KEYSERVER)
1225                         rc = gpg_error (GPG_ERR_NO_PUBKEY);
1226                     }
1227                   else
1228                     {
1229                       rc = keyserver_import_mbox (ctrl, name, &fpr, &fpr_len,
1230                                                   opt.keyserver);
1231                     }
1232                   glo_ctrl.in_auto_key_retrieve--;
1233                 }
1234               else
1235                 {
1236                   mechanism_string = "Unconfigured keyserver";
1237                   rc = GPG_ERR_NO_PUBKEY;
1238                 }
1239               break;
1240
1241             case AKL_SPEC:
1242               {
1243                 struct keyserver_spec *keyserver;
1244
1245                 mechanism_string = akl->spec->uri;
1246                 keyserver = keyserver_match (akl->spec);
1247                 glo_ctrl.in_auto_key_retrieve++;
1248                 if (is_fpr)
1249                   {
1250                     rc = keyserver_import_fprint (ctrl,
1251                                                   fprbuf.u.fpr, fprbuf.fprlen,
1252                                                   opt.keyserver,
1253                                                   KEYSERVER_IMPORT_FLAG_LDAP);
1254                     if (gpg_err_code (rc) == GPG_ERR_NO_DATA
1255                         || gpg_err_code (rc) == GPG_ERR_NO_KEYSERVER)
1256                       rc = gpg_error (GPG_ERR_NO_PUBKEY);
1257                   }
1258                 else
1259                   {
1260                     rc = keyserver_import_mbox (ctrl, name,
1261                                                 &fpr, &fpr_len, keyserver);
1262                   }
1263                 glo_ctrl.in_auto_key_retrieve--;
1264               }
1265               break;
1266             }
1267
1268           /* Use the fingerprint of the key that we actually fetched.
1269            * This helps prevent problems where the key that we fetched
1270            * doesn't have the same name that we used to fetch it.  In
1271            * the case of CERT, this is an actual security
1272            * requirement as the URL might point to a key put in by an
1273            * attacker.  By forcing the use of the fingerprint, we
1274            * won't use the attacker's key here. */
1275           if (!rc && (fpr || is_fpr))
1276             {
1277               char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
1278
1279               if (is_fpr)
1280                 {
1281                   log_assert (fprbuf.fprlen <= MAX_FINGERPRINT_LEN);
1282                   bin2hex (fprbuf.u.fpr, fprbuf.fprlen, fpr_string);
1283                 }
1284               else
1285                 {
1286                   log_assert (fpr_len <= MAX_FINGERPRINT_LEN);
1287                   bin2hex (fpr, fpr_len, fpr_string);
1288                 }
1289
1290               if (opt.verbose)
1291                 log_info ("auto-key-locate found fingerprint %s\n",
1292                           fpr_string);
1293
1294               free_strlist (namelist);
1295               namelist = NULL;
1296               add_to_strlist (&namelist, fpr_string);
1297             }
1298           else if (!rc && !fpr && !did_akl_local)
1299             { /* The acquisition method said no failure occurred, but
1300                * it didn't return a fingerprint.  That's a failure.  */
1301               no_fingerprint = 1;
1302               rc = GPG_ERR_NO_PUBKEY;
1303             }
1304           xfree (fpr);
1305           fpr = NULL;
1306
1307           if (!rc && !did_akl_local)
1308             { /* There was no error and we didn't do a local lookup.
1309                * This means that we imported a key into the local
1310                * keyring.  Try to read the imported key from the
1311                * keyring.  */
1312               if (retctx)
1313                 {
1314                   getkey_end (ctrl, *retctx);
1315                   *retctx = NULL;
1316                 }
1317               rc = key_byname (ctrl, anylocalfirst ? retctx : NULL,
1318                                namelist, pk, 0,
1319                                include_unusable, ret_keyblock, ret_kdbhd);
1320             }
1321           if (!rc)
1322             {
1323               /* Key found.  */
1324               if (opt.verbose)
1325                 log_info (_("automatically retrieved '%s' via %s\n"),
1326                           name, mechanism_string);
1327               break;
1328             }
1329           if ((gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1330                || opt.verbose || no_fingerprint) && *mechanism_string)
1331             log_info (_("error retrieving '%s' via %s: %s\n"),
1332                       name, mechanism_string,
1333                       no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
1334         }
1335     }
1336
1337   if (rc && retctx)
1338     {
1339       getkey_end (ctrl, *retctx);
1340       *retctx = NULL;
1341     }
1342
1343   if (retctx && *retctx)
1344     {
1345       GETKEY_CTX ctx = *retctx;
1346       strlist_t sl;
1347
1348       if (ctx->extra_list)
1349         {
1350           for (sl=ctx->extra_list; sl->next; sl = sl->next)
1351             ;
1352           sl->next = namelist;
1353         }
1354       else
1355         ctx->extra_list = namelist;
1356       (*retctx)->found_via_akl = mechanism_type;
1357     }
1358   else
1359     free_strlist (namelist);
1360
1361   return rc;
1362 }
1363
1364
1365 \f
1366
1367 /* Comparison machinery for get_best_pubkey_byname.  */
1368
1369 /* First we have a struct to cache computed information about the key
1370  * in question.  */
1371 struct pubkey_cmp_cookie
1372 {
1373   int valid;                    /* Is this cookie valid?  */
1374   PKT_public_key key;           /* The key.  */
1375   PKT_user_id *uid;             /* The matching UID packet.  */
1376   unsigned int validity;        /* Computed validity of (KEY, UID).  */
1377   u32 creation_time;            /* Creation time of the newest subkey
1378                                    capable of encryption.  */
1379 };
1380
1381
1382 /* Then we have a series of helper functions.  */
1383 static int
1384 key_is_ok (const PKT_public_key *key)
1385 {
1386   return (! key->has_expired && ! key->flags.revoked
1387           && key->flags.valid && ! key->flags.disabled);
1388 }
1389
1390
1391 static int
1392 uid_is_ok (const PKT_public_key *key, const PKT_user_id *uid)
1393 {
1394   return key_is_ok (key) && ! uid->flags.revoked;
1395 }
1396
1397
1398 static int
1399 subkey_is_ok (const PKT_public_key *sub)
1400 {
1401   return ! sub->flags.revoked && sub->flags.valid && ! sub->flags.disabled;
1402 }
1403
1404 /* Return true if KEYBLOCK has only expired encryption subkeys.  Note
1405  * that the function returns false if the key has no encryption
1406  * subkeys at all or the subkeys are revoked.  */
1407 static int
1408 only_expired_enc_subkeys (kbnode_t keyblock)
1409 {
1410   kbnode_t node;
1411   PKT_public_key *sub;
1412   int any = 0;
1413
1414   for (node = find_next_kbnode (keyblock, PKT_PUBLIC_SUBKEY);
1415        node; node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY))
1416     {
1417       sub = node->pkt->pkt.public_key;
1418
1419       if (!(sub->pubkey_usage & PUBKEY_USAGE_ENC))
1420         continue;
1421
1422       if (!subkey_is_ok (sub))
1423         continue;
1424
1425       any = 1;
1426       if (!sub->has_expired)
1427         return 0;
1428     }
1429
1430   return any? 1 : 0;
1431 }
1432
1433 /* Finally this function compares a NEW key to the former candidate
1434  * OLD.  Returns < 0 if the old key is worse, > 0 if the old key is
1435  * better, == 0 if it is a tie.  */
1436 static int
1437 pubkey_cmp (ctrl_t ctrl, const char *name, struct pubkey_cmp_cookie *old,
1438             struct pubkey_cmp_cookie *new, KBNODE new_keyblock)
1439 {
1440   kbnode_t n;
1441
1442   if ((new->key.pubkey_usage & PUBKEY_USAGE_ENC) == 0)
1443     new->creation_time = 0;
1444   else
1445     new->creation_time = new->key.timestamp;
1446
1447   for (n = find_next_kbnode (new_keyblock, PKT_PUBLIC_SUBKEY);
1448        n; n = find_next_kbnode (n, PKT_PUBLIC_SUBKEY))
1449     {
1450       PKT_public_key *sub = n->pkt->pkt.public_key;
1451
1452       if ((sub->pubkey_usage & PUBKEY_USAGE_ENC) == 0)
1453         continue;
1454
1455       if (! subkey_is_ok (sub))
1456         continue;
1457
1458       if (sub->timestamp > new->creation_time)
1459         new->creation_time = sub->timestamp;
1460     }
1461
1462   /* When new key has no encryption key, use OLD key.  */
1463   if (new->creation_time == 0)
1464     return 1;
1465
1466   for (n = find_next_kbnode (new_keyblock, PKT_USER_ID);
1467        n; n = find_next_kbnode (n, PKT_USER_ID))
1468     {
1469       PKT_user_id *uid = n->pkt->pkt.user_id;
1470       char *mbox = mailbox_from_userid (uid->name, 0);
1471       int match = mbox ? strcasecmp (name, mbox) == 0 : 0;
1472
1473       xfree (mbox);
1474       if (! match)
1475         continue;
1476
1477       new->uid = scopy_user_id (uid);
1478       new->validity =
1479         get_validity (ctrl, new_keyblock, &new->key, uid, NULL, 0) & TRUST_MASK;
1480       new->valid = 1;
1481
1482       if (! old->valid)
1483         return -1;      /* No OLD key.  */
1484
1485       if (! uid_is_ok (&old->key, old->uid) && uid_is_ok (&new->key, uid))
1486         return -1;      /* Validity of the NEW key is better.  */
1487
1488       if (new->validity != TRUST_EXPIRED && old->validity < new->validity)
1489         return -1;      /* Validity of the NEW key is better.  */
1490       if (old->validity == TRUST_EXPIRED && new->validity != TRUST_EXPIRED)
1491         return -1;      /* Validity of the NEW key is better.  */
1492
1493       if (old->validity == new->validity && uid_is_ok (&new->key, uid)
1494           && old->creation_time < new->creation_time)
1495         return -1;      /* Both keys are of the same validity, but the
1496                            NEW key is newer.  */
1497     }
1498
1499   /* Stick with the OLD key.  */
1500   return 1;
1501 }
1502
1503
1504 /* This function works like get_pubkey_byname, but if the name
1505  * resembles a mail address, the results are ranked and only the best
1506  * result is returned.  */
1507 gpg_error_t
1508 get_best_pubkey_byname (ctrl_t ctrl, enum get_pubkey_modes mode,
1509                         GETKEY_CTX *retctx, PKT_public_key *pk,
1510                         const char *name, KBNODE *ret_keyblock,
1511                         int include_unusable)
1512 {
1513   gpg_error_t err;
1514   struct getkey_ctx_s *ctx = NULL;
1515   int is_mbox;
1516   int wkd_tried = 0;
1517   PKT_public_key pk0;
1518
1519   log_assert (ret_keyblock != NULL);
1520
1521   if (retctx)
1522     *retctx = NULL;
1523
1524   memset (&pk0, 0, sizeof pk0);
1525   pk0.req_usage = pk? pk->req_usage : 0;
1526
1527   is_mbox = is_valid_mailbox (name);
1528   if (!is_mbox && *name == '<' && name[1] && name[strlen(name)-1]=='>'
1529       && name[1] != '>'
1530       && is_valid_mailbox_mem (name+1, strlen (name)-2))
1531     {
1532       /* The mailbox is in the form "<foo@example.org>" which is not
1533        * detected by is_valid_mailbox.  Set the flag but keep name as
1534        * it is because get_pubkey_byname does an is_valid_mailbox_mem
1535        * itself.  */
1536       is_mbox = 1;
1537     }
1538
1539  start_over:
1540   if (ctx)  /* Clear  in case of a start over.  */
1541     {
1542       release_kbnode (*ret_keyblock);
1543       *ret_keyblock = NULL;
1544       getkey_end (ctrl, ctx);
1545       ctx = NULL;
1546     }
1547   err = get_pubkey_byname (ctrl, mode,
1548                            &ctx, &pk0, name, ret_keyblock,
1549                            NULL, include_unusable);
1550   if (err)
1551     {
1552       goto leave;
1553     }
1554
1555   /* If the keyblock was retrieved from the local database and the key
1556    * has expired, do further checks.  However, we can do this only if
1557    * the caller requested a keyblock.  */
1558   if (is_mbox && ctx && ctx->found_via_akl == AKL_LOCAL)
1559     {
1560       u32 now = make_timestamp ();
1561       int found;
1562
1563       /* If the key has expired and its origin was the WKD then try to
1564        * get a fresh key from the WKD.  We also try this if the key
1565        * has any only expired encryption subkeys.  In case we checked
1566        * for a fresh copy in the last 3 hours we won't do that again.
1567        * Unfortunately that does not yet work because KEYUPDATE is
1568        * only updated during import iff the key has actually changed
1569        * (see import.c:import_one).  */
1570       if (!wkd_tried && pk0.keyorg == KEYORG_WKD
1571           && (pk0.keyupdate + 3*3600) < now
1572           && (pk0.has_expired || only_expired_enc_subkeys (*ret_keyblock)))
1573         {
1574           if (opt.verbose)
1575             log_info (_("checking for a fresh copy of an expired key via %s\n"),
1576                       "WKD");
1577           wkd_tried = 1;
1578           glo_ctrl.in_auto_key_retrieve++;
1579           found = !keyserver_import_wkd (ctrl, name, 0, NULL, NULL);
1580           glo_ctrl.in_auto_key_retrieve--;
1581           if (found)
1582             {
1583               release_public_key_parts (&pk0);
1584               goto start_over;
1585             }
1586         }
1587     }
1588
1589   if (is_mbox && ctx)
1590     {
1591       /* Rank results and return only the most relevant key for encryption.  */
1592       struct pubkey_cmp_cookie best = { 0 };
1593       struct pubkey_cmp_cookie new = { 0 };
1594       kbnode_t new_keyblock;
1595
1596       copy_public_key (&new.key, &pk0);
1597       if (pubkey_cmp (ctrl, name, &best, &new, *ret_keyblock) >= 0)
1598         {
1599           release_public_key_parts (&new.key);
1600           free_user_id (new.uid);
1601         }
1602       else
1603         best = new;
1604       new.uid = NULL;
1605
1606       while (getkey_next (ctrl, ctx, &new.key, &new_keyblock) == 0)
1607         {
1608           int diff = pubkey_cmp (ctrl, name, &best, &new, new_keyblock);
1609           release_kbnode (new_keyblock);
1610           if (diff < 0)
1611             {
1612               /* New key is better.  */
1613               release_public_key_parts (&best.key);
1614               free_user_id (best.uid);
1615               best = new;
1616             }
1617           else if (diff > 0)
1618             {
1619               /* Old key is better.  */
1620               release_public_key_parts (&new.key);
1621               free_user_id (new.uid);
1622             }
1623           else
1624             {
1625               /* A tie.  Keep the old key.  */
1626               release_public_key_parts (&new.key);
1627               free_user_id (new.uid);
1628             }
1629           new.uid = NULL;
1630         }
1631
1632       getkey_end (ctrl, ctx);
1633       ctx = NULL;
1634       free_user_id (best.uid);
1635       best.uid = NULL;
1636
1637       if (best.valid)
1638         {
1639           ctx = xtrycalloc (1, sizeof **retctx);
1640           if (! ctx)
1641             err = gpg_error_from_syserror ();
1642           else
1643             {
1644               ctx->kr_handle = keydb_new (ctrl);
1645               if (! ctx->kr_handle)
1646                 {
1647                   err = gpg_error_from_syserror ();
1648                   xfree (ctx);
1649                   ctx = NULL;
1650                   if (retctx)
1651                     *retctx = NULL;
1652                 }
1653               else
1654                 {
1655                   u32 *keyid = pk_keyid (&best.key);
1656                   ctx->exact = 1;
1657                   ctx->nitems = 1;
1658                   ctx->items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
1659                   ctx->items[0].u.kid[0] = keyid[0];
1660                   ctx->items[0].u.kid[1] = keyid[1];
1661
1662                   release_kbnode (*ret_keyblock);
1663                   *ret_keyblock = NULL;
1664                   err = getkey_next (ctrl, ctx, NULL, ret_keyblock);
1665                 }
1666             }
1667
1668           if (pk)
1669             *pk = best.key;
1670           else
1671             release_public_key_parts (&best.key);
1672           release_public_key_parts (&pk0);
1673         }
1674       else
1675         {
1676           if (pk)
1677             *pk = pk0;
1678           else
1679             release_public_key_parts (&pk0);
1680         }
1681     }
1682   else
1683     {
1684       if (pk)
1685         *pk = pk0;
1686       else
1687         release_public_key_parts (&pk0);
1688     }
1689
1690   if (err && ctx)
1691     {
1692       getkey_end (ctrl, ctx);
1693       ctx = NULL;
1694     }
1695
1696   if (retctx && ctx)
1697     {
1698       *retctx = ctx;
1699       ctx = NULL;
1700     }
1701
1702  leave:
1703   getkey_end (ctrl, ctx);
1704   return err;
1705 }
1706
1707 \f
1708
1709 /* Get a public key from a file.
1710  *
1711  * PK is the buffer to store the key.  The caller needs to make sure
1712  * that PK->REQ_USAGE is valid.  PK->REQ_USAGE is passed through to
1713  * the lookup function and is a mask of PUBKEY_USAGE_SIG,
1714  * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.  If this is non-zero, only
1715  * keys with the specified usage will be returned.
1716  *
1717  * FNAME is the file name.  That file should contain exactly one
1718  * keyblock.
1719  *
1720  * This function returns 0 on success.  Otherwise, an error code is
1721  * returned.  In particular, GPG_ERR_NO_PUBKEY is returned if the key
1722  * is not found.  If R_KEYBLOCK is not NULL and a key was found the
1723  * keyblock is stored there; otherwiese NULL is stored there.
1724  *
1725  * The self-signed data has already been merged into the public key
1726  * using merge_selfsigs.  The caller must release the content of PK by
1727  * calling release_public_key_parts (or, if PK was malloced, using
1728  * free_public_key).
1729  */
1730 gpg_error_t
1731 get_pubkey_fromfile (ctrl_t ctrl, PKT_public_key *pk, const char *fname,
1732                      kbnode_t *r_keyblock)
1733 {
1734   gpg_error_t err;
1735   kbnode_t keyblock;
1736   kbnode_t found_key;
1737   unsigned int infoflags;
1738
1739   if (r_keyblock)
1740     *r_keyblock = NULL;
1741
1742   err = read_key_from_file_or_buffer (ctrl, fname, NULL, 0, &keyblock);
1743   if (!err)
1744     {
1745       /* Warning: node flag bits 0 and 1 should be preserved by
1746        * merge_selfsigs.  FIXME: Check whether this still holds. */
1747       merge_selfsigs (ctrl, keyblock);
1748       found_key = finish_lookup (keyblock, pk->req_usage, 0, 0, &infoflags);
1749       print_status_key_considered (keyblock, infoflags);
1750       if (found_key)
1751         pk_from_block (pk, keyblock, found_key);
1752       else
1753         err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
1754     }
1755
1756   if (!err && r_keyblock)
1757     *r_keyblock = keyblock;
1758   else
1759     release_kbnode (keyblock);
1760   return err;
1761 }
1762
1763
1764 /* Return a public key from the buffer (BUFFER, BUFLEN).  The key is
1765  * onlyretruned if it matches the keyid given in WANT_KEYID. On
1766  * success the key is stored at the caller provided PKBUF structure.
1767  * The caller must release the content of PK by calling
1768  * release_public_key_parts (or, if PKBUF was malloced, using
1769  * free_public_key).  If R_KEYBLOCK is not NULL the full keyblock is
1770  * also stored there.  */
1771 gpg_error_t
1772 get_pubkey_from_buffer (ctrl_t ctrl, PKT_public_key *pkbuf,
1773                         const void *buffer, size_t buflen, u32 *want_keyid,
1774                         kbnode_t *r_keyblock)
1775 {
1776   gpg_error_t err;
1777   kbnode_t keyblock;
1778   kbnode_t node;
1779   PKT_public_key *pk;
1780
1781   if (r_keyblock)
1782     *r_keyblock = NULL;
1783
1784   err = read_key_from_file_or_buffer (ctrl, NULL, buffer, buflen, &keyblock);
1785   if (!err)
1786     {
1787       merge_selfsigs (ctrl, keyblock);
1788       for (node = keyblock; node; node = node->next)
1789         {
1790           if (node->pkt->pkttype == PKT_PUBLIC_KEY
1791               || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1792             {
1793               pk = node->pkt->pkt.public_key;
1794               keyid_from_pk (pk, NULL);
1795               if (pk->keyid[0] == want_keyid[0]
1796                   && pk->keyid[1] == want_keyid[1])
1797                 break;
1798             }
1799         }
1800       if (node)
1801         copy_public_key (pkbuf, pk);
1802       else
1803         err = gpg_error (GPG_ERR_NO_PUBKEY);
1804     }
1805
1806   if (!err && r_keyblock)
1807     *r_keyblock = keyblock;
1808   else
1809     release_kbnode (keyblock);
1810   return err;
1811 }
1812
1813
1814 /* Lookup a key with the specified fingerprint.
1815  *
1816  * If PK is not NULL, the public key of the first result is returned
1817  * in *PK.  Note: this function does an exact search and thus the
1818  * returned public key may be a subkey rather than the primary key.
1819  * Note: The self-signed data has already been merged into the public
1820  * key using merge_selfsigs.  Free *PK by calling
1821  * release_public_key_parts (or, if PK was allocated using xmalloc, you
1822  * can use free_public_key, which calls release_public_key_parts(PK)
1823  * and then xfree(PK)).
1824  *
1825  * If PK->REQ_USAGE is set, it is used to filter the search results.
1826  * Thus, if PK is not NULL, PK->REQ_USAGE must be valid!  See the
1827  * documentation for finish_lookup to understand exactly how this is
1828  * used.
1829  *
1830  * If R_KEYBLOCK is not NULL, then the first result's keyblock is
1831  * returned in *R_KEYBLOCK.  This should be freed using
1832  * release_kbnode().
1833  *
1834  * FPRINT is a byte array whose contents is the fingerprint to use as
1835  * the search term.  FPRINT_LEN specifies the length of the
1836  * fingerprint (in bytes).  Currently, only 16, 20, and 32-byte
1837  * fingerprints are supported.
1838  *
1839  * FIXME: We should replace this with the _byname function.  This can
1840  * be done by creating a userID conforming to the unified fingerprint
1841  * style.  */
1842 int
1843 get_pubkey_byfprint (ctrl_t ctrl, PKT_public_key *pk, kbnode_t *r_keyblock,
1844                      const byte * fprint, size_t fprint_len)
1845 {
1846   int rc;
1847
1848   if (r_keyblock)
1849     *r_keyblock = NULL;
1850
1851   if (fprint_len == 32 || fprint_len == 20 || fprint_len == 16)
1852     {
1853       struct getkey_ctx_s ctx;
1854       KBNODE kb = NULL;
1855       KBNODE found_key = NULL;
1856
1857       memset (&ctx, 0, sizeof ctx);
1858       ctx.exact = 1;
1859       ctx.not_allocated = 1;
1860       /* FIXME: We should get the handle from the cache like we do in
1861        * get_pubkey.  */
1862       ctx.kr_handle = keydb_new (ctrl);
1863       if (!ctx.kr_handle)
1864         return gpg_error_from_syserror ();
1865
1866       ctx.nitems = 1;
1867       ctx.items[0].mode = KEYDB_SEARCH_MODE_FPR;
1868       memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1869       ctx.items[0].fprlen = fprint_len;
1870       if (pk)
1871         ctx.req_usage = pk->req_usage;
1872       rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
1873       if (!rc && pk)
1874         pk_from_block (pk, kb, found_key);
1875       if (!rc && r_keyblock)
1876         {
1877           *r_keyblock = kb;
1878           kb = NULL;
1879         }
1880       release_kbnode (kb);
1881       getkey_end (ctrl, &ctx);
1882     }
1883   else
1884     rc = GPG_ERR_GENERAL; /* Oops */
1885   return rc;
1886 }
1887
1888
1889 /* This function is similar to get_pubkey_byfprint, but it doesn't
1890  * merge the self-signed data into the public key and subkeys or into
1891  * the user ids.  It also doesn't add the key to the user id cache.
1892  * Further, this function ignores PK->REQ_USAGE.
1893  *
1894  * This function is intended to avoid recursion and, as such, should
1895  * only be used in very specific situations.
1896  *
1897  * Like get_pubkey_byfprint, PK may be NULL.  In that case, this
1898  * function effectively just checks for the existence of the key.  */
1899 gpg_error_t
1900 get_pubkey_byfprint_fast (ctrl_t ctrl, PKT_public_key * pk,
1901                           const byte * fprint, size_t fprint_len)
1902 {
1903   gpg_error_t err;
1904   KBNODE keyblock;
1905
1906   err = get_keyblock_byfprint_fast (ctrl,
1907                                     &keyblock, NULL, fprint, fprint_len, 0);
1908   if (!err)
1909     {
1910       if (pk)
1911         copy_public_key (pk, keyblock->pkt->pkt.public_key);
1912       release_kbnode (keyblock);
1913     }
1914
1915   return err;
1916 }
1917
1918
1919 /* This function is similar to get_pubkey_byfprint_fast but returns a
1920  * keydb handle at R_HD and the keyblock at R_KEYBLOCK.  R_KEYBLOCK or
1921  * R_HD may be NULL.  If LOCK is set the handle has been opend in
1922  * locked mode and keydb_disable_caching () has been called.  On error
1923  * R_KEYBLOCK is set to NULL but R_HD must be released by the caller;
1924  * it may have a value of NULL, though.  This allows to do an insert
1925  * operation on a locked keydb handle.  */
1926 gpg_error_t
1927 get_keyblock_byfprint_fast (ctrl_t ctrl,
1928                             kbnode_t *r_keyblock, KEYDB_HANDLE *r_hd,
1929                             const byte *fprint, size_t fprint_len, int lock)
1930 {
1931   gpg_error_t err;
1932   KEYDB_HANDLE hd;
1933   kbnode_t keyblock;
1934   byte fprbuf[MAX_FINGERPRINT_LEN];
1935   int i;
1936
1937   if (r_keyblock)
1938     *r_keyblock = NULL;
1939   if (r_hd)
1940     *r_hd = NULL;
1941
1942   for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1943     fprbuf[i] = fprint[i];
1944
1945   hd = keydb_new (ctrl);
1946   if (!hd)
1947     return gpg_error_from_syserror ();
1948
1949   if (lock)
1950     {
1951       err = keydb_lock (hd);
1952       if (err)
1953         {
1954           /* If locking did not work, we better don't return a handle
1955            * at all - there was a reason that locking has been
1956            * requested.  */
1957           keydb_release (hd);
1958           return err;
1959         }
1960       keydb_disable_caching (hd);
1961     }
1962
1963   /* For all other errors we return the handle.  */
1964   if (r_hd)
1965     *r_hd = hd;
1966
1967   err = keydb_search_fpr (hd, fprbuf, fprint_len);
1968   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1969     {
1970       if (!r_hd)
1971         keydb_release (hd);
1972       return gpg_error (GPG_ERR_NO_PUBKEY);
1973     }
1974   err = keydb_get_keyblock (hd, &keyblock);
1975   if (err)
1976     {
1977       log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (err));
1978       if (!r_hd)
1979         keydb_release (hd);
1980       return gpg_error (GPG_ERR_NO_PUBKEY);
1981     }
1982
1983   log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1984               || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1985
1986   /* Not caching key here since it won't have all of the fields
1987      properly set. */
1988
1989   if (r_keyblock)
1990     *r_keyblock = keyblock;
1991   else
1992     release_kbnode (keyblock);
1993
1994   if (!r_hd)
1995     keydb_release (hd);
1996
1997   return 0;
1998 }
1999
2000
2001 const char *
2002 parse_def_secret_key (ctrl_t ctrl)
2003 {
2004   KEYDB_HANDLE hd = NULL;
2005   strlist_t t;
2006   static int warned;
2007
2008   for (t = opt.def_secret_key; t; t = t->next)
2009     {
2010       gpg_error_t err;
2011       KEYDB_SEARCH_DESC desc;
2012       KBNODE kb;
2013       KBNODE node;
2014
2015       err = classify_user_id (t->d, &desc, 1);
2016       if (err)
2017         {
2018           log_error (_("secret key \"%s\" not found: %s\n"),
2019                      t->d, gpg_strerror (err));
2020           if (!opt.quiet)
2021             log_info (_("(check argument of option '%s')\n"), "--default-key");
2022           continue;
2023         }
2024
2025       if (! hd)
2026         {
2027           hd = keydb_new (ctrl);
2028           if (!hd)
2029             return NULL;
2030         }
2031       else
2032         keydb_search_reset (hd);
2033
2034
2035       err = keydb_search (hd, &desc, 1, NULL);
2036       if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2037         continue;
2038
2039       if (err)
2040         {
2041           log_error (_("key \"%s\" not found: %s\n"), t->d, gpg_strerror (err));
2042           t = NULL;
2043           break;
2044         }
2045
2046       err = keydb_get_keyblock (hd, &kb);
2047       if (err)
2048         {
2049           log_error (_("error reading keyblock: %s\n"),
2050                      gpg_strerror (err));
2051           continue;
2052         }
2053
2054       merge_selfsigs (ctrl, kb);
2055
2056       err = gpg_error (GPG_ERR_NO_SECKEY);
2057       node = kb;
2058       do
2059         {
2060           PKT_public_key *pk = node->pkt->pkt.public_key;
2061
2062           /* Check if the key is valid.  */
2063           if (pk->flags.revoked)
2064             {
2065               if (DBG_LOOKUP)
2066                 log_debug ("not using %s as default key, %s",
2067                            keystr_from_pk (pk), "revoked");
2068               continue;
2069             }
2070           if (pk->has_expired)
2071             {
2072               if (DBG_LOOKUP)
2073                 log_debug ("not using %s as default key, %s",
2074                            keystr_from_pk (pk), "expired");
2075               continue;
2076             }
2077           if (pk_is_disabled (pk))
2078             {
2079               if (DBG_LOOKUP)
2080                 log_debug ("not using %s as default key, %s",
2081                            keystr_from_pk (pk), "disabled");
2082               continue;
2083             }
2084
2085           if (agent_probe_secret_key (ctrl, pk))
2086             {
2087               /* This is a valid key.  */
2088               err = 0;
2089               break;
2090             }
2091         }
2092       while ((node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY)));
2093
2094       release_kbnode (kb);
2095       if (err)
2096         {
2097           if (! warned && ! opt.quiet)
2098             {
2099               log_info (_("Warning: not using '%s' as default key: %s\n"),
2100                         t->d, gpg_strerror (GPG_ERR_NO_SECKEY));
2101               print_reported_error (err, GPG_ERR_NO_SECKEY);
2102             }
2103         }
2104       else
2105         {
2106           if (! warned && ! opt.quiet)
2107             log_info (_("using \"%s\" as default secret key for signing\n"),
2108                       t->d);
2109           break;
2110         }
2111     }
2112
2113   if (! warned && opt.def_secret_key && ! t)
2114     log_info (_("all values passed to '%s' ignored\n"),
2115               "--default-key");
2116
2117   warned = 1;
2118
2119   if (hd)
2120     keydb_release (hd);
2121
2122   if (t)
2123     return t->d;
2124   return NULL;
2125 }
2126
2127
2128 /* Look up a secret key.
2129  *
2130  * If PK is not NULL, the public key of the first result is returned
2131  * in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
2132  * set, it is used to filter the search results.  See the
2133  * documentation for finish_lookup to understand exactly how this is
2134  * used.  Note: The self-signed data has already been merged into the
2135  * public key using merge_selfsigs.  Free *PK by calling
2136  * release_public_key_parts (or, if PK was allocated using xfree, you
2137  * can use free_public_key, which calls release_public_key_parts(PK)
2138  * and then xfree(PK)).
2139  *
2140  * If --default-key was set, then the specified key is looked up.  (In
2141  * this case, the default key is returned even if it is considered
2142  * unusable.  See the documentation for skip_unusable for exactly what
2143  * this means.)
2144  *
2145  * Otherwise, this initiates a DB scan that returns all keys that are
2146  * usable (see previous paragraph for exactly what usable means) and
2147  * for which a secret key is available.
2148  *
2149  * This function returns the first match.  Additional results can be
2150  * returned using getkey_next.  */
2151 gpg_error_t
2152 get_seckey_default (ctrl_t ctrl, PKT_public_key *pk)
2153 {
2154   gpg_error_t err;
2155   strlist_t namelist = NULL;
2156   int include_unusable = 1;
2157
2158
2159   const char *def_secret_key = parse_def_secret_key (ctrl);
2160   if (def_secret_key)
2161     add_to_strlist (&namelist, def_secret_key);
2162   else
2163     include_unusable = 0;
2164
2165   err = key_byname (ctrl, NULL, namelist, pk, 1, include_unusable, NULL, NULL);
2166
2167   free_strlist (namelist);
2168
2169   return err;
2170 }
2171
2172
2173 \f
2174 /* Search for keys matching some criteria.
2175  *
2176  * If RETCTX is not NULL, then the constructed context is returned in
2177  * *RETCTX so that getpubkey_next can be used to get subsequent
2178  * results.  In this case, getkey_end() must be used to free the
2179  * search context.  If RETCTX is not NULL, then RET_KDBHD must be
2180  * NULL.
2181  *
2182  * If PK is not NULL, the public key of the first result is returned
2183  * in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
2184  * set, it is used to filter the search results.  See the
2185  * documentation for finish_lookup to understand exactly how this is
2186  * used.  Note: The self-signed data has already been merged into the
2187  * public key using merge_selfsigs.  Free *PK by calling
2188  * release_public_key_parts (or, if PK was allocated using xfree, you
2189  * can use free_public_key, which calls release_public_key_parts(PK)
2190  * and then xfree(PK)).
2191  *
2192  * If NAMES is not NULL, then a search query is constructed using
2193  * classify_user_id on each of the strings in the list.  (Recall: the
2194  * database does an OR of the terms, not an AND.)  If NAMES is
2195  * NULL, then all results are returned.
2196  *
2197  * If WANT_SECRET is set, then only keys with an available secret key
2198  * (either locally or via key registered on a smartcard) are returned.
2199  *
2200  * This function does not skip unusable keys (see the documentation
2201  * for skip_unusable for an exact definition).
2202  *
2203  * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2204  * *RET_KEYBLOCK.  This should be freed using release_kbnode().
2205  *
2206  * This function returns 0 on success.  Otherwise, an error code is
2207  * returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2208  * (if want_secret is set) is returned if the key is not found.  */
2209 gpg_error_t
2210 getkey_bynames (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2211                 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
2212 {
2213   return key_byname (ctrl, retctx, names, pk, want_secret, 1,
2214                      ret_keyblock, NULL);
2215 }
2216
2217
2218 /* Search for one key matching some criteria.
2219  *
2220  * If RETCTX is not NULL, then the constructed context is returned in
2221  * *RETCTX so that getpubkey_next can be used to get subsequent
2222  * results.  In this case, getkey_end() must be used to free the
2223  * search context.  If RETCTX is not NULL, then RET_KDBHD must be
2224  * NULL.
2225  *
2226  * If PK is not NULL, the public key of the first result is returned
2227  * in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
2228  * set, it is used to filter the search results.  See the
2229  * documentation for finish_lookup to understand exactly how this is
2230  * used.  Note: The self-signed data has already been merged into the
2231  * public key using merge_selfsigs.  Free *PK by calling
2232  * release_public_key_parts (or, if PK was allocated using xfree, you
2233  * can use free_public_key, which calls release_public_key_parts(PK)
2234  * and then xfree(PK)).
2235  *
2236  * If NAME is not NULL, then a search query is constructed using
2237  * classify_user_id on the string.  In this case, even unusable keys
2238  * (see the documentation for skip_unusable for an exact definition of
2239  * unusable) are returned.  Otherwise, if --default-key was set, then
2240  * that key is returned (even if it is unusable).  If neither of these
2241  * conditions holds, then the first usable key is returned.
2242  *
2243  * If WANT_SECRET is set, then only keys with an available secret key
2244  * (either locally or via key registered on a smartcard) are returned.
2245  *
2246  * This function does not skip unusable keys (see the documentation
2247  * for skip_unusable for an exact definition).
2248  *
2249  * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2250  * *RET_KEYBLOCK.  This should be freed using release_kbnode().
2251  *
2252  * This function returns 0 on success.  Otherwise, an error code is
2253  * returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2254  * (if want_secret is set) is returned if the key is not found.
2255  *
2256  * FIXME: We also have the get_pubkey_byname function which has a
2257  * different semantic.  Should be merged with this one.  */
2258 gpg_error_t
2259 getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2260                const char *name, int want_secret, kbnode_t *ret_keyblock)
2261 {
2262   gpg_error_t err;
2263   strlist_t namelist = NULL;
2264   int with_unusable = 1;
2265   const char *def_secret_key = NULL;
2266
2267   if (want_secret && !name)
2268     def_secret_key = parse_def_secret_key (ctrl);
2269
2270   if (want_secret && !name && def_secret_key)
2271     add_to_strlist (&namelist, def_secret_key);
2272   else if (name)
2273     add_to_strlist (&namelist, name);
2274   else
2275     with_unusable = 0;
2276
2277   err = key_byname (ctrl, retctx, namelist, pk, want_secret, with_unusable,
2278                     ret_keyblock, NULL);
2279
2280   /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
2281      WANT_SECRET has been used.  */
2282
2283   free_strlist (namelist);
2284
2285   return err;
2286 }
2287
2288
2289 /* Return the next search result.
2290  *
2291  * If PK is not NULL, the public key of the next result is returned in
2292  * *PK.  Note: The self-signed data has already been merged into the
2293  * public key using merge_selfsigs.  Free *PK by calling
2294  * release_public_key_parts (or, if PK was allocated using xmalloc, you
2295  * can use free_public_key, which calls release_public_key_parts(PK)
2296  * and then xfree(PK)).
2297  *
2298  * RET_KEYBLOCK can be given as NULL; if it is not NULL it the entire
2299  * found keyblock is returned which must be released with
2300  * release_kbnode.  If the function returns an error NULL is stored at
2301  * RET_KEYBLOCK.
2302  *
2303  * The self-signed data has already been merged into the public key
2304  * using merge_selfsigs.  */
2305 gpg_error_t
2306 getkey_next (ctrl_t ctrl, getkey_ctx_t ctx,
2307              PKT_public_key *pk, kbnode_t *ret_keyblock)
2308 {
2309   int rc; /* Fixme:  Make sure this is proper gpg_error */
2310   KBNODE keyblock = NULL;
2311   KBNODE found_key = NULL;
2312
2313   /* We need to disable the caching so that for an exact key search we
2314      won't get the result back from the cache and thus end up in an
2315      endless loop.  The endless loop can occur, because the cache is
2316      used without respecting the current file pointer!  */
2317   keydb_disable_caching (ctx->kr_handle);
2318
2319   /* FOUND_KEY is only valid as long as RET_KEYBLOCK is.  If the
2320    * caller wants PK, but not RET_KEYBLOCK, we need hand in our own
2321    * keyblock.  */
2322   if (pk && ret_keyblock == NULL)
2323       ret_keyblock = &keyblock;
2324
2325   rc = lookup (ctrl, ctx, ctx->want_secret,
2326                ret_keyblock, pk ? &found_key : NULL);
2327   if (!rc && pk)
2328     {
2329       log_assert (found_key);
2330       pk_from_block (pk, NULL, found_key);
2331       release_kbnode (keyblock);
2332     }
2333
2334   return rc;
2335 }
2336
2337
2338 /* Release any resources used by a key listing context.  This must be
2339  * called on the context returned by, e.g., getkey_byname.  */
2340 void
2341 getkey_end (ctrl_t ctrl, getkey_ctx_t ctx)
2342 {
2343   if (ctx)
2344     {
2345 #ifdef HAVE_W32_SYSTEM
2346
2347       /* FIXME: This creates a big regression for Windows because the
2348        * keyring is only released after the global ctrl is released.
2349        * So if an operation does a getkey and then tries to modify the
2350        * keyring it will fail on Windows with a sharing violation.  We
2351        * need to modify all keyring write operations to also take the
2352        * ctrl and close the cached_getkey_kdb handle to make writing
2353        * work.  See: GnuPG-bug-id: 3097  */
2354       (void)ctrl;
2355       keydb_release (ctx->kr_handle);
2356
2357 #else /*!HAVE_W32_SYSTEM*/
2358
2359       if (ctrl && !ctrl->cached_getkey_kdb)
2360         ctrl->cached_getkey_kdb = ctx->kr_handle;
2361       else
2362         keydb_release (ctx->kr_handle);
2363
2364 #endif /*!HAVE_W32_SYSTEM*/
2365
2366       free_strlist (ctx->extra_list);
2367       if (!ctx->not_allocated)
2368         xfree (ctx);
2369     }
2370 }
2371
2372
2373 \f
2374 /************************************************
2375  ************* Merging stuff ********************
2376  ************************************************/
2377
2378 /* Set the mainkey_id fields for all keys in KEYBLOCK.  This is
2379  * usually done by merge_selfsigs but at some places we only need the
2380  * main_kid not a full merge.  The function also guarantees that all
2381  * pk->keyids are computed.  */
2382 void
2383 setup_main_keyids (kbnode_t keyblock)
2384 {
2385   u32 kid[2], mainkid[2];
2386   kbnode_t kbctx, node;
2387   PKT_public_key *pk;
2388
2389   if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2390     BUG ();
2391   pk = keyblock->pkt->pkt.public_key;
2392
2393   keyid_from_pk (pk, mainkid);
2394   for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
2395     {
2396       if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
2397             || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
2398         continue;
2399       pk = node->pkt->pkt.public_key;
2400       keyid_from_pk (pk, kid); /* Make sure pk->keyid is set.  */
2401       if (!pk->main_keyid[0] && !pk->main_keyid[1])
2402         {
2403           pk->main_keyid[0] = mainkid[0];
2404           pk->main_keyid[1] = mainkid[1];
2405         }
2406     }
2407 }
2408
2409
2410 /* KEYBLOCK corresponds to a public key block.  This function merges
2411  * much of the information from the self-signed data into the public
2412  * key, public subkey and user id data structures.  If you use the
2413  * high-level search API (e.g., get_pubkey) for looking up key blocks,
2414  * then you don't need to call this function.  This function is
2415  * useful, however, if you change the keyblock, e.g., by adding or
2416  * removing a self-signed data packet.  */
2417 void
2418 merge_keys_and_selfsig (ctrl_t ctrl, kbnode_t keyblock)
2419 {
2420   if (!keyblock)
2421     ;
2422   else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
2423     merge_selfsigs (ctrl, keyblock);
2424   else
2425     log_debug ("FIXME: merging secret key blocks is not anymore available\n");
2426 }
2427
2428
2429 /* This function parses the key flags and returns PUBKEY_USAGE_ flags.  */
2430 unsigned int
2431 parse_key_usage (PKT_signature * sig)
2432 {
2433   int key_usage = 0;
2434   const byte *p;
2435   size_t n;
2436   byte flags;
2437
2438   p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_FLAGS, &n);
2439   if (p && n)
2440     {
2441       /* First octet of the keyflags.  */
2442       flags = *p;
2443
2444       if (flags & 1)
2445         {
2446           key_usage |= PUBKEY_USAGE_CERT;
2447           flags &= ~1;
2448         }
2449
2450       if (flags & 2)
2451         {
2452           key_usage |= PUBKEY_USAGE_SIG;
2453           flags &= ~2;
2454         }
2455
2456       /* We do not distinguish between encrypting communications and
2457          encrypting storage. */
2458       if (flags & (0x04 | 0x08))
2459         {
2460           key_usage |= PUBKEY_USAGE_ENC;
2461           flags &= ~(0x04 | 0x08);
2462         }
2463
2464       if (flags & 0x20)
2465         {
2466           key_usage |= PUBKEY_USAGE_AUTH;
2467           flags &= ~0x20;
2468         }
2469
2470       if ((flags & 0x80))
2471         {
2472           key_usage |= PUBKEY_USAGE_GROUP;
2473           flags &= ~0x80;
2474         }
2475
2476       if (flags)
2477         key_usage |= PUBKEY_USAGE_UNKNOWN;
2478
2479       n--;
2480       p++;
2481       if (n)
2482         {
2483           flags = *p;
2484           if ((flags & 0x04))
2485             key_usage |= PUBKEY_USAGE_RENC;
2486           if ((flags & 0x08))
2487             key_usage |= PUBKEY_USAGE_TIME;
2488         }
2489
2490       if (!key_usage)
2491         key_usage |= PUBKEY_USAGE_NONE;
2492
2493     }
2494   else if (p) /* Key flags of length zero.  */
2495     key_usage |= PUBKEY_USAGE_NONE;
2496
2497   /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
2498      capability that we do not handle.  This serves to distinguish
2499      between a zero key usage which we handle as the default
2500      capabilities for that algorithm, and a usage that we do not
2501      handle.  Likewise we use PUBKEY_USAGE_NONE to indicate that
2502      key_flags have been given but they do not specify any usage.  */
2503
2504   return key_usage;
2505 }
2506
2507
2508 /* Apply information from SIGNODE (which is the valid self-signature
2509  * associated with that UID) to the UIDNODE:
2510  * - wether the UID has been revoked
2511  * - assumed creation date of the UID
2512  * - temporary store the keyflags here
2513  * - temporary store the key expiration time here
2514  * - mark whether the primary user ID flag hat been set.
2515  * - store the preferences
2516  */
2517 static void
2518 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
2519 {
2520   PKT_user_id *uid = uidnode->pkt->pkt.user_id;
2521   PKT_signature *sig = signode->pkt->pkt.signature;
2522   const byte *p, *sym, *aead, *hash, *zip;
2523   size_t n, nsym, naead, nhash, nzip;
2524
2525   sig->flags.chosen_selfsig = 1;/* We chose this one. */
2526   uid->created = 0;             /* Not created == invalid. */
2527   if (IS_UID_REV (sig))
2528     {
2529       uid->flags.revoked = 1;
2530       return; /* Has been revoked.  */
2531     }
2532   else
2533     uid->flags.revoked = 0;
2534
2535   uid->expiredate = sig->expiredate;
2536
2537   if (sig->flags.expired)
2538     {
2539       uid->flags.expired = 1;
2540       return; /* Has expired.  */
2541     }
2542   else
2543     uid->flags.expired = 0;
2544
2545   uid->created = sig->timestamp; /* This one is okay. */
2546   uid->selfsigversion = sig->version;
2547   /* If we got this far, it's not expired :) */
2548   uid->flags.expired = 0;
2549
2550   /* Store the key flags in the helper variable for later processing.  */
2551   uid->help_key_usage = parse_key_usage (sig);
2552
2553   /* Ditto for the key expiration.  */
2554   p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
2555   if (p && buf32_to_u32 (p))
2556     uid->help_key_expire = keycreated + buf32_to_u32 (p);
2557   else
2558     uid->help_key_expire = 0;
2559
2560   /* Set the primary user ID flag - we will later wipe out some
2561    * of them to only have one in our keyblock.  */
2562   uid->flags.primary = 0;
2563   p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PRIMARY_UID, NULL);
2564   if (p && *p)
2565     uid->flags.primary = 2;
2566
2567   /* We could also query this from the unhashed area if it is not in
2568    * the hased area and then later try to decide which is the better
2569    * there should be no security problem with this.
2570    * For now we only look at the hashed one.  */
2571
2572   /* Now build the preferences list.  These must come from the
2573      hashed section so nobody can modify the ciphers a key is
2574      willing to accept.  */
2575   p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_SYM, &n);
2576   sym = p;
2577   nsym = p ? n : 0;
2578   p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_AEAD, &n);
2579   aead = p;
2580   naead = p ? n : 0;
2581   p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_HASH, &n);
2582   hash = p;
2583   nhash = p ? n : 0;
2584   p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_COMPR, &n);
2585   zip = p;
2586   nzip = p ? n : 0;
2587   if (uid->prefs)
2588     xfree (uid->prefs);
2589   n = nsym + naead + nhash + nzip;
2590   if (!n)
2591     uid->prefs = NULL;
2592   else
2593     {
2594       uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
2595       n = 0;
2596       for (; nsym; nsym--, n++)
2597         {
2598           uid->prefs[n].type = PREFTYPE_SYM;
2599           uid->prefs[n].value = *sym++;
2600         }
2601       for (; naead; naead--, n++)
2602         {
2603           uid->prefs[n].type = PREFTYPE_AEAD;
2604           uid->prefs[n].value = *aead++;
2605         }
2606       for (; nhash; nhash--, n++)
2607         {
2608           uid->prefs[n].type = PREFTYPE_HASH;
2609           uid->prefs[n].value = *hash++;
2610         }
2611       for (; nzip; nzip--, n++)
2612         {
2613           uid->prefs[n].type = PREFTYPE_ZIP;
2614           uid->prefs[n].value = *zip++;
2615         }
2616       uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker  */
2617       uid->prefs[n].value = 0;
2618     }
2619
2620   /* See whether we have the MDC feature.  */
2621   uid->flags.mdc = 0;
2622   p = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n);
2623   if (p && n && (p[0] & 0x01))
2624     uid->flags.mdc = 1;
2625
2626   /* See whether we have the AEAD feature.  */
2627   uid->flags.aead = 0;
2628   p = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n);
2629   if (p && n && (p[0] & 0x02))
2630     uid->flags.aead = 1;
2631
2632   /* And the keyserver modify flag.  */
2633   uid->flags.ks_modify = 1;
2634   p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KS_FLAGS, &n);
2635   if (p && n && (p[0] & 0x80))
2636     uid->flags.ks_modify = 0;
2637 }
2638
2639 static void
2640 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
2641 {
2642   rinfo->date = sig->timestamp;
2643   rinfo->algo = sig->pubkey_algo;
2644   rinfo->keyid[0] = sig->keyid[0];
2645   rinfo->keyid[1] = sig->keyid[1];
2646 }
2647
2648
2649 /* Given a keyblock, parse the key block and extract various pieces of
2650  * information and save them with the primary key packet and the user
2651  * id packets.  For instance, some information is stored in signature
2652  * packets.  We find the latest such valid packet (since the user can
2653  * change that information) and copy its contents into the
2654  * PKT_public_key.
2655  *
2656  * Note that R_REVOKED may be set to 0, 1 or 2.
2657  *
2658  * This function fills in the following fields in the primary key's
2659  * keyblock:
2660  *
2661  *   main_keyid          (computed)
2662  *   revkey / numrevkeys (derived from self signed key data)
2663  *   flags.valid         (whether we have at least 1 self-sig)
2664  *   flags.maybe_revoked (whether a designed revoked the key, but
2665  *                        we are missing the key to check the sig)
2666  *   selfsigversion      (highest version of any valid self-sig)
2667  *   pubkey_usage        (derived from most recent self-sig or most
2668  *                        recent user id)
2669  *   has_expired         (various sources)
2670  *   expiredate          (various sources)
2671  *
2672  * See the documentation for fixup_uidnode for how the user id packets
2673  * are modified.  In addition to that the primary user id's is_primary
2674  * field is set to 1 and the other user id's is_primary are set to 0.
2675  */
2676 static void
2677 merge_selfsigs_main (ctrl_t ctrl, kbnode_t keyblock, int *r_revoked,
2678                      struct revoke_info *rinfo)
2679 {
2680   PKT_public_key *pk = NULL;
2681   KBNODE k;
2682   u32 kid[2];
2683   u32 sigdate, uiddate, uiddate2;
2684   KBNODE signode, uidnode, uidnode2;
2685   u32 curtime = make_timestamp ();
2686   unsigned int key_usage = 0;
2687   u32 keytimestamp = 0;  /* Creation time of the key.  */
2688   u32 key_expire = 0;
2689   int key_expire_seen = 0;
2690   byte sigversion = 0;
2691
2692   *r_revoked = 0;
2693   memset (rinfo, 0, sizeof (*rinfo));
2694
2695   /* Section 11.1 of RFC 4880 determines the order of packets within a
2696    * message.  There are three sections, which must occur in the
2697    * following order: the public key, the user ids and user attributes
2698    * and the subkeys.  Within each section, each primary packet (e.g.,
2699    * a user id packet) is followed by one or more signature packets,
2700    * which modify that packet.  */
2701
2702   /* According to Section 11.1 of RFC 4880, the public key must be the
2703      first packet.  Note that parse_keyblock_image ensures that the
2704      first packet is the public key.  */
2705   if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2706     BUG ();
2707   pk = keyblock->pkt->pkt.public_key;
2708   keytimestamp = pk->timestamp;
2709
2710   keyid_from_pk (pk, kid);
2711   pk->main_keyid[0] = kid[0];
2712   pk->main_keyid[1] = kid[1];
2713
2714   if (pk->version < 4)
2715     {
2716       /* Before v4 the key packet itself contains the expiration date
2717        * and there was no way to change it, so we start with the one
2718        * from the key packet.  We do not support v3 keys anymore but
2719        * we keep the code in case a future key versions introduces a
2720        * hard expire time again. */
2721       key_expire = pk->max_expiredate;
2722       key_expire_seen = 1;
2723     }
2724
2725   /* First pass:
2726    *
2727    * - Find the latest direct key self-signature.  We assume that the
2728    *   newest one overrides all others.
2729    *
2730    * - Determine whether the key has been revoked.
2731    *
2732    * - Gather all revocation keys (unlike other data, we don't just
2733    *   take them from the latest self-signed packet).
2734    *
2735    * - Determine max (sig[...]->version).
2736    */
2737
2738   /* Reset this in case this key was already merged. */
2739   xfree (pk->revkey);
2740   pk->revkey = NULL;
2741   pk->numrevkeys = 0;
2742
2743   signode = NULL;
2744   sigdate = 0; /* Helper variable to find the latest signature.  */
2745
2746   /* According to Section 11.1 of RFC 4880, the public key comes first
2747    * and is immediately followed by any signature packets that modify
2748    * it.  */
2749   for (k = keyblock;
2750        k && k->pkt->pkttype != PKT_USER_ID
2751          && k->pkt->pkttype != PKT_ATTRIBUTE
2752          && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2753        k = k->next)
2754     {
2755       if (k->pkt->pkttype == PKT_SIGNATURE)
2756         {
2757           PKT_signature *sig = k->pkt->pkt.signature;
2758           if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2759             { /* Self sig.  */
2760
2761               if (check_key_signature (ctrl, keyblock, k, NULL))
2762                 ; /* Signature did not verify.  */
2763               else if (IS_KEY_REV (sig))
2764                 {
2765                   /* Key has been revoked - there is no way to
2766                    * override such a revocation, so we theoretically
2767                    * can stop now.  We should not cope with expiration
2768                    * times for revocations here because we have to
2769                    * assume that an attacker can generate all kinds of
2770                    * signatures.  However due to the fact that the key
2771                    * has been revoked it does not harm either and by
2772                    * continuing we gather some more info on that
2773                    * key.  */
2774                   *r_revoked = 1;
2775                   sig_to_revoke_info (sig, rinfo);
2776                 }
2777               else if (IS_KEY_SIG (sig))
2778                 {
2779                   /* Add the indicated revocations keys from all
2780                    * signatures not just the latest.  We do this
2781                    * because you need multiple 1F sigs to properly
2782                    * handle revocation keys (PGP does it this way, and
2783                    * a revocation key could be sensitive and hence in
2784                    * a different signature).  */
2785                   if (sig->revkey)
2786                     {
2787                       int i;
2788
2789                       pk->revkey =
2790                         xrealloc (pk->revkey, sizeof (struct revocation_key) *
2791                                   (pk->numrevkeys + sig->numrevkeys));
2792
2793                       for (i = 0; i < sig->numrevkeys; i++, pk->numrevkeys++)
2794                         {
2795                           pk->revkey[pk->numrevkeys].class
2796                             = sig->revkey[i].class;
2797                           pk->revkey[pk->numrevkeys].algid
2798                             = sig->revkey[i].algid;
2799                           pk->revkey[pk->numrevkeys].fprlen
2800                             = sig->revkey[i].fprlen;
2801                           memcpy (pk->revkey[pk->numrevkeys].fpr,
2802                                   sig->revkey[i].fpr, sig->revkey[i].fprlen);
2803                           memset (pk->revkey[pk->numrevkeys].fpr
2804                                   + sig->revkey[i].fprlen,
2805                                   0,
2806                                   sizeof (sig->revkey[i].fpr)
2807                                   - sig->revkey[i].fprlen);
2808                         }
2809                     }
2810
2811                   if (sig->timestamp >= sigdate)
2812                     { /* This is the latest signature so far.  */
2813
2814                       if (sig->flags.expired)
2815                         ; /* Signature has expired - ignore it.  */
2816                       else
2817                         {
2818                           sigdate = sig->timestamp;
2819                           signode = k;
2820                           if (sig->version > sigversion)
2821                             sigversion = sig->version;
2822
2823                         }
2824                     }
2825                 }
2826             }
2827         }
2828     }
2829
2830   /* Remove dupes from the revocation keys.  */
2831   if (pk->revkey)
2832     {
2833       int i, j, x, changed = 0;
2834
2835       for (i = 0; i < pk->numrevkeys; i++)
2836         {
2837           for (j = i + 1; j < pk->numrevkeys; j++)
2838             {
2839               if (memcmp (&pk->revkey[i], &pk->revkey[j],
2840                           sizeof (struct revocation_key)) == 0)
2841                 {
2842                   /* remove j */
2843
2844                   for (x = j; x < pk->numrevkeys - 1; x++)
2845                     pk->revkey[x] = pk->revkey[x + 1];
2846
2847                   pk->numrevkeys--;
2848                   j--;
2849                   changed = 1;
2850                 }
2851             }
2852         }
2853
2854       if (changed)
2855         pk->revkey = xrealloc (pk->revkey,
2856                                pk->numrevkeys *
2857                                sizeof (struct revocation_key));
2858     }
2859
2860   /* SIGNODE is the direct key signature packet (sigclass 0x1f) with
2861    * the latest creation time.  Extract some information from it.  */
2862   if (signode)
2863     {
2864       /* Some information from a direct key signature take precedence
2865        * over the same information given in UID sigs.  */
2866       PKT_signature *sig = signode->pkt->pkt.signature;
2867       const byte *p;
2868
2869       key_usage = parse_key_usage (sig);
2870
2871       p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
2872       if (p && buf32_to_u32 (p))
2873         {
2874           key_expire = keytimestamp + buf32_to_u32 (p);
2875           key_expire_seen = 1;
2876         }
2877
2878       /* Mark that key as valid: One direct key signature should
2879        * render a key as valid.  */
2880       pk->flags.valid = 1;
2881     }
2882
2883   /* Pass 1.5: Look for key revocation signatures that were not made
2884    * by the key (i.e. did a revocation key issue a revocation for
2885    * us?).  Only bother to do this if there is a revocation key in the
2886    * first place and we're not revoked already.  */
2887
2888   if (!*r_revoked && pk->revkey)
2889     for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
2890       {
2891         if (k->pkt->pkttype == PKT_SIGNATURE)
2892           {
2893             PKT_signature *sig = k->pkt->pkt.signature;
2894
2895             if (IS_KEY_REV (sig) &&
2896                 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
2897               {
2898                 int rc = check_revocation_keys (ctrl, pk, sig);
2899                 if (rc == 0)
2900                   {
2901                     *r_revoked = 2;
2902                     sig_to_revoke_info (sig, rinfo);
2903                     /* Don't continue checking since we can't be any
2904                      * more revoked than this.  */
2905                     break;
2906                   }
2907                 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2908                   pk->flags.maybe_revoked = 1;
2909
2910                 /* A failure here means the sig did not verify, was
2911                  * not issued by a revocation key, or a revocation
2912                  * key loop was broken.  If a revocation key isn't
2913                  * findable, however, the key might be revoked and
2914                  * we don't know it.  */
2915
2916                 /* Fixme: In the future handle subkey and cert
2917                  * revocations?  PGP doesn't, but it's in 2440.  */
2918               }
2919           }
2920       }
2921
2922   /* Second pass: Look at the self-signature of all user IDs.  */
2923
2924   /* According to RFC 4880 section 11.1, user id and attribute packets
2925    * are in the second section, after the public key packet and before
2926    * the subkey packets.  */
2927   signode = uidnode = NULL;
2928   sigdate = 0; /* Helper variable to find the latest signature in one UID. */
2929   for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2930     {
2931       if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
2932         { /* New user id packet.  */
2933
2934           /* Apply the data from the most recent self-signed packet to
2935            * the preceding user id packet.  */
2936           if (uidnode && signode)
2937             {
2938               fixup_uidnode (uidnode, signode, keytimestamp);
2939               pk->flags.valid = 1;
2940             }
2941
2942           /* Clear SIGNODE.  The only relevant self-signed data for
2943            * UIDNODE follows it.  */
2944           if (k->pkt->pkttype == PKT_USER_ID)
2945             uidnode = k;
2946           else
2947             uidnode = NULL;
2948
2949           signode = NULL;
2950           sigdate = 0;
2951         }
2952       else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2953         {
2954           PKT_signature *sig = k->pkt->pkt.signature;
2955           if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2956             {
2957               if (check_key_signature (ctrl, keyblock, k, NULL))
2958                 ;               /* signature did not verify */
2959               else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
2960                        && sig->timestamp >= sigdate)
2961                 {
2962                   /* Note: we allow invalidation of cert revocations
2963                    * by a newer signature.  An attacker can't use this
2964                    * because a key should be revoked with a key revocation.
2965                    * The reason why we have to allow for that is that at
2966                    * one time an email address may become invalid but later
2967                    * the same email address may become valid again (hired,
2968                    * fired, hired again).  */
2969
2970                   sigdate = sig->timestamp;
2971                   signode = k;
2972                   signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2973                   if (sig->version > sigversion)
2974                     sigversion = sig->version;
2975                 }
2976             }
2977         }
2978     }
2979   if (uidnode && signode)
2980     {
2981       fixup_uidnode (uidnode, signode, keytimestamp);
2982       pk->flags.valid = 1;
2983     }
2984
2985   /* If the key isn't valid yet, and we have
2986    * --allow-non-selfsigned-uid set, then force it valid. */
2987   if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
2988     {
2989       if (opt.verbose)
2990         log_info (_("Invalid key %s made valid by"
2991                     " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
2992       pk->flags.valid = 1;
2993     }
2994
2995   /* The key STILL isn't valid, so try and find an ultimately
2996    * trusted signature. */
2997   if (!pk->flags.valid)
2998     {
2999       uidnode = NULL;
3000
3001       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3002            k = k->next)
3003         {
3004           if (k->pkt->pkttype == PKT_USER_ID)
3005             uidnode = k;
3006           else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
3007             {
3008               PKT_signature *sig = k->pkt->pkt.signature;
3009
3010               if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
3011                 {
3012                   PKT_public_key *ultimate_pk;
3013
3014                   ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
3015
3016                   /* We don't want to use the full get_pubkey to avoid
3017                    * infinite recursion in certain cases.  There is no
3018                    * reason to check that an ultimately trusted key is
3019                    * still valid - if it has been revoked the user
3020                    * should also remove the ultimate trust flag.  */
3021                   if (get_pubkey_fast (ctrl, ultimate_pk, sig->keyid) == 0
3022                       && check_key_signature2 (ctrl,
3023                                                keyblock, k, ultimate_pk,
3024                                                NULL, NULL, NULL, NULL) == 0
3025                       && get_ownertrust (ctrl, ultimate_pk) == TRUST_ULTIMATE)
3026                     {
3027                       free_public_key (ultimate_pk);
3028                       pk->flags.valid = 1;
3029                       break;
3030                     }
3031
3032                   free_public_key (ultimate_pk);
3033                 }
3034             }
3035         }
3036     }
3037
3038   /* Record the highest selfsig version so we know if this is a v3 key
3039    * through and through, or a v3 key with a v4 selfsig somewhere.
3040    * This is useful in a few places to know if the key must be treated
3041    * as PGP2-style or OpenPGP-style.  Note that a selfsig revocation
3042    * with a higher version number will also raise this value.  This is
3043    * okay since such a revocation must be issued by the user (i.e. it
3044    * cannot be issued by someone else to modify the key behavior.) */
3045
3046   pk->selfsigversion = sigversion;
3047
3048   /* Now that we had a look at all user IDs we can now get some
3049    * information from those user IDs.  */
3050
3051   if (!key_usage)
3052     {
3053       /* Find the latest user ID with key flags set. */
3054       uiddate = 0; /* Helper to find the latest user ID.  */
3055       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3056            k = k->next)
3057         {
3058           if (k->pkt->pkttype == PKT_USER_ID)
3059             {
3060               PKT_user_id *uid = k->pkt->pkt.user_id;
3061
3062               if (uid->help_key_usage
3063                   && (uid->created > uiddate || (!uid->created && !uiddate)))
3064                 {
3065                   key_usage = uid->help_key_usage;
3066                   uiddate = uid->created;
3067                 }
3068             }
3069         }
3070     }
3071
3072   if (!key_usage)
3073     {
3074       /* No key flags at all: get it from the algo.  */
3075       key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
3076     }
3077   else
3078     {
3079       /* Check that the usage matches the usage as given by the algo.  */
3080       int x = openpgp_pk_algo_usage (pk->pubkey_algo);
3081       if (x) /* Mask it down to the actual allowed usage.  */
3082         key_usage &= x;
3083     }
3084
3085   /* Whatever happens, it's a primary key, so it can certify. */
3086   pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
3087
3088   if (!key_expire_seen)
3089     {
3090       /* Find the latest valid user ID with a key expiration set.
3091        * This may be a different one than from usage computation above
3092        * because some user IDs may have no expiration date set.  */
3093       uiddate = 0;
3094       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3095            k = k->next)
3096         {
3097           if (k->pkt->pkttype == PKT_USER_ID)
3098             {
3099               PKT_user_id *uid = k->pkt->pkt.user_id;
3100               if (uid->help_key_expire
3101                   && (uid->created > uiddate || (!uid->created && !uiddate)))
3102                 {
3103                   key_expire = uid->help_key_expire;
3104                   uiddate = uid->created;
3105                 }
3106             }
3107         }
3108     }
3109
3110   /* Currently only the not anymore supported v3 keys have a maximum
3111    * expiration date, but future key versions may get this feature again. */
3112   if (key_expire == 0
3113       || (pk->max_expiredate && key_expire > pk->max_expiredate))
3114     key_expire = pk->max_expiredate;
3115
3116   pk->has_expired = key_expire >= curtime ? 0 : key_expire;
3117   pk->expiredate = key_expire;
3118
3119   /* Fixme: we should see how to get rid of the expiretime fields but
3120    * this needs changes at other places too.  */
3121
3122   /* And now find the real primary user ID and delete all others.  */
3123   uiddate = uiddate2 = 0;
3124   uidnode = uidnode2 = NULL;
3125   for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3126     {
3127       if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
3128         {
3129           PKT_user_id *uid = k->pkt->pkt.user_id;
3130           if (uid->flags.primary)
3131             {
3132               if (uid->created > uiddate)
3133                 {
3134                   uiddate = uid->created;
3135                   uidnode = k;
3136                 }
3137               else if (uid->created == uiddate && uidnode)
3138                 {
3139                   /* The dates are equal, so we need to do a different
3140                    * (and arbitrary) comparison.  This should rarely,
3141                    * if ever, happen.  It's good to try and guarantee
3142                    * that two different GnuPG users with two different
3143                    * keyrings at least pick the same primary.  */
3144                   if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
3145                     uidnode = k;
3146                 }
3147             }
3148           else
3149             {
3150               if (uid->created > uiddate2)
3151                 {
3152                   uiddate2 = uid->created;
3153                   uidnode2 = k;
3154                 }
3155               else if (uid->created == uiddate2 && uidnode2)
3156                 {
3157                   if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
3158                     uidnode2 = k;
3159                 }
3160             }
3161         }
3162     }
3163   if (uidnode)
3164     {
3165       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3166            k = k->next)
3167         {
3168           if (k->pkt->pkttype == PKT_USER_ID &&
3169               !k->pkt->pkt.user_id->attrib_data)
3170             {
3171               PKT_user_id *uid = k->pkt->pkt.user_id;
3172               if (k != uidnode)
3173                 uid->flags.primary = 0;
3174             }
3175         }
3176     }
3177   else if (uidnode2)
3178     {
3179       /* None is flagged primary - use the latest user ID we have,
3180        * and disambiguate with the arbitrary packet comparison. */
3181       uidnode2->pkt->pkt.user_id->flags.primary = 1;
3182     }
3183   else
3184     {
3185       /* None of our uids were self-signed, so pick the one that
3186        * sorts first to be the primary.  This is the best we can do
3187        * here since there are no self sigs to date the uids. */
3188
3189       uidnode = NULL;
3190
3191       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3192            k = k->next)
3193         {
3194           if (k->pkt->pkttype == PKT_USER_ID
3195               && !k->pkt->pkt.user_id->attrib_data)
3196             {
3197               if (!uidnode)
3198                 {
3199                   uidnode = k;
3200                   uidnode->pkt->pkt.user_id->flags.primary = 1;
3201                   continue;
3202                 }
3203               else
3204                 {
3205                   if (cmp_user_ids (k->pkt->pkt.user_id,
3206                                     uidnode->pkt->pkt.user_id) > 0)
3207                     {
3208                       uidnode->pkt->pkt.user_id->flags.primary = 0;
3209                       uidnode = k;
3210                       uidnode->pkt->pkt.user_id->flags.primary = 1;
3211                     }
3212                   else
3213                     {
3214                       /* just to be safe: */
3215                       k->pkt->pkt.user_id->flags.primary = 0;
3216                     }
3217                 }
3218             }
3219         }
3220     }
3221 }
3222
3223
3224 /* Convert a buffer to a signature.  Useful for 0x19 embedded sigs.
3225  * Caller must free the signature when they are done. */
3226 static PKT_signature *
3227 buf_to_sig (const byte * buf, size_t len)
3228 {
3229   PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
3230   IOBUF iobuf = iobuf_temp_with_content (buf, len);
3231   int save_mode = set_packet_list_mode (0);
3232
3233   if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
3234     {
3235       free_seckey_enc (sig);
3236       sig = NULL;
3237     }
3238
3239   set_packet_list_mode (save_mode);
3240   iobuf_close (iobuf);
3241
3242   return sig;
3243 }
3244
3245
3246 /* Use the self-signed data to fill in various fields in subkeys.
3247  *
3248  * KEYBLOCK is the whole keyblock.  SUBNODE is the subkey to fill in.
3249  *
3250  * Sets the following fields on the subkey:
3251  *
3252  *   main_keyid
3253  *   flags.valid        if the subkey has a valid self-sig binding
3254  *   flags.revoked
3255  *   flags.backsig
3256  *   pubkey_usage
3257  *   has_expired
3258  *   expired_date
3259  *
3260  * On this subkey's most recent valid self-signed packet, the
3261  * following field is set:
3262  *
3263  *   flags.chosen_selfsig
3264  */
3265 static void
3266 merge_selfsigs_subkey (ctrl_t ctrl, kbnode_t keyblock, kbnode_t subnode)
3267 {
3268   PKT_public_key *mainpk = NULL, *subpk = NULL;
3269   PKT_signature *sig;
3270   KBNODE k;
3271   u32 mainkid[2];
3272   u32 sigdate = 0;
3273   KBNODE signode;
3274   u32 curtime = make_timestamp ();
3275   unsigned int key_usage = 0;
3276   u32 keytimestamp = 0;
3277   u32 key_expire = 0;
3278   const byte *p;
3279
3280   if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3281     BUG ();
3282   mainpk = keyblock->pkt->pkt.public_key;
3283   if (mainpk->version < 4)
3284     return;/* (actually this should never happen) */
3285   keyid_from_pk (mainpk, mainkid);
3286   subpk = subnode->pkt->pkt.public_key;
3287   keytimestamp = subpk->timestamp;
3288
3289   subpk->flags.valid = 0;
3290   subpk->flags.exact = 0;
3291   subpk->main_keyid[0] = mainpk->main_keyid[0];
3292   subpk->main_keyid[1] = mainpk->main_keyid[1];
3293
3294   /* Find the latest key binding self-signature.  */
3295   signode = NULL;
3296   sigdate = 0; /* Helper to find the latest signature.  */
3297   for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3298        k = k->next)
3299     {
3300       if (k->pkt->pkttype == PKT_SIGNATURE)
3301         {
3302           sig = k->pkt->pkt.signature;
3303           if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
3304             {
3305               if (check_key_signature (ctrl, keyblock, k, NULL))
3306                 ; /* Signature did not verify.  */
3307               else if (IS_SUBKEY_REV (sig))
3308                 {
3309                   /* Note that this means that the date on a
3310                    * revocation sig does not matter - even if the
3311                    * binding sig is dated after the revocation sig,
3312                    * the subkey is still marked as revoked.  This
3313                    * seems ok, as it is just as easy to make new
3314                    * subkeys rather than re-sign old ones as the
3315                    * problem is in the distribution.  Plus, PGP (7)
3316                    * does this the same way.  */
3317                   subpk->flags.revoked = 1;
3318                   sig_to_revoke_info (sig, &subpk->revoked);
3319                   /* Although we could stop now, we continue to
3320                    * figure out other information like the old expiration
3321                    * time.  */
3322                 }
3323               else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
3324                 {
3325                   if (sig->flags.expired)
3326                     ; /* Signature has expired - ignore it.  */
3327                   else
3328                     {
3329                       sigdate = sig->timestamp;
3330                       signode = k;
3331                       signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
3332                     }
3333                 }
3334             }
3335         }
3336     }
3337
3338   /* No valid key binding.  */
3339   if (!signode)
3340     return;
3341
3342   sig = signode->pkt->pkt.signature;
3343   sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later.  */
3344
3345   key_usage = parse_key_usage (sig);
3346   if (!key_usage)
3347     {
3348       /* No key flags at all: get it from the algo.  */
3349       key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
3350     }
3351   else
3352     {
3353       /* Check that the usage matches the usage as given by the algo.  */
3354       int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
3355       if (x) /* Mask it down to the actual allowed usage.  */
3356         key_usage &= x;
3357     }
3358
3359   subpk->pubkey_usage = key_usage;
3360
3361   p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
3362   if (p && buf32_to_u32 (p))
3363     key_expire = keytimestamp + buf32_to_u32 (p);
3364   else
3365     key_expire = 0;
3366
3367   subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
3368   subpk->expiredate = key_expire;
3369
3370   /* Algo doesn't exist.  */
3371   if (openpgp_pk_test_algo (subpk->pubkey_algo))
3372     return;
3373
3374   subpk->flags.valid = 1;
3375
3376   /* Find the most recent 0x19 embedded signature on our self-sig. */
3377   if (!subpk->flags.backsig)
3378     {
3379       int seq = 0;
3380       size_t n;
3381       PKT_signature *backsig = NULL;
3382
3383       sigdate = 0;
3384
3385       /* We do this while() since there may be other embedded
3386        * signatures in the future.  We only want 0x19 here. */
3387
3388       while ((p = enum_sig_subpkt (sig, 1, SIGSUBPKT_SIGNATURE,
3389                                    &n, &seq, NULL)))
3390         if (n > 3
3391             && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)
3392                 || (p[0] == 5 && p[1] == 0x19)))
3393           {
3394             PKT_signature *tempsig = buf_to_sig (p, n);
3395             if (tempsig)
3396               {
3397                 if (tempsig->timestamp > sigdate)
3398                   {
3399                     if (backsig)
3400                       free_seckey_enc (backsig);
3401
3402                     backsig = tempsig;
3403                     sigdate = backsig->timestamp;
3404                   }
3405                 else
3406                   free_seckey_enc (tempsig);
3407               }
3408           }
3409
3410       seq = 0;
3411
3412       /* It is safe to have this in the unhashed area since the 0x19
3413        * is located on the selfsig for convenience, not security. */
3414       while ((p = enum_sig_subpkt (sig, 0, SIGSUBPKT_SIGNATURE,
3415                                    &n, &seq, NULL)))
3416         if (n > 3
3417             && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)
3418                  || (p[0] == 5 && p[1] == 0x19)))
3419           {
3420             PKT_signature *tempsig = buf_to_sig (p, n);
3421             if (tempsig)
3422               {
3423                 if (tempsig->timestamp > sigdate)
3424                   {
3425                     if (backsig)
3426                       free_seckey_enc (backsig);
3427
3428                     backsig = tempsig;
3429                     sigdate = backsig->timestamp;
3430                   }
3431                 else
3432                   free_seckey_enc (tempsig);
3433               }
3434           }
3435
3436       if (backsig)
3437         {
3438           /* At this point, backsig contains the most recent 0x19 sig.
3439            * Let's see if it is good. */
3440
3441           /* 2==valid, 1==invalid, 0==didn't check */
3442           if (check_backsig (mainpk, subpk, backsig) == 0)
3443             subpk->flags.backsig = 2;
3444           else
3445             subpk->flags.backsig = 1;
3446
3447           free_seckey_enc (backsig);
3448         }
3449     }
3450 }
3451
3452
3453 /* Merge information from the self-signatures with the public key,
3454  * subkeys and user ids to make using them more easy.
3455  *
3456  * See documentation for merge_selfsigs_main, merge_selfsigs_subkey
3457  * and fixup_uidnode for exactly which fields are updated.  */
3458 static void
3459 merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock)
3460 {
3461   KBNODE k;
3462   int revoked;
3463   struct revoke_info rinfo;
3464   PKT_public_key *main_pk;
3465   prefitem_t *prefs;
3466   unsigned int mdc_feature;
3467   unsigned int aead_feature;
3468
3469   if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
3470     {
3471       if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
3472         {
3473           log_error ("expected public key but found secret key "
3474                      "- must stop\n");
3475           /* We better exit here because a public key is expected at
3476            * other places too.  FIXME: Figure this out earlier and
3477            * don't get to here at all */
3478           g10_exit (1);
3479         }
3480       BUG ();
3481     }
3482
3483   merge_selfsigs_main (ctrl, keyblock, &revoked, &rinfo);
3484
3485   /* Now merge in the data from each of the subkeys.  */
3486   for (k = keyblock; k; k = k->next)
3487     {
3488       if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3489         {
3490           merge_selfsigs_subkey (ctrl, keyblock, k);
3491         }
3492     }
3493
3494   main_pk = keyblock->pkt->pkt.public_key;
3495   if (revoked || main_pk->has_expired || !main_pk->flags.valid)
3496     {
3497       /* If the primary key is revoked, expired, or invalid we
3498        * better set the appropriate flags on that key and all
3499        * subkeys.  */
3500       for (k = keyblock; k; k = k->next)
3501         {
3502           if (k->pkt->pkttype == PKT_PUBLIC_KEY
3503               || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3504             {
3505               PKT_public_key *pk = k->pkt->pkt.public_key;
3506               if (!main_pk->flags.valid)
3507                 pk->flags.valid = 0;
3508               if (revoked && !pk->flags.revoked)
3509                 {
3510                   pk->flags.revoked = revoked;
3511                   memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
3512                 }
3513               if (main_pk->has_expired)
3514                 {
3515                   pk->has_expired = main_pk->has_expired;
3516                   if (!pk->expiredate || pk->expiredate > main_pk->expiredate)
3517                     pk->expiredate = main_pk->expiredate;
3518                 }
3519             }
3520         }
3521       return;
3522     }
3523
3524   /* Set the preference list of all keys to those of the primary real
3525    * user ID.  Note: we use these preferences when we don't know by
3526    * which user ID the key has been selected.
3527    * fixme: we should keep atoms of commonly used preferences or
3528    * use reference counting to optimize the preference lists storage.
3529    * FIXME: it might be better to use the intersection of
3530    * all preferences.
3531    * Do a similar thing for the MDC feature flag.  */
3532   prefs = NULL;
3533   mdc_feature = aead_feature = 0;
3534   for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3535     {
3536       if (k->pkt->pkttype == PKT_USER_ID
3537           && !k->pkt->pkt.user_id->attrib_data
3538           && k->pkt->pkt.user_id->flags.primary)
3539         {
3540           prefs = k->pkt->pkt.user_id->prefs;
3541           mdc_feature = k->pkt->pkt.user_id->flags.mdc;
3542           aead_feature = k->pkt->pkt.user_id->flags.aead;
3543           break;
3544         }
3545     }
3546   for (k = keyblock; k; k = k->next)
3547     {
3548       if (k->pkt->pkttype == PKT_PUBLIC_KEY
3549           || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3550         {
3551           PKT_public_key *pk = k->pkt->pkt.public_key;
3552           if (pk->prefs)
3553             xfree (pk->prefs);
3554           pk->prefs = copy_prefs (prefs);
3555           pk->flags.mdc = mdc_feature;
3556           pk->flags.aead = aead_feature;
3557         }
3558     }
3559 }
3560
3561
3562 \f
3563 /* See whether the key satisfies any additional requirements specified
3564  * in CTX.  If so, return the node of an appropriate key or subkey.
3565  * Otherwise, return NULL if there was no appropriate key.
3566  *
3567  * Note that we do not return a reference, i.e. the result must not be
3568  * freed using 'release_kbnode'.
3569  *
3570  * In case the primary key is not required, select a suitable subkey.
3571  * We need the primary key if PUBKEY_USAGE_CERT is set in REQ_USAGE or
3572  * we are in PGP7 mode and PUBKEY_USAGE_SIG is set in
3573  * REQ_USAGE.
3574  *
3575  * If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
3576  * are set in REQ_USAGE, we filter by the key's function.  Concretely,
3577  * if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then we only
3578  * return a key if it is (at least) either a signing or a
3579  * certification key.
3580  *
3581  * If REQ_USAGE is set, then we reject any keys that are not good
3582  * (i.e., valid, not revoked, not expired, etc.).  This allows the
3583  * getkey functions to be used for plain key listings.
3584  *
3585  * Sets the matched key's user id field (pk->user_id) to the user id
3586  * that matched the low-level search criteria or NULL.
3587  *
3588  * If R_FLAGS is not NULL set certain flags for more detailed error
3589  * reporting.  Used flags are:
3590  *
3591  * - LOOKUP_ALL_SUBKEYS_EXPIRED :: All Subkeys are expired or have
3592  *                                 been revoked.
3593  * - LOOKUP_NOT_SELECTED :: No suitable key found
3594  *
3595  * This function needs to handle several different cases:
3596  *
3597  *  1. No requested usage and no primary key requested
3598  *     Examples for this case are that we have a keyID to be used
3599  *     for decryption or verification.
3600  *  2. No usage but primary key requested
3601  *     This is the case for all functions which work on an
3602  *     entire keyblock, e.g. for editing or listing
3603  *  3. Usage and primary key requested
3604  *     FIXME
3605  *  4. Usage but no primary key requested
3606  *     FIXME
3607  *
3608  */
3609 static kbnode_t
3610 finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact,
3611                int want_secret, unsigned int *r_flags)
3612 {
3613   kbnode_t k;
3614
3615   /* If WANT_EXACT is set, the key or subkey that actually matched the
3616      low-level search criteria.  */
3617   kbnode_t foundk = NULL;
3618   /* The user id (if any) that matched the low-level search criteria.  */
3619   PKT_user_id *foundu = NULL;
3620
3621   u32 latest_date;
3622   kbnode_t latest_key;
3623   PKT_public_key *pk;
3624   int req_prim;
3625   u32 curtime = make_timestamp ();
3626
3627   if (r_flags)
3628     *r_flags = 0;
3629
3630 #define USAGE_MASK  (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
3631   req_usage &= USAGE_MASK;
3632
3633   /* Request the primary if we're certifying another key, and also if
3634    * signing data while --pgp7 is on since pgp 7 do
3635    * not understand signatures made by a signing subkey.  PGP 8 does. */
3636   req_prim = ((req_usage & PUBKEY_USAGE_CERT)
3637               || (PGP7 && (req_usage & PUBKEY_USAGE_SIG)));
3638
3639
3640   log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
3641
3642   /* For an exact match mark the primary or subkey that matched the
3643    * low-level search criteria.  Use this loop also to sort our keys
3644    * found using an ADSK fingerprint.  */
3645   for (k = keyblock; k; k = k->next)
3646     {
3647       if ((k->flag & 1) && (k->pkt->pkttype == PKT_PUBLIC_KEY
3648                             || k->pkt->pkttype == PKT_PUBLIC_SUBKEY))
3649         {
3650           if (want_exact)
3651             {
3652               if (DBG_LOOKUP)
3653                 log_debug ("finish_lookup: exact search requested and found\n");
3654               foundk = k;
3655               pk = k->pkt->pkt.public_key;
3656               pk->flags.exact = 1;
3657               break;
3658             }
3659           else if ((k->pkt->pkt.public_key->pubkey_usage == PUBKEY_USAGE_RENC))
3660             {
3661               if (DBG_LOOKUP)
3662                 log_debug ("finish_lookup: found via ADSK - not selected\n");
3663               if (r_flags)
3664                 *r_flags |= LOOKUP_NOT_SELECTED;
3665               return NULL; /* Not found.  */
3666             }
3667         }
3668     }
3669
3670   /* Get the user id that matched that low-level search criteria.  */
3671   for (k = keyblock; k; k = k->next)
3672     {
3673       if ((k->flag & 2))
3674         {
3675           log_assert (k->pkt->pkttype == PKT_USER_ID);
3676           foundu = k->pkt->pkt.user_id;
3677           break;
3678         }
3679     }
3680
3681   if (DBG_LOOKUP)
3682     log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
3683                (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
3684                foundk ? "one" : "all", req_usage);
3685
3686   if (!req_usage)
3687     {
3688       latest_key = foundk ? foundk : keyblock;
3689       goto found;
3690     }
3691
3692   latest_date = 0;
3693   latest_key = NULL;
3694   /* Set LATEST_KEY to the latest (the one with the most recent
3695    * timestamp) good (valid, not revoked, not expired, etc.) subkey.
3696    *
3697    * Don't bother if we are only looking for a primary key or we need
3698    * an exact match and the exact match is not a subkey.  */
3699   if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
3700     ;
3701   else
3702     {
3703       kbnode_t nextk;
3704       int n_subkeys = 0;
3705       int n_revoked_or_expired = 0;
3706       int last_secret_key_avail = 0;
3707
3708       /* Either start a loop or check just this one subkey.  */
3709       for (k = foundk ? foundk : keyblock; k; k = nextk)
3710         {
3711           if (foundk)
3712             {
3713               /* If FOUNDK is not NULL, then only consider that exact
3714                  key, i.e., don't iterate.  */
3715               nextk = NULL;
3716             }
3717           else
3718             nextk = k->next;
3719
3720           if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3721             continue;
3722
3723           pk = k->pkt->pkt.public_key;
3724           if (DBG_LOOKUP)
3725             log_debug ("\tchecking subkey %08lX\n",
3726                        (ulong) keyid_from_pk (pk, NULL));
3727
3728           if (!pk->flags.valid)
3729             {
3730               if (DBG_LOOKUP)
3731                 log_debug ("\tsubkey not valid\n");
3732               continue;
3733             }
3734           if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3735             {
3736               if (DBG_LOOKUP)
3737                 log_debug ("\tusage does not match: want=%x have=%x\n",
3738                            req_usage, pk->pubkey_usage);
3739               continue;
3740             }
3741
3742           n_subkeys++;
3743           if (pk->flags.revoked)
3744             {
3745               if (DBG_LOOKUP)
3746                 log_debug ("\tsubkey has been revoked\n");
3747               n_revoked_or_expired++;
3748               continue;
3749             }
3750           if (pk->has_expired && !opt.ignore_expiration)
3751             {
3752               if (DBG_LOOKUP)
3753                 log_debug ("\tsubkey has expired\n");
3754               n_revoked_or_expired++;
3755               continue;
3756             }
3757           if (pk->timestamp > curtime && !opt.ignore_valid_from)
3758             {
3759               if (DBG_LOOKUP)
3760                 log_debug ("\tsubkey not yet valid\n");
3761               continue;
3762             }
3763
3764           if (want_secret)
3765             {
3766               int secret_key_avail = agent_probe_secret_key (NULL, pk);
3767
3768               if (!secret_key_avail)
3769                 {
3770                   if (DBG_LOOKUP)
3771                     log_debug ("\tno secret key\n");
3772                   continue;
3773                 }
3774
3775               if (secret_key_avail > last_secret_key_avail)
3776                 {
3777                   /* Use this key.  */
3778                   last_secret_key_avail = secret_key_avail;
3779                   latest_date = 0;
3780                 }
3781             }
3782
3783           if (DBG_LOOKUP)
3784             log_debug ("\tsubkey might be fine\n");
3785           /* In case a key has a timestamp of 0 set, we make sure
3786              that it is used.  A better change would be to compare
3787              ">=" but that might also change the selected keys and
3788              is as such a more intrusive change.  */
3789           if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
3790             {
3791               latest_date = pk->timestamp;
3792               latest_key = k;
3793             }
3794         }
3795       if (n_subkeys == n_revoked_or_expired && r_flags)
3796         *r_flags |= LOOKUP_ALL_SUBKEYS_EXPIRED;
3797     }
3798
3799   /* Check if the primary key is ok (valid, not revoke, not expire,
3800    * matches requested usage) if:
3801    *
3802    *   - we didn't find an appropriate subkey and we're not doing an
3803    *     exact search,
3804    *
3805    *   - we're doing an exact match and the exact match was the
3806    *     primary key, or,
3807    *
3808    *   - we're just considering the primary key.  */
3809   if ((!latest_key && !want_exact) || foundk == keyblock || req_prim)
3810     {
3811       if (DBG_LOOKUP && !foundk && !req_prim)
3812         log_debug ("\tno suitable subkeys found - trying primary\n");
3813       pk = keyblock->pkt->pkt.public_key;
3814       if (!pk->flags.valid)
3815         {
3816           if (DBG_LOOKUP)
3817             log_debug ("\tprimary key not valid\n");
3818         }
3819       else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3820         {
3821           if (DBG_LOOKUP)
3822             log_debug ("\tprimary key usage does not match: "
3823                        "want=%x have=%x\n", req_usage, pk->pubkey_usage);
3824         }
3825       else if (pk->flags.revoked)
3826         {
3827           if (DBG_LOOKUP)
3828             log_debug ("\tprimary key has been revoked\n");
3829         }
3830       else if (pk->has_expired)
3831         {
3832           if (DBG_LOOKUP)
3833             log_debug ("\tprimary key has expired\n");
3834         }
3835       else /* Okay.  */
3836         {
3837           if (DBG_LOOKUP)
3838             log_debug ("\tprimary key may be used\n");
3839           latest_key = keyblock;
3840         }
3841     }
3842
3843   if (!latest_key)
3844     {
3845       if (DBG_LOOKUP)
3846         log_debug ("\tno suitable key found -  giving up\n");
3847       if (r_flags)
3848         *r_flags |= LOOKUP_NOT_SELECTED;
3849       return NULL; /* Not found.  */
3850     }
3851
3852  found:
3853   if (DBG_LOOKUP)
3854     log_debug ("\tusing key %08lX\n",
3855                (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
3856
3857   if (latest_key)
3858     {
3859       pk = latest_key->pkt->pkt.public_key;
3860       free_user_id (pk->user_id);
3861       pk->user_id = scopy_user_id (foundu);
3862     }
3863
3864   if (latest_key != keyblock && opt.verbose)
3865     {
3866       char *tempkeystr =
3867         xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
3868       log_info (_("using subkey %s instead of primary key %s\n"),
3869                 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
3870       xfree (tempkeystr);
3871     }
3872
3873   cache_put_keyblock (keyblock);
3874
3875   return latest_key ? latest_key : keyblock; /* Found.  */
3876 }
3877
3878
3879 /* Print a KEY_CONSIDERED status line.  */
3880 static void
3881 print_status_key_considered (kbnode_t keyblock, unsigned int flags)
3882 {
3883   char hexfpr[2*MAX_FINGERPRINT_LEN + 1];
3884   kbnode_t node;
3885   char flagbuf[20];
3886
3887   if (!is_status_enabled ())
3888     return;
3889
3890   for (node=keyblock; node; node = node->next)
3891     if (node->pkt->pkttype == PKT_PUBLIC_KEY
3892         || node->pkt->pkttype == PKT_SECRET_KEY)
3893       break;
3894   if (!node)
3895     {
3896       log_error ("%s: keyblock w/o primary key\n", __func__);
3897       return;
3898     }
3899
3900   hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr);
3901   snprintf (flagbuf, sizeof flagbuf, " %u", flags);
3902   write_status_strings (STATUS_KEY_CONSIDERED, hexfpr, flagbuf, NULL);
3903 }
3904
3905
3906
3907 /* A high-level function to lookup keys.
3908  *
3909  * This function builds on top of the low-level keydb API.  It first
3910  * searches the database using the description stored in CTX->ITEMS,
3911  * then it filters the results using CTX and, finally, if WANT_SECRET
3912  * is set, it ignores any keys for which no secret key is available.
3913  *
3914  * Unlike the low-level search functions, this function also merges
3915  * all of the self-signed data into the keys, subkeys and user id
3916  * packets (see the merge_selfsigs for details).
3917  *
3918  * On success the key's keyblock is stored at *RET_KEYBLOCK, and the
3919  * specific subkey is stored at *RET_FOUND_KEY.  Note that we do not
3920  * return a reference in *RET_FOUND_KEY, i.e. the result must not be
3921  * freed using 'release_kbnode', and it is only valid until
3922  * *RET_KEYBLOCK is deallocated.  Therefore, if RET_FOUND_KEY is not
3923  * NULL, then RET_KEYBLOCK must not be NULL.  */
3924 static int
3925 lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret,
3926         kbnode_t *ret_keyblock, kbnode_t *ret_found_key)
3927 {
3928   int rc;
3929   int no_suitable_key = 0;
3930   KBNODE keyblock = NULL;
3931   KBNODE found_key = NULL;
3932   unsigned int infoflags;
3933
3934   log_assert (ret_found_key == NULL || ret_keyblock != NULL);
3935   if (ret_keyblock)
3936     *ret_keyblock = NULL;
3937
3938   for (;;)
3939     {
3940       rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
3941       if (rc)
3942         break;
3943
3944       /* If we are iterating over the entire database, then we need to
3945        * change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
3946        * reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next record.  */
3947       if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
3948         ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
3949
3950       rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
3951       if (rc)
3952         {
3953           log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
3954           goto skip;
3955         }
3956
3957       if (want_secret)
3958         {
3959           rc = agent_probe_any_secret_key (ctrl, keyblock);
3960           if (gpg_err_code(rc) == GPG_ERR_NO_SECKEY)
3961             goto skip; /* No secret key available.  */
3962           if (rc)
3963             goto found; /* Unexpected error.  */
3964         }
3965
3966       /* Warning: node flag bits 0 and 1 should be preserved by
3967        * merge_selfsigs.  */
3968       merge_selfsigs (ctrl, keyblock);
3969       found_key = finish_lookup (keyblock, ctx->req_usage, ctx->exact,
3970                                  want_secret, &infoflags);
3971       print_status_key_considered (keyblock, infoflags);
3972       if (found_key)
3973         {
3974           no_suitable_key = 0;
3975           goto found;
3976         }
3977       else
3978         {
3979           no_suitable_key = 1;
3980         }
3981
3982     skip:
3983       /* Release resources and continue search. */
3984       release_kbnode (keyblock);
3985       keyblock = NULL;
3986       /* The keyblock cache ignores the current "file position".
3987        * Thus, if we request the next result and the cache matches
3988        * (and it will since it is what we just looked for), we'll get
3989        * the same entry back!  We can avoid this infinite loop by
3990        * disabling the cache.  */
3991       keydb_disable_caching (ctx->kr_handle);
3992     }
3993
3994  found:
3995   if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
3996     log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
3997
3998   if (!rc)
3999     {
4000       if (ret_keyblock)
4001         {
4002           *ret_keyblock = keyblock; /* Return the keyblock.  */
4003           keyblock = NULL;
4004         }
4005     }
4006   else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
4007     rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
4008   else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
4009     rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
4010
4011   release_kbnode (keyblock);
4012
4013   if (ret_found_key)
4014     {
4015       if (! rc)
4016         *ret_found_key = found_key;
4017       else
4018         *ret_found_key = NULL;
4019     }
4020
4021   return rc;
4022 }
4023
4024
4025 /* If a default key has been specified, return that key.  If a card
4026  * based key is also available as indicated by FPR_CARD not being
4027  * NULL, return that key if suitable.  */
4028 gpg_error_t
4029 get_seckey_default_or_card (ctrl_t ctrl, PKT_public_key *pk,
4030                             const byte *fpr_card, size_t fpr_len)
4031 {
4032   gpg_error_t err;
4033   strlist_t namelist = NULL;
4034   const char *def_secret_key;
4035
4036   def_secret_key = parse_def_secret_key (ctrl);
4037
4038   if (def_secret_key)
4039     add_to_strlist (&namelist, def_secret_key);
4040   else if (fpr_card)
4041     {
4042       err = get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len);
4043       if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
4044         {
4045           if (opt.debug)
4046             log_debug ("using LDAP to find public key for current card\n");
4047           err = keyserver_import_fprint (ctrl, fpr_card, fpr_len,
4048                                          opt.keyserver,
4049                                          KEYSERVER_IMPORT_FLAG_LDAP);
4050           if (!err)
4051             err = get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len);
4052           else if (gpg_err_code (err) == GPG_ERR_NO_DATA
4053                    || gpg_err_code (err) == GPG_ERR_NO_KEYSERVER)
4054             {
4055               /* Dirmngr returns NO DATA is the selected keyserver
4056                * does not have the requested key.  It returns NO
4057                * KEYSERVER if no LDAP keyservers are configured.  */
4058               err = gpg_error (GPG_ERR_NO_PUBKEY);
4059             }
4060         }
4061
4062       /* The key on card can be not suitable for requested usage.  */
4063       if (gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY)
4064         fpr_card = NULL;        /* Fallthrough as no card.  */
4065       else
4066         return err;  /* Success or other error.  */
4067     }
4068
4069   if (!fpr_card || (def_secret_key && *def_secret_key
4070                     && def_secret_key[strlen (def_secret_key)-1] == '!'))
4071     {
4072       err = key_byname (ctrl, NULL, namelist, pk, 1, 0, NULL, NULL);
4073     }
4074   else
4075     { /* Default key is specified and card key is also available.  */
4076       kbnode_t k, keyblock = NULL;
4077
4078       err = key_byname (ctrl, NULL, namelist, pk, 1, 0, &keyblock, NULL);
4079       if (err)
4080         goto leave;
4081       for (k = keyblock; k; k = k->next)
4082         {
4083           PKT_public_key *pk_candidate;
4084           char fpr[MAX_FINGERPRINT_LEN];
4085
4086           if (k->pkt->pkttype != PKT_PUBLIC_KEY
4087               &&k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
4088             continue;
4089
4090           pk_candidate = k->pkt->pkt.public_key;
4091           if (!pk_candidate->flags.valid)
4092             continue;
4093           if (!((pk_candidate->pubkey_usage & USAGE_MASK) & pk->req_usage))
4094             continue;
4095           fingerprint_from_pk (pk_candidate, fpr, NULL);
4096           if (!memcmp (fpr_card, fpr, fpr_len))
4097             {
4098               release_public_key_parts (pk);
4099               copy_public_key (pk, pk_candidate);
4100               break;
4101             }
4102         }
4103       release_kbnode (keyblock);
4104     }
4105
4106  leave:
4107   free_strlist (namelist);
4108   return err;
4109 }
4110
4111
4112 \f
4113 /*********************************************
4114  ***********  User ID printing helpers *******
4115  *********************************************/
4116
4117 /* Return a string with a printable representation of the user_id.
4118  * this string must be freed by xfree.  If R_NOUID is not NULL it is
4119  * set to true if a user id was not found; otherwise to false.  */
4120 static char *
4121 get_user_id_string (ctrl_t ctrl, u32 * keyid, int mode)
4122 {
4123   char *name;
4124   unsigned int namelen;
4125   char *p;
4126
4127   log_assert (mode != 2);
4128
4129   name = cache_get_uid_bykid (keyid, &namelen);
4130   if (!name)
4131     {
4132       /* Get it so that the cache will be filled.  */
4133       if (!get_pubkey (ctrl, NULL, keyid))
4134         name = cache_get_uid_bykid (keyid, &namelen);
4135     }
4136
4137   if (name)
4138     {
4139       if (mode)
4140         p = xasprintf ("%08lX%08lX %.*s",
4141                        (ulong) keyid[0], (ulong) keyid[1], namelen, name);
4142       else
4143         p = xasprintf ("%s %.*s", keystr (keyid), namelen, name);
4144
4145       xfree (name);
4146     }
4147   else
4148     {
4149       if (mode)
4150         p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
4151       else
4152         p = xasprintf ("%s [?]", keystr (keyid));
4153     }
4154
4155   return p;
4156 }
4157
4158
4159 char *
4160 get_user_id_string_native (ctrl_t ctrl, u32 * keyid)
4161 {
4162   char *p = get_user_id_string (ctrl, keyid, 0);
4163   char *p2 = utf8_to_native (p, strlen (p), 0);
4164   xfree (p);
4165   return p2;
4166 }
4167
4168
4169 char *
4170 get_long_user_id_string (ctrl_t ctrl, u32 * keyid)
4171 {
4172   return get_user_id_string (ctrl, keyid, 1);
4173 }
4174
4175
4176 /* Please try to use get_user_byfpr instead of this one.  */
4177 char *
4178 get_user_id (ctrl_t ctrl, u32 *keyid, size_t *rn, int *r_nouid)
4179 {
4180   char *name;
4181   unsigned int namelen;
4182
4183   if (r_nouid)
4184     *r_nouid = 0;
4185
4186   name = cache_get_uid_bykid (keyid, &namelen);
4187   if (!name)
4188     {
4189       /* Get it so that the cache will be filled.  */
4190       if (!get_pubkey (ctrl, NULL, keyid))
4191         name = cache_get_uid_bykid (keyid, &namelen);
4192     }
4193
4194   if (!name)
4195     {
4196       name = xstrdup (user_id_not_found_utf8 ());
4197       namelen = strlen (name);
4198       if (r_nouid)
4199         *r_nouid = 1;
4200     }
4201
4202   if (rn && name)
4203     *rn = namelen;
4204   return name;
4205 }
4206
4207
4208 /* Please try to use get_user_id_byfpr_native instead of this one.  */
4209 char *
4210 get_user_id_native (ctrl_t ctrl, u32 *keyid)
4211 {
4212   size_t rn;
4213   char *p = get_user_id (ctrl, keyid, &rn, NULL);
4214   char *p2 = utf8_to_native (p, rn, 0);
4215   xfree (p);
4216   return p2;
4217 }
4218
4219
4220 /* Return the user id for a key designated by its fingerprint, FPR,
4221    which must be MAX_FINGERPRINT_LEN bytes in size.  Note: the
4222    returned string, which must be freed using xfree, may not be NUL
4223    terminated.  To determine the length of the string, you must use
4224    *RN.  */
4225 static char *
4226 get_user_id_byfpr (ctrl_t ctrl, const byte *fpr, size_t fprlen, size_t *rn)
4227 {
4228   char *name;
4229
4230   name = cache_get_uid_byfpr (fpr, fprlen, rn);
4231   if (!name)
4232     {
4233       /* Get it so that the cache will be filled.  */
4234       if (!get_pubkey_byfprint (ctrl, NULL, NULL, fpr, fprlen))
4235         name = cache_get_uid_byfpr (fpr, fprlen, rn);
4236     }
4237
4238   if (!name)
4239     {
4240       name = xstrdup (user_id_not_found_utf8 ());
4241       *rn = strlen (name);
4242     }
4243
4244   return name;
4245 }
4246
4247 /* Like get_user_id_byfpr, but convert the string to the native
4248    encoding.  The returned string needs to be freed.  Unlike
4249    get_user_id_byfpr, the returned string is NUL terminated.  */
4250 char *
4251 get_user_id_byfpr_native (ctrl_t ctrl, const byte *fpr, size_t fprlen)
4252 {
4253   size_t rn;
4254   char *p = get_user_id_byfpr (ctrl, fpr, fprlen, &rn);
4255   char *p2 = utf8_to_native (p, rn, 0);
4256   xfree (p);
4257   return p2;
4258 }
4259
4260
4261 /* Return the database handle used by this context.  The context still
4262    owns the handle.  */
4263 KEYDB_HANDLE
4264 get_ctx_handle (GETKEY_CTX ctx)
4265 {
4266   return ctx->kr_handle;
4267 }
4268
4269 static void
4270 free_akl (struct akl *akl)
4271 {
4272   if (! akl)
4273     return;
4274
4275   if (akl->spec)
4276     free_keyserver_spec (akl->spec);
4277
4278   xfree (akl);
4279 }
4280
4281 void
4282 release_akl (void)
4283 {
4284   while (opt.auto_key_locate)
4285     {
4286       struct akl *akl2 = opt.auto_key_locate;
4287       opt.auto_key_locate = opt.auto_key_locate->next;
4288       free_akl (akl2);
4289     }
4290 }
4291
4292
4293 /* Returns true if the AKL is empty or has only the local method
4294  * active.  */
4295 int
4296 akl_empty_or_only_local (void)
4297 {
4298   struct akl *akl;
4299   int any = 0;
4300
4301   for (akl = opt.auto_key_locate; akl; akl = akl->next)
4302     if (akl->type != AKL_NODEFAULT && akl->type != AKL_LOCAL)
4303       {
4304         any = 1;
4305         break;
4306       }
4307
4308   return !any;
4309 }
4310
4311
4312 /* Returns false on error. */
4313 int
4314 parse_auto_key_locate (const char *options_arg)
4315 {
4316   char *tok;
4317   char *options, *options_buf;
4318
4319   options = options_buf = xstrdup (options_arg);
4320   while ((tok = optsep (&options)))
4321     {
4322       struct akl *akl, *check, *last = NULL;
4323       int dupe = 0;
4324
4325       if (tok[0] == '\0')
4326         continue;
4327
4328       akl = xmalloc_clear (sizeof (*akl));
4329
4330       if (ascii_strcasecmp (tok, "clear") == 0)
4331         {
4332           xfree (akl);
4333           free_akl (opt.auto_key_locate);
4334           opt.auto_key_locate = NULL;
4335           continue;
4336         }
4337       else if (ascii_strcasecmp (tok, "nodefault") == 0)
4338         akl->type = AKL_NODEFAULT;
4339       else if (ascii_strcasecmp (tok, "local") == 0)
4340         akl->type = AKL_LOCAL;
4341       else if (ascii_strcasecmp (tok, "ldap") == 0)
4342         akl->type = AKL_LDAP;
4343       else if (ascii_strcasecmp (tok, "keyserver") == 0)
4344         akl->type = AKL_KEYSERVER;
4345       else if (ascii_strcasecmp (tok, "cert") == 0)
4346         akl->type = AKL_CERT;
4347       else if (ascii_strcasecmp (tok, "pka") == 0)
4348         akl->type = AKL_PKA;
4349       else if (ascii_strcasecmp (tok, "dane") == 0)
4350         akl->type = AKL_DANE;
4351       else if (ascii_strcasecmp (tok, "wkd") == 0)
4352         akl->type = AKL_WKD;
4353       else if (ascii_strcasecmp (tok, "ntds") == 0)
4354         akl->type = AKL_NTDS;
4355       else if ((akl->spec = parse_keyserver_uri (tok, 1)))
4356         akl->type = AKL_SPEC;
4357       else
4358         {
4359           free_akl (akl);
4360           xfree (options_buf);
4361           return 0;
4362         }
4363
4364       /* We must maintain the order the user gave us */
4365       for (check = opt.auto_key_locate; check;
4366            last = check, check = check->next)
4367         {
4368           /* Check for duplicates */
4369           if (check->type == akl->type
4370               && (akl->type != AKL_SPEC
4371                   || (akl->type == AKL_SPEC
4372                       && strcmp (check->spec->uri, akl->spec->uri) == 0)))
4373             {
4374               dupe = 1;
4375               free_akl (akl);
4376               break;
4377             }
4378         }
4379
4380       if (!dupe)
4381         {
4382           if (last)
4383             last->next = akl;
4384           else
4385             opt.auto_key_locate = akl;
4386         }
4387     }
4388
4389   xfree (options_buf);
4390   return 1;
4391 }
4392
4393
4394 \f
4395 /* The list of key origins. */
4396 static struct {
4397   const char *name;
4398   int origin;
4399 } key_origin_list[] =
4400   {
4401     { "self",    KEYORG_SELF    },
4402     { "file",    KEYORG_FILE    },
4403     { "url",     KEYORG_URL     },
4404     { "wkd",     KEYORG_WKD     },
4405     { "dane",    KEYORG_DANE    },
4406     { "ks-pref", KEYORG_KS_PREF },
4407     { "ks",      KEYORG_KS      },
4408     { "unknown", KEYORG_UNKNOWN }
4409   };
4410
4411 /* Parse the argument for --key-origin.  Return false on error. */
4412 int
4413 parse_key_origin (char *string)
4414 {
4415   int i;
4416   char *comma;
4417
4418   comma = strchr (string, ',');
4419   if (comma)
4420     *comma = 0;
4421
4422   if (!ascii_strcasecmp (string, "help"))
4423     {
4424       log_info (_("valid values for option '%s':\n"), "--key-origin");
4425       for (i=0; i < DIM (key_origin_list); i++)
4426         log_info ("  %s\n", key_origin_list[i].name);
4427       g10_exit (1);
4428     }
4429
4430   for (i=0; i < DIM (key_origin_list); i++)
4431     if (!ascii_strcasecmp (string, key_origin_list[i].name))
4432       {
4433         opt.key_origin = key_origin_list[i].origin;
4434         xfree (opt.key_origin_url);
4435         opt.key_origin_url = NULL;
4436         if (comma && comma[1])
4437           {
4438             opt.key_origin_url = xstrdup (comma+1);
4439             trim_spaces (opt.key_origin_url);
4440           }
4441
4442         return 1;
4443       }
4444
4445   if (comma)
4446     *comma = ',';
4447   return 0;
4448 }
4449
4450 /* Return a string or "?" for the key ORIGIN.  */
4451 const char *
4452 key_origin_string (int origin)
4453 {
4454   int i;
4455
4456   for (i=0; i < DIM (key_origin_list); i++)
4457     if (key_origin_list[i].origin == origin)
4458       return key_origin_list[i].name;
4459   return "?";
4460 }
4461
4462
4463 \f
4464 /* Returns true if a secret key is available for the public key with
4465    key id KEYID; returns false if not.  This function ignores legacy
4466    keys.  Note: this is just a fast check and does not tell us whether
4467    the secret key is valid; this check merely indicates whether there
4468    is some secret key with the specified key id.  */
4469 int
4470 have_secret_key_with_kid (ctrl_t ctrl, u32 *keyid)
4471 {
4472   gpg_error_t err;
4473   KEYDB_HANDLE kdbhd;
4474   KEYDB_SEARCH_DESC desc;
4475   kbnode_t keyblock;
4476   kbnode_t node;
4477   int result = 0;
4478
4479   kdbhd = keydb_new (ctrl);
4480   if (!kdbhd)
4481     return 0;
4482   memset (&desc, 0, sizeof desc);
4483   desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
4484   desc.u.kid[0] = keyid[0];
4485   desc.u.kid[1] = keyid[1];
4486   while (!result)
4487     {
4488       err = keydb_search (kdbhd, &desc, 1, NULL);
4489       if (err)
4490         break;
4491
4492       err = keydb_get_keyblock (kdbhd, &keyblock);
4493       if (err)
4494         {
4495           log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
4496           break;
4497         }
4498
4499       for (node = keyblock; node; node = node->next)
4500         {
4501           /* Bit 0 of the flags is set if the search found the key
4502              using that key or subkey.  Note: a search will only ever
4503              match a single key or subkey.  */
4504           if ((node->flag & 1))
4505             {
4506               log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY
4507                           || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
4508
4509               if (agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
4510                 result = 1; /* Secret key available.  */
4511               else
4512                 result = 0;
4513
4514               break;
4515             }
4516         }
4517       release_kbnode (keyblock);
4518     }
4519
4520   keydb_release (kdbhd);
4521   return result;
4522 }