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