Coverage Report

Created: 2026-08-13 06:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/g10/import.c
Line
Count
Source
1
/* import.c - import a key into our key storage.
2
 * Copyright (C) 1998-2007, 2010-2011 Free Software Foundation, Inc.
3
 * Copyright (C) 2014, 2016, 2017, 2019  Werner Koch
4
 *
5
 * This file is part of GnuPG.
6
 *
7
 * GnuPG is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * GnuPG is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
#include <config.h>
22
#include <stdio.h>
23
#include <stdlib.h>
24
#include <string.h>
25
#include <errno.h>
26
27
#include "gpg.h"
28
#include "options.h"
29
#include "packet.h"
30
#include "../common/status.h"
31
#include "keydb.h"
32
#include "../common/util.h"
33
#include "trustdb.h"
34
#include "main.h"
35
#include "../common/i18n.h"
36
#include "../common/ttyio.h"
37
#include "../common/recsel.h"
38
#include "keyserver-internal.h"
39
#include "call-agent.h"
40
#include "../common/membuf.h"
41
#include "../common/init.h"
42
#include "../common/mbox-util.h"
43
#include "key-check.h"
44
#include "key-clean.h"
45
46
47
struct import_stats_s
48
{
49
  ulong count;
50
  ulong no_user_id;
51
  ulong imported;
52
  ulong n_uids;
53
  ulong n_sigs;
54
  ulong n_subk;
55
  ulong unchanged;
56
  ulong n_revoc;
57
  ulong secret_read;
58
  ulong secret_imported;
59
  ulong secret_dups;
60
  ulong skipped_new_keys;
61
  ulong not_imported;
62
  ulong n_sigs_cleaned;
63
  ulong n_uids_cleaned;
64
  ulong v3keys;   /* Number of V3 keys seen.  */
65
};
66
67
68
/* Node flag to indicate that a user ID or a subkey has a
69
 * valid self-signature.  */
70
37.7k
#define NODE_GOOD_SELFSIG  1
71
/* Node flag to indicate that a user ID or subkey has
72
 * an invalid self-signature.  */
73
28.3k
#define NODE_BAD_SELFSIG   2
74
/* Node flag to indicate that the node shall be deleted.  */
75
8.84k
#define NODE_DELETION_MARK 4
76
/* A node flag used to temporary mark a node. */
77
16.2M
#define NODE_FLAG_A  8
78
/* A flag used by transfer_secret_keys. */
79
154
#define NODE_TRANSFER_SECKEY 16
80
81
82
/* An object and a global instance to store selectors created from
83
 * --import-filter keep-uid=EXPR.
84
 * --import-filter drop-sig=EXPR.
85
 *
86
 * FIXME: We should put this into the CTRL object but that requires a
87
 * lot more changes right now.  For now we use save and restore
88
 * function to temporary change them.
89
 */
90
/* Definition of the import filters.  */
91
struct import_filter_s
92
{
93
  recsel_expr_t keep_uid;
94
  recsel_expr_t drop_sig;
95
};
96
/* The current instance.  */
97
struct import_filter_s import_filter;
98
99
100
static int import (ctrl_t ctrl,
101
                   IOBUF inp, const char* fname, struct import_stats_s *stats,
102
       unsigned char **fpr, size_t *fpr_len, unsigned int options,
103
       import_screener_t screener, void *screener_arg,
104
                   int origin, const char *url);
105
static int read_block (IOBUF a, unsigned int options,
106
                       PACKET **pending_pkt, kbnode_t *ret_root, int *r_v3keys);
107
static void revocation_present (ctrl_t ctrl, kbnode_t keyblock);
108
static gpg_error_t import_one (ctrl_t ctrl,
109
                       kbnode_t keyblock,
110
                       struct import_stats_s *stats,
111
                       unsigned char **fpr, size_t *fpr_len,
112
                       unsigned int options, int from_sk, int silent,
113
                       import_screener_t screener, void *screener_arg,
114
                       int origin, const char *url, int *r_valid);
115
static gpg_error_t import_matching_seckeys (
116
                       ctrl_t ctrl, kbnode_t seckeys,
117
                       const byte *mainfpr, size_t mainfprlen,
118
                       struct import_stats_s *stats, int batch);
119
static gpg_error_t import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
120
                              struct import_stats_s *stats, int batch,
121
                              unsigned int options, int for_migration,
122
                              import_screener_t screener, void *screener_arg,
123
                              kbnode_t *r_secattic);
124
static int import_revoke_cert (ctrl_t ctrl, kbnode_t node, unsigned int options,
125
                               struct import_stats_s *stats);
126
static int chk_self_sigs (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid,
127
                          int *non_self);
128
static int delete_inv_parts (ctrl_t ctrl, kbnode_t keyblock,
129
                             u32 *keyid, unsigned int options,
130
                             kbnode_t *r_otherrevsigs);
131
static int any_uid_left (kbnode_t keyblock);
132
static void remove_all_non_self_sigs (kbnode_t *keyblock, u32 *keyid);
133
static int merge_blocks (ctrl_t ctrl, unsigned int options,
134
                         kbnode_t keyblock_orig,
135
       kbnode_t keyblock, u32 *keyid,
136
                         u32 curtime, int origin, const char *url,
137
       int *n_uids, int *n_sigs, int *n_subk );
138
static gpg_error_t append_new_uid (unsigned int options,
139
                                   kbnode_t keyblock, kbnode_t node,
140
                                   u32 curtime, int origin, const char *url,
141
                                   int *n_sigs);
142
static int append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs);
143
static int merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs);
144
static int merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs);
145
146
147

148
static void
149
release_import_filter (import_filter_t filt)
150
0
{
151
0
  recsel_release (filt->keep_uid);
152
0
  filt->keep_uid = NULL;
153
0
  recsel_release (filt->drop_sig);
154
0
  filt->drop_sig = NULL;
155
0
}
156
157
static void
158
cleanup_import_globals (void)
159
0
{
160
0
  release_import_filter (&import_filter);
161
0
}
162
163
164
int
165
parse_import_options(char *str,unsigned int *options,int noisy)
166
0
{
167
0
  struct parse_options import_opts[]=
168
0
    {
169
0
      {"import-local-sigs",IMPORT_LOCAL_SIGS,NULL,
170
0
       N_("import signatures that are marked as local-only")},
171
172
0
      {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,
173
0
       N_("repair damage from the pks keyserver during import")},
174
175
0
      {"keep-ownertrust", IMPORT_KEEP_OWNERTTRUST, NULL,
176
0
       N_("do not clear the ownertrust values during import")},
177
178
0
      {"fast-import",IMPORT_FAST,NULL,
179
0
       N_("do not update the trustdb after import")},
180
181
0
      {"bulk-import",IMPORT_BULK, NULL,
182
0
       N_("enable bulk import mode")},
183
184
0
      {"import-show",IMPORT_SHOW,NULL,
185
0
       N_("show key during import")},
186
187
0
      {"show-only", (IMPORT_SHOW | IMPORT_DRY_RUN), NULL,
188
0
       N_("show key but do not actually import") },
189
190
0
      {"merge-only",IMPORT_MERGE_ONLY,NULL,
191
0
       N_("only accept updates to existing keys")},
192
193
0
      {"import-clean",IMPORT_CLEAN,NULL,
194
0
       N_("remove unusable parts from key after import")},
195
196
0
      {"import-minimal",IMPORT_MINIMAL|IMPORT_CLEAN,NULL,
197
0
       N_("remove as much as possible from key after import")},
198
199
0
      {"self-sigs-only", IMPORT_SELF_SIGS_ONLY, NULL,
200
0
       N_("ignore key-signatures which are not self-signatures")},
201
202
0
      {"import-export", IMPORT_EXPORT, NULL,
203
0
       N_("run import filters and export key immediately")},
204
205
0
      {"restore", IMPORT_RESTORE, NULL,
206
0
       N_("assume the GnuPG key backup format")},
207
0
      {"import-restore", IMPORT_RESTORE, NULL, NULL},
208
209
0
      {"repair-keys", IMPORT_REPAIR_KEYS, NULL,
210
0
       N_("repair keys on import")},
211
212
0
      {"force-update", IMPORT_FORCE_UPDATE, NULL,
213
0
       N_("update even unchanged keys")},
214
215
      /* New options.  Right now, without description string.  */
216
0
      {"ignore-attributes", IMPORT_IGNORE_ATTRIBUTES, NULL, NULL},
217
218
0
      {"only-pubkeys", IMPORT_ONLY_PUBKEYS, NULL,
219
0
       N_("do not import secret keys")},
220
221
      /* Hidden options which are enabled by default and are provided
222
       * in case of problems with the respective implementation.  */
223
0
      {"collapse-uids", IMPORT_COLLAPSE_UIDS, NULL, NULL},
224
0
      {"collapse-subkeys", IMPORT_COLLAPSE_SUBKEYS, NULL, NULL},
225
226
      /* Aliases for backward compatibility */
227
0
      {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL},
228
0
      {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL},
229
      /* dummy */
230
0
      {"import-unusable-sigs",0,NULL,NULL},
231
0
      {"import-clean-sigs",0,NULL,NULL},
232
0
      {"import-clean-uids",0,NULL,NULL},
233
0
      {"convert-sk-to-pk",0, NULL,NULL}, /* Not anymore needed due to
234
                                            the new design.  */
235
0
      {NULL,0,NULL,NULL}
236
0
    };
237
0
  int rc;
238
0
  int saved_self_sigs_only, saved_import_clean;
239
240
  /* We need to set flags indicating whether the user has set certain
241
   * options or if they came from the default.  */
242
0
  saved_self_sigs_only = (*options & IMPORT_SELF_SIGS_ONLY);
243
0
  saved_self_sigs_only &= ~IMPORT_SELF_SIGS_ONLY;
244
0
  saved_import_clean   = (*options & IMPORT_CLEAN);
245
0
  saved_import_clean   &= ~IMPORT_CLEAN;
246
247
0
  rc = parse_options (str, options, import_opts, noisy);
248
249
0
  if (rc && (*options & IMPORT_SELF_SIGS_ONLY))
250
0
    opt.flags.expl_import_self_sigs_only = 1;
251
0
  else
252
0
    *options |= saved_self_sigs_only;
253
254
0
  if (rc && (*options & IMPORT_CLEAN))
255
0
    opt.flags.expl_import_clean = 1;
256
0
  else
257
0
    *options |= saved_import_clean;
258
259
260
0
  if (rc && (*options & IMPORT_RESTORE))
261
0
    {
262
      /* Alter other options we want or don't want for restore.  */
263
0
      *options |= (IMPORT_LOCAL_SIGS | IMPORT_KEEP_OWNERTTRUST);
264
0
      *options &= ~(IMPORT_MINIMAL | IMPORT_CLEAN
265
0
                    | IMPORT_REPAIR_PKS_SUBKEY_BUG
266
0
                    | IMPORT_MERGE_ONLY);
267
0
    }
268
0
  return rc;
269
0
}
270
271
272
/* Parse and set an import filter from string.  STRING has the format
273
 * "NAME=EXPR" with NAME being the name of the filter.  Spaces before
274
 * and after NAME are not allowed.  If this function is all called
275
 * several times all expressions for the same NAME are concatenated.
276
 * Supported filter names are:
277
 *
278
 *  - keep-uid :: If the expression evaluates to true for a certain
279
 *                user ID packet, that packet and all it dependencies
280
 *                will be imported.  The expression may use these
281
 *                variables:
282
 *
283
 *                - uid  :: The entire user ID.
284
 *                - mbox :: The mail box part of the user ID.
285
 *                - primary :: Evaluate to true for the primary user ID.
286
 */
287
gpg_error_t
288
parse_and_set_import_filter (const char *string)
289
0
{
290
0
  gpg_error_t err;
291
292
  /* Auto register the cleanup function.  */
293
0
  register_mem_cleanup_func (cleanup_import_globals);
294
295
0
  if (!strncmp (string, "keep-uid=", 9))
296
0
    err = recsel_parse_expr (&import_filter.keep_uid, string+9);
297
0
  else if (!strncmp (string, "drop-sig=", 9))
298
0
    err = recsel_parse_expr (&import_filter.drop_sig, string+9);
299
0
  else
300
0
    err = gpg_error (GPG_ERR_INV_NAME);
301
302
0
  return err;
303
0
}
304
305
306
/* Save the current import filters, return them, and clear the current
307
 * filters.  Returns NULL on error and sets ERRNO.  */
308
import_filter_t
309
save_and_clear_import_filter (void)
310
0
{
311
0
  import_filter_t filt;
312
313
0
  filt = xtrycalloc (1, sizeof *filt);
314
0
  if (!filt)
315
0
    return NULL;
316
0
  *filt = import_filter;
317
0
  memset (&import_filter, 0, sizeof import_filter);
318
319
0
  return filt;
320
0
}
321
322
323
/* Release the current import filters and restore them from NEWFILT.
324
 * Ownership of NEWFILT is moved to this function.  */
325
void
326
restore_import_filter (import_filter_t filt)
327
0
{
328
0
  if (filt)
329
0
    {
330
0
      release_import_filter (&import_filter);
331
0
      import_filter = *filt;
332
0
      xfree (filt);
333
0
    }
334
0
}
335
336
337
import_stats_t
338
import_new_stats_handle (void)
339
7.50k
{
340
7.50k
  return xmalloc_clear ( sizeof (struct import_stats_s) );
341
7.50k
}
342
343
344
void
345
import_release_stats_handle (import_stats_t p)
346
7.50k
{
347
7.50k
  xfree (p);
348
7.50k
}
349
350
351
/* Read a key from a file.  Only the first key in the file is
352
 * considered and stored at R_KEYBLOCK.  FNAME is the name of the
353
 * file.
354
 */
355
gpg_error_t
356
read_key_from_file_or_buffer (ctrl_t ctrl, const char *fname,
357
                              const void *buffer, size_t buflen,
358
                              kbnode_t *r_keyblock)
359
0
{
360
0
  gpg_error_t err;
361
0
  iobuf_t inp;
362
0
  PACKET *pending_pkt = NULL;
363
0
  kbnode_t keyblock = NULL;
364
0
  u32 keyid[2];
365
0
  int v3keys;   /* Dummy */
366
0
  int non_self; /* Dummy */
367
368
0
  (void)ctrl;
369
370
0
  *r_keyblock = NULL;
371
372
0
  log_assert (!!fname ^ !!buffer);
373
374
0
  if (fname)
375
0
    {
376
0
      inp = iobuf_open (fname);
377
0
      if (!inp)
378
0
        err = gpg_error_from_syserror ();
379
0
      else if (is_secured_file (iobuf_get_fd (inp)))
380
0
        {
381
0
          iobuf_close (inp);
382
0
          inp = NULL;
383
0
          err = gpg_error (GPG_ERR_EPERM);
384
0
        }
385
0
      else
386
0
        err = 0;
387
0
      if (err)
388
0
        {
389
0
          log_error (_("can't open '%s': %s\n"),
390
0
                     iobuf_is_pipe_filename (fname)? "[stdin]": fname,
391
0
                     gpg_strerror (err));
392
0
          if (gpg_err_code (err) == GPG_ERR_ENOENT)
393
0
            err = gpg_error (GPG_ERR_NO_PUBKEY);
394
0
          goto leave;
395
0
        }
396
397
      /* Push the armor filter.  */
398
0
      {
399
0
        armor_filter_context_t *afx;
400
0
        afx = new_armor_context ();
401
0
        afx->only_keyblocks = 1;
402
0
        push_armor_filter (afx, inp);
403
0
        release_armor_context (afx);
404
0
      }
405
406
0
    }
407
0
  else  /* Read from buffer (No armor expected).  */
408
0
    {
409
0
      inp = iobuf_temp_with_content (buffer, buflen);
410
0
    }
411
412
  /* Read the first non-v3 keyblock.  */
413
0
  while (!(err = read_block (inp, 0, &pending_pkt, &keyblock, &v3keys)))
414
0
    {
415
0
      if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
416
0
        break;
417
0
      log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
418
0
      release_kbnode (keyblock);
419
0
      keyblock = NULL;
420
0
    }
421
0
  if (err)
422
0
    {
423
0
      if (gpg_err_code (err) != GPG_ERR_INV_KEYRING)
424
0
        log_error (_("error reading '%s': %s\n"),
425
0
                   fname? (iobuf_is_pipe_filename (fname)? "[stdin]": fname)
426
0
                   /* */ : "[buffer]",
427
0
                   gpg_strerror (err));
428
0
      goto leave;
429
0
    }
430
431
0
  keyid_from_pk (keyblock->pkt->pkt.public_key, keyid);
432
433
0
  if (!find_next_kbnode (keyblock, PKT_USER_ID))
434
0
    {
435
0
      err = gpg_error (GPG_ERR_NO_USER_ID);
436
0
      goto leave;
437
0
    }
438
439
  /* We do the collapsing unconditionally although it is expected that
440
   * clean keys are provided here.  */
441
0
  collapse_uids (&keyblock);
442
0
  collapse_subkeys (&keyblock);
443
444
0
  clear_kbnode_flags (keyblock);
445
0
  if (chk_self_sigs (ctrl, keyblock, keyid, &non_self))
446
0
    {
447
0
      err = gpg_error (GPG_ERR_INV_KEYRING);
448
0
      goto leave;
449
0
    }
450
451
0
  if (!delete_inv_parts (ctrl, keyblock, keyid, 0, NULL) )
452
0
    {
453
0
      err = gpg_error (GPG_ERR_NO_USER_ID);
454
0
      goto leave;
455
0
    }
456
457
0
  *r_keyblock = keyblock;
458
0
  keyblock = NULL;
459
460
0
 leave:
461
0
  if (inp)
462
0
    {
463
0
      iobuf_close (inp);
464
      /* Must invalidate that ugly cache to actually close the file. */
465
0
      if (fname)
466
0
        iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
467
0
    }
468
0
  release_kbnode (keyblock);
469
  /* FIXME: Do we need to free PENDING_PKT ? */
470
0
  return err;
471
0
}
472
473
474
/* Import an already checked public key which was included in a
475
 * signature and the signature verified out using this key.  */
476
gpg_error_t
477
import_included_key_block (ctrl_t ctrl, kbnode_t keyblock)
478
0
{
479
0
  gpg_error_t err;
480
0
  struct import_stats_s *stats;
481
0
  import_filter_t save_filt;
482
0
  int save_armor = opt.armor;
483
484
0
  opt.armor = 0;
485
0
  stats = import_new_stats_handle ();
486
0
  save_filt = save_and_clear_import_filter ();
487
0
  if (!save_filt)
488
0
    {
489
0
      err = gpg_error_from_syserror ();
490
0
      goto leave;
491
0
    }
492
493
  /* FIXME: Should we introduce a dedicated KEYORG ? */
494
0
  err = import_one (ctrl, keyblock,
495
0
                    stats, NULL, 0, 0, 0, 0,
496
0
                    NULL, NULL, KEYORG_UNKNOWN, NULL, NULL);
497
498
0
 leave:
499
0
  restore_import_filter (save_filt);
500
0
  import_release_stats_handle (stats);
501
0
  opt.armor = save_armor;
502
0
  return err;
503
0
}
504
505
506
507
/*
508
 * Import the public keys from the given filename. Input may be armored.
509
 * This function rejects all keys which are not validly self signed on at
510
 * least one userid. Only user ids which are self signed will be imported.
511
 * Other signatures are not checked.
512
 *
513
 * Actually this function does a merge. It works like this:
514
 *
515
 *  - get the keyblock
516
 *  - check self-signatures and remove all userids and their signatures
517
 *    without/invalid self-signatures.
518
 *  - reject the keyblock, if we have no valid userid.
519
 *  - See whether we have this key already in one of our pubrings.
520
 *    If not, simply add it to the default keyring.
521
 *  - Compare the key and the self-signatures of the new and the one in
522
 *    our keyring.  If they are different something weird is going on;
523
 *    ask what to do.
524
 *  - See whether we have only non-self-signature on one user id; if not
525
 *    ask the user what to do.
526
 *  - compare the signatures: If we already have this signature, check
527
 *    that they compare okay; if not, issue a warning and ask the user.
528
 *    (consider looking at the timestamp and use the newest?)
529
 *  - Simply add the signature.  Can't verify here because we may not have
530
 *    the signature's public key yet; verification is done when putting it
531
 *    into the trustdb, which is done automagically as soon as this pubkey
532
 *    is used.
533
 *  - Proceed with next signature.
534
 *
535
 *  Key revocation certificates have special handling.
536
 */
537
static gpg_error_t
538
import_keys_internal (ctrl_t ctrl, iobuf_t inp, char **fnames, int nnames,
539
          import_stats_t stats_handle,
540
                      unsigned char **fpr, size_t *fpr_len,
541
          unsigned int options,
542
                      import_screener_t screener, void *screener_arg,
543
                      int origin, const char *url)
544
7.50k
{
545
7.50k
  int i;
546
7.50k
  gpg_error_t err = 0;
547
7.50k
  struct import_stats_s *stats = stats_handle;
548
549
7.50k
  if (!stats)
550
7.50k
    stats = import_new_stats_handle ();
551
552
7.50k
  if (inp)
553
0
    {
554
0
      err = import (ctrl, inp, "[stream]", stats, fpr, fpr_len, options,
555
0
                    screener, screener_arg, origin, url);
556
0
    }
557
7.50k
  else
558
7.50k
    {
559
7.50k
      if (!fnames && !nnames)
560
0
        nnames = 1;  /* Ohh what a ugly hack to jump into the loop */
561
562
15.0k
      for (i=0; i < nnames; i++)
563
7.50k
        {
564
7.50k
          const char *fname = fnames? fnames[i] : NULL;
565
7.50k
          IOBUF inp2 = iobuf_open(fname);
566
567
7.50k
          if (!fname)
568
0
            fname = "[stdin]";
569
7.50k
          if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
570
0
            {
571
0
              iobuf_close (inp2);
572
0
              inp2 = NULL;
573
0
              gpg_err_set_errno (EPERM);
574
0
            }
575
7.50k
          if (!inp2)
576
7.50k
            log_error (_("can't open '%s': %s\n"), fname, strerror (errno));
577
7.50k
          else
578
7.50k
            {
579
7.50k
              err = import (ctrl, inp2, fname, stats, fpr, fpr_len, options,
580
7.50k
                           screener, screener_arg, origin, url);
581
7.50k
              iobuf_close (inp2);
582
              /* Must invalidate that ugly cache to actually close it. */
583
7.50k
              iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
584
7.50k
              if (err)
585
7.50k
                log_error ("import from '%s' failed: %s\n",
586
3.15k
                           fname, gpg_strerror (err) );
587
7.50k
            }
588
7.50k
          if (!fname)
589
0
            break;
590
7.50k
  }
591
7.50k
    }
592
593
7.50k
  if (!stats_handle)
594
7.50k
    {
595
7.50k
      if ((options & (IMPORT_SHOW | IMPORT_DRY_RUN))
596
7.50k
          != (IMPORT_SHOW | IMPORT_DRY_RUN))
597
7.50k
        import_print_stats (stats);
598
7.50k
      import_release_stats_handle (stats);
599
7.50k
    }
600
601
  /* If no fast import and the trustdb is dirty (i.e. we added a key
602
     or userID that had something other than a selfsig, a signature
603
     that was other than a selfsig, or any revocation), then
604
     update/check the trustdb if the user specified by setting
605
     interactive or by not setting no-auto-check-trustdb */
606
607
7.50k
  if (!(options & IMPORT_FAST))
608
7.50k
    check_or_update_trustdb (ctrl);
609
610
7.50k
  return err;
611
7.50k
}
612
613
614
void
615
import_keys (ctrl_t ctrl, char **fnames, int nnames,
616
       import_stats_t stats_handle, unsigned int options,
617
             int origin, const char *url)
618
7.50k
{
619
7.50k
  import_keys_internal (ctrl, NULL, fnames, nnames, stats_handle,
620
7.50k
                        NULL, NULL, options, NULL, NULL, origin, url);
621
7.50k
}
622
623
624
gpg_error_t
625
import_keys_es_stream (ctrl_t ctrl, estream_t fp,
626
                       import_stats_t stats_handle,
627
                       unsigned char **fpr, size_t *fpr_len,
628
                       unsigned int options,
629
                       import_screener_t screener, void *screener_arg,
630
                       int origin, const char *url)
631
0
{
632
0
  gpg_error_t err;
633
0
  iobuf_t inp;
634
635
0
  inp = iobuf_esopen (fp, "rb", 1, 0);
636
0
  if (!inp)
637
0
    {
638
0
      err = gpg_error_from_syserror ();
639
0
      log_error ("iobuf_esopen failed: %s\n", gpg_strerror (err));
640
0
      return err;
641
0
    }
642
643
0
  err = import_keys_internal (ctrl, inp, NULL, 0, stats_handle,
644
0
                             fpr, fpr_len, options,
645
0
                             screener, screener_arg, origin, url);
646
647
0
  iobuf_close (inp);
648
0
  return err;
649
0
}
650
651
652
static int
653
import (ctrl_t ctrl, IOBUF inp, const char* fname,struct import_stats_s *stats,
654
  unsigned char **fpr,size_t *fpr_len, unsigned int options,
655
  import_screener_t screener, void *screener_arg,
656
        int origin, const char *url)
657
7.50k
{
658
7.50k
  PACKET *pending_pkt = NULL;
659
7.50k
  kbnode_t keyblock = NULL;  /* Need to initialize because gcc can't
660
                                grasp the return semantics of
661
                                read_block. */
662
7.50k
  kbnode_t secattic = NULL;  /* Kludge for PGP desktop percularity */
663
7.50k
  int rc = 0;
664
7.50k
  int v3keys;
665
666
7.50k
  getkey_disable_caches ();
667
668
7.50k
  if (!opt.no_armor) /* Armored reading is not disabled.  */
669
7.50k
    {
670
7.50k
      armor_filter_context_t *afx;
671
672
7.50k
      afx = new_armor_context ();
673
7.50k
      afx->only_keyblocks = 1;
674
7.50k
      push_armor_filter (afx, inp);
675
7.50k
      release_armor_context (afx);
676
7.50k
    }
677
678
23.8k
  while (!(rc = read_block (inp, options, &pending_pkt, &keyblock, &v3keys)))
679
16.4k
    {
680
16.4k
      stats->v3keys += v3keys;
681
16.4k
      if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
682
11.9k
        {
683
11.9k
          rc = import_one (ctrl, keyblock,
684
11.9k
                           stats, fpr, fpr_len, options, 0, 0,
685
11.9k
                           screener, screener_arg, origin, url, NULL);
686
11.9k
          if (secattic)
687
27
            {
688
27
              byte tmpfpr[MAX_FINGERPRINT_LEN];
689
27
              size_t tmpfprlen;
690
691
27
              if (!rc && !(opt.dry_run || (options & IMPORT_DRY_RUN)))
692
27
                {
693
                  /* Kudge for PGP desktop - see below.  */
694
27
                  fingerprint_from_pk (keyblock->pkt->pkt.public_key,
695
27
                                       tmpfpr, &tmpfprlen);
696
27
                  rc = import_matching_seckeys (ctrl, secattic,
697
27
                                                tmpfpr, tmpfprlen,
698
27
                                                stats, opt.batch);
699
27
                }
700
27
              release_kbnode (secattic);
701
27
              secattic = NULL;
702
27
            }
703
11.9k
        }
704
4.50k
      else if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
705
4.16k
        {
706
4.16k
          release_kbnode (secattic);
707
4.16k
          secattic = NULL;
708
4.16k
          rc = import_secret_one (ctrl, keyblock, stats,
709
4.16k
                                  opt.batch, options, 0,
710
4.16k
                                  screener, screener_arg, &secattic);
711
4.16k
          keyblock = NULL;  /* Ownership was transferred.  */
712
4.16k
          if (secattic)
713
1.35k
            {
714
1.35k
              if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
715
1.33k
                rc = 0; /* Try import after the next pubkey.  */
716
717
              /* The attic is a workaround for the peculiar PGP
718
               * Desktop method of exporting a secret key: The
719
               * exported file is the concatenation of two armored
720
               * keyblocks; first the private one and then the public
721
               * one.  The strange thing is that the secret one has no
722
               * binding signatures at all and thus we have not
723
               * imported it.  The attic stores that secret keys and
724
               * we try to import it once after the very next public
725
               * keyblock.  */
726
1.35k
            }
727
4.16k
        }
728
343
      else if (keyblock->pkt->pkttype == PKT_SIGNATURE
729
343
               && IS_KEY_REV (keyblock->pkt->pkt.signature) )
730
343
        {
731
343
          release_kbnode (secattic);
732
343
          secattic = NULL;
733
343
          rc = import_revoke_cert (ctrl, keyblock, options, stats);
734
343
        }
735
0
      else
736
0
        {
737
0
          release_kbnode (secattic);
738
0
          secattic = NULL;
739
0
          log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
740
0
  }
741
16.4k
      release_kbnode (keyblock);
742
743
      /* fixme: we should increment the not imported counter but
744
         this does only make sense if we keep on going despite of
745
         errors.  For now we do this only if the imported key is too
746
         large. */
747
16.4k
      if (gpg_err_code (rc) == GPG_ERR_TOO_LARGE
748
0
            && gpg_err_source (rc) == GPG_ERR_SOURCE_KEYBOX)
749
0
        {
750
0
          stats->not_imported++;
751
0
        }
752
16.4k
      else if (rc)
753
105
        break;
754
755
16.3k
      if (!(++stats->count % 100) && !opt.quiet)
756
16.3k
        log_info (_("%lu keys processed so far\n"), stats->count );
757
758
16.3k
      if (origin == KEYORG_WKD && stats->count >= 5)
759
0
        {
760
          /* We limit the number of keys _received_ from the WKD to 5.
761
           * In fact there should be only one key but some sites want
762
           * to store a few expired keys there also.  gpg's key
763
           * selection will later figure out which key to use.  Note
764
           * that for WKD we always return the fingerprint of the
765
           * first imported key.  */
766
0
          log_info ("import from WKD stopped after %d keys\n", 5);
767
0
          break;
768
0
        }
769
16.3k
    }
770
7.50k
  stats->v3keys += v3keys;
771
7.50k
  if (rc == -1)
772
4.35k
    rc = 0;
773
3.15k
  else if (rc && gpg_err_code (rc) != GPG_ERR_INV_KEYRING)
774
3.15k
    log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (rc));
775
776
7.50k
  release_kbnode (secattic);
777
778
  /* When read_block loop was stopped by error, we have PENDING_PKT left.  */
779
7.50k
  if (pending_pkt)
780
6
    {
781
6
      free_packet (pending_pkt, NULL);
782
6
      xfree (pending_pkt);
783
6
    }
784
7.50k
  return rc;
785
7.50k
}
786
787
788
/* Helper to migrate secring.gpg to GnuPG 2.1.  */
789
gpg_error_t
790
import_old_secring (ctrl_t ctrl, const char *fname)
791
0
{
792
0
  gpg_error_t err;
793
0
  iobuf_t inp;
794
0
  PACKET *pending_pkt = NULL;
795
0
  kbnode_t keyblock = NULL;  /* Need to initialize because gcc can't
796
                                grasp the return semantics of
797
                                read_block. */
798
0
  struct import_stats_s *stats;
799
0
  int v3keys;
800
801
0
  inp = iobuf_open (fname);
802
0
  if (inp && is_secured_file (iobuf_get_fd (inp)))
803
0
    {
804
0
      iobuf_close (inp);
805
0
      inp = NULL;
806
0
      gpg_err_set_errno (EPERM);
807
0
    }
808
0
  if (!inp)
809
0
    {
810
0
      err = gpg_error_from_syserror ();
811
0
      log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
812
0
      return err;
813
0
    }
814
815
0
  getkey_disable_caches();
816
0
  stats = import_new_stats_handle ();
817
0
  while (!(err = read_block (inp, 0, &pending_pkt, &keyblock, &v3keys)))
818
0
    {
819
0
      if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
820
0
        {
821
0
          err = import_secret_one (ctrl, keyblock, stats, 1, 0, 1,
822
0
                                   NULL, NULL, NULL);
823
0
          keyblock = NULL; /* Ownership was transferred.  */
824
0
        }
825
0
      release_kbnode (keyblock);
826
0
      if (err)
827
0
        break;
828
0
    }
829
0
  import_release_stats_handle (stats);
830
0
  if (err == -1)
831
0
    err = 0;
832
0
  else if (err && gpg_err_code (err) != GPG_ERR_INV_KEYRING)
833
0
    log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
834
0
  else if (err)
835
0
    log_error ("import from '%s' failed: %s\n", fname, gpg_strerror (err));
836
837
0
  iobuf_close (inp);
838
0
  iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
839
840
0
  return err;
841
0
}
842
843
844
void
845
import_print_stats (import_stats_t stats)
846
7.50k
{
847
7.50k
  if (!opt.quiet)
848
7.50k
    {
849
7.50k
      log_info(_("Total number processed: %lu\n"),
850
7.50k
               stats->count + stats->v3keys);
851
7.50k
      if (stats->v3keys)
852
7.50k
        log_info(_("    skipped PGP-2 keys: %lu\n"), stats->v3keys);
853
7.50k
      if (stats->skipped_new_keys )
854
7.50k
        log_info(_("      skipped new keys: %lu\n"),
855
0
                 stats->skipped_new_keys );
856
7.50k
      if (stats->no_user_id )
857
7.50k
        log_info(_("          w/o user IDs: %lu\n"), stats->no_user_id );
858
7.50k
      if (stats->imported)
859
27
        {
860
27
          log_info(_("              imported: %lu"), stats->imported );
861
27
          log_printf ("\n");
862
27
        }
863
7.50k
      if (stats->unchanged )
864
7.50k
        log_info(_("             unchanged: %lu\n"), stats->unchanged );
865
7.50k
      if (stats->n_uids )
866
7.50k
        log_info(_("          new user IDs: %lu\n"), stats->n_uids );
867
7.50k
      if (stats->n_subk )
868
7.50k
        log_info(_("           new subkeys: %lu\n"), stats->n_subk );
869
7.50k
      if (stats->n_sigs )
870
7.50k
        log_info(_("        new signatures: %lu\n"), stats->n_sigs );
871
7.50k
      if (stats->n_revoc )
872
7.50k
        log_info(_("   new key revocations: %lu\n"), stats->n_revoc );
873
7.50k
      if (stats->secret_read )
874
7.50k
        log_info(_("      secret keys read: %lu\n"), stats->secret_read );
875
7.50k
      if (stats->secret_imported )
876
7.50k
        log_info(_("  secret keys imported: %lu\n"), stats->secret_imported );
877
7.50k
      if (stats->secret_dups )
878
7.50k
        log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
879
7.50k
      if (stats->not_imported )
880
7.50k
        log_info(_("          not imported: %lu\n"), stats->not_imported );
881
7.50k
      if (stats->n_sigs_cleaned)
882
7.50k
        log_info(_("    signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
883
7.50k
      if (stats->n_uids_cleaned)
884
7.50k
        log_info(_("      user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
885
7.50k
    }
886
887
7.50k
  if (is_status_enabled ())
888
0
    {
889
0
      char buf[15*20];
890
891
0
      snprintf (buf, sizeof buf,
892
0
                "%lu %lu %lu 0 %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
893
0
    stats->count + stats->v3keys,
894
0
    stats->no_user_id,
895
0
    stats->imported,
896
0
    stats->unchanged,
897
0
    stats->n_uids,
898
0
    stats->n_subk,
899
0
    stats->n_sigs,
900
0
    stats->n_revoc,
901
0
    stats->secret_read,
902
0
    stats->secret_imported,
903
0
    stats->secret_dups,
904
0
    stats->skipped_new_keys,
905
0
                stats->not_imported,
906
0
                stats->v3keys );
907
0
      write_status_text (STATUS_IMPORT_RES, buf);
908
0
    }
909
7.50k
}
910
911
912
/* Return true if PKTTYPE is valid in a keyblock.  */
913
static int
914
valid_keyblock_packet (int pkttype)
915
64.6k
{
916
64.6k
  switch (pkttype)
917
64.6k
    {
918
2.05k
    case PKT_PUBLIC_KEY:
919
5.45k
    case PKT_PUBLIC_SUBKEY:
920
6.03k
    case PKT_SECRET_KEY:
921
8.16k
    case PKT_SECRET_SUBKEY:
922
34.9k
    case PKT_SIGNATURE:
923
60.7k
    case PKT_USER_ID:
924
60.7k
    case PKT_ATTRIBUTE:
925
60.7k
    case PKT_RING_TRUST:
926
60.7k
      return 1;
927
3.88k
    default:
928
3.88k
      return 0;
929
64.6k
    }
930
64.6k
}
931
932
933
/* Read the next keyblock from stream A.  Meta data (ring trust
934
 * packets) are only considered if OPTIONS has the IMPORT_RESTORE flag
935
 * set.  PENDING_PKT should be initialized to NULL and not changed by
936
 * the caller.
937
 *
938
 * Returns 0 for okay, -1 no more blocks, or any other errorcode.  The
939
 * integer at R_V3KEY counts the number of unsupported v3 keyblocks.
940
 */
941
static int
942
read_block( IOBUF a, unsigned int options,
943
            PACKET **pending_pkt, kbnode_t *ret_root, int *r_v3keys)
944
23.8k
{
945
23.8k
  int rc;
946
23.8k
  struct parse_packet_ctx_s parsectx;
947
23.8k
  PACKET *pkt;
948
23.8k
  kbnode_t root = NULL;
949
23.8k
  kbnode_t lastnode = NULL;
950
23.8k
  int in_cert, in_v3key, skip_sigs;
951
23.8k
  u32 keyid[2];
952
23.8k
  int got_keyid = 0;
953
23.8k
  unsigned int dropped_nonselfsigs = 0;
954
955
23.8k
  *r_v3keys = 0;
956
957
23.8k
  if (*pending_pkt)
958
14.2k
    {
959
14.2k
      root = lastnode = new_kbnode( *pending_pkt );
960
14.2k
      *pending_pkt = NULL;
961
14.2k
      log_assert (root->pkt->pkttype == PKT_PUBLIC_KEY
962
14.2k
                  || root->pkt->pkttype == PKT_SECRET_KEY);
963
14.2k
      in_cert = 1;
964
14.2k
      keyid_from_pk (root->pkt->pkt.public_key, keyid);
965
14.2k
      got_keyid = 1;
966
14.2k
    }
967
9.63k
  else
968
9.63k
    in_cert = 0;
969
970
23.8k
  pkt = xmalloc (sizeof *pkt);
971
23.8k
  init_packet (pkt);
972
23.8k
  init_parse_packet (&parsectx, a);
973
23.8k
  if (!(options & IMPORT_RESTORE))
974
23.8k
    parsectx.skip_meta = 1;
975
23.8k
  in_v3key = 0;
976
23.8k
  skip_sigs = 0;
977
130k
  while ((rc=parse_packet (&parsectx, pkt)) != -1)
978
124k
    {
979
124k
      if (rc && (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY
980
1.38k
                 && (pkt->pkttype == PKT_PUBLIC_KEY
981
1.00k
                     || pkt->pkttype == PKT_SECRET_KEY)))
982
1.38k
        {
983
1.38k
          in_v3key = 1;
984
1.38k
          ++*r_v3keys;
985
1.38k
          free_packet (pkt, &parsectx);
986
1.38k
          init_packet (pkt);
987
1.38k
          continue;
988
1.38k
        }
989
123k
      else if (rc ) /* (ignore errors) */
990
4.76k
        {
991
4.76k
          skip_sigs = 0;
992
4.76k
          if (gpg_err_code (rc) == GPG_ERR_UNKNOWN_PACKET)
993
1.71k
            ; /* Do not show a diagnostic.  */
994
3.04k
          else if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
995
2.79k
                   && (pkt->pkttype == PKT_USER_ID
996
2.74k
                       || pkt->pkttype == PKT_ATTRIBUTE))
997
54
            {
998
              /* This indicates a too large user id or attribute
999
               * packet.  We skip this packet and all following
1000
               * signatures.  Sure, this won't allow to repair a
1001
               * garbled keyring in case one of the signatures belong
1002
               * to another user id.  However, this better mitigates
1003
               * DoS using inserted user ids.  */
1004
54
              skip_sigs = 1;
1005
54
            }
1006
2.99k
          else if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
1007
2.74k
                   && (pkt->pkttype == PKT_OLD_COMMENT
1008
2.73k
                       || pkt->pkttype == PKT_COMMENT))
1009
22
            ; /* Ignore too large comment packets.  */
1010
2.97k
          else
1011
2.97k
            {
1012
2.97k
              log_error("read_block: read error: %s\n", gpg_strerror (rc) );
1013
2.97k
              rc = GPG_ERR_INV_KEYRING;
1014
2.97k
              goto ready;
1015
2.97k
            }
1016
1.79k
          free_packet (pkt, &parsectx);
1017
1.79k
          init_packet(pkt);
1018
1.79k
          continue;
1019
4.76k
  }
1020
118k
      else if ((opt.import_options & IMPORT_IGNORE_ATTRIBUTES)
1021
0
               && (pkt->pkttype == PKT_USER_ID || pkt->pkttype == PKT_ATTRIBUTE)
1022
0
               && pkt->pkt.user_id->attrib_data)
1023
0
        {
1024
0
          skip_sigs = 1;
1025
0
          free_packet (pkt, &parsectx);
1026
0
          init_packet (pkt);
1027
0
          continue;
1028
0
        }
1029
1030
118k
      if (skip_sigs)
1031
96
        {
1032
96
          if (pkt->pkttype == PKT_SIGNATURE)
1033
87
            {
1034
87
              free_packet (pkt, &parsectx);
1035
87
              init_packet (pkt);
1036
87
              continue;
1037
87
            }
1038
9
          skip_sigs = 0;
1039
9
        }
1040
1041
118k
      if (in_v3key && !(pkt->pkttype == PKT_PUBLIC_KEY
1042
2.13k
                        || pkt->pkttype == PKT_SECRET_KEY))
1043
1.83k
        {
1044
1.83k
          free_packet (pkt, &parsectx);
1045
1.83k
          init_packet(pkt);
1046
1.83k
          continue;
1047
1.83k
        }
1048
116k
      in_v3key = 0;
1049
1050
116k
      if (!root && pkt->pkttype == PKT_SIGNATURE
1051
11.0k
          && IS_KEY_REV (pkt->pkt.signature) )
1052
343
        {
1053
          /* This is a revocation certificate which is handled in a
1054
           * special way.  */
1055
343
          root = new_kbnode( pkt );
1056
343
          pkt = NULL;
1057
343
          goto ready;
1058
343
        }
1059
1060
      /* Make a linked list of all packets.  */
1061
116k
      switch (pkt->pkttype)
1062
116k
        {
1063
75
        case PKT_COMPRESSED:
1064
75
          if (!(opt.compat_flags & COMPAT_COMPR_KEYS))
1065
75
            {
1066
75
              rc = GPG_ERR_UNEXPECTED_PACKET;
1067
75
              goto ready;
1068
75
            }
1069
0
          else if (check_compress_algo (pkt->pkt.compressed->algorithm))
1070
0
            {
1071
0
              rc = GPG_ERR_COMPR_ALGO;
1072
0
              goto ready;
1073
0
            }
1074
0
          else
1075
0
            {
1076
0
              compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
1077
0
              pkt->pkt.compressed->buf = NULL;
1078
0
              if (push_compress_filter2 (a, cfx,
1079
0
                                         pkt->pkt.compressed->algorithm, 1))
1080
0
                xfree (cfx); /* e.g. in case of compression_algo NONE.  */
1081
0
            }
1082
0
          free_packet (pkt, &parsectx);
1083
0
          init_packet(pkt);
1084
0
          break;
1085
1086
0
        case PKT_RING_TRUST:
1087
          /* Skip those packets unless we are in restore mode.  */
1088
0
          if ((opt.import_options & IMPORT_RESTORE))
1089
0
            goto x_default;
1090
0
          free_packet (pkt, &parsectx);
1091
0
          init_packet(pkt);
1092
0
          break;
1093
1094
37.5k
        case PKT_SIGNATURE:
1095
37.5k
          if (!in_cert)
1096
10.7k
            goto x_default;
1097
26.8k
          if (!(options & IMPORT_SELF_SIGS_ONLY))
1098
26.8k
            goto x_default;
1099
26.8k
          log_assert (got_keyid);
1100
0
    if (pkt->pkt.signature->keyid[0] == keyid[0]
1101
0
              && pkt->pkt.signature->keyid[1] == keyid[1])
1102
0
      { /* This is likely a self-signature.  We import this one.
1103
               * Eventually we should use the ISSUER_FPR to compare
1104
               * self-signatures, but that will work only for v5 keys
1105
               * which are currently not even deployed.
1106
               * Note that we do not do any crypto verify here because
1107
               * that would defeat this very mitigation of DoS by
1108
               * importing a key with a huge amount of faked
1109
               * key-signatures.  A verification will be done later in
1110
               * the processing anyway.  Here we want a cheap an early
1111
               * way to drop non-self-signatures.  */
1112
0
              goto x_default;
1113
0
            }
1114
          /* Skip this signature.  */
1115
0
          dropped_nonselfsigs++;
1116
0
          free_packet (pkt, &parsectx);
1117
0
          init_packet(pkt);
1118
0
          break;
1119
1120
12.6k
        case PKT_PUBLIC_KEY:
1121
16.9k
        case PKT_SECRET_KEY:
1122
16.9k
          if (!got_keyid)
1123
2.64k
            {
1124
2.64k
              keyid_from_pk (pkt->pkt.public_key, keyid);
1125
2.64k
              got_keyid = 1;
1126
2.64k
            }
1127
16.9k
          if (in_cert) /* Store this packet.  */
1128
14.2k
            {
1129
14.2k
              *pending_pkt = pkt;
1130
14.2k
              pkt = NULL;
1131
14.2k
              goto ready;
1132
14.2k
            }
1133
2.64k
          in_cert = 1;
1134
2.64k
          goto x_default;
1135
1136
61.6k
        default:
1137
101k
        x_default:
1138
101k
          if (in_cert && valid_keyblock_packet (pkt->pkttype))
1139
60.7k
            {
1140
60.7k
              if (!root )
1141
2.64k
                root = lastnode = new_kbnode (pkt);
1142
58.1k
              else
1143
58.1k
                {
1144
58.1k
                  lastnode->next = new_kbnode (pkt);
1145
58.1k
                  lastnode = lastnode->next;
1146
58.1k
                }
1147
60.7k
              pkt = xmalloc (sizeof *pkt);
1148
60.7k
            }
1149
41.0k
          else
1150
41.0k
            free_packet (pkt, &parsectx);
1151
101k
          init_packet(pkt);
1152
101k
          break;
1153
116k
        }
1154
116k
    }
1155
1156
23.8k
 ready:
1157
23.8k
  if (rc == -1 && root )
1158
1.88k
    rc = 0;
1159
1160
23.8k
  if (rc )
1161
7.40k
    release_kbnode( root );
1162
16.4k
  else
1163
16.4k
    *ret_root = root;
1164
23.8k
  free_packet (pkt, &parsectx);
1165
23.8k
  deinit_parse_packet (&parsectx);
1166
23.8k
  xfree( pkt );
1167
23.8k
  if (!rc && dropped_nonselfsigs && opt.verbose)
1168
23.8k
    log_info ("key %s: number of dropped non-self-signatures: %u\n",
1169
0
              keystr (keyid), dropped_nonselfsigs);
1170
1171
23.8k
  return rc;
1172
23.8k
}
1173
1174
1175
/* Walk through the subkeys on a pk to find if we have the PKS
1176
   disease: multiple subkeys with their binding sigs stripped, and the
1177
   sig for the first subkey placed after the last subkey.  That is,
1178
   instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
1179
   "pk uid sig sub1 sub2 sub3 bind1".  We can't do anything about sub2
1180
   and sub3, as they are already lost, but we can try and rescue sub1
1181
   by reordering the keyblock so that it reads "pk uid sig sub1 bind1
1182
   sub2 sub3".  Returns TRUE if the keyblock was modified. */
1183
static int
1184
fix_pks_corruption (ctrl_t ctrl, kbnode_t keyblock)
1185
0
{
1186
0
  int changed = 0;
1187
0
  int keycount = 0;
1188
0
  kbnode_t node;
1189
0
  kbnode_t last = NULL;
1190
0
  kbnode_t sknode=NULL;
1191
1192
  /* First determine if we have the problem at all.  Look for 2 or
1193
     more subkeys in a row, followed by a single binding sig. */
1194
0
  for (node=keyblock; node; last=node, node=node->next)
1195
0
    {
1196
0
      if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1197
0
  {
1198
0
    keycount++;
1199
0
    if(!sknode)
1200
0
      sknode=node;
1201
0
  }
1202
0
      else if (node->pkt->pkttype == PKT_SIGNATURE
1203
0
               && IS_SUBKEY_SIG (node->pkt->pkt.signature)
1204
0
               && keycount >= 2
1205
0
               && !node->next)
1206
0
  {
1207
    /* We might have the problem, as this key has two subkeys in
1208
       a row without any intervening packets. */
1209
1210
    /* Sanity check */
1211
0
    if (!last)
1212
0
      break;
1213
1214
    /* Temporarily attach node to sknode. */
1215
0
    node->next = sknode->next;
1216
0
    sknode->next = node;
1217
0
    last->next = NULL;
1218
1219
    /* Note we aren't checking whether this binding sig is a
1220
       selfsig.  This is not necessary here as the subkey and
1221
       binding sig will be rejected later if that is the
1222
       case. */
1223
0
    if (check_key_signature (ctrl, keyblock,node,NULL))
1224
0
      {
1225
        /* Not a match, so undo the changes. */
1226
0
        sknode->next = node->next;
1227
0
        last->next = node;
1228
0
        node->next = NULL;
1229
0
        break;
1230
0
      }
1231
0
    else
1232
0
      {
1233
              /* Mark it good so we don't need to check it again */
1234
0
        sknode->flag |= NODE_GOOD_SELFSIG;
1235
0
        changed = 1;
1236
0
        break;
1237
0
      }
1238
0
  }
1239
0
      else
1240
0
  keycount = 0;
1241
0
    }
1242
1243
0
  return changed;
1244
0
}
1245
1246
1247
/* Versions of GnuPG before 1.4.11 and 2.0.16 allowed to import bogus
1248
   direct key signatures.  A side effect of this was that a later
1249
   import of the same good direct key signatures was not possible
1250
   because the cmp_signature check in merge_blocks considered them
1251
   equal.  Although direct key signatures are now checked during
1252
   import, there might still be bogus signatures sitting in a keyring.
1253
   We need to detect and delete them before doing a merge.  This
1254
   function returns the number of removed sigs.  */
1255
static int
1256
fix_bad_direct_key_sigs (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid)
1257
3.10k
{
1258
3.10k
  gpg_error_t err;
1259
3.10k
  kbnode_t node;
1260
3.10k
  int count = 0;
1261
1262
7.71k
  for (node = keyblock->next; node; node=node->next)
1263
7.71k
    {
1264
7.71k
      if (node->pkt->pkttype == PKT_USER_ID)
1265
3.10k
        break;
1266
4.61k
      if (node->pkt->pkttype == PKT_SIGNATURE
1267
4.61k
          && IS_KEY_SIG (node->pkt->pkt.signature))
1268
733
        {
1269
733
          err = check_key_signature (ctrl, keyblock, node, NULL);
1270
733
          if (err && gpg_err_code (err) != GPG_ERR_PUBKEY_ALGO )
1271
717
            {
1272
              /* If we don't know the error, we can't decide; this is
1273
                 not a problem because cmp_signature can't compare the
1274
                 signature either.  */
1275
717
              log_info ("key %s: invalid direct key signature removed\n",
1276
717
                        keystr (keyid));
1277
717
              delete_kbnode (node);
1278
717
              count++;
1279
717
            }
1280
733
        }
1281
4.61k
    }
1282
1283
3.10k
  return count;
1284
3.10k
}
1285
1286
1287
static void
1288
print_import_ok (PKT_public_key *pk, unsigned int reason)
1289
0
{
1290
0
  byte array[MAX_FINGERPRINT_LEN], *s;
1291
0
  char buf[MAX_FINGERPRINT_LEN*2+30], *p;
1292
0
  size_t i, n;
1293
1294
0
  snprintf (buf, sizeof buf, "%u ", reason);
1295
0
  p = buf + strlen (buf);
1296
1297
0
  fingerprint_from_pk (pk, array, &n);
1298
0
  s = array;
1299
0
  for (i=0; i < n ; i++, s++, p += 2)
1300
0
    sprintf (p, "%02X", *s);
1301
1302
0
  write_status_text (STATUS_IMPORT_OK, buf);
1303
0
}
1304
1305
1306
static void
1307
print_import_check (PKT_public_key * pk, PKT_user_id * id)
1308
0
{
1309
0
  byte hexfpr[2*MAX_FINGERPRINT_LEN+1];
1310
0
  u32 keyid[2];
1311
1312
0
  keyid_from_pk (pk, keyid);
1313
0
  hexfingerprint (pk, hexfpr, sizeof hexfpr);
1314
0
  write_status_printf (STATUS_IMPORT_CHECK, "%08X%08X %s %s",
1315
0
                       keyid[0], keyid[1], hexfpr, id->name);
1316
1317
0
}
1318
1319
1320
static void
1321
check_prefs_warning(PKT_public_key *pk)
1322
0
{
1323
0
  log_info(_("WARNING: key %s contains preferences for unavailable\n"
1324
0
             "algorithms on these user IDs:\n"), keystr_from_pk(pk));
1325
0
}
1326
1327
1328
static void
1329
check_prefs (ctrl_t ctrl, kbnode_t keyblock)
1330
0
{
1331
0
  kbnode_t node;
1332
0
  PKT_public_key *pk;
1333
0
  int problem=0;
1334
1335
0
  merge_keys_and_selfsig (ctrl, keyblock);
1336
0
  pk=keyblock->pkt->pkt.public_key;
1337
1338
0
  for(node=keyblock;node;node=node->next)
1339
0
    {
1340
0
      if(node->pkt->pkttype==PKT_USER_ID
1341
0
   && node->pkt->pkt.user_id->created
1342
0
   && node->pkt->pkt.user_id->prefs)
1343
0
  {
1344
0
    PKT_user_id *uid = node->pkt->pkt.user_id;
1345
0
    prefitem_t *prefs = uid->prefs;
1346
0
    char *user = utf8_to_native(uid->name,strlen(uid->name),0);
1347
1348
0
    for(;prefs->type;prefs++)
1349
0
      {
1350
0
        char num[10]; /* prefs->value is a byte, so we're over
1351
             safe here */
1352
1353
0
        sprintf(num,"%u",prefs->value);
1354
1355
0
        if(prefs->type==PREFTYPE_SYM)
1356
0
    {
1357
0
      if (openpgp_cipher_test_algo (prefs->value))
1358
0
        {
1359
0
          const char *algo =
1360
0
                        (openpgp_cipher_test_algo (prefs->value)
1361
0
                         ? num
1362
0
                         : openpgp_cipher_algo_name (prefs->value));
1363
0
          if(!problem)
1364
0
      check_prefs_warning(pk);
1365
0
          log_info(_("         \"%s\": preference for cipher"
1366
0
         " algorithm %s\n"), user, algo);
1367
0
          problem=1;
1368
0
        }
1369
0
    }
1370
0
        else if(prefs->type==PREFTYPE_AEAD)
1371
0
    {
1372
0
      if (openpgp_aead_test_algo (prefs->value))
1373
0
        {
1374
                      /* FIXME: The test below is wrong.  We should
1375
                       * check if ...algo_name yields a "?" and
1376
                       * only in that case use NUM.  */
1377
0
          const char *algo =
1378
0
                        (openpgp_aead_test_algo (prefs->value)
1379
0
                         ? num
1380
0
                         : openpgp_aead_algo_name (prefs->value));
1381
0
          if(!problem)
1382
0
      check_prefs_warning(pk);
1383
0
          log_info(_("         \"%s\": preference for AEAD"
1384
0
         " algorithm %s\n"), user, algo);
1385
0
          problem=1;
1386
0
        }
1387
0
    }
1388
0
        else if(prefs->type==PREFTYPE_HASH)
1389
0
    {
1390
0
      if(openpgp_md_test_algo(prefs->value))
1391
0
        {
1392
0
          const char *algo =
1393
0
                        (gcry_md_test_algo (prefs->value)
1394
0
                         ? num
1395
0
                         : gcry_md_algo_name (prefs->value));
1396
0
          if(!problem)
1397
0
      check_prefs_warning(pk);
1398
0
          log_info(_("         \"%s\": preference for digest"
1399
0
         " algorithm %s\n"), user, algo);
1400
0
          problem=1;
1401
0
        }
1402
0
    }
1403
0
        else if(prefs->type==PREFTYPE_ZIP)
1404
0
    {
1405
0
      if(check_compress_algo (prefs->value))
1406
0
        {
1407
0
          const char *algo=compress_algo_to_string(prefs->value);
1408
0
          if(!problem)
1409
0
      check_prefs_warning(pk);
1410
0
          log_info(_("         \"%s\": preference for compression"
1411
0
         " algorithm %s\n"),user,algo?algo:num);
1412
0
          problem=1;
1413
0
        }
1414
0
    }
1415
0
      }
1416
1417
0
    xfree(user);
1418
0
  }
1419
0
    }
1420
1421
0
  if(problem)
1422
0
    {
1423
0
      log_info(_("it is strongly suggested that you update"
1424
0
     " your preferences and\n"));
1425
0
      log_info(_("re-distribute this key to avoid potential algorithm"
1426
0
     " mismatch problems\n"));
1427
1428
0
      if(!opt.batch)
1429
0
  {
1430
0
    strlist_t sl = NULL;
1431
0
          strlist_t locusr = NULL;
1432
0
    size_t fprlen=0;
1433
0
    byte fpr[MAX_FINGERPRINT_LEN], *p;
1434
0
    char username[(MAX_FINGERPRINT_LEN*2)+1];
1435
0
    unsigned int i;
1436
1437
0
    p = fingerprint_from_pk (pk,fpr,&fprlen);
1438
0
    for(i=0;i<fprlen;i++,p++)
1439
0
      sprintf(username+2*i,"%02X",*p);
1440
0
    add_to_strlist(&locusr,username);
1441
1442
0
    append_to_strlist(&sl,"updpref");
1443
0
    append_to_strlist(&sl,"save");
1444
1445
0
    keyedit_menu (ctrl, username, locusr, sl, 1, 1 );
1446
0
    free_strlist(sl);
1447
0
    free_strlist(locusr);
1448
0
  }
1449
0
      else if(!opt.quiet)
1450
0
  log_info(_("you can update your preferences with:"
1451
0
       " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
1452
0
    }
1453
0
}
1454
1455
1456
/* Helper for apply_*_filter in import.c and export.c and also used by
1457
 * keylist.c.  */
1458
const char *
1459
impex_filter_getval (void *cookie, const char *propname)
1460
0
{
1461
  /* FIXME: Malloc our static buffers and access them via PARM.  */
1462
0
  struct impex_filter_parm_s *parm = cookie;
1463
0
  ctrl_t ctrl = parm->ctrl;
1464
0
  kbnode_t node = parm->node;
1465
0
  static char numbuf[20];
1466
0
  const char *result;
1467
0
  const char *s;
1468
0
  enum { scpNone = 0, scpPub, scpSub, scpUid, scpSig} scope = 0;
1469
1470
0
  log_assert (ctrl && ctrl->magic == SERVER_CONTROL_MAGIC);
1471
1472
  /* We allow a prefix delimited by a slash to limit the scope of the
1473
   * keyword.  Note that "pub" also includes "sec" and "sub" includes
1474
   * "ssb".  */
1475
0
  if (DBG_RECSEL)  /* Printing the packet type is useful.  */
1476
0
    log_debug ("%s: pkttype=%s\n", __func__, pkttype_str (node->pkt->pkttype));
1477
0
  if ((s=strchr (propname, '/')) && s != propname)
1478
0
    {
1479
0
      size_t n = s - propname;
1480
0
      if (!strncmp (propname, "pub", n))
1481
0
        scope = scpPub;
1482
0
      else if (!strncmp (propname, "sub", n))
1483
0
        scope = scpSub;
1484
0
      else if (!strncmp (propname, "uid", n))
1485
0
        scope = scpUid;
1486
0
      else if (!strncmp (propname, "sig", n))
1487
0
        scope = scpSig;
1488
1489
0
      propname = s + 1;
1490
0
    }
1491
1492
0
  if ((node->pkt->pkttype == PKT_USER_ID
1493
0
       || node->pkt->pkttype == PKT_ATTRIBUTE)
1494
0
      && (!scope || scope == scpUid))
1495
0
    {
1496
0
      PKT_user_id *uid = node->pkt->pkt.user_id;
1497
1498
0
      if (!strcmp (propname, "uid"))
1499
0
        result = uid->name;
1500
0
      else if (!strcmp (propname, "mbox"))
1501
0
        {
1502
0
          if (!uid->mbox)
1503
0
            {
1504
0
              uid->mbox = mailbox_from_userid (uid->name, 0);
1505
0
            }
1506
0
          result = uid->mbox;
1507
0
        }
1508
0
      else if (!strcmp (propname, "primary"))
1509
0
        {
1510
0
          result = uid->flags.primary? "1":"0";
1511
0
        }
1512
0
      else if (!strcmp (propname, "expired"))
1513
0
        {
1514
0
          result = uid->flags.expired? "1":"0";
1515
0
        }
1516
0
      else if (!strcmp (propname, "revoked"))
1517
0
        {
1518
0
          result = uid->flags.revoked? "1":"0";
1519
0
        }
1520
0
      else
1521
0
        result = NULL;
1522
0
    }
1523
0
  else if (node->pkt->pkttype == PKT_SIGNATURE
1524
0
           && (!scope || scope == scpSig))
1525
0
    {
1526
0
      PKT_signature *sig = node->pkt->pkt.signature;
1527
1528
0
      if (!strcmp (propname, "sig_created"))
1529
0
        {
1530
0
          snprintf (numbuf, sizeof numbuf, "%lu", (ulong)sig->timestamp);
1531
0
          result = numbuf;
1532
0
        }
1533
0
      else if (!strcmp (propname, "sig_created_d"))
1534
0
        {
1535
0
          result = dateonlystr_from_sig (sig);
1536
0
        }
1537
0
      else if (!strcmp (propname, "sig_expires"))
1538
0
        {
1539
0
          snprintf (numbuf, sizeof numbuf, "%lu", (ulong)sig->expiredate);
1540
0
          result = numbuf;
1541
0
        }
1542
0
      else if (!strcmp (propname, "sig_expires_d"))
1543
0
        {
1544
0
          static char exdatestr[MK_DATESTR_SIZE];
1545
1546
0
          if (sig->expiredate)
1547
0
            result = mk_datestr (exdatestr, sizeof exdatestr, sig->expiredate);
1548
0
          else
1549
0
            result = "";
1550
0
        }
1551
0
      else if (!strcmp (propname, "sig_algo"))
1552
0
        {
1553
0
          snprintf (numbuf, sizeof numbuf, "%d", sig->pubkey_algo);
1554
0
          result = numbuf;
1555
0
        }
1556
0
      else if (!strcmp (propname, "sig_digest_algo"))
1557
0
        {
1558
0
          snprintf (numbuf, sizeof numbuf, "%d", sig->digest_algo);
1559
0
          result = numbuf;
1560
0
        }
1561
0
      else if (!strcmp (propname, "expired"))
1562
0
        {
1563
0
          result = sig->flags.expired? "1":"0";
1564
0
        }
1565
0
      else
1566
0
        result = NULL;
1567
0
    }
1568
0
  else if (((node->pkt->pkttype == PKT_PUBLIC_KEY
1569
0
             || node->pkt->pkttype == PKT_SECRET_KEY)
1570
0
            && (!scope || scope == scpPub))
1571
0
           || ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1572
0
                || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1573
0
               && (!scope || scope == scpSub)))
1574
0
    {
1575
0
      PKT_public_key *pk = node->pkt->pkt.public_key;
1576
1577
0
      if (!strcmp (propname, "secret"))
1578
0
        {
1579
0
          result = (node->pkt->pkttype == PKT_SECRET_KEY
1580
0
                    || node->pkt->pkttype == PKT_SECRET_SUBKEY)? "1":"0";
1581
0
        }
1582
0
      else if (!strcmp (propname, "key_algo"))
1583
0
        {
1584
0
          snprintf (numbuf, sizeof numbuf, "%d", pk->pubkey_algo);
1585
0
          result = numbuf;
1586
0
        }
1587
0
      else if (!strcmp (propname, "key_size"))
1588
0
        {
1589
0
          snprintf (numbuf, sizeof numbuf, "%u", nbits_from_pk (pk));
1590
0
          result = numbuf;
1591
0
        }
1592
0
      else if (!strcmp (propname, "algostr"))
1593
0
        {
1594
0
          pubkey_string (pk, parm->hexfpr, sizeof parm->hexfpr);
1595
0
          result = parm->hexfpr;
1596
0
        }
1597
0
      else if (!strcmp (propname, "key_created"))
1598
0
        {
1599
0
          snprintf (numbuf, sizeof numbuf, "%lu", (ulong)pk->timestamp);
1600
0
          result = numbuf;
1601
0
        }
1602
0
      else if (!strcmp (propname, "key_created_d"))
1603
0
        {
1604
0
          result = dateonlystr_from_pk (pk);
1605
0
        }
1606
0
      else if (!strcmp (propname, "key_expires"))
1607
0
        {
1608
0
          snprintf (numbuf, sizeof numbuf, "%lu", (ulong)pk->expiredate);
1609
0
          result = numbuf;
1610
0
        }
1611
0
      else if (!strcmp (propname, "key_expires_d"))
1612
0
        {
1613
0
          static char exdatestr[MK_DATESTR_SIZE];
1614
1615
0
          if (pk->expiredate)
1616
0
            result = mk_datestr (exdatestr, sizeof exdatestr, pk->expiredate);
1617
0
          else
1618
0
            result = "";
1619
0
        }
1620
0
      else if (!strcmp (propname, "expired"))
1621
0
        {
1622
0
          result = pk->has_expired? "1":"0";
1623
0
        }
1624
0
      else if (!strcmp (propname, "revoked"))
1625
0
        {
1626
0
          result = pk->flags.revoked? "1":"0";
1627
0
        }
1628
0
      else if (!strcmp (propname, "disabled"))
1629
0
        {
1630
0
          result = pk_is_disabled (pk)? "1":"0";
1631
0
        }
1632
0
      else if (!strcmp (propname, "usage"))
1633
0
        {
1634
0
          snprintf (numbuf, sizeof numbuf, "%s%s%s%s%s",
1635
0
                    (pk->pubkey_usage & PUBKEY_USAGE_ENC)?"e":"",
1636
0
                    (pk->pubkey_usage & PUBKEY_USAGE_SIG)?"s":"",
1637
0
                    (pk->pubkey_usage & PUBKEY_USAGE_CERT)?"c":"",
1638
0
                    (pk->pubkey_usage & PUBKEY_USAGE_AUTH)?"a":"",
1639
0
                    (pk->pubkey_usage & PUBKEY_USAGE_UNKNOWN)?"?":"");
1640
0
          result = numbuf;
1641
0
        }
1642
0
      else if (!strcmp (propname, "fpr"))
1643
0
        {
1644
0
          hexfingerprint (pk, parm->hexfpr, sizeof parm->hexfpr);
1645
0
          result = parm->hexfpr;
1646
0
        }
1647
0
      else if (!strcmp (propname, "origin"))
1648
0
        {
1649
0
          result = key_origin_string (pk->keyorg);
1650
0
        }
1651
0
      else if (!strcmp (propname, "lastupd"))
1652
0
        {
1653
0
          snprintf (numbuf, sizeof numbuf, "%lu", (ulong)pk->keyupdate);
1654
0
          result = numbuf;
1655
0
        }
1656
0
      else if (!strcmp (propname, "url"))
1657
0
        {
1658
0
          if (pk->updateurl && *pk->updateurl)
1659
0
            {
1660
              /* Fixme: This might get truncated.  */
1661
0
              mem2str (parm->hexfpr, pk->updateurl, sizeof parm->hexfpr);
1662
0
              result = parm->hexfpr;
1663
0
            }
1664
0
          else
1665
0
            result = "";
1666
0
        }
1667
0
      else
1668
0
        result = NULL;
1669
0
    }
1670
0
  else
1671
0
    result = NULL;
1672
1673
0
  return result;
1674
0
}
1675
1676
1677
/*
1678
 * Apply the keep-uid filter to the keyblock.  The deleted nodes are
1679
 * marked and thus the caller should call commit_kbnode afterwards.
1680
 * KEYBLOCK must not have any blocks marked as deleted.
1681
 */
1682
static void
1683
apply_keep_uid_filter (ctrl_t ctrl, kbnode_t keyblock, recsel_expr_t selector)
1684
0
{
1685
0
  kbnode_t node;
1686
0
  struct impex_filter_parm_s parm;
1687
1688
0
  parm.ctrl = ctrl;
1689
1690
0
  for (node = keyblock->next; node; node = node->next )
1691
0
    {
1692
0
      if (node->pkt->pkttype == PKT_USER_ID)
1693
0
        {
1694
0
          parm.node = node;
1695
0
          if (!recsel_select (selector, impex_filter_getval, &parm))
1696
0
            {
1697
1698
              /* log_debug ("keep-uid: deleting '%s'\n", */
1699
              /*            node->pkt->pkt.user_id->name); */
1700
              /* The UID packet and all following packets up to the
1701
               * next UID or a subkey.  */
1702
0
              delete_kbnode (node);
1703
0
              for (; node->next
1704
0
                     && node->next->pkt->pkttype != PKT_USER_ID
1705
0
                     && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1706
0
                     && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1707
0
                   node = node->next)
1708
0
                delete_kbnode (node->next);
1709
0
      }
1710
          /* else */
1711
          /*   log_debug ("keep-uid: keeping '%s'\n", */
1712
          /*              node->pkt->pkt.user_id->name); */
1713
0
        }
1714
0
    }
1715
0
}
1716
1717
1718
/*
1719
 * Apply the drop-sig filter to the keyblock.  The deleted nodes are
1720
 * marked and thus the caller should call commit_kbnode afterwards.
1721
 * KEYBLOCK must not have any blocks marked as deleted.
1722
 */
1723
static void
1724
apply_drop_sig_filter (ctrl_t ctrl, kbnode_t keyblock, recsel_expr_t selector)
1725
0
{
1726
0
  kbnode_t node;
1727
0
  int active = 0;
1728
0
  u32 main_keyid[2];
1729
0
  PKT_signature *sig;
1730
0
  struct impex_filter_parm_s parm;
1731
1732
0
  parm.ctrl = ctrl;
1733
1734
0
  keyid_from_pk (keyblock->pkt->pkt.public_key, main_keyid);
1735
1736
  /* Loop over all signatures for user id and attribute packets which
1737
   * are not self signatures.  */
1738
0
  for (node = keyblock->next; node; node = node->next )
1739
0
    {
1740
0
      if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1741
0
          || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1742
0
        break; /* ready.  */
1743
0
      if (node->pkt->pkttype == PKT_USER_ID
1744
0
          || node->pkt->pkttype == PKT_ATTRIBUTE)
1745
0
        active = 1;
1746
0
      if (!active)
1747
0
        continue;
1748
0
      if (node->pkt->pkttype != PKT_SIGNATURE)
1749
0
        continue;
1750
1751
0
      sig = node->pkt->pkt.signature;
1752
0
      if (main_keyid[0] == sig->keyid[0] || main_keyid[1] == sig->keyid[1])
1753
0
        continue;  /* Skip self-signatures.  */
1754
1755
0
      if (IS_UID_SIG(sig) || IS_UID_REV(sig))
1756
0
        {
1757
0
          parm.node = node;
1758
0
          if (recsel_select (selector, impex_filter_getval, &parm))
1759
0
            delete_kbnode (node);
1760
0
        }
1761
0
    }
1762
0
}
1763
1764
1765
/* Insert a key origin into a public key packet.  */
1766
static gpg_error_t
1767
insert_key_origin_pk (PKT_public_key *pk, u32 curtime,
1768
                      int origin, const char *url)
1769
27
{
1770
27
  if (origin == KEYORG_WKD || origin == KEYORG_DANE)
1771
0
    {
1772
      /* For WKD and DANE we insert origin information also for the
1773
       * key but we don't record the URL because we have have no use
1774
       * for that: An update using a keyserver has higher precedence
1775
       * and will thus update this origin info.  For refresh using WKD
1776
       * or DANE we need to go via the User ID anyway.  Recall that we
1777
       * are only inserting a new key. */
1778
0
      pk->keyorg = origin;
1779
0
      pk->keyupdate = curtime;
1780
0
    }
1781
27
  else if (origin == KEYORG_KS && url)
1782
0
    {
1783
      /* If the key was retrieved from a keyserver using a fingerprint
1784
       * request we add the meta information.  Note that the use of a
1785
       * fingerprint needs to be enforced by the caller of the import
1786
       * function.  This is commonly triggered by verifying a modern
1787
       * signature which has an Issuer Fingerprint signature
1788
       * subpacket.  */
1789
0
      pk->keyorg = origin;
1790
0
      pk->keyupdate = curtime;
1791
0
      xfree (pk->updateurl);
1792
0
      pk->updateurl = xtrystrdup (url);
1793
0
      if (!pk->updateurl)
1794
0
        return gpg_error_from_syserror ();
1795
0
    }
1796
27
  else if (origin == KEYORG_FILE)
1797
0
    {
1798
0
      pk->keyorg = origin;
1799
0
      pk->keyupdate = curtime;
1800
0
    }
1801
27
  else if (origin == KEYORG_URL)
1802
0
    {
1803
0
      pk->keyorg = origin;
1804
0
      pk->keyupdate = curtime;
1805
0
      if (url)
1806
0
        {
1807
0
          xfree (pk->updateurl);
1808
0
          pk->updateurl = xtrystrdup (url);
1809
0
          if (!pk->updateurl)
1810
0
            return gpg_error_from_syserror ();
1811
0
        }
1812
0
    }
1813
1814
27
  return 0;
1815
27
}
1816
1817
1818
/* Insert a key origin into a user id packet.  */
1819
static gpg_error_t
1820
insert_key_origin_uid (PKT_user_id *uid, u32 curtime,
1821
                       int origin, const char *url)
1822
1823
31
{
1824
31
  if (origin == KEYORG_WKD || origin == KEYORG_DANE)
1825
0
    {
1826
      /* We insert origin information on a UID only when we received
1827
       * them via the Web Key Directory or a DANE record.  The key we
1828
       * receive here from the WKD has been filtered to contain only
1829
       * the user ID as looked up in the WKD.  For a DANE origin
1830
       * this should also be the case.  Thus we will see here only one
1831
       * user id.  */
1832
0
      uid->keyorg = origin;
1833
0
      uid->keyupdate = curtime;
1834
0
      if (url)
1835
0
        {
1836
0
          xfree (uid->updateurl);
1837
0
          uid->updateurl = xtrystrdup (url);
1838
0
          if (!uid->updateurl)
1839
0
            return gpg_error_from_syserror ();
1840
0
        }
1841
0
    }
1842
31
  else if (origin == KEYORG_KS && url)
1843
0
    {
1844
      /* If the key was retrieved from a keyserver using a fingerprint
1845
       * request we mark that also in the user ID.  However we do not
1846
       * store the keyserver URL in the UID.  A later update (merge)
1847
       * from a more trusted source will replace this info.  */
1848
0
      uid->keyorg = origin;
1849
0
      uid->keyupdate = curtime;
1850
0
    }
1851
31
  else if (origin == KEYORG_FILE)
1852
0
    {
1853
0
      uid->keyorg = origin;
1854
0
      uid->keyupdate = curtime;
1855
0
    }
1856
31
  else if (origin == KEYORG_URL)
1857
0
    {
1858
0
      uid->keyorg = origin;
1859
0
      uid->keyupdate = curtime;
1860
0
    }
1861
1862
31
  return 0;
1863
31
}
1864
1865
1866
/* Apply meta data to KEYBLOCK.  This sets the origin of the key to
1867
 * ORIGIN and the updateurl to URL.  Note that this function is only
1868
 * used for a new key, that is not when we are merging keys.  */
1869
static gpg_error_t
1870
insert_key_origin (kbnode_t keyblock, int origin, const char *url)
1871
27
{
1872
27
  gpg_error_t err;
1873
27
  kbnode_t node;
1874
27
  u32 curtime = make_timestamp ();
1875
1876
136
  for (node = keyblock; node; node = node->next)
1877
109
    {
1878
109
      if (is_deleted_kbnode (node))
1879
0
        ;
1880
109
      else if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1881
27
        {
1882
27
          err = insert_key_origin_pk (node->pkt->pkt.public_key, curtime,
1883
27
                                      origin, url);
1884
27
          if (err)
1885
0
            return err;
1886
27
        }
1887
82
      else if (node->pkt->pkttype == PKT_USER_ID)
1888
27
        {
1889
27
          err = insert_key_origin_uid (node->pkt->pkt.user_id, curtime,
1890
27
                                       origin, url);
1891
27
          if (err)
1892
0
            return err;
1893
27
        }
1894
109
    }
1895
1896
27
  return 0;
1897
27
}
1898
1899
1900
/* Update meta data on KEYBLOCK.  This updates the key origin on the
1901
 * public key according to ORIGIN and URL.  The UIDs are already
1902
 * updated when this function is called.  */
1903
static gpg_error_t
1904
update_key_origin (kbnode_t keyblock, u32 curtime, int origin, const char *url)
1905
2.85k
{
1906
2.85k
  PKT_public_key *pk;
1907
1908
2.85k
  log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
1909
2.85k
  pk = keyblock->pkt->pkt.public_key;
1910
1911
2.85k
  if (pk->keyupdate > curtime)
1912
0
    ; /* Don't do it for a time warp.  */
1913
2.85k
  else if (origin == KEYORG_WKD || origin == KEYORG_DANE)
1914
0
    {
1915
      /* We only update the origin info if they either have never been
1916
       * set or are the origin was the same as the new one.  If this
1917
       * is WKD we also update the UID to show from which user id this
1918
       * was updated.  */
1919
0
      if (!pk->keyorg || pk->keyorg == KEYORG_WKD || pk->keyorg == KEYORG_DANE)
1920
0
        {
1921
0
          pk->keyorg = origin;
1922
0
          pk->keyupdate = curtime;
1923
0
          xfree (pk->updateurl);
1924
0
          pk->updateurl = NULL;
1925
0
          if (origin == KEYORG_WKD && url)
1926
0
            {
1927
0
              pk->updateurl = xtrystrdup (url);
1928
0
              if (!pk->updateurl)
1929
0
                return gpg_error_from_syserror ();
1930
0
            }
1931
0
        }
1932
0
    }
1933
2.85k
  else if (origin == KEYORG_KS)
1934
0
    {
1935
      /* All updates from a keyserver are considered to have the
1936
       * freshed key.  Thus we always set the new key origin.  */
1937
0
      pk->keyorg = origin;
1938
0
      pk->keyupdate = curtime;
1939
0
      xfree (pk->updateurl);
1940
0
      pk->updateurl = NULL;
1941
0
      if (url)
1942
0
        {
1943
0
          pk->updateurl = xtrystrdup (url);
1944
0
          if (!pk->updateurl)
1945
0
            return gpg_error_from_syserror ();
1946
0
        }
1947
0
    }
1948
2.85k
  else if (origin == KEYORG_FILE)
1949
0
    {
1950
      /* Updates from a file are considered to be fresh.  */
1951
0
      pk->keyorg = origin;
1952
0
      pk->keyupdate = curtime;
1953
0
      xfree (pk->updateurl);
1954
0
      pk->updateurl = NULL;
1955
0
    }
1956
2.85k
  else if (origin == KEYORG_URL)
1957
0
    {
1958
      /* Updates from a URL are considered to be fresh.  */
1959
0
      pk->keyorg = origin;
1960
0
      pk->keyupdate = curtime;
1961
0
      xfree (pk->updateurl);
1962
0
      pk->updateurl = NULL;
1963
0
      if (url)
1964
0
        {
1965
0
          pk->updateurl = xtrystrdup (url);
1966
0
          if (!pk->updateurl)
1967
0
            return gpg_error_from_syserror ();
1968
0
        }
1969
0
    }
1970
1971
2.85k
  return 0;
1972
2.85k
}
1973
1974
1975
/*
1976
 * Try to import one keyblock. Return an error only in serious cases,
1977
 * but never for an invalid keyblock.  It uses log_error to increase
1978
 * the internal errorcount, so that invalid input can be detected by
1979
 * programs which called gpg.  If SILENT is no messages are printed -
1980
 * even most error messages are suppressed.  ORIGIN is the origin of
1981
 * the key (0 for unknown) and URL the corresponding URL.  FROM_SK
1982
 * indicates that the key has been made from a secret key.  If R_SAVED
1983
 * is not NULL a boolean will be stored indicating whether the
1984
 * keyblock has valid parts.  Unless OTHERREVSIGS is NULL it is
1985
 * updated with encountered new revocation signatures.
1986
 */
1987
static gpg_error_t
1988
import_one_real (ctrl_t ctrl,
1989
                 kbnode_t keyblock, struct import_stats_s *stats,
1990
                 unsigned char **fpr, size_t *fpr_len, unsigned int options,
1991
                 int from_sk, int silent,
1992
                 import_screener_t screener, void *screener_arg,
1993
                 int origin, const char *url, int *r_valid,
1994
                 kbnode_t *otherrevsigs)
1995
13.3k
{
1996
13.3k
  gpg_error_t err = 0;
1997
13.3k
  PKT_public_key *pk;
1998
13.3k
  kbnode_t node, uidnode;
1999
13.3k
  kbnode_t keyblock_orig = NULL;
2000
13.3k
  byte fpr2[MAX_FINGERPRINT_LEN];
2001
13.3k
  size_t fpr2len;
2002
13.3k
  u32 keyid[2];
2003
13.3k
  int new_key = 0;
2004
13.3k
  int mod_key = 0;
2005
13.3k
  int same_key = 0;
2006
13.3k
  int non_self_or_utk = 0;
2007
13.3k
  char pkstrbuf[PUBKEY_STRING_SIZE];
2008
13.3k
  int merge_keys_done = 0;
2009
13.3k
  int any_filter = 0;
2010
13.3k
  KEYDB_HANDLE hd = NULL;
2011
2012
13.3k
  if (r_valid)
2013
1.41k
    *r_valid = 0;
2014
2015
  /* If show-only is active we don't won't any extra output.  */
2016
13.3k
  if ((options & (IMPORT_SHOW | IMPORT_DRY_RUN)))
2017
0
    silent = 1;
2018
2019
  /* Get the key and print some info about it. */
2020
13.3k
  node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
2021
13.3k
  if (!node )
2022
0
    BUG();
2023
2024
13.3k
  pk = node->pkt->pkt.public_key;
2025
2026
13.3k
  fingerprint_from_pk (pk, fpr2, &fpr2len);
2027
13.3k
  if (MAX_FINGERPRINT_LEN > fpr2len)
2028
13.1k
    memset (fpr2+fpr2len, 0, MAX_FINGERPRINT_LEN - fpr2len);
2029
13.3k
  keyid_from_pk( pk, keyid );
2030
13.3k
  uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
2031
2032
13.3k
  if (opt.verbose && !opt.interactive && !silent && !from_sk)
2033
0
    {
2034
      /* Note that we do not print this info in FROM_SK mode
2035
       * because import_secret_one already printed that.  */
2036
0
      log_info ("pub  %s/%s %s  ",
2037
0
                pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
2038
0
                keystr_from_pk(pk), datestr_from_pk(pk) );
2039
0
      if (uidnode)
2040
0
        print_utf8_buffer (log_get_stream (),
2041
0
                           uidnode->pkt->pkt.user_id->name,
2042
0
                           uidnode->pkt->pkt.user_id->len );
2043
0
      log_printf ("\n");
2044
0
    }
2045
2046
2047
13.3k
  if (!uidnode)
2048
2.98k
    {
2049
2.98k
      if (!silent)
2050
2.98k
        log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
2051
2.98k
      return 0;
2052
2.98k
    }
2053
2054
10.4k
  if (screener && screener (keyblock, screener_arg))
2055
0
    {
2056
0
      log_error (_("key %s: %s\n"), keystr_from_pk (pk),
2057
0
                 _("rejected by import screener"));
2058
0
      return 0;
2059
0
    }
2060
2061
10.4k
  if (opt.interactive && !silent)
2062
0
    {
2063
0
      if (is_status_enabled())
2064
0
        print_import_check (pk, uidnode->pkt->pkt.user_id);
2065
0
      merge_keys_and_selfsig (ctrl, keyblock);
2066
0
      tty_printf ("\n");
2067
0
      show_basic_key_info (ctrl, keyblock, from_sk);
2068
0
      tty_printf ("\n");
2069
0
      if (!cpr_get_answer_is_yes ("import.okay",
2070
0
                                  "Do you want to import this key? (y/N) "))
2071
0
        return 0;
2072
0
    }
2073
2074
  /* Remove all non-self-sigs if requested.  Note that this is a NOP if
2075
   * that option has been globally set but we may also be called
2076
   * latter with the already parsed keyblock and a locally changed
2077
   * option.  This is why we need to remove them here as well.  */
2078
10.4k
  if ((options & IMPORT_SELF_SIGS_ONLY))
2079
0
    remove_all_non_self_sigs (&keyblock, keyid);
2080
2081
  /* Remove or collapse the user ids.  */
2082
10.4k
  if ((options & IMPORT_COLLAPSE_UIDS))
2083
0
    collapse_uids (&keyblock);
2084
2085
10.4k
  if ((options & IMPORT_COLLAPSE_SUBKEYS))
2086
0
    collapse_subkeys (&keyblock);
2087
2088
  /* Clean the key that we're about to import, to cut down on things
2089
     that we have to clean later.  This has no practical impact on the
2090
     end result, but does result in less logging which might confuse
2091
     the user. */
2092
10.4k
  if ((options & IMPORT_CLEAN))
2093
0
    {
2094
0
      merge_keys_and_selfsig (ctrl, keyblock);
2095
0
      clean_all_uids (ctrl, keyblock,
2096
0
                      opt.verbose,
2097
0
                      (options&IMPORT_MINIMAL)? EXPORT_MINIMAL : 0,
2098
0
                      NULL, NULL);
2099
0
      clean_all_subkeys (ctrl, keyblock, opt.verbose, KEY_CLEAN_NONE,
2100
0
                         NULL, NULL);
2101
0
    }
2102
2103
10.4k
  clear_kbnode_flags( keyblock );
2104
2105
10.4k
  if ((options&IMPORT_REPAIR_PKS_SUBKEY_BUG)
2106
0
      && fix_pks_corruption (ctrl, keyblock)
2107
0
      && opt.verbose)
2108
10.4k
    log_info (_("key %s: PKS subkey corruption repaired\n"),
2109
0
              keystr_from_pk(pk));
2110
2111
10.4k
  if ((options & IMPORT_REPAIR_KEYS))
2112
10.4k
    key_check_all_keysigs (ctrl, 1, keyblock, 0, 0);
2113
2114
10.4k
  if (chk_self_sigs (ctrl, keyblock, keyid, &non_self_or_utk))
2115
21
    return 0;  /* Invalid keyblock - error already printed.  */
2116
2117
  /* If the imported key is marked as ultimately trusted key (using
2118
   * --trusted-key), we set the flag so that we can later set the
2119
   * revalidation mark.  */
2120
10.3k
  if (!non_self_or_utk)
2121
3.60k
    {
2122
      /* Make sure the trustdb is initialized so that the UTK list is
2123
       * available.  */
2124
3.60k
      init_trustdb (ctrl, 1);
2125
3.60k
      if (tdb_keyid_is_utk (keyid))
2126
0
        non_self_or_utk = 2;
2127
3.60k
    }
2128
2129
  /* If we allow such a thing, mark unsigned uids as valid */
2130
10.3k
  if (opt.allow_non_selfsigned_uid)
2131
0
    {
2132
0
      for (node=keyblock; node; node = node->next )
2133
0
        if (node->pkt->pkttype == PKT_USER_ID
2134
0
            && !(node->flag & NODE_GOOD_SELFSIG)
2135
0
            && !(node->flag & NODE_BAD_SELFSIG) )
2136
0
          {
2137
0
            char *user=utf8_to_native(node->pkt->pkt.user_id->name,
2138
0
                                      node->pkt->pkt.user_id->len,0);
2139
            /* Fake a good signature status for the user id.  */
2140
0
            node->flag |= NODE_GOOD_SELFSIG;
2141
0
            log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
2142
0
                      keystr_from_pk(pk),user);
2143
0
            xfree(user);
2144
0
    }
2145
0
    }
2146
2147
  /* Delete invalid parts and bail out if there are no user ids left.  */
2148
10.3k
  if (!delete_inv_parts (ctrl, keyblock, keyid, options, otherrevsigs))
2149
7.24k
    {
2150
7.24k
      if (!silent)
2151
7.24k
        {
2152
7.24k
          log_error ( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
2153
7.24k
          if (!opt.quiet)
2154
7.24k
            log_info(_("this may be caused by a missing self-signature\n"));
2155
7.24k
        }
2156
7.24k
      stats->no_user_id++;
2157
7.24k
      return 0;
2158
7.24k
    }
2159
2160
  /* Get rid of deleted nodes.  */
2161
3.14k
  commit_kbnode (&keyblock);
2162
2163
  /* Apply import filter.  */
2164
3.14k
  if (import_filter.keep_uid)
2165
0
    {
2166
0
      apply_keep_uid_filter (ctrl, keyblock, import_filter.keep_uid);
2167
0
      commit_kbnode (&keyblock);
2168
0
      any_filter = 1;
2169
0
    }
2170
3.14k
  if (import_filter.drop_sig)
2171
0
    {
2172
0
      apply_drop_sig_filter (ctrl, keyblock, import_filter.drop_sig);
2173
0
      commit_kbnode (&keyblock);
2174
0
      any_filter = 1;
2175
0
    }
2176
2177
  /* If we ran any filter we need to check that at least one user id
2178
   * is left in the keyring.  Note that we do not use log_error in
2179
   * this case. */
2180
3.14k
  if (any_filter && !any_uid_left (keyblock))
2181
0
    {
2182
0
      if (!opt.quiet )
2183
0
        log_info ( _("key %s: no valid user IDs\n"), keystr_from_pk (pk));
2184
0
      stats->no_user_id++;
2185
0
      return 0;
2186
0
    }
2187
2188
  /* The keyblock is valid and ready for real import.  */
2189
3.14k
  if (r_valid)
2190
59
    *r_valid = 1;
2191
2192
  /* Show the key in the form it is merged or inserted.  We skip this
2193
   * if "import-export" is also active without --armor or the output
2194
   * file has explicily been given. */
2195
3.14k
  if ((options & IMPORT_SHOW)
2196
0
      && !((options & IMPORT_EXPORT) && !opt.armor && !opt.outfile))
2197
0
    {
2198
0
      merge_keys_and_selfsig (ctrl, keyblock);
2199
0
      merge_keys_done = 1;
2200
      /* Note that we do not want to show the validity because the key
2201
       * has not yet imported.  */
2202
0
      err = list_keyblock_direct (ctrl, keyblock, from_sk, 0,
2203
0
                            opt.fingerprint || opt.with_fingerprint, 1);
2204
0
      es_fflush (es_stdout);
2205
0
      no_usable_encr_subkeys_warning (keyblock);
2206
0
      if (err)
2207
0
        goto leave;
2208
0
    }
2209
2210
  /* Write the keyblock to the output and do not actually import.  */
2211
3.14k
  if ((options & IMPORT_EXPORT))
2212
0
    {
2213
0
      if (!merge_keys_done)
2214
0
        {
2215
0
          merge_keys_and_selfsig (ctrl, keyblock);
2216
0
          merge_keys_done = 1;
2217
0
        }
2218
0
      err = write_keyblock_to_output (keyblock, opt.armor, opt.export_options);
2219
0
      goto leave;
2220
0
    }
2221
2222
3.14k
  if (opt.dry_run || (options & IMPORT_DRY_RUN))
2223
0
    goto leave;
2224
2225
  /* Do we have this key already in one of our pubrings ? */
2226
3.14k
  err = get_keyblock_byfpr_fast (ctrl, &keyblock_orig, &hd,
2227
3.14k
                                 1 /*primary only */,
2228
3.14k
                                 fpr2, fpr2len, 1/*locked*/);
2229
3.14k
  if ((err
2230
27
       && gpg_err_code (err) != GPG_ERR_NO_PUBKEY
2231
0
       && gpg_err_code (err) != GPG_ERR_UNUSABLE_PUBKEY)
2232
3.14k
      || !hd)
2233
0
    {
2234
      /* The !hd above is to catch a misbehaving function which
2235
       * returns NO_PUBKEY for failing to allocate a handle.  */
2236
0
      if (!silent)
2237
0
        log_error (_("key %s: public key not found: %s\n"),
2238
0
                   keystr(keyid), gpg_strerror (err));
2239
0
    }
2240
3.14k
  else if (err && ((opt.import_options|options)&IMPORT_MERGE_ONLY) )
2241
0
    {
2242
0
      if (opt.verbose && !silent )
2243
0
        log_info( _("key %s: new key - skipped\n"), keystr(keyid));
2244
0
      err = 0;
2245
0
      stats->skipped_new_keys++;
2246
0
    }
2247
3.14k
  else if (err)  /* Insert this key. */
2248
27
    {
2249
      /* Note: ERR can only be NO_PUBKEY or UNUSABLE_PUBKEY.  */
2250
27
      int n_sigs_cleaned, n_uids_cleaned;
2251
2252
27
      err = keydb_locate_writable (hd);
2253
27
      if (err)
2254
0
        {
2255
0
          log_error (_("no writable keyring found: %s\n"), gpg_strerror (err));
2256
0
          err = gpg_error (GPG_ERR_GENERAL);
2257
0
          goto leave;
2258
0
  }
2259
27
      if (opt.verbose > 1 )
2260
27
        log_info (_("writing to '%s'\n"), keydb_get_resource_name (hd) );
2261
2262
27
      if ((options & IMPORT_CLEAN))
2263
0
        {
2264
0
          merge_keys_and_selfsig (ctrl, keyblock);
2265
0
          clean_all_uids (ctrl, keyblock, opt.verbose,
2266
0
                          (options&IMPORT_MINIMAL)? EXPORT_MINIMAL : 0,
2267
0
                          &n_uids_cleaned,&n_sigs_cleaned);
2268
0
          clean_all_subkeys (ctrl, keyblock, opt.verbose, KEY_CLEAN_NONE,
2269
0
                             NULL, NULL);
2270
0
        }
2271
2272
      /* Unless we are in restore mode apply meta data to the
2273
       * keyblock.  Note that this will never change the first packet
2274
       * and thus the address of KEYBLOCK won't change.  */
2275
27
      if ( !(options & IMPORT_RESTORE) )
2276
27
        {
2277
27
          err = insert_key_origin (keyblock, origin, url);
2278
27
          if (err)
2279
0
            {
2280
0
              log_error ("insert_key_origin failed: %s\n", gpg_strerror (err));
2281
0
              err = gpg_error (GPG_ERR_GENERAL);
2282
0
              goto leave;
2283
0
            }
2284
27
        }
2285
2286
27
      err = keydb_insert_keyblock (hd, keyblock);
2287
27
      if (err)
2288
27
        log_error (_("error writing keyring '%s': %s\n"),
2289
0
                   keydb_get_resource_name (hd), gpg_strerror (err));
2290
27
      else if (!(opt.import_options & IMPORT_KEEP_OWNERTTRUST))
2291
27
        {
2292
          /* This should not be possible since we delete the
2293
             ownertrust when a key is deleted, but it can happen if
2294
             the keyring and trustdb are out of sync.  It can also
2295
             be made to happen with the trusted-key command and by
2296
             importing and locally exported key. */
2297
2298
27
          clear_ownertrusts (ctrl, pk);
2299
27
          if (non_self_or_utk)
2300
6
            revalidation_mark (ctrl);
2301
27
        }
2302
2303
      /* Release the handle and thus unlock the keyring asap.  */
2304
27
      keydb_release (hd);
2305
27
      hd = NULL;
2306
2307
      /* We are ready.  */
2308
27
      if (!err && !opt.quiet && !silent)
2309
27
        {
2310
27
          char *p = get_user_id_byfpr_native (ctrl, fpr2, fpr2len);
2311
27
          log_info (_("key %s: public key \"%s\" imported\n"),
2312
27
                    keystr(keyid), p);
2313
27
          xfree(p);
2314
27
        }
2315
27
      if (!err && is_status_enabled())
2316
0
        {
2317
0
          char *us = get_long_user_id_string (ctrl, keyid);
2318
0
          write_status_text( STATUS_IMPORTED, us );
2319
0
          xfree(us);
2320
0
          print_import_ok (pk, 1);
2321
0
        }
2322
27
      if (!err)
2323
27
        {
2324
27
          stats->imported++;
2325
27
          new_key = 1;
2326
27
        }
2327
27
    }
2328
3.12k
  else /* Key already exists - merge.  */
2329
3.12k
    {
2330
3.12k
      int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
2331
3.12k
      u32 curtime = make_timestamp ();
2332
2333
      /* Compare the original against the new key; just to be sure nothing
2334
       * weird is going on */
2335
3.12k
      if (cmp_public_keys (keyblock_orig->pkt->pkt.public_key, pk))
2336
19
        {
2337
19
          if (!silent)
2338
19
            log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
2339
19
          goto leave;
2340
19
        }
2341
2342
      /* Make sure the original direct key sigs are all sane.  */
2343
3.10k
      n_sigs_cleaned = fix_bad_direct_key_sigs (ctrl, keyblock_orig, keyid);
2344
3.10k
      if (n_sigs_cleaned)
2345
521
        commit_kbnode (&keyblock_orig);
2346
2347
      /* Try to merge KEYBLOCK into KEYBLOCK_ORIG.  */
2348
3.10k
      clear_kbnode_flags( keyblock_orig );
2349
3.10k
      clear_kbnode_flags( keyblock );
2350
3.10k
      n_uids = n_sigs = n_subk = n_uids_cleaned = 0;
2351
3.10k
      err = merge_blocks (ctrl, options, keyblock_orig, keyblock, keyid,
2352
3.10k
                          curtime, origin, url,
2353
3.10k
                          &n_uids, &n_sigs, &n_subk );
2354
3.10k
      if (err)
2355
0
        goto leave;
2356
2357
      /* Clean the final keyblock again if requested.  we can't do
2358
       * this if only self-signatures are imported; see bug #4628.  */
2359
3.10k
      if ((options & IMPORT_CLEAN)
2360
0
          && !(options & IMPORT_SELF_SIGS_ONLY))
2361
0
        {
2362
0
          merge_keys_and_selfsig (ctrl, keyblock_orig);
2363
0
          clean_all_uids (ctrl, keyblock_orig, opt.verbose,
2364
0
                          (options&IMPORT_MINIMAL)? EXPORT_MINIMAL : 0,
2365
0
                          &n_uids_cleaned,&n_sigs_cleaned);
2366
0
          clean_all_subkeys (ctrl, keyblock_orig, opt.verbose, KEY_CLEAN_NONE,
2367
0
                             NULL, NULL);
2368
0
        }
2369
2370
3.10k
      if (n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned
2371
243
          || (options & IMPORT_FORCE_UPDATE))
2372
2.85k
        {
2373
          /* Unless we are in restore mode apply meta data to the
2374
           * keyblock.  Note that this will never change the first packet
2375
           * and thus the address of KEYBLOCK won't change.  */
2376
2.85k
          if ( !(options & IMPORT_RESTORE) )
2377
2.85k
            {
2378
2.85k
              err = update_key_origin (keyblock_orig, curtime, origin, url);
2379
2.85k
              if (err)
2380
0
                {
2381
0
                  log_error ("update_key_origin failed: %s\n",
2382
0
                             gpg_strerror (err));
2383
0
                  goto leave;
2384
0
                }
2385
2.85k
            }
2386
2387
2.85k
          mod_key = 1;
2388
          /* KEYBLOCK_ORIG has been updated; write */
2389
2.85k
          err = keydb_update_keyblock (ctrl, hd, keyblock_orig);
2390
2.85k
          if (err)
2391
2.85k
            log_error (_("error writing keyring '%s': %s\n"),
2392
0
                       keydb_get_resource_name (hd), gpg_strerror (err));
2393
2.85k
          else if (non_self_or_utk)
2394
1.60k
            revalidation_mark (ctrl);
2395
2396
          /* Release the handle and thus unlock the keyring asap.  */
2397
2.85k
          keydb_release (hd);
2398
2.85k
          hd = NULL;
2399
2400
          /* We are ready.  Print and update stats if we got no error.
2401
           * An error here comes from writing the keyblock and thus
2402
           * very likely means that no update happened.  */
2403
2.85k
          if (!err && !opt.quiet && !silent)
2404
2.85k
            {
2405
2.85k
              char *p = get_user_id_byfpr_native (ctrl, fpr2, fpr2len);
2406
2.85k
              if (n_uids == 1 )
2407
2.85k
                log_info( _("key %s: \"%s\" 1 new user ID\n"),
2408
4
                          keystr(keyid),p);
2409
2.85k
              else if (n_uids )
2410
2.85k
                log_info( _("key %s: \"%s\" %d new user IDs\n"),
2411
0
                          keystr(keyid),p,n_uids);
2412
2.85k
              if (n_sigs == 1 )
2413
2.85k
                log_info( _("key %s: \"%s\" 1 new signature\n"),
2414
2.00k
                          keystr(keyid), p);
2415
856
              else if (n_sigs )
2416
856
                log_info( _("key %s: \"%s\" %d new signatures\n"),
2417
843
                          keystr(keyid), p, n_sigs );
2418
2.85k
              if (n_subk == 1 )
2419
2.85k
                log_info( _("key %s: \"%s\" 1 new subkey\n"),
2420
365
                          keystr(keyid), p);
2421
2.49k
              else if (n_subk )
2422
2.49k
                log_info( _("key %s: \"%s\" %d new subkeys\n"),
2423
0
                          keystr(keyid), p, n_subk );
2424
2.85k
              if (n_sigs_cleaned==1)
2425
2.85k
                log_info(_("key %s: \"%s\" %d signature cleaned\n"),
2426
427
                         keystr(keyid),p,n_sigs_cleaned);
2427
2.43k
              else if (n_sigs_cleaned)
2428
2.43k
                log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
2429
94
                         keystr(keyid),p,n_sigs_cleaned);
2430
2.85k
              if (n_uids_cleaned==1)
2431
2.85k
                log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
2432
0
                         keystr(keyid),p,n_uids_cleaned);
2433
2.85k
              else if (n_uids_cleaned)
2434
2.85k
                log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
2435
0
                         keystr(keyid),p,n_uids_cleaned);
2436
2.85k
              xfree(p);
2437
2.85k
            }
2438
2439
2.85k
          if (!err)
2440
2.85k
            {
2441
2.85k
              stats->n_uids +=n_uids;
2442
2.85k
              stats->n_sigs +=n_sigs;
2443
2.85k
              stats->n_subk +=n_subk;
2444
2.85k
              stats->n_sigs_cleaned +=n_sigs_cleaned;
2445
2.85k
              stats->n_uids_cleaned +=n_uids_cleaned;
2446
2447
2.85k
              if (is_status_enabled () && !silent)
2448
0
                print_import_ok (pk, ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
2449
2.85k
            }
2450
2.85k
  }
2451
243
      else
2452
243
        {
2453
          /* Release the handle and thus unlock the keyring asap.  */
2454
243
          keydb_release (hd);
2455
243
          hd = NULL;
2456
2457
          /* FIXME: We do not track the time we last checked a key for
2458
           * updates.  To do this we would need to rewrite even the
2459
           * keys which have no changes.  Adding this would be useful
2460
           * for the automatic update of expired keys via the WKD in
2461
           * case the WKD still carries the expired key.  See
2462
           * get_best_pubkey_byname.  */
2463
243
          same_key = 1;
2464
243
          if (is_status_enabled ())
2465
0
            print_import_ok (pk, 0);
2466
2467
243
          if (!opt.quiet && !silent)
2468
243
            {
2469
243
              char *p = get_user_id_byfpr_native (ctrl, fpr2, fpr2len);
2470
243
              log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
2471
243
              xfree(p);
2472
243
            }
2473
2474
243
          stats->unchanged++;
2475
243
        }
2476
3.10k
    }
2477
2478
3.14k
 leave:
2479
3.14k
  keydb_release (hd);
2480
3.14k
  if (mod_key || new_key || same_key)
2481
3.12k
    {
2482
      /* A little explanation for this: we fill in the fingerprint
2483
         when importing keys as it can be useful to know the
2484
         fingerprint in certain keyserver-related cases (a keyserver
2485
         asked for a particular name, but the key doesn't have that
2486
         name).  However, in cases where we're importing more than
2487
         one key at a time, we cannot know which key to fingerprint.
2488
         In these cases, rather than guessing, we do not
2489
         fingerprinting at all, and we must hope the user ID on the
2490
         keys are useful.  Note that we need to do this for new
2491
         keys, merged keys and even for unchanged keys.  This is
2492
         required because for example the --auto-key-locate feature
2493
         may import an already imported key and needs to know the
2494
         fingerprint of the key in all cases.  */
2495
3.12k
      if (fpr)
2496
0
        {
2497
          /* Note that we need to compare against 0 here because
2498
             COUNT gets only incremented after returning from this
2499
             function.  */
2500
0
          if (!stats->count)
2501
0
            {
2502
0
              xfree (*fpr);
2503
0
              *fpr = fingerprint_from_pk (pk, NULL, fpr_len);
2504
0
            }
2505
0
          else if (origin != KEYORG_WKD)
2506
0
            {
2507
0
              xfree (*fpr);
2508
0
              *fpr = NULL;
2509
0
            }
2510
0
        }
2511
3.12k
    }
2512
2513
  /* Now that the key is definitely incorporated into the keydb, we
2514
     need to check if a designated revocation is present or if the
2515
     prefs are not rational so we can warn the user. */
2516
2517
3.14k
  if (mod_key)
2518
2.85k
    {
2519
2.85k
      revocation_present (ctrl, keyblock_orig);
2520
2.85k
      if (!from_sk && have_secret_key_with_kid (ctrl, keyid))
2521
0
        check_prefs (ctrl, keyblock_orig);
2522
2.85k
    }
2523
289
  else if (new_key)
2524
27
    {
2525
27
      revocation_present (ctrl, keyblock);
2526
27
      if (!from_sk && have_secret_key_with_kid (ctrl, keyid))
2527
0
        check_prefs (ctrl, keyblock);
2528
27
    }
2529
2530
3.14k
  release_kbnode( keyblock_orig );
2531
2532
3.14k
  return err;
2533
3.14k
}
2534
2535
2536
/* Wrapper around import_one_real to retry the import in some cases.  */
2537
static gpg_error_t
2538
import_one (ctrl_t ctrl,
2539
            kbnode_t keyblock, struct import_stats_s *stats,
2540
      unsigned char **fpr, size_t *fpr_len, unsigned int options,
2541
      int from_sk, int silent,
2542
            import_screener_t screener, void *screener_arg,
2543
            int origin, const char *url, int *r_valid)
2544
13.3k
{
2545
13.3k
  gpg_error_t err;
2546
13.3k
  kbnode_t otherrevsigs = NULL;
2547
13.3k
  kbnode_t node;
2548
2549
13.3k
  err = import_one_real (ctrl, keyblock, stats, fpr, fpr_len, options,
2550
13.3k
                         from_sk, silent, screener, screener_arg,
2551
13.3k
                         origin, url, r_valid, &otherrevsigs);
2552
13.3k
  if (gpg_err_code (err) == GPG_ERR_TOO_LARGE
2553
0
      && gpg_err_source (err) == GPG_ERR_SOURCE_KEYBOX
2554
0
      && ((options & (IMPORT_SELF_SIGS_ONLY | IMPORT_CLEAN))
2555
0
          != (IMPORT_SELF_SIGS_ONLY | IMPORT_CLEAN)))
2556
0
    {
2557
      /* We hit the maximum image length.  Ask the wrapper to do
2558
       * everything again but this time with some extra options.  */
2559
0
      u32 keyid[2];
2560
2561
0
      keyid_from_pk (keyblock->pkt->pkt.public_key, keyid);
2562
0
      log_info ("key %s: keyblock too large, retrying with self-sigs-only\n",
2563
0
                keystr (keyid));
2564
0
      options |= IMPORT_SELF_SIGS_ONLY | IMPORT_CLEAN;
2565
0
      err = import_one_real (ctrl, keyblock, stats, fpr, fpr_len, options,
2566
0
                             from_sk, silent, screener, screener_arg,
2567
0
                             origin, url, r_valid, &otherrevsigs);
2568
0
    }
2569
2570
  /* Finally try to import other revocation certificates.  For example
2571
   * those of a former key appended to the current key.  */
2572
13.3k
  if (!err)
2573
13.3k
    {
2574
15.6k
      for (node = otherrevsigs; node; node = node->next)
2575
2.24k
        {
2576
2.24k
          log_info ("trying to import a revocation\n");
2577
2.24k
          import_revoke_cert (ctrl, node, options, stats);
2578
2.24k
        }
2579
13.3k
    }
2580
13.3k
  release_kbnode (otherrevsigs);
2581
13.3k
  return err;
2582
13.3k
}
2583
2584
2585
2586
/* Convert our internal secret key object into an S-expression.  PK is
2587
 * the public key.  R_CURVE received an sexp with the name of the
2588
 * curve; caller must free this.  R_SKEY will receive the result;
2589
 * caller must of course also free this.
2590
 *
2591
 * Note that this SEXP is only intended to be transferred to
2592
 * gpg-agent, which is not in actual use by any public key computation
2593
 * with libgcrypt.  For transfer, it omits (flags ...) part in the
2594
 * expression.  It is the gpg-agent which will composes the SEXP in
2595
 * use, adding required (flags ...) part.
2596
 */
2597
static gpg_error_t
2598
internal_skey_object_to_sexp (PKT_public_key *pk, gcry_sexp_t *r_curve,
2599
                              gcry_sexp_t *r_skey)
2600
0
{
2601
0
  gpg_error_t err;
2602
0
  int nskey;
2603
0
  int i, j;
2604
0
  membuf_t mbuf;
2605
0
  const char *curvename;
2606
0
  char *curvestr = NULL;
2607
0
  void *format_args[2*PUBKEY_MAX_NSKEY];
2608
2609
0
  *r_curve = NULL;
2610
0
  *r_skey = NULL;
2611
0
  init_membuf (&mbuf, 50);
2612
2613
0
  nskey = pubkey_get_nskey (pk->pubkey_algo);
2614
0
  if (!nskey || nskey > PUBKEY_MAX_NSKEY)
2615
0
    {
2616
0
      err = gpg_error (GPG_ERR_BAD_SECKEY);
2617
0
      log_error ("internal error: %s\n", gpg_strerror (err));
2618
0
      goto leave;
2619
0
    }
2620
2621
0
  put_membuf_str (&mbuf, "(skey");
2622
2623
0
  if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
2624
0
      || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
2625
0
      || pk->pubkey_algo == PUBKEY_ALGO_ECDH)
2626
0
    {
2627
      /* The ECC case.  */
2628
0
      curvestr = openpgp_oid_to_str (pk->pkey[0]);
2629
0
      if (!curvestr)
2630
0
        {
2631
0
          err = gpg_error_from_syserror ();
2632
0
          goto leave;
2633
0
        }
2634
2635
0
      curvename = openpgp_oid_to_curve (curvestr, 1);
2636
0
      gcry_sexp_release (*r_curve);
2637
0
      err = gcry_sexp_build (r_curve, NULL, "(curve %s)",
2638
0
                             curvename?curvename:curvestr);
2639
0
      if (err)
2640
0
        goto leave;
2641
2642
0
      j = 0;
2643
      /* Append the public key element Q.  */
2644
0
      put_membuf_str (&mbuf, " _ %m");
2645
0
      format_args[j++] = pk->pkey + 1;
2646
2647
      /* Append the secret key element D.  For ECDH we skip PKEY[2]
2648
       * because this holds the KEK which is not needed by gpg-agent.  */
2649
0
      i = pk->pubkey_algo == PUBKEY_ALGO_ECDH? 3 : 2;
2650
0
      if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
2651
0
        put_membuf_str (&mbuf, " e %m");
2652
0
      else
2653
0
        put_membuf_str (&mbuf, " _ %m");
2654
0
      format_args[j++] = pk->pkey + i;
2655
2656
      /* Simple hack to print a warning for an invalid key in case of
2657
       * cv25519.  We have only opaque MPIs here. */
2658
0
      if (pk->pubkey_algo == PUBKEY_ALGO_ECDH
2659
0
          && !strcmp (curvestr, "1.3.6.1.4.1.3029.1.5.1")
2660
0
          && !gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1)
2661
0
          && gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_OPAQUE))
2662
0
        {
2663
0
          const unsigned char *pp;
2664
0
          unsigned int nn;
2665
2666
0
          pp = gcry_mpi_get_opaque (pk->pkey[i], &nn);
2667
0
          nn = (nn+7)/8;
2668
0
          if (pp && nn && (pp[nn-1] & 7))
2669
0
            log_info ("warning: lower 3 bits of the secret key"
2670
0
                      " are not cleared\n");
2671
0
        }
2672
0
    }
2673
0
  else /* Standard case for the old (non-ECC) algorithms.  */
2674
0
    {
2675
0
      for (i=j=0; i < nskey; i++)
2676
0
        {
2677
0
          if (!pk->pkey[i])
2678
0
            continue; /* Protected keys only have NPKEY+1 elements.  */
2679
2680
0
          if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
2681
0
            put_membuf_str (&mbuf, " e %m");
2682
0
          else
2683
0
            put_membuf_str (&mbuf, " _ %m");
2684
0
          format_args[j++] = pk->pkey + i;
2685
0
        }
2686
0
    }
2687
0
  put_membuf_str (&mbuf, ")");
2688
0
  put_membuf (&mbuf, "", 1);
2689
2690
  /* Finally convert to an sexp and store that at R_SKEY.  */
2691
0
  {
2692
0
    char *format = get_membuf (&mbuf, NULL);
2693
0
    if (!format)
2694
0
      err = gpg_error_from_syserror ();
2695
0
    else
2696
0
      err = gcry_sexp_build_array (r_skey, NULL, format, format_args);
2697
0
    xfree (format);
2698
0
  }
2699
2700
0
 leave:
2701
0
  xfree (curvestr);
2702
0
  xfree (get_membuf (&mbuf, NULL));
2703
0
  return err;
2704
0
}
2705
2706
2707
static gpg_error_t
2708
build_classic_transfer_sexp (PKT_public_key *pk, gcry_sexp_t *result)
2709
0
{
2710
0
  gpg_error_t err;
2711
0
  gcry_sexp_t skey;
2712
0
  gcry_sexp_t prot = NULL;
2713
0
  gcry_sexp_t curve = NULL;
2714
0
  struct seckey_info *ski = pk->seckey_info;
2715
2716
0
  *result = NULL;
2717
2718
  /* Convert our internal secret key object into an S-expression.  */
2719
0
  err = internal_skey_object_to_sexp (pk, &curve, &skey);
2720
0
  if (err)
2721
0
    {
2722
0
      log_error ("error building skey array: %s\n", gpg_strerror (err));
2723
0
      goto leave;
2724
0
    }
2725
0
  log_assert (skey);
2726
2727
0
  if (ski->is_protected)
2728
0
    {
2729
0
      char countbuf[35];
2730
2731
      /* FIXME: Support AEAD */
2732
      /* Note that the IVLEN may be zero if we are working on a dummy
2733
       * key.  We can't express that in an S-expression and thus we
2734
       * send dummy data for the IV.  */
2735
0
      snprintf (countbuf, sizeof countbuf, "%lu",(unsigned long)ski->s2k.count);
2736
0
      err = gcry_sexp_build (&prot, NULL,
2737
0
                             " (protection %s %s %b %d %s %b %s)\n",
2738
0
                             ski->sha1chk? "sha1":"sum",
2739
0
                             openpgp_cipher_algo_name (ski->algo),
2740
0
                             ski->ivlen? (int)ski->ivlen:1,
2741
0
                             ski->ivlen? ski->iv: (const unsigned char*)"X",
2742
0
                             ski->s2k.mode,
2743
0
                             openpgp_md_algo_name (ski->s2k.hash_algo),
2744
0
                             (int)sizeof (ski->s2k.salt), ski->s2k.salt,
2745
0
                             countbuf);
2746
0
    }
2747
0
  else
2748
0
    err = gcry_sexp_build (&prot, NULL, " (protection none)\n");
2749
0
  if (err)
2750
0
    goto leave;
2751
2752
0
  err = gcry_sexp_build (result, NULL,
2753
0
                         "(openpgp-private-key\n"
2754
0
                         " (version %d)\n"
2755
0
                         " (algo %s)\n"
2756
0
                         " %S%S\n"
2757
0
                         " (csum %d)\n"
2758
0
                         " %S)\n",
2759
0
                         pk->version,
2760
0
                         openpgp_pk_algo_name (pk->pubkey_algo),
2761
0
                         curve, skey,
2762
0
                         (int)(unsigned long)ski->csum, prot);
2763
2764
0
 leave:
2765
0
  gcry_sexp_release (prot);
2766
0
  gcry_sexp_release (skey);
2767
0
  gcry_sexp_release (curve);
2768
0
  return err;
2769
0
}
2770
2771
2772
/* Transfer all the secret keys in SEC_KEYBLOCK to the gpg-agent.  The
2773
 * function prints diagnostics and returns an error code.  If BATCH is
2774
 * true the secret keys are stored by gpg-agent in the transfer format
2775
 * (i.e. no re-protection and aksing for passphrases). If ONLY_MARKED
2776
 * is set, only those nodes with flag NODE_TRANSFER_SECKEY are
2777
 * processed.  */
2778
gpg_error_t
2779
transfer_secret_keys (ctrl_t ctrl, struct import_stats_s *stats,
2780
                      kbnode_t sec_keyblock, int batch, int force,
2781
                      int only_marked)
2782
84
{
2783
84
  gpg_error_t err = 0;
2784
84
  void *kek = NULL;
2785
84
  size_t keklen;
2786
84
  kbnode_t ctx = NULL;
2787
84
  kbnode_t node;
2788
84
  PKT_public_key *main_pk, *pk;
2789
84
  struct seckey_info *ski;
2790
84
  gcry_sexp_t tmpsexp;
2791
84
  unsigned char *transferkey = NULL;
2792
84
  size_t transferkeylen;
2793
84
  gcry_cipher_hd_t cipherhd = NULL;
2794
84
  unsigned char *wrappedkey = NULL;
2795
84
  size_t wrappedkeylen;
2796
84
  char *cache_nonce = NULL;
2797
84
  int stub_key_skipped = 0;
2798
2799
  /* Get the current KEK.  */
2800
84
  err = agent_keywrap_key (ctrl, 0, &kek, &keklen);
2801
84
  if (err)
2802
84
    {
2803
84
      log_error ("error getting the KEK: %s\n", gpg_strerror (err));
2804
84
      goto leave;
2805
84
    }
2806
2807
  /* Prepare a cipher context.  */
2808
0
  err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
2809
0
                          GCRY_CIPHER_MODE_AESWRAP, 0);
2810
0
  if (!err)
2811
0
    err = gcry_cipher_setkey (cipherhd, kek, keklen);
2812
0
  if (err)
2813
0
    goto leave;
2814
0
  xfree (kek);
2815
0
  kek = NULL;
2816
2817
  /* Note: We need to use walk_kbnode so that we skip nodes which are
2818
   * marked as deleted.  */
2819
0
  main_pk = NULL;
2820
0
  while ((node = walk_kbnode (sec_keyblock, &ctx, 0)))
2821
0
    {
2822
0
      if (node->pkt->pkttype != PKT_SECRET_KEY
2823
0
          && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2824
0
        continue;
2825
0
      if (only_marked && !(node->flag & NODE_TRANSFER_SECKEY))
2826
0
        continue;
2827
0
      pk = node->pkt->pkt.public_key;
2828
0
      if (!main_pk)
2829
0
        main_pk = pk;
2830
2831
      /* Make sure the keyids are available.  */
2832
0
      keyid_from_pk (pk, NULL);
2833
0
      if (node->pkt->pkttype == PKT_SECRET_KEY)
2834
0
        {
2835
0
          pk->main_keyid[0] = pk->keyid[0];
2836
0
          pk->main_keyid[1] = pk->keyid[1];
2837
0
        }
2838
0
      else
2839
0
        {
2840
0
          pk->main_keyid[0] = main_pk->keyid[0];
2841
0
          pk->main_keyid[1] = main_pk->keyid[1];
2842
0
        }
2843
2844
2845
0
      ski = pk->seckey_info;
2846
0
      if (!ski)
2847
0
        BUG ();
2848
2849
0
      if (stats)
2850
0
        {
2851
0
          stats->count++;
2852
0
          stats->secret_read++;
2853
0
        }
2854
2855
      /* We ignore stub keys.  The way we handle them in other parts
2856
         of the code is by asking the agent whether any secret key is
2857
         available for a given keyblock and then concluding that we
2858
         have a secret key; all secret (sub)keys of the keyblock the
2859
         agent does not know of are then stub keys.  This works also
2860
         for card stub keys.  The learn command or the card-status
2861
         command may be used to check with the agent whether a card
2862
         has been inserted and a stub key is in turn generated by the
2863
         agent.  */
2864
0
      if (ski->s2k.mode == 1001 || ski->s2k.mode == 1002)
2865
0
        {
2866
0
          stub_key_skipped = 1;
2867
0
          continue;
2868
0
        }
2869
2870
0
      tmpsexp = NULL;
2871
0
      if (ski->s2k.mode == 1003)
2872
0
        {
2873
0
          const void *tmpbuf;
2874
0
          unsigned int tmpbuflen;
2875
0
          int npkey;
2876
2877
          /* Fixme: Check that the public key parameters in pkey match
2878
           *        those in the s-expression of the secret key.  */
2879
0
          npkey = pubkey_get_npkey (pk->pubkey_algo);
2880
0
          if (npkey+1 > PUBKEY_MAX_NSKEY)
2881
0
            err = gpg_error (GPG_ERR_BAD_SECKEY);
2882
0
          else if (!pk->pkey[npkey]
2883
0
                   || !gcry_mpi_get_flag (pk->pkey[npkey], GCRYMPI_FLAG_OPAQUE))
2884
0
            err = gpg_error (GPG_ERR_BAD_SECKEY);
2885
0
          else
2886
0
            {
2887
0
              tmpbuf = gcry_mpi_get_opaque (pk->pkey[npkey], &tmpbuflen);
2888
0
              tmpbuflen = (tmpbuflen +7)/8;  /* Fixup bits to bytes */
2889
0
              err = gcry_sexp_new (&tmpsexp, tmpbuf, tmpbuflen, 0);
2890
0
            }
2891
0
        }
2892
0
      else
2893
0
        err = build_classic_transfer_sexp (pk, &tmpsexp);
2894
2895
0
      xfree (transferkey);
2896
0
      transferkey = NULL;
2897
0
      if (!err)
2898
0
        err = make_canon_sexp_pad (tmpsexp, 1, &transferkey, &transferkeylen);
2899
0
      gcry_sexp_release (tmpsexp);
2900
0
      tmpsexp = NULL;
2901
0
      if (err)
2902
0
        {
2903
0
          log_error ("error building transfer key: %s\n", gpg_strerror (err));
2904
0
          goto leave;
2905
0
        }
2906
2907
      /* Wrap the key.  */
2908
0
      wrappedkeylen = transferkeylen + 8;
2909
0
      xfree (wrappedkey);
2910
0
      wrappedkey = xtrymalloc (wrappedkeylen);
2911
0
      if (!wrappedkey)
2912
0
        err = gpg_error_from_syserror ();
2913
0
      else
2914
0
        err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen,
2915
0
                                   transferkey, transferkeylen);
2916
0
      if (err)
2917
0
        goto leave;
2918
0
      xfree (transferkey);
2919
0
      transferkey = NULL;
2920
2921
      /* Send the wrapped key to the agent.  */
2922
0
      {
2923
0
        char *desc = gpg_format_keydesc (ctrl, pk, FORMAT_KEYDESC_IMPORT, 1);
2924
0
        err = agent_import_key (ctrl, desc, ski->s2k.mode == 1003,
2925
0
                                &cache_nonce,
2926
0
                                wrappedkey, wrappedkeylen, batch, force,
2927
0
        pk->keyid, pk->main_keyid, pk->pubkey_algo,
2928
0
                                pk->timestamp);
2929
0
        xfree (desc);
2930
0
      }
2931
0
      if (!err)
2932
0
        {
2933
0
          if (opt.verbose)
2934
0
            log_info (_("key %s: secret key imported\n"),
2935
0
                      keystr_from_pk_with_sub (main_pk, pk));
2936
0
          if (stats)
2937
0
            stats->secret_imported++;
2938
0
        }
2939
0
      else if ( gpg_err_code (err) == GPG_ERR_EEXIST )
2940
0
        {
2941
0
          if (opt.verbose)
2942
0
            log_info (_("key %s: secret key already exists\n"),
2943
0
                      keystr_from_pk_with_sub (main_pk, pk));
2944
0
          err = 0;
2945
0
          if (stats)
2946
0
            stats->secret_dups++;
2947
0
        }
2948
0
      else
2949
0
        {
2950
0
          log_error (_("key %s: error sending to agent: %s\n"),
2951
0
                     keystr_from_pk_with_sub (main_pk, pk),
2952
0
                     gpg_strerror (err));
2953
0
          if (gpg_err_code (err) == GPG_ERR_CANCELED
2954
0
              || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
2955
0
            break; /* Don't try the other subkeys.  */
2956
0
        }
2957
0
    }
2958
2959
0
  if (!err && stub_key_skipped)
2960
    /* We need to notify user how to migrate stub keys.  */
2961
0
    err = gpg_error (GPG_ERR_NOT_PROCESSED);
2962
2963
84
 leave:
2964
84
  xfree (cache_nonce);
2965
84
  xfree (wrappedkey);
2966
84
  xfree (transferkey);
2967
84
  gcry_cipher_close (cipherhd);
2968
84
  xfree (kek);
2969
84
  return err;
2970
0
}
2971
2972
2973
/* Walk a secret keyblock and produce a public keyblock out of it.
2974
 * Returns a new node or NULL on error.  Modifies the tag field of the
2975
 * nodes.  */
2976
static kbnode_t
2977
sec_to_pub_keyblock (kbnode_t sec_keyblock)
2978
1.41k
{
2979
1.41k
  kbnode_t pub_keyblock = NULL;
2980
1.41k
  kbnode_t ctx = NULL;
2981
1.41k
  kbnode_t secnode, pubnode;
2982
1.41k
  kbnode_t lastnode = NULL;
2983
1.41k
  unsigned int tag = 0;
2984
2985
  /* Set a tag to all nodes.  */
2986
15.8k
  for (secnode = sec_keyblock; secnode; secnode = secnode->next)
2987
14.4k
    secnode->tag = ++tag;
2988
2989
  /* Copy.  */
2990
15.8k
  while ((secnode = walk_kbnode (sec_keyblock, &ctx, 0)))
2991
14.4k
    {
2992
14.4k
      if (secnode->pkt->pkttype == PKT_SECRET_KEY
2993
13.0k
          || secnode->pkt->pkttype == PKT_SECRET_SUBKEY)
2994
2.12k
  {
2995
    /* Make a public key.  */
2996
2.12k
    PACKET *pkt;
2997
2.12k
          PKT_public_key *pk;
2998
2999
2.12k
    pkt = xtrycalloc (1, sizeof *pkt);
3000
2.12k
          pk = pkt? copy_public_key (NULL, secnode->pkt->pkt.public_key): NULL;
3001
2.12k
          if (!pk)
3002
0
            {
3003
0
              xfree (pkt);
3004
0
        release_kbnode (pub_keyblock);
3005
0
              return NULL;
3006
0
            }
3007
2.12k
    if (secnode->pkt->pkttype == PKT_SECRET_KEY)
3008
1.41k
      pkt->pkttype = PKT_PUBLIC_KEY;
3009
710
    else
3010
710
      pkt->pkttype = PKT_PUBLIC_SUBKEY;
3011
2.12k
    pkt->pkt.public_key = pk;
3012
3013
2.12k
    pubnode = new_kbnode (pkt);
3014
2.12k
  }
3015
12.3k
      else
3016
12.3k
  {
3017
12.3k
    pubnode = clone_kbnode (secnode);
3018
12.3k
  }
3019
14.4k
      pubnode->tag = secnode->tag;
3020
3021
14.4k
      if (!pub_keyblock)
3022
1.41k
        pub_keyblock = lastnode = pubnode;
3023
13.0k
      else
3024
13.0k
        {
3025
13.0k
          lastnode->next = pubnode;
3026
13.0k
          lastnode = pubnode;
3027
13.0k
        }
3028
14.4k
    }
3029
3030
1.41k
  return pub_keyblock;
3031
1.41k
}
3032
3033
3034
/* Delete all notes in the keyblock at R_KEYBLOCK which are not in
3035
 * PUB_KEYBLOCK.  Modifies the tags of both keyblock's nodes.  */
3036
static gpg_error_t
3037
resync_sec_with_pub_keyblock (kbnode_t *r_keyblock, kbnode_t pub_keyblock,
3038
                              kbnode_t *r_removedsecs)
3039
1.41k
{
3040
1.41k
  kbnode_t sec_keyblock = *r_keyblock;
3041
1.41k
  kbnode_t node, prevnode;
3042
1.41k
  unsigned int *taglist;
3043
1.41k
  unsigned int ntaglist, n;
3044
1.41k
  kbnode_t attic = NULL;
3045
1.41k
  kbnode_t *attic_head = &attic;
3046
3047
  /* Collect all tags in an array for faster searching.  */
3048
3.29k
  for (ntaglist = 0, node = pub_keyblock; node; node = node->next)
3049
1.88k
    ntaglist++;
3050
1.41k
  taglist = xtrycalloc (ntaglist, sizeof *taglist);
3051
1.41k
  if (!taglist)
3052
0
    return gpg_error_from_syserror ();
3053
3.29k
  for (ntaglist = 0, node = pub_keyblock; node; node = node->next)
3054
1.88k
    taglist[ntaglist++] = node->tag;
3055
3056
  /* Walks over the secret keyblock and delete all nodes which are not
3057
   * in the tag list.  Those nodes have been deleted in the
3058
   * pub_keyblock.  Sequential search is a bit lazy and could be
3059
   * optimized by sorting and bsearch; however secret keyrings are
3060
   * short and there are easier ways to DoS the import.  */
3061
2.11k
 again:
3062
18.0k
  for (prevnode=NULL, node=sec_keyblock; node; prevnode=node, node=node->next)
3063
16.6k
    {
3064
42.2k
      for (n=0; n < ntaglist; n++)
3065
28.2k
        if (taglist[n] == node->tag)
3066
2.59k
          break;
3067
16.6k
      if (n == ntaglist)  /* Not in public keyblock.  */
3068
14.0k
        {
3069
14.0k
          if (node->pkt->pkttype == PKT_SECRET_KEY
3070
14.0k
              || node->pkt->pkttype == PKT_SECRET_SUBKEY)
3071
701
            {
3072
701
              if (!prevnode)
3073
0
                sec_keyblock = node->next;
3074
701
              else
3075
701
                prevnode->next = node->next;
3076
701
              node->next = NULL;
3077
701
              *attic_head = node;
3078
701
              attic_head = &node->next;
3079
701
              goto again;  /* That's lame; I know.  */
3080
701
            }
3081
13.3k
          else
3082
13.3k
            delete_kbnode (node);
3083
14.0k
        }
3084
16.6k
    }
3085
3086
1.41k
  xfree (taglist);
3087
3088
  /* Commit the as deleted marked nodes and return the possibly
3089
   * modified keyblock and a list of removed secret key nodes.  */
3090
1.41k
  commit_kbnode (&sec_keyblock);
3091
1.41k
  *r_keyblock = sec_keyblock;
3092
1.41k
  *r_removedsecs = attic;
3093
1.41k
  return 0;
3094
2.11k
}
3095
3096
3097
/* Helper for import_secret_one.  */
3098
static gpg_error_t
3099
do_transfer (ctrl_t ctrl, kbnode_t keyblock, PKT_public_key *pk,
3100
             struct import_stats_s *stats, int batch, int only_marked)
3101
3102
84
{
3103
84
  gpg_error_t err;
3104
84
  struct import_stats_s subkey_stats = {0};
3105
84
  int force = 0;
3106
84
  int already_exist = agent_probe_secret_key (ctrl, pk);
3107
3108
84
  if (already_exist == 2 || already_exist == 4)
3109
0
    {
3110
0
      if (!opt.quiet)
3111
0
        log_info (_("key %s: card reference is overridden by key material\n"),
3112
0
                  keystr_from_pk (pk));
3113
0
      force = 1;
3114
0
    }
3115
3116
84
  err = transfer_secret_keys (ctrl, &subkey_stats, keyblock,
3117
84
                              batch, force, only_marked);
3118
84
  if (gpg_err_code (err) == GPG_ERR_NOT_PROCESSED)
3119
0
    {
3120
      /* TRANSLATORS: For a smartcard, each private key on host has a
3121
       * reference (stub) to a smartcard and actual private key data
3122
       * is stored on the card.  A single smartcard can have up to
3123
       * three private key data.  Importing private key stub is always
3124
       * skipped in 2.1, and it returns GPG_ERR_NOT_PROCESSED.
3125
       * Instead, user should be suggested to run 'gpg --card-status',
3126
       * then, references to a card will be automatically created
3127
       * again.  */
3128
0
      log_info (_("To migrate '%s', with each smartcard, "
3129
0
                  "run: %s\n"), "secring.gpg", "gpg --card-status");
3130
0
      err = 0;
3131
0
    }
3132
3133
84
  if (!err)
3134
0
    {
3135
0
      int status = 16;
3136
3137
0
      if (!opt.quiet)
3138
0
        log_info (_("key %s: secret key imported\n"), keystr_from_pk (pk));
3139
0
      if (subkey_stats.secret_imported)
3140
0
        {
3141
0
          status |= 1;
3142
0
          stats->secret_imported += 1;
3143
0
        }
3144
0
      if (subkey_stats.secret_dups)
3145
0
        stats->secret_dups += 1;
3146
3147
0
      if (is_status_enabled ())
3148
0
        print_import_ok (pk, status);
3149
0
    }
3150
3151
84
  return err;
3152
84
}
3153
3154
3155
/* If the secret keys (main or subkey) in SECKEYS have a corresponding
3156
 * public key in the public key described by (FPR,FPRLEN) import these
3157
 * parts.
3158
 */
3159
static gpg_error_t
3160
import_matching_seckeys (ctrl_t ctrl, kbnode_t seckeys,
3161
                         const byte *mainfpr, size_t mainfprlen,
3162
                         struct import_stats_s *stats, int batch)
3163
1.37k
{
3164
1.37k
  gpg_error_t err;
3165
1.37k
  kbnode_t pub_keyblock = NULL;
3166
1.37k
  kbnode_t node;
3167
1.37k
  struct { byte fpr[MAX_FINGERPRINT_LEN]; size_t fprlen; } *fprlist = NULL;
3168
1.37k
  size_t n, nfprlist;
3169
1.37k
  byte fpr[MAX_FINGERPRINT_LEN];
3170
1.37k
  size_t fprlen;
3171
1.37k
  PKT_public_key *pk;
3172
3173
  /* Get the entire public key block from our keystore and put all its
3174
   * fingerprints into an array.  */
3175
1.37k
  err = get_pubkey_byfpr (ctrl, NULL, &pub_keyblock, mainfpr, mainfprlen);
3176
1.37k
  if (err)
3177
1.35k
    goto leave;
3178
1.37k
  log_assert (pub_keyblock && pub_keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
3179
25
  pk = pub_keyblock->pkt->pkt.public_key;
3180
3181
7.47k
  for (nfprlist = 0, node = pub_keyblock; node; node = node->next)
3182
7.45k
    if (node->pkt->pkttype == PKT_PUBLIC_KEY
3183
7.42k
        || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3184
459
      nfprlist++;
3185
25
  log_assert (nfprlist);
3186
25
  fprlist = xtrycalloc (nfprlist, sizeof *fprlist);
3187
25
  if (!fprlist)
3188
0
    {
3189
0
      err = gpg_error_from_syserror ();
3190
0
      goto leave;
3191
0
    }
3192
7.47k
  for (n = 0, node = pub_keyblock; node; node = node->next)
3193
7.45k
    if (node->pkt->pkttype == PKT_PUBLIC_KEY
3194
7.42k
        || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3195
459
      {
3196
459
        fingerprint_from_pk (node->pkt->pkt.public_key,
3197
459
                             fprlist[n].fpr, &fprlist[n].fprlen);
3198
459
        n++;
3199
459
      }
3200
25
  log_assert (n == nfprlist);
3201
3202
  /* for (n=0; n < nfprlist; n++) */
3203
  /*   log_printhex (fprlist[n].fpr, fprlist[n].fprlen, "pubkey %zu:", n); */
3204
3205
  /* Mark all secret keys which have a matching public key part in
3206
   * PUB_KEYBLOCK.  */
3207
123
  for (node = seckeys; node; node = node->next)
3208
98
    {
3209
98
      if (node->pkt->pkttype != PKT_SECRET_KEY
3210
73
          && node->pkt->pkttype != PKT_SECRET_SUBKEY)
3211
0
        continue; /* Should not happen.  */
3212
98
      fingerprint_from_pk (node->pkt->pkt.public_key, fpr, &fprlen);
3213
98
      node->flag &= ~NODE_TRANSFER_SECKEY;
3214
724
      for (n=0; n < nfprlist; n++)
3215
682
        if (fprlist[n].fprlen == fprlen && !memcmp (fprlist[n].fpr,fpr,fprlen))
3216
56
          {
3217
56
            node->flag |= NODE_TRANSFER_SECKEY;
3218
            /* log_debug ("found matching seckey\n"); */
3219
56
            break;
3220
56
          }
3221
98
    }
3222
3223
  /* Transfer all marked keys.  */
3224
25
  err = do_transfer (ctrl, seckeys, pk, stats, batch, 1);
3225
3226
1.37k
 leave:
3227
1.37k
  xfree (fprlist);
3228
1.37k
  release_kbnode (pub_keyblock);
3229
1.37k
  return err;
3230
25
}
3231
3232
3233
/* Import function for a single secret keyblock.  Handling is simpler
3234
 * than for public keys.  We allow secret key importing only when
3235
 * allow is true, this is so that a secret key can not be imported
3236
 * accidentally and thereby tampering with the trust calculation.
3237
 *
3238
 * Ownership of KEYBLOCK is transferred to this function!
3239
 *
3240
 * If R_SECATTIC is not null the last special sec_keyblock is stored
3241
 * there.
3242
 */
3243
static gpg_error_t
3244
import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
3245
                   struct import_stats_s *stats, int batch,
3246
                   unsigned int options, int for_migration,
3247
                   import_screener_t screener, void *screener_arg,
3248
                   kbnode_t *r_secattic)
3249
4.16k
{
3250
4.16k
  PKT_public_key *pk;
3251
4.16k
  struct seckey_info *ski;
3252
4.16k
  kbnode_t node, uidnode;
3253
4.16k
  u32 keyid[2];
3254
4.16k
  gpg_error_t err = 0;
3255
4.16k
  int nr_prev;
3256
4.16k
  kbnode_t pub_keyblock;
3257
4.16k
  kbnode_t attic = NULL;
3258
4.16k
  byte fpr[MAX_FINGERPRINT_LEN];
3259
4.16k
  size_t fprlen;
3260
4.16k
  char pkstrbuf[PUBKEY_STRING_SIZE];
3261
3262
  /* Get the key and print some info about it */
3263
4.16k
  node = find_kbnode (keyblock, PKT_SECRET_KEY);
3264
4.16k
  if (!node)
3265
0
    BUG ();
3266
3267
4.16k
  pk = node->pkt->pkt.public_key;
3268
3269
4.16k
  fingerprint_from_pk (pk, fpr, &fprlen);
3270
4.16k
  keyid_from_pk (pk, keyid);
3271
4.16k
  uidnode = find_next_kbnode (keyblock, PKT_USER_ID);
3272
3273
4.16k
  if (screener && screener (keyblock, screener_arg))
3274
0
    {
3275
0
      log_error (_("secret key %s: %s\n"), keystr_from_pk (pk),
3276
0
                 _("rejected by import screener"));
3277
0
      release_kbnode (keyblock);
3278
0
      return 0;
3279
0
    }
3280
3281
4.16k
  if (opt.verbose && !for_migration)
3282
0
    {
3283
0
      log_info ("sec  %s/%s %s  ",
3284
0
                pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
3285
0
                keystr_from_pk (pk), datestr_from_pk (pk));
3286
0
      if (uidnode)
3287
0
        print_utf8_buffer (log_get_stream (), uidnode->pkt->pkt.user_id->name,
3288
0
                           uidnode->pkt->pkt.user_id->len);
3289
0
      log_printf ("\n");
3290
0
    }
3291
4.16k
  stats->secret_read++;
3292
3293
4.16k
  if ((options & IMPORT_ONLY_PUBKEYS))
3294
0
    {
3295
0
      if (!for_migration)
3296
0
        log_error (_("importing secret keys not allowed\n"));
3297
0
      release_kbnode (keyblock);
3298
0
      return 0;
3299
0
    }
3300
3301
4.16k
  if (!uidnode)
3302
2.30k
    {
3303
2.30k
      if (!for_migration)
3304
2.30k
        log_error( _("key %s: no user ID\n"), keystr_from_pk (pk));
3305
2.30k
      release_kbnode (keyblock);
3306
2.30k
      return 0;
3307
2.30k
    }
3308
3309
1.86k
  ski = pk->seckey_info;
3310
1.86k
  if (!ski)
3311
104
    {
3312
      /* Actually an internal error.  */
3313
104
      log_error ("key %s: secret key info missing\n", keystr_from_pk (pk));
3314
104
      release_kbnode (keyblock);
3315
104
      return 0;
3316
104
    }
3317
3318
  /* A quick check to not import keys with an invalid protection
3319
     cipher algorithm (only checks the primary key, though).  */
3320
1.76k
  if (ski->algo > 110)
3321
350
    {
3322
350
      if (!for_migration)
3323
350
        log_error (_("key %s: secret key with invalid cipher %d"
3324
350
                     " - skipped\n"), keystr_from_pk (pk), ski->algo);
3325
350
      release_kbnode (keyblock);
3326
350
      return 0;
3327
350
    }
3328
3329
#ifdef ENABLE_SELINUX_HACKS
3330
  if (1)
3331
    {
3332
      /* We don't allow importing secret keys because that may be used
3333
         to put a secret key into the keyring and the user might later
3334
         be tricked into signing stuff with that key.  */
3335
      log_error (_("importing secret keys not allowed\n"));
3336
      release_kbnode (keyblock);
3337
      return 0;
3338
    }
3339
#endif
3340
3341
1.41k
  clear_kbnode_flags (keyblock);
3342
3343
1.41k
  nr_prev = stats->skipped_new_keys;
3344
3345
  /* Make a public key out of the key. */
3346
1.41k
  pub_keyblock = sec_to_pub_keyblock (keyblock);
3347
1.41k
  if (!pub_keyblock)
3348
0
    {
3349
0
      err = gpg_error_from_syserror ();
3350
0
      log_error ("key %s: failed to create public key from secret key\n",
3351
0
                 keystr_from_pk (pk));
3352
0
    }
3353
1.41k
  else
3354
1.41k
    {
3355
1.41k
      int valid;
3356
3357
      /* Note that this outputs an IMPORT_OK status message for the
3358
   public key block, and below we will output another one for
3359
   the secret keys.  FIXME?  */
3360
1.41k
      import_one (ctrl, pub_keyblock, stats,
3361
1.41k
      NULL, NULL, options, 1, for_migration,
3362
1.41k
                  screener, screener_arg, 0, NULL, &valid);
3363
3364
      /* The secret keyblock may not have nodes which are deleted in
3365
       * the public keyblock.  Otherwise we would import just the
3366
       * secret key without having the public key.  That would be
3367
       * surprising and clutters our private-keys-v1.d.  */
3368
1.41k
      err = resync_sec_with_pub_keyblock (&keyblock, pub_keyblock, &attic);
3369
1.41k
      if (err)
3370
0
        goto leave;
3371
3372
1.41k
      if (!valid)
3373
1.35k
        {
3374
          /* If the block was not valid the primary key is left in the
3375
           * original keyblock because we require that for the first
3376
           * node.   Move it to ATTIC.  */
3377
1.35k
          if (keyblock && keyblock->pkt->pkttype == PKT_SECRET_KEY)
3378
1.35k
            {
3379
1.35k
              node = keyblock;
3380
1.35k
              keyblock = node->next;
3381
1.35k
              node->next = NULL;
3382
1.35k
              if (attic)
3383
180
                {
3384
180
                  node->next = attic;
3385
180
                  attic = node;
3386
180
                }
3387
1.17k
              else
3388
1.17k
                attic = node;
3389
1.35k
            }
3390
3391
          /* Try to import the secret key iff we have a public key.  */
3392
1.35k
          if (attic && !(opt.dry_run || (options & IMPORT_DRY_RUN)))
3393
1.35k
            err = import_matching_seckeys (ctrl, attic, fpr, fprlen,
3394
1.35k
                                           stats, batch);
3395
0
          else
3396
0
            err = gpg_error (GPG_ERR_NO_SECKEY);
3397
1.35k
          goto leave;
3398
1.35k
        }
3399
3400
      /* log_debug ("attic is:\n"); */
3401
      /* dump_kbnode (attic); */
3402
3403
      /* Proceed with the valid parts of PUBKEYBLOCK. */
3404
3405
      /* At least we cancel the secret key import when the public key
3406
   import was skipped due to MERGE_ONLY option and a new
3407
   key.  */
3408
59
      if (!(opt.dry_run || (options & IMPORT_DRY_RUN))
3409
59
          && stats->skipped_new_keys <= nr_prev)
3410
59
  {
3411
          /* Read the keyblock again to get the effects of a merge for
3412
           * the public key.  */
3413
59
          err = get_pubkey_byfpr (ctrl, NULL, &node, fpr, fprlen);
3414
59
          if (err || !node)
3415
59
            log_error ("key %s: failed to re-lookup public key: %s\n",
3416
0
                       keystr_from_pk (pk), gpg_strerror (err));
3417
59
          else
3418
59
            {
3419
59
              err = do_transfer (ctrl, keyblock, pk, stats, batch, 0);
3420
59
              if (!err)
3421
0
                check_prefs (ctrl, node);
3422
59
              release_kbnode (node);
3423
3424
59
              if (!err && attic)
3425
0
                {
3426
                  /* Try to import invalid subkeys.  This can be the
3427
                   * case if the primary secret key was imported due
3428
                   * to --allow-non-selfsigned-uid.  */
3429
0
                  err = import_matching_seckeys (ctrl, attic, fpr, fprlen,
3430
0
                                                 stats, batch);
3431
0
                }
3432
3433
59
            }
3434
59
        }
3435
59
    }
3436
3437
1.41k
 leave:
3438
1.41k
  release_kbnode (keyblock);
3439
1.41k
  release_kbnode (pub_keyblock);
3440
1.41k
  if (r_secattic)
3441
1.41k
    *r_secattic = attic;
3442
0
  else
3443
0
    release_kbnode (attic);
3444
1.41k
  return err;
3445
1.41k
}
3446
3447
3448
/* Return a string for the revocation reason CODE.  R_FREEM must be an
3449
 * possibly unintialized ptr which should be freed by the caller after
3450
 * the return value has been consumed.  */
3451
const char *
3452
revocation_reason_code_to_str (int code, char **freeme)
3453
0
{
3454
  /* Take care: get_revocation_reason has knowledge of the internal
3455
   * working of this fucntion.  */
3456
0
  const char *result;
3457
3458
0
  *freeme = NULL;
3459
0
  switch (code)
3460
0
    {
3461
0
    case 0x00: result = _("No reason specified"); break;
3462
0
    case 0x01: result = _("Key is superseded");   break;
3463
0
    case 0x02: result = _("Key has been compromised"); break;
3464
0
    case 0x03: result = _("Key is no longer used"); break;
3465
0
    case 0x20: result = _("User ID is no longer valid"); break;
3466
0
    default:
3467
0
      *freeme = xasprintf ("code=%02x", code);
3468
0
      result = *freeme;
3469
0
      break;
3470
0
    }
3471
3472
0
  return result;
3473
0
}
3474
3475
3476
/* Return the recocation reason from signature SIG.  If no revocation
3477
 * reason is available 0 is returned, in other cases the reason
3478
 * (0..255).  If R_REASON is not NULL a malloced textual
3479
 * representation of the code is stored there.  If R_COMMENT is not
3480
 * NULL the comment from the reason is stored there and its length at
3481
 * R_COMMENTLEN.  Note that the value at R_COMMENT is not filtered but
3482
 * user supplied data in UTF8; thus it needs to be escaped for display
3483
 * purposes.  Both return values are either NULL or a malloced
3484
 * string/buffer.  */
3485
int
3486
get_revocation_reason (PKT_signature *sig, char **r_reason,
3487
                       char **r_comment, size_t *r_commentlen)
3488
0
{
3489
0
  int reason_seq = 0;
3490
0
  size_t reason_n;
3491
0
  const byte *reason_p;
3492
0
  int reason_code = 0;
3493
0
  const char *reason_string;
3494
0
  char *freeme;
3495
3496
0
  if (r_reason)
3497
0
    *r_reason = NULL;
3498
0
  if (r_comment)
3499
0
    *r_comment = NULL;
3500
3501
  /* Skip over empty reason packets.  */
3502
0
  while ((reason_p = enum_sig_subpkt (sig, 1, SIGSUBPKT_REVOC_REASON,
3503
0
                                      &reason_n, &reason_seq, NULL))
3504
0
         && !reason_n)
3505
0
    ;
3506
0
  if (reason_p && reason_n)
3507
0
    {
3508
0
      reason_code = *reason_p;
3509
0
      reason_n--; reason_p++;
3510
0
      reason_string = revocation_reason_code_to_str (reason_code, &freeme);
3511
0
      if (r_reason && freeme)
3512
0
        *r_reason = freeme;
3513
0
      else if (r_reason && reason_string)
3514
0
        *r_reason = xstrdup (reason_string);
3515
0
      else
3516
0
        xfree (freeme);
3517
3518
0
      if (r_comment && reason_n)
3519
0
        {
3520
0
          *r_comment = xmalloc (reason_n);
3521
0
          memcpy (*r_comment, reason_p, reason_n);
3522
0
          *r_commentlen = reason_n;
3523
0
        }
3524
0
    }
3525
3526
0
  return reason_code;
3527
0
}
3528
3529
3530
/* List the recocation signature as a "rvs" record.  SIGRC shows the
3531
 * character from the signature verification or 0 if no public key was
3532
 * found.  */
3533
static void
3534
list_standalone_revocation (ctrl_t ctrl, PKT_signature *sig, int sigrc)
3535
0
{
3536
0
  char *siguid = NULL;
3537
0
  size_t siguidlen = 0;
3538
0
  char *issuer_fpr = NULL;
3539
0
  int reason_code = 0;
3540
0
  char *reason_text = NULL;
3541
0
  char *reason_comment = NULL;
3542
0
  size_t reason_commentlen;
3543
3544
0
  if (sigrc != '%' && sigrc != '?' && !opt.fast_list_mode)
3545
0
    {
3546
0
      int nouid;
3547
0
      siguid = get_user_id (ctrl, sig->keyid, &siguidlen, &nouid);
3548
0
      if (nouid)
3549
0
        sigrc = '?';
3550
0
    }
3551
3552
0
  reason_code = get_revocation_reason (sig, &reason_text,
3553
0
                                       &reason_comment, &reason_commentlen);
3554
3555
0
  if (opt.with_colons)
3556
0
    {
3557
0
      es_fputs ("rvs:", es_stdout);
3558
0
      if (sigrc)
3559
0
        es_putc (sigrc, es_stdout);
3560
0
      es_fprintf (es_stdout, "::%d:%08lX%08lX:%s:%s:::",
3561
0
                  sig->pubkey_algo,
3562
0
                  (ulong) sig->keyid[0], (ulong) sig->keyid[1],
3563
0
                  colon_datestr_from_sig (sig),
3564
0
                  colon_expirestr_from_sig (sig));
3565
3566
0
      if (siguid)
3567
0
        es_write_sanitized (es_stdout, siguid, siguidlen, ":", NULL);
3568
3569
0
      es_fprintf (es_stdout, ":%02x%c", sig->sig_class,
3570
0
                  sig->flags.exportable ? 'x' : 'l');
3571
0
      if (reason_text)
3572
0
        es_fprintf (es_stdout, ",%02x", reason_code);
3573
0
      es_fputs ("::", es_stdout);
3574
3575
0
      if ((issuer_fpr = issuer_fpr_string (sig)))
3576
0
        es_fputs (issuer_fpr, es_stdout);
3577
3578
0
      es_fprintf (es_stdout, ":::%d:", sig->digest_algo);
3579
3580
0
      if (reason_comment)
3581
0
        {
3582
0
          es_fputs ("::::", es_stdout);
3583
0
          es_write_sanitized (es_stdout, reason_comment, reason_commentlen,
3584
0
                              ":", NULL);
3585
0
          es_putc (':', es_stdout);
3586
0
        }
3587
0
      es_putc ('\n', es_stdout);
3588
3589
0
      if (opt.show_subpackets)
3590
0
        print_subpackets_colon (sig);
3591
0
    }
3592
0
  else /* Human readable. */
3593
0
    {
3594
0
      es_fputs ("rvs", es_stdout);
3595
0
      es_fprintf (es_stdout, "%c%c %c%c%c%c%c%c %s %s",
3596
0
      sigrc, (sig->sig_class - 0x10 > 0 &&
3597
0
        sig->sig_class - 0x10 <
3598
0
        4) ? '0' + sig->sig_class - 0x10 : ' ',
3599
0
      sig->flags.exportable ? ' ' : 'L',
3600
0
      sig->flags.revocable ? ' ' : 'R',
3601
0
      sig->flags.policy_url ? 'P' : ' ',
3602
0
      sig->flags.notation ? 'N' : ' ',
3603
0
      sig->flags.expired ? 'X' : ' ',
3604
0
      (sig->trust_depth > 9) ? 'T' : (sig->trust_depth >
3605
0
              0) ? '0' +
3606
0
      sig->trust_depth : ' ', keystr (sig->keyid),
3607
0
      datestr_from_sig (sig));
3608
0
      if (siguid)
3609
0
        {
3610
0
          es_fprintf (es_stdout, "  ");
3611
0
          print_utf8_buffer (es_stdout, siguid, siguidlen);
3612
0
        }
3613
0
      es_putc ('\n', es_stdout);
3614
3615
0
      if (sig->flags.policy_url
3616
0
          && (opt.list_options & LIST_SHOW_POLICY_URLS))
3617
0
        show_policy_url (sig, 3, 0);
3618
3619
0
      if (sig->flags.notation && (opt.list_options & LIST_SHOW_NOTATIONS))
3620
0
        show_notation (sig, 3, 0,
3621
0
                       ((opt.list_options & LIST_SHOW_STD_NOTATIONS) ? 1 : 0)
3622
0
                       +
3623
0
                       ((opt.list_options & LIST_SHOW_USER_NOTATIONS) ? 2 : 0)
3624
0
                       +
3625
0
                       ((opt.list_options & LIST_SHOW_HIDDEN_NOTATIONS) ? 4:0));
3626
3627
0
      if (sig->flags.pref_ks
3628
0
          && (opt.list_options & LIST_SHOW_KEYSERVER_URLS))
3629
0
        show_keyserver_url (sig, 3, 0);
3630
3631
0
      if (reason_text)
3632
0
        {
3633
0
          es_fprintf (es_stdout, "      %s%s\n",
3634
0
                      _("reason for revocation: "), reason_text);
3635
0
          print_revocation_reason_comment (reason_comment, reason_commentlen);
3636
0
        }
3637
0
    }
3638
3639
0
  es_fflush (es_stdout);
3640
3641
0
  xfree (reason_text);
3642
0
  xfree (reason_comment);
3643
0
  xfree (siguid);
3644
0
  xfree (issuer_fpr);
3645
0
}
3646
3647
3648
/* Import a revocation certificate; only the first packet in the
3649
 * NODE-list is considered.  */
3650
static int
3651
import_revoke_cert (ctrl_t ctrl, kbnode_t node, unsigned int options,
3652
                    struct import_stats_s *stats)
3653
2.58k
{
3654
2.58k
  PKT_public_key *pk = NULL;
3655
2.58k
  PKT_public_key *pk_buffer = NULL;
3656
2.58k
  PKT_signature *sig = NULL;
3657
2.58k
  kbnode_t onode = NULL;
3658
2.58k
  kbnode_t keyblock = NULL;
3659
2.58k
  KEYDB_HANDLE hd = NULL;
3660
2.58k
  u32 keyid[2];
3661
2.58k
  int rc = 0;
3662
2.58k
  int sigrc = 0;
3663
2.58k
  int silent;
3664
3665
  /* No error output for --show-keys.  */
3666
2.58k
  silent = (options & (IMPORT_SHOW | IMPORT_DRY_RUN));
3667
3668
2.58k
  log_assert (node->pkt->pkttype == PKT_SIGNATURE );
3669
2.58k
  log_assert (IS_KEY_REV (node->pkt->pkt.signature));
3670
3671
  /* FIXME: We can do better here by using the issuer fingerprint if
3672
   * available.  We should also make use of get_keyblock_byfprint_fast.  */
3673
2.58k
  sig = node->pkt->pkt.signature;
3674
3675
  /* If the revocation signature has an intended recipient fingerprint subpacket
3676
   * use the provided fingerprint (stored in REV_SUBJECT_INFO). */
3677
2.58k
  if (sig->rev_subject_info)
3678
0
    {
3679
0
      hd = keydb_new (ctrl);
3680
0
      if (!hd)
3681
0
        {
3682
0
          rc = gpg_error_from_syserror ();
3683
0
          goto leave;
3684
0
        }
3685
3686
0
      rc = keydb_lock (hd);
3687
0
      if (rc)
3688
0
        goto leave;
3689
3690
0
      rc = keydb_search_fpr (hd,
3691
0
                             sig->rev_subject_info->fpr,
3692
0
                             sig->rev_subject_info->fprlen);
3693
3694
0
      keyid_from_fingerprint (ctrl,
3695
0
                              sig->rev_subject_info->fpr,
3696
0
                              sig->rev_subject_info->fprlen, keyid);
3697
3698
      /* The keyblock might not be found if the revocation subject
3699
       * is not in the local keyring. This should not be an error. */
3700
0
      if (rc)
3701
0
        {
3702
0
          if (!silent)
3703
0
            log_error (_("key %s: can't locate keyblock: %s\n"),
3704
0
                       keystr (keyid), gpg_strerror (rc));
3705
0
          rc = 0;
3706
0
          goto leave;
3707
0
        }
3708
3709
0
      rc = keydb_get_keyblock (hd, &keyblock);
3710
0
      if (rc)
3711
0
        {
3712
0
          log_error (_("key %s: can't read keyblock: %s\n"),
3713
0
                     keystr (keyid), gpg_strerror (rc));
3714
0
          goto leave;
3715
0
        }
3716
3717
0
      pk = keyblock->pkt->pkt.public_key;
3718
0
    }
3719
2.58k
  else
3720
2.58k
    {
3721
2.58k
      log_info ("we may have an old standalone revocation signature\n");
3722
3723
      /* Path without intended recipient fingerprint subpacket. */
3724
2.58k
      keyid[0] = node->pkt->pkt.signature->keyid[0];
3725
2.58k
      keyid[1] = node->pkt->pkt.signature->keyid[1];
3726
3727
2.58k
      pk_buffer = xmalloc_clear( sizeof *pk_buffer );
3728
2.58k
      pk = pk_buffer;
3729
3730
2.58k
      rc = get_pubkey (ctrl, pk, keyid);
3731
2.58k
      if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
3732
1.04k
        {
3733
1.04k
          if (!silent)
3734
1.04k
            log_error (_("key %s: no public key -"
3735
1.04k
                         " can't apply revocation certificate\n"), keystr(keyid));
3736
1.04k
          rc = 0;
3737
1.04k
          goto leave;
3738
1.04k
        }
3739
1.54k
      else if (rc )
3740
0
        {
3741
0
          log_error (_("key %s: public key not found: %s\n"),
3742
0
                     keystr(keyid), gpg_strerror (rc));
3743
0
          goto leave;
3744
0
        }
3745
3746
      /* Read the original keyblock. */
3747
1.54k
      hd = keydb_new (ctrl);
3748
1.54k
      if (!hd)
3749
0
        {
3750
0
          rc = gpg_error_from_syserror ();
3751
0
          goto leave;
3752
0
        }
3753
3754
1.54k
      rc = keydb_lock (hd);
3755
1.54k
      if (rc)
3756
0
        goto leave;
3757
3758
1.54k
      {
3759
1.54k
        byte afp[MAX_FINGERPRINT_LEN];
3760
1.54k
        size_t an;
3761
3762
1.54k
        fingerprint_from_pk (pk, afp, &an);
3763
1.54k
        rc = keydb_search_fpr (hd, afp, an);
3764
1.54k
      }
3765
1.54k
      if (rc)
3766
0
        {
3767
0
          log_error (_("key %s: can't locate original keyblock: %s\n"),
3768
0
                     keystr(keyid), gpg_strerror (rc));
3769
0
          goto leave;
3770
0
        }
3771
1.54k
      rc = keydb_get_keyblock (hd, &keyblock );
3772
1.54k
      if (rc)
3773
0
        {
3774
0
          log_error (_("key %s: can't read original keyblock: %s\n"),
3775
0
                     keystr(keyid), gpg_strerror (rc));
3776
0
          goto leave;
3777
0
        }
3778
1.54k
    }
3779
3780
  /* it is okay, that node is not in keyblock because
3781
   * check_key_signature works fine for sig_class 0x20 (KEY_REV) in
3782
   * this special case.  SIGRC is only used for IMPORT_SHOW.  */
3783
1.54k
  rc = check_key_signature (ctrl, keyblock, node, NULL);
3784
1.54k
  switch (gpg_err_code (rc))
3785
1.54k
    {
3786
179
    case 0:                       sigrc = '!'; break;
3787
57
    case GPG_ERR_BAD_SIGNATURE:   sigrc = '-'; break;
3788
0
    case GPG_ERR_NO_PUBKEY:       sigrc = '?'; break;
3789
0
    case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break;
3790
1.30k
    default:                      sigrc = '%'; break;
3791
1.54k
    }
3792
1.54k
  if (gpg_err_code (rc) == GPG_ERR_CERT_REVOKED)
3793
0
    {
3794
0
      log_info ("key %s: already revoked: %s", keystr (keyid), gpg_strerror(rc));
3795
0
      rc = 0;
3796
0
      goto leave;
3797
0
    }
3798
1.54k
  else if (rc)
3799
1.36k
    {
3800
1.36k
      if (!silent)
3801
1.36k
        log_error (_("key %s: invalid revocation certificate"
3802
1.36k
                     ": %s - rejected\n"), keystr(keyid), gpg_strerror (rc));
3803
1.36k
      goto leave;
3804
1.36k
    }
3805
3806
  /* check whether we already have this */
3807
200
  for(onode=keyblock->next; onode; onode=onode->next ) {
3808
200
    if (onode->pkt->pkttype == PKT_USER_ID )
3809
8
      break;
3810
192
    else if (onode->pkt->pkttype == PKT_SIGNATURE
3811
192
             && !cmp_signatures(node->pkt->pkt.signature,
3812
192
                                onode->pkt->pkt.signature))
3813
171
      {
3814
171
        rc = 0;
3815
171
        goto leave; /* yes, we already know about it */
3816
171
      }
3817
200
  }
3818
3819
  /* insert it */
3820
8
  insert_kbnode( keyblock, clone_kbnode(node), 0 );
3821
3822
  /* and write the keyblock back unless in dry run mode.  */
3823
8
  if (!(opt.dry_run || (options & IMPORT_DRY_RUN)))
3824
8
    {
3825
8
      rc = keydb_update_keyblock (ctrl, hd, keyblock );
3826
8
      if (rc)
3827
8
        log_error (_("error writing keyring '%s': %s\n"),
3828
0
                   keydb_get_resource_name (hd), gpg_strerror (rc) );
3829
8
      keydb_release (hd);
3830
8
      hd = NULL;
3831
3832
      /* we are ready */
3833
8
      if (!opt.quiet )
3834
8
        {
3835
8
          char *p=get_user_id_native (ctrl, keyid);
3836
8
          log_info( _("key %s: \"%s\" revocation certificate imported\n"),
3837
8
                    keystr(keyid),p);
3838
8
          xfree(p);
3839
8
        }
3840
3841
      /* If the key we just revoked was ultimately trusted, remove its
3842
       * ultimate trust.  This doesn't stop the user from putting the
3843
       * ultimate trust back, but is a reasonable solution for now. */
3844
8
      if (get_ownertrust (ctrl, pk) == TRUST_ULTIMATE)
3845
0
        clear_ownertrusts (ctrl, pk);
3846
3847
8
      revalidation_mark (ctrl);
3848
8
    }
3849
8
  stats->n_revoc++;
3850
3851
2.58k
 leave:
3852
2.58k
  if ((options & IMPORT_SHOW))
3853
0
    list_standalone_revocation (ctrl, node->pkt->pkt.signature, sigrc);
3854
3855
2.58k
  keydb_release (hd);
3856
2.58k
  release_kbnode( keyblock );
3857
2.58k
  free_public_key( pk_buffer );
3858
2.58k
  return rc;
3859
8
}
3860
3861
3862
/* Loop over the KEYBLOCK and check all self signatures.  KEYID is the
3863
 * keyid of the primary key for reporting purposes. On return the
3864
 * following bits in the node flags are set:
3865
 *
3866
 * - NODE_GOOD_SELFSIG  :: User ID or subkey has a self-signature
3867
 * - NODE_BAD_SELFSIG   :: Used ID or subkey has an invalid self-signature
3868
 * - NODE_DELETION_MARK :: This node shall be deleted
3869
 *
3870
 * NON_SELF is set to true if there are any sigs other than self-sigs
3871
 * in this keyblock.
3872
 *
3873
 * Returns 0 on success or -1 (but not an error code) if the keyblock
3874
 * is invalid.
3875
 */
3876
static int
3877
chk_self_sigs (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid, int *non_self)
3878
10.4k
{
3879
10.4k
  kbnode_t knode = NULL;   /* The node of the current subkey.  */
3880
10.4k
  PKT_public_key *subpk = NULL; /* and its packet. */
3881
10.4k
  kbnode_t bsnode = NULL;  /* Subkey binding signature node.  */
3882
10.4k
  u32 bsdate = 0;          /* Timestamp of that node.   */
3883
10.4k
  kbnode_t rsnode = NULL;  /* Subkey recocation signature node.  */
3884
10.4k
  u32 rsdate = 0;          /* Timestamp of that node.  */
3885
10.4k
  PKT_signature *sig;
3886
10.4k
  int rc;
3887
10.4k
  kbnode_t n;
3888
3889
61.7k
  for (n=keyblock; (n = find_next_kbnode (n, 0)); )
3890
51.3k
    {
3891
51.3k
      if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3892
3.92k
  {
3893
3.92k
    knode = n;
3894
3.92k
          subpk = knode->pkt->pkt.public_key;
3895
3.92k
    bsdate = 0;
3896
3.92k
    rsdate = 0;
3897
3.92k
    bsnode = NULL;
3898
3.92k
    rsnode = NULL;
3899
3.92k
    continue;
3900
3.92k
  }
3901
3902
47.4k
      if ( n->pkt->pkttype != PKT_SIGNATURE )
3903
24.4k
        continue;
3904
3905
22.9k
      sig = n->pkt->pkt.signature;
3906
22.9k
      if ( keyid[0] != sig->keyid[0] || keyid[1] != sig->keyid[1] )
3907
13.8k
        {
3908
13.8k
          *non_self = 1;
3909
13.8k
          continue;
3910
13.8k
        }
3911
3912
      /* This just caches the sigs for later use.  That way we
3913
         import a fully-cached key which speeds things up. */
3914
9.07k
      if (!opt.no_sig_cache)
3915
9.07k
        check_key_signature (ctrl, keyblock, n, NULL);
3916
3917
9.07k
      if ( IS_UID_SIG(sig) || IS_UID_REV(sig) )
3918
5.43k
        {
3919
5.43k
          kbnode_t unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
3920
5.43k
          if ( !unode )
3921
21
            {
3922
21
              log_error( _("key %s: no user ID for signature\n"),
3923
21
                         keystr(keyid));
3924
21
              return -1;  /* The complete keyblock is invalid.  */
3925
21
            }
3926
3927
          /* If it hasn't been marked valid yet, keep trying.  */
3928
5.41k
          if (!(unode->flag & NODE_GOOD_SELFSIG))
3929
5.38k
            {
3930
5.38k
              rc = check_key_signature (ctrl, keyblock, n, NULL);
3931
5.38k
              if ( rc )
3932
2.11k
                {
3933
2.11k
                  if ( opt.verbose )
3934
0
                    {
3935
0
                      char *p = utf8_to_native
3936
0
                        (unode->pkt->pkt.user_id->name,
3937
0
                         strlen (unode->pkt->pkt.user_id->name),0);
3938
0
                      log_info (gpg_err_code(rc) == GPG_ERR_PUBKEY_ALGO ?
3939
0
                                _("key %s: unsupported public key "
3940
0
                                  "algorithm on user ID \"%s\"\n"):
3941
0
                                _("key %s: invalid self-signature "
3942
0
                                  "on user ID \"%s\"\n"),
3943
0
                                keystr (keyid),p);
3944
0
                      xfree (p);
3945
0
                    }
3946
2.11k
                }
3947
3.26k
              else
3948
3.26k
                unode->flag |= NODE_GOOD_SELFSIG;
3949
5.38k
            }
3950
5.41k
        }
3951
3.64k
      else if (IS_KEY_SIG (sig))
3952
619
        {
3953
619
          rc = check_key_signature (ctrl, keyblock, n, NULL);
3954
619
          if ( rc )
3955
612
            {
3956
612
              if (opt.verbose)
3957
612
                log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
3958
0
                          _("key %s: unsupported public key algorithm\n"):
3959
0
                          _("key %s: invalid direct key signature\n"),
3960
0
                          keystr (keyid));
3961
612
              n->flag |= NODE_DELETION_MARK;
3962
612
            }
3963
619
        }
3964
3.02k
      else if ( IS_SUBKEY_SIG (sig) )
3965
1.10k
        {
3966
          /* Note that this works based solely on the timestamps like
3967
             the rest of gpg.  If the standard gets revocation
3968
             targets, this may need to be revised.  */
3969
3970
1.10k
          if ( !knode )
3971
19
            {
3972
19
              if (opt.verbose)
3973
19
                log_info (_("key %s: no subkey for key binding\n"),
3974
0
                          keystr (keyid));
3975
19
              n->flag |= NODE_DELETION_MARK;
3976
19
            }
3977
1.08k
          else
3978
1.08k
            {
3979
1.08k
              rc = check_key_signature (ctrl, keyblock, n, NULL);
3980
1.08k
              if ( rc )
3981
439
                {
3982
439
                  if (opt.verbose)
3983
0
                    {
3984
0
                      keyid_from_pk (subpk, NULL);
3985
0
                      log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
3986
0
                                _("key %s: unsupported public key"
3987
0
                                  " algorithm\n"):
3988
0
                                _("key %s: invalid subkey binding\n"),
3989
0
                                keystr_with_sub (keyid, subpk->keyid));
3990
0
                    }
3991
439
                  n->flag |= NODE_DELETION_MARK;
3992
439
                }
3993
646
              else
3994
646
                {
3995
                  /* It's valid, so is it newer? */
3996
646
                  if (sig->timestamp >= bsdate)
3997
646
                    {
3998
646
                      knode->flag |= NODE_GOOD_SELFSIG; /* Subkey is valid.  */
3999
646
                      if (bsnode)
4000
0
                        {
4001
                          /* Delete the last binding sig since this
4002
                             one is newer */
4003
0
                          bsnode->flag |= NODE_DELETION_MARK;
4004
0
                          if (opt.verbose)
4005
0
                            {
4006
0
                              keyid_from_pk (subpk, NULL);
4007
0
                              log_info (_("key %s: removed multiple subkey"
4008
0
                                          " binding\n"),
4009
0
                                        keystr_with_sub (keyid, subpk->keyid));
4010
0
                            }
4011
0
                        }
4012
4013
646
                      bsnode = n;
4014
646
                      bsdate = sig->timestamp;
4015
646
                    }
4016
0
                  else
4017
0
                    n->flag |= NODE_DELETION_MARK; /* older */
4018
646
                }
4019
1.08k
            }
4020
1.10k
        }
4021
1.91k
      else if ( IS_SUBKEY_REV (sig) )
4022
915
        {
4023
          /* We don't actually mark the subkey as revoked right now,
4024
             so just check that the revocation sig is the most recent
4025
             valid one.  Note that we don't care if the binding sig is
4026
             newer than the revocation sig.  See the comment in
4027
             getkey.c:merge_selfsigs_subkey for more.  */
4028
915
          if ( !knode )
4029
86
            {
4030
86
              if (opt.verbose)
4031
86
                log_info (_("key %s: no subkey for key revocation\n"),
4032
0
                          keystr(keyid));
4033
86
              n->flag |= NODE_DELETION_MARK;
4034
86
            }
4035
829
          else
4036
829
            {
4037
829
              rc = check_key_signature (ctrl, keyblock, n, NULL);
4038
829
              if ( rc )
4039
803
                {
4040
803
                  if(opt.verbose)
4041
803
                    log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
4042
0
                              _("key %s: unsupported public"
4043
0
                                " key algorithm\n"):
4044
0
                              _("key %s: invalid subkey revocation\n"),
4045
0
                              keystr(keyid));
4046
803
                  n->flag |= NODE_DELETION_MARK;
4047
803
                }
4048
26
              else
4049
26
                {
4050
                  /* It's valid, so is it newer? */
4051
26
                  if (sig->timestamp >= rsdate)
4052
26
                    {
4053
26
                      if (rsnode)
4054
0
                        {
4055
                          /* Delete the last revocation sig since
4056
                             this one is newer.  */
4057
0
                          rsnode->flag |= NODE_DELETION_MARK;
4058
0
                          if (opt.verbose)
4059
0
                            log_info (_("key %s: removed multiple subkey"
4060
0
                                        " revocation\n"),keystr(keyid));
4061
0
                        }
4062
4063
26
                      rsnode = n;
4064
26
                      rsdate = sig->timestamp;
4065
26
                    }
4066
0
                  else
4067
0
                    n->flag |= NODE_DELETION_MARK; /* older */
4068
26
                }
4069
829
            }
4070
915
        }
4071
9.07k
    }
4072
4073
10.3k
  return 0;
4074
10.4k
}
4075
4076
4077
/* Delete all parts which are invalid and those signatures whose
4078
 * public key algorithm is not available in this implementation; but
4079
 * consider RSA as valid, because parse/build_packets knows about it.
4080
 * If R_OTHERREVSIGS is not NULL, it is used to return a list of
4081
 * revocation certificates which have been deleted from KEYBLOCK but
4082
 * should be handled later.
4083
 *
4084
 * Returns: True if at least one valid user-id is left over.
4085
 */
4086
static int
4087
delete_inv_parts (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid,
4088
                  unsigned int options, kbnode_t *r_otherrevsigs)
4089
10.3k
{
4090
10.3k
  kbnode_t node;
4091
10.3k
  int nvalid=0, uid_seen=0, subkey_seen=0;
4092
10.3k
  PKT_public_key *pk;
4093
4094
50.8k
  for (node=keyblock->next; node; node = node->next )
4095
40.4k
    {
4096
40.4k
      if (node->pkt->pkttype == PKT_USER_ID)
4097
24.0k
        {
4098
24.0k
          uid_seen = 1;
4099
24.0k
          if ((node->flag & NODE_BAD_SELFSIG)
4100
24.0k
              || !(node->flag & NODE_GOOD_SELFSIG))
4101
20.7k
            {
4102
20.7k
              if (opt.verbose )
4103
0
                {
4104
0
                  char *p=utf8_to_native(node->pkt->pkt.user_id->name,
4105
0
                                         node->pkt->pkt.user_id->len,0);
4106
0
                  log_info( _("key %s: skipped user ID \"%s\"\n"),
4107
0
                            keystr(keyid),p);
4108
0
                  xfree(p);
4109
0
                }
4110
20.7k
              delete_kbnode( node ); /* the user-id */
4111
              /* and all following packets up to the next user-id */
4112
30.1k
              while (node->next
4113
23.1k
                     && node->next->pkt->pkttype != PKT_USER_ID
4114
10.9k
                     && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
4115
9.73k
                     && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
4116
9.40k
                delete_kbnode( node->next );
4117
9.40k
                node = node->next;
4118
9.40k
              }
4119
20.7k
      }
4120
3.26k
          else
4121
3.26k
            nvalid++;
4122
24.0k
  }
4123
16.4k
      else if (   node->pkt->pkttype == PKT_PUBLIC_SUBKEY
4124
12.5k
               || node->pkt->pkttype == PKT_SECRET_SUBKEY )
4125
4.37k
        {
4126
4.37k
          if ((node->flag & NODE_BAD_SELFSIG)
4127
4.37k
              || !(node->flag & NODE_GOOD_SELFSIG))
4128
3.73k
            {
4129
3.73k
              if (opt.verbose )
4130
0
                {
4131
0
                  pk = node->pkt->pkt.public_key;
4132
0
                  keyid_from_pk (pk, NULL);
4133
0
                  log_info (_("key %s: skipped subkey\n"),
4134
0
                            keystr_with_sub (keyid, pk->keyid));
4135
0
                }
4136
4137
3.73k
              delete_kbnode( node ); /* the subkey */
4138
              /* and all following signature packets */
4139
5.19k
              while (node->next
4140
4.32k
                     && node->next->pkt->pkttype == PKT_SIGNATURE ) {
4141
1.46k
                delete_kbnode( node->next );
4142
1.46k
                node = node->next;
4143
1.46k
              }
4144
3.73k
      }
4145
646
          else
4146
646
            subkey_seen = 1;
4147
4.37k
  }
4148
12.0k
      else if (node->pkt->pkttype == PKT_SIGNATURE
4149
12.0k
               && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
4150
1.86k
               && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
4151
1.86k
        {
4152
1.86k
          delete_kbnode( node ); /* build_packet() can't handle this */
4153
1.86k
        }
4154
10.2k
      else if (node->pkt->pkttype == PKT_SIGNATURE
4155
10.2k
               && !node->pkt->pkt.signature->flags.exportable
4156
144
               && !(options&IMPORT_LOCAL_SIGS)
4157
144
               && !have_secret_key_with_kid (ctrl,
4158
144
                                             node->pkt->pkt.signature->keyid))
4159
144
        {
4160
          /* here we violate the rfc a bit by still allowing
4161
           * to import non-exportable signature when we have the
4162
           * the secret key used to create this signature - it
4163
           * seems that this makes sense */
4164
144
          if(opt.verbose)
4165
144
            log_info( _("key %s: non exportable signature"
4166
0
                        " (class 0x%02X) - skipped\n"),
4167
0
                      keystr(keyid), node->pkt->pkt.signature->sig_class );
4168
144
          delete_kbnode( node );
4169
144
        }
4170
10.0k
      else if (node->pkt->pkttype == PKT_SIGNATURE
4171
10.0k
               && IS_KEY_REV (node->pkt->pkt.signature))
4172
2.52k
        {
4173
2.52k
          if (uid_seen )
4174
14
            {
4175
14
              if(opt.verbose)
4176
14
                log_info( _("key %s: revocation certificate"
4177
0
                            " at wrong place - skipped\n"),keystr(keyid));
4178
14
              if (r_otherrevsigs)
4179
14
                {
4180
14
                  PACKET *pkt;
4181
4182
14
                  pkt = xcalloc (1, sizeof *pkt);
4183
14
                  pkt->pkttype = PKT_SIGNATURE;
4184
14
                  pkt->pkt.signature = copy_signature
4185
14
                    (NULL, node->pkt->pkt.signature);
4186
14
                  *r_otherrevsigs = new_kbnode2 (*r_otherrevsigs, pkt);
4187
14
                }
4188
14
              delete_kbnode( node );
4189
14
            }
4190
2.51k
          else
4191
2.51k
            {
4192
        /* If the revocation cert is from a different key than
4193
                 the one we're working on don't check it - it's
4194
                 probably from a revocation key and won't be
4195
                 verifiable with this key anyway. */
4196
4197
2.51k
        if(node->pkt->pkt.signature->keyid[0]==keyid[0]
4198
478
                 && node->pkt->pkt.signature->keyid[1]==keyid[1])
4199
284
    {
4200
284
      int rc = check_key_signature (ctrl, keyblock, node, NULL);
4201
284
      if (rc )
4202
254
        {
4203
254
          if(opt.verbose)
4204
254
      log_info( _("key %s: invalid revocation"
4205
0
            " certificate: %s - skipped\n"),
4206
0
          keystr(keyid), gpg_strerror (rc));
4207
254
          delete_kbnode( node );
4208
254
        }
4209
284
    }
4210
2.22k
              else if (r_otherrevsigs)
4211
2.22k
                {
4212
2.22k
                  PACKET *pkt;
4213
4214
2.22k
                  pkt = xcalloc (1, sizeof *pkt);
4215
2.22k
                  pkt->pkttype = PKT_SIGNATURE;
4216
2.22k
                  pkt->pkt.signature = copy_signature
4217
2.22k
                    (NULL, node->pkt->pkt.signature);
4218
2.22k
                  *r_otherrevsigs = new_kbnode2 (*r_otherrevsigs, pkt);
4219
2.22k
                }
4220
2.51k
      }
4221
2.52k
  }
4222
7.54k
      else if (node->pkt->pkttype == PKT_SIGNATURE
4223
7.54k
               && (IS_SUBKEY_SIG (node->pkt->pkt.signature)
4224
6.78k
                   || IS_SUBKEY_REV (node->pkt->pkt.signature))
4225
1.15k
               && !subkey_seen )
4226
338
        {
4227
338
          if(opt.verbose)
4228
338
            log_info( _("key %s: subkey signature"
4229
0
                        " in wrong place - skipped\n"), keystr(keyid));
4230
338
          delete_kbnode( node );
4231
338
        }
4232
7.20k
      else if (node->pkt->pkttype == PKT_SIGNATURE
4233
7.20k
               && !IS_CERT(node->pkt->pkt.signature))
4234
320
        {
4235
320
          if(opt.verbose)
4236
320
            log_info(_("key %s: unexpected signature class (0x%02X) -"
4237
0
                       " skipped\n"),keystr(keyid),
4238
0
                     node->pkt->pkt.signature->sig_class);
4239
320
          delete_kbnode(node);
4240
320
    }
4241
6.88k
      else if ((node->flag & NODE_DELETION_MARK))
4242
327
        delete_kbnode( node );
4243
40.4k
    }
4244
4245
  /* note: because keyblock is the public key, it is never marked
4246
   * for deletion and so keyblock cannot change */
4247
10.3k
  commit_kbnode( &keyblock );
4248
10.3k
  return nvalid;
4249
10.3k
}
4250
4251
/* This function returns true if any UID is left in the keyring.  */
4252
static int
4253
any_uid_left (kbnode_t keyblock)
4254
0
{
4255
0
  kbnode_t node;
4256
4257
0
  for (node=keyblock->next; node; node = node->next)
4258
0
    if (node->pkt->pkttype == PKT_USER_ID)
4259
0
      return 1;
4260
0
  return 0;
4261
0
}
4262
4263
4264
/* Delete all non-self-sigs from KEYBLOCK.
4265
 * Returns: True if the keyblock has changed.  */
4266
static void
4267
remove_all_non_self_sigs (kbnode_t *keyblock, u32 *keyid)
4268
0
{
4269
0
  kbnode_t node;
4270
0
  unsigned int dropped = 0;
4271
4272
0
  for (node = *keyblock; node; node = node->next)
4273
0
    {
4274
0
      if (is_deleted_kbnode (node))
4275
0
  continue;
4276
4277
0
      if (node->pkt->pkttype != PKT_SIGNATURE)
4278
0
  continue;
4279
4280
0
      if (node->pkt->pkt.signature->keyid[0] == keyid[0]
4281
0
          && node->pkt->pkt.signature->keyid[1] == keyid[1])
4282
0
        continue;
4283
0
      delete_kbnode (node);
4284
0
      dropped++;
4285
0
    }
4286
4287
0
  if (dropped)
4288
0
    commit_kbnode (keyblock);
4289
4290
0
  if (dropped && opt.verbose)
4291
0
    log_info ("key %s: number of dropped non-self-signatures: %u\n",
4292
0
              keystr (keyid), dropped);
4293
0
}
4294
4295
4296
/*
4297
 * It may happen that the imported keyblock has duplicated user IDs.
4298
 * We check this here and collapse those user IDs together with their
4299
 * sigs into one.
4300
 * Returns: True if the keyblock has changed.
4301
 */
4302
int
4303
collapse_uids (kbnode_t *keyblock)
4304
0
{
4305
0
  kbnode_t uid1;
4306
0
  int any=0;
4307
4308
0
  for(uid1=*keyblock;uid1;uid1=uid1->next)
4309
0
    {
4310
0
      kbnode_t uid2;
4311
4312
0
      if(is_deleted_kbnode(uid1))
4313
0
  continue;
4314
4315
0
      if(uid1->pkt->pkttype!=PKT_USER_ID)
4316
0
  continue;
4317
4318
0
      for(uid2=uid1->next;uid2;uid2=uid2->next)
4319
0
  {
4320
0
    if(is_deleted_kbnode(uid2))
4321
0
      continue;
4322
4323
0
    if(uid2->pkt->pkttype!=PKT_USER_ID)
4324
0
      continue;
4325
4326
0
    if(cmp_user_ids(uid1->pkt->pkt.user_id,
4327
0
        uid2->pkt->pkt.user_id)==0)
4328
0
      {
4329
        /* We have a duplicated uid */
4330
0
        kbnode_t sig1,last;
4331
4332
0
        any=1;
4333
4334
        /* Now take uid2's signatures, and attach them to
4335
     uid1 */
4336
0
        for(last=uid2;last->next;last=last->next)
4337
0
    {
4338
0
      if(is_deleted_kbnode(last))
4339
0
        continue;
4340
4341
0
      if(last->next->pkt->pkttype==PKT_USER_ID
4342
0
         || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
4343
0
         || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
4344
0
        break;
4345
0
    }
4346
4347
        /* Snip out uid2 */
4348
0
        (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
4349
4350
        /* Now put uid2 in place as part of uid1 */
4351
0
        last->next=uid1->next;
4352
0
        uid1->next=uid2;
4353
0
        delete_kbnode(uid2);
4354
4355
        /* Now dedupe uid1 */
4356
0
        for(sig1=uid1->next;sig1;sig1=sig1->next)
4357
0
    {
4358
0
      kbnode_t sig2;
4359
4360
0
      if(is_deleted_kbnode(sig1))
4361
0
        continue;
4362
4363
0
      if(sig1->pkt->pkttype==PKT_USER_ID
4364
0
         || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
4365
0
         || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
4366
0
        break;
4367
4368
0
      if(sig1->pkt->pkttype!=PKT_SIGNATURE)
4369
0
        continue;
4370
4371
0
      for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
4372
0
        {
4373
0
          if(is_deleted_kbnode(sig2))
4374
0
      continue;
4375
4376
0
          if(sig2->pkt->pkttype==PKT_USER_ID
4377
0
       || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
4378
0
       || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
4379
0
      break;
4380
4381
0
          if(sig2->pkt->pkttype!=PKT_SIGNATURE)
4382
0
      continue;
4383
4384
0
          if(cmp_signatures(sig1->pkt->pkt.signature,
4385
0
          sig2->pkt->pkt.signature)==0)
4386
0
      {
4387
        /* We have a match, so delete the second
4388
           signature */
4389
0
        delete_kbnode(sig2);
4390
0
        sig2=last;
4391
0
      }
4392
0
        }
4393
0
    }
4394
0
      }
4395
0
  }
4396
0
    }
4397
4398
0
  commit_kbnode(keyblock);
4399
4400
0
  if(any && !opt.quiet)
4401
0
    {
4402
0
      const char *key="???";
4403
4404
0
      if ((uid1 = find_kbnode (*keyblock, PKT_PUBLIC_KEY)) )
4405
0
  key = keystr_from_pk (uid1->pkt->pkt.public_key);
4406
0
      else if ((uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY)) )
4407
0
  key = keystr_from_pk (uid1->pkt->pkt.public_key);
4408
4409
0
      log_info (_("key %s: duplicated user ID detected - merged\n"), key);
4410
0
    }
4411
4412
0
  return any;
4413
0
}
4414
4415
4416
/*
4417
 * It may happen that the imported keyblock has duplicated subkeys.
4418
 * We check this here and collapse those subkeys along with their
4419
 * binding self-signatures.
4420
 * Returns: True if the keyblock has changed.
4421
 */
4422
int
4423
collapse_subkeys (kbnode_t *keyblock)
4424
0
{
4425
0
  kbnode_t kb1, kb2, sig1, sig2, last;
4426
0
  int any = 0;
4427
4428
0
  for (kb1 = *keyblock; kb1; kb1 = kb1->next)
4429
0
    {
4430
0
      if (is_deleted_kbnode (kb1))
4431
0
  continue;
4432
4433
0
      if (kb1->pkt->pkttype != PKT_PUBLIC_SUBKEY
4434
0
          && kb1->pkt->pkttype != PKT_SECRET_SUBKEY)
4435
0
  continue;
4436
4437
      /* We assume just a few duplicates and use a straightforward
4438
       * algorithm.  */
4439
0
      for (kb2 = kb1->next; kb2; kb2 = kb2->next)
4440
0
  {
4441
0
    if (is_deleted_kbnode (kb2))
4442
0
      continue;
4443
4444
0
          if (kb2->pkt->pkttype != PKT_PUBLIC_SUBKEY
4445
0
              && kb2->pkt->pkttype != PKT_SECRET_SUBKEY)
4446
0
      continue;
4447
4448
0
          if (cmp_public_keys (kb1->pkt->pkt.public_key,
4449
0
                               kb2->pkt->pkt.public_key))
4450
0
            continue;
4451
4452
          /* We have a duplicated subkey. */
4453
0
          any = 1;
4454
4455
          /* Take subkey-2's signatures, and attach them to subkey-1. */
4456
0
          for (last = kb2; last->next; last = last->next)
4457
0
            {
4458
0
              if (is_deleted_kbnode (last))
4459
0
                continue;
4460
4461
0
              if (last->next->pkt->pkttype != PKT_SIGNATURE)
4462
0
                break;
4463
0
            }
4464
4465
          /* Snip out subkye-2 */
4466
0
          find_prev_kbnode (*keyblock, kb2, 0)->next = last->next;
4467
4468
    /* Put subkey-2 in place as part of subkey-1 */
4469
0
          last->next = kb1->next;
4470
0
          kb1->next = kb2;
4471
0
          delete_kbnode (kb2);
4472
4473
          /* Now dedupe kb1 */
4474
0
          for (sig1 = kb1->next; sig1; sig1 = sig1->next)
4475
0
            {
4476
0
              if (is_deleted_kbnode (sig1))
4477
0
                continue;
4478
4479
0
              if (sig1->pkt->pkttype != PKT_SIGNATURE)
4480
0
                break;
4481
4482
0
              for (sig2 = sig1->next, last = sig1;
4483
0
                   sig2;
4484
0
                   last = sig2, sig2 = sig2->next)
4485
0
                {
4486
0
                  if (is_deleted_kbnode (sig2))
4487
0
                    continue;
4488
4489
0
                  if (sig2->pkt->pkttype != PKT_SIGNATURE)
4490
0
                    break;
4491
4492
0
                  if (!cmp_signatures (sig1->pkt->pkt.signature,
4493
0
                                       sig2->pkt->pkt.signature))
4494
0
                    {
4495
                      /* We have a match, so delete the second
4496
                         signature */
4497
0
                      delete_kbnode (sig2);
4498
0
                      sig2 = last;
4499
0
                    }
4500
0
                }
4501
0
            }
4502
0
        }
4503
0
    }
4504
4505
0
  commit_kbnode (keyblock);
4506
4507
0
  if (any && !opt.quiet)
4508
0
    {
4509
0
      const char *key="???";
4510
4511
0
      if ((kb1 = find_kbnode (*keyblock, PKT_PUBLIC_KEY)) )
4512
0
  key = keystr_from_pk (kb1->pkt->pkt.public_key);
4513
0
      else if ((kb1 = find_kbnode (*keyblock, PKT_SECRET_KEY)) )
4514
0
  key = keystr_from_pk (kb1->pkt->pkt.public_key);
4515
4516
0
      log_info (_("key %s: duplicated subkeys detected - merged\n"), key);
4517
0
    }
4518
4519
0
  return any;
4520
0
}
4521
4522
4523
/* Check for a 0x20 revocation from a revocation key that is not
4524
   present.  This may be called without the benefit of merge_xxxx so
4525
   you can't rely on pk->revkey and friends. */
4526
static void
4527
revocation_present (ctrl_t ctrl, kbnode_t keyblock)
4528
2.88k
{
4529
2.88k
  kbnode_t onode, inode;
4530
2.88k
  PKT_public_key *pk = keyblock->pkt->pkt.public_key;
4531
4532
7.37k
  for(onode=keyblock->next;onode;onode=onode->next)
4533
7.37k
    {
4534
      /* If we reach user IDs, we're done. */
4535
7.37k
      if(onode->pkt->pkttype==PKT_USER_ID)
4536
2.88k
  break;
4537
4538
4.48k
      if (onode->pkt->pkttype == PKT_SIGNATURE
4539
4.48k
          && IS_KEY_SIG (onode->pkt->pkt.signature)
4540
778
          && onode->pkt->pkt.signature->revkey)
4541
31
  {
4542
31
    int idx;
4543
31
    PKT_signature *sig=onode->pkt->pkt.signature;
4544
4545
62
    for(idx=0;idx<sig->numrevkeys;idx++)
4546
31
      {
4547
31
        u32 keyid[2];
4548
4549
31
        keyid_from_fingerprint (ctrl, sig->revkey[idx].fpr,
4550
31
                                      sig->revkey[idx].fprlen, keyid);
4551
4552
139
        for(inode=keyblock->next;inode;inode=inode->next)
4553
139
    {
4554
      /* If we reach user IDs, we're done. */
4555
139
      if(inode->pkt->pkttype==PKT_USER_ID)
4556
31
        break;
4557
4558
108
      if (inode->pkt->pkttype == PKT_SIGNATURE
4559
108
                      && IS_KEY_REV (inode->pkt->pkt.signature)
4560
51
                      && inode->pkt->pkt.signature->keyid[0]==keyid[0]
4561
0
                      && inode->pkt->pkt.signature->keyid[1]==keyid[1])
4562
0
        {
4563
          /* Okay, we have a revocation key, and a
4564
                       * revocation issued by it.  Do we have the key
4565
                       * itself?  */
4566
0
                      gpg_error_t err;
4567
4568
0
          err = get_pubkey_byfpr_fast (ctrl, NULL,
4569
0
                                                   sig->revkey[idx].fpr,
4570
0
                                                   sig->revkey[idx].fprlen);
4571
0
          if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY
4572
0
                          || gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY)
4573
0
      {
4574
0
        char *tempkeystr = xstrdup (keystr_from_pk (pk));
4575
4576
        /* No, so try and get it */
4577
0
        if ((opt.keyserver_options.options
4578
0
                               & KEYSERVER_AUTO_KEY_RETRIEVE)
4579
0
                              && keyserver_any_configured (ctrl))
4580
0
          {
4581
0
            log_info(_("WARNING: key %s may be revoked:"
4582
0
           " fetching revocation key %s\n"),
4583
0
               tempkeystr,keystr(keyid));
4584
0
            keyserver_import_fpr (ctrl,
4585
0
                                                    sig->revkey[idx].fpr,
4586
0
                                                    sig->revkey[idx].fprlen,
4587
0
                                                    opt.keyserver, 0);
4588
4589
            /* Do we have it now? */
4590
0
            err = get_pubkey_byfpr_fast (ctrl, NULL,
4591
0
                 sig->revkey[idx].fpr,
4592
0
                                                     sig->revkey[idx].fprlen);
4593
0
          }
4594
4595
0
        if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY
4596
0
                              || gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY)
4597
0
          log_info(_("WARNING: key %s may be revoked:"
4598
0
               " revocation key %s not present.\n"),
4599
0
             tempkeystr,keystr(keyid));
4600
4601
0
        xfree(tempkeystr);
4602
0
      }
4603
0
        }
4604
108
    }
4605
31
      }
4606
31
  }
4607
4.48k
    }
4608
2.88k
}
4609
4610
4611
/*
4612
 * compare and merge the blocks
4613
 *
4614
 * o compare the signatures: If we already have this signature, check
4615
 *   that they compare okay; if not, issue a warning and ask the user.
4616
 * o Simply add the signature.  Can't verify here because we may not have
4617
 *   the signature's public key yet; verification is done when putting it
4618
 *   into the trustdb, which is done automagically as soon as this pubkey
4619
 *   is used.
4620
 * Note: We indicate newly inserted packets with NODE_FLAG_A.
4621
 */
4622
static int
4623
merge_blocks (ctrl_t ctrl, unsigned int options,
4624
              kbnode_t keyblock_orig, kbnode_t keyblock,
4625
              u32 *keyid, u32 curtime, int origin, const char *url,
4626
        int *n_uids, int *n_sigs, int *n_subk )
4627
3.10k
{
4628
3.10k
  kbnode_t onode, node;
4629
3.10k
  int rc, found;
4630
4631
  /* 1st: handle revocation certificates */
4632
5.13k
  for (node=keyblock->next; node; node=node->next )
4633
5.13k
    {
4634
5.13k
      if (node->pkt->pkttype == PKT_USER_ID )
4635
3.10k
        break;
4636
2.03k
      else if (node->pkt->pkttype == PKT_SIGNATURE
4637
1.53k
               && IS_KEY_REV (node->pkt->pkt.signature))
4638
106
        {
4639
          /* check whether we already have this */
4640
106
          found = 0;
4641
2.15k
          for (onode=keyblock_orig->next; onode; onode=onode->next)
4642
2.15k
            {
4643
2.15k
              if (onode->pkt->pkttype == PKT_USER_ID )
4644
68
                break;
4645
2.08k
              else if (onode->pkt->pkttype == PKT_SIGNATURE
4646
2.08k
                       && IS_KEY_REV (onode->pkt->pkt.signature)
4647
1.41k
                       && !cmp_signatures(onode->pkt->pkt.signature,
4648
1.41k
                                          node->pkt->pkt.signature))
4649
38
                {
4650
38
                  found = 1;
4651
38
                  break;
4652
38
                }
4653
2.15k
      }
4654
106
          if (!found)
4655
68
            {
4656
68
              kbnode_t n2 = clone_kbnode(node);
4657
68
              insert_kbnode( keyblock_orig, n2, 0 );
4658
68
              n2->flag |= NODE_FLAG_A;
4659
68
              ++*n_sigs;
4660
68
              if(!opt.quiet)
4661
68
                {
4662
68
                  char *p = get_user_id_native (ctrl, keyid);
4663
68
                  log_info(_("key %s: \"%s\" revocation"
4664
68
                             " certificate added\n"), keystr(keyid),p);
4665
68
                  xfree(p);
4666
68
                }
4667
68
      }
4668
106
  }
4669
5.13k
    }
4670
4671
  /* 2nd: merge in any direct key (0x1F) sigs */
4672
5.13k
  for(node=keyblock->next; node; node=node->next)
4673
5.13k
    {
4674
5.13k
      if (node->pkt->pkttype == PKT_USER_ID )
4675
3.10k
        break;
4676
2.03k
      else if (node->pkt->pkttype == PKT_SIGNATURE
4677
1.53k
               && IS_KEY_SIG (node->pkt->pkt.signature))
4678
787
        {
4679
          /* check whether we already have this */
4680
787
          found = 0;
4681
5.93k
          for (onode=keyblock_orig->next; onode; onode=onode->next)
4682
5.93k
            {
4683
5.93k
              if (onode->pkt->pkttype == PKT_USER_ID)
4684
762
                break;
4685
5.17k
              else if (onode->pkt->pkttype == PKT_SIGNATURE
4686
5.17k
                       && IS_KEY_SIG (onode->pkt->pkt.signature)
4687
418
                       && !cmp_signatures(onode->pkt->pkt.signature,
4688
418
                                          node->pkt->pkt.signature))
4689
25
                {
4690
25
                  found = 1;
4691
25
                  break;
4692
25
    }
4693
5.93k
      }
4694
787
          if (!found )
4695
762
            {
4696
762
              kbnode_t n2 = clone_kbnode(node);
4697
762
              insert_kbnode( keyblock_orig, n2, 0 );
4698
762
              n2->flag |= NODE_FLAG_A;
4699
762
              ++*n_sigs;
4700
762
              if(!opt.quiet)
4701
762
                log_info( _("key %s: direct key signature added\n"),
4702
762
                          keystr(keyid));
4703
762
            }
4704
787
  }
4705
5.13k
    }
4706
4707
  /* 3rd: try to merge new certificates in */
4708
8.14M
  for (onode=keyblock_orig->next; onode; onode=onode->next)
4709
8.13M
    {
4710
8.13M
      if (!(onode->flag & NODE_FLAG_A) && onode->pkt->pkttype == PKT_USER_ID)
4711
5.78k
        {
4712
          /* find the user id in the imported keyblock */
4713
15.7k
          for (node=keyblock->next; node; node=node->next)
4714
13.0k
            if (node->pkt->pkttype == PKT_USER_ID
4715
5.82k
                && !cmp_user_ids( onode->pkt->pkt.user_id,
4716
5.82k
                                  node->pkt->pkt.user_id ) )
4717
3.11k
              break;
4718
5.78k
          if (node ) /* found: merge */
4719
3.11k
            {
4720
3.11k
              rc = merge_sigs (onode, node, n_sigs);
4721
3.11k
              if (rc )
4722
0
                return rc;
4723
3.11k
      }
4724
5.78k
  }
4725
8.13M
    }
4726
4727
  /* 4th: add new user-ids */
4728
12.0k
  for (node=keyblock->next; node; node=node->next)
4729
8.96k
    {
4730
8.96k
      if (node->pkt->pkttype == PKT_USER_ID)
4731
3.22k
        {
4732
          /* do we have this in the original keyblock */
4733
22.2k
          for (onode=keyblock_orig->next; onode; onode=onode->next )
4734
22.2k
            if (onode->pkt->pkttype == PKT_USER_ID
4735
3.28k
                && !cmp_user_ids( onode->pkt->pkt.user_id,
4736
3.28k
                                  node->pkt->pkt.user_id ) )
4737
3.21k
              break;
4738
3.22k
          if (!onode ) /* this is a new user id: append */
4739
4
            {
4740
4
              rc = append_new_uid (options, keyblock_orig, node,
4741
4
                                   curtime, origin, url, n_sigs);
4742
4
              if (rc )
4743
0
                return rc;
4744
4
              ++*n_uids;
4745
4
      }
4746
3.22k
  }
4747
8.96k
    }
4748
4749
  /* 5th: add new subkeys */
4750
12.0k
  for (node=keyblock->next; node; node=node->next)
4751
8.96k
    {
4752
8.96k
      onode = NULL;
4753
8.96k
      if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4754
552
        {
4755
          /* do we have this in the original keyblock? */
4756
1.14M
          for(onode=keyblock_orig->next; onode; onode=onode->next)
4757
1.14M
            if (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
4758
62.3k
                && !cmp_public_keys( onode->pkt->pkt.public_key,
4759
62.3k
                                     node->pkt->pkt.public_key))
4760
187
              break;
4761
552
          if (!onode ) /* This is a new subkey: append.  */
4762
365
            {
4763
365
              rc = append_key (keyblock_orig, node, n_sigs);
4764
365
              if (rc)
4765
0
                return rc;
4766
365
              ++*n_subk;
4767
365
      }
4768
552
  }
4769
8.40k
      else if (node->pkt->pkttype == PKT_SECRET_SUBKEY)
4770
0
        {
4771
          /* do we have this in the original keyblock? */
4772
0
          for (onode=keyblock_orig->next; onode; onode=onode->next )
4773
0
            if (onode->pkt->pkttype == PKT_SECRET_SUBKEY
4774
0
                && !cmp_public_keys (onode->pkt->pkt.public_key,
4775
0
                                     node->pkt->pkt.public_key) )
4776
0
              break;
4777
0
          if (!onode ) /* This is a new subkey: append.  */
4778
0
            {
4779
0
              rc = append_key (keyblock_orig, node, n_sigs);
4780
0
              if (rc )
4781
0
                return rc;
4782
0
              ++*n_subk;
4783
0
      }
4784
0
  }
4785
8.96k
    }
4786
4787
  /* 6th: merge subkey certificates */
4788
8.14M
  for (onode=keyblock_orig->next; onode; onode=onode->next)
4789
8.14M
    {
4790
8.14M
      if (!(onode->flag & NODE_FLAG_A)
4791
8.13M
          && (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
4792
7.63M
              || onode->pkt->pkttype == PKT_SECRET_SUBKEY))
4793
504k
        {
4794
          /* find the subkey in the imported keyblock */
4795
1.76M
          for(node=keyblock->next; node; node=node->next)
4796
1.27M
            {
4797
1.27M
              if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
4798
1.19M
                   || node->pkt->pkttype == PKT_SECRET_SUBKEY)
4799
80.7k
                  && !cmp_public_keys( onode->pkt->pkt.public_key,
4800
80.7k
                                       node->pkt->pkt.public_key ) )
4801
18.6k
                break;
4802
1.27M
      }
4803
504k
          if (node) /* Found: merge.  */
4804
18.6k
            {
4805
18.6k
              rc = merge_keysigs( onode, node, n_sigs);
4806
18.6k
              if (rc )
4807
0
                return rc;
4808
18.6k
      }
4809
504k
  }
4810
8.14M
    }
4811
4812
3.10k
  return 0;
4813
3.10k
}
4814
4815
4816
/* Helper function for merge_blocks.
4817
 *
4818
 * Append the new userid starting with NODE and all signatures to
4819
 * KEYBLOCK.  ORIGIN and URL conveys the usual key origin info.  The
4820
 * integer at N_SIGS is updated with the number of new signatures.
4821
 */
4822
static gpg_error_t
4823
append_new_uid (unsigned int options,
4824
                kbnode_t keyblock, kbnode_t node, u32 curtime,
4825
                int origin, const char *url, int *n_sigs)
4826
4
{
4827
4
  gpg_error_t err;
4828
4
  kbnode_t n;
4829
4
  kbnode_t n_where = NULL;
4830
4831
4
  log_assert (node->pkt->pkttype == PKT_USER_ID);
4832
4833
  /* Find the right position for the new user id and its signatures.  */
4834
19
  for (n = keyblock; n; n_where = n, n = n->next)
4835
15
    {
4836
15
      if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
4837
15
          || n->pkt->pkttype == PKT_SECRET_SUBKEY )
4838
0
        break;
4839
15
    }
4840
4
  if (!n)
4841
4
    n_where = NULL;
4842
4843
  /* and append/insert */
4844
12
  while (node)
4845
9
    {
4846
      /* we add a clone to the original keyblock, because this
4847
       * one is released first. */
4848
9
      n = clone_kbnode(node);
4849
9
      if (n->pkt->pkttype == PKT_USER_ID
4850
4
          && !(options & IMPORT_RESTORE) )
4851
4
        {
4852
4
          err = insert_key_origin_uid (n->pkt->pkt.user_id,
4853
4
                                       curtime, origin, url);
4854
4
          if (err)
4855
0
            {
4856
0
              release_kbnode (n);
4857
0
              return err;
4858
0
            }
4859
4
        }
4860
4861
9
      if (n_where)
4862
0
        {
4863
0
          insert_kbnode( n_where, n, 0 );
4864
0
          n_where = n;
4865
0
  }
4866
9
      else
4867
9
        add_kbnode( keyblock, n );
4868
9
      n->flag |= NODE_FLAG_A;
4869
9
      node->flag |= NODE_FLAG_A;
4870
9
      if (n->pkt->pkttype == PKT_SIGNATURE )
4871
5
        ++*n_sigs;
4872
4873
9
      node = node->next;
4874
9
      if (node && node->pkt->pkttype != PKT_SIGNATURE )
4875
1
        break;
4876
9
    }
4877
4878
4
  return 0;
4879
4
}
4880
4881
4882
/* Helper function for merge_blocks
4883
 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
4884
 * (how should we handle comment packets here?)
4885
 */
4886
static int
4887
merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs)
4888
3.11k
{
4889
3.11k
  kbnode_t n, n2;
4890
3.11k
  int found = 0;
4891
4892
3.11k
  log_assert (dst->pkt->pkttype == PKT_USER_ID);
4893
3.11k
  log_assert (src->pkt->pkttype == PKT_USER_ID);
4894
4895
6.70k
  for (n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next)
4896
3.59k
    {
4897
3.59k
      if (n->pkt->pkttype != PKT_SIGNATURE )
4898
51
        continue;
4899
3.54k
      if (IS_SUBKEY_SIG (n->pkt->pkt.signature)
4900
3.49k
          || IS_SUBKEY_REV (n->pkt->pkt.signature) )
4901
93
        continue; /* skip signatures which are only valid on subkeys */
4902
4903
3.44k
      found = 0;
4904
3.92M
      for (n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
4905
3.92M
        if (!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
4906
377
          {
4907
377
            found++;
4908
377
            break;
4909
377
          }
4910
3.44k
      if (!found )
4911
3.07k
        {
4912
          /* This signature is new or newer, append N to DST.
4913
           * We add a clone to the original keyblock, because this
4914
           * one is released first */
4915
3.07k
          n2 = clone_kbnode(n);
4916
3.07k
          insert_kbnode( dst, n2, PKT_SIGNATURE );
4917
3.07k
          n2->flag |= NODE_FLAG_A;
4918
3.07k
          n->flag |= NODE_FLAG_A;
4919
3.07k
          ++*n_sigs;
4920
3.07k
  }
4921
3.44k
    }
4922
4923
3.11k
  return 0;
4924
3.11k
}
4925
4926
4927
/* Helper function for merge_blocks
4928
 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
4929
 */
4930
static int
4931
merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs)
4932
18.6k
{
4933
18.6k
  kbnode_t n, n2;
4934
18.6k
  int found = 0;
4935
4936
18.6k
  log_assert (dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
4937
18.6k
              || dst->pkt->pkttype == PKT_SECRET_SUBKEY);
4938
4939
93.4k
  for (n=src->next; n ; n = n->next)
4940
74.8k
    {
4941
74.8k
      if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
4942
74.7k
          || n->pkt->pkttype == PKT_PUBLIC_KEY )
4943
11
        break;
4944
74.7k
      if (n->pkt->pkttype != PKT_SIGNATURE )
4945
18.6k
        continue;
4946
4947
56.1k
      found = 0;
4948
206k
      for (n2=dst->next; n2; n2 = n2->next)
4949
206k
        {
4950
206k
          if (n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
4951
204k
              || n2->pkt->pkttype == PKT_PUBLIC_KEY )
4952
1.66k
            break;
4953
204k
          if (n2->pkt->pkttype == PKT_SIGNATURE
4954
204k
              && (n->pkt->pkt.signature->keyid[0]
4955
204k
                  == n2->pkt->pkt.signature->keyid[0])
4956
78.6k
              && (n->pkt->pkt.signature->keyid[1]
4957
78.6k
                  == n2->pkt->pkt.signature->keyid[1])
4958
73.9k
              && (n->pkt->pkt.signature->timestamp
4959
73.9k
                  <= n2->pkt->pkt.signature->timestamp)
4960
73.7k
              && (n->pkt->pkt.signature->sig_class
4961
73.7k
                  == n2->pkt->pkt.signature->sig_class))
4962
54.4k
            {
4963
54.4k
              found++;
4964
54.4k
              break;
4965
54.4k
      }
4966
204k
  }
4967
56.1k
      if (!found )
4968
1.77k
        {
4969
          /* This signature is new or newer, append N to DST.
4970
           * We add a clone to the original keyblock, because this
4971
           * one is released first */
4972
1.77k
          n2 = clone_kbnode(n);
4973
1.77k
          insert_kbnode( dst, n2, PKT_SIGNATURE );
4974
1.77k
          n2->flag |= NODE_FLAG_A;
4975
1.77k
          n->flag |= NODE_FLAG_A;
4976
1.77k
          ++*n_sigs;
4977
1.77k
  }
4978
56.1k
    }
4979
4980
18.6k
  return 0;
4981
18.6k
}
4982
4983
4984
/* Helper function for merge_blocks.
4985
 * Append the subkey starting with NODE and all signatures to KEYBLOCK.
4986
 * Mark all new and copied packets by setting flag bit 0.
4987
 */
4988
static int
4989
append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs)
4990
365
{
4991
365
  kbnode_t n;
4992
4993
365
  log_assert (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
4994
365
              || node->pkt->pkttype == PKT_SECRET_SUBKEY);
4995
4996
1.28k
  while (node)
4997
1.26k
    {
4998
      /* we add a clone to the original keyblock, because this
4999
       * one is released first */
5000
1.26k
      n = clone_kbnode(node);
5001
1.26k
      add_kbnode( keyblock, n );
5002
1.26k
      n->flag |= NODE_FLAG_A;
5003
1.26k
      node->flag |= NODE_FLAG_A;
5004
1.26k
      if (n->pkt->pkttype == PKT_SIGNATURE )
5005
899
        ++*n_sigs;
5006
5007
1.26k
      node = node->next;
5008
1.26k
      if (node && node->pkt->pkttype != PKT_SIGNATURE )
5009
340
        break;
5010
1.26k
    }
5011
5012
365
  return 0;
5013
365
}