1 /* import.c - import a key into our key storage.
2  * Copyright (C) 1998-2007, 2010-2011 Free Software Foundation, Inc.
3  * Copyright (C) 2014, 2016, 2017, 2019  Werner Koch
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20 
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 
27 #include "gpg.h"
28 #include "options.h"
29 #include "packet.h"
30 #include "../common/status.h"
31 #include "keydb.h"
32 #include "../common/util.h"
33 #include "trustdb.h"
34 #include "main.h"
35 #include "../common/i18n.h"
36 #include "../common/ttyio.h"
37 #include "../common/recsel.h"
38 #include "keyserver-internal.h"
39 #include "call-agent.h"
40 #include "../common/membuf.h"
41 #include "../common/init.h"
42 #include "../common/mbox-util.h"
43 #include "key-check.h"
44 #include "key-clean.h"
45 
46 
47 struct import_stats_s
48 {
49   ulong count;
50   ulong no_user_id;
51   ulong imported;
52   ulong n_uids;
53   ulong n_sigs;
54   ulong n_subk;
55   ulong unchanged;
56   ulong n_revoc;
57   ulong secret_read;
58   ulong secret_imported;
59   ulong secret_dups;
60   ulong skipped_new_keys;
61   ulong not_imported;
62   ulong n_sigs_cleaned;
63   ulong n_uids_cleaned;
64   ulong v3keys;   /* Number of V3 keys seen.  */
65 };
66 
67 
68 /* Node flag to indicate that a user ID or a subkey has a
69  * valid self-signature.  */
70 #define NODE_GOOD_SELFSIG  1
71 /* Node flag to indicate that a user ID or subkey has
72  * an invalid self-signature.  */
73 #define NODE_BAD_SELFSIG   2
74 /* Node flag to indicate that the node shall be deleted.  */
75 #define NODE_DELETION_MARK 4
76 /* A node flag used to temporary mark a node. */
77 #define NODE_FLAG_A  8
78 /* A flag used by transfer_secret_keys. */
79 #define NODE_TRANSFER_SECKEY 16
80 
81 
82 /* An object and a global instance to store selectors created from
83  * --import-filter keep-uid=EXPR.
84  * --import-filter drop-sig=EXPR.
85  *
86  * FIXME: We should put this into the CTRL object but that requires a
87  * lot more changes right now.  For now we use save and restore
88  * function to temporary change them.
89  */
90 /* Definition of the import filters.  */
91 struct import_filter_s
92 {
93   recsel_expr_t keep_uid;
94   recsel_expr_t drop_sig;
95 };
96 /* The current instance.  */
97 struct import_filter_s import_filter;
98 
99 
100 static int import (ctrl_t ctrl,
101                    IOBUF inp, const char* fname, struct import_stats_s *stats,
102 		   unsigned char **fpr, size_t *fpr_len, unsigned int options,
103 		   import_screener_t screener, void *screener_arg,
104                    int origin, const char *url);
105 static int read_block (IOBUF a, unsigned int options,
106                        PACKET **pending_pkt, kbnode_t *ret_root, int *r_v3keys);
107 static void revocation_present (ctrl_t ctrl, kbnode_t keyblock);
108 static gpg_error_t import_one (ctrl_t ctrl,
109                        kbnode_t keyblock,
110                        struct import_stats_s *stats,
111                        unsigned char **fpr, size_t *fpr_len,
112                        unsigned int options, int from_sk, int silent,
113                        import_screener_t screener, void *screener_arg,
114                        int origin, const char *url, int *r_valid);
115 static gpg_error_t import_matching_seckeys (
116                        ctrl_t ctrl, kbnode_t seckeys,
117                        const byte *mainfpr, size_t mainfprlen,
118                        struct import_stats_s *stats, int batch);
119 static gpg_error_t import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
120                               struct import_stats_s *stats, int batch,
121                               unsigned int options, int for_migration,
122                               import_screener_t screener, void *screener_arg,
123                               kbnode_t *r_secattic);
124 static int import_revoke_cert (ctrl_t ctrl, kbnode_t node, unsigned int options,
125                                struct import_stats_s *stats);
126 static int chk_self_sigs (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid,
127                           int *non_self);
128 static int delete_inv_parts (ctrl_t ctrl, kbnode_t keyblock,
129                              u32 *keyid, unsigned int options);
130 static int any_uid_left (kbnode_t keyblock);
131 static void remove_all_non_self_sigs (kbnode_t *keyblock, u32 *keyid);
132 static int merge_blocks (ctrl_t ctrl, unsigned int options,
133                          kbnode_t keyblock_orig,
134 			 kbnode_t keyblock, u32 *keyid,
135                          u32 curtime, int origin, const char *url,
136 			 int *n_uids, int *n_sigs, int *n_subk );
137 static gpg_error_t append_new_uid (unsigned int options,
138                                    kbnode_t keyblock, kbnode_t node,
139                                    u32 curtime, int origin, const char *url,
140                                    int *n_sigs);
141 static int append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs);
142 static int merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs);
143 static int merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs);
144 
145 
146 
147 static void
release_import_filter(import_filter_t filt)148 release_import_filter (import_filter_t filt)
149 {
150   recsel_release (filt->keep_uid);
151   filt->keep_uid = NULL;
152   recsel_release (filt->drop_sig);
153   filt->drop_sig = NULL;
154 }
155 
156 static void
cleanup_import_globals(void)157 cleanup_import_globals (void)
158 {
159   release_import_filter (&import_filter);
160 }
161 
162 
163 int
parse_import_options(char * str,unsigned int * options,int noisy)164 parse_import_options(char *str,unsigned int *options,int noisy)
165 {
166   struct parse_options import_opts[]=
167     {
168       {"import-local-sigs",IMPORT_LOCAL_SIGS,NULL,
169        N_("import signatures that are marked as local-only")},
170 
171       {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,
172        N_("repair damage from the pks keyserver during import")},
173 
174       {"keep-ownertrust", IMPORT_KEEP_OWNERTTRUST, NULL,
175        N_("do not clear the ownertrust values during import")},
176 
177       {"fast-import",IMPORT_FAST,NULL,
178        N_("do not update the trustdb after import")},
179 
180       {"bulk-import",IMPORT_BULK, NULL,
181        N_("enable bulk import mode")},
182 
183       {"import-show",IMPORT_SHOW,NULL,
184        N_("show key during import")},
185 
186       {"show-only", (IMPORT_SHOW | IMPORT_DRY_RUN), NULL,
187        N_("show key but do not actually import") },
188 
189       {"merge-only",IMPORT_MERGE_ONLY,NULL,
190        N_("only accept updates to existing keys")},
191 
192       {"import-clean",IMPORT_CLEAN,NULL,
193        N_("remove unusable parts from key after import")},
194 
195       {"import-minimal",IMPORT_MINIMAL|IMPORT_CLEAN,NULL,
196        N_("remove as much as possible from key after import")},
197 
198       {"self-sigs-only", IMPORT_SELF_SIGS_ONLY, NULL,
199        N_("ignore key-signatures which are not self-signatures")},
200 
201       {"import-export", IMPORT_EXPORT, NULL,
202        N_("run import filters and export key immediately")},
203 
204       {"restore", IMPORT_RESTORE, NULL,
205        N_("assume the GnuPG key backup format")},
206       {"import-restore", IMPORT_RESTORE, NULL, NULL},
207 
208       {"repair-keys", IMPORT_REPAIR_KEYS, NULL,
209        N_("repair keys on import")},
210 
211       /* Hidden options which are enabled by default and are provided
212        * in case of problems with the respective implementation.  */
213       {"collapse-uids", IMPORT_COLLAPSE_UIDS, NULL, NULL},
214       {"collapse-subkeys", IMPORT_COLLAPSE_SUBKEYS, NULL, NULL},
215 
216       /* Aliases for backward compatibility */
217       {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL},
218       {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL},
219       /* dummy */
220       {"import-unusable-sigs",0,NULL,NULL},
221       {"import-clean-sigs",0,NULL,NULL},
222       {"import-clean-uids",0,NULL,NULL},
223       {"convert-sk-to-pk",0, NULL,NULL}, /* Not anymore needed due to
224                                             the new design.  */
225       {NULL,0,NULL,NULL}
226     };
227   int rc;
228   int saved_self_sigs_only, saved_import_clean;
229 
230   /* We need to set flags indicating wether the user has set certain
231    * options or if they came from the default.  */
232   saved_self_sigs_only = (*options & IMPORT_SELF_SIGS_ONLY);
233   saved_self_sigs_only &= ~IMPORT_SELF_SIGS_ONLY;
234   saved_import_clean   = (*options & IMPORT_CLEAN);
235   saved_import_clean   &= ~IMPORT_CLEAN;
236 
237   rc = parse_options (str, options, import_opts, noisy);
238 
239   if (rc && (*options & IMPORT_SELF_SIGS_ONLY))
240     opt.flags.expl_import_self_sigs_only = 1;
241   else
242     *options |= saved_self_sigs_only;
243 
244   if (rc && (*options & IMPORT_CLEAN))
245     opt.flags.expl_import_clean = 1;
246   else
247     *options |= saved_import_clean;
248 
249 
250   if (rc && (*options & IMPORT_RESTORE))
251     {
252       /* Alter other options we want or don't want for restore.  */
253       *options |= (IMPORT_LOCAL_SIGS | IMPORT_KEEP_OWNERTTRUST);
254       *options &= ~(IMPORT_MINIMAL | IMPORT_CLEAN
255                     | IMPORT_REPAIR_PKS_SUBKEY_BUG
256                     | IMPORT_MERGE_ONLY);
257     }
258   return rc;
259 }
260 
261 
262 /* Parse and set an import filter from string.  STRING has the format
263  * "NAME=EXPR" with NAME being the name of the filter.  Spaces before
264  * and after NAME are not allowed.  If this function is all called
265  * several times all expressions for the same NAME are concatenated.
266  * Supported filter names are:
267  *
268  *  - keep-uid :: If the expression evaluates to true for a certain
269  *                user ID packet, that packet and all it dependencies
270  *                will be imported.  The expression may use these
271  *                variables:
272  *
273  *                - uid  :: The entire user ID.
274  *                - mbox :: The mail box part of the user ID.
275  *                - primary :: Evaluate to true for the primary user ID.
276  */
277 gpg_error_t
parse_and_set_import_filter(const char * string)278 parse_and_set_import_filter (const char *string)
279 {
280   gpg_error_t err;
281 
282   /* Auto register the cleanup function.  */
283   register_mem_cleanup_func (cleanup_import_globals);
284 
285   if (!strncmp (string, "keep-uid=", 9))
286     err = recsel_parse_expr (&import_filter.keep_uid, string+9);
287   else if (!strncmp (string, "drop-sig=", 9))
288     err = recsel_parse_expr (&import_filter.drop_sig, string+9);
289   else
290     err = gpg_error (GPG_ERR_INV_NAME);
291 
292   return err;
293 }
294 
295 
296 /* Save the current import filters, return them, and clear the current
297  * filters.  Returns NULL on error and sets ERRNO.  */
298 import_filter_t
save_and_clear_import_filter(void)299 save_and_clear_import_filter (void)
300 {
301   import_filter_t filt;
302 
303   filt = xtrycalloc (1, sizeof *filt);
304   if (!filt)
305     return NULL;
306   *filt = import_filter;
307   memset (&import_filter, 0, sizeof import_filter);
308 
309   return filt;
310 }
311 
312 
313 /* Release the current import filters and restore them from NEWFILT.
314  * Ownership of NEWFILT is moved to this function.  */
315 void
restore_import_filter(import_filter_t filt)316 restore_import_filter (import_filter_t filt)
317 {
318   if (filt)
319     {
320       release_import_filter (&import_filter);
321       import_filter = *filt;
322       xfree (filt);
323     }
324 }
325 
326 
327 import_stats_t
import_new_stats_handle(void)328 import_new_stats_handle (void)
329 {
330   return xmalloc_clear ( sizeof (struct import_stats_s) );
331 }
332 
333 
334 void
import_release_stats_handle(import_stats_t p)335 import_release_stats_handle (import_stats_t p)
336 {
337   xfree (p);
338 }
339 
340 
341 /* Read a key from a file.  Only the first key in the file is
342  * considered and stored at R_KEYBLOCK.  FNAME is the name of the
343  * file.
344  */
345 gpg_error_t
read_key_from_file_or_buffer(ctrl_t ctrl,const char * fname,const void * buffer,size_t buflen,kbnode_t * r_keyblock)346 read_key_from_file_or_buffer (ctrl_t ctrl, const char *fname,
347                               const void *buffer, size_t buflen,
348                               kbnode_t *r_keyblock)
349 {
350   gpg_error_t err;
351   iobuf_t inp;
352   PACKET *pending_pkt = NULL;
353   kbnode_t keyblock = NULL;
354   u32 keyid[2];
355   int v3keys;   /* Dummy */
356   int non_self; /* Dummy */
357 
358   (void)ctrl;
359 
360   *r_keyblock = NULL;
361 
362   log_assert (!!fname ^ !!buffer);
363 
364   if (fname)
365     {
366       inp = iobuf_open (fname);
367       if (!inp)
368         err = gpg_error_from_syserror ();
369       else if (is_secured_file (iobuf_get_fd (inp)))
370         {
371           iobuf_close (inp);
372           inp = NULL;
373           err = gpg_error (GPG_ERR_EPERM);
374         }
375       else
376         err = 0;
377       if (err)
378         {
379           log_error (_("can't open '%s': %s\n"),
380                      iobuf_is_pipe_filename (fname)? "[stdin]": fname,
381                      gpg_strerror (err));
382           if (gpg_err_code (err) == GPG_ERR_ENOENT)
383             err = gpg_error (GPG_ERR_NO_PUBKEY);
384           goto leave;
385         }
386 
387       /* Push the armor filter.  */
388       {
389         armor_filter_context_t *afx;
390         afx = new_armor_context ();
391         afx->only_keyblocks = 1;
392         push_armor_filter (afx, inp);
393         release_armor_context (afx);
394       }
395 
396     }
397   else  /* Read from buffer (No armor expected).  */
398     {
399       inp = iobuf_temp_with_content (buffer, buflen);
400     }
401 
402   /* Read the first non-v3 keyblock.  */
403   while (!(err = read_block (inp, 0, &pending_pkt, &keyblock, &v3keys)))
404     {
405       if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
406         break;
407       log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
408       release_kbnode (keyblock);
409       keyblock = NULL;
410     }
411   if (err)
412     {
413       if (gpg_err_code (err) != GPG_ERR_INV_KEYRING)
414         log_error (_("error reading '%s': %s\n"),
415                    fname? (iobuf_is_pipe_filename (fname)? "[stdin]": fname)
416                    /* */ : "[buffer]",
417                    gpg_strerror (err));
418       goto leave;
419     }
420 
421   keyid_from_pk (keyblock->pkt->pkt.public_key, keyid);
422 
423   if (!find_next_kbnode (keyblock, PKT_USER_ID))
424     {
425       err = gpg_error (GPG_ERR_NO_USER_ID);
426       goto leave;
427     }
428 
429   /* We do the collapsing unconditionally although it is expected that
430    * clean keys are provided here.  */
431   collapse_uids (&keyblock);
432   collapse_subkeys (&keyblock);
433 
434   clear_kbnode_flags (keyblock);
435   if (chk_self_sigs (ctrl, keyblock, keyid, &non_self))
436     {
437       err = gpg_error (GPG_ERR_INV_KEYRING);
438       goto leave;
439     }
440 
441   if (!delete_inv_parts (ctrl, keyblock, keyid, 0) )
442     {
443       err = gpg_error (GPG_ERR_NO_USER_ID);
444       goto leave;
445     }
446 
447   *r_keyblock = keyblock;
448   keyblock = NULL;
449 
450  leave:
451   if (inp)
452     {
453       iobuf_close (inp);
454       /* Must invalidate that ugly cache to actually close the file. */
455       if (fname)
456         iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
457     }
458   release_kbnode (keyblock);
459   /* FIXME: Do we need to free PENDING_PKT ? */
460   return err;
461 }
462 
463 
464 /* Import an already checked public key which was included in a
465  * signature and the signature verified out using this key.  */
466 gpg_error_t
import_included_key_block(ctrl_t ctrl,kbnode_t keyblock)467 import_included_key_block (ctrl_t ctrl, kbnode_t keyblock)
468 {
469   gpg_error_t err;
470   struct import_stats_s *stats;
471   import_filter_t save_filt;
472   int save_armor = opt.armor;
473 
474   opt.armor = 0;
475   stats = import_new_stats_handle ();
476   save_filt = save_and_clear_import_filter ();
477   if (!save_filt)
478     {
479       err = gpg_error_from_syserror ();
480       goto leave;
481     }
482 
483   /* FIXME: Should we introduce a dedicated KEYORG ? */
484   err = import_one (ctrl, keyblock,
485                     stats, NULL, 0, 0, 0, 0,
486                     NULL, NULL, KEYORG_UNKNOWN, NULL, NULL);
487 
488  leave:
489   restore_import_filter (save_filt);
490   import_release_stats_handle (stats);
491   opt.armor = save_armor;
492   return err;
493 }
494 
495 
496 
497 /*
498  * Import the public keys from the given filename. Input may be armored.
499  * This function rejects all keys which are not validly self signed on at
500  * least one userid. Only user ids which are self signed will be imported.
501  * Other signatures are not checked.
502  *
503  * Actually this function does a merge. It works like this:
504  *
505  *  - get the keyblock
506  *  - check self-signatures and remove all userids and their signatures
507  *    without/invalid self-signatures.
508  *  - reject the keyblock, if we have no valid userid.
509  *  - See whether we have this key already in one of our pubrings.
510  *    If not, simply add it to the default keyring.
511  *  - Compare the key and the self-signatures of the new and the one in
512  *    our keyring.  If they are different something weird is going on;
513  *    ask what to do.
514  *  - See whether we have only non-self-signature on one user id; if not
515  *    ask the user what to do.
516  *  - compare the signatures: If we already have this signature, check
517  *    that they compare okay; if not, issue a warning and ask the user.
518  *    (consider looking at the timestamp and use the newest?)
519  *  - Simply add the signature.  Can't verify here because we may not have
520  *    the signature's public key yet; verification is done when putting it
521  *    into the trustdb, which is done automagically as soon as this pubkey
522  *    is used.
523  *  - Proceed with next signature.
524  *
525  *  Key revocation certificates have special handling.
526  */
527 static gpg_error_t
import_keys_internal(ctrl_t ctrl,iobuf_t inp,char ** fnames,int nnames,import_stats_t stats_handle,unsigned char ** fpr,size_t * fpr_len,unsigned int options,import_screener_t screener,void * screener_arg,int origin,const char * url)528 import_keys_internal (ctrl_t ctrl, iobuf_t inp, char **fnames, int nnames,
529 		      import_stats_t stats_handle,
530                       unsigned char **fpr, size_t *fpr_len,
531 		      unsigned int options,
532                       import_screener_t screener, void *screener_arg,
533                       int origin, const char *url)
534 {
535   int i;
536   gpg_error_t err = 0;
537   struct import_stats_s *stats = stats_handle;
538 
539   if (!stats)
540     stats = import_new_stats_handle ();
541 
542   if (inp)
543     {
544       err = import (ctrl, inp, "[stream]", stats, fpr, fpr_len, options,
545                     screener, screener_arg, origin, url);
546     }
547   else
548     {
549       if (!fnames && !nnames)
550         nnames = 1;  /* Ohh what a ugly hack to jump into the loop */
551 
552       for (i=0; i < nnames; i++)
553         {
554           const char *fname = fnames? fnames[i] : NULL;
555           IOBUF inp2 = iobuf_open(fname);
556 
557           if (!fname)
558             fname = "[stdin]";
559           if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
560             {
561               iobuf_close (inp2);
562               inp2 = NULL;
563               gpg_err_set_errno (EPERM);
564             }
565           if (!inp2)
566             log_error (_("can't open '%s': %s\n"), fname, strerror (errno));
567           else
568             {
569               err = import (ctrl, inp2, fname, stats, fpr, fpr_len, options,
570                            screener, screener_arg, origin, url);
571               iobuf_close (inp2);
572               /* Must invalidate that ugly cache to actually close it. */
573               iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
574               if (err)
575                 log_error ("import from '%s' failed: %s\n",
576                            fname, gpg_strerror (err) );
577             }
578           if (!fname)
579             break;
580 	}
581     }
582 
583   if (!stats_handle)
584     {
585       if ((options & (IMPORT_SHOW | IMPORT_DRY_RUN))
586           != (IMPORT_SHOW | IMPORT_DRY_RUN))
587         import_print_stats (stats);
588       import_release_stats_handle (stats);
589     }
590 
591   /* If no fast import and the trustdb is dirty (i.e. we added a key
592      or userID that had something other than a selfsig, a signature
593      that was other than a selfsig, or any revocation), then
594      update/check the trustdb if the user specified by setting
595      interactive or by not setting no-auto-check-trustdb */
596 
597   if (!(options & IMPORT_FAST))
598     check_or_update_trustdb (ctrl);
599 
600   return err;
601 }
602 
603 
604 void
import_keys(ctrl_t ctrl,char ** fnames,int nnames,import_stats_t stats_handle,unsigned int options,int origin,const char * url)605 import_keys (ctrl_t ctrl, char **fnames, int nnames,
606 	     import_stats_t stats_handle, unsigned int options,
607              int origin, const char *url)
608 {
609   import_keys_internal (ctrl, NULL, fnames, nnames, stats_handle,
610                         NULL, NULL, options, NULL, NULL, origin, url);
611 }
612 
613 
614 gpg_error_t
import_keys_es_stream(ctrl_t ctrl,estream_t fp,import_stats_t stats_handle,unsigned char ** fpr,size_t * fpr_len,unsigned int options,import_screener_t screener,void * screener_arg,int origin,const char * url)615 import_keys_es_stream (ctrl_t ctrl, estream_t fp,
616                        import_stats_t stats_handle,
617                        unsigned char **fpr, size_t *fpr_len,
618                        unsigned int options,
619                        import_screener_t screener, void *screener_arg,
620                        int origin, const char *url)
621 {
622   gpg_error_t err;
623   iobuf_t inp;
624 
625   inp = iobuf_esopen (fp, "rb", 1, 0);
626   if (!inp)
627     {
628       err = gpg_error_from_syserror ();
629       log_error ("iobuf_esopen failed: %s\n", gpg_strerror (err));
630       return err;
631     }
632 
633   err = import_keys_internal (ctrl, inp, NULL, 0, stats_handle,
634                              fpr, fpr_len, options,
635                              screener, screener_arg, origin, url);
636 
637   iobuf_close (inp);
638   return err;
639 }
640 
641 
642 static int
import(ctrl_t ctrl,IOBUF inp,const char * fname,struct import_stats_s * stats,unsigned char ** fpr,size_t * fpr_len,unsigned int options,import_screener_t screener,void * screener_arg,int origin,const char * url)643 import (ctrl_t ctrl, IOBUF inp, const char* fname,struct import_stats_s *stats,
644 	unsigned char **fpr,size_t *fpr_len, unsigned int options,
645 	import_screener_t screener, void *screener_arg,
646         int origin, const char *url)
647 {
648   PACKET *pending_pkt = NULL;
649   kbnode_t keyblock = NULL;  /* Need to initialize because gcc can't
650                                 grasp the return semantics of
651                                 read_block. */
652   kbnode_t secattic = NULL;  /* Kludge for PGP desktop percularity */
653   int rc = 0;
654   int v3keys;
655 
656   getkey_disable_caches ();
657 
658   if (!opt.no_armor) /* Armored reading is not disabled.  */
659     {
660       armor_filter_context_t *afx;
661 
662       afx = new_armor_context ();
663       afx->only_keyblocks = 1;
664       push_armor_filter (afx, inp);
665       release_armor_context (afx);
666     }
667 
668   while (!(rc = read_block (inp, options, &pending_pkt, &keyblock, &v3keys)))
669     {
670       stats->v3keys += v3keys;
671       if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
672         {
673           rc = import_one (ctrl, keyblock,
674                            stats, fpr, fpr_len, options, 0, 0,
675                            screener, screener_arg, origin, url, NULL);
676           if (secattic)
677             {
678               byte tmpfpr[MAX_FINGERPRINT_LEN];
679               size_t tmpfprlen;
680 
681               if (!rc && !(opt.dry_run || (options & IMPORT_DRY_RUN)))
682                 {
683                   /* Kudge for PGP desktop - see below.  */
684                   fingerprint_from_pk (keyblock->pkt->pkt.public_key,
685                                        tmpfpr, &tmpfprlen);
686                   rc = import_matching_seckeys (ctrl, secattic,
687                                                 tmpfpr, tmpfprlen,
688                                                 stats, opt.batch);
689                 }
690               release_kbnode (secattic);
691               secattic = NULL;
692             }
693         }
694       else if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
695         {
696           release_kbnode (secattic);
697           secattic = NULL;
698           rc = import_secret_one (ctrl, keyblock, stats,
699                                   opt.batch, options, 0,
700                                   screener, screener_arg, &secattic);
701           keyblock = NULL;  /* Ownership was transferred.  */
702           if (secattic)
703             {
704               if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
705                 rc = 0; /* Try import after the next pubkey.  */
706 
707               /* The attic is a workaround for the peculiar PGP
708                * Desktop method of exporting a secret key: The
709                * exported file is the concatenation of two armored
710                * keyblocks; first the private one and then the public
711                * one.  The strange thing is that the secret one has no
712                * binding signatures at all and thus we have not
713                * imported it.  The attic stores that secret keys and
714                * we try to import it once after the very next public
715                * keyblock.  */
716             }
717         }
718       else if (keyblock->pkt->pkttype == PKT_SIGNATURE
719                && IS_KEY_REV (keyblock->pkt->pkt.signature) )
720         {
721           release_kbnode (secattic);
722           secattic = NULL;
723           rc = import_revoke_cert (ctrl, keyblock, options, stats);
724         }
725       else
726         {
727           release_kbnode (secattic);
728           secattic = NULL;
729           log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
730 	}
731       release_kbnode (keyblock);
732 
733       /* fixme: we should increment the not imported counter but
734          this does only make sense if we keep on going despite of
735          errors.  For now we do this only if the imported key is too
736          large. */
737       if (gpg_err_code (rc) == GPG_ERR_TOO_LARGE
738             && gpg_err_source (rc) == GPG_ERR_SOURCE_KEYBOX)
739         {
740           stats->not_imported++;
741         }
742       else if (rc)
743         break;
744 
745       if (!(++stats->count % 100) && !opt.quiet)
746         log_info (_("%lu keys processed so far\n"), stats->count );
747 
748       if (origin == KEYORG_WKD && stats->count >= 5)
749         {
750           /* We limit the number of keys _received_ from the WKD to 5.
751            * In fact there should be only one key but some sites want
752            * to store a few expired keys there also.  gpg's key
753            * selection will later figure out which key to use.  Note
754            * that for WKD we always return the fingerprint of the
755            * first imported key.  */
756           log_info ("import from WKD stopped after %d keys\n", 5);
757           break;
758         }
759     }
760   stats->v3keys += v3keys;
761   if (rc == -1)
762     rc = 0;
763   else if (rc && gpg_err_code (rc) != GPG_ERR_INV_KEYRING)
764     log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (rc));
765 
766   release_kbnode (secattic);
767 
768   /* When read_block loop was stopped by error, we have PENDING_PKT left.  */
769   if (pending_pkt)
770     {
771       free_packet (pending_pkt, NULL);
772       xfree (pending_pkt);
773     }
774   return rc;
775 }
776 
777 
778 /* Helper to migrate secring.gpg to GnuPG 2.1.  */
779 gpg_error_t
import_old_secring(ctrl_t ctrl,const char * fname)780 import_old_secring (ctrl_t ctrl, const char *fname)
781 {
782   gpg_error_t err;
783   iobuf_t inp;
784   PACKET *pending_pkt = NULL;
785   kbnode_t keyblock = NULL;  /* Need to initialize because gcc can't
786                                 grasp the return semantics of
787                                 read_block. */
788   struct import_stats_s *stats;
789   int v3keys;
790 
791   inp = iobuf_open (fname);
792   if (inp && is_secured_file (iobuf_get_fd (inp)))
793     {
794       iobuf_close (inp);
795       inp = NULL;
796       gpg_err_set_errno (EPERM);
797     }
798   if (!inp)
799     {
800       err = gpg_error_from_syserror ();
801       log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
802       return err;
803     }
804 
805   getkey_disable_caches();
806   stats = import_new_stats_handle ();
807   while (!(err = read_block (inp, 0, &pending_pkt, &keyblock, &v3keys)))
808     {
809       if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
810         {
811           err = import_secret_one (ctrl, keyblock, stats, 1, 0, 1,
812                                    NULL, NULL, NULL);
813           keyblock = NULL; /* Ownership was transferred.  */
814         }
815       release_kbnode (keyblock);
816       if (err)
817         break;
818     }
819   import_release_stats_handle (stats);
820   if (err == -1)
821     err = 0;
822   else if (err && gpg_err_code (err) != GPG_ERR_INV_KEYRING)
823     log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
824   else if (err)
825     log_error ("import from '%s' failed: %s\n", fname, gpg_strerror (err));
826 
827   iobuf_close (inp);
828   iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
829 
830   return err;
831 }
832 
833 
834 void
import_print_stats(import_stats_t stats)835 import_print_stats (import_stats_t stats)
836 {
837   if (!opt.quiet)
838     {
839       log_info(_("Total number processed: %lu\n"),
840                stats->count + stats->v3keys);
841       if (stats->v3keys)
842         log_info(_("    skipped PGP-2 keys: %lu\n"), stats->v3keys);
843       if (stats->skipped_new_keys )
844         log_info(_("      skipped new keys: %lu\n"),
845                  stats->skipped_new_keys );
846       if (stats->no_user_id )
847         log_info(_("          w/o user IDs: %lu\n"), stats->no_user_id );
848       if (stats->imported)
849         {
850           log_info(_("              imported: %lu"), stats->imported );
851           log_printf ("\n");
852         }
853       if (stats->unchanged )
854         log_info(_("             unchanged: %lu\n"), stats->unchanged );
855       if (stats->n_uids )
856         log_info(_("          new user IDs: %lu\n"), stats->n_uids );
857       if (stats->n_subk )
858         log_info(_("           new subkeys: %lu\n"), stats->n_subk );
859       if (stats->n_sigs )
860         log_info(_("        new signatures: %lu\n"), stats->n_sigs );
861       if (stats->n_revoc )
862         log_info(_("   new key revocations: %lu\n"), stats->n_revoc );
863       if (stats->secret_read )
864         log_info(_("      secret keys read: %lu\n"), stats->secret_read );
865       if (stats->secret_imported )
866         log_info(_("  secret keys imported: %lu\n"), stats->secret_imported );
867       if (stats->secret_dups )
868         log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
869       if (stats->not_imported )
870         log_info(_("          not imported: %lu\n"), stats->not_imported );
871       if (stats->n_sigs_cleaned)
872         log_info(_("    signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
873       if (stats->n_uids_cleaned)
874         log_info(_("      user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
875     }
876 
877   if (is_status_enabled ())
878     {
879       char buf[15*20];
880 
881       snprintf (buf, sizeof buf,
882                 "%lu %lu %lu 0 %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
883 		stats->count + stats->v3keys,
884 		stats->no_user_id,
885 		stats->imported,
886 		stats->unchanged,
887 		stats->n_uids,
888 		stats->n_subk,
889 		stats->n_sigs,
890 		stats->n_revoc,
891 		stats->secret_read,
892 		stats->secret_imported,
893 		stats->secret_dups,
894 		stats->skipped_new_keys,
895                 stats->not_imported,
896                 stats->v3keys );
897       write_status_text (STATUS_IMPORT_RES, buf);
898     }
899 }
900 
901 
902 /* Return true if PKTTYPE is valid in a keyblock.  */
903 static int
valid_keyblock_packet(int pkttype)904 valid_keyblock_packet (int pkttype)
905 {
906   switch (pkttype)
907     {
908     case PKT_PUBLIC_KEY:
909     case PKT_PUBLIC_SUBKEY:
910     case PKT_SECRET_KEY:
911     case PKT_SECRET_SUBKEY:
912     case PKT_SIGNATURE:
913     case PKT_USER_ID:
914     case PKT_ATTRIBUTE:
915     case PKT_RING_TRUST:
916       return 1;
917     default:
918       return 0;
919     }
920 }
921 
922 
923 /* Read the next keyblock from stream A.  Meta data (ring trust
924  * packets) are only considered if OPTIONS has the IMPORT_RESTORE flag
925  * set.  PENDING_PKT should be initialized to NULL and not changed by
926  * the caller.
927  *
928  * Returns 0 for okay, -1 no more blocks, or any other errorcode.  The
929  * integer at R_V3KEY counts the number of unsupported v3 keyblocks.
930  */
931 static int
read_block(IOBUF a,unsigned int options,PACKET ** pending_pkt,kbnode_t * ret_root,int * r_v3keys)932 read_block( IOBUF a, unsigned int options,
933             PACKET **pending_pkt, kbnode_t *ret_root, int *r_v3keys)
934 {
935   int rc;
936   struct parse_packet_ctx_s parsectx;
937   PACKET *pkt;
938   kbnode_t root = NULL;
939   kbnode_t lastnode = NULL;
940   int in_cert, in_v3key, skip_sigs;
941   u32 keyid[2];
942   int got_keyid = 0;
943   unsigned int dropped_nonselfsigs = 0;
944 
945   *r_v3keys = 0;
946 
947   if (*pending_pkt)
948     {
949       root = lastnode = new_kbnode( *pending_pkt );
950       *pending_pkt = NULL;
951       log_assert (root->pkt->pkttype == PKT_PUBLIC_KEY
952                   || root->pkt->pkttype == PKT_SECRET_KEY);
953       in_cert = 1;
954       keyid_from_pk (root->pkt->pkt.public_key, keyid);
955       got_keyid = 1;
956     }
957   else
958     in_cert = 0;
959 
960   pkt = xmalloc (sizeof *pkt);
961   init_packet (pkt);
962   init_parse_packet (&parsectx, a);
963   if (!(options & IMPORT_RESTORE))
964     parsectx.skip_meta = 1;
965   in_v3key = 0;
966   skip_sigs = 0;
967   while ((rc=parse_packet (&parsectx, pkt)) != -1)
968     {
969       if (rc && (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY
970                  && (pkt->pkttype == PKT_PUBLIC_KEY
971                      || pkt->pkttype == PKT_SECRET_KEY)))
972         {
973           in_v3key = 1;
974           ++*r_v3keys;
975           free_packet (pkt, &parsectx);
976           init_packet (pkt);
977           continue;
978         }
979       else if (rc ) /* (ignore errors) */
980         {
981           skip_sigs = 0;
982           if (gpg_err_code (rc) == GPG_ERR_UNKNOWN_PACKET)
983             ; /* Do not show a diagnostic.  */
984           else if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
985                    && (pkt->pkttype == PKT_USER_ID
986                        || pkt->pkttype == PKT_ATTRIBUTE))
987             {
988               /* This indicates a too large user id or attribute
989                * packet.  We skip this packet and all following
990                * signatures.  Sure, this won't allow to repair a
991                * garbled keyring in case one of the signatures belong
992                * to another user id.  However, this better mitigates
993                * DoS using inserted user ids.  */
994               skip_sigs = 1;
995             }
996           else if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
997                    && (pkt->pkttype == PKT_OLD_COMMENT
998                        || pkt->pkttype == PKT_COMMENT))
999             ; /* Ignore too large comment packets.  */
1000           else
1001             {
1002               log_error("read_block: read error: %s\n", gpg_strerror (rc) );
1003               rc = GPG_ERR_INV_KEYRING;
1004               goto ready;
1005             }
1006           free_packet (pkt, &parsectx);
1007           init_packet(pkt);
1008           continue;
1009 	}
1010 
1011       if (skip_sigs)
1012         {
1013           if (pkt->pkttype == PKT_SIGNATURE)
1014             {
1015               free_packet (pkt, &parsectx);
1016               init_packet (pkt);
1017               continue;
1018             }
1019           skip_sigs = 0;
1020         }
1021 
1022       if (in_v3key && !(pkt->pkttype == PKT_PUBLIC_KEY
1023                         || pkt->pkttype == PKT_SECRET_KEY))
1024         {
1025           free_packet (pkt, &parsectx);
1026           init_packet(pkt);
1027           continue;
1028         }
1029       in_v3key = 0;
1030 
1031       if (!root && pkt->pkttype == PKT_SIGNATURE
1032           && IS_KEY_REV (pkt->pkt.signature) )
1033         {
1034           /* This is a revocation certificate which is handled in a
1035            * special way.  */
1036           root = new_kbnode( pkt );
1037           pkt = NULL;
1038           goto ready;
1039         }
1040 
1041       /* Make a linked list of all packets.  */
1042       switch (pkt->pkttype)
1043         {
1044         case PKT_COMPRESSED:
1045           if (check_compress_algo (pkt->pkt.compressed->algorithm))
1046             {
1047               rc = GPG_ERR_COMPR_ALGO;
1048               goto ready;
1049             }
1050           else
1051             {
1052               compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
1053               pkt->pkt.compressed->buf = NULL;
1054               if (push_compress_filter2 (a, cfx,
1055                                          pkt->pkt.compressed->algorithm, 1))
1056                 xfree (cfx); /* e.g. in case of compression_algo NONE.  */
1057             }
1058           free_packet (pkt, &parsectx);
1059           init_packet(pkt);
1060           break;
1061 
1062         case PKT_RING_TRUST:
1063           /* Skip those packets unless we are in restore mode.  */
1064           if ((opt.import_options & IMPORT_RESTORE))
1065             goto x_default;
1066           free_packet (pkt, &parsectx);
1067           init_packet(pkt);
1068           break;
1069 
1070         case PKT_SIGNATURE:
1071           if (!in_cert)
1072             goto x_default;
1073           if (!(options & IMPORT_SELF_SIGS_ONLY))
1074             goto x_default;
1075           log_assert (got_keyid);
1076 	  if (pkt->pkt.signature->keyid[0] == keyid[0]
1077               && pkt->pkt.signature->keyid[1] == keyid[1])
1078 	    { /* This is likely a self-signature.  We import this one.
1079                * Eventually we should use the ISSUER_FPR to compare
1080                * self-signatures, but that will work only for v5 keys
1081                * which are currently not even deployed.
1082                * Note that we do not do any crypto verify here because
1083                * that would defeat this very mitigation of DoS by
1084                * importing a key with a huge amount of faked
1085                * key-signatures.  A verification will be done later in
1086                * the processing anyway.  Here we want a cheap an early
1087                * way to drop non-self-signatures.  */
1088               goto x_default;
1089             }
1090           /* Skip this signature.  */
1091           dropped_nonselfsigs++;
1092           free_packet (pkt, &parsectx);
1093           init_packet(pkt);
1094           break;
1095 
1096         case PKT_PUBLIC_KEY:
1097         case PKT_SECRET_KEY:
1098           if (!got_keyid)
1099             {
1100               keyid_from_pk (pkt->pkt.public_key, keyid);
1101               got_keyid = 1;
1102             }
1103           if (in_cert) /* Store this packet.  */
1104             {
1105               *pending_pkt = pkt;
1106               pkt = NULL;
1107               goto ready;
1108             }
1109           in_cert = 1;
1110           goto x_default;
1111 
1112         default:
1113         x_default:
1114           if (in_cert && valid_keyblock_packet (pkt->pkttype))
1115             {
1116               if (!root )
1117                 root = lastnode = new_kbnode (pkt);
1118               else
1119                 {
1120                   lastnode->next = new_kbnode (pkt);
1121                   lastnode = lastnode->next;
1122                 }
1123               pkt = xmalloc (sizeof *pkt);
1124             }
1125           else
1126             free_packet (pkt, &parsectx);
1127           init_packet(pkt);
1128           break;
1129         }
1130     }
1131 
1132  ready:
1133   if (rc == -1 && root )
1134     rc = 0;
1135 
1136   if (rc )
1137     release_kbnode( root );
1138   else
1139     *ret_root = root;
1140   free_packet (pkt, &parsectx);
1141   deinit_parse_packet (&parsectx);
1142   xfree( pkt );
1143   if (!rc && dropped_nonselfsigs && opt.verbose)
1144     log_info ("key %s: number of dropped non-self-signatures: %u\n",
1145               keystr (keyid), dropped_nonselfsigs);
1146 
1147   return rc;
1148 }
1149 
1150 
1151 /* Walk through the subkeys on a pk to find if we have the PKS
1152    disease: multiple subkeys with their binding sigs stripped, and the
1153    sig for the first subkey placed after the last subkey.  That is,
1154    instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
1155    "pk uid sig sub1 sub2 sub3 bind1".  We can't do anything about sub2
1156    and sub3, as they are already lost, but we can try and rescue sub1
1157    by reordering the keyblock so that it reads "pk uid sig sub1 bind1
1158    sub2 sub3".  Returns TRUE if the keyblock was modified. */
1159 static int
fix_pks_corruption(ctrl_t ctrl,kbnode_t keyblock)1160 fix_pks_corruption (ctrl_t ctrl, kbnode_t keyblock)
1161 {
1162   int changed = 0;
1163   int keycount = 0;
1164   kbnode_t node;
1165   kbnode_t last = NULL;
1166   kbnode_t sknode=NULL;
1167 
1168   /* First determine if we have the problem at all.  Look for 2 or
1169      more subkeys in a row, followed by a single binding sig. */
1170   for (node=keyblock; node; last=node, node=node->next)
1171     {
1172       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1173 	{
1174 	  keycount++;
1175 	  if(!sknode)
1176 	    sknode=node;
1177 	}
1178       else if (node->pkt->pkttype == PKT_SIGNATURE
1179                && IS_SUBKEY_SIG (node->pkt->pkt.signature)
1180                && keycount >= 2
1181                && !node->next)
1182 	{
1183 	  /* We might have the problem, as this key has two subkeys in
1184 	     a row without any intervening packets. */
1185 
1186 	  /* Sanity check */
1187 	  if (!last)
1188 	    break;
1189 
1190 	  /* Temporarily attach node to sknode. */
1191 	  node->next = sknode->next;
1192 	  sknode->next = node;
1193 	  last->next = NULL;
1194 
1195 	  /* Note we aren't checking whether this binding sig is a
1196 	     selfsig.  This is not necessary here as the subkey and
1197 	     binding sig will be rejected later if that is the
1198 	     case. */
1199 	  if (check_key_signature (ctrl, keyblock,node,NULL))
1200 	    {
1201 	      /* Not a match, so undo the changes. */
1202 	      sknode->next = node->next;
1203 	      last->next = node;
1204 	      node->next = NULL;
1205 	      break;
1206 	    }
1207 	  else
1208 	    {
1209               /* Mark it good so we don't need to check it again */
1210 	      sknode->flag |= NODE_GOOD_SELFSIG;
1211 	      changed = 1;
1212 	      break;
1213 	    }
1214 	}
1215       else
1216 	keycount = 0;
1217     }
1218 
1219   return changed;
1220 }
1221 
1222 
1223 /* Versions of GnuPG before 1.4.11 and 2.0.16 allowed to import bogus
1224    direct key signatures.  A side effect of this was that a later
1225    import of the same good direct key signatures was not possible
1226    because the cmp_signature check in merge_blocks considered them
1227    equal.  Although direct key signatures are now checked during
1228    import, there might still be bogus signatures sitting in a keyring.
1229    We need to detect and delete them before doing a merge.  This
1230    function returns the number of removed sigs.  */
1231 static int
fix_bad_direct_key_sigs(ctrl_t ctrl,kbnode_t keyblock,u32 * keyid)1232 fix_bad_direct_key_sigs (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid)
1233 {
1234   gpg_error_t err;
1235   kbnode_t node;
1236   int count = 0;
1237 
1238   for (node = keyblock->next; node; node=node->next)
1239     {
1240       if (node->pkt->pkttype == PKT_USER_ID)
1241         break;
1242       if (node->pkt->pkttype == PKT_SIGNATURE
1243           && IS_KEY_SIG (node->pkt->pkt.signature))
1244         {
1245           err = check_key_signature (ctrl, keyblock, node, NULL);
1246           if (err && gpg_err_code (err) != GPG_ERR_PUBKEY_ALGO )
1247             {
1248               /* If we don't know the error, we can't decide; this is
1249                  not a problem because cmp_signature can't compare the
1250                  signature either.  */
1251               log_info ("key %s: invalid direct key signature removed\n",
1252                         keystr (keyid));
1253               delete_kbnode (node);
1254               count++;
1255             }
1256         }
1257     }
1258 
1259   return count;
1260 }
1261 
1262 
1263 static void
print_import_ok(PKT_public_key * pk,unsigned int reason)1264 print_import_ok (PKT_public_key *pk, unsigned int reason)
1265 {
1266   byte array[MAX_FINGERPRINT_LEN], *s;
1267   char buf[MAX_FINGERPRINT_LEN*2+30], *p;
1268   size_t i, n;
1269 
1270   snprintf (buf, sizeof buf, "%u ", reason);
1271   p = buf + strlen (buf);
1272 
1273   fingerprint_from_pk (pk, array, &n);
1274   s = array;
1275   for (i=0; i < n ; i++, s++, p += 2)
1276     sprintf (p, "%02X", *s);
1277 
1278   write_status_text (STATUS_IMPORT_OK, buf);
1279 }
1280 
1281 
1282 static void
print_import_check(PKT_public_key * pk,PKT_user_id * id)1283 print_import_check (PKT_public_key * pk, PKT_user_id * id)
1284 {
1285   byte hexfpr[2*MAX_FINGERPRINT_LEN+1];
1286   u32 keyid[2];
1287 
1288   keyid_from_pk (pk, keyid);
1289   hexfingerprint (pk, hexfpr, sizeof hexfpr);
1290   write_status_printf (STATUS_IMPORT_CHECK, "%08X%08X %s %s",
1291                        keyid[0], keyid[1], hexfpr, id->name);
1292 
1293 }
1294 
1295 
1296 static void
check_prefs_warning(PKT_public_key * pk)1297 check_prefs_warning(PKT_public_key *pk)
1298 {
1299   log_info(_("WARNING: key %s contains preferences for unavailable\n"
1300              "algorithms on these user IDs:\n"), keystr_from_pk(pk));
1301 }
1302 
1303 
1304 static void
check_prefs(ctrl_t ctrl,kbnode_t keyblock)1305 check_prefs (ctrl_t ctrl, kbnode_t keyblock)
1306 {
1307   kbnode_t node;
1308   PKT_public_key *pk;
1309   int problem=0;
1310 
1311   merge_keys_and_selfsig (ctrl, keyblock);
1312   pk=keyblock->pkt->pkt.public_key;
1313 
1314   for(node=keyblock;node;node=node->next)
1315     {
1316       if(node->pkt->pkttype==PKT_USER_ID
1317 	 && node->pkt->pkt.user_id->created
1318 	 && node->pkt->pkt.user_id->prefs)
1319 	{
1320 	  PKT_user_id *uid = node->pkt->pkt.user_id;
1321 	  prefitem_t *prefs = uid->prefs;
1322 	  char *user = utf8_to_native(uid->name,strlen(uid->name),0);
1323 
1324 	  for(;prefs->type;prefs++)
1325 	    {
1326 	      char num[10]; /* prefs->value is a byte, so we're over
1327 			       safe here */
1328 
1329 	      sprintf(num,"%u",prefs->value);
1330 
1331 	      if(prefs->type==PREFTYPE_SYM)
1332 		{
1333 		  if (openpgp_cipher_test_algo (prefs->value))
1334 		    {
1335 		      const char *algo =
1336                         (openpgp_cipher_test_algo (prefs->value)
1337                          ? num
1338                          : openpgp_cipher_algo_name (prefs->value));
1339 		      if(!problem)
1340 			check_prefs_warning(pk);
1341 		      log_info(_("         \"%s\": preference for cipher"
1342 				 " algorithm %s\n"), user, algo);
1343 		      problem=1;
1344 		    }
1345 		}
1346 	      else if(prefs->type==PREFTYPE_AEAD)
1347 		{
1348 		  if (openpgp_aead_test_algo (prefs->value))
1349 		    {
1350                       /* FIXME: The test below is wrong.  We should
1351                        * check if ...algo_name yields a "?" and
1352                        * only in that case use NUM.  */
1353 		      const char *algo =
1354                         (openpgp_aead_test_algo (prefs->value)
1355                          ? num
1356                          : openpgp_aead_algo_name (prefs->value));
1357 		      if(!problem)
1358 			check_prefs_warning(pk);
1359 		      log_info(_("         \"%s\": preference for AEAD"
1360 				 " algorithm %s\n"), user, algo);
1361 		      problem=1;
1362 		    }
1363 		}
1364 	      else if(prefs->type==PREFTYPE_HASH)
1365 		{
1366 		  if(openpgp_md_test_algo(prefs->value))
1367 		    {
1368 		      const char *algo =
1369                         (gcry_md_test_algo (prefs->value)
1370                          ? num
1371                          : gcry_md_algo_name (prefs->value));
1372 		      if(!problem)
1373 			check_prefs_warning(pk);
1374 		      log_info(_("         \"%s\": preference for digest"
1375 				 " algorithm %s\n"), user, algo);
1376 		      problem=1;
1377 		    }
1378 		}
1379 	      else if(prefs->type==PREFTYPE_ZIP)
1380 		{
1381 		  if(check_compress_algo (prefs->value))
1382 		    {
1383 		      const char *algo=compress_algo_to_string(prefs->value);
1384 		      if(!problem)
1385 			check_prefs_warning(pk);
1386 		      log_info(_("         \"%s\": preference for compression"
1387 				 " algorithm %s\n"),user,algo?algo:num);
1388 		      problem=1;
1389 		    }
1390 		}
1391 	    }
1392 
1393 	  xfree(user);
1394 	}
1395     }
1396 
1397   if(problem)
1398     {
1399       log_info(_("it is strongly suggested that you update"
1400 		 " your preferences and\n"));
1401       log_info(_("re-distribute this key to avoid potential algorithm"
1402 		 " mismatch problems\n"));
1403 
1404       if(!opt.batch)
1405 	{
1406 	  strlist_t sl = NULL;
1407           strlist_t locusr = NULL;
1408 	  size_t fprlen=0;
1409 	  byte fpr[MAX_FINGERPRINT_LEN], *p;
1410 	  char username[(MAX_FINGERPRINT_LEN*2)+1];
1411 	  unsigned int i;
1412 
1413 	  p = fingerprint_from_pk (pk,fpr,&fprlen);
1414 	  for(i=0;i<fprlen;i++,p++)
1415 	    sprintf(username+2*i,"%02X",*p);
1416 	  add_to_strlist(&locusr,username);
1417 
1418 	  append_to_strlist(&sl,"updpref");
1419 	  append_to_strlist(&sl,"save");
1420 
1421 	  keyedit_menu (ctrl, username, locusr, sl, 1, 1 );
1422 	  free_strlist(sl);
1423 	  free_strlist(locusr);
1424 	}
1425       else if(!opt.quiet)
1426 	log_info(_("you can update your preferences with:"
1427 		   " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
1428     }
1429 }
1430 
1431 
1432 /* Helper for apply_*_filter in import.c and export.c.  */
1433 const char *
impex_filter_getval(void * cookie,const char * propname)1434 impex_filter_getval (void *cookie, const char *propname)
1435 {
1436   /* FIXME: Malloc our static buffers and access them via PARM.  */
1437   struct impex_filter_parm_s *parm = cookie;
1438   ctrl_t ctrl = parm->ctrl;
1439   kbnode_t node = parm->node;
1440   static char numbuf[20];
1441   const char *result;
1442 
1443   log_assert (ctrl && ctrl->magic == SERVER_CONTROL_MAGIC);
1444 
1445   if (node->pkt->pkttype == PKT_USER_ID
1446       || node->pkt->pkttype == PKT_ATTRIBUTE)
1447     {
1448       PKT_user_id *uid = node->pkt->pkt.user_id;
1449 
1450       if (!strcmp (propname, "uid"))
1451         result = uid->name;
1452       else if (!strcmp (propname, "mbox"))
1453         {
1454           if (!uid->mbox)
1455             {
1456               uid->mbox = mailbox_from_userid (uid->name, 0);
1457             }
1458           result = uid->mbox;
1459         }
1460       else if (!strcmp (propname, "primary"))
1461         {
1462           result = uid->flags.primary? "1":"0";
1463         }
1464       else if (!strcmp (propname, "expired"))
1465         {
1466           result = uid->flags.expired? "1":"0";
1467         }
1468       else if (!strcmp (propname, "revoked"))
1469         {
1470           result = uid->flags.revoked? "1":"0";
1471         }
1472       else
1473         result = NULL;
1474     }
1475   else if (node->pkt->pkttype == PKT_SIGNATURE)
1476     {
1477       PKT_signature *sig = node->pkt->pkt.signature;
1478 
1479       if (!strcmp (propname, "sig_created"))
1480         {
1481           snprintf (numbuf, sizeof numbuf, "%lu", (ulong)sig->timestamp);
1482           result = numbuf;
1483         }
1484       else if (!strcmp (propname, "sig_created_d"))
1485         {
1486           result = dateonlystr_from_sig (sig);
1487         }
1488       else if (!strcmp (propname, "sig_algo"))
1489         {
1490           snprintf (numbuf, sizeof numbuf, "%d", sig->pubkey_algo);
1491           result = numbuf;
1492         }
1493       else if (!strcmp (propname, "sig_digest_algo"))
1494         {
1495           snprintf (numbuf, sizeof numbuf, "%d", sig->digest_algo);
1496           result = numbuf;
1497         }
1498       else if (!strcmp (propname, "expired"))
1499         {
1500           result = sig->flags.expired? "1":"0";
1501         }
1502       else
1503         result = NULL;
1504     }
1505   else if (node->pkt->pkttype == PKT_PUBLIC_KEY
1506            || node->pkt->pkttype == PKT_SECRET_KEY
1507            || node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1508            || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1509     {
1510       PKT_public_key *pk = node->pkt->pkt.public_key;
1511 
1512       if (!strcmp (propname, "secret"))
1513         {
1514           result = (node->pkt->pkttype == PKT_SECRET_KEY
1515                     || node->pkt->pkttype == PKT_SECRET_SUBKEY)? "1":"0";
1516         }
1517       else if (!strcmp (propname, "key_algo"))
1518         {
1519           snprintf (numbuf, sizeof numbuf, "%d", pk->pubkey_algo);
1520           result = numbuf;
1521         }
1522       else if (!strcmp (propname, "key_created"))
1523         {
1524           snprintf (numbuf, sizeof numbuf, "%lu", (ulong)pk->timestamp);
1525           result = numbuf;
1526         }
1527       else if (!strcmp (propname, "key_created_d"))
1528         {
1529           result = dateonlystr_from_pk (pk);
1530         }
1531       else if (!strcmp (propname, "expired"))
1532         {
1533           result = pk->has_expired? "1":"0";
1534         }
1535       else if (!strcmp (propname, "revoked"))
1536         {
1537           result = pk->flags.revoked? "1":"0";
1538         }
1539       else if (!strcmp (propname, "disabled"))
1540         {
1541           result = pk_is_disabled (pk)? "1":"0";
1542         }
1543       else if (!strcmp (propname, "usage"))
1544         {
1545           snprintf (numbuf, sizeof numbuf, "%s%s%s%s%s",
1546                     (pk->pubkey_usage & PUBKEY_USAGE_ENC)?"e":"",
1547                     (pk->pubkey_usage & PUBKEY_USAGE_SIG)?"s":"",
1548                     (pk->pubkey_usage & PUBKEY_USAGE_CERT)?"c":"",
1549                     (pk->pubkey_usage & PUBKEY_USAGE_AUTH)?"a":"",
1550                     (pk->pubkey_usage & PUBKEY_USAGE_UNKNOWN)?"?":"");
1551           result = numbuf;
1552         }
1553       else if (!strcmp (propname, "fpr"))
1554         {
1555           hexfingerprint (pk, parm->hexfpr, sizeof parm->hexfpr);
1556           result = parm->hexfpr;
1557         }
1558       else
1559         result = NULL;
1560     }
1561   else
1562     result = NULL;
1563 
1564   return result;
1565 }
1566 
1567 
1568 /*
1569  * Apply the keep-uid filter to the keyblock.  The deleted nodes are
1570  * marked and thus the caller should call commit_kbnode afterwards.
1571  * KEYBLOCK must not have any blocks marked as deleted.
1572  */
1573 static void
apply_keep_uid_filter(ctrl_t ctrl,kbnode_t keyblock,recsel_expr_t selector)1574 apply_keep_uid_filter (ctrl_t ctrl, kbnode_t keyblock, recsel_expr_t selector)
1575 {
1576   kbnode_t node;
1577   struct impex_filter_parm_s parm;
1578 
1579   parm.ctrl = ctrl;
1580 
1581   for (node = keyblock->next; node; node = node->next )
1582     {
1583       if (node->pkt->pkttype == PKT_USER_ID)
1584         {
1585           parm.node = node;
1586           if (!recsel_select (selector, impex_filter_getval, &parm))
1587             {
1588 
1589               /* log_debug ("keep-uid: deleting '%s'\n", */
1590               /*            node->pkt->pkt.user_id->name); */
1591               /* The UID packet and all following packets up to the
1592                * next UID or a subkey.  */
1593               delete_kbnode (node);
1594               for (; node->next
1595                      && node->next->pkt->pkttype != PKT_USER_ID
1596                      && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1597                      && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1598                    node = node->next)
1599                 delete_kbnode (node->next);
1600 	    }
1601           /* else */
1602           /*   log_debug ("keep-uid: keeping '%s'\n", */
1603           /*              node->pkt->pkt.user_id->name); */
1604         }
1605     }
1606 }
1607 
1608 
1609 /*
1610  * Apply the drop-sig filter to the keyblock.  The deleted nodes are
1611  * marked and thus the caller should call commit_kbnode afterwards.
1612  * KEYBLOCK must not have any blocks marked as deleted.
1613  */
1614 static void
apply_drop_sig_filter(ctrl_t ctrl,kbnode_t keyblock,recsel_expr_t selector)1615 apply_drop_sig_filter (ctrl_t ctrl, kbnode_t keyblock, recsel_expr_t selector)
1616 {
1617   kbnode_t node;
1618   int active = 0;
1619   u32 main_keyid[2];
1620   PKT_signature *sig;
1621   struct impex_filter_parm_s parm;
1622 
1623   parm.ctrl = ctrl;
1624 
1625   keyid_from_pk (keyblock->pkt->pkt.public_key, main_keyid);
1626 
1627   /* Loop over all signatures for user id and attribute packets which
1628    * are not self signatures.  */
1629   for (node = keyblock->next; node; node = node->next )
1630     {
1631       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1632           || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1633         break; /* ready.  */
1634       if (node->pkt->pkttype == PKT_USER_ID
1635           || node->pkt->pkttype == PKT_ATTRIBUTE)
1636         active = 1;
1637       if (!active)
1638         continue;
1639       if (node->pkt->pkttype != PKT_SIGNATURE)
1640         continue;
1641 
1642       sig = node->pkt->pkt.signature;
1643       if (main_keyid[0] == sig->keyid[0] || main_keyid[1] == sig->keyid[1])
1644         continue;  /* Skip self-signatures.  */
1645 
1646       if (IS_UID_SIG(sig) || IS_UID_REV(sig))
1647         {
1648           parm.node = node;
1649           if (recsel_select (selector, impex_filter_getval, &parm))
1650             delete_kbnode (node);
1651         }
1652     }
1653 }
1654 
1655 
1656 /* Insert a key origin into a public key packet.  */
1657 static gpg_error_t
insert_key_origin_pk(PKT_public_key * pk,u32 curtime,int origin,const char * url)1658 insert_key_origin_pk (PKT_public_key *pk, u32 curtime,
1659                       int origin, const char *url)
1660 {
1661   if (origin == KEYORG_WKD || origin == KEYORG_DANE)
1662     {
1663       /* For WKD and DANE we insert origin information also for the
1664        * key but we don't record the URL because we have have no use
1665        * for that: An update using a keyserver has higher precedence
1666        * and will thus update this origin info.  For refresh using WKD
1667        * or DANE we need to go via the User ID anyway.  Recall that we
1668        * are only inserting a new key. */
1669       pk->keyorg = origin;
1670       pk->keyupdate = curtime;
1671     }
1672   else if (origin == KEYORG_KS && url)
1673     {
1674       /* If the key was retrieved from a keyserver using a fingerprint
1675        * request we add the meta information.  Note that the use of a
1676        * fingerprint needs to be enforced by the caller of the import
1677        * function.  This is commonly triggered by verifying a modern
1678        * signature which has an Issuer Fingerprint signature
1679        * subpacket.  */
1680       pk->keyorg = origin;
1681       pk->keyupdate = curtime;
1682       xfree (pk->updateurl);
1683       pk->updateurl = xtrystrdup (url);
1684       if (!pk->updateurl)
1685         return gpg_error_from_syserror ();
1686     }
1687   else if (origin == KEYORG_FILE)
1688     {
1689       pk->keyorg = origin;
1690       pk->keyupdate = curtime;
1691     }
1692   else if (origin == KEYORG_URL)
1693     {
1694       pk->keyorg = origin;
1695       pk->keyupdate = curtime;
1696       if (url)
1697         {
1698           xfree (pk->updateurl);
1699           pk->updateurl = xtrystrdup (url);
1700           if (!pk->updateurl)
1701             return gpg_error_from_syserror ();
1702         }
1703     }
1704 
1705   return 0;
1706 }
1707 
1708 
1709 /* Insert a key origin into a user id packet.  */
1710 static gpg_error_t
insert_key_origin_uid(PKT_user_id * uid,u32 curtime,int origin,const char * url)1711 insert_key_origin_uid (PKT_user_id *uid, u32 curtime,
1712                        int origin, const char *url)
1713 
1714 {
1715   if (origin == KEYORG_WKD || origin == KEYORG_DANE)
1716     {
1717       /* We insert origin information on a UID only when we received
1718        * them via the Web Key Directory or a DANE record.  The key we
1719        * receive here from the WKD has been filtered to contain only
1720        * the user ID as looked up in the WKD.  For a DANE origin we
1721        * this should also be the case.  Thus we will see here only one
1722        * user id.  */
1723       uid->keyorg = origin;
1724       uid->keyupdate = curtime;
1725       if (url)
1726         {
1727           xfree (uid->updateurl);
1728           uid->updateurl = xtrystrdup (url);
1729           if (!uid->updateurl)
1730             return gpg_error_from_syserror ();
1731         }
1732     }
1733   else if (origin == KEYORG_KS && url)
1734     {
1735       /* If the key was retrieved from a keyserver using a fingerprint
1736        * request we mark that also in the user ID.  However we do not
1737        * store the keyserver URL in the UID.  A later update (merge)
1738        * from a more trusted source will replace this info.  */
1739       uid->keyorg = origin;
1740       uid->keyupdate = curtime;
1741     }
1742   else if (origin == KEYORG_FILE)
1743     {
1744       uid->keyorg = origin;
1745       uid->keyupdate = curtime;
1746     }
1747   else if (origin == KEYORG_URL)
1748     {
1749       uid->keyorg = origin;
1750       uid->keyupdate = curtime;
1751     }
1752 
1753   return 0;
1754 }
1755 
1756 
1757 /* Apply meta data to KEYBLOCK.  This sets the origin of the key to
1758  * ORIGIN and the updateurl to URL.  Note that this function is only
1759  * used for a new key, that is not when we are merging keys.  */
1760 static gpg_error_t
insert_key_origin(kbnode_t keyblock,int origin,const char * url)1761 insert_key_origin (kbnode_t keyblock, int origin, const char *url)
1762 {
1763   gpg_error_t err;
1764   kbnode_t node;
1765   u32 curtime = make_timestamp ();
1766 
1767   for (node = keyblock; node; node = node->next)
1768     {
1769       if (is_deleted_kbnode (node))
1770         ;
1771       else if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1772         {
1773           err = insert_key_origin_pk (node->pkt->pkt.public_key, curtime,
1774                                       origin, url);
1775           if (err)
1776             return err;
1777         }
1778       else if (node->pkt->pkttype == PKT_USER_ID)
1779         {
1780           err = insert_key_origin_uid (node->pkt->pkt.user_id, curtime,
1781                                        origin, url);
1782           if (err)
1783             return err;
1784         }
1785     }
1786 
1787   return 0;
1788 }
1789 
1790 
1791 /* Update meta data on KEYBLOCK.  This updates the key origin on the
1792  * public key according to ORIGIN and URL.  The UIDs are already
1793  * updated when this function is called.  */
1794 static gpg_error_t
update_key_origin(kbnode_t keyblock,u32 curtime,int origin,const char * url)1795 update_key_origin (kbnode_t keyblock, u32 curtime, int origin, const char *url)
1796 {
1797   PKT_public_key *pk;
1798 
1799   log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
1800   pk = keyblock->pkt->pkt.public_key;
1801 
1802   if (pk->keyupdate > curtime)
1803     ; /* Don't do it for a time warp.  */
1804   else if (origin == KEYORG_WKD || origin == KEYORG_DANE)
1805     {
1806       /* We only update the origin info if they either have never been
1807        * set or are the origin was the same as the new one.  If this
1808        * is WKD we also update the UID to show from which user id this
1809        * was updated.  */
1810       if (!pk->keyorg || pk->keyorg == KEYORG_WKD || pk->keyorg == KEYORG_DANE)
1811         {
1812           pk->keyorg = origin;
1813           pk->keyupdate = curtime;
1814           xfree (pk->updateurl);
1815           pk->updateurl = NULL;
1816           if (origin == KEYORG_WKD && url)
1817             {
1818               pk->updateurl = xtrystrdup (url);
1819               if (!pk->updateurl)
1820                 return gpg_error_from_syserror ();
1821             }
1822         }
1823     }
1824   else if (origin == KEYORG_KS)
1825     {
1826       /* All updates from a keyserver are considered to have the
1827        * freshed key.  Thus we always set the new key origin.  */
1828       pk->keyorg = origin;
1829       pk->keyupdate = curtime;
1830       xfree (pk->updateurl);
1831       pk->updateurl = NULL;
1832       if (url)
1833         {
1834           pk->updateurl = xtrystrdup (url);
1835           if (!pk->updateurl)
1836             return gpg_error_from_syserror ();
1837         }
1838     }
1839   else if (origin == KEYORG_FILE)
1840     {
1841       /* Updates from a file are considered to be fresh.  */
1842       pk->keyorg = origin;
1843       pk->keyupdate = curtime;
1844       xfree (pk->updateurl);
1845       pk->updateurl = NULL;
1846     }
1847   else if (origin == KEYORG_URL)
1848     {
1849       /* Updates from a URL are considered to be fresh.  */
1850       pk->keyorg = origin;
1851       pk->keyupdate = curtime;
1852       xfree (pk->updateurl);
1853       pk->updateurl = NULL;
1854       if (url)
1855         {
1856           pk->updateurl = xtrystrdup (url);
1857           if (!pk->updateurl)
1858             return gpg_error_from_syserror ();
1859         }
1860     }
1861 
1862   return 0;
1863 }
1864 
1865 
1866 /*
1867  * Try to import one keyblock. Return an error only in serious cases,
1868  * but never for an invalid keyblock.  It uses log_error to increase
1869  * the internal errorcount, so that invalid input can be detected by
1870  * programs which called gpg.  If SILENT is no messages are printed -
1871  * even most error messages are suppressed.  ORIGIN is the origin of
1872  * the key (0 for unknown) and URL the corresponding URL.  FROM_SK
1873  * indicates that the key has been made from a secret key.  If R_SAVED
1874  * is not NULL a boolean will be stored indicating whether the keyblock
1875  * has valid parts.
1876  */
1877 static gpg_error_t
import_one_real(ctrl_t ctrl,kbnode_t keyblock,struct import_stats_s * stats,unsigned char ** fpr,size_t * fpr_len,unsigned int options,int from_sk,int silent,import_screener_t screener,void * screener_arg,int origin,const char * url,int * r_valid)1878 import_one_real (ctrl_t ctrl,
1879                  kbnode_t keyblock, struct import_stats_s *stats,
1880                  unsigned char **fpr, size_t *fpr_len, unsigned int options,
1881                  int from_sk, int silent,
1882                  import_screener_t screener, void *screener_arg,
1883                  int origin, const char *url, int *r_valid)
1884 {
1885   gpg_error_t err = 0;
1886   PKT_public_key *pk;
1887   kbnode_t node, uidnode;
1888   kbnode_t keyblock_orig = NULL;
1889   byte fpr2[MAX_FINGERPRINT_LEN];
1890   size_t fpr2len;
1891   u32 keyid[2];
1892   int new_key = 0;
1893   int mod_key = 0;
1894   int same_key = 0;
1895   int non_self = 0;
1896   size_t an;
1897   char pkstrbuf[PUBKEY_STRING_SIZE];
1898   int merge_keys_done = 0;
1899   int any_filter = 0;
1900   KEYDB_HANDLE hd = NULL;
1901 
1902   if (r_valid)
1903     *r_valid = 0;
1904 
1905   /* If show-only is active we don't won't any extra output.  */
1906   if ((options & (IMPORT_SHOW | IMPORT_DRY_RUN)))
1907     silent = 1;
1908 
1909   /* Get the key and print some info about it. */
1910   node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
1911   if (!node )
1912     BUG();
1913 
1914   pk = node->pkt->pkt.public_key;
1915 
1916   fingerprint_from_pk (pk, fpr2, &fpr2len);
1917   for (an = fpr2len; an < MAX_FINGERPRINT_LEN; an++)
1918     fpr2[an] = 0;
1919   keyid_from_pk( pk, keyid );
1920   uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1921 
1922   if (opt.verbose && !opt.interactive && !silent && !from_sk)
1923     {
1924       /* Note that we do not print this info in FROM_SK mode
1925        * because import_secret_one already printed that.  */
1926       log_info ("pub  %s/%s %s  ",
1927                 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
1928                 keystr_from_pk(pk), datestr_from_pk(pk) );
1929       if (uidnode)
1930         print_utf8_buffer (log_get_stream (),
1931                            uidnode->pkt->pkt.user_id->name,
1932                            uidnode->pkt->pkt.user_id->len );
1933       log_printf ("\n");
1934     }
1935 
1936 
1937   if (!uidnode)
1938     {
1939       if (!silent)
1940         log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
1941       return 0;
1942     }
1943 
1944   if (screener && screener (keyblock, screener_arg))
1945     {
1946       log_error (_("key %s: %s\n"), keystr_from_pk (pk),
1947                  _("rejected by import screener"));
1948       return 0;
1949     }
1950 
1951   if (opt.interactive && !silent)
1952     {
1953       if (is_status_enabled())
1954         print_import_check (pk, uidnode->pkt->pkt.user_id);
1955       merge_keys_and_selfsig (ctrl, keyblock);
1956       tty_printf ("\n");
1957       show_basic_key_info (ctrl, keyblock, from_sk);
1958       tty_printf ("\n");
1959       if (!cpr_get_answer_is_yes ("import.okay",
1960                                   "Do you want to import this key? (y/N) "))
1961         return 0;
1962     }
1963 
1964   /* Remove all non-self-sigs if requested.  Note that this is a NOP if
1965    * that option has been globally set but we may also be called
1966    * latter with the already parsed keyblock and a locally changed
1967    * option.  This is why we need to remove them here as well.  */
1968   if ((options & IMPORT_SELF_SIGS_ONLY))
1969     remove_all_non_self_sigs (&keyblock, keyid);
1970 
1971   /* Remove or collapse the user ids.  */
1972   if ((options & IMPORT_COLLAPSE_UIDS))
1973     collapse_uids (&keyblock);
1974 
1975   if ((options & IMPORT_COLLAPSE_SUBKEYS))
1976     collapse_subkeys (&keyblock);
1977 
1978   /* Clean the key that we're about to import, to cut down on things
1979      that we have to clean later.  This has no practical impact on the
1980      end result, but does result in less logging which might confuse
1981      the user. */
1982   if ((options & IMPORT_CLEAN))
1983     {
1984       merge_keys_and_selfsig (ctrl, keyblock);
1985       clean_all_uids (ctrl, keyblock,
1986                       opt.verbose, (options&IMPORT_MINIMAL), NULL, NULL);
1987       clean_all_subkeys (ctrl, keyblock, opt.verbose, KEY_CLEAN_NONE,
1988                          NULL, NULL);
1989     }
1990 
1991   clear_kbnode_flags( keyblock );
1992 
1993   if ((options&IMPORT_REPAIR_PKS_SUBKEY_BUG)
1994       && fix_pks_corruption (ctrl, keyblock)
1995       && opt.verbose)
1996     log_info (_("key %s: PKS subkey corruption repaired\n"),
1997               keystr_from_pk(pk));
1998 
1999   if ((options & IMPORT_REPAIR_KEYS))
2000     key_check_all_keysigs (ctrl, 1, keyblock, 0, 0);
2001 
2002   if (chk_self_sigs (ctrl, keyblock, keyid, &non_self))
2003     return 0;  /* Invalid keyblock - error already printed.  */
2004 
2005   /* If we allow such a thing, mark unsigned uids as valid */
2006   if (opt.allow_non_selfsigned_uid)
2007     {
2008       for (node=keyblock; node; node = node->next )
2009         if (node->pkt->pkttype == PKT_USER_ID
2010             && !(node->flag & NODE_GOOD_SELFSIG)
2011             && !(node->flag & NODE_BAD_SELFSIG) )
2012           {
2013             char *user=utf8_to_native(node->pkt->pkt.user_id->name,
2014                                       node->pkt->pkt.user_id->len,0);
2015             /* Fake a good signature status for the user id.  */
2016             node->flag |= NODE_GOOD_SELFSIG;
2017             log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
2018                       keystr_from_pk(pk),user);
2019             xfree(user);
2020 	  }
2021     }
2022 
2023   /* Delete invalid parts and bail out if there are no user ids left.  */
2024   if (!delete_inv_parts (ctrl, keyblock, keyid, options))
2025     {
2026       if (!silent)
2027         {
2028           log_error ( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
2029           if (!opt.quiet)
2030             log_info(_("this may be caused by a missing self-signature\n"));
2031         }
2032       stats->no_user_id++;
2033       return 0;
2034     }
2035 
2036   /* Get rid of deleted nodes.  */
2037   commit_kbnode (&keyblock);
2038 
2039   /* Apply import filter.  */
2040   if (import_filter.keep_uid)
2041     {
2042       apply_keep_uid_filter (ctrl, keyblock, import_filter.keep_uid);
2043       commit_kbnode (&keyblock);
2044       any_filter = 1;
2045     }
2046   if (import_filter.drop_sig)
2047     {
2048       apply_drop_sig_filter (ctrl, keyblock, import_filter.drop_sig);
2049       commit_kbnode (&keyblock);
2050       any_filter = 1;
2051     }
2052 
2053   /* If we ran any filter we need to check that at least one user id
2054    * is left in the keyring.  Note that we do not use log_error in
2055    * this case. */
2056   if (any_filter && !any_uid_left (keyblock))
2057     {
2058       if (!opt.quiet )
2059         log_info ( _("key %s: no valid user IDs\n"), keystr_from_pk (pk));
2060       stats->no_user_id++;
2061       return 0;
2062     }
2063 
2064   /* The keyblock is valid and ready for real import.  */
2065   if (r_valid)
2066     *r_valid = 1;
2067 
2068   /* Show the key in the form it is merged or inserted.  We skip this
2069    * if "import-export" is also active without --armor or the output
2070    * file has explicily been given. */
2071   if ((options & IMPORT_SHOW)
2072       && !((options & IMPORT_EXPORT) && !opt.armor && !opt.outfile))
2073     {
2074       merge_keys_and_selfsig (ctrl, keyblock);
2075       merge_keys_done = 1;
2076       /* Note that we do not want to show the validity because the key
2077        * has not yet imported.  */
2078       list_keyblock_direct (ctrl, keyblock, from_sk, 0,
2079                             opt.fingerprint || opt.with_fingerprint, 1);
2080       es_fflush (es_stdout);
2081     }
2082 
2083   /* Write the keyblock to the output and do not actually import.  */
2084   if ((options & IMPORT_EXPORT))
2085     {
2086       if (!merge_keys_done)
2087         {
2088           merge_keys_and_selfsig (ctrl, keyblock);
2089           merge_keys_done = 1;
2090         }
2091       err = write_keyblock_to_output (keyblock, opt.armor, opt.export_options);
2092       goto leave;
2093     }
2094 
2095   if (opt.dry_run || (options & IMPORT_DRY_RUN))
2096     goto leave;
2097 
2098   /* Do we have this key already in one of our pubrings ? */
2099   err = get_keyblock_byfprint_fast (ctrl, &keyblock_orig, &hd,
2100                                     fpr2, fpr2len, 1/*locked*/);
2101   if ((err
2102        && gpg_err_code (err) != GPG_ERR_NO_PUBKEY
2103        && gpg_err_code (err) != GPG_ERR_UNUSABLE_PUBKEY)
2104       || !hd)
2105     {
2106       /* The !hd above is to catch a misbehaving function which
2107        * returns NO_PUBKEY for failing to allocate a handle.  */
2108       if (!silent)
2109         log_error (_("key %s: public key not found: %s\n"),
2110                    keystr(keyid), gpg_strerror (err));
2111     }
2112   else if (err && (opt.import_options&IMPORT_MERGE_ONLY) )
2113     {
2114       if (opt.verbose && !silent )
2115         log_info( _("key %s: new key - skipped\n"), keystr(keyid));
2116       err = 0;
2117       stats->skipped_new_keys++;
2118     }
2119   else if (err)  /* Insert this key. */
2120     {
2121       /* Note: ERR can only be NO_PUBKEY or UNUSABLE_PUBKEY.  */
2122       int n_sigs_cleaned, n_uids_cleaned;
2123 
2124       err = keydb_locate_writable (hd);
2125       if (err)
2126         {
2127           log_error (_("no writable keyring found: %s\n"), gpg_strerror (err));
2128           err = gpg_error (GPG_ERR_GENERAL);
2129           goto leave;
2130 	}
2131       if (opt.verbose > 1 )
2132         log_info (_("writing to '%s'\n"), keydb_get_resource_name (hd) );
2133 
2134       if ((options & IMPORT_CLEAN))
2135         {
2136           merge_keys_and_selfsig (ctrl, keyblock);
2137           clean_all_uids (ctrl, keyblock, opt.verbose, (options&IMPORT_MINIMAL),
2138                           &n_uids_cleaned,&n_sigs_cleaned);
2139           clean_all_subkeys (ctrl, keyblock, opt.verbose, KEY_CLEAN_NONE,
2140                              NULL, NULL);
2141         }
2142 
2143       /* Unless we are in restore mode apply meta data to the
2144        * keyblock.  Note that this will never change the first packet
2145        * and thus the address of KEYBLOCK won't change.  */
2146       if ( !(options & IMPORT_RESTORE) )
2147         {
2148           err = insert_key_origin (keyblock, origin, url);
2149           if (err)
2150             {
2151               log_error ("insert_key_origin failed: %s\n", gpg_strerror (err));
2152               err = gpg_error (GPG_ERR_GENERAL);
2153               goto leave;
2154             }
2155         }
2156 
2157       err = keydb_insert_keyblock (hd, keyblock );
2158       if (err)
2159         log_error (_("error writing keyring '%s': %s\n"),
2160                    keydb_get_resource_name (hd), gpg_strerror (err));
2161       else if (!(opt.import_options & IMPORT_KEEP_OWNERTTRUST))
2162         {
2163           /* This should not be possible since we delete the
2164              ownertrust when a key is deleted, but it can happen if
2165              the keyring and trustdb are out of sync.  It can also
2166              be made to happen with the trusted-key command and by
2167              importing and locally exported key. */
2168 
2169           clear_ownertrusts (ctrl, pk);
2170           if (non_self)
2171             revalidation_mark (ctrl);
2172         }
2173 
2174       /* Release the handle and thus unlock the keyring asap.  */
2175       keydb_release (hd);
2176       hd = NULL;
2177 
2178       /* We are ready.  */
2179       if (!err && !opt.quiet && !silent)
2180         {
2181           char *p = get_user_id_byfpr_native (ctrl, fpr2, fpr2len);
2182           log_info (_("key %s: public key \"%s\" imported\n"),
2183                     keystr(keyid), p);
2184           xfree(p);
2185         }
2186       if (!err && is_status_enabled())
2187         {
2188           char *us = get_long_user_id_string (ctrl, keyid);
2189           write_status_text( STATUS_IMPORTED, us );
2190           xfree(us);
2191           print_import_ok (pk, 1);
2192         }
2193       if (!err)
2194         {
2195           stats->imported++;
2196           new_key = 1;
2197         }
2198     }
2199   else /* Key already exists - merge.  */
2200     {
2201       int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
2202       u32 curtime = make_timestamp ();
2203 
2204       /* Compare the original against the new key; just to be sure nothing
2205        * weird is going on */
2206       if (cmp_public_keys (keyblock_orig->pkt->pkt.public_key, pk))
2207         {
2208           if (!silent)
2209             log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
2210           goto leave;
2211         }
2212 
2213       /* Make sure the original direct key sigs are all sane.  */
2214       n_sigs_cleaned = fix_bad_direct_key_sigs (ctrl, keyblock_orig, keyid);
2215       if (n_sigs_cleaned)
2216         commit_kbnode (&keyblock_orig);
2217 
2218       /* Try to merge KEYBLOCK into KEYBLOCK_ORIG.  */
2219       clear_kbnode_flags( keyblock_orig );
2220       clear_kbnode_flags( keyblock );
2221       n_uids = n_sigs = n_subk = n_uids_cleaned = 0;
2222       err = merge_blocks (ctrl, options, keyblock_orig, keyblock, keyid,
2223                           curtime, origin, url,
2224                           &n_uids, &n_sigs, &n_subk );
2225       if (err)
2226         goto leave;
2227 
2228       /* Clean the final keyblock again if requested.  we can't do
2229        * this if only self-signatures are imported; see bug #4628.  */
2230       if ((options & IMPORT_CLEAN)
2231           && !(options & IMPORT_SELF_SIGS_ONLY))
2232         {
2233           merge_keys_and_selfsig (ctrl, keyblock_orig);
2234           clean_all_uids (ctrl, keyblock_orig, opt.verbose,
2235                           (options&IMPORT_MINIMAL),
2236                           &n_uids_cleaned,&n_sigs_cleaned);
2237           clean_all_subkeys (ctrl, keyblock_orig, opt.verbose, KEY_CLEAN_NONE,
2238                              NULL, NULL);
2239         }
2240 
2241       if (n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned)
2242         {
2243           /* Unless we are in restore mode apply meta data to the
2244            * keyblock.  Note that this will never change the first packet
2245            * and thus the address of KEYBLOCK won't change.  */
2246           if ( !(options & IMPORT_RESTORE) )
2247             {
2248               err = update_key_origin (keyblock_orig, curtime, origin, url);
2249               if (err)
2250                 {
2251                   log_error ("update_key_origin failed: %s\n",
2252                              gpg_strerror (err));
2253                   goto leave;
2254                 }
2255             }
2256 
2257           mod_key = 1;
2258           /* KEYBLOCK_ORIG has been updated; write */
2259           err = keydb_update_keyblock (ctrl, hd, keyblock_orig);
2260           if (err)
2261             log_error (_("error writing keyring '%s': %s\n"),
2262                        keydb_get_resource_name (hd), gpg_strerror (err));
2263           else if (non_self)
2264             revalidation_mark (ctrl);
2265 
2266           /* Release the handle and thus unlock the keyring asap.  */
2267           keydb_release (hd);
2268           hd = NULL;
2269 
2270           /* We are ready.  Print and update stats if we got no error.
2271            * An error here comes from writing the keyblock and thus
2272            * very likely means that no update happened.  */
2273           if (!err && !opt.quiet && !silent)
2274             {
2275               char *p = get_user_id_byfpr_native (ctrl, fpr2, fpr2len);
2276               if (n_uids == 1 )
2277                 log_info( _("key %s: \"%s\" 1 new user ID\n"),
2278                           keystr(keyid),p);
2279               else if (n_uids )
2280                 log_info( _("key %s: \"%s\" %d new user IDs\n"),
2281                           keystr(keyid),p,n_uids);
2282               if (n_sigs == 1 )
2283                 log_info( _("key %s: \"%s\" 1 new signature\n"),
2284                           keystr(keyid), p);
2285               else if (n_sigs )
2286                 log_info( _("key %s: \"%s\" %d new signatures\n"),
2287                           keystr(keyid), p, n_sigs );
2288               if (n_subk == 1 )
2289                 log_info( _("key %s: \"%s\" 1 new subkey\n"),
2290                           keystr(keyid), p);
2291               else if (n_subk )
2292                 log_info( _("key %s: \"%s\" %d new subkeys\n"),
2293                           keystr(keyid), p, n_subk );
2294               if (n_sigs_cleaned==1)
2295                 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
2296                          keystr(keyid),p,n_sigs_cleaned);
2297               else if (n_sigs_cleaned)
2298                 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
2299                          keystr(keyid),p,n_sigs_cleaned);
2300               if (n_uids_cleaned==1)
2301                 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
2302                          keystr(keyid),p,n_uids_cleaned);
2303               else if (n_uids_cleaned)
2304                 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
2305                          keystr(keyid),p,n_uids_cleaned);
2306               xfree(p);
2307             }
2308 
2309           if (!err)
2310             {
2311               stats->n_uids +=n_uids;
2312               stats->n_sigs +=n_sigs;
2313               stats->n_subk +=n_subk;
2314               stats->n_sigs_cleaned +=n_sigs_cleaned;
2315               stats->n_uids_cleaned +=n_uids_cleaned;
2316 
2317               if (is_status_enabled () && !silent)
2318                 print_import_ok (pk, ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
2319             }
2320 	}
2321       else
2322         {
2323           /* Release the handle and thus unlock the keyring asap.  */
2324           keydb_release (hd);
2325           hd = NULL;
2326 
2327           /* FIXME: We do not track the time we last checked a key for
2328            * updates.  To do this we would need to rewrite even the
2329            * keys which have no changes.  Adding this would be useful
2330            * for the automatic update of expired keys via the WKD in
2331            * case the WKD still carries the expired key.  See
2332            * get_best_pubkey_byname.  */
2333           same_key = 1;
2334           if (is_status_enabled ())
2335             print_import_ok (pk, 0);
2336 
2337           if (!opt.quiet && !silent)
2338             {
2339               char *p = get_user_id_byfpr_native (ctrl, fpr2, fpr2len);
2340               log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
2341               xfree(p);
2342             }
2343 
2344           stats->unchanged++;
2345         }
2346     }
2347 
2348  leave:
2349   keydb_release (hd);
2350   if (mod_key || new_key || same_key)
2351     {
2352       /* A little explanation for this: we fill in the fingerprint
2353          when importing keys as it can be useful to know the
2354          fingerprint in certain keyserver-related cases (a keyserver
2355          asked for a particular name, but the key doesn't have that
2356          name).  However, in cases where we're importing more than
2357          one key at a time, we cannot know which key to fingerprint.
2358          In these cases, rather than guessing, we do not
2359          fingerprinting at all, and we must hope the user ID on the
2360          keys are useful.  Note that we need to do this for new
2361          keys, merged keys and even for unchanged keys.  This is
2362          required because for example the --auto-key-locate feature
2363          may import an already imported key and needs to know the
2364          fingerprint of the key in all cases.  */
2365       if (fpr)
2366         {
2367           /* Note that we need to compare against 0 here because
2368              COUNT gets only incremented after returning from this
2369              function.  */
2370           if (!stats->count)
2371             {
2372               xfree (*fpr);
2373               *fpr = fingerprint_from_pk (pk, NULL, fpr_len);
2374             }
2375           else if (origin != KEYORG_WKD)
2376             {
2377               xfree (*fpr);
2378               *fpr = NULL;
2379             }
2380         }
2381     }
2382 
2383   /* Now that the key is definitely incorporated into the keydb, we
2384      need to check if a designated revocation is present or if the
2385      prefs are not rational so we can warn the user. */
2386 
2387   if (mod_key)
2388     {
2389       revocation_present (ctrl, keyblock_orig);
2390       if (!from_sk && have_secret_key_with_kid (ctrl, keyid))
2391         check_prefs (ctrl, keyblock_orig);
2392     }
2393   else if (new_key)
2394     {
2395       revocation_present (ctrl, keyblock);
2396       if (!from_sk && have_secret_key_with_kid (ctrl, keyid))
2397         check_prefs (ctrl, keyblock);
2398     }
2399 
2400   release_kbnode( keyblock_orig );
2401 
2402   return err;
2403 }
2404 
2405 
2406 /* Wrapper around import_one_real to retry the import in some cases.  */
2407 static gpg_error_t
import_one(ctrl_t ctrl,kbnode_t keyblock,struct import_stats_s * stats,unsigned char ** fpr,size_t * fpr_len,unsigned int options,int from_sk,int silent,import_screener_t screener,void * screener_arg,int origin,const char * url,int * r_valid)2408 import_one (ctrl_t ctrl,
2409             kbnode_t keyblock, struct import_stats_s *stats,
2410 	    unsigned char **fpr, size_t *fpr_len, unsigned int options,
2411 	    int from_sk, int silent,
2412             import_screener_t screener, void *screener_arg,
2413             int origin, const char *url, int *r_valid)
2414 {
2415   gpg_error_t err;
2416 
2417   err = import_one_real (ctrl, keyblock, stats, fpr, fpr_len, options,
2418                          from_sk, silent, screener, screener_arg,
2419                          origin, url, r_valid);
2420   if (gpg_err_code (err) == GPG_ERR_TOO_LARGE
2421       && gpg_err_source (err) == GPG_ERR_SOURCE_KEYBOX
2422       && ((options & (IMPORT_SELF_SIGS_ONLY | IMPORT_CLEAN))
2423           != (IMPORT_SELF_SIGS_ONLY | IMPORT_CLEAN)))
2424     {
2425       /* We hit the maximum image length.  Ask the wrapper to do
2426        * everything again but this time with some extra options.  */
2427       u32 keyid[2];
2428 
2429       keyid_from_pk (keyblock->pkt->pkt.public_key, keyid);
2430       log_info ("key %s: keyblock too large, retrying with self-sigs-only\n",
2431                 keystr (keyid));
2432       options |= IMPORT_SELF_SIGS_ONLY | IMPORT_CLEAN;
2433       err = import_one_real (ctrl, keyblock, stats, fpr, fpr_len, options,
2434                              from_sk, silent, screener, screener_arg,
2435                              origin, url, r_valid);
2436     }
2437   return err;
2438 }
2439 
2440 
2441 /* Transfer all the secret keys in SEC_KEYBLOCK to the gpg-agent.  The
2442  * function prints diagnostics and returns an error code.  If BATCH is
2443  * true the secret keys are stored by gpg-agent in the transfer format
2444  * (i.e. no re-protection and aksing for passphrases). If ONLY_MARKED
2445  * is set, only those nodes with flag NODE_TRANSFER_SECKEY are
2446  * processed.  */
2447 gpg_error_t
transfer_secret_keys(ctrl_t ctrl,struct import_stats_s * stats,kbnode_t sec_keyblock,int batch,int force,int only_marked)2448 transfer_secret_keys (ctrl_t ctrl, struct import_stats_s *stats,
2449                       kbnode_t sec_keyblock, int batch, int force,
2450                       int only_marked)
2451 {
2452   gpg_error_t err = 0;
2453   void *kek = NULL;
2454   size_t keklen;
2455   kbnode_t ctx = NULL;
2456   kbnode_t node;
2457   PKT_public_key *main_pk, *pk;
2458   struct seckey_info *ski;
2459   int nskey;
2460   membuf_t mbuf;
2461   int i, j;
2462   void *format_args[2*PUBKEY_MAX_NSKEY];
2463   gcry_sexp_t skey, prot, tmpsexp;
2464   gcry_sexp_t curve = NULL;
2465   unsigned char *transferkey = NULL;
2466   size_t transferkeylen;
2467   gcry_cipher_hd_t cipherhd = NULL;
2468   unsigned char *wrappedkey = NULL;
2469   size_t wrappedkeylen;
2470   char *cache_nonce = NULL;
2471   int stub_key_skipped = 0;
2472 
2473   /* Get the current KEK.  */
2474   err = agent_keywrap_key (ctrl, 0, &kek, &keklen);
2475   if (err)
2476     {
2477       log_error ("error getting the KEK: %s\n", gpg_strerror (err));
2478       goto leave;
2479     }
2480 
2481   /* Prepare a cipher context.  */
2482   err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
2483                           GCRY_CIPHER_MODE_AESWRAP, 0);
2484   if (!err)
2485     err = gcry_cipher_setkey (cipherhd, kek, keklen);
2486   if (err)
2487     goto leave;
2488   xfree (kek);
2489   kek = NULL;
2490 
2491   /* Note: We need to use walk_kbnode so that we skip nodes which are
2492    * marked as deleted.  */
2493   main_pk = NULL;
2494   while ((node = walk_kbnode (sec_keyblock, &ctx, 0)))
2495     {
2496       if (node->pkt->pkttype != PKT_SECRET_KEY
2497           && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2498         continue;
2499       if (only_marked && !(node->flag & NODE_TRANSFER_SECKEY))
2500         continue;
2501       pk = node->pkt->pkt.public_key;
2502       if (!main_pk)
2503         main_pk = pk;
2504 
2505       /* Make sure the keyids are available.  */
2506       keyid_from_pk (pk, NULL);
2507       if (node->pkt->pkttype == PKT_SECRET_KEY)
2508         {
2509           pk->main_keyid[0] = pk->keyid[0];
2510           pk->main_keyid[1] = pk->keyid[1];
2511         }
2512       else
2513         {
2514           pk->main_keyid[0] = main_pk->keyid[0];
2515           pk->main_keyid[1] = main_pk->keyid[1];
2516         }
2517 
2518 
2519       ski = pk->seckey_info;
2520       if (!ski)
2521         BUG ();
2522 
2523       if (stats)
2524         {
2525           stats->count++;
2526           stats->secret_read++;
2527         }
2528 
2529       /* We ignore stub keys.  The way we handle them in other parts
2530          of the code is by asking the agent whether any secret key is
2531          available for a given keyblock and then concluding that we
2532          have a secret key; all secret (sub)keys of the keyblock the
2533          agent does not know of are then stub keys.  This works also
2534          for card stub keys.  The learn command or the card-status
2535          command may be used to check with the agent whether a card
2536          has been inserted and a stub key is in turn generated by the
2537          agent.  */
2538       if (ski->s2k.mode == 1001 || ski->s2k.mode == 1002)
2539         {
2540           stub_key_skipped = 1;
2541           continue;
2542         }
2543 
2544       /* Convert our internal secret key object into an S-expression.  */
2545       nskey = pubkey_get_nskey (pk->pubkey_algo);
2546       if (!nskey || nskey > PUBKEY_MAX_NSKEY)
2547         {
2548           err = gpg_error (GPG_ERR_BAD_SECKEY);
2549           log_error ("internal error: %s\n", gpg_strerror (err));
2550           goto leave;
2551         }
2552 
2553       init_membuf (&mbuf, 50);
2554       put_membuf_str (&mbuf, "(skey");
2555       if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
2556           || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
2557           || pk->pubkey_algo == PUBKEY_ALGO_ECDH)
2558         {
2559           /* The ECC case.  */
2560           char *curvestr = openpgp_oid_to_str (pk->pkey[0]);
2561           if (!curvestr)
2562             err = gpg_error_from_syserror ();
2563           else
2564             {
2565               const char *curvename = openpgp_oid_to_curve (curvestr, 1);
2566               gcry_sexp_release (curve);
2567               err = gcry_sexp_build (&curve, NULL, "(curve %s)",
2568                                      curvename?curvename:curvestr);
2569               if (!err)
2570                 {
2571                   j = 0;
2572                   /* Append the public key element Q.  */
2573                   put_membuf_str (&mbuf, " _ %m");
2574                   format_args[j++] = pk->pkey + 1;
2575 
2576                   /* Append the secret key element D.  For ECDH we
2577                      skip PKEY[2] because this holds the KEK which is
2578                      not needed by gpg-agent.  */
2579                   i = pk->pubkey_algo == PUBKEY_ALGO_ECDH? 3 : 2;
2580                   if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
2581                     put_membuf_str (&mbuf, " e %m");
2582                   else
2583                     put_membuf_str (&mbuf, " _ %m");
2584                   format_args[j++] = pk->pkey + i;
2585 
2586                   /* Simple hack to print a warning for an invalid key
2587                    * in case of cv25519.  We have only opaque MPIs here. */
2588                   if (pk->pubkey_algo == PUBKEY_ALGO_ECDH
2589                       && !strcmp (curvestr, "1.3.6.1.4.1.3029.1.5.1")
2590                       && gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_OPAQUE))
2591                     {
2592                       const unsigned char *pp;
2593                       unsigned int nn;
2594 
2595                       pp = gcry_mpi_get_opaque (pk->pkey[i], &nn);
2596                       nn = (nn+7)/8;
2597                       if (pp && nn && (pp[nn-1] & 7))
2598                         log_info ("warning: lower 3 bits of the secret key"
2599                                   " are not cleared\n");
2600                     }
2601                 }
2602               xfree (curvestr);
2603             }
2604         }
2605       else
2606         {
2607           /* Standard case for the old (non-ECC) algorithms.  */
2608           for (i=j=0; i < nskey; i++)
2609             {
2610               if (!pk->pkey[i])
2611                 continue; /* Protected keys only have NPKEY+1 elements.  */
2612 
2613               if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
2614                 put_membuf_str (&mbuf, " e %m");
2615               else
2616                 put_membuf_str (&mbuf, " _ %m");
2617               format_args[j++] = pk->pkey + i;
2618             }
2619         }
2620       put_membuf_str (&mbuf, ")");
2621       put_membuf (&mbuf, "", 1);
2622       if (err)
2623         xfree (get_membuf (&mbuf, NULL));
2624       else
2625         {
2626           char *format = get_membuf (&mbuf, NULL);
2627           if (!format)
2628             err = gpg_error_from_syserror ();
2629           else
2630             err = gcry_sexp_build_array (&skey, NULL, format, format_args);
2631           xfree (format);
2632         }
2633       if (err)
2634         {
2635           log_error ("error building skey array: %s\n", gpg_strerror (err));
2636           goto leave;
2637         }
2638 
2639       if (ski->is_protected)
2640         {
2641           char countbuf[35];
2642 
2643           /* FIXME: Support AEAD */
2644           /* Note that the IVLEN may be zero if we are working on a
2645              dummy key.  We can't express that in an S-expression and
2646              thus we send dummy data for the IV.  */
2647           snprintf (countbuf, sizeof countbuf, "%lu",
2648                     (unsigned long)ski->s2k.count);
2649           err = gcry_sexp_build
2650             (&prot, NULL,
2651              " (protection %s %s %b %d %s %b %s)\n",
2652              ski->sha1chk? "sha1":"sum",
2653              openpgp_cipher_algo_name (ski->algo),
2654              ski->ivlen? (int)ski->ivlen:1,
2655              ski->ivlen? ski->iv: (const unsigned char*)"X",
2656              ski->s2k.mode,
2657              openpgp_md_algo_name (ski->s2k.hash_algo),
2658              (int)sizeof (ski->s2k.salt), ski->s2k.salt,
2659              countbuf);
2660         }
2661       else
2662         err = gcry_sexp_build (&prot, NULL, " (protection none)\n");
2663 
2664       tmpsexp = NULL;
2665       xfree (transferkey);
2666       transferkey = NULL;
2667       if (!err)
2668         err = gcry_sexp_build (&tmpsexp, NULL,
2669                                "(openpgp-private-key\n"
2670                                " (version %d)\n"
2671                                " (algo %s)\n"
2672                                " %S%S\n"
2673                                " (csum %d)\n"
2674                                " %S)\n",
2675                                pk->version,
2676                                openpgp_pk_algo_name (pk->pubkey_algo),
2677                                curve, skey,
2678                                (int)(unsigned long)ski->csum, prot);
2679       gcry_sexp_release (skey);
2680       gcry_sexp_release (prot);
2681       if (!err)
2682         err = make_canon_sexp_pad (tmpsexp, 1, &transferkey, &transferkeylen);
2683       gcry_sexp_release (tmpsexp);
2684       if (err)
2685         {
2686           log_error ("error building transfer key: %s\n", gpg_strerror (err));
2687           goto leave;
2688         }
2689 
2690       /* Wrap the key.  */
2691       wrappedkeylen = transferkeylen + 8;
2692       xfree (wrappedkey);
2693       wrappedkey = xtrymalloc (wrappedkeylen);
2694       if (!wrappedkey)
2695         err = gpg_error_from_syserror ();
2696       else
2697         err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen,
2698                                    transferkey, transferkeylen);
2699       if (err)
2700         goto leave;
2701       xfree (transferkey);
2702       transferkey = NULL;
2703 
2704       /* Send the wrapped key to the agent.  */
2705       {
2706         char *desc = gpg_format_keydesc (ctrl, pk, FORMAT_KEYDESC_IMPORT, 1);
2707         err = agent_import_key (ctrl, desc, &cache_nonce,
2708                                 wrappedkey, wrappedkeylen, batch, force,
2709 				pk->keyid, pk->main_keyid, pk->pubkey_algo,
2710                                 pk->timestamp);
2711         xfree (desc);
2712       }
2713       if (!err)
2714         {
2715           if (opt.verbose)
2716             log_info (_("key %s: secret key imported\n"),
2717                       keystr_from_pk_with_sub (main_pk, pk));
2718           if (stats)
2719             stats->secret_imported++;
2720         }
2721       else if ( gpg_err_code (err) == GPG_ERR_EEXIST )
2722         {
2723           if (opt.verbose)
2724             log_info (_("key %s: secret key already exists\n"),
2725                       keystr_from_pk_with_sub (main_pk, pk));
2726           err = 0;
2727           if (stats)
2728             stats->secret_dups++;
2729         }
2730       else
2731         {
2732           log_error (_("key %s: error sending to agent: %s\n"),
2733                      keystr_from_pk_with_sub (main_pk, pk),
2734                      gpg_strerror (err));
2735           if (gpg_err_code (err) == GPG_ERR_CANCELED
2736               || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
2737             break; /* Don't try the other subkeys.  */
2738         }
2739     }
2740 
2741   if (!err && stub_key_skipped)
2742     /* We need to notify user how to migrate stub keys.  */
2743     err = gpg_error (GPG_ERR_NOT_PROCESSED);
2744 
2745  leave:
2746   gcry_sexp_release (curve);
2747   xfree (cache_nonce);
2748   xfree (wrappedkey);
2749   xfree (transferkey);
2750   gcry_cipher_close (cipherhd);
2751   xfree (kek);
2752   return err;
2753 }
2754 
2755 
2756 /* Walk a secret keyblock and produce a public keyblock out of it.
2757  * Returns a new node or NULL on error.  Modifies the tag field of the
2758  * nodes.  */
2759 static kbnode_t
sec_to_pub_keyblock(kbnode_t sec_keyblock)2760 sec_to_pub_keyblock (kbnode_t sec_keyblock)
2761 {
2762   kbnode_t pub_keyblock = NULL;
2763   kbnode_t ctx = NULL;
2764   kbnode_t secnode, pubnode;
2765   kbnode_t lastnode = NULL;
2766   unsigned int tag = 0;
2767 
2768   /* Set a tag to all nodes.  */
2769   for (secnode = sec_keyblock; secnode; secnode = secnode->next)
2770     secnode->tag = ++tag;
2771 
2772   /* Copy.  */
2773   while ((secnode = walk_kbnode (sec_keyblock, &ctx, 0)))
2774     {
2775       if (secnode->pkt->pkttype == PKT_SECRET_KEY
2776           || secnode->pkt->pkttype == PKT_SECRET_SUBKEY)
2777 	{
2778 	  /* Make a public key.  */
2779 	  PACKET *pkt;
2780           PKT_public_key *pk;
2781 
2782 	  pkt = xtrycalloc (1, sizeof *pkt);
2783           pk = pkt? copy_public_key (NULL, secnode->pkt->pkt.public_key): NULL;
2784           if (!pk)
2785             {
2786               xfree (pkt);
2787 	      release_kbnode (pub_keyblock);
2788               return NULL;
2789             }
2790 	  if (secnode->pkt->pkttype == PKT_SECRET_KEY)
2791 	    pkt->pkttype = PKT_PUBLIC_KEY;
2792 	  else
2793 	    pkt->pkttype = PKT_PUBLIC_SUBKEY;
2794 	  pkt->pkt.public_key = pk;
2795 
2796 	  pubnode = new_kbnode (pkt);
2797 	}
2798       else
2799 	{
2800 	  pubnode = clone_kbnode (secnode);
2801 	}
2802       pubnode->tag = secnode->tag;
2803 
2804       if (!pub_keyblock)
2805         pub_keyblock = lastnode = pubnode;
2806       else
2807         {
2808           lastnode->next = pubnode;
2809           lastnode = pubnode;
2810         }
2811     }
2812 
2813   return pub_keyblock;
2814 }
2815 
2816 
2817 /* Delete all notes in the keyblock at R_KEYBLOCK which are not in
2818  * PUB_KEYBLOCK.  Modifies the tags of both keyblock's nodes.  */
2819 static gpg_error_t
resync_sec_with_pub_keyblock(kbnode_t * r_keyblock,kbnode_t pub_keyblock,kbnode_t * r_removedsecs)2820 resync_sec_with_pub_keyblock (kbnode_t *r_keyblock, kbnode_t pub_keyblock,
2821                               kbnode_t *r_removedsecs)
2822 {
2823   kbnode_t sec_keyblock = *r_keyblock;
2824   kbnode_t node, prevnode;
2825   unsigned int *taglist;
2826   unsigned int ntaglist, n;
2827   kbnode_t attic = NULL;
2828   kbnode_t *attic_head = &attic;
2829 
2830   /* Collect all tags in an array for faster searching.  */
2831   for (ntaglist = 0, node = pub_keyblock; node; node = node->next)
2832     ntaglist++;
2833   taglist = xtrycalloc (ntaglist, sizeof *taglist);
2834   if (!taglist)
2835     return gpg_error_from_syserror ();
2836   for (ntaglist = 0, node = pub_keyblock; node; node = node->next)
2837     taglist[ntaglist++] = node->tag;
2838 
2839   /* Walks over the secret keyblock and delete all nodes which are not
2840    * in the tag list.  Those nodes have been deleted in the
2841    * pub_keyblock.  Sequential search is a bit lazy and could be
2842    * optimized by sorting and bsearch; however secret keyrings are
2843    * short and there are easier ways to DoS the import.  */
2844  again:
2845   for (prevnode=NULL, node=sec_keyblock; node; prevnode=node, node=node->next)
2846     {
2847       for (n=0; n < ntaglist; n++)
2848         if (taglist[n] == node->tag)
2849           break;
2850       if (n == ntaglist)  /* Not in public keyblock.  */
2851         {
2852           if (node->pkt->pkttype == PKT_SECRET_KEY
2853               || node->pkt->pkttype == PKT_SECRET_SUBKEY)
2854             {
2855               if (!prevnode)
2856                 sec_keyblock = node->next;
2857               else
2858                 prevnode->next = node->next;
2859               node->next = NULL;
2860               *attic_head = node;
2861               attic_head = &node->next;
2862               goto again;  /* That's lame; I know.  */
2863             }
2864           else
2865             delete_kbnode (node);
2866         }
2867     }
2868 
2869   xfree (taglist);
2870 
2871   /* Commit the as deleted marked nodes and return the possibly
2872    * modified keyblock and a list of removed secret key nodes.  */
2873   commit_kbnode (&sec_keyblock);
2874   *r_keyblock = sec_keyblock;
2875   *r_removedsecs = attic;
2876   return 0;
2877 }
2878 
2879 
2880 /* Helper for import_secret_one.  */
2881 static gpg_error_t
do_transfer(ctrl_t ctrl,kbnode_t keyblock,PKT_public_key * pk,struct import_stats_s * stats,int batch,int only_marked)2882 do_transfer (ctrl_t ctrl, kbnode_t keyblock, PKT_public_key *pk,
2883              struct import_stats_s *stats, int batch, int only_marked)
2884 
2885 {
2886   gpg_error_t err;
2887   struct import_stats_s subkey_stats = {0};
2888 
2889   err = transfer_secret_keys (ctrl, &subkey_stats, keyblock,
2890                               batch, 0, only_marked);
2891   if (gpg_err_code (err) == GPG_ERR_NOT_PROCESSED)
2892     {
2893       /* TRANSLATORS: For a smartcard, each private key on host has a
2894        * reference (stub) to a smartcard and actual private key data
2895        * is stored on the card.  A single smartcard can have up to
2896        * three private key data.  Importing private key stub is always
2897        * skipped in 2.1, and it returns GPG_ERR_NOT_PROCESSED.
2898        * Instead, user should be suggested to run 'gpg --card-status',
2899        * then, references to a card will be automatically created
2900        * again.  */
2901       log_info (_("To migrate '%s', with each smartcard, "
2902                   "run: %s\n"), "secring.gpg", "gpg --card-status");
2903       err = 0;
2904     }
2905 
2906   if (!err)
2907     {
2908       int status = 16;
2909 
2910       if (!opt.quiet)
2911         log_info (_("key %s: secret key imported\n"), keystr_from_pk (pk));
2912       if (subkey_stats.secret_imported)
2913         {
2914           status |= 1;
2915           stats->secret_imported += 1;
2916         }
2917       if (subkey_stats.secret_dups)
2918         stats->secret_dups += 1;
2919 
2920       if (is_status_enabled ())
2921         print_import_ok (pk, status);
2922     }
2923 
2924   return err;
2925 }
2926 
2927 
2928 /* If the secret keys (main or subkey) in SECKEYS have a corresponding
2929  * public key in the public key described by (FPR,FPRLEN) import these
2930  * parts.
2931  */
2932 static gpg_error_t
import_matching_seckeys(ctrl_t ctrl,kbnode_t seckeys,const byte * mainfpr,size_t mainfprlen,struct import_stats_s * stats,int batch)2933 import_matching_seckeys (ctrl_t ctrl, kbnode_t seckeys,
2934                          const byte *mainfpr, size_t mainfprlen,
2935                          struct import_stats_s *stats, int batch)
2936 {
2937   gpg_error_t err;
2938   kbnode_t pub_keyblock = NULL;
2939   kbnode_t node;
2940   struct { byte fpr[MAX_FINGERPRINT_LEN]; size_t fprlen; } *fprlist = NULL;
2941   size_t n, nfprlist;
2942   byte fpr[MAX_FINGERPRINT_LEN];
2943   size_t fprlen;
2944   PKT_public_key *pk;
2945 
2946   /* Get the entire public key block from our keystore and put all its
2947    * fingerprints into an array.  */
2948   err = get_pubkey_byfprint (ctrl, NULL, &pub_keyblock, mainfpr, mainfprlen);
2949   if (err)
2950     goto leave;
2951   log_assert (pub_keyblock && pub_keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
2952   pk = pub_keyblock->pkt->pkt.public_key;
2953 
2954   for (nfprlist = 0, node = pub_keyblock; node; node = node->next)
2955     if (node->pkt->pkttype == PKT_PUBLIC_KEY
2956         || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2957       nfprlist++;
2958   log_assert (nfprlist);
2959   fprlist = xtrycalloc (nfprlist, sizeof *fprlist);
2960   if (!fprlist)
2961     {
2962       err = gpg_error_from_syserror ();
2963       goto leave;
2964     }
2965   for (n = 0, node = pub_keyblock; node; node = node->next)
2966     if (node->pkt->pkttype == PKT_PUBLIC_KEY
2967         || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2968       {
2969         fingerprint_from_pk (node->pkt->pkt.public_key,
2970                              fprlist[n].fpr, &fprlist[n].fprlen);
2971         n++;
2972       }
2973   log_assert (n == nfprlist);
2974 
2975   /* for (n=0; n < nfprlist; n++) */
2976   /*   log_printhex (fprlist[n].fpr, fprlist[n].fprlen, "pubkey %zu:", n); */
2977 
2978   /* Mark all secret keys which have a matching public key part in
2979    * PUB_KEYBLOCK.  */
2980   for (node = seckeys; node; node = node->next)
2981     {
2982       if (node->pkt->pkttype != PKT_SECRET_KEY
2983           && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2984         continue; /* Should not happen.  */
2985       fingerprint_from_pk (node->pkt->pkt.public_key, fpr, &fprlen);
2986       node->flag &= ~NODE_TRANSFER_SECKEY;
2987       for (n=0; n < nfprlist; n++)
2988         if (fprlist[n].fprlen == fprlen && !memcmp (fprlist[n].fpr,fpr,fprlen))
2989           {
2990             node->flag |= NODE_TRANSFER_SECKEY;
2991             /* log_debug ("found matching seckey\n"); */
2992             break;
2993           }
2994     }
2995 
2996   /* Transfer all marked keys.  */
2997   err = do_transfer (ctrl, seckeys, pk, stats, batch, 1);
2998 
2999  leave:
3000   xfree (fprlist);
3001   release_kbnode (pub_keyblock);
3002   return err;
3003 }
3004 
3005 
3006 /* Import function for a single secret keyblock.  Handling is simpler
3007  * than for public keys.  We allow secret key importing only when
3008  * allow is true, this is so that a secret key can not be imported
3009  * accidentally and thereby tampering with the trust calculation.
3010  *
3011  * Ownership of KEYBLOCK is transferred to this function!
3012  *
3013  * If R_SECATTIC is not null the last special sec_keyblock is stored
3014  * there.
3015  */
3016 static gpg_error_t
import_secret_one(ctrl_t ctrl,kbnode_t keyblock,struct import_stats_s * stats,int batch,unsigned int options,int for_migration,import_screener_t screener,void * screener_arg,kbnode_t * r_secattic)3017 import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
3018                    struct import_stats_s *stats, int batch,
3019                    unsigned int options, int for_migration,
3020                    import_screener_t screener, void *screener_arg,
3021                    kbnode_t *r_secattic)
3022 {
3023   PKT_public_key *pk;
3024   struct seckey_info *ski;
3025   kbnode_t node, uidnode;
3026   u32 keyid[2];
3027   gpg_error_t err = 0;
3028   int nr_prev;
3029   kbnode_t pub_keyblock;
3030   kbnode_t attic = NULL;
3031   byte fpr[MAX_FINGERPRINT_LEN];
3032   size_t fprlen;
3033   char pkstrbuf[PUBKEY_STRING_SIZE];
3034 
3035   /* Get the key and print some info about it */
3036   node = find_kbnode (keyblock, PKT_SECRET_KEY);
3037   if (!node)
3038     BUG ();
3039 
3040   pk = node->pkt->pkt.public_key;
3041 
3042   fingerprint_from_pk (pk, fpr, &fprlen);
3043   keyid_from_pk (pk, keyid);
3044   uidnode = find_next_kbnode (keyblock, PKT_USER_ID);
3045 
3046   if (screener && screener (keyblock, screener_arg))
3047     {
3048       log_error (_("secret key %s: %s\n"), keystr_from_pk (pk),
3049                  _("rejected by import screener"));
3050       release_kbnode (keyblock);
3051       return 0;
3052     }
3053 
3054   if (opt.verbose && !for_migration)
3055     {
3056       log_info ("sec  %s/%s %s  ",
3057                 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
3058                 keystr_from_pk (pk), datestr_from_pk (pk));
3059       if (uidnode)
3060         print_utf8_buffer (log_get_stream (), uidnode->pkt->pkt.user_id->name,
3061                            uidnode->pkt->pkt.user_id->len);
3062       log_printf ("\n");
3063     }
3064   stats->secret_read++;
3065 
3066   if ((options & IMPORT_NO_SECKEY))
3067     {
3068       if (!for_migration)
3069         log_error (_("importing secret keys not allowed\n"));
3070       release_kbnode (keyblock);
3071       return 0;
3072     }
3073 
3074   if (!uidnode)
3075     {
3076       if (!for_migration)
3077         log_error( _("key %s: no user ID\n"), keystr_from_pk (pk));
3078       release_kbnode (keyblock);
3079       return 0;
3080     }
3081 
3082   ski = pk->seckey_info;
3083   if (!ski)
3084     {
3085       /* Actually an internal error.  */
3086       log_error ("key %s: secret key info missing\n", keystr_from_pk (pk));
3087       release_kbnode (keyblock);
3088       return 0;
3089     }
3090 
3091   /* A quick check to not import keys with an invalid protection
3092      cipher algorithm (only checks the primary key, though).  */
3093   if (ski->algo > 110)
3094     {
3095       if (!for_migration)
3096         log_error (_("key %s: secret key with invalid cipher %d"
3097                      " - skipped\n"), keystr_from_pk (pk), ski->algo);
3098       release_kbnode (keyblock);
3099       return 0;
3100     }
3101 
3102 #ifdef ENABLE_SELINUX_HACKS
3103   if (1)
3104     {
3105       /* We don't allow importing secret keys because that may be used
3106          to put a secret key into the keyring and the user might later
3107          be tricked into signing stuff with that key.  */
3108       log_error (_("importing secret keys not allowed\n"));
3109       release_kbnode (keyblock);
3110       return 0;
3111     }
3112 #endif
3113 
3114   clear_kbnode_flags (keyblock);
3115 
3116   nr_prev = stats->skipped_new_keys;
3117 
3118   /* Make a public key out of the key. */
3119   pub_keyblock = sec_to_pub_keyblock (keyblock);
3120   if (!pub_keyblock)
3121     {
3122       err = gpg_error_from_syserror ();
3123       log_error ("key %s: failed to create public key from secret key\n",
3124                  keystr_from_pk (pk));
3125     }
3126   else
3127     {
3128       int valid;
3129 
3130       /* Note that this outputs an IMPORT_OK status message for the
3131 	 public key block, and below we will output another one for
3132 	 the secret keys.  FIXME?  */
3133       import_one (ctrl, pub_keyblock, stats,
3134 		  NULL, NULL, options, 1, for_migration,
3135                   screener, screener_arg, 0, NULL, &valid);
3136 
3137       /* The secret keyblock may not have nodes which are deleted in
3138        * the public keyblock.  Otherwise we would import just the
3139        * secret key without having the public key.  That would be
3140        * surprising and clutters our private-keys-v1.d.  */
3141       err = resync_sec_with_pub_keyblock (&keyblock, pub_keyblock, &attic);
3142       if (err)
3143         goto leave;
3144 
3145       if (!valid)
3146         {
3147           /* If the block was not valid the primary key is left in the
3148            * original keyblock because we require that for the first
3149            * node.   Move it to ATTIC.  */
3150           if (keyblock && keyblock->pkt->pkttype == PKT_SECRET_KEY)
3151             {
3152               node = keyblock;
3153               keyblock = node->next;
3154               node->next = NULL;
3155               if (attic)
3156                 {
3157                   node->next = attic;
3158                   attic = node;
3159                 }
3160               else
3161                 attic = node;
3162             }
3163 
3164           /* Try to import the secret key iff we have a public key.  */
3165           if (attic && !(opt.dry_run || (options & IMPORT_DRY_RUN)))
3166             err = import_matching_seckeys (ctrl, attic, fpr, fprlen,
3167                                            stats, batch);
3168           else
3169             err = gpg_error (GPG_ERR_NO_SECKEY);
3170           goto leave;
3171         }
3172 
3173       /* log_debug ("attic is:\n"); */
3174       /* dump_kbnode (attic); */
3175 
3176       /* Proceed with the valid parts of PUBKEYBLOCK. */
3177 
3178       /* At least we cancel the secret key import when the public key
3179 	 import was skipped due to MERGE_ONLY option and a new
3180 	 key.  */
3181       if (!(opt.dry_run || (options & IMPORT_DRY_RUN))
3182           && stats->skipped_new_keys <= nr_prev)
3183 	{
3184           /* Read the keyblock again to get the effects of a merge for
3185            * the public key.  */
3186           err = get_pubkey_byfprint (ctrl, NULL, &node, fpr, fprlen);
3187           if (err || !node)
3188             log_error ("key %s: failed to re-lookup public key: %s\n",
3189                        keystr_from_pk (pk), gpg_strerror (err));
3190           else
3191             {
3192               err = do_transfer (ctrl, keyblock, pk, stats, batch, 0);
3193               if (!err)
3194                 check_prefs (ctrl, node);
3195               release_kbnode (node);
3196 
3197               if (!err && attic)
3198                 {
3199                   /* Try to import invalid subkeys.  This can be the
3200                    * case if the primary secret key was imported due
3201                    * to --allow-non-selfsigned-uid.  */
3202                   err = import_matching_seckeys (ctrl, attic, fpr, fprlen,
3203                                                  stats, batch);
3204                 }
3205 
3206             }
3207         }
3208     }
3209 
3210  leave:
3211   release_kbnode (keyblock);
3212   release_kbnode (pub_keyblock);
3213   if (r_secattic)
3214     *r_secattic = attic;
3215   else
3216     release_kbnode (attic);
3217   return err;
3218 }
3219 
3220 
3221 
3222 /* Return the recocation reason from signature SIG.  If no revocation
3223  * reason is available 0 is returned, in other cases the reason
3224  * (0..255).  If R_REASON is not NULL a malloced textual
3225  * representation of the code is stored there.  If R_COMMENT is not
3226  * NULL the comment from the reason is stored there and its length at
3227  * R_COMMENTLEN.  Note that the value at R_COMMENT is not filtered but
3228  * user supplied data in UTF8; thus it needs to be escaped for display
3229  * purposes.  Both return values are either NULL or a malloced
3230  * string/buffer.  */
3231 int
get_revocation_reason(PKT_signature * sig,char ** r_reason,char ** r_comment,size_t * r_commentlen)3232 get_revocation_reason (PKT_signature *sig, char **r_reason,
3233                        char **r_comment, size_t *r_commentlen)
3234 {
3235   int reason_seq = 0;
3236   size_t reason_n;
3237   const byte *reason_p;
3238   char reason_code_buf[20];
3239   const char *reason_text = NULL;
3240   int reason_code = 0;
3241 
3242   if (r_reason)
3243     *r_reason = NULL;
3244   if (r_comment)
3245     *r_comment = NULL;
3246 
3247   /* Skip over empty reason packets.  */
3248   while ((reason_p = enum_sig_subpkt (sig, 1, SIGSUBPKT_REVOC_REASON,
3249                                       &reason_n, &reason_seq, NULL))
3250          && !reason_n)
3251     ;
3252   if (reason_p)
3253     {
3254       reason_code = *reason_p;
3255       reason_n--; reason_p++;
3256       switch (reason_code)
3257         {
3258         case 0x00: reason_text = _("No reason specified"); break;
3259         case 0x01: reason_text = _("Key is superseded");   break;
3260         case 0x02: reason_text = _("Key has been compromised"); break;
3261         case 0x03: reason_text = _("Key is no longer used"); break;
3262         case 0x20: reason_text = _("User ID is no longer valid"); break;
3263         default:
3264           snprintf (reason_code_buf, sizeof reason_code_buf,
3265                     "code=%02x", reason_code);
3266           reason_text = reason_code_buf;
3267           break;
3268         }
3269 
3270       if (r_reason)
3271         *r_reason = xstrdup (reason_text);
3272 
3273       if (r_comment && reason_n)
3274         {
3275           *r_comment = xmalloc (reason_n);
3276           memcpy (*r_comment, reason_p, reason_n);
3277           *r_commentlen = reason_n;
3278         }
3279     }
3280 
3281   return reason_code;
3282 }
3283 
3284 
3285 /* List the recocation signature as a "rvs" record.  SIGRC shows the
3286  * character from the signature verification or 0 if no public key was
3287  * found.  */
3288 static void
list_standalone_revocation(ctrl_t ctrl,PKT_signature * sig,int sigrc)3289 list_standalone_revocation (ctrl_t ctrl, PKT_signature *sig, int sigrc)
3290 {
3291   char *siguid = NULL;
3292   size_t siguidlen = 0;
3293   char *issuer_fpr = NULL;
3294   int reason_code = 0;
3295   char *reason_text = NULL;
3296   char *reason_comment = NULL;
3297   size_t reason_commentlen;
3298 
3299   if (sigrc != '%' && sigrc != '?' && !opt.fast_list_mode)
3300     {
3301       int nouid;
3302       siguid = get_user_id (ctrl, sig->keyid, &siguidlen, &nouid);
3303       if (nouid)
3304         sigrc = '?';
3305     }
3306 
3307   reason_code = get_revocation_reason (sig, &reason_text,
3308                                        &reason_comment, &reason_commentlen);
3309 
3310   if (opt.with_colons)
3311     {
3312       es_fputs ("rvs:", es_stdout);
3313       if (sigrc)
3314         es_putc (sigrc, es_stdout);
3315       es_fprintf (es_stdout, "::%d:%08lX%08lX:%s:%s:::",
3316                   sig->pubkey_algo,
3317                   (ulong) sig->keyid[0], (ulong) sig->keyid[1],
3318                   colon_datestr_from_sig (sig),
3319                   colon_expirestr_from_sig (sig));
3320 
3321       if (siguid)
3322         es_write_sanitized (es_stdout, siguid, siguidlen, ":", NULL);
3323 
3324       es_fprintf (es_stdout, ":%02x%c", sig->sig_class,
3325                   sig->flags.exportable ? 'x' : 'l');
3326       if (reason_text)
3327         es_fprintf (es_stdout, ",%02x", reason_code);
3328       es_fputs ("::", es_stdout);
3329 
3330       if ((issuer_fpr = issuer_fpr_string (sig)))
3331         es_fputs (issuer_fpr, es_stdout);
3332 
3333       es_fprintf (es_stdout, ":::%d:", sig->digest_algo);
3334 
3335       if (reason_comment)
3336         {
3337           es_fputs ("::::", es_stdout);
3338           es_write_sanitized (es_stdout, reason_comment, reason_commentlen,
3339                               ":", NULL);
3340           es_putc (':', es_stdout);
3341         }
3342       es_putc ('\n', es_stdout);
3343 
3344       if (opt.show_subpackets)
3345         print_subpackets_colon (sig);
3346     }
3347   else /* Human readable. */
3348     {
3349       es_fputs ("rvs", es_stdout);
3350       es_fprintf (es_stdout, "%c%c %c%c%c%c%c%c %s %s",
3351 		  sigrc, (sig->sig_class - 0x10 > 0 &&
3352 			  sig->sig_class - 0x10 <
3353 			  4) ? '0' + sig->sig_class - 0x10 : ' ',
3354 		  sig->flags.exportable ? ' ' : 'L',
3355 		  sig->flags.revocable ? ' ' : 'R',
3356 		  sig->flags.policy_url ? 'P' : ' ',
3357 		  sig->flags.notation ? 'N' : ' ',
3358 		  sig->flags.expired ? 'X' : ' ',
3359 		  (sig->trust_depth > 9) ? 'T' : (sig->trust_depth >
3360 						  0) ? '0' +
3361 		  sig->trust_depth : ' ', keystr (sig->keyid),
3362 		  datestr_from_sig (sig));
3363       if (siguid)
3364         {
3365           es_fprintf (es_stdout, "  ");
3366           print_utf8_buffer (es_stdout, siguid, siguidlen);
3367         }
3368       es_putc ('\n', es_stdout);
3369 
3370       if (sig->flags.policy_url
3371           && (opt.list_options & LIST_SHOW_POLICY_URLS))
3372         show_policy_url (sig, 3, 0);
3373 
3374       if (sig->flags.notation && (opt.list_options & LIST_SHOW_NOTATIONS))
3375         show_notation (sig, 3, 0,
3376                        ((opt.list_options & LIST_SHOW_STD_NOTATIONS) ? 1 : 0)
3377                        +
3378                        ((opt.list_options & LIST_SHOW_USER_NOTATIONS) ? 2 : 0));
3379 
3380       if (sig->flags.pref_ks
3381           && (opt.list_options & LIST_SHOW_KEYSERVER_URLS))
3382         show_keyserver_url (sig, 3, 0);
3383 
3384       if (reason_text)
3385         {
3386           es_fprintf (es_stdout, "      %s%s\n",
3387                       _("reason for revocation: "), reason_text);
3388           if (reason_comment)
3389             {
3390               const byte *s, *s_lf;
3391               size_t n, n_lf;
3392 
3393               s = reason_comment;
3394               n = reason_commentlen;
3395               s_lf = NULL;
3396               do
3397                 {
3398                   /* We don't want any empty lines, so we skip them.  */
3399                   for (;n && *s == '\n'; s++, n--)
3400                     ;
3401                   if (n)
3402                     {
3403                       s_lf = memchr (s, '\n', n);
3404                       n_lf = s_lf? s_lf - s : n;
3405                       es_fprintf (es_stdout, "         %s",
3406                                   _("revocation comment: "));
3407                       es_write_sanitized (es_stdout, s, n_lf, NULL, NULL);
3408                       es_putc ('\n', es_stdout);
3409                       s += n_lf; n -= n_lf;
3410                     }
3411                 } while (s_lf);
3412             }
3413         }
3414     }
3415 
3416   es_fflush (es_stdout);
3417 
3418   xfree (reason_text);
3419   xfree (reason_comment);
3420   xfree (siguid);
3421   xfree (issuer_fpr);
3422 }
3423 
3424 
3425 /****************
3426  * Import a revocation certificate; this is a single signature packet.
3427  */
3428 static int
import_revoke_cert(ctrl_t ctrl,kbnode_t node,unsigned int options,struct import_stats_s * stats)3429 import_revoke_cert (ctrl_t ctrl, kbnode_t node, unsigned int options,
3430                     struct import_stats_s *stats)
3431 {
3432   PKT_public_key *pk = NULL;
3433   kbnode_t onode;
3434   kbnode_t keyblock = NULL;
3435   KEYDB_HANDLE hd = NULL;
3436   u32 keyid[2];
3437   int rc = 0;
3438   int sigrc = 0;
3439   int silent;
3440 
3441   /* No error output for --show-keys.  */
3442   silent = (options & (IMPORT_SHOW | IMPORT_DRY_RUN));
3443 
3444   log_assert (!node->next );
3445   log_assert (node->pkt->pkttype == PKT_SIGNATURE );
3446   log_assert (IS_KEY_REV (node->pkt->pkt.signature));
3447 
3448   keyid[0] = node->pkt->pkt.signature->keyid[0];
3449   keyid[1] = node->pkt->pkt.signature->keyid[1];
3450 
3451   pk = xmalloc_clear( sizeof *pk );
3452   rc = get_pubkey (ctrl, pk, keyid );
3453   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY )
3454     {
3455       if (!silent)
3456         log_error (_("key %s: no public key -"
3457                      " can't apply revocation certificate\n"), keystr(keyid));
3458       rc = 0;
3459       goto leave;
3460     }
3461   else if (rc )
3462     {
3463       log_error (_("key %s: public key not found: %s\n"),
3464                  keystr(keyid), gpg_strerror (rc));
3465       goto leave;
3466     }
3467 
3468   /* Read the original keyblock. */
3469   hd = keydb_new (ctrl);
3470   if (!hd)
3471     {
3472       rc = gpg_error_from_syserror ();
3473       goto leave;
3474     }
3475 
3476   {
3477     byte afp[MAX_FINGERPRINT_LEN];
3478     size_t an;
3479 
3480     fingerprint_from_pk (pk, afp, &an);
3481     rc = keydb_search_fpr (hd, afp, an);
3482   }
3483   if (rc)
3484     {
3485       log_error (_("key %s: can't locate original keyblock: %s\n"),
3486                  keystr(keyid), gpg_strerror (rc));
3487       goto leave;
3488     }
3489   rc = keydb_get_keyblock (hd, &keyblock );
3490   if (rc)
3491     {
3492       log_error (_("key %s: can't read original keyblock: %s\n"),
3493                  keystr(keyid), gpg_strerror (rc));
3494       goto leave;
3495     }
3496 
3497   /* it is okay, that node is not in keyblock because
3498    * check_key_signature works fine for sig_class 0x20 (KEY_REV) in
3499    * this special case.  SIGRC is only used for IMPORT_SHOW.  */
3500   rc = check_key_signature (ctrl, keyblock, node, NULL);
3501   switch (gpg_err_code (rc))
3502     {
3503     case 0:                       sigrc = '!'; break;
3504     case GPG_ERR_BAD_SIGNATURE:   sigrc = '-'; break;
3505     case GPG_ERR_NO_PUBKEY:       sigrc = '?'; break;
3506     case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break;
3507     default:                      sigrc = '%'; break;
3508     }
3509   if (rc )
3510     {
3511       if (!silent)
3512         log_error (_("key %s: invalid revocation certificate"
3513                      ": %s - rejected\n"), keystr(keyid), gpg_strerror (rc));
3514       goto leave;
3515     }
3516 
3517   /* check whether we already have this */
3518   for(onode=keyblock->next; onode; onode=onode->next ) {
3519     if (onode->pkt->pkttype == PKT_USER_ID )
3520       break;
3521     else if (onode->pkt->pkttype == PKT_SIGNATURE
3522              && !cmp_signatures(node->pkt->pkt.signature,
3523                                 onode->pkt->pkt.signature))
3524       {
3525         rc = 0;
3526         goto leave; /* yes, we already know about it */
3527       }
3528   }
3529 
3530   /* insert it */
3531   insert_kbnode( keyblock, clone_kbnode(node), 0 );
3532 
3533   /* and write the keyblock back unless in dry run mode.  */
3534   if (!(opt.dry_run || (options & IMPORT_DRY_RUN)))
3535     {
3536       rc = keydb_update_keyblock (ctrl, hd, keyblock );
3537       if (rc)
3538         log_error (_("error writing keyring '%s': %s\n"),
3539                    keydb_get_resource_name (hd), gpg_strerror (rc) );
3540       keydb_release (hd);
3541       hd = NULL;
3542 
3543       /* we are ready */
3544       if (!opt.quiet )
3545         {
3546           char *p=get_user_id_native (ctrl, keyid);
3547           log_info( _("key %s: \"%s\" revocation certificate imported\n"),
3548                     keystr(keyid),p);
3549           xfree(p);
3550         }
3551 
3552       /* If the key we just revoked was ultimately trusted, remove its
3553        * ultimate trust.  This doesn't stop the user from putting the
3554        * ultimate trust back, but is a reasonable solution for now. */
3555       if (get_ownertrust (ctrl, pk) == TRUST_ULTIMATE)
3556         clear_ownertrusts (ctrl, pk);
3557 
3558       revalidation_mark (ctrl);
3559     }
3560   stats->n_revoc++;
3561 
3562  leave:
3563   if ((options & IMPORT_SHOW))
3564     list_standalone_revocation (ctrl, node->pkt->pkt.signature, sigrc);
3565 
3566   keydb_release (hd);
3567   release_kbnode( keyblock );
3568   free_public_key( pk );
3569   return rc;
3570 }
3571 
3572 
3573 /* Loop over the KEYBLOCK and check all self signatures.  KEYID is the
3574  * keyid of the primary key for reporting purposes. On return the
3575  * following bits in the node flags are set:
3576  *
3577  * - NODE_GOOD_SELFSIG  :: User ID or subkey has a self-signature
3578  * - NODE_BAD_SELFSIG   :: Used ID or subkey has an invalid self-signature
3579  * - NODE_DELETION_MARK :: This node shall be deleted
3580  *
3581  * NON_SELF is set to true if there are any sigs other than self-sigs
3582  * in this keyblock.
3583  *
3584  * Returns 0 on success or -1 (but not an error code) if the keyblock
3585  * is invalid.
3586  */
3587 static int
chk_self_sigs(ctrl_t ctrl,kbnode_t keyblock,u32 * keyid,int * non_self)3588 chk_self_sigs (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid, int *non_self)
3589 {
3590   kbnode_t knode = NULL;   /* The node of the current subkey.  */
3591   PKT_public_key *subpk = NULL; /* and its packet. */
3592   kbnode_t bsnode = NULL;  /* Subkey binding signature node.  */
3593   u32 bsdate = 0;          /* Timestamp of that node.   */
3594   kbnode_t rsnode = NULL;  /* Subkey recocation signature node.  */
3595   u32 rsdate = 0;          /* Timestamp of that node.  */
3596   PKT_signature *sig;
3597   int rc;
3598   kbnode_t n;
3599 
3600   for (n=keyblock; (n = find_next_kbnode (n, 0)); )
3601     {
3602       if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3603 	{
3604 	  knode = n;
3605           subpk = knode->pkt->pkt.public_key;
3606 	  bsdate = 0;
3607 	  rsdate = 0;
3608 	  bsnode = NULL;
3609 	  rsnode = NULL;
3610 	  continue;
3611 	}
3612 
3613       if ( n->pkt->pkttype != PKT_SIGNATURE )
3614         continue;
3615 
3616       sig = n->pkt->pkt.signature;
3617       if ( keyid[0] != sig->keyid[0] || keyid[1] != sig->keyid[1] )
3618         {
3619           *non_self = 1;
3620           continue;
3621         }
3622 
3623       /* This just caches the sigs for later use.  That way we
3624          import a fully-cached key which speeds things up. */
3625       if (!opt.no_sig_cache)
3626         check_key_signature (ctrl, keyblock, n, NULL);
3627 
3628       if ( IS_UID_SIG(sig) || IS_UID_REV(sig) )
3629         {
3630           kbnode_t unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
3631           if ( !unode )
3632             {
3633               log_error( _("key %s: no user ID for signature\n"),
3634                          keystr(keyid));
3635               return -1;  /* The complete keyblock is invalid.  */
3636             }
3637 
3638           /* If it hasn't been marked valid yet, keep trying.  */
3639           if (!(unode->flag & NODE_GOOD_SELFSIG))
3640             {
3641               rc = check_key_signature (ctrl, keyblock, n, NULL);
3642               if ( rc )
3643                 {
3644                   if ( opt.verbose )
3645                     {
3646                       char *p = utf8_to_native
3647                         (unode->pkt->pkt.user_id->name,
3648                          strlen (unode->pkt->pkt.user_id->name),0);
3649                       log_info (gpg_err_code(rc) == GPG_ERR_PUBKEY_ALGO ?
3650                                 _("key %s: unsupported public key "
3651                                   "algorithm on user ID \"%s\"\n"):
3652                                 _("key %s: invalid self-signature "
3653                                   "on user ID \"%s\"\n"),
3654                                 keystr (keyid),p);
3655                       xfree (p);
3656                     }
3657                 }
3658               else
3659                 unode->flag |= NODE_GOOD_SELFSIG;
3660             }
3661         }
3662       else if (IS_KEY_SIG (sig))
3663         {
3664           rc = check_key_signature (ctrl, keyblock, n, NULL);
3665           if ( rc )
3666             {
3667               if (opt.verbose)
3668                 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
3669                           _("key %s: unsupported public key algorithm\n"):
3670                           _("key %s: invalid direct key signature\n"),
3671                           keystr (keyid));
3672               n->flag |= NODE_DELETION_MARK;
3673             }
3674         }
3675       else if ( IS_SUBKEY_SIG (sig) )
3676         {
3677           /* Note that this works based solely on the timestamps like
3678              the rest of gpg.  If the standard gets revocation
3679              targets, this may need to be revised.  */
3680 
3681           if ( !knode )
3682             {
3683               if (opt.verbose)
3684                 log_info (_("key %s: no subkey for key binding\n"),
3685                           keystr (keyid));
3686               n->flag |= NODE_DELETION_MARK;
3687             }
3688           else
3689             {
3690               rc = check_key_signature (ctrl, keyblock, n, NULL);
3691               if ( rc )
3692                 {
3693                   if (opt.verbose)
3694                     {
3695                       keyid_from_pk (subpk, NULL);
3696                       log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
3697                                 _("key %s: unsupported public key"
3698                                   " algorithm\n"):
3699                                 _("key %s: invalid subkey binding\n"),
3700                                 keystr_with_sub (keyid, subpk->keyid));
3701                     }
3702                   n->flag |= NODE_DELETION_MARK;
3703                 }
3704               else
3705                 {
3706                   /* It's valid, so is it newer? */
3707                   if (sig->timestamp >= bsdate)
3708                     {
3709                       knode->flag |= NODE_GOOD_SELFSIG; /* Subkey is valid.  */
3710                       if (bsnode)
3711                         {
3712                           /* Delete the last binding sig since this
3713                              one is newer */
3714                           bsnode->flag |= NODE_DELETION_MARK;
3715                           if (opt.verbose)
3716                             {
3717                               keyid_from_pk (subpk, NULL);
3718                               log_info (_("key %s: removed multiple subkey"
3719                                           " binding\n"),
3720                                         keystr_with_sub (keyid, subpk->keyid));
3721                             }
3722                         }
3723 
3724                       bsnode = n;
3725                       bsdate = sig->timestamp;
3726                     }
3727                   else
3728                     n->flag |= NODE_DELETION_MARK; /* older */
3729                 }
3730             }
3731         }
3732       else if ( IS_SUBKEY_REV (sig) )
3733         {
3734           /* We don't actually mark the subkey as revoked right now,
3735              so just check that the revocation sig is the most recent
3736              valid one.  Note that we don't care if the binding sig is
3737              newer than the revocation sig.  See the comment in
3738              getkey.c:merge_selfsigs_subkey for more.  */
3739           if ( !knode )
3740             {
3741               if (opt.verbose)
3742                 log_info (_("key %s: no subkey for key revocation\n"),
3743                           keystr(keyid));
3744               n->flag |= NODE_DELETION_MARK;
3745             }
3746           else
3747             {
3748               rc = check_key_signature (ctrl, keyblock, n, NULL);
3749               if ( rc )
3750                 {
3751                   if(opt.verbose)
3752                     log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
3753                               _("key %s: unsupported public"
3754                                 " key algorithm\n"):
3755                               _("key %s: invalid subkey revocation\n"),
3756                               keystr(keyid));
3757                   n->flag |= NODE_DELETION_MARK;
3758                 }
3759               else
3760                 {
3761                   /* It's valid, so is it newer? */
3762                   if (sig->timestamp >= rsdate)
3763                     {
3764                       if (rsnode)
3765                         {
3766                           /* Delete the last revocation sig since
3767                              this one is newer.  */
3768                           rsnode->flag |= NODE_DELETION_MARK;
3769                           if (opt.verbose)
3770                             log_info (_("key %s: removed multiple subkey"
3771                                         " revocation\n"),keystr(keyid));
3772                         }
3773 
3774                       rsnode = n;
3775                       rsdate = sig->timestamp;
3776                     }
3777                   else
3778                     n->flag |= NODE_DELETION_MARK; /* older */
3779                 }
3780             }
3781         }
3782     }
3783 
3784   return 0;
3785 }
3786 
3787 
3788 /* Delete all parts which are invalid and those signatures whose
3789  * public key algorithm is not available in this implementation; but
3790  * consider RSA as valid, because parse/build_packets knows about it.
3791  *
3792  * Returns: True if at least one valid user-id is left over.
3793  */
3794 static int
delete_inv_parts(ctrl_t ctrl,kbnode_t keyblock,u32 * keyid,unsigned int options)3795 delete_inv_parts (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid,
3796                   unsigned int options)
3797 {
3798   kbnode_t node;
3799   int nvalid=0, uid_seen=0, subkey_seen=0;
3800   PKT_public_key *pk;
3801 
3802   for (node=keyblock->next; node; node = node->next )
3803     {
3804       if (node->pkt->pkttype == PKT_USER_ID)
3805         {
3806           uid_seen = 1;
3807           if ((node->flag & NODE_BAD_SELFSIG)
3808               || !(node->flag & NODE_GOOD_SELFSIG))
3809             {
3810               if (opt.verbose )
3811                 {
3812                   char *p=utf8_to_native(node->pkt->pkt.user_id->name,
3813                                          node->pkt->pkt.user_id->len,0);
3814                   log_info( _("key %s: skipped user ID \"%s\"\n"),
3815                             keystr(keyid),p);
3816                   xfree(p);
3817                 }
3818               delete_kbnode( node ); /* the user-id */
3819               /* and all following packets up to the next user-id */
3820               while (node->next
3821                      && node->next->pkt->pkttype != PKT_USER_ID
3822                      && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
3823                      && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
3824                 delete_kbnode( node->next );
3825                 node = node->next;
3826               }
3827 	    }
3828           else
3829             nvalid++;
3830 	}
3831       else if (   node->pkt->pkttype == PKT_PUBLIC_SUBKEY
3832                || node->pkt->pkttype == PKT_SECRET_SUBKEY )
3833         {
3834           if ((node->flag & NODE_BAD_SELFSIG)
3835               || !(node->flag & NODE_GOOD_SELFSIG))
3836             {
3837               if (opt.verbose )
3838                 {
3839                   pk = node->pkt->pkt.public_key;
3840                   keyid_from_pk (pk, NULL);
3841                   log_info (_("key %s: skipped subkey\n"),
3842                             keystr_with_sub (keyid, pk->keyid));
3843                 }
3844 
3845               delete_kbnode( node ); /* the subkey */
3846               /* and all following signature packets */
3847               while (node->next
3848                      && node->next->pkt->pkttype == PKT_SIGNATURE ) {
3849                 delete_kbnode( node->next );
3850                 node = node->next;
3851               }
3852 	    }
3853           else
3854             subkey_seen = 1;
3855 	}
3856       else if (node->pkt->pkttype == PKT_SIGNATURE
3857                && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
3858                && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
3859         {
3860           delete_kbnode( node ); /* build_packet() can't handle this */
3861         }
3862       else if (node->pkt->pkttype == PKT_SIGNATURE
3863                && !node->pkt->pkt.signature->flags.exportable
3864                && !(options&IMPORT_LOCAL_SIGS)
3865                && !have_secret_key_with_kid (ctrl,
3866                                              node->pkt->pkt.signature->keyid))
3867         {
3868           /* here we violate the rfc a bit by still allowing
3869            * to import non-exportable signature when we have the
3870            * the secret key used to create this signature - it
3871            * seems that this makes sense */
3872           if(opt.verbose)
3873             log_info( _("key %s: non exportable signature"
3874                         " (class 0x%02X) - skipped\n"),
3875                       keystr(keyid), node->pkt->pkt.signature->sig_class );
3876           delete_kbnode( node );
3877         }
3878       else if (node->pkt->pkttype == PKT_SIGNATURE
3879                && IS_KEY_REV (node->pkt->pkt.signature))
3880         {
3881           if (uid_seen )
3882             {
3883               if(opt.verbose)
3884                 log_info( _("key %s: revocation certificate"
3885                             " at wrong place - skipped\n"),keystr(keyid));
3886               delete_kbnode( node );
3887             }
3888           else
3889             {
3890 	      /* If the revocation cert is from a different key than
3891                  the one we're working on don't check it - it's
3892                  probably from a revocation key and won't be
3893                  verifiable with this key anyway. */
3894 
3895 	      if(node->pkt->pkt.signature->keyid[0]==keyid[0]
3896                  && node->pkt->pkt.signature->keyid[1]==keyid[1])
3897 		{
3898 		  int rc = check_key_signature (ctrl, keyblock, node, NULL);
3899 		  if (rc )
3900 		    {
3901 		      if(opt.verbose)
3902 			log_info( _("key %s: invalid revocation"
3903 				    " certificate: %s - skipped\n"),
3904 				  keystr(keyid), gpg_strerror (rc));
3905 		      delete_kbnode( node );
3906 		    }
3907 		}
3908 	    }
3909 	}
3910       else if (node->pkt->pkttype == PKT_SIGNATURE
3911                && (IS_SUBKEY_SIG (node->pkt->pkt.signature)
3912                    || IS_SUBKEY_REV (node->pkt->pkt.signature))
3913                && !subkey_seen )
3914         {
3915           if(opt.verbose)
3916             log_info( _("key %s: subkey signature"
3917                         " in wrong place - skipped\n"), keystr(keyid));
3918           delete_kbnode( node );
3919         }
3920       else if (node->pkt->pkttype == PKT_SIGNATURE
3921                && !IS_CERT(node->pkt->pkt.signature))
3922         {
3923           if(opt.verbose)
3924             log_info(_("key %s: unexpected signature class (0x%02X) -"
3925                        " skipped\n"),keystr(keyid),
3926                      node->pkt->pkt.signature->sig_class);
3927           delete_kbnode(node);
3928 	  }
3929       else if ((node->flag & NODE_DELETION_MARK))
3930         delete_kbnode( node );
3931     }
3932 
3933   /* note: because keyblock is the public key, it is never marked
3934    * for deletion and so keyblock cannot change */
3935   commit_kbnode( &keyblock );
3936   return nvalid;
3937 }
3938 
3939 /* This function returns true if any UID is left in the keyring.  */
3940 static int
any_uid_left(kbnode_t keyblock)3941 any_uid_left (kbnode_t keyblock)
3942 {
3943   kbnode_t node;
3944 
3945   for (node=keyblock->next; node; node = node->next)
3946     if (node->pkt->pkttype == PKT_USER_ID)
3947       return 1;
3948   return 0;
3949 }
3950 
3951 
3952 /* Delete all non-self-sigs from KEYBLOCK.
3953  * Returns: True if the keyblock has changed.  */
3954 static void
remove_all_non_self_sigs(kbnode_t * keyblock,u32 * keyid)3955 remove_all_non_self_sigs (kbnode_t *keyblock, u32 *keyid)
3956 {
3957   kbnode_t node;
3958   unsigned int dropped = 0;
3959 
3960   for (node = *keyblock; node; node = node->next)
3961     {
3962       if (is_deleted_kbnode (node))
3963 	continue;
3964 
3965       if (node->pkt->pkttype != PKT_SIGNATURE)
3966 	continue;
3967 
3968       if (node->pkt->pkt.signature->keyid[0] == keyid[0]
3969           && node->pkt->pkt.signature->keyid[1] == keyid[1])
3970         continue;
3971       delete_kbnode (node);
3972       dropped++;
3973     }
3974 
3975   if (dropped)
3976     commit_kbnode (keyblock);
3977 
3978   if (dropped && opt.verbose)
3979     log_info ("key %s: number of dropped non-self-signatures: %u\n",
3980               keystr (keyid), dropped);
3981 }
3982 
3983 
3984 /*
3985  * It may happen that the imported keyblock has duplicated user IDs.
3986  * We check this here and collapse those user IDs together with their
3987  * sigs into one.
3988  * Returns: True if the keyblock has changed.
3989  */
3990 int
collapse_uids(kbnode_t * keyblock)3991 collapse_uids (kbnode_t *keyblock)
3992 {
3993   kbnode_t uid1;
3994   int any=0;
3995 
3996   for(uid1=*keyblock;uid1;uid1=uid1->next)
3997     {
3998       kbnode_t uid2;
3999 
4000       if(is_deleted_kbnode(uid1))
4001 	continue;
4002 
4003       if(uid1->pkt->pkttype!=PKT_USER_ID)
4004 	continue;
4005 
4006       for(uid2=uid1->next;uid2;uid2=uid2->next)
4007 	{
4008 	  if(is_deleted_kbnode(uid2))
4009 	    continue;
4010 
4011 	  if(uid2->pkt->pkttype!=PKT_USER_ID)
4012 	    continue;
4013 
4014 	  if(cmp_user_ids(uid1->pkt->pkt.user_id,
4015 			  uid2->pkt->pkt.user_id)==0)
4016 	    {
4017 	      /* We have a duplicated uid */
4018 	      kbnode_t sig1,last;
4019 
4020 	      any=1;
4021 
4022 	      /* Now take uid2's signatures, and attach them to
4023 		 uid1 */
4024 	      for(last=uid2;last->next;last=last->next)
4025 		{
4026 		  if(is_deleted_kbnode(last))
4027 		    continue;
4028 
4029 		  if(last->next->pkt->pkttype==PKT_USER_ID
4030 		     || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
4031 		     || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
4032 		    break;
4033 		}
4034 
4035 	      /* Snip out uid2 */
4036 	      (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
4037 
4038 	      /* Now put uid2 in place as part of uid1 */
4039 	      last->next=uid1->next;
4040 	      uid1->next=uid2;
4041 	      delete_kbnode(uid2);
4042 
4043 	      /* Now dedupe uid1 */
4044 	      for(sig1=uid1->next;sig1;sig1=sig1->next)
4045 		{
4046 		  kbnode_t sig2;
4047 
4048 		  if(is_deleted_kbnode(sig1))
4049 		    continue;
4050 
4051 		  if(sig1->pkt->pkttype==PKT_USER_ID
4052 		     || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
4053 		     || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
4054 		    break;
4055 
4056 		  if(sig1->pkt->pkttype!=PKT_SIGNATURE)
4057 		    continue;
4058 
4059 		  for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
4060 		    {
4061 		      if(is_deleted_kbnode(sig2))
4062 			continue;
4063 
4064 		      if(sig2->pkt->pkttype==PKT_USER_ID
4065 			 || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
4066 			 || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
4067 			break;
4068 
4069 		      if(sig2->pkt->pkttype!=PKT_SIGNATURE)
4070 			continue;
4071 
4072 		      if(cmp_signatures(sig1->pkt->pkt.signature,
4073 					sig2->pkt->pkt.signature)==0)
4074 			{
4075 			  /* We have a match, so delete the second
4076 			     signature */
4077 			  delete_kbnode(sig2);
4078 			  sig2=last;
4079 			}
4080 		    }
4081 		}
4082 	    }
4083 	}
4084     }
4085 
4086   commit_kbnode(keyblock);
4087 
4088   if(any && !opt.quiet)
4089     {
4090       const char *key="???";
4091 
4092       if ((uid1 = find_kbnode (*keyblock, PKT_PUBLIC_KEY)) )
4093 	key = keystr_from_pk (uid1->pkt->pkt.public_key);
4094       else if ((uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY)) )
4095 	key = keystr_from_pk (uid1->pkt->pkt.public_key);
4096 
4097       log_info (_("key %s: duplicated user ID detected - merged\n"), key);
4098     }
4099 
4100   return any;
4101 }
4102 
4103 
4104 /*
4105  * It may happen that the imported keyblock has duplicated subkeys.
4106  * We check this here and collapse those subkeys along with their
4107  * binding self-signatures.
4108  * Returns: True if the keyblock has changed.
4109  */
4110 int
collapse_subkeys(kbnode_t * keyblock)4111 collapse_subkeys (kbnode_t *keyblock)
4112 {
4113   kbnode_t kb1, kb2, sig1, sig2, last;
4114   int any = 0;
4115 
4116   for (kb1 = *keyblock; kb1; kb1 = kb1->next)
4117     {
4118       if (is_deleted_kbnode (kb1))
4119 	continue;
4120 
4121       if (kb1->pkt->pkttype != PKT_PUBLIC_SUBKEY
4122           && kb1->pkt->pkttype != PKT_SECRET_SUBKEY)
4123 	continue;
4124 
4125       /* We assume just a few duplicates and use a straightforward
4126        * algorithm.  */
4127       for (kb2 = kb1->next; kb2; kb2 = kb2->next)
4128 	{
4129 	  if (is_deleted_kbnode (kb2))
4130 	    continue;
4131 
4132           if (kb2->pkt->pkttype != PKT_PUBLIC_SUBKEY
4133               && kb2->pkt->pkttype != PKT_SECRET_SUBKEY)
4134 	    continue;
4135 
4136           if (cmp_public_keys (kb1->pkt->pkt.public_key,
4137                                kb2->pkt->pkt.public_key))
4138             continue;
4139 
4140           /* We have a duplicated subkey. */
4141           any = 1;
4142 
4143           /* Take subkey-2's signatures, and attach them to subkey-1. */
4144           for (last = kb2; last->next; last = last->next)
4145             {
4146               if (is_deleted_kbnode (last))
4147                 continue;
4148 
4149               if (last->next->pkt->pkttype != PKT_SIGNATURE)
4150                 break;
4151             }
4152 
4153           /* Snip out subkye-2 */
4154           find_prev_kbnode (*keyblock, kb2, 0)->next = last->next;
4155 
4156 	  /* Put subkey-2 in place as part of subkey-1 */
4157           last->next = kb1->next;
4158           kb1->next = kb2;
4159           delete_kbnode (kb2);
4160 
4161           /* Now dedupe kb1 */
4162           for (sig1 = kb1->next; sig1; sig1 = sig1->next)
4163             {
4164               if (is_deleted_kbnode (sig1))
4165                 continue;
4166 
4167               if (sig1->pkt->pkttype != PKT_SIGNATURE)
4168                 break;
4169 
4170               for (sig2 = sig1->next, last = sig1;
4171                    sig2;
4172                    last = sig2, sig2 = sig2->next)
4173                 {
4174                   if (is_deleted_kbnode (sig2))
4175                     continue;
4176 
4177                   if (sig2->pkt->pkttype != PKT_SIGNATURE)
4178                     break;
4179 
4180                   if (!cmp_signatures (sig1->pkt->pkt.signature,
4181                                        sig2->pkt->pkt.signature))
4182                     {
4183                       /* We have a match, so delete the second
4184                          signature */
4185                       delete_kbnode (sig2);
4186                       sig2 = last;
4187                     }
4188                 }
4189             }
4190         }
4191     }
4192 
4193   commit_kbnode (keyblock);
4194 
4195   if (any && !opt.quiet)
4196     {
4197       const char *key="???";
4198 
4199       if ((kb1 = find_kbnode (*keyblock, PKT_PUBLIC_KEY)) )
4200 	key = keystr_from_pk (kb1->pkt->pkt.public_key);
4201       else if ((kb1 = find_kbnode (*keyblock, PKT_SECRET_KEY)) )
4202 	key = keystr_from_pk (kb1->pkt->pkt.public_key);
4203 
4204       log_info (_("key %s: duplicated subkeys detected - merged\n"), key);
4205     }
4206 
4207   return any;
4208 }
4209 
4210 
4211 /* Check for a 0x20 revocation from a revocation key that is not
4212    present.  This may be called without the benefit of merge_xxxx so
4213    you can't rely on pk->revkey and friends. */
4214 static void
revocation_present(ctrl_t ctrl,kbnode_t keyblock)4215 revocation_present (ctrl_t ctrl, kbnode_t keyblock)
4216 {
4217   kbnode_t onode, inode;
4218   PKT_public_key *pk = keyblock->pkt->pkt.public_key;
4219 
4220   for(onode=keyblock->next;onode;onode=onode->next)
4221     {
4222       /* If we reach user IDs, we're done. */
4223       if(onode->pkt->pkttype==PKT_USER_ID)
4224 	break;
4225 
4226       if (onode->pkt->pkttype == PKT_SIGNATURE
4227           && IS_KEY_SIG (onode->pkt->pkt.signature)
4228           && onode->pkt->pkt.signature->revkey)
4229 	{
4230 	  int idx;
4231 	  PKT_signature *sig=onode->pkt->pkt.signature;
4232 
4233 	  for(idx=0;idx<sig->numrevkeys;idx++)
4234 	    {
4235 	      u32 keyid[2];
4236 
4237 	      keyid_from_fingerprint (ctrl, sig->revkey[idx].fpr,
4238                                       sig->revkey[idx].fprlen, keyid);
4239 
4240 	      for(inode=keyblock->next;inode;inode=inode->next)
4241 		{
4242 		  /* If we reach user IDs, we're done. */
4243 		  if(inode->pkt->pkttype==PKT_USER_ID)
4244 		    break;
4245 
4246 		  if (inode->pkt->pkttype == PKT_SIGNATURE
4247                       && IS_KEY_REV (inode->pkt->pkt.signature)
4248                       && inode->pkt->pkt.signature->keyid[0]==keyid[0]
4249                       && inode->pkt->pkt.signature->keyid[1]==keyid[1])
4250 		    {
4251 		      /* Okay, we have a revocation key, and a
4252                        * revocation issued by it.  Do we have the key
4253                        * itself?  */
4254                       gpg_error_t err;
4255 
4256 		      err = get_pubkey_byfprint_fast (ctrl, NULL,
4257                                                       sig->revkey[idx].fpr,
4258                                                       sig->revkey[idx].fprlen);
4259 		      if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY
4260                           || gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY)
4261 			{
4262 			  char *tempkeystr = xstrdup (keystr_from_pk (pk));
4263 
4264 			  /* No, so try and get it */
4265 			  if ((opt.keyserver_options.options
4266                                & KEYSERVER_AUTO_KEY_RETRIEVE)
4267                               && keyserver_any_configured (ctrl))
4268 			    {
4269 			      log_info(_("WARNING: key %s may be revoked:"
4270 					 " fetching revocation key %s\n"),
4271 				       tempkeystr,keystr(keyid));
4272 			      keyserver_import_fprint (ctrl,
4273                                                        sig->revkey[idx].fpr,
4274                                                        sig->revkey[idx].fprlen,
4275                                                        opt.keyserver, 0);
4276 
4277 			      /* Do we have it now? */
4278 			      err = get_pubkey_byfprint_fast (ctrl, NULL,
4279 						     sig->revkey[idx].fpr,
4280                                                      sig->revkey[idx].fprlen);
4281 			    }
4282 
4283 			  if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY
4284                               || gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY)
4285 			    log_info(_("WARNING: key %s may be revoked:"
4286 				       " revocation key %s not present.\n"),
4287 				     tempkeystr,keystr(keyid));
4288 
4289 			  xfree(tempkeystr);
4290 			}
4291 		    }
4292 		}
4293 	    }
4294 	}
4295     }
4296 }
4297 
4298 
4299 /*
4300  * compare and merge the blocks
4301  *
4302  * o compare the signatures: If we already have this signature, check
4303  *   that they compare okay; if not, issue a warning and ask the user.
4304  * o Simply add the signature.	Can't verify here because we may not have
4305  *   the signature's public key yet; verification is done when putting it
4306  *   into the trustdb, which is done automagically as soon as this pubkey
4307  *   is used.
4308  * Note: We indicate newly inserted packets with NODE_FLAG_A.
4309  */
4310 static int
merge_blocks(ctrl_t ctrl,unsigned int options,kbnode_t keyblock_orig,kbnode_t keyblock,u32 * keyid,u32 curtime,int origin,const char * url,int * n_uids,int * n_sigs,int * n_subk)4311 merge_blocks (ctrl_t ctrl, unsigned int options,
4312               kbnode_t keyblock_orig, kbnode_t keyblock,
4313               u32 *keyid, u32 curtime, int origin, const char *url,
4314 	      int *n_uids, int *n_sigs, int *n_subk )
4315 {
4316   kbnode_t onode, node;
4317   int rc, found;
4318 
4319   /* 1st: handle revocation certificates */
4320   for (node=keyblock->next; node; node=node->next )
4321     {
4322       if (node->pkt->pkttype == PKT_USER_ID )
4323         break;
4324       else if (node->pkt->pkttype == PKT_SIGNATURE
4325                && IS_KEY_REV (node->pkt->pkt.signature))
4326         {
4327           /* check whether we already have this */
4328           found = 0;
4329           for (onode=keyblock_orig->next; onode; onode=onode->next)
4330             {
4331               if (onode->pkt->pkttype == PKT_USER_ID )
4332                 break;
4333               else if (onode->pkt->pkttype == PKT_SIGNATURE
4334                        && IS_KEY_REV (onode->pkt->pkt.signature)
4335                        && !cmp_signatures(onode->pkt->pkt.signature,
4336                                           node->pkt->pkt.signature))
4337                 {
4338                   found = 1;
4339                   break;
4340                 }
4341 	    }
4342           if (!found)
4343             {
4344               kbnode_t n2 = clone_kbnode(node);
4345               insert_kbnode( keyblock_orig, n2, 0 );
4346               n2->flag |= NODE_FLAG_A;
4347               ++*n_sigs;
4348               if(!opt.quiet)
4349                 {
4350                   char *p = get_user_id_native (ctrl, keyid);
4351                   log_info(_("key %s: \"%s\" revocation"
4352                              " certificate added\n"), keystr(keyid),p);
4353                   xfree(p);
4354                 }
4355 	    }
4356 	}
4357     }
4358 
4359   /* 2nd: merge in any direct key (0x1F) sigs */
4360   for(node=keyblock->next; node; node=node->next)
4361     {
4362       if (node->pkt->pkttype == PKT_USER_ID )
4363         break;
4364       else if (node->pkt->pkttype == PKT_SIGNATURE
4365                && IS_KEY_SIG (node->pkt->pkt.signature))
4366         {
4367           /* check whether we already have this */
4368           found = 0;
4369           for (onode=keyblock_orig->next; onode; onode=onode->next)
4370             {
4371               if (onode->pkt->pkttype == PKT_USER_ID)
4372                 break;
4373               else if (onode->pkt->pkttype == PKT_SIGNATURE
4374                        && IS_KEY_SIG (onode->pkt->pkt.signature)
4375                        && !cmp_signatures(onode->pkt->pkt.signature,
4376                                           node->pkt->pkt.signature))
4377                 {
4378                   found = 1;
4379                   break;
4380 		}
4381 	    }
4382           if (!found )
4383             {
4384               kbnode_t n2 = clone_kbnode(node);
4385               insert_kbnode( keyblock_orig, n2, 0 );
4386               n2->flag |= NODE_FLAG_A;
4387               ++*n_sigs;
4388               if(!opt.quiet)
4389                 log_info( _("key %s: direct key signature added\n"),
4390                           keystr(keyid));
4391             }
4392 	}
4393     }
4394 
4395   /* 3rd: try to merge new certificates in */
4396   for (onode=keyblock_orig->next; onode; onode=onode->next)
4397     {
4398       if (!(onode->flag & NODE_FLAG_A) && onode->pkt->pkttype == PKT_USER_ID)
4399         {
4400           /* find the user id in the imported keyblock */
4401           for (node=keyblock->next; node; node=node->next)
4402             if (node->pkt->pkttype == PKT_USER_ID
4403                 && !cmp_user_ids( onode->pkt->pkt.user_id,
4404                                   node->pkt->pkt.user_id ) )
4405               break;
4406           if (node ) /* found: merge */
4407             {
4408               rc = merge_sigs (onode, node, n_sigs);
4409               if (rc )
4410                 return rc;
4411 	    }
4412 	}
4413     }
4414 
4415   /* 4th: add new user-ids */
4416   for (node=keyblock->next; node; node=node->next)
4417     {
4418       if (node->pkt->pkttype == PKT_USER_ID)
4419         {
4420           /* do we have this in the original keyblock */
4421           for (onode=keyblock_orig->next; onode; onode=onode->next )
4422             if (onode->pkt->pkttype == PKT_USER_ID
4423                 && !cmp_user_ids( onode->pkt->pkt.user_id,
4424                                   node->pkt->pkt.user_id ) )
4425               break;
4426           if (!onode ) /* this is a new user id: append */
4427             {
4428               rc = append_new_uid (options, keyblock_orig, node,
4429                                    curtime, origin, url, n_sigs);
4430               if (rc )
4431                 return rc;
4432               ++*n_uids;
4433 	    }
4434 	}
4435     }
4436 
4437   /* 5th: add new subkeys */
4438   for (node=keyblock->next; node; node=node->next)
4439     {
4440       onode = NULL;
4441       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4442         {
4443           /* do we have this in the original keyblock? */
4444           for(onode=keyblock_orig->next; onode; onode=onode->next)
4445             if (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
4446                 && !cmp_public_keys( onode->pkt->pkt.public_key,
4447                                      node->pkt->pkt.public_key))
4448               break;
4449           if (!onode ) /* This is a new subkey: append.  */
4450             {
4451               rc = append_key (keyblock_orig, node, n_sigs);
4452               if (rc)
4453                 return rc;
4454               ++*n_subk;
4455 	    }
4456 	}
4457       else if (node->pkt->pkttype == PKT_SECRET_SUBKEY)
4458         {
4459           /* do we have this in the original keyblock? */
4460           for (onode=keyblock_orig->next; onode; onode=onode->next )
4461             if (onode->pkt->pkttype == PKT_SECRET_SUBKEY
4462                 && !cmp_public_keys (onode->pkt->pkt.public_key,
4463                                      node->pkt->pkt.public_key) )
4464               break;
4465           if (!onode ) /* This is a new subkey: append.  */
4466             {
4467               rc = append_key (keyblock_orig, node, n_sigs);
4468               if (rc )
4469                 return rc;
4470               ++*n_subk;
4471 	    }
4472 	}
4473     }
4474 
4475   /* 6th: merge subkey certificates */
4476   for (onode=keyblock_orig->next; onode; onode=onode->next)
4477     {
4478       if (!(onode->flag & NODE_FLAG_A)
4479           && (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
4480               || onode->pkt->pkttype == PKT_SECRET_SUBKEY))
4481         {
4482           /* find the subkey in the imported keyblock */
4483           for(node=keyblock->next; node; node=node->next)
4484             {
4485               if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
4486                    || node->pkt->pkttype == PKT_SECRET_SUBKEY)
4487                   && !cmp_public_keys( onode->pkt->pkt.public_key,
4488                                        node->pkt->pkt.public_key ) )
4489                 break;
4490 	    }
4491           if (node) /* Found: merge.  */
4492             {
4493               rc = merge_keysigs( onode, node, n_sigs);
4494               if (rc )
4495                 return rc;
4496 	    }
4497 	}
4498     }
4499 
4500   return 0;
4501 }
4502 
4503 
4504 /* Helper function for merge_blocks.
4505  *
4506  * Append the new userid starting with NODE and all signatures to
4507  * KEYBLOCK.  ORIGIN and URL conveys the usual key origin info.  The
4508  * integer at N_SIGS is updated with the number of new signatures.
4509  */
4510 static gpg_error_t
append_new_uid(unsigned int options,kbnode_t keyblock,kbnode_t node,u32 curtime,int origin,const char * url,int * n_sigs)4511 append_new_uid (unsigned int options,
4512                 kbnode_t keyblock, kbnode_t node, u32 curtime,
4513                 int origin, const char *url, int *n_sigs)
4514 {
4515   gpg_error_t err;
4516   kbnode_t n;
4517   kbnode_t n_where = NULL;
4518 
4519   log_assert (node->pkt->pkttype == PKT_USER_ID);
4520 
4521   /* Find the right position for the new user id and its signatures.  */
4522   for (n = keyblock; n; n_where = n, n = n->next)
4523     {
4524       if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
4525           || n->pkt->pkttype == PKT_SECRET_SUBKEY )
4526         break;
4527     }
4528   if (!n)
4529     n_where = NULL;
4530 
4531   /* and append/insert */
4532   while (node)
4533     {
4534       /* we add a clone to the original keyblock, because this
4535        * one is released first. */
4536       n = clone_kbnode(node);
4537       if (n->pkt->pkttype == PKT_USER_ID
4538           && !(options & IMPORT_RESTORE) )
4539         {
4540           err = insert_key_origin_uid (n->pkt->pkt.user_id,
4541                                        curtime, origin, url);
4542           if (err)
4543             {
4544               release_kbnode (n);
4545               return err;
4546             }
4547         }
4548 
4549       if (n_where)
4550         {
4551           insert_kbnode( n_where, n, 0 );
4552           n_where = n;
4553 	}
4554       else
4555         add_kbnode( keyblock, n );
4556       n->flag |= NODE_FLAG_A;
4557       node->flag |= NODE_FLAG_A;
4558       if (n->pkt->pkttype == PKT_SIGNATURE )
4559         ++*n_sigs;
4560 
4561       node = node->next;
4562       if (node && node->pkt->pkttype != PKT_SIGNATURE )
4563         break;
4564     }
4565 
4566   return 0;
4567 }
4568 
4569 
4570 /* Helper function for merge_blocks
4571  * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
4572  * (how should we handle comment packets here?)
4573  */
4574 static int
merge_sigs(kbnode_t dst,kbnode_t src,int * n_sigs)4575 merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs)
4576 {
4577   kbnode_t n, n2;
4578   int found = 0;
4579 
4580   log_assert (dst->pkt->pkttype == PKT_USER_ID);
4581   log_assert (src->pkt->pkttype == PKT_USER_ID);
4582 
4583   for (n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next)
4584     {
4585       if (n->pkt->pkttype != PKT_SIGNATURE )
4586         continue;
4587       if (IS_SUBKEY_SIG (n->pkt->pkt.signature)
4588           || IS_SUBKEY_REV (n->pkt->pkt.signature) )
4589         continue; /* skip signatures which are only valid on subkeys */
4590 
4591       found = 0;
4592       for (n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
4593         if (!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
4594           {
4595             found++;
4596             break;
4597           }
4598       if (!found )
4599         {
4600           /* This signature is new or newer, append N to DST.
4601            * We add a clone to the original keyblock, because this
4602            * one is released first */
4603           n2 = clone_kbnode(n);
4604           insert_kbnode( dst, n2, PKT_SIGNATURE );
4605           n2->flag |= NODE_FLAG_A;
4606           n->flag |= NODE_FLAG_A;
4607           ++*n_sigs;
4608 	}
4609     }
4610 
4611   return 0;
4612 }
4613 
4614 
4615 /* Helper function for merge_blocks
4616  * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
4617  */
4618 static int
merge_keysigs(kbnode_t dst,kbnode_t src,int * n_sigs)4619 merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs)
4620 {
4621   kbnode_t n, n2;
4622   int found = 0;
4623 
4624   log_assert (dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
4625               || dst->pkt->pkttype == PKT_SECRET_SUBKEY);
4626 
4627   for (n=src->next; n ; n = n->next)
4628     {
4629       if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
4630           || n->pkt->pkttype == PKT_PUBLIC_KEY )
4631         break;
4632       if (n->pkt->pkttype != PKT_SIGNATURE )
4633         continue;
4634 
4635       found = 0;
4636       for (n2=dst->next; n2; n2 = n2->next)
4637         {
4638           if (n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
4639               || n2->pkt->pkttype == PKT_PUBLIC_KEY )
4640             break;
4641           if (n2->pkt->pkttype == PKT_SIGNATURE
4642               && (n->pkt->pkt.signature->keyid[0]
4643                   == n2->pkt->pkt.signature->keyid[0])
4644               && (n->pkt->pkt.signature->keyid[1]
4645                   == n2->pkt->pkt.signature->keyid[1])
4646               && (n->pkt->pkt.signature->timestamp
4647                   <= n2->pkt->pkt.signature->timestamp)
4648               && (n->pkt->pkt.signature->sig_class
4649                   == n2->pkt->pkt.signature->sig_class))
4650             {
4651               found++;
4652               break;
4653 	    }
4654 	}
4655       if (!found )
4656         {
4657           /* This signature is new or newer, append N to DST.
4658            * We add a clone to the original keyblock, because this
4659            * one is released first */
4660           n2 = clone_kbnode(n);
4661           insert_kbnode( dst, n2, PKT_SIGNATURE );
4662           n2->flag |= NODE_FLAG_A;
4663           n->flag |= NODE_FLAG_A;
4664           ++*n_sigs;
4665 	}
4666     }
4667 
4668   return 0;
4669 }
4670 
4671 
4672 /* Helper function for merge_blocks.
4673  * Append the subkey starting with NODE and all signatures to KEYBLOCK.
4674  * Mark all new and copied packets by setting flag bit 0.
4675  */
4676 static int
append_key(kbnode_t keyblock,kbnode_t node,int * n_sigs)4677 append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs)
4678 {
4679   kbnode_t n;
4680 
4681   log_assert (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
4682               || node->pkt->pkttype == PKT_SECRET_SUBKEY);
4683 
4684   while (node)
4685     {
4686       /* we add a clone to the original keyblock, because this
4687        * one is released first */
4688       n = clone_kbnode(node);
4689       add_kbnode( keyblock, n );
4690       n->flag |= NODE_FLAG_A;
4691       node->flag |= NODE_FLAG_A;
4692       if (n->pkt->pkttype == PKT_SIGNATURE )
4693         ++*n_sigs;
4694 
4695       node = node->next;
4696       if (node && node->pkt->pkttype != PKT_SIGNATURE )
4697         break;
4698     }
4699 
4700   return 0;
4701 }
4702