Coverage Report

Created: 2026-04-28 07:00

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