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