Coverage Report

Created: 2026-01-17 06:46

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