chiark / gitweb /
doc: Document summary values of TOFU_STATS
[gnupg2.git] / g10 / import.c
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  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 "status.h"
31 #include "keydb.h"
32 #include "util.h"
33 #include "trustdb.h"
34 #include "main.h"
35 #include "i18n.h"
36 #include "ttyio.h"
37 #include "status.h"
38 #include "recsel.h"
39 #include "keyserver-internal.h"
40 #include "call-agent.h"
41 #include "../common/membuf.h"
42 #include "../common/init.h"
43 #include "../common/mbox-util.h"
44
45
46 struct import_stats_s
47 {
48   ulong count;
49   ulong no_user_id;
50   ulong imported;
51   ulong n_uids;
52   ulong n_sigs;
53   ulong n_subk;
54   ulong unchanged;
55   ulong n_revoc;
56   ulong secret_read;
57   ulong secret_imported;
58   ulong secret_dups;
59   ulong skipped_new_keys;
60   ulong not_imported;
61   ulong n_sigs_cleaned;
62   ulong n_uids_cleaned;
63   ulong v3keys;   /* Number of V3 keys seen.  */
64 };
65
66
67 /* Node flag to indicate that a user ID or a subkey has a
68  * valid self-signature.  */
69 #define NODE_GOOD_SELFSIG  1
70 /* Node flag to indicate that a user ID or subkey has
71  * an invalid self-signature.  */
72 #define NODE_BAD_SELFSIG   2
73 /* Node flag to indicate that the node shall be deleted.  */
74 #define NODE_DELETION_MARK 4
75 /* A node flag used to temporary mark a node. */
76 #define NODE_FLAG_A  8
77
78
79 /* A an object and a global instance to store selectors created from
80  * --import-filter keep-uid=EXPR.
81  * --import-filter drop-sig=EXPR.
82  *
83  * FIXME: We should put this into the CTRL object but that requires a
84  * lot more changes right now.  For now we use save and restore
85  * function to temporary change them.
86  */
87 /* Definition of the import filters.  */
88 struct import_filter_s
89 {
90   recsel_expr_t keep_uid;
91   recsel_expr_t drop_sig;
92 };
93 /* The current instance.  */
94 struct import_filter_s import_filter;
95
96
97 static int import (ctrl_t ctrl,
98                    IOBUF inp, const char* fname, struct import_stats_s *stats,
99                    unsigned char **fpr, size_t *fpr_len, unsigned int options,
100                    import_screener_t screener, void *screener_arg);
101 static int read_block (IOBUF a, PACKET **pending_pkt, kbnode_t *ret_root,
102                        int *r_v3keys);
103 static void revocation_present (ctrl_t ctrl, kbnode_t keyblock);
104 static int import_one (ctrl_t ctrl,
105                        kbnode_t keyblock,
106                        struct import_stats_s *stats,
107                        unsigned char **fpr, size_t *fpr_len,
108                        unsigned int options, int from_sk, int silent,
109                        import_screener_t screener, void *screener_arg);
110 static int import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
111                               struct import_stats_s *stats, int batch,
112                               unsigned int options, int for_migration,
113                               import_screener_t screener, void *screener_arg);
114 static int import_revoke_cert (ctrl_t ctrl,
115                                kbnode_t node, struct import_stats_s *stats);
116 static int chk_self_sigs (kbnode_t keyblock, u32 *keyid, int *non_self);
117 static int delete_inv_parts (kbnode_t keyblock,
118                              u32 *keyid, unsigned int options);
119 static int any_uid_left (kbnode_t keyblock);
120 static int merge_blocks (kbnode_t keyblock_orig,
121                          kbnode_t keyblock, u32 *keyid,
122                          int *n_uids, int *n_sigs, int *n_subk );
123 static int append_uid (kbnode_t keyblock, kbnode_t node, int *n_sigs);
124 static int append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs);
125 static int merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs);
126 static int merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs);
127
128
129 \f
130 static void
131 release_import_filter (import_filter_t filt)
132 {
133   recsel_release (filt->keep_uid);
134   filt->keep_uid = NULL;
135   recsel_release (filt->drop_sig);
136   filt->drop_sig = NULL;
137 }
138
139 static void
140 cleanup_import_globals (void)
141 {
142   release_import_filter (&import_filter);
143 }
144
145
146 int
147 parse_import_options(char *str,unsigned int *options,int noisy)
148 {
149   struct parse_options import_opts[]=
150     {
151       {"import-local-sigs",IMPORT_LOCAL_SIGS,NULL,
152        N_("import signatures that are marked as local-only")},
153
154       {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,
155        N_("repair damage from the pks keyserver during import")},
156
157       {"keep-ownertrust", IMPORT_KEEP_OWNERTTRUST, NULL,
158        N_("do not clear the ownertrust values during import")},
159
160       {"fast-import",IMPORT_FAST,NULL,
161        N_("do not update the trustdb after import")},
162
163       {"import-show",IMPORT_SHOW,NULL,
164        N_("show key during import")},
165
166       {"merge-only",IMPORT_MERGE_ONLY,NULL,
167        N_("only accept updates to existing keys")},
168
169       {"import-clean",IMPORT_CLEAN,NULL,
170        N_("remove unusable parts from key after import")},
171
172       {"import-minimal",IMPORT_MINIMAL|IMPORT_CLEAN,NULL,
173        N_("remove as much as possible from key after import")},
174
175       {"import-export", IMPORT_EXPORT, NULL,
176        N_("run import filters and export key immediately")},
177
178       /* Aliases for backward compatibility */
179       {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL},
180       {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL},
181       /* dummy */
182       {"import-unusable-sigs",0,NULL,NULL},
183       {"import-clean-sigs",0,NULL,NULL},
184       {"import-clean-uids",0,NULL,NULL},
185       {"convert-sk-to-pk",0, NULL,NULL}, /* Not anymore needed due to
186                                             the new design.  */
187       {NULL,0,NULL,NULL}
188     };
189
190   return parse_options(str,options,import_opts,noisy);
191 }
192
193
194 /* Parse and set an import filter from string.  STRING has the format
195  * "NAME=EXPR" with NAME being the name of the filter.  Spaces before
196  * and after NAME are not allowed.  If this function is all called
197  * several times all expressions for the same NAME are concatenated.
198  * Supported filter names are:
199  *
200  *  - keep-uid :: If the expression evaluates to true for a certain
201  *                user ID packet, that packet and all it dependencies
202  *                will be imported.  The expression may use these
203  *                variables:
204  *
205  *                - uid  :: The entire user ID.
206  *                - mbox :: The mail box part of the user ID.
207  *                - primary :: Evaluate to true for the primary user ID.
208  */
209 gpg_error_t
210 parse_and_set_import_filter (const char *string)
211 {
212   gpg_error_t err;
213
214   /* Auto register the cleanup function.  */
215   register_mem_cleanup_func (cleanup_import_globals);
216
217   if (!strncmp (string, "keep-uid=", 9))
218     err = recsel_parse_expr (&import_filter.keep_uid, string+9);
219   else if (!strncmp (string, "drop-sig=", 9))
220     err = recsel_parse_expr (&import_filter.drop_sig, string+9);
221   else
222     err = gpg_error (GPG_ERR_INV_NAME);
223
224   return err;
225 }
226
227
228 /* Save the current import filters, return them, and clear the current
229  * filters.  Returns NULL on error and sets ERRNO.  */
230 import_filter_t
231 save_and_clear_import_filter (void)
232 {
233   import_filter_t filt;
234
235   filt = xtrycalloc (1, sizeof *filt);
236   if (!filt)
237     return NULL;
238   *filt = import_filter;
239   memset (&import_filter, 0, sizeof import_filter);
240
241   return filt;
242 }
243
244
245 /* Release the current import filters and restore them from NEWFILT.
246  * Ownership of NEWFILT is moved to this function.  */
247 void
248 restore_import_filter (import_filter_t filt)
249 {
250   if (filt)
251     {
252       release_import_filter (&import_filter);
253       import_filter = *filt;
254       xfree (filt);
255     }
256 }
257
258
259 import_stats_t
260 import_new_stats_handle (void)
261 {
262   return xmalloc_clear ( sizeof (struct import_stats_s) );
263 }
264
265
266 void
267 import_release_stats_handle (import_stats_t p)
268 {
269   xfree (p);
270 }
271
272
273 /* Read a key from a file.  Only the first key in the file is
274  * considered and stored at R_KEYBLOCK.  FNAME is the name of the
275  * file.
276  */
277 gpg_error_t
278 read_key_from_file (ctrl_t ctrl, const char *fname, kbnode_t *r_keyblock)
279 {
280   gpg_error_t err;
281   iobuf_t inp;
282   PACKET *pending_pkt = NULL;
283   kbnode_t keyblock = NULL;
284   u32 keyid[2];
285   int v3keys;   /* Dummy */
286   int non_self; /* Dummy */
287
288   (void)ctrl;
289
290   *r_keyblock = NULL;
291
292   inp = iobuf_open (fname);
293   if (!inp)
294     err = gpg_error_from_syserror ();
295   else if (is_secured_file (iobuf_get_fd (inp)))
296     {
297       iobuf_close (inp);
298       inp = NULL;
299       err = gpg_error (GPG_ERR_EPERM);
300     }
301   else
302     err = 0;
303   if (err)
304     {
305       log_error (_("can't open '%s': %s\n"),
306                  iobuf_is_pipe_filename (fname)? "[stdin]": fname,
307                  gpg_strerror (err));
308       if (gpg_err_code (err) == GPG_ERR_ENOENT)
309         err = gpg_error (GPG_ERR_NO_PUBKEY);
310       goto leave;
311     }
312
313   /* Push the armor filter.  */
314   {
315     armor_filter_context_t *afx;
316     afx = new_armor_context ();
317     afx->only_keyblocks = 1;
318     push_armor_filter (afx, inp);
319     release_armor_context (afx);
320   }
321
322   /* Read the first non-v3 keyblock.  */
323   while (!(err = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
324     {
325       if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
326         break;
327       log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
328       release_kbnode (keyblock);
329       keyblock = NULL;
330     }
331   if (err)
332     {
333       if (gpg_err_code (err) != GPG_ERR_INV_KEYRING)
334         log_error (_("error reading '%s': %s\n"),
335                    iobuf_is_pipe_filename (fname)? "[stdin]": fname,
336                    gpg_strerror (err));
337       goto leave;
338     }
339
340   keyid_from_pk (keyblock->pkt->pkt.public_key, keyid);
341
342   if (!find_next_kbnode (keyblock, PKT_USER_ID))
343     {
344       err = gpg_error (GPG_ERR_NO_USER_ID);
345       goto leave;
346     }
347
348   collapse_uids (&keyblock);
349
350   clear_kbnode_flags (keyblock);
351   if (chk_self_sigs (keyblock, keyid, &non_self))
352     {
353       err = gpg_error (GPG_ERR_INV_KEYRING);
354       goto leave;
355     }
356
357   if (!delete_inv_parts (keyblock, keyid, 0) )
358     {
359       err = gpg_error (GPG_ERR_NO_USER_ID);
360       goto leave;
361     }
362
363   *r_keyblock = keyblock;
364   keyblock = NULL;
365
366  leave:
367   if (inp)
368     {
369       iobuf_close (inp);
370       /* Must invalidate that ugly cache to actually close the file. */
371       iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
372     }
373   release_kbnode (keyblock);
374   /* FIXME: Do we need to free PENDING_PKT ? */
375   return err;
376 }
377
378
379
380 /*
381  * Import the public keys from the given filename. Input may be armored.
382  * This function rejects all keys which are not validly self signed on at
383  * least one userid. Only user ids which are self signed will be imported.
384  * Other signatures are not checked.
385  *
386  * Actually this function does a merge. It works like this:
387  *
388  *  - get the keyblock
389  *  - check self-signatures and remove all userids and their signatures
390  *    without/invalid self-signatures.
391  *  - reject the keyblock, if we have no valid userid.
392  *  - See whether we have this key already in one of our pubrings.
393  *    If not, simply add it to the default keyring.
394  *  - Compare the key and the self-signatures of the new and the one in
395  *    our keyring.  If they are different something weird is going on;
396  *    ask what to do.
397  *  - See whether we have only non-self-signature on one user id; if not
398  *    ask the user what to do.
399  *  - compare the signatures: If we already have this signature, check
400  *    that they compare okay; if not, issue a warning and ask the user.
401  *    (consider looking at the timestamp and use the newest?)
402  *  - Simply add the signature.  Can't verify here because we may not have
403  *    the signature's public key yet; verification is done when putting it
404  *    into the trustdb, which is done automagically as soon as this pubkey
405  *    is used.
406  *  - Proceed with next signature.
407  *
408  *  Key revocation certificates have special handling.
409  */
410 static int
411 import_keys_internal (ctrl_t ctrl, iobuf_t inp, char **fnames, int nnames,
412                       import_stats_t stats_handle,
413                       unsigned char **fpr, size_t *fpr_len,
414                       unsigned int options,
415                       import_screener_t screener, void *screener_arg)
416 {
417   int i;
418   int rc = 0;
419   struct import_stats_s *stats = stats_handle;
420
421   if (!stats)
422     stats = import_new_stats_handle ();
423
424   if (inp)
425     {
426       rc = import (ctrl, inp, "[stream]", stats, fpr, fpr_len, options,
427                    screener, screener_arg);
428     }
429   else
430     {
431       if (!fnames && !nnames)
432         nnames = 1;  /* Ohh what a ugly hack to jump into the loop */
433
434       for (i=0; i < nnames; i++)
435         {
436           const char *fname = fnames? fnames[i] : NULL;
437           IOBUF inp2 = iobuf_open(fname);
438
439           if (!fname)
440             fname = "[stdin]";
441           if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
442             {
443               iobuf_close (inp2);
444               inp2 = NULL;
445               gpg_err_set_errno (EPERM);
446             }
447           if (!inp2)
448             log_error (_("can't open '%s': %s\n"), fname, strerror (errno));
449           else
450             {
451               rc = import (ctrl, inp2, fname, stats, fpr, fpr_len, options,
452                            screener, screener_arg);
453               iobuf_close (inp2);
454               /* Must invalidate that ugly cache to actually close it. */
455               iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
456               if (rc)
457                 log_error ("import from '%s' failed: %s\n",
458                            fname, gpg_strerror (rc) );
459             }
460           if (!fname)
461             break;
462         }
463     }
464
465   if (!stats_handle)
466     {
467       import_print_stats (stats);
468       import_release_stats_handle (stats);
469     }
470
471   /* If no fast import and the trustdb is dirty (i.e. we added a key
472      or userID that had something other than a selfsig, a signature
473      that was other than a selfsig, or any revocation), then
474      update/check the trustdb if the user specified by setting
475      interactive or by not setting no-auto-check-trustdb */
476
477   if (!(options & IMPORT_FAST))
478     check_or_update_trustdb (ctrl);
479
480   return rc;
481 }
482
483
484 void
485 import_keys (ctrl_t ctrl, char **fnames, int nnames,
486              import_stats_t stats_handle, unsigned int options )
487 {
488   import_keys_internal (ctrl, NULL, fnames, nnames, stats_handle,
489                         NULL, NULL, options, NULL, NULL);
490 }
491
492 int
493 import_keys_stream (ctrl_t ctrl, IOBUF inp, import_stats_t stats_handle,
494                     unsigned char **fpr, size_t *fpr_len, unsigned int options)
495 {
496   return import_keys_internal (ctrl, inp, NULL, 0, stats_handle,
497                                fpr, fpr_len, options, NULL, NULL);
498 }
499
500
501 /* Variant of import_keys_stream reading from an estream_t.  */
502 int
503 import_keys_es_stream (ctrl_t ctrl, estream_t fp,
504                        import_stats_t stats_handle,
505                        unsigned char **fpr, size_t *fpr_len,
506                        unsigned int options,
507                        import_screener_t screener, void *screener_arg)
508 {
509   int rc;
510   iobuf_t inp;
511
512   inp = iobuf_esopen (fp, "rb", 1);
513   if (!inp)
514     {
515       rc = gpg_error_from_syserror ();
516       log_error ("iobuf_esopen failed: %s\n", gpg_strerror (rc));
517       return rc;
518     }
519
520   rc = import_keys_internal (ctrl, inp, NULL, 0, stats_handle,
521                              fpr, fpr_len, options,
522                              screener, screener_arg);
523
524   iobuf_close (inp);
525   return rc;
526 }
527
528
529 static int
530 import (ctrl_t ctrl, IOBUF inp, const char* fname,struct import_stats_s *stats,
531         unsigned char **fpr,size_t *fpr_len, unsigned int options,
532         import_screener_t screener, void *screener_arg)
533 {
534   PACKET *pending_pkt = NULL;
535   kbnode_t keyblock = NULL;  /* Need to initialize because gcc can't
536                                 grasp the return semantics of
537                                 read_block. */
538   int rc = 0;
539   int v3keys;
540
541   getkey_disable_caches ();
542
543   if (!opt.no_armor) /* Armored reading is not disabled.  */
544     {
545       armor_filter_context_t *afx;
546
547       afx = new_armor_context ();
548       afx->only_keyblocks = 1;
549       push_armor_filter (afx, inp);
550       release_armor_context (afx);
551     }
552
553   while (!(rc = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
554     {
555       stats->v3keys += v3keys;
556       if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
557         rc = import_one (ctrl, keyblock,
558                          stats, fpr, fpr_len, options, 0, 0,
559                          screener, screener_arg);
560       else if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
561         rc = import_secret_one (ctrl, keyblock, stats,
562                                 opt.batch, options, 0,
563                                 screener, screener_arg);
564       else if (keyblock->pkt->pkttype == PKT_SIGNATURE
565                && keyblock->pkt->pkt.signature->sig_class == 0x20 )
566         rc = import_revoke_cert (ctrl, keyblock, stats);
567       else
568         {
569           log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
570         }
571       release_kbnode (keyblock);
572
573       /* fixme: we should increment the not imported counter but
574          this does only make sense if we keep on going despite of
575          errors.  For now we do this only if the imported key is too
576          large. */
577       if (gpg_err_code (rc) == GPG_ERR_TOO_LARGE
578             && gpg_err_source (rc) == GPG_ERR_SOURCE_KEYBOX)
579         {
580           stats->not_imported++;
581         }
582       else if (rc)
583         break;
584
585       if (!(++stats->count % 100) && !opt.quiet)
586         log_info (_("%lu keys processed so far\n"), stats->count );
587     }
588   stats->v3keys += v3keys;
589   if (rc == -1)
590     rc = 0;
591   else if (rc && gpg_err_code (rc) != GPG_ERR_INV_KEYRING)
592     log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (rc));
593
594   return rc;
595 }
596
597
598 /* Helper to migrate secring.gpg to GnuPG 2.1.  */
599 gpg_error_t
600 import_old_secring (ctrl_t ctrl, const char *fname)
601 {
602   gpg_error_t err;
603   iobuf_t inp;
604   PACKET *pending_pkt = NULL;
605   kbnode_t keyblock = NULL;  /* Need to initialize because gcc can't
606                                 grasp the return semantics of
607                                 read_block. */
608   struct import_stats_s *stats;
609   int v3keys;
610
611   inp = iobuf_open (fname);
612   if (inp && is_secured_file (iobuf_get_fd (inp)))
613     {
614       iobuf_close (inp);
615       inp = NULL;
616       gpg_err_set_errno (EPERM);
617     }
618   if (!inp)
619     {
620       err = gpg_error_from_syserror ();
621       log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
622       return err;
623     }
624
625   getkey_disable_caches();
626   stats = import_new_stats_handle ();
627   while (!(err = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
628     {
629       if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
630         err = import_secret_one (ctrl, keyblock, stats, 1, 0, 1,
631                                  NULL, NULL);
632       release_kbnode (keyblock);
633       if (err)
634         break;
635     }
636   import_release_stats_handle (stats);
637   if (err == -1)
638     err = 0;
639   else if (err && gpg_err_code (err) != GPG_ERR_INV_KEYRING)
640     log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
641   else if (err)
642     log_error ("import from '%s' failed: %s\n", fname, gpg_strerror (err));
643
644   iobuf_close (inp);
645   iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
646
647   return err;
648 }
649
650
651 void
652 import_print_stats (import_stats_t stats)
653 {
654   if (!opt.quiet)
655     {
656       log_info(_("Total number processed: %lu\n"),
657                stats->count + stats->v3keys);
658       if (stats->v3keys)
659         log_info(_("    skipped PGP-2 keys: %lu\n"), stats->v3keys);
660       if (stats->skipped_new_keys )
661         log_info(_("      skipped new keys: %lu\n"),
662                  stats->skipped_new_keys );
663       if (stats->no_user_id )
664         log_info(_("          w/o user IDs: %lu\n"), stats->no_user_id );
665       if (stats->imported)
666         {
667           log_info(_("              imported: %lu"), stats->imported );
668           log_printf ("\n");
669         }
670       if (stats->unchanged )
671         log_info(_("             unchanged: %lu\n"), stats->unchanged );
672       if (stats->n_uids )
673         log_info(_("          new user IDs: %lu\n"), stats->n_uids );
674       if (stats->n_subk )
675         log_info(_("           new subkeys: %lu\n"), stats->n_subk );
676       if (stats->n_sigs )
677         log_info(_("        new signatures: %lu\n"), stats->n_sigs );
678       if (stats->n_revoc )
679         log_info(_("   new key revocations: %lu\n"), stats->n_revoc );
680       if (stats->secret_read )
681         log_info(_("      secret keys read: %lu\n"), stats->secret_read );
682       if (stats->secret_imported )
683         log_info(_("  secret keys imported: %lu\n"), stats->secret_imported );
684       if (stats->secret_dups )
685         log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
686       if (stats->not_imported )
687         log_info(_("          not imported: %lu\n"), stats->not_imported );
688       if (stats->n_sigs_cleaned)
689         log_info(_("    signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
690       if (stats->n_uids_cleaned)
691         log_info(_("      user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
692     }
693
694   if (is_status_enabled ())
695     {
696       char buf[15*20];
697
698       snprintf (buf, sizeof buf,
699                 "%lu %lu %lu 0 %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
700                 stats->count + stats->v3keys,
701                 stats->no_user_id,
702                 stats->imported,
703                 stats->unchanged,
704                 stats->n_uids,
705                 stats->n_subk,
706                 stats->n_sigs,
707                 stats->n_revoc,
708                 stats->secret_read,
709                 stats->secret_imported,
710                 stats->secret_dups,
711                 stats->skipped_new_keys,
712                 stats->not_imported,
713                 stats->v3keys );
714       write_status_text (STATUS_IMPORT_RES, buf);
715     }
716 }
717
718
719 /* Return true if PKTTYPE is valid in a keyblock.  */
720 static int
721 valid_keyblock_packet (int pkttype)
722 {
723   switch (pkttype)
724     {
725     case PKT_PUBLIC_KEY:
726     case PKT_PUBLIC_SUBKEY:
727     case PKT_SECRET_KEY:
728     case PKT_SECRET_SUBKEY:
729     case PKT_SIGNATURE:
730     case PKT_USER_ID:
731     case PKT_ATTRIBUTE:
732     case PKT_RING_TRUST:
733       return 1;
734     default:
735       return 0;
736     }
737 }
738
739
740 /****************
741  * Read the next keyblock from stream A.
742  * PENDING_PKT should be initialzed to NULL
743  * and not changed by the caller.
744  * Return: 0 = okay, -1 no more blocks or another errorcode.
745  *         The int at at R_V3KEY counts the number of unsupported v3
746  *         keyblocks.
747  */
748 static int
749 read_block( IOBUF a, PACKET **pending_pkt, kbnode_t *ret_root, int *r_v3keys)
750 {
751   int rc;
752   PACKET *pkt;
753   kbnode_t root = NULL;
754   int in_cert, in_v3key;
755
756   *r_v3keys = 0;
757
758   if (*pending_pkt)
759     {
760       root = new_kbnode( *pending_pkt );
761       *pending_pkt = NULL;
762       in_cert = 1;
763     }
764   else
765     in_cert = 0;
766
767   pkt = xmalloc (sizeof *pkt);
768   init_packet (pkt);
769   in_v3key = 0;
770   while ((rc=parse_packet(a, pkt)) != -1)
771     {
772       if (rc && (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY
773                  && (pkt->pkttype == PKT_PUBLIC_KEY
774                      || pkt->pkttype == PKT_SECRET_KEY)))
775         {
776           in_v3key = 1;
777           ++*r_v3keys;
778           free_packet (pkt);
779           init_packet (pkt);
780           continue;
781         }
782       else if (rc ) /* (ignore errors) */
783         {
784           if (gpg_err_code (rc) == GPG_ERR_UNKNOWN_PACKET)
785             ; /* Do not show a diagnostic.  */
786           else
787             {
788               log_error("read_block: read error: %s\n", gpg_strerror (rc) );
789               rc = GPG_ERR_INV_KEYRING;
790               goto ready;
791             }
792           free_packet( pkt );
793           init_packet(pkt);
794           continue;
795         }
796
797         if (in_v3key && !(pkt->pkttype == PKT_PUBLIC_KEY
798                           || pkt->pkttype == PKT_SECRET_KEY))
799           {
800             free_packet( pkt );
801             init_packet(pkt);
802             continue;
803           }
804         in_v3key = 0;
805
806         if (!root && pkt->pkttype == PKT_SIGNATURE
807                   && pkt->pkt.signature->sig_class == 0x20 )
808           {
809             /* This is a revocation certificate which is handled in a
810              * special way.  */
811             root = new_kbnode( pkt );
812             pkt = NULL;
813             goto ready;
814           }
815
816         /* Make a linked list of all packets.  */
817         switch (pkt->pkttype)
818           {
819           case PKT_COMPRESSED:
820             if (check_compress_algo (pkt->pkt.compressed->algorithm))
821               {
822                 rc = GPG_ERR_COMPR_ALGO;
823                 goto ready;
824               }
825             else
826               {
827                 compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
828                 pkt->pkt.compressed->buf = NULL;
829                 push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1);
830               }
831             free_packet( pkt );
832             init_packet(pkt);
833             break;
834
835           case PKT_RING_TRUST:
836             /* Skip those packets.  */
837             free_packet( pkt );
838             init_packet(pkt);
839             break;
840
841           case PKT_PUBLIC_KEY:
842           case PKT_SECRET_KEY:
843             if (in_cert ) /* Store this packet.  */
844               {
845                 *pending_pkt = pkt;
846                 pkt = NULL;
847                 goto ready;
848               }
849             in_cert = 1;
850           default:
851             if (in_cert && valid_keyblock_packet (pkt->pkttype))
852               {
853                 if (!root )
854                   root = new_kbnode (pkt);
855                 else
856                   add_kbnode (root, new_kbnode (pkt));
857                 pkt = xmalloc (sizeof *pkt);
858               }
859             init_packet(pkt);
860             break;
861           }
862     }
863
864  ready:
865   if (rc == -1 && root )
866     rc = 0;
867
868   if (rc )
869     release_kbnode( root );
870   else
871     *ret_root = root;
872   free_packet( pkt );
873   xfree( pkt );
874   return rc;
875 }
876
877
878 /* Walk through the subkeys on a pk to find if we have the PKS
879    disease: multiple subkeys with their binding sigs stripped, and the
880    sig for the first subkey placed after the last subkey.  That is,
881    instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
882    "pk uid sig sub1 sub2 sub3 bind1".  We can't do anything about sub2
883    and sub3, as they are already lost, but we can try and rescue sub1
884    by reordering the keyblock so that it reads "pk uid sig sub1 bind1
885    sub2 sub3".  Returns TRUE if the keyblock was modified. */
886 static int
887 fix_pks_corruption (kbnode_t keyblock)
888 {
889   int changed = 0;
890   int keycount = 0;
891   kbnode_t node;
892   kbnode_t last = NULL;
893   kbnode_t sknode=NULL;
894
895   /* First determine if we have the problem at all.  Look for 2 or
896      more subkeys in a row, followed by a single binding sig. */
897   for (node=keyblock; node; last=node, node=node->next)
898     {
899       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
900         {
901           keycount++;
902           if(!sknode)
903             sknode=node;
904         }
905       else if (node->pkt->pkttype == PKT_SIGNATURE
906                && node->pkt->pkt.signature->sig_class == 0x18
907                && keycount >= 2
908                && !node->next)
909         {
910           /* We might have the problem, as this key has two subkeys in
911              a row without any intervening packets. */
912
913           /* Sanity check */
914           if (!last)
915             break;
916
917           /* Temporarily attach node to sknode. */
918           node->next = sknode->next;
919           sknode->next = node;
920           last->next = NULL;
921
922           /* Note we aren't checking whether this binding sig is a
923              selfsig.  This is not necessary here as the subkey and
924              binding sig will be rejected later if that is the
925              case. */
926           if (check_key_signature (keyblock,node,NULL))
927             {
928               /* Not a match, so undo the changes. */
929               sknode->next = node->next;
930               last->next = node;
931               node->next = NULL;
932               break;
933             }
934           else
935             {
936               /* Mark it good so we don't need to check it again */
937               sknode->flag |= NODE_GOOD_SELFSIG;
938               changed = 1;
939               break;
940             }
941         }
942       else
943         keycount = 0;
944     }
945
946   return changed;
947 }
948
949
950 /* Versions of GnuPG before 1.4.11 and 2.0.16 allowed to import bogus
951    direct key signatures.  A side effect of this was that a later
952    import of the same good direct key signatures was not possible
953    because the cmp_signature check in merge_blocks considered them
954    equal.  Although direct key signatures are now checked during
955    import, there might still be bogus signatures sitting in a keyring.
956    We need to detect and delete them before doing a merge.  This
957    function returns the number of removed sigs.  */
958 static int
959 fix_bad_direct_key_sigs (kbnode_t keyblock, u32 *keyid)
960 {
961   gpg_error_t err;
962   kbnode_t node;
963   int count = 0;
964
965   for (node = keyblock->next; node; node=node->next)
966     {
967       if (node->pkt->pkttype == PKT_USER_ID)
968         break;
969       if (node->pkt->pkttype == PKT_SIGNATURE
970           && IS_KEY_SIG (node->pkt->pkt.signature))
971         {
972           err = check_key_signature (keyblock, node, NULL);
973           if (err && gpg_err_code (err) != GPG_ERR_PUBKEY_ALGO )
974             {
975               /* If we don't know the error, we can't decide; this is
976                  not a problem because cmp_signature can't compare the
977                  signature either.  */
978               log_info ("key %s: invalid direct key signature removed\n",
979                         keystr (keyid));
980               delete_kbnode (node);
981               count++;
982             }
983         }
984     }
985
986   return count;
987 }
988
989
990 static void
991 print_import_ok (PKT_public_key *pk, unsigned int reason)
992 {
993   byte array[MAX_FINGERPRINT_LEN], *s;
994   char buf[MAX_FINGERPRINT_LEN*2+30], *p;
995   size_t i, n;
996
997   snprintf (buf, sizeof buf, "%u ", reason);
998   p = buf + strlen (buf);
999
1000   fingerprint_from_pk (pk, array, &n);
1001   s = array;
1002   for (i=0; i < n ; i++, s++, p += 2)
1003     sprintf (p, "%02X", *s);
1004
1005   write_status_text (STATUS_IMPORT_OK, buf);
1006 }
1007
1008
1009 static void
1010 print_import_check (PKT_public_key * pk, PKT_user_id * id)
1011 {
1012   char * buf;
1013   byte fpr[24];
1014   u32 keyid[2];
1015   size_t i, n;
1016   size_t pos = 0;
1017
1018   buf = xmalloc (17+41+id->len+32);
1019   keyid_from_pk (pk, keyid);
1020   sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
1021   pos = 17;
1022   fingerprint_from_pk (pk, fpr, &n);
1023   for (i = 0; i < n; i++, pos += 2)
1024     sprintf (buf+pos, "%02X", fpr[i]);
1025   strcat (buf, " ");
1026   strcat (buf, id->name);
1027   write_status_text (STATUS_IMPORT_CHECK, buf);
1028   xfree (buf);
1029 }
1030
1031
1032 static void
1033 check_prefs_warning(PKT_public_key *pk)
1034 {
1035   log_info(_("WARNING: key %s contains preferences for unavailable\n"
1036              "algorithms on these user IDs:\n"), keystr_from_pk(pk));
1037 }
1038
1039
1040 static void
1041 check_prefs (ctrl_t ctrl, kbnode_t keyblock)
1042 {
1043   kbnode_t node;
1044   PKT_public_key *pk;
1045   int problem=0;
1046
1047   merge_keys_and_selfsig(keyblock);
1048   pk=keyblock->pkt->pkt.public_key;
1049
1050   for(node=keyblock;node;node=node->next)
1051     {
1052       if(node->pkt->pkttype==PKT_USER_ID
1053          && node->pkt->pkt.user_id->created
1054          && node->pkt->pkt.user_id->prefs)
1055         {
1056           PKT_user_id *uid = node->pkt->pkt.user_id;
1057           prefitem_t *prefs = uid->prefs;
1058           char *user = utf8_to_native(uid->name,strlen(uid->name),0);
1059
1060           for(;prefs->type;prefs++)
1061             {
1062               char num[10]; /* prefs->value is a byte, so we're over
1063                                safe here */
1064
1065               sprintf(num,"%u",prefs->value);
1066
1067               if(prefs->type==PREFTYPE_SYM)
1068                 {
1069                   if (openpgp_cipher_test_algo (prefs->value))
1070                     {
1071                       const char *algo =
1072                         (openpgp_cipher_test_algo (prefs->value)
1073                          ? num
1074                          : openpgp_cipher_algo_name (prefs->value));
1075                       if(!problem)
1076                         check_prefs_warning(pk);
1077                       log_info(_("         \"%s\": preference for cipher"
1078                                  " algorithm %s\n"), user, algo);
1079                       problem=1;
1080                     }
1081                 }
1082               else if(prefs->type==PREFTYPE_HASH)
1083                 {
1084                   if(openpgp_md_test_algo(prefs->value))
1085                     {
1086                       const char *algo =
1087                         (gcry_md_test_algo (prefs->value)
1088                          ? num
1089                          : gcry_md_algo_name (prefs->value));
1090                       if(!problem)
1091                         check_prefs_warning(pk);
1092                       log_info(_("         \"%s\": preference for digest"
1093                                  " algorithm %s\n"), user, algo);
1094                       problem=1;
1095                     }
1096                 }
1097               else if(prefs->type==PREFTYPE_ZIP)
1098                 {
1099                   if(check_compress_algo (prefs->value))
1100                     {
1101                       const char *algo=compress_algo_to_string(prefs->value);
1102                       if(!problem)
1103                         check_prefs_warning(pk);
1104                       log_info(_("         \"%s\": preference for compression"
1105                                  " algorithm %s\n"),user,algo?algo:num);
1106                       problem=1;
1107                     }
1108                 }
1109             }
1110
1111           xfree(user);
1112         }
1113     }
1114
1115   if(problem)
1116     {
1117       log_info(_("it is strongly suggested that you update"
1118                  " your preferences and\n"));
1119       log_info(_("re-distribute this key to avoid potential algorithm"
1120                  " mismatch problems\n"));
1121
1122       if(!opt.batch)
1123         {
1124           strlist_t sl = NULL;
1125           strlist_t locusr = NULL;
1126           size_t fprlen=0;
1127           byte fpr[MAX_FINGERPRINT_LEN], *p;
1128           char username[(MAX_FINGERPRINT_LEN*2)+1];
1129           unsigned int i;
1130
1131           p = fingerprint_from_pk (pk,fpr,&fprlen);
1132           for(i=0;i<fprlen;i++,p++)
1133             sprintf(username+2*i,"%02X",*p);
1134           add_to_strlist(&locusr,username);
1135
1136           append_to_strlist(&sl,"updpref");
1137           append_to_strlist(&sl,"save");
1138
1139           keyedit_menu (ctrl, username, locusr, sl, 1, 1 );
1140           free_strlist(sl);
1141           free_strlist(locusr);
1142         }
1143       else if(!opt.quiet)
1144         log_info(_("you can update your preferences with:"
1145                    " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
1146     }
1147 }
1148
1149
1150 /* Helper for apply_*_filter in im,port.c and export.c.  */
1151 const char *
1152 impex_filter_getval (void *cookie, const char *propname)
1153 {
1154   /* FIXME: Malloc our static buffers and access them via the cookie.  */
1155   kbnode_t node = cookie;
1156   static char numbuf[20];
1157   const char *result;
1158
1159   if (node->pkt->pkttype == PKT_USER_ID)
1160     {
1161       if (!strcmp (propname, "uid"))
1162         result = node->pkt->pkt.user_id->name;
1163       else if (!strcmp (propname, "mbox"))
1164         {
1165           if (!node->pkt->pkt.user_id->mbox)
1166             {
1167               node->pkt->pkt.user_id->mbox
1168                 = mailbox_from_userid (node->pkt->pkt.user_id->name);
1169             }
1170           result = node->pkt->pkt.user_id->mbox;
1171         }
1172       else if (!strcmp (propname, "primary"))
1173         result = node->pkt->pkt.user_id->is_primary? "1":"0";
1174       else
1175         result = NULL;
1176     }
1177   else if (node->pkt->pkttype == PKT_SIGNATURE
1178            || node->pkt->pkttype == PKT_ATTRIBUTE)
1179     {
1180       PKT_signature *sig = node->pkt->pkt.signature;
1181
1182       if (!strcmp (propname, "sig_created"))
1183         {
1184           snprintf (numbuf, sizeof numbuf, "%lu", (ulong)sig->timestamp);
1185           result = numbuf;
1186         }
1187       else if (!strcmp (propname, "sig_created_d"))
1188         {
1189           result = datestr_from_sig (sig);
1190         }
1191       else if (!strcmp (propname, "sig_algo"))
1192         {
1193           snprintf (numbuf, sizeof numbuf, "%d", sig->pubkey_algo);
1194           result = numbuf;
1195         }
1196       else if (!strcmp (propname, "sig_digest_algo"))
1197         {
1198           snprintf (numbuf, sizeof numbuf, "%d", sig->digest_algo);
1199           result = numbuf;
1200         }
1201       else
1202         result = NULL;
1203     }
1204   else if (node->pkt->pkttype == PKT_PUBLIC_KEY
1205            || node->pkt->pkttype == PKT_SECRET_KEY
1206            || node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1207            || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1208     {
1209       PKT_public_key *pk = node->pkt->pkt.public_key;
1210
1211       if (!strcmp (propname, "secret"))
1212         {
1213           result = (node->pkt->pkttype == PKT_SECRET_KEY
1214                     || node->pkt->pkttype == PKT_SECRET_SUBKEY)? "1":"0";
1215         }
1216       else if (!strcmp (propname, "key_algo"))
1217         {
1218           snprintf (numbuf, sizeof numbuf, "%d", pk->pubkey_algo);
1219           result = numbuf;
1220         }
1221       if (!strcmp (propname, "key_created"))
1222         {
1223           snprintf (numbuf, sizeof numbuf, "%lu", (ulong)pk->timestamp);
1224           result = numbuf;
1225         }
1226       else if (!strcmp (propname, "key_created_d"))
1227         {
1228           result = datestr_from_pk (pk);
1229         }
1230       else
1231         result = NULL;
1232     }
1233   else
1234     result = NULL;
1235
1236   return result;
1237 }
1238
1239
1240 /*
1241  * Apply the keep-uid filter to the keyblock.  The deleted nodes are
1242  * marked and thus the caller should call commit_kbnode afterwards.
1243  * KEYBLOCK must not have any blocks marked as deleted.
1244  */
1245 static void
1246 apply_keep_uid_filter (kbnode_t keyblock, recsel_expr_t selector)
1247 {
1248   kbnode_t node;
1249
1250   for (node = keyblock->next; node; node = node->next )
1251     {
1252       if (node->pkt->pkttype == PKT_USER_ID)
1253         {
1254           if (!recsel_select (selector, impex_filter_getval, node))
1255             {
1256
1257               /* log_debug ("keep-uid: deleting '%s'\n", */
1258               /*            node->pkt->pkt.user_id->name); */
1259               /* The UID packet and all following packets up to the
1260                * next UID or a subkey.  */
1261               delete_kbnode (node);
1262               for (; node->next
1263                      && node->next->pkt->pkttype != PKT_USER_ID
1264                      && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1265                      && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1266                    node = node->next)
1267                 delete_kbnode (node->next);
1268             }
1269           /* else */
1270           /*   log_debug ("keep-uid: keeping '%s'\n", */
1271           /*              node->pkt->pkt.user_id->name); */
1272         }
1273     }
1274 }
1275
1276
1277 /*
1278  * Apply the drop-sig filter to the keyblock.  The deleted nodes are
1279  * marked and thus the caller should call commit_kbnode afterwards.
1280  * KEYBLOCK must not have any blocks marked as deleted.
1281  */
1282 static void
1283 apply_drop_sig_filter (kbnode_t keyblock, recsel_expr_t selector)
1284 {
1285   kbnode_t node;
1286   int active = 0;
1287   u32 main_keyid[2];
1288   PKT_signature *sig;
1289
1290   keyid_from_pk (keyblock->pkt->pkt.public_key, main_keyid);
1291
1292   /* Loop over all signatures for user id and attribute packets which
1293    * are not self signatures.  */
1294   for (node = keyblock->next; node; node = node->next )
1295     {
1296       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1297           || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1298         break; /* ready.  */
1299       if (node->pkt->pkttype == PKT_USER_ID)
1300         active = 1;
1301       if (!active)
1302         continue;
1303       if (node->pkt->pkttype != PKT_SIGNATURE
1304           && node->pkt->pkttype != PKT_ATTRIBUTE)
1305         continue;
1306
1307       sig = node->pkt->pkt.signature;
1308       if (main_keyid[0] == sig->keyid[0] || main_keyid[1] == sig->keyid[1])
1309         continue;  /* Skip self-signatures.  */
1310
1311       if (IS_UID_SIG(sig) || IS_UID_REV(sig))
1312         {
1313           if (recsel_select (selector, impex_filter_getval, node))
1314             delete_kbnode (node);
1315         }
1316     }
1317 }
1318
1319
1320 /*
1321  * Try to import one keyblock. Return an error only in serious cases,
1322  * but never for an invalid keyblock.  It uses log_error to increase
1323  * the internal errorcount, so that invalid input can be detected by
1324  * programs which called gpg.  If SILENT is no messages are printed -
1325  * even most error messages are suppressed.
1326  */
1327 static int
1328 import_one (ctrl_t ctrl,
1329             kbnode_t keyblock, struct import_stats_s *stats,
1330             unsigned char **fpr, size_t *fpr_len, unsigned int options,
1331             int from_sk, int silent,
1332             import_screener_t screener, void *screener_arg)
1333 {
1334   PKT_public_key *pk;
1335   PKT_public_key *pk_orig = NULL;
1336   kbnode_t node, uidnode;
1337   kbnode_t keyblock_orig = NULL;
1338   byte fpr2[MAX_FINGERPRINT_LEN];
1339   size_t fpr2len;
1340   u32 keyid[2];
1341   int rc = 0;
1342   int new_key = 0;
1343   int mod_key = 0;
1344   int same_key = 0;
1345   int non_self = 0;
1346   size_t an;
1347   char pkstrbuf[PUBKEY_STRING_SIZE];
1348   int merge_keys_done = 0;
1349   int any_filter = 0;
1350
1351   /* Get the key and print some info about it. */
1352   node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
1353   if (!node )
1354     BUG();
1355
1356   pk = node->pkt->pkt.public_key;
1357
1358   fingerprint_from_pk (pk, fpr2, &fpr2len);
1359   for (an = fpr2len; an < MAX_FINGERPRINT_LEN; an++)
1360     fpr2[an] = 0;
1361   keyid_from_pk( pk, keyid );
1362   uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1363
1364   if (opt.verbose && !opt.interactive && !silent)
1365     {
1366       log_info( "pub  %s/%s %s  ",
1367                 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
1368                 keystr_from_pk(pk), datestr_from_pk(pk) );
1369       if (uidnode)
1370         print_utf8_buffer (log_get_stream (),
1371                            uidnode->pkt->pkt.user_id->name,
1372                            uidnode->pkt->pkt.user_id->len );
1373       log_printf ("\n");
1374     }
1375
1376
1377   if (!uidnode )
1378     {
1379       if (!silent)
1380         log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
1381       return 0;
1382     }
1383
1384   if (screener && screener (keyblock, screener_arg))
1385     {
1386       log_error (_("key %s: %s\n"), keystr_from_pk (pk),
1387                  _("rejected by import screener"));
1388       return 0;
1389     }
1390
1391   if (opt.interactive && !silent)
1392     {
1393       if (is_status_enabled())
1394         print_import_check (pk, uidnode->pkt->pkt.user_id);
1395       merge_keys_and_selfsig (keyblock);
1396       tty_printf ("\n");
1397       show_basic_key_info (keyblock);
1398       tty_printf ("\n");
1399       if (!cpr_get_answer_is_yes ("import.okay",
1400                                   "Do you want to import this key? (y/N) "))
1401         return 0;
1402     }
1403
1404   collapse_uids(&keyblock);
1405
1406   /* Clean the key that we're about to import, to cut down on things
1407      that we have to clean later.  This has no practical impact on the
1408      end result, but does result in less logging which might confuse
1409      the user. */
1410   if (options&IMPORT_CLEAN)
1411     clean_key (keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL);
1412
1413   clear_kbnode_flags( keyblock );
1414
1415   if ((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
1416       && opt.verbose)
1417     log_info (_("key %s: PKS subkey corruption repaired\n"),
1418               keystr_from_pk(pk));
1419
1420   if (chk_self_sigs (keyblock, keyid, &non_self))
1421     return 0;  /* Invalid keyblock - error already printed.  */
1422
1423   /* If we allow such a thing, mark unsigned uids as valid */
1424   if (opt.allow_non_selfsigned_uid)
1425     {
1426       for (node=keyblock; node; node = node->next )
1427         if (node->pkt->pkttype == PKT_USER_ID
1428             && !(node->flag & NODE_GOOD_SELFSIG)
1429             && !(node->flag & NODE_BAD_SELFSIG) )
1430           {
1431             char *user=utf8_to_native(node->pkt->pkt.user_id->name,
1432                                       node->pkt->pkt.user_id->len,0);
1433             /* Fake a good signature status for the user id.  */
1434             node->flag |= NODE_GOOD_SELFSIG;
1435             log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
1436                       keystr_from_pk(pk),user);
1437             xfree(user);
1438           }
1439     }
1440
1441   if (!delete_inv_parts (keyblock, keyid, options ) )
1442     {
1443       if (!silent)
1444         {
1445           log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
1446           if (!opt.quiet )
1447             log_info(_("this may be caused by a missing self-signature\n"));
1448         }
1449       stats->no_user_id++;
1450       return 0;
1451     }
1452
1453   /* Get rid of deleted nodes.  */
1454   commit_kbnode (&keyblock);
1455
1456   /* Apply import filter.  */
1457   if (import_filter.keep_uid)
1458     {
1459       apply_keep_uid_filter (keyblock, import_filter.keep_uid);
1460       commit_kbnode (&keyblock);
1461       any_filter = 1;
1462     }
1463   if (import_filter.drop_sig)
1464     {
1465       apply_drop_sig_filter (keyblock, import_filter.drop_sig);
1466       commit_kbnode (&keyblock);
1467       any_filter = 1;
1468     }
1469
1470   /* If we ran any filter we need to check that at least one user id
1471    * is left in the keyring.  Note that we do not use log_error in
1472    * this case. */
1473   if (any_filter && !any_uid_left (keyblock))
1474     {
1475       if (!opt.quiet )
1476         log_info ( _("key %s: no valid user IDs\n"), keystr_from_pk (pk));
1477       stats->no_user_id++;
1478       return 0;
1479     }
1480
1481   /* Show the key in the form it is merged or inserted.  We skip this
1482    * if "import-export" is also active without --armor or the output
1483    * file has explicily been given. */
1484   if ((options & IMPORT_SHOW)
1485       && !((options & IMPORT_EXPORT) && !opt.armor && !opt.outfile))
1486     {
1487       merge_keys_and_selfsig (keyblock);
1488       merge_keys_done = 1;
1489       /* Note that we do not want to show the validity because the key
1490        * has not yet imported.  */
1491       list_keyblock_direct (ctrl, keyblock, 0, 0, 1, 1);
1492       es_fflush (es_stdout);
1493     }
1494
1495   /* Write the keyblock to the output and do not actually import.  */
1496   if ((options & IMPORT_EXPORT))
1497     {
1498       if (!merge_keys_done)
1499         {
1500           merge_keys_and_selfsig (keyblock);
1501           merge_keys_done = 1;
1502         }
1503       rc = write_keyblock_to_output (keyblock, opt.armor, opt.export_options);
1504       goto leave;
1505     }
1506
1507   if (opt.dry_run)
1508     goto leave;
1509
1510   /* Do we have this key already in one of our pubrings ? */
1511   pk_orig = xmalloc_clear( sizeof *pk_orig );
1512   rc = get_pubkey_byfprint_fast (pk_orig, fpr2, fpr2len);
1513   if (rc && gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1514       && gpg_err_code (rc) != GPG_ERR_UNUSABLE_PUBKEY )
1515     {
1516       if (!silent)
1517         log_error (_("key %s: public key not found: %s\n"),
1518                    keystr(keyid), gpg_strerror (rc));
1519     }
1520   else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) )
1521     {
1522       if (opt.verbose && !silent )
1523         log_info( _("key %s: new key - skipped\n"), keystr(keyid));
1524       rc = 0;
1525       stats->skipped_new_keys++;
1526     }
1527   else if (rc )  /* Insert this key. */
1528     {
1529       KEYDB_HANDLE hd;
1530
1531       hd = keydb_new ();
1532       if (!hd)
1533         return gpg_error_from_syserror ();
1534
1535       rc = keydb_locate_writable (hd);
1536       if (rc)
1537         {
1538           log_error (_("no writable keyring found: %s\n"), gpg_strerror (rc));
1539           keydb_release (hd);
1540           return GPG_ERR_GENERAL;
1541         }
1542       if (opt.verbose > 1 )
1543         log_info (_("writing to '%s'\n"), keydb_get_resource_name (hd) );
1544
1545       rc = keydb_insert_keyblock (hd, keyblock );
1546       if (rc)
1547         log_error (_("error writing keyring '%s': %s\n"),
1548                    keydb_get_resource_name (hd), gpg_strerror (rc));
1549       else if (!(opt.import_options & IMPORT_KEEP_OWNERTTRUST))
1550         {
1551           /* This should not be possible since we delete the
1552              ownertrust when a key is deleted, but it can happen if
1553              the keyring and trustdb are out of sync.  It can also
1554              be made to happen with the trusted-key command and by
1555              importing and locally exported key. */
1556
1557           clear_ownertrusts (pk);
1558           if (non_self)
1559             revalidation_mark ();
1560         }
1561       keydb_release (hd);
1562
1563       /* We are ready.  */
1564       if (!opt.quiet && !silent)
1565         {
1566           char *p = get_user_id_byfpr_native (fpr2);
1567           log_info (_("key %s: public key \"%s\" imported\n"),
1568                     keystr(keyid), p);
1569           xfree(p);
1570         }
1571       if (is_status_enabled())
1572         {
1573           char *us = get_long_user_id_string( keyid );
1574           write_status_text( STATUS_IMPORTED, us );
1575           xfree(us);
1576           print_import_ok (pk, 1);
1577         }
1578       stats->imported++;
1579       new_key = 1;
1580     }
1581   else /* merge */
1582     {
1583       KEYDB_HANDLE hd;
1584       int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
1585
1586       /* Compare the original against the new key; just to be sure nothing
1587        * weird is going on */
1588       if (cmp_public_keys( pk_orig, pk ) )
1589         {
1590           if (!silent)
1591             log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
1592           goto leave;
1593         }
1594
1595       /* Now read the original keyblock again so that we can use
1596          that handle for updating the keyblock.  */
1597       hd = keydb_new ();
1598       if (!hd)
1599         {
1600           rc = gpg_error_from_syserror ();
1601           goto leave;
1602         }
1603       keydb_disable_caching (hd);
1604       rc = keydb_search_fpr (hd, fpr2);
1605       if (rc )
1606         {
1607           log_error (_("key %s: can't locate original keyblock: %s\n"),
1608                      keystr(keyid), gpg_strerror (rc));
1609           keydb_release (hd);
1610           goto leave;
1611         }
1612       rc = keydb_get_keyblock (hd, &keyblock_orig);
1613       if (rc)
1614         {
1615           log_error (_("key %s: can't read original keyblock: %s\n"),
1616                      keystr(keyid), gpg_strerror (rc));
1617           keydb_release (hd);
1618           goto leave;
1619         }
1620
1621       /* Make sure the original direct key sigs are all sane.  */
1622       n_sigs_cleaned = fix_bad_direct_key_sigs (keyblock_orig, keyid);
1623       if (n_sigs_cleaned)
1624         commit_kbnode (&keyblock_orig);
1625
1626       /* and try to merge the block */
1627       clear_kbnode_flags( keyblock_orig );
1628       clear_kbnode_flags( keyblock );
1629       n_uids = n_sigs = n_subk = n_uids_cleaned = 0;
1630       rc = merge_blocks (keyblock_orig, keyblock,
1631                          keyid, &n_uids, &n_sigs, &n_subk );
1632       if (rc )
1633         {
1634           keydb_release (hd);
1635           goto leave;
1636         }
1637
1638       if ((options & IMPORT_CLEAN))
1639         clean_key (keyblock_orig,opt.verbose,options&IMPORT_MINIMAL,
1640                    &n_uids_cleaned,&n_sigs_cleaned);
1641
1642       if (n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned)
1643         {
1644           mod_key = 1;
1645           /* KEYBLOCK_ORIG has been updated; write */
1646           rc = keydb_update_keyblock (ctrl, hd, keyblock_orig);
1647           if (rc)
1648             log_error (_("error writing keyring '%s': %s\n"),
1649                        keydb_get_resource_name (hd), gpg_strerror (rc) );
1650           else if (non_self)
1651             revalidation_mark ();
1652
1653           /* We are ready.  */
1654           if (!opt.quiet && !silent)
1655             {
1656               char *p = get_user_id_byfpr_native (fpr2);
1657               if (n_uids == 1 )
1658                 log_info( _("key %s: \"%s\" 1 new user ID\n"),
1659                           keystr(keyid),p);
1660               else if (n_uids )
1661                 log_info( _("key %s: \"%s\" %d new user IDs\n"),
1662                           keystr(keyid),p,n_uids);
1663               if (n_sigs == 1 )
1664                 log_info( _("key %s: \"%s\" 1 new signature\n"),
1665                           keystr(keyid), p);
1666               else if (n_sigs )
1667                 log_info( _("key %s: \"%s\" %d new signatures\n"),
1668                           keystr(keyid), p, n_sigs );
1669               if (n_subk == 1 )
1670                 log_info( _("key %s: \"%s\" 1 new subkey\n"),
1671                           keystr(keyid), p);
1672               else if (n_subk )
1673                 log_info( _("key %s: \"%s\" %d new subkeys\n"),
1674                           keystr(keyid), p, n_subk );
1675               if (n_sigs_cleaned==1)
1676                 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
1677                          keystr(keyid),p,n_sigs_cleaned);
1678               else if (n_sigs_cleaned)
1679                 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
1680                          keystr(keyid),p,n_sigs_cleaned);
1681               if (n_uids_cleaned==1)
1682                 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
1683                          keystr(keyid),p,n_uids_cleaned);
1684               else if (n_uids_cleaned)
1685                 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
1686                          keystr(keyid),p,n_uids_cleaned);
1687               xfree(p);
1688             }
1689
1690           stats->n_uids +=n_uids;
1691           stats->n_sigs +=n_sigs;
1692           stats->n_subk +=n_subk;
1693           stats->n_sigs_cleaned +=n_sigs_cleaned;
1694           stats->n_uids_cleaned +=n_uids_cleaned;
1695
1696           if (is_status_enabled () && !silent)
1697             print_import_ok (pk, ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
1698         }
1699       else
1700         {
1701           same_key = 1;
1702           if (is_status_enabled ())
1703             print_import_ok (pk, 0);
1704
1705           if (!opt.quiet && !silent)
1706             {
1707               char *p = get_user_id_byfpr_native (fpr2);
1708               log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
1709               xfree(p);
1710             }
1711
1712           stats->unchanged++;
1713         }
1714
1715       keydb_release (hd); hd = NULL;
1716     }
1717
1718  leave:
1719   if (mod_key || new_key || same_key)
1720     {
1721       /* A little explanation for this: we fill in the fingerprint
1722          when importing keys as it can be useful to know the
1723          fingerprint in certain keyserver-related cases (a keyserver
1724          asked for a particular name, but the key doesn't have that
1725          name).  However, in cases where we're importing more than
1726          one key at a time, we cannot know which key to fingerprint.
1727          In these cases, rather than guessing, we do not
1728          fingerprinting at all, and we must hope the user ID on the
1729          keys are useful.  Note that we need to do this for new
1730          keys, merged keys and even for unchanged keys.  This is
1731          required because for example the --auto-key-locate feature
1732          may import an already imported key and needs to know the
1733          fingerprint of the key in all cases.  */
1734       if (fpr)
1735         {
1736           xfree (*fpr);
1737           /* Note that we need to compare against 0 here because
1738              COUNT gets only incremented after returning from this
1739              function.  */
1740           if (!stats->count)
1741             *fpr = fingerprint_from_pk (pk, NULL, fpr_len);
1742           else
1743             *fpr = NULL;
1744         }
1745     }
1746
1747   /* Now that the key is definitely incorporated into the keydb, we
1748      need to check if a designated revocation is present or if the
1749      prefs are not rational so we can warn the user. */
1750
1751   if (mod_key)
1752     {
1753       revocation_present (ctrl, keyblock_orig);
1754       if (!from_sk && have_secret_key_with_kid (keyid))
1755         check_prefs (ctrl, keyblock_orig);
1756     }
1757   else if (new_key)
1758     {
1759       revocation_present (ctrl, keyblock);
1760       if (!from_sk && have_secret_key_with_kid (keyid))
1761         check_prefs (ctrl, keyblock);
1762     }
1763
1764   release_kbnode( keyblock_orig );
1765   free_public_key( pk_orig );
1766
1767   return rc;
1768 }
1769
1770
1771 /* Transfer all the secret keys in SEC_KEYBLOCK to the gpg-agent.  The
1772    function prints diagnostics and returns an error code.  If BATCH is
1773    true the secret keys are stored by gpg-agent in the transfer format
1774    (i.e. no re-protection and aksing for passphrases). */
1775 gpg_error_t
1776 transfer_secret_keys (ctrl_t ctrl, struct import_stats_s *stats,
1777                       kbnode_t sec_keyblock, int batch, int force)
1778 {
1779   gpg_error_t err = 0;
1780   void *kek = NULL;
1781   size_t keklen;
1782   kbnode_t ctx = NULL;
1783   kbnode_t node;
1784   PKT_public_key *main_pk, *pk;
1785   struct seckey_info *ski;
1786   int nskey;
1787   membuf_t mbuf;
1788   int i, j;
1789   void *format_args[2*PUBKEY_MAX_NSKEY];
1790   gcry_sexp_t skey, prot, tmpsexp;
1791   gcry_sexp_t curve = NULL;
1792   unsigned char *transferkey = NULL;
1793   size_t transferkeylen;
1794   gcry_cipher_hd_t cipherhd = NULL;
1795   unsigned char *wrappedkey = NULL;
1796   size_t wrappedkeylen;
1797   char *cache_nonce = NULL;
1798   int stub_key_skipped = 0;
1799
1800   /* Get the current KEK.  */
1801   err = agent_keywrap_key (ctrl, 0, &kek, &keklen);
1802   if (err)
1803     {
1804       log_error ("error getting the KEK: %s\n", gpg_strerror (err));
1805       goto leave;
1806     }
1807
1808   /* Prepare a cipher context.  */
1809   err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
1810                           GCRY_CIPHER_MODE_AESWRAP, 0);
1811   if (!err)
1812     err = gcry_cipher_setkey (cipherhd, kek, keklen);
1813   if (err)
1814     goto leave;
1815   xfree (kek);
1816   kek = NULL;
1817
1818   main_pk = NULL;
1819   while ((node = walk_kbnode (sec_keyblock, &ctx, 0)))
1820     {
1821       if (node->pkt->pkttype != PKT_SECRET_KEY
1822           && node->pkt->pkttype != PKT_SECRET_SUBKEY)
1823         continue;
1824       pk = node->pkt->pkt.public_key;
1825       if (!main_pk)
1826         main_pk = pk;
1827
1828       /* Make sure the keyids are available.  */
1829       keyid_from_pk (pk, NULL);
1830       if (node->pkt->pkttype == PKT_SECRET_KEY)
1831         {
1832           pk->main_keyid[0] = pk->keyid[0];
1833           pk->main_keyid[1] = pk->keyid[1];
1834         }
1835       else
1836         {
1837           pk->main_keyid[0] = main_pk->keyid[0];
1838           pk->main_keyid[1] = main_pk->keyid[1];
1839         }
1840
1841
1842       ski = pk->seckey_info;
1843       if (!ski)
1844         BUG ();
1845
1846       if (stats)
1847         {
1848           stats->count++;
1849           stats->secret_read++;
1850         }
1851
1852       /* We ignore stub keys.  The way we handle them in other parts
1853          of the code is by asking the agent whether any secret key is
1854          available for a given keyblock and then concluding that we
1855          have a secret key; all secret (sub)keys of the keyblock the
1856          agent does not know of are then stub keys.  This works also
1857          for card stub keys.  The learn command or the card-status
1858          command may be used to check with the agent whether a card
1859          has been inserted and a stub key is in turn generated by the
1860          agent.  */
1861       if (ski->s2k.mode == 1001 || ski->s2k.mode == 1002)
1862         {
1863           stub_key_skipped = 1;
1864           continue;
1865         }
1866
1867       /* Convert our internal secret key object into an S-expression.  */
1868       nskey = pubkey_get_nskey (pk->pubkey_algo);
1869       if (!nskey || nskey > PUBKEY_MAX_NSKEY)
1870         {
1871           err = gpg_error (GPG_ERR_BAD_SECKEY);
1872           log_error ("internal error: %s\n", gpg_strerror (err));
1873           goto leave;
1874         }
1875
1876       init_membuf (&mbuf, 50);
1877       put_membuf_str (&mbuf, "(skey");
1878       if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
1879           || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
1880           || pk->pubkey_algo == PUBKEY_ALGO_ECDH)
1881         {
1882           /* The ECC case.  */
1883           char *curvestr = openpgp_oid_to_str (pk->pkey[0]);
1884           if (!curvestr)
1885             err = gpg_error_from_syserror ();
1886           else
1887             {
1888               const char *curvename = openpgp_oid_to_curve (curvestr, 1);
1889               gcry_sexp_release (curve);
1890               err = gcry_sexp_build (&curve, NULL, "(curve %s)",
1891                                      curvename?curvename:curvestr);
1892               xfree (curvestr);
1893               if (!err)
1894                 {
1895                   j = 0;
1896                   /* Append the public key element Q.  */
1897                   put_membuf_str (&mbuf, " _ %m");
1898                   format_args[j++] = pk->pkey + 1;
1899
1900                   /* Append the secret key element D.  For ECDH we
1901                      skip PKEY[2] because this holds the KEK which is
1902                      not needed by gpg-agent.  */
1903                   i = pk->pubkey_algo == PUBKEY_ALGO_ECDH? 3 : 2;
1904                   if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
1905                     put_membuf_str (&mbuf, " e %m");
1906                   else
1907                     put_membuf_str (&mbuf, " _ %m");
1908                   format_args[j++] = pk->pkey + i;
1909                 }
1910             }
1911         }
1912       else
1913         {
1914           /* Standard case for the old (non-ECC) algorithms.  */
1915           for (i=j=0; i < nskey; i++)
1916             {
1917               if (!pk->pkey[i])
1918                 continue; /* Protected keys only have NPKEY+1 elements.  */
1919
1920               if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
1921                 put_membuf_str (&mbuf, " e %m");
1922               else
1923                 put_membuf_str (&mbuf, " _ %m");
1924               format_args[j++] = pk->pkey + i;
1925             }
1926         }
1927       put_membuf_str (&mbuf, ")");
1928       put_membuf (&mbuf, "", 1);
1929       if (err)
1930         xfree (get_membuf (&mbuf, NULL));
1931       else
1932         {
1933           char *format = get_membuf (&mbuf, NULL);
1934           if (!format)
1935             err = gpg_error_from_syserror ();
1936           else
1937             err = gcry_sexp_build_array (&skey, NULL, format, format_args);
1938           xfree (format);
1939         }
1940       if (err)
1941         {
1942           log_error ("error building skey array: %s\n", gpg_strerror (err));
1943           goto leave;
1944         }
1945
1946       if (ski->is_protected)
1947         {
1948           char countbuf[35];
1949
1950           /* Note that the IVLEN may be zero if we are working on a
1951              dummy key.  We can't express that in an S-expression and
1952              thus we send dummy data for the IV.  */
1953           snprintf (countbuf, sizeof countbuf, "%lu",
1954                     (unsigned long)ski->s2k.count);
1955           err = gcry_sexp_build
1956             (&prot, NULL,
1957              " (protection %s %s %b %d %s %b %s)\n",
1958              ski->sha1chk? "sha1":"sum",
1959              openpgp_cipher_algo_name (ski->algo),
1960              ski->ivlen? (int)ski->ivlen:1,
1961              ski->ivlen? ski->iv: (const unsigned char*)"X",
1962              ski->s2k.mode,
1963              openpgp_md_algo_name (ski->s2k.hash_algo),
1964              (int)sizeof (ski->s2k.salt), ski->s2k.salt,
1965              countbuf);
1966         }
1967       else
1968         err = gcry_sexp_build (&prot, NULL, " (protection none)\n");
1969
1970       tmpsexp = NULL;
1971       xfree (transferkey);
1972       transferkey = NULL;
1973       if (!err)
1974         err = gcry_sexp_build (&tmpsexp, NULL,
1975                                "(openpgp-private-key\n"
1976                                " (version %d)\n"
1977                                " (algo %s)\n"
1978                                " %S%S\n"
1979                                " (csum %d)\n"
1980                                " %S)\n",
1981                                pk->version,
1982                                openpgp_pk_algo_name (pk->pubkey_algo),
1983                                curve, skey,
1984                                (int)(unsigned long)ski->csum, prot);
1985       gcry_sexp_release (skey);
1986       gcry_sexp_release (prot);
1987       if (!err)
1988         err = make_canon_sexp_pad (tmpsexp, 1, &transferkey, &transferkeylen);
1989       gcry_sexp_release (tmpsexp);
1990       if (err)
1991         {
1992           log_error ("error building transfer key: %s\n", gpg_strerror (err));
1993           goto leave;
1994         }
1995
1996       /* Wrap the key.  */
1997       wrappedkeylen = transferkeylen + 8;
1998       xfree (wrappedkey);
1999       wrappedkey = xtrymalloc (wrappedkeylen);
2000       if (!wrappedkey)
2001         err = gpg_error_from_syserror ();
2002       else
2003         err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen,
2004                                    transferkey, transferkeylen);
2005       if (err)
2006         goto leave;
2007       xfree (transferkey);
2008       transferkey = NULL;
2009
2010       /* Send the wrapped key to the agent.  */
2011       {
2012         char *desc = gpg_format_keydesc (pk, FORMAT_KEYDESC_IMPORT, 1);
2013         err = agent_import_key (ctrl, desc, &cache_nonce,
2014                                 wrappedkey, wrappedkeylen, batch, force);
2015         xfree (desc);
2016       }
2017       if (!err)
2018         {
2019           if (opt.verbose)
2020             log_info (_("key %s: secret key imported\n"),
2021                       keystr_from_pk_with_sub (main_pk, pk));
2022           if (stats)
2023             stats->secret_imported++;
2024         }
2025       else if ( gpg_err_code (err) == GPG_ERR_EEXIST )
2026         {
2027           if (opt.verbose)
2028             log_info (_("key %s: secret key already exists\n"),
2029                       keystr_from_pk_with_sub (main_pk, pk));
2030           err = 0;
2031           if (stats)
2032             stats->secret_dups++;
2033         }
2034       else
2035         {
2036           log_error (_("key %s: error sending to agent: %s\n"),
2037                      keystr_from_pk_with_sub (main_pk, pk),
2038                      gpg_strerror (err));
2039           if (gpg_err_code (err) == GPG_ERR_CANCELED
2040               || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
2041             break; /* Don't try the other subkeys.  */
2042         }
2043     }
2044
2045   if (!err && stub_key_skipped)
2046     /* We need to notify user how to migrate stub keys.  */
2047     err = gpg_error (GPG_ERR_NOT_PROCESSED);
2048
2049  leave:
2050   gcry_sexp_release (curve);
2051   xfree (cache_nonce);
2052   xfree (wrappedkey);
2053   xfree (transferkey);
2054   gcry_cipher_close (cipherhd);
2055   xfree (kek);
2056   return err;
2057 }
2058
2059
2060 /* Walk a secret keyblock and produce a public keyblock out of it.
2061    Returns a new node or NULL on error. */
2062 static kbnode_t
2063 sec_to_pub_keyblock (kbnode_t sec_keyblock)
2064 {
2065   kbnode_t pub_keyblock = NULL;
2066   kbnode_t ctx = NULL;
2067   kbnode_t secnode, pubnode;
2068
2069   while ((secnode = walk_kbnode (sec_keyblock, &ctx, 0)))
2070     {
2071       if (secnode->pkt->pkttype == PKT_SECRET_KEY
2072           || secnode->pkt->pkttype == PKT_SECRET_SUBKEY)
2073         {
2074           /* Make a public key.  */
2075           PACKET *pkt;
2076           PKT_public_key *pk;
2077
2078           pkt = xtrycalloc (1, sizeof *pkt);
2079           pk = pkt? copy_public_key (NULL, secnode->pkt->pkt.public_key): NULL;
2080           if (!pk)
2081             {
2082               xfree (pkt);
2083               release_kbnode (pub_keyblock);
2084               return NULL;
2085             }
2086           if (secnode->pkt->pkttype == PKT_SECRET_KEY)
2087             pkt->pkttype = PKT_PUBLIC_KEY;
2088           else
2089             pkt->pkttype = PKT_PUBLIC_SUBKEY;
2090           pkt->pkt.public_key = pk;
2091
2092           pubnode = new_kbnode (pkt);
2093         }
2094       else
2095         {
2096           pubnode = clone_kbnode (secnode);
2097         }
2098
2099       if (!pub_keyblock)
2100         pub_keyblock = pubnode;
2101       else
2102         add_kbnode (pub_keyblock, pubnode);
2103     }
2104
2105   return pub_keyblock;
2106 }
2107
2108 /****************
2109  * Ditto for secret keys.  Handling is simpler than for public keys.
2110  * We allow secret key importing only when allow is true, this is so
2111  * that a secret key can not be imported accidentally and thereby tampering
2112  * with the trust calculation.
2113  */
2114 static int
2115 import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
2116                    struct import_stats_s *stats, int batch, unsigned int options,
2117                    int for_migration,
2118                    import_screener_t screener, void *screener_arg)
2119 {
2120   PKT_public_key *pk;
2121   struct seckey_info *ski;
2122   kbnode_t node, uidnode;
2123   u32 keyid[2];
2124   int rc = 0;
2125   int nr_prev;
2126   kbnode_t pub_keyblock;
2127   char pkstrbuf[PUBKEY_STRING_SIZE];
2128
2129   /* Get the key and print some info about it */
2130   node = find_kbnode (keyblock, PKT_SECRET_KEY);
2131   if (!node)
2132     BUG ();
2133
2134   pk = node->pkt->pkt.public_key;
2135
2136   keyid_from_pk (pk, keyid);
2137   uidnode = find_next_kbnode (keyblock, PKT_USER_ID);
2138
2139   if (screener && screener (keyblock, screener_arg))
2140     {
2141       log_error (_("secret key %s: %s\n"), keystr_from_pk (pk),
2142                  _("rejected by import screener"));
2143       return 0;
2144   }
2145
2146   if (opt.verbose && !for_migration)
2147     {
2148       log_info ("sec  %s/%s %s   ",
2149                 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
2150                 keystr_from_pk (pk), datestr_from_pk (pk));
2151       if (uidnode)
2152         print_utf8_buffer (log_get_stream (), uidnode->pkt->pkt.user_id->name,
2153                            uidnode->pkt->pkt.user_id->len);
2154       log_printf ("\n");
2155     }
2156   stats->secret_read++;
2157
2158   if ((options & IMPORT_NO_SECKEY))
2159     {
2160       if (!for_migration)
2161         log_error (_("importing secret keys not allowed\n"));
2162       return 0;
2163     }
2164
2165   if (!uidnode)
2166     {
2167       if (!for_migration)
2168         log_error( _("key %s: no user ID\n"), keystr_from_pk (pk));
2169       return 0;
2170     }
2171
2172   ski = pk->seckey_info;
2173   if (!ski)
2174     {
2175       /* Actually an internal error.  */
2176       log_error ("key %s: secret key info missing\n", keystr_from_pk (pk));
2177       return 0;
2178     }
2179
2180   /* A quick check to not import keys with an invalid protection
2181      cipher algorithm (only checks the primary key, though).  */
2182   if (ski->algo > 110)
2183     {
2184       if (!for_migration)
2185         log_error (_("key %s: secret key with invalid cipher %d"
2186                      " - skipped\n"), keystr_from_pk (pk), ski->algo);
2187       return 0;
2188     }
2189
2190 #ifdef ENABLE_SELINUX_HACKS
2191   if (1)
2192     {
2193       /* We don't allow importing secret keys because that may be used
2194          to put a secret key into the keyring and the user might later
2195          be tricked into signing stuff with that key.  */
2196       log_error (_("importing secret keys not allowed\n"));
2197       return 0;
2198     }
2199 #endif
2200
2201   clear_kbnode_flags (keyblock);
2202
2203   nr_prev = stats->skipped_new_keys;
2204
2205   /* Make a public key out of the key. */
2206   pub_keyblock = sec_to_pub_keyblock (keyblock);
2207   if (!pub_keyblock)
2208     log_error ("key %s: failed to create public key from secret key\n",
2209                    keystr_from_pk (pk));
2210   else
2211     {
2212       /* Note that this outputs an IMPORT_OK status message for the
2213          public key block, and below we will output another one for
2214          the secret keys.  FIXME?  */
2215       import_one (ctrl, pub_keyblock, stats,
2216                   NULL, NULL, options, 1, for_migration,
2217                   screener, screener_arg);
2218
2219       /* Fixme: We should check for an invalid keyblock and
2220          cancel the secret key import in this case.  */
2221       release_kbnode (pub_keyblock);
2222
2223       /* At least we cancel the secret key import when the public key
2224          import was skipped due to MERGE_ONLY option and a new
2225          key.  */
2226       if (stats->skipped_new_keys <= nr_prev)
2227         {
2228           /* Read the keyblock again to get the effects of a merge.  */
2229           /* Fixme: we should do this based on the fingerprint or
2230              even better let import_one return the merged
2231              keyblock.  */
2232           node = get_pubkeyblock (keyid);
2233           if (!node)
2234             log_error ("key %s: failed to re-lookup public key\n",
2235                        keystr_from_pk (pk));
2236           else
2237             {
2238               gpg_error_t err;
2239
2240               /* transfer_secret_keys collects subkey stats.  */
2241               struct import_stats_s subkey_stats = {0};
2242
2243               err = transfer_secret_keys (ctrl, &subkey_stats, keyblock,
2244                                           batch, 0);
2245               if (gpg_err_code (err) == GPG_ERR_NOT_PROCESSED)
2246                 {
2247                   /* TRANSLATORS: For smartcard, each private key on
2248                      host has a reference (stub) to a smartcard and
2249                      actual private key data is stored on the card.  A
2250                      single smartcard can have up to three private key
2251                      data.  Importing private key stub is always
2252                      skipped in 2.1, and it returns
2253                      GPG_ERR_NOT_PROCESSED.  Instead, user should be
2254                      suggested to run 'gpg --card-status', then,
2255                      references to a card will be automatically
2256                      created again.  */
2257                   log_info (_("To migrate '%s', with each smartcard, "
2258                               "run: %s\n"), "secring.gpg", "gpg --card-status");
2259                   err = 0;
2260                 }
2261               if (!err)
2262                 {
2263                   int status = 16;
2264                   if (!opt.quiet)
2265                     log_info (_("key %s: secret key imported\n"),
2266                               keystr_from_pk (pk));
2267                   if (subkey_stats.secret_imported)
2268                     {
2269                       status |= 1;
2270                       stats->secret_imported += 1;
2271                     }
2272                   if (subkey_stats.secret_dups)
2273                     stats->secret_dups += 1;
2274
2275                   if (is_status_enabled ())
2276                     print_import_ok (pk, status);
2277                   check_prefs (ctrl, node);
2278                 }
2279               release_kbnode (node);
2280             }
2281         }
2282     }
2283
2284   return rc;
2285 }
2286
2287
2288 /****************
2289  * Import a revocation certificate; this is a single signature packet.
2290  */
2291 static int
2292 import_revoke_cert (ctrl_t ctrl, kbnode_t node, struct import_stats_s *stats)
2293 {
2294   PKT_public_key *pk = NULL;
2295   kbnode_t onode;
2296   kbnode_t keyblock = NULL;
2297   KEYDB_HANDLE hd = NULL;
2298   u32 keyid[2];
2299   int rc = 0;
2300
2301   log_assert (!node->next );
2302   log_assert (node->pkt->pkttype == PKT_SIGNATURE );
2303   log_assert (node->pkt->pkt.signature->sig_class == 0x20 );
2304
2305   keyid[0] = node->pkt->pkt.signature->keyid[0];
2306   keyid[1] = node->pkt->pkt.signature->keyid[1];
2307
2308   pk = xmalloc_clear( sizeof *pk );
2309   rc = get_pubkey( pk, keyid );
2310   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY )
2311     {
2312       log_error(_("key %s: no public key -"
2313                   " can't apply revocation certificate\n"), keystr(keyid));
2314       rc = 0;
2315       goto leave;
2316     }
2317   else if (rc )
2318     {
2319       log_error(_("key %s: public key not found: %s\n"),
2320                 keystr(keyid), gpg_strerror (rc));
2321       goto leave;
2322     }
2323
2324   /* Read the original keyblock. */
2325   hd = keydb_new ();
2326   if (!hd)
2327     {
2328       rc = gpg_error_from_syserror ();
2329       goto leave;
2330     }
2331
2332   {
2333     byte afp[MAX_FINGERPRINT_LEN];
2334     size_t an;
2335
2336     fingerprint_from_pk (pk, afp, &an);
2337     while (an < MAX_FINGERPRINT_LEN)
2338       afp[an++] = 0;
2339     rc = keydb_search_fpr (hd, afp);
2340   }
2341   if (rc)
2342     {
2343       log_error (_("key %s: can't locate original keyblock: %s\n"),
2344                  keystr(keyid), gpg_strerror (rc));
2345       goto leave;
2346     }
2347   rc = keydb_get_keyblock (hd, &keyblock );
2348   if (rc)
2349     {
2350       log_error (_("key %s: can't read original keyblock: %s\n"),
2351                  keystr(keyid), gpg_strerror (rc));
2352       goto leave;
2353     }
2354
2355   /* it is okay, that node is not in keyblock because
2356    * check_key_signature works fine for sig_class 0x20 in this
2357    * special case. */
2358   rc = check_key_signature( keyblock, node, NULL);
2359   if (rc )
2360     {
2361       log_error( _("key %s: invalid revocation certificate"
2362                    ": %s - rejected\n"), keystr(keyid), gpg_strerror (rc));
2363       goto leave;
2364     }
2365
2366   /* check whether we already have this */
2367   for(onode=keyblock->next; onode; onode=onode->next ) {
2368     if (onode->pkt->pkttype == PKT_USER_ID )
2369       break;
2370     else if (onode->pkt->pkttype == PKT_SIGNATURE
2371              && !cmp_signatures(node->pkt->pkt.signature,
2372                                 onode->pkt->pkt.signature))
2373       {
2374         rc = 0;
2375         goto leave; /* yes, we already know about it */
2376       }
2377   }
2378
2379   /* insert it */
2380   insert_kbnode( keyblock, clone_kbnode(node), 0 );
2381
2382   /* and write the keyblock back */
2383   rc = keydb_update_keyblock (ctrl, hd, keyblock );
2384   if (rc)
2385     log_error (_("error writing keyring '%s': %s\n"),
2386                keydb_get_resource_name (hd), gpg_strerror (rc) );
2387   keydb_release (hd);
2388   hd = NULL;
2389
2390   /* we are ready */
2391   if (!opt.quiet )
2392     {
2393       char *p=get_user_id_native (keyid);
2394       log_info( _("key %s: \"%s\" revocation certificate imported\n"),
2395                 keystr(keyid),p);
2396       xfree(p);
2397     }
2398   stats->n_revoc++;
2399
2400   /* If the key we just revoked was ultimately trusted, remove its
2401      ultimate trust.  This doesn't stop the user from putting the
2402      ultimate trust back, but is a reasonable solution for now. */
2403   if(get_ownertrust(pk)==TRUST_ULTIMATE)
2404     clear_ownertrusts(pk);
2405
2406   revalidation_mark ();
2407
2408  leave:
2409   keydb_release (hd);
2410   release_kbnode( keyblock );
2411   free_public_key( pk );
2412   return rc;
2413 }
2414
2415
2416 /* Loop over the keyblock and check all self signatures.  On return
2417  * the following bis in the node flags are set:
2418  *
2419  * - NODE_GOOD_SELFSIG  :: User ID or subkey has a self-signature
2420  * - NODE_BAD_SELFSIG   :: Used ID or subkey has an invalid self-signature
2421  * - NODE_DELETION_MARK :: This node shall be deleted
2422  *
2423  * NON_SELF is set to true if there are any sigs other than self-sigs
2424  * in this keyblock.
2425  *
2426  * Returns 0 on success or -1 (but not an error code) if the keyblock
2427  * is invalid.
2428  */
2429 static int
2430 chk_self_sigs (kbnode_t keyblock, u32 *keyid, int *non_self )
2431 {
2432   kbnode_t n, knode = NULL;
2433   PKT_signature *sig;
2434   int rc;
2435   u32 bsdate=0, rsdate=0;
2436   kbnode_t bsnode = NULL, rsnode = NULL;
2437
2438   for (n=keyblock; (n = find_next_kbnode (n, 0)); )
2439     {
2440       if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2441         {
2442           knode = n;
2443           bsdate = 0;
2444           rsdate = 0;
2445           bsnode = NULL;
2446           rsnode = NULL;
2447           continue;
2448         }
2449
2450       if ( n->pkt->pkttype != PKT_SIGNATURE )
2451         continue;
2452
2453       sig = n->pkt->pkt.signature;
2454       if ( keyid[0] != sig->keyid[0] || keyid[1] != sig->keyid[1] )
2455         {
2456           *non_self = 1;
2457           continue;
2458         }
2459
2460       /* This just caches the sigs for later use.  That way we
2461          import a fully-cached key which speeds things up. */
2462       if (!opt.no_sig_cache)
2463         check_key_signature (keyblock, n, NULL);
2464
2465       if ( IS_UID_SIG(sig) || IS_UID_REV(sig) )
2466         {
2467           kbnode_t unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
2468           if ( !unode )
2469             {
2470               log_error( _("key %s: no user ID for signature\n"),
2471                          keystr(keyid));
2472               return -1;  /* The complete keyblock is invalid.  */
2473             }
2474
2475           /* If it hasn't been marked valid yet, keep trying.  */
2476           if (!(unode->flag & NODE_GOOD_SELFSIG))
2477             {
2478               rc = check_key_signature (keyblock, n, NULL);
2479               if ( rc )
2480                 {
2481                   if ( opt.verbose )
2482                     {
2483                       char *p = utf8_to_native
2484                         (unode->pkt->pkt.user_id->name,
2485                          strlen (unode->pkt->pkt.user_id->name),0);
2486                       log_info (gpg_err_code(rc) == GPG_ERR_PUBKEY_ALGO ?
2487                                 _("key %s: unsupported public key "
2488                                   "algorithm on user ID \"%s\"\n"):
2489                                 _("key %s: invalid self-signature "
2490                                   "on user ID \"%s\"\n"),
2491                                 keystr (keyid),p);
2492                       xfree (p);
2493                     }
2494                 }
2495               else
2496                 unode->flag |= NODE_GOOD_SELFSIG;
2497             }
2498         }
2499       else if (IS_KEY_SIG (sig))
2500         {
2501           rc = check_key_signature (keyblock, n, NULL);
2502           if ( rc )
2503             {
2504               if (opt.verbose)
2505                 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
2506                           _("key %s: unsupported public key algorithm\n"):
2507                           _("key %s: invalid direct key signature\n"),
2508                           keystr (keyid));
2509               n->flag |= NODE_DELETION_MARK;
2510             }
2511         }
2512       else if ( IS_SUBKEY_SIG (sig) )
2513         {
2514           /* Note that this works based solely on the timestamps like
2515              the rest of gpg.  If the standard gets revocation
2516              targets, this may need to be revised.  */
2517
2518           if ( !knode )
2519             {
2520               if (opt.verbose)
2521                 log_info (_("key %s: no subkey for key binding\n"),
2522                           keystr (keyid));
2523               n->flag |= NODE_DELETION_MARK;
2524             }
2525           else
2526             {
2527               rc = check_key_signature (keyblock, n, NULL);
2528               if ( rc )
2529                 {
2530                   if (opt.verbose)
2531                     log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
2532                               _("key %s: unsupported public key"
2533                                 " algorithm\n"):
2534                               _("key %s: invalid subkey binding\n"),
2535                               keystr (keyid));
2536                   n->flag |= NODE_DELETION_MARK;
2537                 }
2538               else
2539                 {
2540                   /* It's valid, so is it newer? */
2541                   if (sig->timestamp >= bsdate)
2542                     {
2543                       knode->flag |= NODE_GOOD_SELFSIG; /* Subkey is valid.  */
2544                       if (bsnode)
2545                         {
2546                           /* Delete the last binding sig since this
2547                              one is newer */
2548                           bsnode->flag |= NODE_DELETION_MARK;
2549                           if (opt.verbose)
2550                             log_info (_("key %s: removed multiple subkey"
2551                                         " binding\n"),keystr(keyid));
2552                         }
2553
2554                       bsnode = n;
2555                       bsdate = sig->timestamp;
2556                     }
2557                   else
2558                     n->flag |= NODE_DELETION_MARK; /* older */
2559                 }
2560             }
2561         }
2562       else if ( IS_SUBKEY_REV (sig) )
2563         {
2564           /* We don't actually mark the subkey as revoked right now,
2565              so just check that the revocation sig is the most recent
2566              valid one.  Note that we don't care if the binding sig is
2567              newer than the revocation sig.  See the comment in
2568              getkey.c:merge_selfsigs_subkey for more.  */
2569           if ( !knode )
2570             {
2571               if (opt.verbose)
2572                 log_info (_("key %s: no subkey for key revocation\n"),
2573                           keystr(keyid));
2574               n->flag |= NODE_DELETION_MARK;
2575             }
2576           else
2577             {
2578               rc = check_key_signature (keyblock, n, NULL);
2579               if ( rc )
2580                 {
2581                   if(opt.verbose)
2582                     log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
2583                               _("key %s: unsupported public"
2584                                 " key algorithm\n"):
2585                               _("key %s: invalid subkey revocation\n"),
2586                               keystr(keyid));
2587                   n->flag |= NODE_DELETION_MARK;
2588                 }
2589               else
2590                 {
2591                   /* It's valid, so is it newer? */
2592                   if (sig->timestamp >= rsdate)
2593                     {
2594                       if (rsnode)
2595                         {
2596                           /* Delete the last revocation sig since
2597                              this one is newer.  */
2598                           rsnode->flag |= NODE_DELETION_MARK;
2599                           if (opt.verbose)
2600                             log_info (_("key %s: removed multiple subkey"
2601                                         " revocation\n"),keystr(keyid));
2602                         }
2603
2604                       rsnode = n;
2605                       rsdate = sig->timestamp;
2606                     }
2607                   else
2608                     n->flag |= NODE_DELETION_MARK; /* older */
2609                 }
2610             }
2611         }
2612     }
2613
2614   return 0;
2615 }
2616
2617
2618 /* Delete all parts which are invalid and those signatures whose
2619  * public key algorithm is not available in this implemenation; but
2620  * consider RSA as valid, because parse/build_packets knows about it.
2621  *
2622  * Returns: True if at least one valid user-id is left over.
2623  */
2624 static int
2625 delete_inv_parts (kbnode_t keyblock, u32 *keyid, unsigned int options)
2626 {
2627   kbnode_t node;
2628   int nvalid=0, uid_seen=0, subkey_seen=0;
2629
2630   for (node=keyblock->next; node; node = node->next )
2631     {
2632       if (node->pkt->pkttype == PKT_USER_ID)
2633         {
2634           uid_seen = 1;
2635           if ((node->flag & NODE_BAD_SELFSIG)
2636               || !(node->flag & NODE_GOOD_SELFSIG))
2637             {
2638               if (opt.verbose )
2639                 {
2640                   char *p=utf8_to_native(node->pkt->pkt.user_id->name,
2641                                          node->pkt->pkt.user_id->len,0);
2642                   log_info( _("key %s: skipped user ID \"%s\"\n"),
2643                             keystr(keyid),p);
2644                   xfree(p);
2645                 }
2646               delete_kbnode( node ); /* the user-id */
2647               /* and all following packets up to the next user-id */
2648               while (node->next
2649                      && node->next->pkt->pkttype != PKT_USER_ID
2650                      && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
2651                      && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
2652                 delete_kbnode( node->next );
2653                 node = node->next;
2654               }
2655             }
2656           else
2657             nvalid++;
2658         }
2659       else if (   node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2660                || node->pkt->pkttype == PKT_SECRET_SUBKEY )
2661         {
2662           if ((node->flag & NODE_BAD_SELFSIG)
2663               || !(node->flag & NODE_GOOD_SELFSIG))
2664             {
2665               if (opt.verbose )
2666                 log_info( _("key %s: skipped subkey\n"),keystr(keyid));
2667
2668               delete_kbnode( node ); /* the subkey */
2669               /* and all following signature packets */
2670               while (node->next
2671                      && node->next->pkt->pkttype == PKT_SIGNATURE ) {
2672                 delete_kbnode( node->next );
2673                 node = node->next;
2674               }
2675             }
2676           else
2677             subkey_seen = 1;
2678         }
2679       else if (node->pkt->pkttype == PKT_SIGNATURE
2680                && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
2681                && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
2682         {
2683           delete_kbnode( node ); /* build_packet() can't handle this */
2684         }
2685       else if (node->pkt->pkttype == PKT_SIGNATURE
2686                && !node->pkt->pkt.signature->flags.exportable
2687                && !(options&IMPORT_LOCAL_SIGS)
2688                && !have_secret_key_with_kid (node->pkt->pkt.signature->keyid))
2689         {
2690           /* here we violate the rfc a bit by still allowing
2691            * to import non-exportable signature when we have the
2692            * the secret key used to create this signature - it
2693            * seems that this makes sense */
2694           if(opt.verbose)
2695             log_info( _("key %s: non exportable signature"
2696                         " (class 0x%02X) - skipped\n"),
2697                       keystr(keyid), node->pkt->pkt.signature->sig_class );
2698           delete_kbnode( node );
2699         }
2700       else if (node->pkt->pkttype == PKT_SIGNATURE
2701                && node->pkt->pkt.signature->sig_class == 0x20)
2702         {
2703           if (uid_seen )
2704             {
2705               if(opt.verbose)
2706                 log_info( _("key %s: revocation certificate"
2707                             " at wrong place - skipped\n"),keystr(keyid));
2708               delete_kbnode( node );
2709             }
2710           else
2711             {
2712               /* If the revocation cert is from a different key than
2713                  the one we're working on don't check it - it's
2714                  probably from a revocation key and won't be
2715                  verifiable with this key anyway. */
2716
2717               if(node->pkt->pkt.signature->keyid[0]==keyid[0]
2718                  && node->pkt->pkt.signature->keyid[1]==keyid[1])
2719                 {
2720                   int rc = check_key_signature( keyblock, node, NULL);
2721                   if (rc )
2722                     {
2723                       if(opt.verbose)
2724                         log_info( _("key %s: invalid revocation"
2725                                     " certificate: %s - skipped\n"),
2726                                   keystr(keyid), gpg_strerror (rc));
2727                       delete_kbnode( node );
2728                     }
2729                 }
2730             }
2731         }
2732       else if (node->pkt->pkttype == PKT_SIGNATURE
2733                && (node->pkt->pkt.signature->sig_class == 0x18
2734                    || node->pkt->pkt.signature->sig_class == 0x28)
2735                && !subkey_seen )
2736         {
2737           if(opt.verbose)
2738             log_info( _("key %s: subkey signature"
2739                         " in wrong place - skipped\n"), keystr(keyid));
2740           delete_kbnode( node );
2741         }
2742       else if (node->pkt->pkttype == PKT_SIGNATURE
2743                && !IS_CERT(node->pkt->pkt.signature))
2744         {
2745           if(opt.verbose)
2746             log_info(_("key %s: unexpected signature class (0x%02X) -"
2747                        " skipped\n"),keystr(keyid),
2748                      node->pkt->pkt.signature->sig_class);
2749           delete_kbnode(node);
2750           }
2751       else if ((node->flag & NODE_DELETION_MARK))
2752         delete_kbnode( node );
2753     }
2754
2755   /* note: because keyblock is the public key, it is never marked
2756    * for deletion and so keyblock cannot change */
2757   commit_kbnode( &keyblock );
2758   return nvalid;
2759 }
2760
2761 /* This function returns true if any UID is left in the keyring.  */
2762 static int
2763 any_uid_left (kbnode_t keyblock)
2764 {
2765   kbnode_t node;
2766
2767   for (node=keyblock->next; node; node = node->next)
2768     if (node->pkt->pkttype == PKT_USER_ID)
2769       return 1;
2770   return 0;
2771 }
2772
2773
2774
2775 /****************
2776  * It may happen that the imported keyblock has duplicated user IDs.
2777  * We check this here and collapse those user IDs together with their
2778  * sigs into one.
2779  * Returns: True if the keyblock has changed.
2780  */
2781 int
2782 collapse_uids( kbnode_t *keyblock )
2783 {
2784   kbnode_t uid1;
2785   int any=0;
2786
2787   for(uid1=*keyblock;uid1;uid1=uid1->next)
2788     {
2789       kbnode_t uid2;
2790
2791       if(is_deleted_kbnode(uid1))
2792         continue;
2793
2794       if(uid1->pkt->pkttype!=PKT_USER_ID)
2795         continue;
2796
2797       for(uid2=uid1->next;uid2;uid2=uid2->next)
2798         {
2799           if(is_deleted_kbnode(uid2))
2800             continue;
2801
2802           if(uid2->pkt->pkttype!=PKT_USER_ID)
2803             continue;
2804
2805           if(cmp_user_ids(uid1->pkt->pkt.user_id,
2806                           uid2->pkt->pkt.user_id)==0)
2807             {
2808               /* We have a duplicated uid */
2809               kbnode_t sig1,last;
2810
2811               any=1;
2812
2813               /* Now take uid2's signatures, and attach them to
2814                  uid1 */
2815               for(last=uid2;last->next;last=last->next)
2816                 {
2817                   if(is_deleted_kbnode(last))
2818                     continue;
2819
2820                   if(last->next->pkt->pkttype==PKT_USER_ID
2821                      || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
2822                      || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
2823                     break;
2824                 }
2825
2826               /* Snip out uid2 */
2827               (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
2828
2829               /* Now put uid2 in place as part of uid1 */
2830               last->next=uid1->next;
2831               uid1->next=uid2;
2832               delete_kbnode(uid2);
2833
2834               /* Now dedupe uid1 */
2835               for(sig1=uid1->next;sig1;sig1=sig1->next)
2836                 {
2837                   kbnode_t sig2;
2838
2839                   if(is_deleted_kbnode(sig1))
2840                     continue;
2841
2842                   if(sig1->pkt->pkttype==PKT_USER_ID
2843                      || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
2844                      || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
2845                     break;
2846
2847                   if(sig1->pkt->pkttype!=PKT_SIGNATURE)
2848                     continue;
2849
2850                   for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
2851                     {
2852                       if(is_deleted_kbnode(sig2))
2853                         continue;
2854
2855                       if(sig2->pkt->pkttype==PKT_USER_ID
2856                          || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
2857                          || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
2858                         break;
2859
2860                       if(sig2->pkt->pkttype!=PKT_SIGNATURE)
2861                         continue;
2862
2863                       if(cmp_signatures(sig1->pkt->pkt.signature,
2864                                         sig2->pkt->pkt.signature)==0)
2865                         {
2866                           /* We have a match, so delete the second
2867                              signature */
2868                           delete_kbnode(sig2);
2869                           sig2=last;
2870                         }
2871                     }
2872                 }
2873             }
2874         }
2875     }
2876
2877   commit_kbnode(keyblock);
2878
2879   if(any && !opt.quiet)
2880     {
2881       const char *key="???";
2882
2883       if ((uid1 = find_kbnode (*keyblock, PKT_PUBLIC_KEY)) )
2884         key = keystr_from_pk (uid1->pkt->pkt.public_key);
2885       else if ((uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY)) )
2886         key = keystr_from_pk (uid1->pkt->pkt.public_key);
2887
2888       log_info (_("key %s: duplicated user ID detected - merged\n"), key);
2889     }
2890
2891   return any;
2892 }
2893
2894
2895 /* Check for a 0x20 revocation from a revocation key that is not
2896    present.  This may be called without the benefit of merge_xxxx so
2897    you can't rely on pk->revkey and friends. */
2898 static void
2899 revocation_present (ctrl_t ctrl, kbnode_t keyblock)
2900 {
2901   kbnode_t onode, inode;
2902   PKT_public_key *pk = keyblock->pkt->pkt.public_key;
2903
2904   for(onode=keyblock->next;onode;onode=onode->next)
2905     {
2906       /* If we reach user IDs, we're done. */
2907       if(onode->pkt->pkttype==PKT_USER_ID)
2908         break;
2909
2910       if(onode->pkt->pkttype==PKT_SIGNATURE &&
2911          onode->pkt->pkt.signature->sig_class==0x1F &&
2912          onode->pkt->pkt.signature->revkey)
2913         {
2914           int idx;
2915           PKT_signature *sig=onode->pkt->pkt.signature;
2916
2917           for(idx=0;idx<sig->numrevkeys;idx++)
2918             {
2919               u32 keyid[2];
2920
2921               keyid_from_fingerprint(sig->revkey[idx].fpr,
2922                                      MAX_FINGERPRINT_LEN,keyid);
2923
2924               for(inode=keyblock->next;inode;inode=inode->next)
2925                 {
2926                   /* If we reach user IDs, we're done. */
2927                   if(inode->pkt->pkttype==PKT_USER_ID)
2928                     break;
2929
2930                   if(inode->pkt->pkttype==PKT_SIGNATURE &&
2931                      inode->pkt->pkt.signature->sig_class==0x20 &&
2932                      inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
2933                      inode->pkt->pkt.signature->keyid[1]==keyid[1])
2934                     {
2935                       /* Okay, we have a revocation key, and a
2936                          revocation issued by it.  Do we have the key
2937                          itself? */
2938                       int rc;
2939
2940                       rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx].fpr,
2941                                                    MAX_FINGERPRINT_LEN);
2942                       if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2943                           || gpg_err_code (rc) == GPG_ERR_UNUSABLE_PUBKEY)
2944                         {
2945                           char *tempkeystr=xstrdup(keystr_from_pk(pk));
2946
2947                           /* No, so try and get it */
2948                           if ((opt.keyserver_options.options
2949                                & KEYSERVER_AUTO_KEY_RETRIEVE)
2950                               && keyserver_any_configured (ctrl))
2951                             {
2952                               log_info(_("WARNING: key %s may be revoked:"
2953                                          " fetching revocation key %s\n"),
2954                                        tempkeystr,keystr(keyid));
2955                               keyserver_import_fprint (ctrl,
2956                                                        sig->revkey[idx].fpr,
2957                                                        MAX_FINGERPRINT_LEN,
2958                                                        opt.keyserver, 0);
2959
2960                               /* Do we have it now? */
2961                               rc=get_pubkey_byfprint_fast (NULL,
2962                                                      sig->revkey[idx].fpr,
2963                                                      MAX_FINGERPRINT_LEN);
2964                             }
2965
2966                           if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2967                               || gpg_err_code (rc) == GPG_ERR_UNUSABLE_PUBKEY)
2968                             log_info(_("WARNING: key %s may be revoked:"
2969                                        " revocation key %s not present.\n"),
2970                                      tempkeystr,keystr(keyid));
2971
2972                           xfree(tempkeystr);
2973                         }
2974                     }
2975                 }
2976             }
2977         }
2978     }
2979 }
2980
2981
2982 /*
2983  * compare and merge the blocks
2984  *
2985  * o compare the signatures: If we already have this signature, check
2986  *   that they compare okay; if not, issue a warning and ask the user.
2987  * o Simply add the signature.  Can't verify here because we may not have
2988  *   the signature's public key yet; verification is done when putting it
2989  *   into the trustdb, which is done automagically as soon as this pubkey
2990  *   is used.
2991  * Note: We indicate newly inserted packets with NODE_FLAG_A.
2992  */
2993 static int
2994 merge_blocks (kbnode_t keyblock_orig, kbnode_t keyblock,
2995               u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
2996 {
2997   kbnode_t onode, node;
2998   int rc, found;
2999
3000   /* 1st: handle revocation certificates */
3001   for (node=keyblock->next; node; node=node->next )
3002     {
3003       if (node->pkt->pkttype == PKT_USER_ID )
3004         break;
3005       else if (node->pkt->pkttype == PKT_SIGNATURE
3006                && node->pkt->pkt.signature->sig_class == 0x20)
3007         {
3008           /* check whether we already have this */
3009           found = 0;
3010           for (onode=keyblock_orig->next; onode; onode=onode->next)
3011             {
3012               if (onode->pkt->pkttype == PKT_USER_ID )
3013                 break;
3014               else if (onode->pkt->pkttype == PKT_SIGNATURE
3015                        && onode->pkt->pkt.signature->sig_class == 0x20
3016                        && !cmp_signatures(onode->pkt->pkt.signature,
3017                                           node->pkt->pkt.signature))
3018                 {
3019                   found = 1;
3020                   break;
3021                 }
3022             }
3023           if (!found)
3024             {
3025               kbnode_t n2 = clone_kbnode(node);
3026               insert_kbnode( keyblock_orig, n2, 0 );
3027               n2->flag |= NODE_FLAG_A;
3028               ++*n_sigs;
3029               if(!opt.quiet)
3030                 {
3031                   char *p=get_user_id_native (keyid);
3032                   log_info(_("key %s: \"%s\" revocation"
3033                              " certificate added\n"), keystr(keyid),p);
3034                   xfree(p);
3035                 }
3036             }
3037         }
3038     }
3039
3040   /* 2nd: merge in any direct key (0x1F) sigs */
3041   for(node=keyblock->next; node; node=node->next)
3042     {
3043       if (node->pkt->pkttype == PKT_USER_ID )
3044         break;
3045       else if (node->pkt->pkttype == PKT_SIGNATURE
3046                && node->pkt->pkt.signature->sig_class == 0x1F)
3047         {
3048           /* check whether we already have this */
3049           found = 0;
3050           for (onode=keyblock_orig->next; onode; onode=onode->next)
3051             {
3052               if (onode->pkt->pkttype == PKT_USER_ID)
3053                 break;
3054               else if (onode->pkt->pkttype == PKT_SIGNATURE
3055                        && onode->pkt->pkt.signature->sig_class == 0x1F
3056                        && !cmp_signatures(onode->pkt->pkt.signature,
3057                                           node->pkt->pkt.signature))
3058                 {
3059                   found = 1;
3060                   break;
3061                 }
3062             }
3063           if (!found )
3064             {
3065               kbnode_t n2 = clone_kbnode(node);
3066               insert_kbnode( keyblock_orig, n2, 0 );
3067               n2->flag |= NODE_FLAG_A;
3068               ++*n_sigs;
3069               if(!opt.quiet)
3070                 log_info( _("key %s: direct key signature added\n"),
3071                           keystr(keyid));
3072             }
3073         }
3074     }
3075
3076   /* 3rd: try to merge new certificates in */
3077   for (onode=keyblock_orig->next; onode; onode=onode->next)
3078     {
3079       if (!(onode->flag & NODE_FLAG_A) && onode->pkt->pkttype == PKT_USER_ID)
3080         {
3081           /* find the user id in the imported keyblock */
3082           for (node=keyblock->next; node; node=node->next)
3083             if (node->pkt->pkttype == PKT_USER_ID
3084                 && !cmp_user_ids( onode->pkt->pkt.user_id,
3085                                   node->pkt->pkt.user_id ) )
3086               break;
3087           if (node ) /* found: merge */
3088             {
3089               rc = merge_sigs (onode, node, n_sigs);
3090               if (rc )
3091                 return rc;
3092             }
3093         }
3094     }
3095
3096   /* 4th: add new user-ids */
3097   for (node=keyblock->next; node; node=node->next)
3098     {
3099       if (node->pkt->pkttype == PKT_USER_ID)
3100         {
3101           /* do we have this in the original keyblock */
3102           for (onode=keyblock_orig->next; onode; onode=onode->next )
3103             if (onode->pkt->pkttype == PKT_USER_ID
3104                 && !cmp_user_ids( onode->pkt->pkt.user_id,
3105                                   node->pkt->pkt.user_id ) )
3106               break;
3107           if (!onode ) /* this is a new user id: append */
3108             {
3109               rc = append_uid (keyblock_orig, node, n_sigs);
3110               if (rc )
3111                 return rc;
3112               ++*n_uids;
3113             }
3114         }
3115     }
3116
3117   /* 5th: add new subkeys */
3118   for (node=keyblock->next; node; node=node->next)
3119     {
3120       onode = NULL;
3121       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3122         {
3123           /* do we have this in the original keyblock? */
3124           for(onode=keyblock_orig->next; onode; onode=onode->next)
3125             if (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
3126                 && !cmp_public_keys( onode->pkt->pkt.public_key,
3127                                      node->pkt->pkt.public_key))
3128               break;
3129           if (!onode ) /* This is a new subkey: append.  */
3130             {
3131               rc = append_key (keyblock_orig, node, n_sigs);
3132               if (rc)
3133                 return rc;
3134               ++*n_subk;
3135             }
3136         }
3137       else if (node->pkt->pkttype == PKT_SECRET_SUBKEY)
3138         {
3139           /* do we have this in the original keyblock? */
3140           for (onode=keyblock_orig->next; onode; onode=onode->next )
3141             if (onode->pkt->pkttype == PKT_SECRET_SUBKEY
3142                 && !cmp_public_keys (onode->pkt->pkt.public_key,
3143                                      node->pkt->pkt.public_key) )
3144               break;
3145           if (!onode ) /* This is a new subkey: append.  */
3146             {
3147               rc = append_key (keyblock_orig, node, n_sigs);
3148               if (rc )
3149                 return rc;
3150               ++*n_subk;
3151             }
3152         }
3153     }
3154
3155   /* 6th: merge subkey certificates */
3156   for (onode=keyblock_orig->next; onode; onode=onode->next)
3157     {
3158       if (!(onode->flag & NODE_FLAG_A)
3159           && (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
3160               || onode->pkt->pkttype == PKT_SECRET_SUBKEY))
3161         {
3162           /* find the subkey in the imported keyblock */
3163           for(node=keyblock->next; node; node=node->next)
3164             {
3165               if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
3166                    || node->pkt->pkttype == PKT_SECRET_SUBKEY)
3167                   && !cmp_public_keys( onode->pkt->pkt.public_key,
3168                                        node->pkt->pkt.public_key ) )
3169                 break;
3170             }
3171           if (node) /* Found: merge.  */
3172             {
3173               rc = merge_keysigs( onode, node, n_sigs);
3174               if (rc )
3175                 return rc;
3176             }
3177         }
3178     }
3179
3180   return 0;
3181 }
3182
3183
3184 /* Helper function for merge_blocks.
3185  * Append the userid starting with NODE and all signatures to KEYBLOCK.
3186  */
3187 static int
3188 append_uid (kbnode_t keyblock, kbnode_t node, int *n_sigs)
3189 {
3190   kbnode_t n;
3191   kbnode_t n_where = NULL;
3192
3193   log_assert (node->pkt->pkttype == PKT_USER_ID );
3194
3195   /* find the position */
3196   for (n = keyblock; n; n_where = n, n = n->next)
3197     {
3198       if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
3199           || n->pkt->pkttype == PKT_SECRET_SUBKEY )
3200         break;
3201     }
3202   if (!n)
3203     n_where = NULL;
3204
3205   /* and append/insert */
3206   while (node)
3207     {
3208       /* we add a clone to the original keyblock, because this
3209        * one is released first */
3210       n = clone_kbnode(node);
3211       if (n_where)
3212         {
3213           insert_kbnode( n_where, n, 0 );
3214           n_where = n;
3215         }
3216       else
3217         add_kbnode( keyblock, n );
3218       n->flag |= NODE_FLAG_A;
3219       node->flag |= NODE_FLAG_A;
3220       if (n->pkt->pkttype == PKT_SIGNATURE )
3221         ++*n_sigs;
3222
3223       node = node->next;
3224       if (node && node->pkt->pkttype != PKT_SIGNATURE )
3225         break;
3226     }
3227
3228   return 0;
3229 }
3230
3231
3232 /* Helper function for merge_blocks
3233  * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
3234  * (how should we handle comment packets here?)
3235  */
3236 static int
3237 merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs)
3238 {
3239   kbnode_t n, n2;
3240   int found = 0;
3241
3242   log_assert (dst->pkt->pkttype == PKT_USER_ID);
3243   log_assert (src->pkt->pkttype == PKT_USER_ID);
3244
3245   for (n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next)
3246     {
3247       if (n->pkt->pkttype != PKT_SIGNATURE )
3248         continue;
3249       if (n->pkt->pkt.signature->sig_class == 0x18
3250           || n->pkt->pkt.signature->sig_class == 0x28 )
3251         continue; /* skip signatures which are only valid on subkeys */
3252
3253       found = 0;
3254       for (n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
3255         if (!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
3256           {
3257             found++;
3258             break;
3259           }
3260       if (!found )
3261         {
3262           /* This signature is new or newer, append N to DST.
3263            * We add a clone to the original keyblock, because this
3264            * one is released first */
3265           n2 = clone_kbnode(n);
3266           insert_kbnode( dst, n2, PKT_SIGNATURE );
3267           n2->flag |= NODE_FLAG_A;
3268           n->flag |= NODE_FLAG_A;
3269           ++*n_sigs;
3270         }
3271     }
3272
3273   return 0;
3274 }
3275
3276
3277 /* Helper function for merge_blocks
3278  * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
3279  */
3280 static int
3281 merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs)
3282 {
3283   kbnode_t n, n2;
3284   int found = 0;
3285
3286   log_assert (dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
3287               || dst->pkt->pkttype == PKT_SECRET_SUBKEY);
3288
3289   for (n=src->next; n ; n = n->next)
3290     {
3291       if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
3292           || n->pkt->pkttype == PKT_PUBLIC_KEY )
3293         break;
3294       if (n->pkt->pkttype != PKT_SIGNATURE )
3295         continue;
3296
3297       found = 0;
3298       for (n2=dst->next; n2; n2 = n2->next)
3299         {
3300           if (n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
3301               || n2->pkt->pkttype == PKT_PUBLIC_KEY )
3302             break;
3303           if (n2->pkt->pkttype == PKT_SIGNATURE
3304               && (n->pkt->pkt.signature->keyid[0]
3305                   == n2->pkt->pkt.signature->keyid[0])
3306               && (n->pkt->pkt.signature->keyid[1]
3307                   == n2->pkt->pkt.signature->keyid[1])
3308               && (n->pkt->pkt.signature->timestamp
3309                   <= n2->pkt->pkt.signature->timestamp)
3310               && (n->pkt->pkt.signature->sig_class
3311                   == n2->pkt->pkt.signature->sig_class))
3312             {
3313               found++;
3314               break;
3315             }
3316         }
3317       if (!found )
3318         {
3319           /* This signature is new or newer, append N to DST.
3320            * We add a clone to the original keyblock, because this
3321            * one is released first */
3322           n2 = clone_kbnode(n);
3323           insert_kbnode( dst, n2, PKT_SIGNATURE );
3324           n2->flag |= NODE_FLAG_A;
3325           n->flag |= NODE_FLAG_A;
3326           ++*n_sigs;
3327         }
3328     }
3329
3330   return 0;
3331 }
3332
3333
3334 /* Helper function for merge_blocks.
3335  * Append the subkey starting with NODE and all signatures to KEYBLOCK.
3336  * Mark all new and copied packets by setting flag bit 0.
3337  */
3338 static int
3339 append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs)
3340 {
3341   kbnode_t n;
3342
3343   log_assert (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
3344               || node->pkt->pkttype == PKT_SECRET_SUBKEY);
3345
3346   while (node)
3347     {
3348       /* we add a clone to the original keyblock, because this
3349        * one is released first */
3350       n = clone_kbnode(node);
3351       add_kbnode( keyblock, n );
3352       n->flag |= NODE_FLAG_A;
3353       node->flag |= NODE_FLAG_A;
3354       if (n->pkt->pkttype == PKT_SIGNATURE )
3355         ++*n_sigs;
3356
3357       node = node->next;
3358       if (node && node->pkt->pkttype != PKT_SIGNATURE )
3359         break;
3360     }
3361
3362   return 0;
3363 }