Coverage Report

Created: 2026-06-09 06:38

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
408
{
328
408
  gpg_error_t err;
329
408
  const byte *fpr;
330
408
  size_t fprlen;
331
332
408
  if (r_keyblock)
333
408
    *r_keyblock = NULL;
334
335
408
  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
408
  pk->req_usage = (PUBKEY_USAGE_SIG | PUBKEY_USAGE_VERIFY
347
408
                   | (pk->req_usage & PUBKEY_USAGE_CERT));
348
349
  /* If SIG is a revocation signature we also consider certify keys. */
350
408
  if (IS_KEY_REV (sig))
351
0
    pk->req_usage |= PUBKEY_USAGE_CERT;
352
353
  /* First try the ISSUER_FPR info.  */
354
408
  fpr = issuer_fpr_raw (sig, &fprlen);
355
408
  if (fpr && !get_pubkey_byfpr (ctrl, pk, r_keyblock, fpr, fprlen))
356
0
    return 0;
357
408
  if (r_keyblock)
358
408
    {
359
408
      release_kbnode (*r_keyblock);
360
408
      *r_keyblock = NULL;
361
408
    }
362
363
  /* Fallback to use the ISSUER_KEYID.  */
364
408
  err = get_pubkey_bykid (ctrl, pk, r_keyblock, sig->keyid);
365
408
  if (err && r_keyblock)
366
408
    {
367
408
      release_kbnode (*r_keyblock);
368
408
      *r_keyblock = NULL;
369
408
    }
370
408
  return err;
371
408
}
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
1.21M
{
403
1.21M
  int internal = 0;
404
1.21M
  gpg_error_t rc = 0;
405
406
1.21M
  if (r_keyblock)
407
408
    *r_keyblock = NULL;
408
409
1.21M
#if MAX_PK_CACHE_ENTRIES
410
1.21M
  if (pk && !r_keyblock)
411
1.21M
    {
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
1.21M
      pk_cache_entry_t ce;
420
1.21M
      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
1.21M
    }
429
1.21M
#endif
430
431
  /* More init stuff.  */
432
1.21M
  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
1.21M
  {
446
1.21M
    struct getkey_ctx_s ctx;
447
1.21M
    kbnode_t kb = NULL;
448
1.21M
    kbnode_t found_key = NULL;
449
450
1.21M
    memset (&ctx, 0, sizeof ctx);
451
1.21M
    ctx.exact = 1; /* Use the key ID exactly as given.  */
452
1.21M
    ctx.not_allocated = 1;
453
454
1.21M
    if (ctrl && ctrl->cached_getkey_kdb)
455
1.21M
      {
456
1.21M
        ctx.kr_handle = ctrl->cached_getkey_kdb;
457
1.21M
        ctrl->cached_getkey_kdb = NULL;
458
1.21M
        keydb_search_reset (ctx.kr_handle);
459
1.21M
      }
460
123
    else
461
123
      {
462
123
        ctx.kr_handle = keydb_new (ctrl);
463
123
        if (!ctx.kr_handle)
464
0
          {
465
0
            rc = gpg_error_from_syserror ();
466
0
            goto leave;
467
0
          }
468
123
      }
469
1.21M
    ctx.nitems = 1;
470
1.21M
    ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
471
1.21M
    ctx.items[0].u.kid[0] = keyid[0];
472
1.21M
    ctx.items[0].u.kid[1] = keyid[1];
473
1.21M
    ctx.req_usage = pk->req_usage;
474
1.21M
    rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
475
1.21M
    if (!rc)
476
0
      pk_from_block (pk, kb, found_key);
477
1.21M
    getkey_end (ctrl, &ctx);
478
1.21M
    if (!rc && r_keyblock)
479
0
      {
480
0
        *r_keyblock = kb;
481
0
        kb = NULL;
482
0
      }
483
1.21M
    release_kbnode (kb);
484
1.21M
  }
485
486
1.21M
  if (rc)  /* Return a more useful error code.  */
487
1.21M
    rc = gpg_error (GPG_ERR_NO_PUBKEY);
488
489
1.21M
leave:
490
1.21M
  if (!rc)
491
0
    cache_public_key (pk);
492
1.21M
  if (internal)
493
0
    free_public_key (pk);
494
1.21M
  return rc;
495
1.21M
}
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
1.21M
{
502
1.21M
  return get_pubkey_bykid (ctrl, pk, NULL, keyid);
503
1.21M
}
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
2.57k
{
555
2.57k
  int rc = 0;
556
2.57k
  KEYDB_HANDLE hd;
557
2.57k
  KBNODE keyblock;
558
2.57k
  u32 pkid[2];
559
560
2.57k
  log_assert (pk);
561
2.57k
#if MAX_PK_CACHE_ENTRIES
562
2.57k
  {
563
    /* Try to get it from the cache */
564
2.57k
    pk_cache_entry_t ce;
565
566
2.57k
    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
2.57k
  }
579
2.57k
#endif
580
581
2.57k
  hd = keydb_new (ctrl);
582
2.57k
  if (!hd)
583
0
    return gpg_error_from_syserror ();
584
2.57k
  rc = keydb_search_kid (hd, keyid);
585
2.57k
  if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
586
2.57k
    {
587
2.57k
      keydb_release (hd);
588
2.57k
      return GPG_ERR_NO_PUBKEY;
589
2.57k
    }
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
3.86k
{
825
3.86k
  int rc = 0;
826
3.86k
  int n;
827
3.86k
  strlist_t r;
828
3.86k
  strlist_t namelist_expanded = NULL;
829
3.86k
  GETKEY_CTX ctx;
830
3.86k
  kbnode_t help_kb = NULL;
831
3.86k
  kbnode_t found_key = NULL;
832
833
3.86k
  if (retctx)
834
3.86k
    {
835
      /* Reset the returned context in case of error.  */
836
3.86k
      log_assert (!ret_kdbhd); /* Not allowed because the handle is stored
837
                                  in the context.  */
838
3.86k
      *retctx = NULL;
839
3.86k
    }
840
3.86k
  if (ret_kdbhd)
841
0
    *ret_kdbhd = NULL;
842
843
3.86k
  if (!namelist)
844
    /* No search terms: iterate over the whole DB.  */
845
3.86k
    {
846
3.86k
      ctx = xmalloc_clear (sizeof *ctx);
847
3.86k
      ctx->nitems = 1;
848
3.86k
      ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
849
3.86k
      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
3.86k
    }
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
3.86k
  ctx->want_secret = !!(flags & GETKEY_WANT_SECRET);
896
3.86k
  ctx->allow_adsk  = !!(flags & GETKEY_ALLOW_ADSK);
897
3.86k
  ctx->kr_handle = keydb_new (ctrl);
898
3.86k
  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
3.86k
  if (!ret_kb)
906
0
    ret_kb = &help_kb;
907
908
3.86k
  if (ret_kdbhd)
909
0
    keydb_lock (ctx->kr_handle);
910
911
912
3.86k
  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
3.86k
  rc = lookup (ctrl, ctx, ctx->want_secret, ret_kb, &found_key);
923
3.86k
  if (!rc && pk)
924
0
    {
925
0
      pk_from_block (pk, *ret_kb, found_key);
926
0
    }
927
928
3.86k
  release_kbnode (help_kb);
929
930
3.86k
  if (retctx) /* Caller wants the context.  */
931
3.86k
    {
932
3.86k
      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
3.86k
      else
939
3.86k
        ctx->extra_list = namelist_expanded;
940
3.86k
      namelist_expanded = NULL;
941
3.86k
      *retctx = ctx;
942
3.86k
    }
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
3.86k
 leave:
954
3.86k
  free_strlist (namelist_expanded);
955
3.86k
  return rc;
956
3.86k
}
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
0
{
1931
0
  int rc;
1932
1933
0
  if (r_keyblock)
1934
0
    *r_keyblock = NULL;
1935
1936
0
  if (fprlen == 32 || fprlen == 20 || fprlen == 16)
1937
0
    {
1938
0
      struct getkey_ctx_s ctx;
1939
0
      KBNODE kb = NULL;
1940
0
      KBNODE found_key = NULL;
1941
1942
0
      memset (&ctx, 0, sizeof ctx);
1943
0
      ctx.exact = 1;
1944
0
      ctx.not_allocated = 1;
1945
      /* FIXME: We should get the handle from the cache like we do in
1946
       * get_pubkey.  */
1947
0
      ctx.kr_handle = keydb_new (ctrl);
1948
0
      if (!ctx.kr_handle)
1949
0
        return gpg_error_from_syserror ();
1950
1951
0
      ctx.nitems = 1;
1952
0
      ctx.items[0].mode = KEYDB_SEARCH_MODE_FPR;
1953
0
      memcpy (ctx.items[0].u.fpr, fpr, fprlen);
1954
0
      ctx.items[0].fprlen = fprlen;
1955
0
      if (pk)
1956
0
        ctx.req_usage = pk->req_usage;
1957
0
      rc = lookup (ctrl, &ctx, 0, &kb, &found_key);
1958
0
      if (!rc && pk)
1959
0
  pk_from_block (pk, kb, found_key);
1960
0
      if (!rc && r_keyblock)
1961
0
  {
1962
0
    *r_keyblock = kb;
1963
0
    kb = NULL;
1964
0
  }
1965
0
      release_kbnode (kb);
1966
0
      getkey_end (ctrl, &ctx);
1967
0
    }
1968
0
  else
1969
0
    rc = GPG_ERR_GENERAL; /* Oops */
1970
0
  return rc;
1971
0
}
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
3.86k
{
2105
3.86k
  KEYDB_HANDLE hd = NULL;
2106
3.86k
  strlist_t t;
2107
3.86k
  static int warned;
2108
2109
3.86k
  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
3.86k
  if (! warned && opt.def_secret_key && ! t)
2233
3.86k
    log_info (_("all values passed to '%s' ignored\n"),
2234
0
              "--default-key");
2235
2236
3.86k
  warned = 1;
2237
2238
3.86k
  if (hd)
2239
0
    keydb_release (hd);
2240
2241
3.86k
  if (t)
2242
0
    return t->d;
2243
3.86k
  return NULL;
2244
3.86k
}
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
3.86k
{
2333
3.86k
  return key_byname (ctrl, retctx, names, pk,
2334
3.86k
                     (flags | GETKEY_WITH_UNUSABLE),
2335
3.86k
                     ret_keyblock, NULL);
2336
3.86k
}
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
1.21M
{
2466
1.21M
  if (ctx)
2467
1.21M
    {
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
1.21M
      if (ctrl && !ctrl->cached_getkey_kdb)
2483
1.21M
        ctrl->cached_getkey_kdb = ctx->kr_handle;
2484
3.86k
      else
2485
3.86k
        keydb_release (ctx->kr_handle);
2486
2487
1.21M
#endif /*!HAVE_W32_SYSTEM*/
2488
2489
1.21M
      free_strlist (ctx->extra_list);
2490
1.21M
      if (!ctx->not_allocated)
2491
3.86k
  xfree (ctx);
2492
1.21M
    }
2493
1.21M
}
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
18.3k
{
2543
18.3k
  if (!keyblock)
2544
0
    ;
2545
18.3k
  else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
2546
17.4k
    merge_selfsigs (ctrl, keyblock);
2547
919
  else
2548
18.3k
    log_debug ("FIXME: merging secret key blocks is not anymore available\n");
2549
18.3k
}
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
2.53k
{
2556
2.53k
  int key_usage = 0;
2557
2.53k
  const byte *p;
2558
2.53k
  size_t n;
2559
2.53k
  byte flags;
2560
2561
2.53k
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_FLAGS, &n);
2562
2.53k
  if (p && n)
2563
494
    {
2564
      /* First octet of the keyflags.  */
2565
494
      flags = *p;
2566
2567
494
      if (flags & 1)
2568
284
  {
2569
284
    key_usage |= PUBKEY_USAGE_CERT;
2570
284
    flags &= ~1;
2571
284
  }
2572
2573
494
      if (flags & 2)
2574
373
  {
2575
373
    key_usage |= PUBKEY_USAGE_SIG;
2576
373
    flags &= ~2;
2577
373
  }
2578
2579
      /* We do not distinguish between encrypting communications and
2580
         encrypting storage. */
2581
494
      if (flags & (0x04 | 0x08))
2582
168
  {
2583
168
    key_usage |= PUBKEY_USAGE_ENC;
2584
168
    flags &= ~(0x04 | 0x08);
2585
168
  }
2586
2587
494
      if (flags & 0x20)
2588
0
  {
2589
0
    key_usage |= PUBKEY_USAGE_AUTH;
2590
0
    flags &= ~0x20;
2591
0
  }
2592
2593
494
      if ((flags & 0x80))
2594
0
  {
2595
0
    key_usage |= PUBKEY_USAGE_GROUP;
2596
0
    flags &= ~0x80;
2597
0
  }
2598
2599
494
      if (flags)
2600
0
  key_usage |= PUBKEY_USAGE_UNKNOWN;
2601
2602
494
      n--;
2603
494
      p++;
2604
494
      if (n)
2605
0
        {
2606
0
          flags = *p;
2607
0
          if ((flags & 0x04))
2608
0
            key_usage |= PUBKEY_USAGE_RENC;
2609
0
          if ((flags & 0x08))
2610
0
            key_usage |= PUBKEY_USAGE_TIME;
2611
0
        }
2612
2613
494
      if (!key_usage)
2614
0
  key_usage |= PUBKEY_USAGE_NONE;
2615
2616
494
    }
2617
2.04k
  else if (p) /* Key flags of length zero.  */
2618
0
    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
2.53k
  return key_usage;
2628
2.53k
}
2629
2630
2631
/* Apply information from SIGNODE (which is the valid self-signature
2632
 * associated with that UID) to the UIDNODE:
2633
 * - whether the UID has been revoked
2634
 * - assumed creation date of the UID
2635
 * - temporary store the keyflags here
2636
 * - temporary store the key expiration time here
2637
 * - mark whether the primary user ID flag hat been set.
2638
 * - store the preferences
2639
 */
2640
static void
2641
fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
2642
1.25k
{
2643
1.25k
  PKT_user_id *uid = uidnode->pkt->pkt.user_id;
2644
1.25k
  PKT_signature *sig = signode->pkt->pkt.signature;
2645
1.25k
  const byte *p, *sym, *aead, *hash, *zip;
2646
1.25k
  size_t n, nsym, naead, nhash, nzip;
2647
2648
1.25k
  sig->flags.chosen_selfsig = 1;/* We chose this one. */
2649
1.25k
  uid->created = 0;   /* Not created == invalid. */
2650
1.25k
  if (IS_UID_REV (sig))
2651
37
    {
2652
37
      uid->flags.revoked = 1;
2653
37
      return; /* Has been revoked.  */
2654
37
    }
2655
1.21k
  else
2656
1.21k
    uid->flags.revoked = 0;
2657
2658
1.21k
  uid->expiredate = sig->expiredate;
2659
2660
1.21k
  if (sig->flags.expired)
2661
0
    {
2662
0
      uid->flags.expired = 1;
2663
0
      return; /* Has expired.  */
2664
0
    }
2665
1.21k
  else
2666
1.21k
    uid->flags.expired = 0;
2667
2668
1.21k
  uid->created = sig->timestamp; /* This one is okay. */
2669
1.21k
  uid->selfsigversion = sig->version;
2670
  /* If we got this far, it's not expired :) */
2671
1.21k
  uid->flags.expired = 0;
2672
2673
  /* Store the key flags in the helper variable for later processing.  */
2674
1.21k
  uid->help_key_usage = parse_key_usage (sig);
2675
2676
  /* Ditto for the key expiration.  */
2677
1.21k
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
2678
1.21k
  if (p && buf32_to_u32 (p))
2679
101
    uid->help_key_expire = keycreated + buf32_to_u32 (p);
2680
1.11k
  else
2681
1.11k
    uid->help_key_expire = 0;
2682
2683
  /* Set the primary user ID flag - we will later wipe out some
2684
   * of them to only have one in our keyblock.  */
2685
1.21k
  uid->flags.primary = 0;
2686
1.21k
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PRIMARY_UID, NULL);
2687
1.21k
  if (p && *p)
2688
0
    uid->flags.primary = 2;
2689
2690
  /* We could also query this from the unhashed area if it is not in
2691
   * the hased area and then later try to decide which is the better
2692
   * there should be no security problem with this.
2693
   * For now we only look at the hashed one.  */
2694
2695
  /* Now build the preferences list.  These must come from the
2696
     hashed section so nobody can modify the ciphers a key is
2697
     willing to accept.  */
2698
1.21k
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_SYM, &n);
2699
1.21k
  sym = p;
2700
1.21k
  nsym = p ? n : 0;
2701
1.21k
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_AEAD, &n);
2702
1.21k
  aead = p;
2703
1.21k
  naead = p ? n : 0;
2704
1.21k
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_HASH, &n);
2705
1.21k
  hash = p;
2706
1.21k
  nhash = p ? n : 0;
2707
1.21k
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_COMPR, &n);
2708
1.21k
  zip = p;
2709
1.21k
  nzip = p ? n : 0;
2710
1.21k
  if (uid->prefs)
2711
0
    xfree (uid->prefs);
2712
1.21k
  n = nsym + naead + nhash + nzip;
2713
1.21k
  if (!n)
2714
285
    uid->prefs = NULL;
2715
931
  else
2716
931
    {
2717
931
      uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
2718
931
      n = 0;
2719
3.14k
      for (; nsym; nsym--, n++)
2720
2.21k
  {
2721
2.21k
    uid->prefs[n].type = PREFTYPE_SYM;
2722
2.21k
    uid->prefs[n].value = *sym++;
2723
2.21k
  }
2724
931
      for (; naead; naead--, n++)
2725
0
  {
2726
0
    uid->prefs[n].type = PREFTYPE_AEAD;
2727
0
    uid->prefs[n].value = *aead++;
2728
0
  }
2729
3.23k
      for (; nhash; nhash--, n++)
2730
2.30k
  {
2731
2.30k
    uid->prefs[n].type = PREFTYPE_HASH;
2732
2.30k
    uid->prefs[n].value = *hash++;
2733
2.30k
  }
2734
2.84k
      for (; nzip; nzip--, n++)
2735
1.91k
  {
2736
1.91k
    uid->prefs[n].type = PREFTYPE_ZIP;
2737
1.91k
    uid->prefs[n].value = *zip++;
2738
1.91k
  }
2739
931
      uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker  */
2740
931
      uid->prefs[n].value = 0;
2741
931
    }
2742
2743
  /* See whether we have the MDC feature.  */
2744
1.21k
  uid->flags.mdc = 0;
2745
1.21k
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n);
2746
1.21k
  if (p && n && (p[0] & 0x01))
2747
334
    uid->flags.mdc = 1;
2748
2749
  /* See whether we have the AEAD feature.  */
2750
1.21k
  uid->flags.aead = 0;
2751
1.21k
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n);
2752
1.21k
  if (p && n && (p[0] & 0x02))
2753
0
    uid->flags.aead = 1;
2754
2755
  /* And the keyserver modify flag.  */
2756
1.21k
  uid->flags.ks_modify = 1;
2757
1.21k
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KS_FLAGS, &n);
2758
1.21k
  if (p && n && (p[0] & 0x80))
2759
784
    uid->flags.ks_modify = 0;
2760
1.21k
}
2761
2762
2763
/* Store the revocation signature into the RINFO struct.  */
2764
static void
2765
sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
2766
22
{
2767
22
  int reason_seq = 0;
2768
22
  size_t reason_n;
2769
22
  const byte *reason_p;
2770
2771
22
  rinfo->date = sig->timestamp;
2772
22
  rinfo->algo = sig->pubkey_algo;
2773
22
  rinfo->keyid[0] = sig->keyid[0];
2774
22
  rinfo->keyid[1] = sig->keyid[1];
2775
22
  xfree (rinfo->reason_comment);
2776
22
  rinfo->reason_comment = NULL;
2777
22
  rinfo->reason_comment_len = 0;
2778
22
  rinfo->reason_code = 0;
2779
22
  rinfo->got_reason = 0;
2780
2781
22
  while ((reason_p = enum_sig_subpkt (sig, 1, SIGSUBPKT_REVOC_REASON,
2782
22
                                      &reason_n, &reason_seq, NULL))
2783
0
         && !reason_n)
2784
0
    ; /* Skip over empty reason packets.  */
2785
2786
22
  if (reason_p)
2787
0
    {
2788
0
      rinfo->got_reason = 1;
2789
0
      rinfo->reason_code = *reason_p;
2790
0
      reason_n--; reason_p++;
2791
0
      if (reason_n)
2792
0
        {
2793
0
          rinfo->reason_comment = xmalloc (reason_n);
2794
0
          memcpy (rinfo->reason_comment, reason_p, reason_n);
2795
0
          rinfo->reason_comment_len = reason_n;
2796
0
        }
2797
0
    }
2798
22
}
2799
2800
2801
/* Given a keyblock, parse the key block and extract various pieces of
2802
 * information and save them with the primary key packet and the user
2803
 * id packets.  For instance, some information is stored in signature
2804
 * packets.  We find the latest such valid packet (since the user can
2805
 * change that information) and copy its contents into the
2806
 * PKT_public_key.
2807
 *
2808
 * Note that R_REVOKED may be set to 0 (not revoked), 1 (self-revoked)
2809
 * or 2 (desig-revoked).
2810
 *
2811
 * This function fills in the following fields in the primary key's
2812
 * keyblock:
2813
 *
2814
 *   main_keyid          (computed)
2815
 *   revkey / numrevkeys (derived from self signed key data)
2816
 *   flags.valid         (whether we have at least 1 self-sig)
2817
 *   flags.maybe_revoked (whether a designed revoked the key, but
2818
 *                        we are missing the key to check the sig)
2819
 *   selfsigversion      (highest version of any valid self-sig)
2820
 *   pubkey_usage        (derived from most recent self-sig or most
2821
 *                        recent user id)
2822
 *   has_expired         (various sources)
2823
 *   expiredate          (various sources)
2824
 *
2825
 * See the documentation for fixup_uidnode for how the user id packets
2826
 * are modified.  In addition to that the primary user id's is_primary
2827
 * field is set to 1 and the other user id's is_primary are set to 0.
2828
 */
2829
static void
2830
merge_selfsigs_main (ctrl_t ctrl, kbnode_t keyblock, int *r_revoked,
2831
         struct revoke_info *rinfo)
2832
17.4k
{
2833
17.4k
  PKT_public_key *pk = NULL;
2834
17.4k
  KBNODE k;
2835
17.4k
  u32 kid[2];
2836
17.4k
  u32 sigdate, uiddate, uiddate2;
2837
17.4k
  KBNODE signode, uidnode, uidnode2;
2838
17.4k
  u32 curtime = make_timestamp ();
2839
17.4k
  unsigned int key_usage = 0;
2840
17.4k
  u32 keytimestamp = 0;  /* Creation time of the key.  */
2841
17.4k
  u32 key_expire = 0;
2842
17.4k
  int key_expire_seen = 0;
2843
17.4k
  byte sigversion = 0;
2844
2845
17.4k
  *r_revoked = 0;
2846
17.4k
  memset (rinfo, 0, sizeof (*rinfo));
2847
2848
  /* Section 11.1 of RFC 4880 determines the order of packets within a
2849
   * message.  There are three sections, which must occur in the
2850
   * following order: the public key, the user ids and user attributes
2851
   * and the subkeys.  Within each section, each primary packet (e.g.,
2852
   * a user id packet) is followed by one or more signature packets,
2853
   * which modify that packet.  */
2854
2855
  /* According to Section 11.1 of RFC 4880, the public key must be the
2856
     first packet.  Note that parse_keyblock_image ensures that the
2857
     first packet is the public key.  */
2858
17.4k
  if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2859
0
    BUG ();
2860
17.4k
  pk = keyblock->pkt->pkt.public_key;
2861
17.4k
  keytimestamp = pk->timestamp;
2862
2863
17.4k
  keyid_from_pk (pk, kid);
2864
17.4k
  pk->main_keyid[0] = kid[0];
2865
17.4k
  pk->main_keyid[1] = kid[1];
2866
2867
17.4k
  if (pk->version < 4)
2868
0
    {
2869
      /* Before v4 the key packet itself contains the expiration date
2870
       * and there was no way to change it, so we start with the one
2871
       * from the key packet.  We do not support v3 keys anymore but
2872
       * we keep the code in case a future key versions introduces a
2873
       * hard expire time again. */
2874
0
      key_expire = pk->max_expiredate;
2875
0
      key_expire_seen = 1;
2876
0
    }
2877
2878
  /* First pass:
2879
   *
2880
   * - Find the latest direct key self-signature.  We assume that the
2881
   *   newest one overrides all others.
2882
   *
2883
   * - Determine whether the key has been revoked.
2884
   *
2885
   * - Gather all revocation keys (unlike other data, we don't just
2886
   *   take them from the latest self-signed packet).
2887
   *
2888
   * - Determine max (sig[...]->version).
2889
   */
2890
2891
  /* Reset this in case this key was already merged. */
2892
17.4k
  xfree (pk->revkey);
2893
17.4k
  pk->revkey = NULL;
2894
17.4k
  pk->numrevkeys = 0;
2895
2896
17.4k
  signode = NULL;
2897
17.4k
  sigdate = 0; /* Helper variable to find the latest signature.  */
2898
2899
  /* According to Section 11.1 of RFC 4880, the public key comes first
2900
   * and is immediately followed by any signature packets that modify
2901
   * it.  */
2902
17.4k
  for (k = keyblock;
2903
39.7k
       k && k->pkt->pkttype != PKT_USER_ID
2904
22.5k
   && k->pkt->pkttype != PKT_ATTRIBUTE
2905
22.5k
   && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2906
22.2k
       k = k->next)
2907
22.2k
    {
2908
22.2k
      if (k->pkt->pkttype == PKT_SIGNATURE)
2909
4.82k
  {
2910
4.82k
    PKT_signature *sig = k->pkt->pkt.signature;
2911
4.82k
    if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2912
1.78k
      { /* Self sig.  */
2913
2914
1.78k
        if (check_key_signature (ctrl, keyblock, k, NULL))
2915
1.77k
    ; /* Signature did not verify.  */
2916
11
        else if (IS_KEY_REV (sig))
2917
11
    {
2918
      /* Key has been revoked - there is no way to
2919
       * override such a revocation, so we theoretically
2920
       * can stop now.  We should not cope with expiration
2921
       * times for revocations here because we have to
2922
       * assume that an attacker can generate all kinds of
2923
       * signatures.  However due to the fact that the key
2924
       * has been revoked it does not harm either and by
2925
       * continuing we gather some more info on that
2926
       * key.  */
2927
11
      *r_revoked = 1;
2928
11
      sig_to_revoke_info (sig, rinfo);
2929
11
    }
2930
0
        else if (IS_KEY_SIG (sig))
2931
0
    {
2932
      /* Add the indicated revocations keys from all
2933
       * signatures not just the latest.  We do this
2934
       * because you need multiple 1F sigs to properly
2935
       * handle revocation keys (PGP does it this way, and
2936
       * a revocation key could be sensitive and hence in
2937
       * a different signature).  */
2938
0
      if (sig->revkey)
2939
0
        {
2940
0
          int i;
2941
2942
0
          pk->revkey =
2943
0
      xrealloc (pk->revkey, sizeof (struct revocation_key) *
2944
0
          (pk->numrevkeys + sig->numrevkeys));
2945
2946
0
          for (i = 0; i < sig->numrevkeys; i++, pk->numrevkeys++)
2947
0
                        {
2948
0
                          pk->revkey[pk->numrevkeys].class
2949
0
                            = sig->revkey[i].class;
2950
0
                          pk->revkey[pk->numrevkeys].algid
2951
0
                            = sig->revkey[i].algid;
2952
0
                          pk->revkey[pk->numrevkeys].fprlen
2953
0
                            = sig->revkey[i].fprlen;
2954
0
                          memcpy (pk->revkey[pk->numrevkeys].fpr,
2955
0
                                  sig->revkey[i].fpr, sig->revkey[i].fprlen);
2956
0
                          memset (pk->revkey[pk->numrevkeys].fpr
2957
0
                                  + sig->revkey[i].fprlen,
2958
0
                                  0,
2959
0
                                  sizeof (sig->revkey[i].fpr)
2960
0
                                  - sig->revkey[i].fprlen);
2961
0
                        }
2962
0
        }
2963
2964
0
      if (sig->timestamp >= sigdate)
2965
0
        { /* This is the latest signature so far.  */
2966
2967
0
          if (sig->flags.expired)
2968
0
      ; /* Signature has expired - ignore it.  */
2969
0
          else
2970
0
      {
2971
0
        sigdate = sig->timestamp;
2972
0
        signode = k;
2973
0
        if (sig->version > sigversion)
2974
0
          sigversion = sig->version;
2975
2976
0
      }
2977
0
        }
2978
0
    }
2979
1.78k
      }
2980
4.82k
  }
2981
22.2k
    }
2982
2983
  /* Remove dupes from the revocation keys.  */
2984
17.4k
  if (pk->revkey)
2985
0
    {
2986
0
      int i, j, x, changed = 0;
2987
2988
0
      for (i = 0; i < pk->numrevkeys; i++)
2989
0
  {
2990
0
    for (j = i + 1; j < pk->numrevkeys; j++)
2991
0
      {
2992
0
        if (memcmp (&pk->revkey[i], &pk->revkey[j],
2993
0
        sizeof (struct revocation_key)) == 0)
2994
0
    {
2995
      /* remove j */
2996
2997
0
      for (x = j; x < pk->numrevkeys - 1; x++)
2998
0
        pk->revkey[x] = pk->revkey[x + 1];
2999
3000
0
      pk->numrevkeys--;
3001
0
      j--;
3002
0
      changed = 1;
3003
0
    }
3004
0
      }
3005
0
  }
3006
3007
0
      if (changed)
3008
0
  pk->revkey = xrealloc (pk->revkey,
3009
0
             pk->numrevkeys *
3010
0
             sizeof (struct revocation_key));
3011
0
    }
3012
3013
  /* SIGNODE is the direct key signature packet (sigclass 0x1f) with
3014
   * the latest creation time.  Extract some information from it.  */
3015
17.4k
  if (signode)
3016
0
    {
3017
      /* Some information from a direct key signature take precedence
3018
       * over the same information given in UID sigs.  */
3019
0
      PKT_signature *sig = signode->pkt->pkt.signature;
3020
0
      const byte *p;
3021
3022
0
      key_usage = parse_key_usage (sig);
3023
3024
0
      p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
3025
0
      if (p && buf32_to_u32 (p))
3026
0
  {
3027
0
    key_expire = keytimestamp + buf32_to_u32 (p);
3028
0
    key_expire_seen = 1;
3029
0
  }
3030
3031
      /* Mark that key as valid: One direct key signature should
3032
       * render a key as valid.  */
3033
0
      pk->flags.valid = 1;
3034
0
    }
3035
3036
  /* Pass 1.5: Look for key revocation signatures that were not made
3037
   * by the key (i.e. did a revocation key issue a revocation for
3038
   * us?).  Only bother to do this if there is a revocation key in the
3039
   * first place and we're not revoked already.  */
3040
3041
17.4k
  if (!*r_revoked && pk->revkey)
3042
0
    for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
3043
0
      {
3044
0
  if (k->pkt->pkttype == PKT_SIGNATURE)
3045
0
    {
3046
0
      PKT_signature *sig = k->pkt->pkt.signature;
3047
3048
0
      if (IS_KEY_REV (sig) &&
3049
0
    (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
3050
0
        {
3051
0
    int rc = check_revocation_keys (ctrl, pk, sig);
3052
0
    if (rc == 0)
3053
0
      {
3054
0
        *r_revoked = 2;
3055
0
        sig_to_revoke_info (sig, rinfo);
3056
        /* Don't continue checking since we can't be any
3057
         * more revoked than this.  */
3058
0
        break;
3059
0
      }
3060
0
    else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
3061
0
      pk->flags.maybe_revoked = 1;
3062
3063
    /* A failure here means the sig did not verify, was
3064
     * not issued by a revocation key, or a revocation
3065
     * key loop was broken.  If a revocation key isn't
3066
     * findable, however, the key might be revoked and
3067
     * we don't know it.  */
3068
3069
    /* Fixme: In the future handle subkey and cert
3070
     * revocations?  PGP doesn't, but it's in 2440.  */
3071
0
        }
3072
0
    }
3073
0
      }
3074
3075
  /* Second pass: Look at the self-signature of all user IDs.  */
3076
3077
  /* According to RFC 4880 section 11.1, user id and attribute packets
3078
   * are in the second section, after the public key packet and before
3079
   * the subkey packets.  */
3080
17.4k
  signode = uidnode = NULL;
3081
17.4k
  sigdate = 0; /* Helper variable to find the latest signature in one UID. */
3082
55.6k
  for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3083
38.1k
    {
3084
38.1k
      if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
3085
10.1k
  { /* New user id packet.  */
3086
3087
          /* Apply the data from the most recent self-signed packet to
3088
     * the preceding user id packet.  */
3089
10.1k
    if (uidnode && signode)
3090
142
      {
3091
142
        fixup_uidnode (uidnode, signode, keytimestamp);
3092
142
        pk->flags.valid = 1;
3093
142
      }
3094
3095
    /* Clear SIGNODE.  The only relevant self-signed data for
3096
     * UIDNODE follows it.  */
3097
10.1k
    if (k->pkt->pkttype == PKT_USER_ID)
3098
10.1k
      uidnode = k;
3099
0
    else
3100
0
      uidnode = NULL;
3101
3102
10.1k
    signode = NULL;
3103
10.1k
    sigdate = 0;
3104
10.1k
  }
3105
28.0k
      else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
3106
5.64k
  {
3107
5.64k
    PKT_signature *sig = k->pkt->pkt.signature;
3108
5.64k
    if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
3109
3.06k
      {
3110
3.06k
        if (check_key_signature (ctrl, keyblock, k, NULL))
3111
1.75k
    ;    /* signature did not verify */
3112
1.30k
        else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
3113
1.25k
           && sig->timestamp >= sigdate)
3114
1.25k
    {
3115
      /* Note: we allow invalidation of cert revocations
3116
       * by a newer signature.  An attacker can't use this
3117
       * because a key should be revoked with a key revocation.
3118
       * The reason why we have to allow for that is that at
3119
       * one time an email address may become invalid but later
3120
       * the same email address may become valid again (hired,
3121
       * fired, hired again).  */
3122
3123
1.25k
      sigdate = sig->timestamp;
3124
1.25k
      signode = k;
3125
1.25k
      signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
3126
1.25k
      if (sig->version > sigversion)
3127
1.13k
        sigversion = sig->version;
3128
1.25k
    }
3129
3.06k
      }
3130
5.64k
  }
3131
38.1k
    }
3132
17.4k
  if (uidnode && signode)
3133
1.11k
    {
3134
1.11k
      fixup_uidnode (uidnode, signode, keytimestamp);
3135
1.11k
      pk->flags.valid = 1;
3136
1.11k
    }
3137
3138
  /* If the key isn't valid yet, and we have
3139
   * --allow-non-selfsigned-uid set, then force it valid. */
3140
17.4k
  if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
3141
0
    {
3142
0
      if (opt.verbose)
3143
0
  log_info (_("Invalid key %s made valid by"
3144
0
        " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
3145
0
      pk->flags.valid = 1;
3146
0
    }
3147
3148
  /* The key STILL isn't valid, so try and find an ultimately
3149
   * trusted signature. */
3150
17.4k
  if (!pk->flags.valid)
3151
16.3k
    {
3152
16.3k
      uidnode = NULL;
3153
3154
49.8k
      for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3155
33.5k
     k = k->next)
3156
33.5k
  {
3157
33.5k
    if (k->pkt->pkttype == PKT_USER_ID)
3158
8.47k
      uidnode = k;
3159
25.0k
    else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
3160
3.88k
      {
3161
3.88k
        PKT_signature *sig = k->pkt->pkt.signature;
3162
3163
3.88k
        if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
3164
2.57k
    {
3165
2.57k
      PKT_public_key *ultimate_pk;
3166
3167
2.57k
      ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
3168
3169
      /* We don't want to use the full get_pubkey to avoid
3170
       * infinite recursion in certain cases.  There is no
3171
       * reason to check that an ultimately trusted key is
3172
       * still valid - if it has been revoked the user
3173
       * should also remove the ultimate trust flag.  */
3174
2.57k
      if (get_pubkey_fast (ctrl, ultimate_pk, sig->keyid) == 0
3175
0
          && check_key_signature2 (ctrl,
3176
0
                                               keyblock, k, ultimate_pk,
3177
0
                 NULL, NULL, NULL, NULL) == 0
3178
0
          && get_ownertrust (ctrl, ultimate_pk) == TRUST_ULTIMATE)
3179
0
        {
3180
0
          free_public_key (ultimate_pk);
3181
0
          pk->flags.valid = 1;
3182
0
          break;
3183
0
        }
3184
3185
2.57k
      free_public_key (ultimate_pk);
3186
2.57k
    }
3187
3.88k
      }
3188
33.5k
  }
3189
16.3k
    }
3190
3191
  /* Record the highest selfsig version so we know if this is a v3 key
3192
   * through and through, or a v3 key with a v4 selfsig somewhere.
3193
   * This is useful in a few places to know if the key must be treated
3194
   * as PGP2-style or OpenPGP-style.  Note that a selfsig revocation
3195
   * with a higher version number will also raise this value.  This is
3196
   * okay since such a revocation must be issued by the user (i.e. it
3197
   * cannot be issued by someone else to modify the key behavior.) */
3198
3199
17.4k
  pk->selfsigversion = sigversion;
3200
3201
  /* Now that we had a look at all user IDs we can now get some
3202
   * information from those user IDs.  */
3203
3204
17.4k
  if (!key_usage)
3205
17.4k
    {
3206
      /* Find the latest user ID with key flags set. */
3207
17.4k
      uiddate = 0; /* Helper to find the latest user ID.  */
3208
55.6k
      for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3209
38.1k
     k = k->next)
3210
38.1k
  {
3211
38.1k
    if (k->pkt->pkttype == PKT_USER_ID)
3212
10.1k
      {
3213
10.1k
        PKT_user_id *uid = k->pkt->pkt.user_id;
3214
3215
10.1k
        if (uid->help_key_usage
3216
281
                  && (uid->created > uiddate || (!uid->created && !uiddate)))
3217
281
    {
3218
281
      key_usage = uid->help_key_usage;
3219
281
      uiddate = uid->created;
3220
281
    }
3221
10.1k
      }
3222
38.1k
  }
3223
17.4k
    }
3224
3225
17.4k
  if (!key_usage)
3226
17.1k
    {
3227
      /* No key flags at all: get it from the algo.  */
3228
17.1k
      key_usage = (openpgp_pk_algo_usage (pk->pubkey_algo)
3229
17.1k
                   & PUBKEY_USAGE_BASIC_MASK);
3230
17.1k
    }
3231
281
  else
3232
281
    {
3233
      /* Check that the usage matches the usage as given by the algo.  */
3234
281
      int x = openpgp_pk_algo_usage (pk->pubkey_algo);
3235
281
      if (x) /* Mask it down to the actual allowed usage.  */
3236
281
  key_usage &= (x | PUBKEY_USAGE_GROUP);
3237
281
    }
3238
3239
  /* Whatever happens, it's a primary key, so it can certify. */
3240
17.4k
  pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
3241
3242
17.4k
  if (!key_expire_seen)
3243
17.4k
    {
3244
      /* Find the latest valid user ID with a key expiration set.
3245
       * This may be a different one than from usage computation above
3246
       * because some user IDs may have no expiration date set.  */
3247
17.4k
      uiddate = 0;
3248
55.6k
      for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3249
38.1k
     k = k->next)
3250
38.1k
  {
3251
38.1k
    if (k->pkt->pkttype == PKT_USER_ID)
3252
10.1k
      {
3253
10.1k
        PKT_user_id *uid = k->pkt->pkt.user_id;
3254
10.1k
        if (uid->help_key_expire
3255
101
                  && (uid->created > uiddate || (!uid->created && !uiddate)))
3256
101
    {
3257
101
      key_expire = uid->help_key_expire;
3258
101
      uiddate = uid->created;
3259
101
    }
3260
10.1k
      }
3261
38.1k
  }
3262
17.4k
    }
3263
3264
  /* Currently only the not anymore supported v3 keys have a maximum
3265
   * expiration date, but future key versions may get this feature again. */
3266
17.4k
  if (key_expire == 0
3267
101
      || (pk->max_expiredate && key_expire > pk->max_expiredate))
3268
17.3k
    key_expire = pk->max_expiredate;
3269
3270
17.4k
  pk->has_expired = key_expire >= curtime ? 0 : key_expire;
3271
17.4k
  pk->expiredate = key_expire;
3272
3273
  /* Fixme: we should see how to get rid of the expiretime fields but
3274
   * this needs changes at other places too.  */
3275
3276
  /* And now find the real primary user ID and delete all others.  */
3277
17.4k
  uiddate = uiddate2 = 0;
3278
17.4k
  uidnode = uidnode2 = NULL;
3279
55.6k
  for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3280
38.1k
    {
3281
38.1k
      if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
3282
8.99k
  {
3283
8.99k
    PKT_user_id *uid = k->pkt->pkt.user_id;
3284
8.99k
    if (uid->flags.primary)
3285
0
      {
3286
0
        if (uid->created > uiddate)
3287
0
    {
3288
0
      uiddate = uid->created;
3289
0
      uidnode = k;
3290
0
    }
3291
0
        else if (uid->created == uiddate && uidnode)
3292
0
    {
3293
      /* The dates are equal, so we need to do a different
3294
       * (and arbitrary) comparison.  This should rarely,
3295
       * if ever, happen.  It's good to try and guarantee
3296
       * that two different GnuPG users with two different
3297
       * keyrings at least pick the same primary.  */
3298
0
      if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
3299
0
        uidnode = k;
3300
0
    }
3301
0
      }
3302
8.99k
    else
3303
8.99k
      {
3304
8.99k
        if (uid->created > uiddate2)
3305
1.20k
    {
3306
1.20k
      uiddate2 = uid->created;
3307
1.20k
      uidnode2 = k;
3308
1.20k
    }
3309
7.78k
        else if (uid->created == uiddate2 && uidnode2)
3310
9
    {
3311
9
      if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
3312
0
        uidnode2 = k;
3313
9
    }
3314
8.99k
      }
3315
8.99k
  }
3316
38.1k
    }
3317
17.4k
  if (uidnode)
3318
0
    {
3319
0
      for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3320
0
     k = k->next)
3321
0
  {
3322
0
    if (k->pkt->pkttype == PKT_USER_ID &&
3323
0
        !k->pkt->pkt.user_id->attrib_data)
3324
0
      {
3325
0
        PKT_user_id *uid = k->pkt->pkt.user_id;
3326
0
        if (k != uidnode)
3327
0
    uid->flags.primary = 0;
3328
0
      }
3329
0
  }
3330
0
    }
3331
17.4k
  else if (uidnode2)
3332
1.09k
    {
3333
      /* None is flagged primary - use the latest user ID we have,
3334
       * and disambiguate with the arbitrary packet comparison. */
3335
1.09k
      uidnode2->pkt->pkt.user_id->flags.primary = 1;
3336
1.09k
    }
3337
16.3k
  else
3338
16.3k
    {
3339
      /* None of our uids were self-signed, so pick the one that
3340
       * sorts first to be the primary.  This is the best we can do
3341
       * here since there are no self sigs to date the uids. */
3342
3343
16.3k
      uidnode = NULL;
3344
3345
49.9k
      for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3346
33.6k
     k = k->next)
3347
33.6k
  {
3348
33.6k
    if (k->pkt->pkttype == PKT_USER_ID
3349
8.51k
        && !k->pkt->pkt.user_id->attrib_data)
3350
7.40k
      {
3351
7.40k
        if (!uidnode)
3352
3.88k
    {
3353
3.88k
      uidnode = k;
3354
3.88k
      uidnode->pkt->pkt.user_id->flags.primary = 1;
3355
3.88k
      continue;
3356
3.88k
    }
3357
3.51k
        else
3358
3.51k
    {
3359
3.51k
      if (cmp_user_ids (k->pkt->pkt.user_id,
3360
3.51k
            uidnode->pkt->pkt.user_id) > 0)
3361
132
        {
3362
132
          uidnode->pkt->pkt.user_id->flags.primary = 0;
3363
132
          uidnode = k;
3364
132
          uidnode->pkt->pkt.user_id->flags.primary = 1;
3365
132
        }
3366
3.38k
      else
3367
3.38k
                    {
3368
                      /* just to be safe: */
3369
3.38k
                      k->pkt->pkt.user_id->flags.primary = 0;
3370
3.38k
                    }
3371
3.51k
    }
3372
7.40k
      }
3373
33.6k
  }
3374
16.3k
    }
3375
17.4k
}
3376
3377
3378
/* Convert a buffer to a signature.  Useful for 0x19 embedded sigs.
3379
 * Caller must free the signature when they are done. */
3380
static PKT_signature *
3381
buf_to_sig (const byte * buf, size_t len)
3382
124
{
3383
124
  PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
3384
124
  IOBUF iobuf = iobuf_temp_with_content (buf, len);
3385
124
  int save_mode = set_packet_list_mode (0);
3386
3387
124
  if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
3388
4
    {
3389
4
      free_seckey_enc (sig);
3390
4
      sig = NULL;
3391
4
    }
3392
3393
124
  set_packet_list_mode (save_mode);
3394
124
  iobuf_close (iobuf);
3395
3396
124
  return sig;
3397
124
}
3398
3399
3400
/* Use the self-signed data to fill in various fields in subkeys.
3401
 *
3402
 * KEYBLOCK is the whole keyblock.  SUBNODE is the subkey to fill in.
3403
 *
3404
 * Sets the following fields on the subkey:
3405
 *
3406
 *   main_keyid
3407
 *   flags.valid        if the subkey has a valid self-sig binding
3408
 *   flags.revoked
3409
 *   flags.backsig
3410
 *   pubkey_usage
3411
 *   has_expired
3412
 *   expired_date
3413
 *
3414
 * On this subkey's most recent valid self-signed packet, the
3415
 * following field is set:
3416
 *
3417
 *   flags.chosen_selfsig
3418
 */
3419
static void
3420
merge_selfsigs_subkey (ctrl_t ctrl, kbnode_t keyblock, kbnode_t subnode)
3421
3.54k
{
3422
3.54k
  PKT_public_key *mainpk = NULL, *subpk = NULL;
3423
3.54k
  PKT_signature *sig;
3424
3.54k
  KBNODE k;
3425
3.54k
  u32 mainkid[2];
3426
3.54k
  u32 sigdate = 0;
3427
3.54k
  KBNODE signode;
3428
3.54k
  u32 curtime = make_timestamp ();
3429
3.54k
  unsigned int key_usage = 0;
3430
3.54k
  u32 keytimestamp = 0;
3431
3.54k
  u32 key_expire = 0;
3432
3.54k
  const byte *p;
3433
3434
3.54k
  if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3435
0
    BUG ();
3436
3.54k
  mainpk = keyblock->pkt->pkt.public_key;
3437
3.54k
  if (mainpk->version < 4)
3438
0
    return;/* (actually this should never happen) */
3439
3.54k
  keyid_from_pk (mainpk, mainkid);
3440
3.54k
  subpk = subnode->pkt->pkt.public_key;
3441
3.54k
  keytimestamp = subpk->timestamp;
3442
3443
3.54k
  subpk->flags.valid = 0;
3444
3.54k
  subpk->flags.exact = 0;
3445
3.54k
  subpk->main_keyid[0] = mainpk->main_keyid[0];
3446
3.54k
  subpk->main_keyid[1] = mainpk->main_keyid[1];
3447
3448
  /* Find the latest key binding self-signature.  */
3449
3.54k
  signode = NULL;
3450
3.54k
  sigdate = 0; /* Helper to find the latest signature.  */
3451
8.37k
  for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3452
4.83k
       k = k->next)
3453
4.83k
    {
3454
4.83k
      if (k->pkt->pkttype == PKT_SIGNATURE)
3455
2.83k
  {
3456
2.83k
    sig = k->pkt->pkt.signature;
3457
2.83k
    if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
3458
1.94k
      {
3459
1.94k
        if (check_key_signature (ctrl, keyblock, k, NULL))
3460
1.10k
    ; /* Signature did not verify.  */
3461
834
        else if (IS_SUBKEY_REV (sig))
3462
11
    {
3463
      /* Note that this means that the date on a
3464
       * revocation sig does not matter - even if the
3465
       * binding sig is dated after the revocation sig,
3466
       * the subkey is still marked as revoked.  This
3467
       * seems ok, as it is just as easy to make new
3468
       * subkeys rather than re-sign old ones as the
3469
       * problem is in the distribution.  Plus, PGP (7)
3470
       * does this the same way.  */
3471
11
      subpk->flags.revoked = 1;
3472
11
      sig_to_revoke_info (sig, &subpk->revoked);
3473
      /* Although we could stop now, we continue to
3474
       * figure out other information like the old expiration
3475
       * time.  */
3476
11
    }
3477
823
        else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
3478
742
    {
3479
742
      if (sig->flags.expired)
3480
0
        ; /* Signature has expired - ignore it.  */
3481
742
      else
3482
742
        {
3483
742
          sigdate = sig->timestamp;
3484
742
          signode = k;
3485
742
          signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
3486
742
        }
3487
742
    }
3488
1.94k
      }
3489
2.83k
  }
3490
4.83k
    }
3491
3492
  /* No valid key binding.  */
3493
3.54k
  if (!signode)
3494
2.79k
    return;
3495
3496
742
  sig = signode->pkt->pkt.signature;
3497
742
  sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later.  */
3498
3499
742
  key_usage = parse_key_usage (sig);
3500
742
  if (!key_usage)
3501
533
    {
3502
      /* No key flags at all: get it from the algo.  */
3503
533
      key_usage = (openpgp_pk_algo_usage (subpk->pubkey_algo)
3504
533
                   & PUBKEY_USAGE_BASIC_MASK);
3505
533
    }
3506
209
  else
3507
209
    {
3508
      /* Check that the usage matches the usage as given by the algo.  */
3509
209
      int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
3510
209
      if (x) /* Mask it down to the actual allowed usage.  */
3511
209
  key_usage &= (x | PUBKEY_USAGE_GROUP);
3512
209
    }
3513
3514
742
  subpk->pubkey_usage = key_usage;
3515
3516
742
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL);
3517
742
  if (p && buf32_to_u32 (p))
3518
47
    key_expire = keytimestamp + buf32_to_u32 (p);
3519
695
  else
3520
695
    key_expire = 0;
3521
3522
742
  subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
3523
742
  subpk->expiredate = key_expire;
3524
3525
  /* Algo doesn't exist.  */
3526
742
  if (openpgp_pk_test_algo (subpk->pubkey_algo))
3527
0
    return;
3528
3529
742
  subpk->flags.valid = 1;
3530
3531
  /* Find the most recent 0x19 embedded signature on our self-sig. */
3532
742
  if (!subpk->flags.backsig)
3533
742
    {
3534
742
      int seq = 0;
3535
742
      size_t n;
3536
742
      PKT_signature *backsig = NULL;
3537
3538
742
      sigdate = 0;
3539
3540
      /* We do this while() since there may be other embedded
3541
       * signatures in the future.  We only want 0x19 here. */
3542
3543
742
      while ((p = enum_sig_subpkt (sig, 1, SIGSUBPKT_SIGNATURE,
3544
742
                                   &n, &seq, NULL)))
3545
0
        if (n > 3
3546
0
            && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)
3547
0
                || (p[0] == 5 && p[1] == 0x19)))
3548
0
          {
3549
0
      PKT_signature *tempsig = buf_to_sig (p, n);
3550
0
      if (tempsig)
3551
0
        {
3552
0
    if (tempsig->timestamp > sigdate)
3553
0
      {
3554
0
        if (backsig)
3555
0
          free_seckey_enc (backsig);
3556
3557
0
        backsig = tempsig;
3558
0
        sigdate = backsig->timestamp;
3559
0
      }
3560
0
    else
3561
0
      free_seckey_enc (tempsig);
3562
0
        }
3563
0
    }
3564
3565
742
      seq = 0;
3566
3567
      /* It is safe to have this in the unhashed area since the 0x19
3568
       * is located on the selfsig for convenience, not security. */
3569
866
      while ((p = enum_sig_subpkt (sig, 0, SIGSUBPKT_SIGNATURE,
3570
866
           &n, &seq, NULL)))
3571
124
        if (n > 3
3572
124
            && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)
3573
0
                 || (p[0] == 5 && p[1] == 0x19)))
3574
124
          {
3575
124
      PKT_signature *tempsig = buf_to_sig (p, n);
3576
124
      if (tempsig)
3577
120
        {
3578
120
    if (tempsig->timestamp > sigdate)
3579
120
      {
3580
120
        if (backsig)
3581
0
          free_seckey_enc (backsig);
3582
3583
120
        backsig = tempsig;
3584
120
        sigdate = backsig->timestamp;
3585
120
      }
3586
0
    else
3587
0
      free_seckey_enc (tempsig);
3588
120
        }
3589
124
    }
3590
3591
742
      if (backsig)
3592
120
  {
3593
    /* At this point, backsig contains the most recent 0x19 sig.
3594
     * Let's see if it is good. */
3595
3596
    /* 2==valid, 1==invalid, 0==didn't check */
3597
120
    if (check_backsig (mainpk, subpk, backsig) == 0)
3598
72
      subpk->flags.backsig = 2;
3599
48
    else
3600
48
      subpk->flags.backsig = 1;
3601
3602
120
    free_seckey_enc (backsig);
3603
120
  }
3604
742
    }
3605
742
}
3606
3607
3608
/* Merge information from the self-signatures with the public key,
3609
 * subkeys and user ids to make using them more easy.
3610
 *
3611
 * See documentation for merge_selfsigs_main, merge_selfsigs_subkey
3612
 * and fixup_uidnode for exactly which fields are updated.  */
3613
static void
3614
merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock)
3615
17.4k
{
3616
17.4k
  KBNODE k;
3617
17.4k
  int revoked;
3618
17.4k
  struct revoke_info rinfo = { 0 };
3619
17.4k
  PKT_public_key *main_pk;
3620
17.4k
  prefitem_t *prefs;
3621
17.4k
  unsigned int mdc_feature;
3622
17.4k
  unsigned int aead_feature;
3623
3624
17.4k
  if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
3625
0
    {
3626
0
      if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
3627
0
  {
3628
0
    log_error ("expected public key but found secret key "
3629
0
         "- must stop\n");
3630
    /* We better exit here because a public key is expected at
3631
     * other places too.  FIXME: Figure this out earlier and
3632
     * don't get to here at all */
3633
0
    g10_exit (1);
3634
0
  }
3635
0
      BUG ();
3636
0
    }
3637
3638
17.4k
  merge_selfsigs_main (ctrl, keyblock, &revoked, &rinfo);
3639
3640
  /* Now merge in the data from each of the subkeys.  */
3641
63.9k
  for (k = keyblock; k; k = k->next)
3642
46.5k
    {
3643
46.5k
      if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3644
3.54k
  {
3645
3.54k
    merge_selfsigs_subkey (ctrl, keyblock, k);
3646
3.54k
  }
3647
46.5k
    }
3648
3649
17.4k
  main_pk = keyblock->pkt->pkt.public_key;
3650
17.4k
  if (revoked || main_pk->has_expired || !main_pk->flags.valid)
3651
16.4k
    {
3652
      /* If the primary key is revoked, expired, or invalid we
3653
       * better set the appropriate flags on that key and all
3654
       * subkeys.  */
3655
57.0k
      for (k = keyblock; k; k = k->next)
3656
40.6k
  {
3657
40.6k
    if (k->pkt->pkttype == PKT_PUBLIC_KEY
3658
24.2k
        || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3659
19.2k
      {
3660
19.2k
        PKT_public_key *pk = k->pkt->pkt.public_key;
3661
3662
19.2k
        if (!main_pk->flags.valid)
3663
19.0k
    pk->flags.valid = 0;
3664
3665
19.2k
        if (revoked && !pk->flags.revoked)
3666
11
    {
3667
                  /* Copy RINFO reason part only the first time
3668
                   * because we don't want to propagate the reason to
3669
                   * the subkeys.  This assumes that we get the public
3670
                   * key first.  */
3671
11
      pk->flags.revoked = revoked;
3672
11
                  memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
3673
11
                  if (rinfo.got_reason)
3674
0
                    {
3675
0
                      rinfo.got_reason = 0;
3676
0
                      rinfo.reason_code = 0;
3677
0
                      rinfo.reason_comment = NULL;  /*(owner is pk->revoked)*/
3678
0
                      rinfo.reason_comment_len = 0;
3679
0
                    }
3680
11
    }
3681
3682
19.2k
        if (main_pk->has_expired)
3683
152
    {
3684
152
      pk->has_expired = main_pk->has_expired;
3685
152
      if (!pk->expiredate || pk->expiredate > main_pk->expiredate)
3686
51
        pk->expiredate = main_pk->expiredate;
3687
152
    }
3688
19.2k
      }
3689
40.6k
  }
3690
16.4k
      goto leave;
3691
16.4k
    }
3692
3693
  /* Set the preference list of all keys to those of the primary real
3694
   * user ID.  Note: we use these preferences when we don't know by
3695
   * which user ID the key has been selected.
3696
   * fixme: we should keep atoms of commonly used preferences or
3697
   * use reference counting to optimize the preference lists storage.
3698
   * FIXME: it might be better to use the intersection of
3699
   * all preferences.
3700
   * Do a similar thing for the MDC feature flag.  */
3701
1.02k
  prefs = NULL;
3702
1.02k
  mdc_feature = aead_feature = 0;
3703
2.31k
  for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3704
2.31k
    {
3705
2.31k
      if (k->pkt->pkttype == PKT_USER_ID
3706
1.15k
    && !k->pkt->pkt.user_id->attrib_data
3707
1.15k
    && k->pkt->pkt.user_id->flags.primary)
3708
1.02k
  {
3709
1.02k
    prefs = k->pkt->pkt.user_id->prefs;
3710
1.02k
    mdc_feature = k->pkt->pkt.user_id->flags.mdc;
3711
1.02k
    aead_feature = k->pkt->pkt.user_id->flags.aead;
3712
1.02k
    break;
3713
1.02k
  }
3714
2.31k
    }
3715
6.92k
  for (k = keyblock; k; k = k->next)
3716
5.89k
    {
3717
5.89k
      if (k->pkt->pkttype == PKT_PUBLIC_KEY
3718
4.86k
    || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3719
1.77k
  {
3720
1.77k
    PKT_public_key *pk = k->pkt->pkt.public_key;
3721
1.77k
    if (pk->prefs)
3722
0
      xfree (pk->prefs);
3723
1.77k
    pk->prefs = copy_prefs (prefs);
3724
1.77k
    pk->flags.mdc = mdc_feature;
3725
1.77k
    pk->flags.aead = aead_feature;
3726
1.77k
  }
3727
5.89k
    }
3728
3729
17.4k
 leave:
3730
17.4k
  xfree (rinfo.reason_comment);
3731
17.4k
}
3732
3733
3734

3735
/* See whether the key satisfies any additional requirements specified
3736
 * in CTX.  If so, return the node of an appropriate key or subkey.
3737
 * Otherwise, return NULL if there was no appropriate key.
3738
 *
3739
 * Note that we do not return a reference, i.e. the result must not be
3740
 * freed using 'release_kbnode'.
3741
 *
3742
 * In case the primary key is not required, select a suitable subkey.
3743
 * We need the primary key if PUBKEY_USAGE_CERT is set in REQ_USAGE or
3744
 * we are in PGP7 mode and PUBKEY_USAGE_SIG is set in
3745
 * REQ_USAGE.
3746
 *
3747
 * If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
3748
 * are set in REQ_USAGE, we filter by the key's function.  Concretely,
3749
 * if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then we only
3750
 * return a key if it is (at least) either a signing or a
3751
 * certification key.
3752
 *
3753
 * If REQ_USAGE is set, then we reject any keys that are not good
3754
 * (i.e., valid, not revoked, not expired, etc.).  This allows the
3755
 * getkey functions to be used for plain key listings.
3756
 *
3757
 * Sets the matched key's user id field (pk->user_id) to the user id
3758
 * that matched the low-level search criteria or NULL.
3759
 *
3760
 * If R_FLAGS is not NULL set certain flags for more detailed error
3761
 * reporting.  Used flags are:
3762
 *
3763
 * - LOOKUP_ALL_SUBKEYS_EXPIRED :: All Subkeys are expired or have
3764
 *                                 been revoked.
3765
 * - LOOKUP_NOT_SELECTED :: No suitable key found
3766
 *
3767
 * This function needs to handle several different cases:
3768
 *
3769
 *  1. No requested usage and no primary key requested
3770
 *     Examples for this case are that we have a keyID to be used
3771
 *     for decryption or verification.
3772
 *  2. No usage but primary key requested
3773
 *     This is the case for all functions which work on an
3774
 *     entire keyblock, e.g. for editing or listing
3775
 *  3. Usage and primary key requested
3776
 *     FIXME
3777
 *  4. Usage but no primary key requested
3778
 *     FIXME
3779
 *
3780
 */
3781
static kbnode_t
3782
finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact,
3783
               int want_secret, int allow_adsk, unsigned int *r_flags)
3784
0
{
3785
0
  kbnode_t k;
3786
3787
  /* If WANT_EXACT is set, the key or subkey that actually matched the
3788
     low-level search criteria.  */
3789
0
  kbnode_t foundk = NULL;
3790
  /* The user id (if any) that matched the low-level search criteria.  */
3791
0
  PKT_user_id *foundu = NULL;
3792
3793
0
  u32 latest_date;
3794
0
  kbnode_t latest_key;
3795
0
  PKT_public_key *pk;
3796
0
  int req_prim;
3797
0
  int diag_exactfound = 0;
3798
0
  int verify_mode = 0;
3799
0
  u32 curtime = make_timestamp ();
3800
3801
0
  if (r_flags)
3802
0
    *r_flags = 0;
3803
3804
3805
  /* The verify mode is used to change the behaviour so that we can
3806
   * return an expired or revoked key for signature verification.  */
3807
0
  verify_mode = ((req_usage & PUBKEY_USAGE_VERIFY)
3808
0
                 && (req_usage & (PUBKEY_USAGE_CERT|PUBKEY_USAGE_SIG)));
3809
3810
0
#define USAGE_MASK  (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
3811
0
  req_usage &= USAGE_MASK;
3812
  /* In allow ADSK mode make sure both encryption bits are set.  */
3813
0
  if (allow_adsk && (req_usage & PUBKEY_USAGE_XENC_MASK))
3814
0
    req_usage |= PUBKEY_USAGE_XENC_MASK;
3815
3816
  /* Request the primary if we're certifying another key, and also if
3817
   * signing data while --pgp7 is on since pgp 7 do
3818
   * not understand signatures made by a signing subkey.  PGP 8 does. */
3819
0
  req_prim = ((req_usage & PUBKEY_USAGE_CERT)
3820
0
              || (PGP7 && (req_usage & PUBKEY_USAGE_SIG)));
3821
3822
3823
0
  log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
3824
3825
  /* For an exact match mark the primary or subkey that matched the
3826
   * low-level search criteria.  Use this loop also to sort our keys
3827
   * found using an ADSK fingerprint.  */
3828
0
  for (k = keyblock; k; k = k->next)
3829
0
    {
3830
0
      if ((k->flag & 1) && (k->pkt->pkttype == PKT_PUBLIC_KEY
3831
0
                            || k->pkt->pkttype == PKT_PUBLIC_SUBKEY))
3832
0
        {
3833
0
          if (want_exact)
3834
0
            {
3835
0
              foundk = k;
3836
0
              pk = k->pkt->pkt.public_key;
3837
0
              pk->flags.exact = 1;
3838
0
              diag_exactfound = 1;
3839
0
              break;
3840
0
            }
3841
0
          else if (!allow_adsk && (k->pkt->pkt.public_key->pubkey_usage
3842
0
                                   == PUBKEY_USAGE_RENC))
3843
0
            {
3844
0
              if (DBG_LOOKUP)
3845
0
                log_debug ("finish_lookup: found via ADSK - not selected\n");
3846
0
              if (r_flags)
3847
0
                *r_flags |= LOOKUP_NOT_SELECTED;
3848
0
              return NULL; /* Not found.  */
3849
0
            }
3850
0
        }
3851
0
    }
3852
3853
  /* Get the user id that matched that low-level search criteria.  */
3854
0
  for (k = keyblock; k; k = k->next)
3855
0
    {
3856
0
      if ((k->flag & 2))
3857
0
  {
3858
0
    log_assert (k->pkt->pkttype == PKT_USER_ID);
3859
0
    foundu = k->pkt->pkt.user_id;
3860
0
    break;
3861
0
  }
3862
0
    }
3863
3864
0
  if (DBG_LOOKUP)
3865
0
    log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x%s)\n",
3866
0
         (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
3867
0
         foundk ? "one" : "all", req_usage, verify_mode? ",verify":"");
3868
0
  if (diag_exactfound && DBG_LOOKUP)
3869
0
    log_debug ("\texact search requested and found\n");
3870
3871
0
  if (!req_usage)
3872
0
    {
3873
0
      latest_key = foundk ? foundk : keyblock;
3874
0
      if (DBG_LOOKUP)
3875
0
        log_debug ("\tno usage requested - accepting key\n");
3876
0
      goto found;
3877
0
    }
3878
3879
0
  latest_date = 0;
3880
0
  latest_key = NULL;
3881
  /* Set LATEST_KEY to the latest (the one with the most recent
3882
   * timestamp) good (valid, not revoked, not expired, etc.) subkey.
3883
   *
3884
   * Don't bother if we are only looking for a primary key or we need
3885
   * an exact match and the exact match is not a subkey.  */
3886
0
  if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
3887
0
    ;
3888
0
  else
3889
0
    {
3890
0
      kbnode_t nextk;
3891
0
      int n_subkeys = 0;
3892
0
      int n_revoked_or_expired = 0;
3893
0
      int last_secret_key_avail = 0;
3894
3895
      /* Either start a loop or check just this one subkey.  */
3896
0
      for (k = foundk ? foundk : keyblock; k; k = nextk)
3897
0
  {
3898
0
    if (foundk)
3899
0
            {
3900
              /* If FOUNDK is not NULL, then only consider that exact
3901
                 key, i.e., don't iterate.  */
3902
0
              nextk = NULL;
3903
0
            }
3904
0
    else
3905
0
      nextk = k->next;
3906
3907
0
    if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3908
0
      continue;
3909
3910
0
    pk = k->pkt->pkt.public_key;
3911
0
    if (DBG_LOOKUP)
3912
0
      log_debug ("\tchecking subkey %08lX\n",
3913
0
           (ulong) keyid_from_pk (pk, NULL));
3914
3915
0
    if (!pk->flags.valid)
3916
0
      {
3917
0
        if (DBG_LOOKUP)
3918
0
    log_debug ("\tsubkey not valid\n");
3919
0
        continue;
3920
0
      }
3921
0
    if (!((pk->pubkey_usage & (USAGE_MASK | PUBKEY_USAGE_RENC))
3922
0
                & req_usage))
3923
0
      {
3924
0
        if (DBG_LOOKUP)
3925
0
    log_debug ("\tusage does not match: want=%x have=%x\n",
3926
0
         req_usage, pk->pubkey_usage);
3927
0
        continue;
3928
0
      }
3929
0
    if (!verify_mode
3930
0
              && opt.flags.disable_pqc_encryption
3931
0
              && pk->pubkey_algo == PUBKEY_ALGO_KYBER)
3932
0
      {
3933
0
        if (DBG_LOOKUP)
3934
0
                log_debug ("\tsubkey skipped due to option %s\n",
3935
0
                           "--disable-pqc-encryption");
3936
0
        continue;
3937
0
      }
3938
3939
0
          n_subkeys++;
3940
0
    if (!verify_mode && pk->flags.revoked)
3941
0
      {
3942
0
        if (DBG_LOOKUP)
3943
0
    log_debug ("\tsubkey has been revoked\n");
3944
0
              n_revoked_or_expired++;
3945
0
        continue;
3946
0
      }
3947
0
    if (!verify_mode && pk->has_expired && !opt.ignore_expiration)
3948
0
      {
3949
0
        if (DBG_LOOKUP)
3950
0
    log_debug ("\tsubkey has expired\n");
3951
0
              n_revoked_or_expired++;
3952
0
        continue;
3953
0
      }
3954
0
    if (!verify_mode && pk->timestamp > curtime && !opt.ignore_valid_from)
3955
0
      {
3956
0
        if (DBG_LOOKUP)
3957
0
    log_debug ("\tsubkey not yet valid\n");
3958
0
        continue;
3959
0
      }
3960
3961
0
          if (!verify_mode
3962
0
              && opt.flags.require_pqc_encryption
3963
0
              && (req_usage & PUBKEY_USAGE_XENC_MASK)
3964
0
              && pk->pubkey_algo != PUBKEY_ALGO_KYBER)
3965
0
            {
3966
0
        if (DBG_LOOKUP)
3967
0
    log_debug ("\tsubkey is not quantum-resistant\n");
3968
0
              continue;
3969
0
            }
3970
3971
3972
0
          if (!verify_mode && want_secret)
3973
0
            {
3974
0
              int secret_key_avail = agent_probe_secret_key (NULL, pk);
3975
3976
0
              if (!secret_key_avail)
3977
0
                {
3978
0
                  if (DBG_LOOKUP)
3979
0
                    log_debug ("\tno secret key\n");
3980
0
                  continue;
3981
0
                }
3982
3983
0
              if (secret_key_avail < last_secret_key_avail)
3984
0
                {
3985
0
                  if (DBG_LOOKUP)
3986
0
                    log_debug ("\tskipping secret key with lower avail\n");
3987
0
                  continue;
3988
0
                }
3989
3990
0
              if (secret_key_avail > last_secret_key_avail)
3991
0
                {
3992
                  /* Use this key.  */
3993
0
                  last_secret_key_avail = secret_key_avail;
3994
0
                  latest_date = 0;
3995
0
                }
3996
0
            }
3997
3998
0
    if (DBG_LOOKUP)
3999
0
      log_debug ("\tsubkey might be fine%s\n",
4000
0
                       verify_mode? " for verification":"");
4001
    /* In case a key has a timestamp of 0 set, we make sure
4002
       that it is used.  A better change would be to compare
4003
       ">=" but that might also change the selected keys and
4004
       is as such a more intrusive change.  */
4005
0
    if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
4006
0
      {
4007
0
        latest_date = pk->timestamp;
4008
0
        latest_key = k;
4009
0
      }
4010
0
  }
4011
0
      if (n_subkeys == n_revoked_or_expired && r_flags)
4012
0
        *r_flags |= LOOKUP_ALL_SUBKEYS_EXPIRED;
4013
0
    }
4014
4015
  /* Check if the primary key is ok (valid, not revoke, not expire,
4016
   * matches requested usage) if:
4017
   *
4018
   *   - we didn't find an appropriate subkey and we're not doing an
4019
   *     exact search,
4020
   *
4021
   *   - we're doing an exact match and the exact match was the
4022
   *     primary key, or,
4023
   *
4024
   *   - we're just considering the primary key.  */
4025
0
  if ((!latest_key && !want_exact) || foundk == keyblock || req_prim)
4026
0
    {
4027
0
      if (DBG_LOOKUP && !foundk && !req_prim)
4028
0
  log_debug ("\tno suitable subkeys found - trying primary\n");
4029
0
      pk = keyblock->pkt->pkt.public_key;
4030
0
      if (!pk->flags.valid)
4031
0
  {
4032
0
    if (DBG_LOOKUP)
4033
0
      log_debug ("\tprimary key not valid\n");
4034
0
  }
4035
0
      else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
4036
0
  {
4037
0
    if (DBG_LOOKUP)
4038
0
      log_debug ("\tprimary key usage does not match: "
4039
0
           "want=%x have=%x\n", req_usage, pk->pubkey_usage);
4040
0
  }
4041
0
      else if (!verify_mode && pk->flags.revoked)
4042
0
  {
4043
0
    if (DBG_LOOKUP)
4044
0
      log_debug ("\tprimary key has been revoked\n");
4045
0
  }
4046
0
      else if (!verify_mode && pk->has_expired)
4047
0
  {
4048
0
    if (DBG_LOOKUP)
4049
0
      log_debug ("\tprimary key has expired\n");
4050
0
  }
4051
0
      else if (!verify_mode
4052
0
               && opt.flags.require_pqc_encryption
4053
0
               && (req_usage & PUBKEY_USAGE_XENC_MASK)
4054
0
               && pk->pubkey_algo != PUBKEY_ALGO_KYBER)
4055
0
        {
4056
0
          if (DBG_LOOKUP)
4057
0
            log_debug ("\tprimary key is not quantum-resistant\n");
4058
0
        }
4059
0
      else /* Okay.  */
4060
0
  {
4061
0
    if (DBG_LOOKUP)
4062
0
      log_debug ("\tprimary key may be used%s\n",
4063
0
                       verify_mode? " for verification":"");
4064
0
    latest_key = keyblock;
4065
0
  }
4066
0
    }
4067
4068
0
  if (!latest_key)
4069
0
    {
4070
0
      if (DBG_LOOKUP)
4071
0
  log_debug ("\tno suitable key found - giving up\n");
4072
0
      if (r_flags)
4073
0
        *r_flags |= LOOKUP_NOT_SELECTED;
4074
0
      return NULL; /* Not found.  */
4075
0
    }
4076
4077
0
 found:
4078
0
  if (DBG_LOOKUP)
4079
0
    log_debug ("\tusing key %08lX\n",
4080
0
         (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
4081
4082
0
  if (latest_key)
4083
0
    {
4084
0
      pk = latest_key->pkt->pkt.public_key;
4085
0
      free_user_id (pk->user_id);
4086
0
      pk->user_id = scopy_user_id (foundu);
4087
0
    }
4088
4089
0
  if (latest_key != keyblock && opt.verbose)
4090
0
    {
4091
0
      char *tempkeystr =
4092
0
  xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
4093
0
      log_info (_("using subkey %s instead of primary key %s\n"),
4094
0
    tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
4095
0
      xfree (tempkeystr);
4096
0
    }
4097
4098
0
  cache_put_keyblock (keyblock);
4099
4100
0
  return latest_key ? latest_key : keyblock; /* Found.  */
4101
0
}
4102
4103
4104
/* Print a KEY_CONSIDERED status line.  */
4105
static void
4106
print_status_key_considered (kbnode_t keyblock, unsigned int flags)
4107
0
{
4108
0
  char hexfpr[2*MAX_FINGERPRINT_LEN + 1];
4109
0
  kbnode_t node;
4110
0
  char flagbuf[20];
4111
4112
0
  if (!is_status_enabled ())
4113
0
    return;
4114
4115
0
  for (node=keyblock; node; node = node->next)
4116
0
    if (node->pkt->pkttype == PKT_PUBLIC_KEY
4117
0
        || node->pkt->pkttype == PKT_SECRET_KEY)
4118
0
      break;
4119
0
  if (!node)
4120
0
    {
4121
0
      log_error ("%s: keyblock w/o primary key\n", __func__);
4122
0
      return;
4123
0
    }
4124
4125
0
  hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr);
4126
0
  snprintf (flagbuf, sizeof flagbuf, " %u", flags);
4127
0
  write_status_strings (STATUS_KEY_CONSIDERED, hexfpr, flagbuf, NULL);
4128
0
}
4129
4130
4131
4132
/* A high-level function to lookup keys.
4133
 *
4134
 * This function builds on top of the low-level keydb API.  It first
4135
 * searches the database using the description stored in CTX->ITEMS,
4136
 * then it filters the results using CTX and, finally, if WANT_SECRET
4137
 * is set, it ignores any keys for which no secret key is available.
4138
 *
4139
 * Unlike the low-level search functions, this function also merges
4140
 * all of the self-signed data into the keys, subkeys and user id
4141
 * packets (see the merge_selfsigs for details).
4142
 *
4143
 * On success the key's keyblock is stored at *RET_KEYBLOCK, and the
4144
 * specific subkey is stored at *RET_FOUND_KEY.  Note that we do not
4145
 * return a reference in *RET_FOUND_KEY, i.e. the result must not be
4146
 * freed using 'release_kbnode', and it is only valid until
4147
 * *RET_KEYBLOCK is deallocated.  Therefore, if RET_FOUND_KEY is not
4148
 * NULL, then RET_KEYBLOCK must not be NULL.  */
4149
static int
4150
lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret,
4151
        kbnode_t *ret_keyblock, kbnode_t *ret_found_key)
4152
1.21M
{
4153
1.21M
  int rc;
4154
1.21M
  int no_suitable_key = 0;
4155
1.21M
  KBNODE keyblock = NULL;
4156
1.21M
  KBNODE found_key = NULL;
4157
1.21M
  unsigned int infoflags;
4158
4159
1.21M
  log_assert (ret_found_key == NULL || ret_keyblock != NULL);
4160
1.21M
  if (ret_keyblock)
4161
1.21M
    *ret_keyblock = NULL;
4162
4163
1.21M
  for (;;)
4164
1.21M
    {
4165
1.21M
      rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
4166
1.21M
      if (rc)
4167
1.21M
        break;
4168
4169
      /* If we are iterating over the entire database, then we need to
4170
       * change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
4171
       * reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next record.  */
4172
0
      if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
4173
0
  ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
4174
4175
0
      rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
4176
0
      if (rc)
4177
0
  {
4178
0
    log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
4179
0
    goto skip;
4180
0
  }
4181
4182
0
      if (want_secret)
4183
0
  {
4184
0
    rc = agent_probe_any_secret_key (ctrl, keyblock);
4185
0
    if (gpg_err_code(rc) == GPG_ERR_NO_SECKEY)
4186
0
      goto skip; /* No secret key available.  */
4187
0
    if (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO)
4188
0
      goto skip; /* Not implemented algo - skip.  */
4189
0
    if (rc)
4190
0
      goto found; /* Unexpected error.  */
4191
0
  }
4192
4193
      /* Warning: node flag bits 0 and 1 should be preserved by
4194
       * merge_selfsigs.  */
4195
0
      merge_selfsigs (ctrl, keyblock);
4196
0
      found_key = finish_lookup (keyblock, ctx->req_usage, ctx->exact,
4197
0
                                 want_secret, ctx->allow_adsk,
4198
0
                                 &infoflags);
4199
0
      print_status_key_considered (keyblock, infoflags);
4200
0
      if (found_key)
4201
0
  {
4202
0
    no_suitable_key = 0;
4203
0
    goto found;
4204
0
  }
4205
0
      else
4206
0
        {
4207
0
          no_suitable_key = 1;
4208
0
        }
4209
4210
0
    skip:
4211
      /* Release resources and continue search. */
4212
0
      release_kbnode (keyblock);
4213
0
      keyblock = NULL;
4214
      /* The keyblock cache ignores the current "file position".
4215
       * Thus, if we request the next result and the cache matches
4216
       * (and it will since it is what we just looked for), we'll get
4217
       * the same entry back!  We can avoid this infinite loop by
4218
       * disabling the cache.  */
4219
0
      keydb_disable_caching (ctx->kr_handle);
4220
0
    }
4221
4222
1.21M
 found:
4223
1.21M
  if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
4224
1.21M
    log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
4225
4226
1.21M
  if (!rc)
4227
0
    {
4228
0
      if (ret_keyblock)
4229
0
        {
4230
0
          *ret_keyblock = keyblock; /* Return the keyblock.  */
4231
0
          keyblock = NULL;
4232
0
        }
4233
0
    }
4234
1.21M
  else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
4235
0
    rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
4236
1.21M
  else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
4237
1.21M
    rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
4238
4239
1.21M
  release_kbnode (keyblock);
4240
4241
1.21M
  if (ret_found_key)
4242
1.21M
    {
4243
1.21M
      if (! rc)
4244
0
  *ret_found_key = found_key;
4245
1.21M
      else
4246
1.21M
  *ret_found_key = NULL;
4247
1.21M
    }
4248
4249
1.21M
  return rc;
4250
1.21M
}
4251
4252
4253
/* If a default key has been specified, return that key.  If a card
4254
 * based key is also available as indicated by FPR_CARD not being
4255
 * NULL, return that key if suitable.  */
4256
gpg_error_t
4257
get_seckey_default_or_card (ctrl_t ctrl, PKT_public_key *pk,
4258
                            const byte *fpr_card, size_t fpr_len)
4259
0
{
4260
0
  gpg_error_t err;
4261
0
  strlist_t namelist = NULL;
4262
0
  const char *def_secret_key;
4263
4264
0
  def_secret_key = parse_def_secret_key (ctrl);
4265
4266
0
  if (def_secret_key)
4267
0
    add_to_strlist (&namelist, def_secret_key);
4268
0
  else if (fpr_card)
4269
0
    {
4270
0
      err = get_pubkey_byfpr (ctrl, pk, NULL, fpr_card, fpr_len);
4271
0
      if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
4272
0
        {
4273
0
          if (opt.debug)
4274
0
            log_debug ("using LDAP to find public key for current card\n");
4275
0
          err = keyserver_import_fpr (ctrl, fpr_card, fpr_len,
4276
0
                                      opt.keyserver,
4277
0
                                      KEYSERVER_IMPORT_FLAG_LDAP);
4278
0
          if (!err)
4279
0
            err = get_pubkey_byfpr (ctrl, pk, NULL, fpr_card, fpr_len);
4280
0
          else if (gpg_err_code (err) == GPG_ERR_NO_DATA
4281
0
                   || gpg_err_code (err) == GPG_ERR_NO_KEYSERVER)
4282
0
            {
4283
              /* Dirmngr returns NO DATA is the selected keyserver
4284
               * does not have the requested key.  It returns NO
4285
               * KEYSERVER if no LDAP keyservers are configured.  */
4286
0
              err = gpg_error (GPG_ERR_NO_PUBKEY);
4287
0
            }
4288
0
        }
4289
4290
      /* The key on card can be not suitable for requested usage.  */
4291
0
      if (gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY)
4292
0
        fpr_card = NULL;        /* Fallthrough as no card.  */
4293
0
      else
4294
0
        return err;  /* Success or other error.  */
4295
0
    }
4296
4297
0
  if (!fpr_card || (def_secret_key && *def_secret_key
4298
0
                    && def_secret_key[strlen (def_secret_key)-1] == '!'))
4299
0
    {
4300
0
      err = key_byname (ctrl, NULL, namelist, pk, GETKEY_WANT_SECRET,
4301
0
                        NULL, NULL);
4302
0
    }
4303
0
  else
4304
0
    { /* Default key is specified and card key is also available.  */
4305
0
      kbnode_t k, keyblock = NULL;
4306
4307
0
      err = key_byname (ctrl, NULL, namelist, pk, GETKEY_WANT_SECRET,
4308
0
                        &keyblock, NULL);
4309
0
      if (err)
4310
0
        goto leave;
4311
0
      for (k = keyblock; k; k = k->next)
4312
0
        {
4313
0
          PKT_public_key *pk_candidate;
4314
0
          char fpr[MAX_FINGERPRINT_LEN];
4315
4316
0
          if (k->pkt->pkttype != PKT_PUBLIC_KEY
4317
0
              &&k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
4318
0
            continue;
4319
4320
0
          pk_candidate = k->pkt->pkt.public_key;
4321
0
          if (!pk_candidate->flags.valid)
4322
0
            continue;
4323
0
          if (!((pk_candidate->pubkey_usage & USAGE_MASK) & pk->req_usage))
4324
0
            continue;
4325
0
          fingerprint_from_pk (pk_candidate, fpr, NULL);
4326
0
          if (!memcmp (fpr_card, fpr, fpr_len))
4327
0
            {
4328
0
              release_public_key_parts (pk);
4329
0
              copy_public_key (pk, pk_candidate);
4330
0
              break;
4331
0
            }
4332
0
        }
4333
0
      release_kbnode (keyblock);
4334
0
    }
4335
4336
0
 leave:
4337
0
  free_strlist (namelist);
4338
0
  return err;
4339
0
}
4340
4341
4342

4343
/*********************************************
4344
 ***********  User ID printing helpers *******
4345
 *********************************************/
4346
4347
/* Return a string with a printable representation of the user_id.
4348
 * this string must be freed by xfree.  If R_NOUID is not NULL it is
4349
 * set to true if a user id was not found; otherwise to false.  */
4350
static char *
4351
get_user_id_string (ctrl_t ctrl, u32 * keyid, int mode)
4352
0
{
4353
0
  char *name;
4354
0
  unsigned int namelen;
4355
0
  char *p;
4356
4357
0
  log_assert (mode != 2);
4358
4359
0
  name = cache_get_uid_bykid (keyid, &namelen);
4360
0
  if (!name)
4361
0
    {
4362
      /* Get it so that the cache will be filled.  */
4363
0
      if (!get_pubkey (ctrl, NULL, keyid))
4364
0
        name = cache_get_uid_bykid (keyid, &namelen);
4365
0
    }
4366
4367
0
  if (name)
4368
0
    {
4369
0
      if (mode)
4370
0
        p = xasprintf ("%08lX%08lX %.*s",
4371
0
                       (ulong) keyid[0], (ulong) keyid[1], namelen, name);
4372
0
      else
4373
0
        p = xasprintf ("%s %.*s", keystr (keyid), namelen, name);
4374
4375
0
      xfree (name);
4376
0
    }
4377
0
  else
4378
0
    {
4379
0
      if (mode)
4380
0
        p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
4381
0
      else
4382
0
        p = xasprintf ("%s [?]", keystr (keyid));
4383
0
    }
4384
4385
0
  return p;
4386
0
}
4387
4388
4389
char *
4390
get_user_id_string_native (ctrl_t ctrl, u32 * keyid)
4391
0
{
4392
0
  char *p = get_user_id_string (ctrl, keyid, 0);
4393
0
  char *p2 = utf8_to_native (p, strlen (p), 0);
4394
0
  xfree (p);
4395
0
  return p2;
4396
0
}
4397
4398
4399
char *
4400
get_long_user_id_string (ctrl_t ctrl, u32 * keyid)
4401
0
{
4402
0
  return get_user_id_string (ctrl, keyid, 1);
4403
0
}
4404
4405
4406
/* Please try to use get_user_byfpr instead of this one.  */
4407
char *
4408
get_user_id (ctrl_t ctrl, u32 *keyid, size_t *rn, int *r_nouid)
4409
0
{
4410
0
  char *name;
4411
0
  unsigned int namelen;
4412
4413
0
  if (r_nouid)
4414
0
    *r_nouid = 0;
4415
4416
0
  name = cache_get_uid_bykid (keyid, &namelen);
4417
0
  if (!name)
4418
0
    {
4419
      /* Get it so that the cache will be filled.  */
4420
0
      if (!get_pubkey (ctrl, NULL, keyid))
4421
0
        name = cache_get_uid_bykid (keyid, &namelen);
4422
0
    }
4423
4424
0
  if (!name)
4425
0
    {
4426
0
      name = xstrdup (user_id_not_found_utf8 ());
4427
0
      namelen = strlen (name);
4428
0
      if (r_nouid)
4429
0
        *r_nouid = 1;
4430
0
    }
4431
4432
0
  if (rn && name)
4433
0
    *rn = namelen;
4434
0
  return name;
4435
0
}
4436
4437
4438
/* Please try to use get_user_id_byfpr_native instead of this one.  */
4439
char *
4440
get_user_id_native (ctrl_t ctrl, u32 *keyid)
4441
0
{
4442
0
  size_t rn;
4443
0
  char *p = get_user_id (ctrl, keyid, &rn, NULL);
4444
0
  char *p2 = utf8_to_native (p, rn, 0);
4445
0
  xfree (p);
4446
0
  return p2;
4447
0
}
4448
4449
4450
/* Return the user id for a key designated by its fingerprint, FPR,
4451
   which must be MAX_FINGERPRINT_LEN bytes in size.  Note: the
4452
   returned string, which must be freed using xfree, may not be NUL
4453
   terminated.  To determine the length of the string, you must use
4454
   *RN.  */
4455
static char *
4456
get_user_id_byfpr (ctrl_t ctrl, const byte *fpr, size_t fprlen, size_t *rn)
4457
0
{
4458
0
  char *name;
4459
4460
0
  name = cache_get_uid_byfpr (fpr, fprlen, rn);
4461
0
  if (!name)
4462
0
    {
4463
      /* Get it so that the cache will be filled.  */
4464
0
      if (!get_pubkey_byfpr (ctrl, NULL, NULL, fpr, fprlen))
4465
0
        name = cache_get_uid_byfpr (fpr, fprlen, rn);
4466
0
    }
4467
4468
0
  if (!name)
4469
0
    {
4470
0
      name = xstrdup (user_id_not_found_utf8 ());
4471
0
      *rn = strlen (name);
4472
0
    }
4473
4474
0
  return name;
4475
0
}
4476
4477
/* Like get_user_id_byfpr, but convert the string to the native
4478
   encoding.  The returned string needs to be freed.  Unlike
4479
   get_user_id_byfpr, the returned string is NUL terminated.  */
4480
char *
4481
get_user_id_byfpr_native (ctrl_t ctrl, const byte *fpr, size_t fprlen)
4482
0
{
4483
0
  size_t rn;
4484
0
  char *p = get_user_id_byfpr (ctrl, fpr, fprlen, &rn);
4485
0
  char *p2 = utf8_to_native (p, rn, 0);
4486
0
  xfree (p);
4487
0
  return p2;
4488
0
}
4489
4490
4491
/* Return the database handle used by this context.  The context still
4492
   owns the handle.  */
4493
KEYDB_HANDLE
4494
get_ctx_handle (GETKEY_CTX ctx)
4495
0
{
4496
0
  return ctx->kr_handle;
4497
0
}
4498
4499
static void
4500
free_akl (struct akl *akl)
4501
0
{
4502
0
  if (! akl)
4503
0
    return;
4504
4505
0
  if (akl->spec)
4506
0
    free_keyserver_spec (akl->spec);
4507
4508
0
  xfree (akl);
4509
0
}
4510
4511
void
4512
release_akl (void)
4513
0
{
4514
0
  while (opt.auto_key_locate)
4515
0
    {
4516
0
      struct akl *akl2 = opt.auto_key_locate;
4517
0
      opt.auto_key_locate = opt.auto_key_locate->next;
4518
0
      free_akl (akl2);
4519
0
    }
4520
0
}
4521
4522
4523
/* Returns true if the AKL is empty or has only the local method
4524
 * active.  */
4525
int
4526
akl_empty_or_only_local (void)
4527
0
{
4528
0
  struct akl *akl;
4529
0
  int any = 0;
4530
4531
0
  for (akl = opt.auto_key_locate; akl; akl = akl->next)
4532
0
    if (akl->type != AKL_NODEFAULT && akl->type != AKL_LOCAL)
4533
0
      {
4534
0
        any = 1;
4535
0
        break;
4536
0
      }
4537
4538
0
  return !any;
4539
0
}
4540
4541
4542
/* Returns false on error. */
4543
int
4544
parse_auto_key_locate (const char *options_arg)
4545
0
{
4546
0
  char *tok;
4547
0
  char *options, *options_buf;
4548
4549
0
  options = options_buf = xstrdup (options_arg);
4550
0
  while ((tok = optsep (&options)))
4551
0
    {
4552
0
      struct akl *akl, *check, *last = NULL;
4553
0
      int dupe = 0;
4554
4555
0
      if (tok[0] == '\0')
4556
0
  continue;
4557
4558
0
      akl = xmalloc_clear (sizeof (*akl));
4559
4560
0
      if (ascii_strcasecmp (tok, "clear") == 0)
4561
0
  {
4562
0
          xfree (akl);
4563
0
          free_akl (opt.auto_key_locate);
4564
0
          opt.auto_key_locate = NULL;
4565
0
          continue;
4566
0
        }
4567
0
      else if (ascii_strcasecmp (tok, "nodefault") == 0)
4568
0
  akl->type = AKL_NODEFAULT;
4569
0
      else if (ascii_strcasecmp (tok, "local") == 0)
4570
0
  akl->type = AKL_LOCAL;
4571
0
      else if (ascii_strcasecmp (tok, "ldap") == 0)
4572
0
  akl->type = AKL_LDAP;
4573
0
      else if (ascii_strcasecmp (tok, "keyserver") == 0)
4574
0
  akl->type = AKL_KEYSERVER;
4575
0
      else if (ascii_strcasecmp (tok, "cert") == 0)
4576
0
  akl->type = AKL_CERT;
4577
0
      else if (ascii_strcasecmp (tok, "pka") == 0)
4578
0
  akl->type = AKL_PKA;
4579
0
      else if (ascii_strcasecmp (tok, "dane") == 0)
4580
0
  akl->type = AKL_DANE;
4581
0
      else if (ascii_strcasecmp (tok, "wkd") == 0)
4582
0
  akl->type = AKL_WKD;
4583
0
      else if (ascii_strcasecmp (tok, "ntds") == 0)
4584
0
  akl->type = AKL_NTDS;
4585
0
      else if ((akl->spec = parse_keyserver_uri (tok, 1)))
4586
0
  akl->type = AKL_SPEC;
4587
0
      else
4588
0
  {
4589
0
    free_akl (akl);
4590
0
          xfree (options_buf);
4591
0
    return 0;
4592
0
  }
4593
4594
      /* We must maintain the order the user gave us */
4595
0
      for (check = opt.auto_key_locate; check;
4596
0
     last = check, check = check->next)
4597
0
  {
4598
    /* Check for duplicates */
4599
0
    if (check->type == akl->type
4600
0
        && (akl->type != AKL_SPEC
4601
0
      || (akl->type == AKL_SPEC
4602
0
          && strcmp (check->spec->uri, akl->spec->uri) == 0)))
4603
0
      {
4604
0
        dupe = 1;
4605
0
        free_akl (akl);
4606
0
        break;
4607
0
      }
4608
0
  }
4609
4610
0
      if (!dupe)
4611
0
  {
4612
0
    if (last)
4613
0
      last->next = akl;
4614
0
    else
4615
0
      opt.auto_key_locate = akl;
4616
0
  }
4617
0
    }
4618
4619
0
  xfree (options_buf);
4620
0
  return 1;
4621
0
}
4622
4623
4624

4625
/* The list of key origins. */
4626
static struct {
4627
  const char *name;
4628
  int origin;
4629
} key_origin_list[] =
4630
  {
4631
    { "self",    KEYORG_SELF    },
4632
    { "file",    KEYORG_FILE    },
4633
    { "url",     KEYORG_URL     },
4634
    { "wkd",     KEYORG_WKD     },
4635
    { "dane",    KEYORG_DANE    },
4636
    { "ks-pref", KEYORG_KS_PREF },
4637
    { "ks",      KEYORG_KS      },
4638
    { "unknown", KEYORG_UNKNOWN }
4639
  };
4640
4641
/* Parse the argument for --key-origin.  Return false on error. */
4642
int
4643
parse_key_origin (char *string)
4644
0
{
4645
0
  int i;
4646
0
  char *comma;
4647
4648
0
  comma = strchr (string, ',');
4649
0
  if (comma)
4650
0
    *comma = 0;
4651
4652
0
  if (!ascii_strcasecmp (string, "help"))
4653
0
    {
4654
0
      log_info (_("valid values for option '%s':\n"), "--key-origin");
4655
0
      for (i=0; i < DIM (key_origin_list); i++)
4656
0
        log_info ("  %s\n", key_origin_list[i].name);
4657
0
      g10_exit (1);
4658
0
    }
4659
4660
0
  for (i=0; i < DIM (key_origin_list); i++)
4661
0
    if (!ascii_strcasecmp (string, key_origin_list[i].name))
4662
0
      {
4663
0
        opt.key_origin = key_origin_list[i].origin;
4664
0
        xfree (opt.key_origin_url);
4665
0
        opt.key_origin_url = NULL;
4666
0
        if (comma && comma[1])
4667
0
          {
4668
0
            opt.key_origin_url = xstrdup (comma+1);
4669
0
            trim_spaces (opt.key_origin_url);
4670
0
          }
4671
4672
0
        return 1;
4673
0
      }
4674
4675
0
  if (comma)
4676
0
    *comma = ',';
4677
0
  return 0;
4678
0
}
4679
4680
/* Return a string or "?" for the key ORIGIN.  */
4681
const char *
4682
key_origin_string (int origin)
4683
0
{
4684
0
  int i;
4685
4686
0
  for (i=0; i < DIM (key_origin_list); i++)
4687
0
    if (key_origin_list[i].origin == origin)
4688
0
      return key_origin_list[i].name;
4689
0
  return "?";
4690
0
}
4691
4692
4693

4694
/* Returns true if a secret key is available for the public key with
4695
   key id KEYID; returns false if not.  This function ignores legacy
4696
   keys.  Note: this is just a fast check and does not tell us whether
4697
   the secret key is valid; this check merely indicates whether there
4698
   is some secret key with the specified key id.  */
4699
int
4700
have_secret_key_with_kid (ctrl_t ctrl, u32 *keyid)
4701
0
{
4702
0
  gpg_error_t err;
4703
0
  KEYDB_HANDLE kdbhd;
4704
0
  KEYDB_SEARCH_DESC desc;
4705
0
  kbnode_t keyblock;
4706
0
  kbnode_t node;
4707
0
  int result = 0;
4708
4709
0
  kdbhd = keydb_new (ctrl);
4710
0
  if (!kdbhd)
4711
0
    return 0;
4712
0
  memset (&desc, 0, sizeof desc);
4713
0
  desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
4714
0
  desc.u.kid[0] = keyid[0];
4715
0
  desc.u.kid[1] = keyid[1];
4716
0
  while (!result)
4717
0
    {
4718
0
      err = keydb_search (kdbhd, &desc, 1, NULL);
4719
0
      if (err)
4720
0
        break;
4721
4722
0
      err = keydb_get_keyblock (kdbhd, &keyblock);
4723
0
      if (err)
4724
0
        {
4725
0
          log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
4726
0
          break;
4727
0
        }
4728
4729
0
      for (node = keyblock; node; node = node->next)
4730
0
  {
4731
          /* Bit 0 of the flags is set if the search found the key
4732
             using that key or subkey.  Note: a search will only ever
4733
             match a single key or subkey.  */
4734
0
    if ((node->flag & 1))
4735
0
            {
4736
0
              log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY
4737
0
                          || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
4738
4739
0
              if (agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
4740
0
    result = 1; /* Secret key available.  */
4741
0
        else
4742
0
    result = 0;
4743
4744
0
        break;
4745
0
      }
4746
0
  }
4747
0
      release_kbnode (keyblock);
4748
0
    }
4749
4750
0
  keydb_release (kdbhd);
4751
0
  return result;
4752
0
}
4753
4754
4755
/* Return an error if KEYBLOCK has a primary or subkey with the given
4756
 * fingerprint (FPR,FPRLEN).  */
4757
gpg_error_t
4758
has_key_with_fingerprint (kbnode_t keyblock, const byte *fpr, size_t fprlen)
4759
0
{
4760
0
  kbnode_t node;
4761
0
  PKT_public_key *pk;
4762
0
  byte pkfpr[MAX_FINGERPRINT_LEN];
4763
0
  size_t pkfprlen;
4764
4765
0
  for (node = keyblock; node; node = node->next)
4766
0
    {
4767
0
      if (node->pkt->pkttype == PKT_PUBLIC_KEY
4768
0
          || node->pkt->pkttype == PKT_PUBLIC_SUBKEY
4769
0
          || node->pkt->pkttype == PKT_SECRET_KEY
4770
0
          || node->pkt->pkttype == PKT_SECRET_SUBKEY)
4771
0
        {
4772
0
          pk = node->pkt->pkt.public_key;
4773
0
          fingerprint_from_pk (pk, pkfpr, &pkfprlen);
4774
0
          if (pkfprlen == fprlen && !memcmp (pkfpr, fpr, fprlen))
4775
0
            return gpg_error (GPG_ERR_DUP_KEY);
4776
0
        }
4777
0
    }
4778
0
  return 0;
4779
0
}