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