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