Coverage Report

Created: 2026-10-28 06:32

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