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