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
5 * This file is part of GnuPG.
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.
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.
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/>.
30 #include "../common/status.h"
32 #include "../common/util.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"
58 ulong secret_imported;
60 ulong skipped_new_keys;
64 ulong v3keys; /* Number of V3 keys seen. */
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. */
78 /* A flag used by transfer_secret_keys. */
79 #define NODE_TRANSFER_SECKEY 16
82 /* An object and a global instance to store selectors created from
83 * --import-filter keep-uid=EXPR.
84 * --import-filter drop-sig=EXPR.
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.
90 /* Definition of the import filters. */
91 struct import_filter_s
93 recsel_expr_t keep_uid;
94 recsel_expr_t drop_sig;
96 /* The current instance. */
97 struct import_filter_s import_filter;
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,
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,
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,
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);
148 release_import_filter (import_filter_t filt)
150 recsel_release (filt->keep_uid);
151 filt->keep_uid = NULL;
152 recsel_release (filt->drop_sig);
153 filt->drop_sig = NULL;
157 cleanup_import_globals (void)
159 release_import_filter (&import_filter);
164 parse_import_options(char *str,unsigned int *options,int noisy)
166 struct parse_options import_opts[]=
168 {"import-local-sigs",IMPORT_LOCAL_SIGS,NULL,
169 N_("import signatures that are marked as local-only")},
171 {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,
172 N_("repair damage from the pks keyserver during import")},
174 {"keep-ownertrust", IMPORT_KEEP_OWNERTTRUST, NULL,
175 N_("do not clear the ownertrust values during import")},
177 {"fast-import",IMPORT_FAST,NULL,
178 N_("do not update the trustdb after import")},
180 {"import-show",IMPORT_SHOW,NULL,
181 N_("show key during import")},
183 {"merge-only",IMPORT_MERGE_ONLY,NULL,
184 N_("only accept updates to existing keys")},
186 {"import-clean",IMPORT_CLEAN,NULL,
187 N_("remove unusable parts from key after import")},
189 {"import-minimal",IMPORT_MINIMAL|IMPORT_CLEAN,NULL,
190 N_("remove as much as possible from key after import")},
192 {"self-sigs-only", IMPORT_SELF_SIGS_ONLY, NULL,
193 N_("ignore key-signatures which are not self-signatures")},
195 {"import-export", IMPORT_EXPORT, NULL,
196 N_("run import filters and export key immediately")},
198 {"restore", IMPORT_RESTORE, NULL,
199 N_("assume the GnuPG key backup format")},
200 {"import-restore", IMPORT_RESTORE, NULL, NULL},
202 {"repair-keys", IMPORT_REPAIR_KEYS, NULL,
203 N_("repair keys on import")},
205 /* No description to avoid string change: Fixme for 2.3 */
206 {"show-only", (IMPORT_SHOW | IMPORT_DRY_RUN), NULL,
209 /* Aliases for backward compatibility */
210 {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL},
211 {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL},
213 {"import-unusable-sigs",0,NULL,NULL},
214 {"import-clean-sigs",0,NULL,NULL},
215 {"import-clean-uids",0,NULL,NULL},
216 {"convert-sk-to-pk",0, NULL,NULL}, /* Not anymore needed due to
222 rc = parse_options (str, options, import_opts, noisy);
223 if (rc && (*options & IMPORT_RESTORE))
225 /* Alter other options we want or don't want for restore. */
226 *options |= (IMPORT_LOCAL_SIGS | IMPORT_KEEP_OWNERTTRUST);
227 *options &= ~(IMPORT_MINIMAL | IMPORT_CLEAN
228 | IMPORT_REPAIR_PKS_SUBKEY_BUG
229 | IMPORT_MERGE_ONLY);
235 /* Parse and set an import filter from string. STRING has the format
236 * "NAME=EXPR" with NAME being the name of the filter. Spaces before
237 * and after NAME are not allowed. If this function is all called
238 * several times all expressions for the same NAME are concatenated.
239 * Supported filter names are:
241 * - keep-uid :: If the expression evaluates to true for a certain
242 * user ID packet, that packet and all it dependencies
243 * will be imported. The expression may use these
246 * - uid :: The entire user ID.
247 * - mbox :: The mail box part of the user ID.
248 * - primary :: Evaluate to true for the primary user ID.
251 parse_and_set_import_filter (const char *string)
255 /* Auto register the cleanup function. */
256 register_mem_cleanup_func (cleanup_import_globals);
258 if (!strncmp (string, "keep-uid=", 9))
259 err = recsel_parse_expr (&import_filter.keep_uid, string+9);
260 else if (!strncmp (string, "drop-sig=", 9))
261 err = recsel_parse_expr (&import_filter.drop_sig, string+9);
263 err = gpg_error (GPG_ERR_INV_NAME);
269 /* Save the current import filters, return them, and clear the current
270 * filters. Returns NULL on error and sets ERRNO. */
272 save_and_clear_import_filter (void)
274 import_filter_t filt;
276 filt = xtrycalloc (1, sizeof *filt);
279 *filt = import_filter;
280 memset (&import_filter, 0, sizeof import_filter);
286 /* Release the current import filters and restore them from NEWFILT.
287 * Ownership of NEWFILT is moved to this function. */
289 restore_import_filter (import_filter_t filt)
293 release_import_filter (&import_filter);
294 import_filter = *filt;
301 import_new_stats_handle (void)
303 return xmalloc_clear ( sizeof (struct import_stats_s) );
308 import_release_stats_handle (import_stats_t p)
314 /* Read a key from a file. Only the first key in the file is
315 * considered and stored at R_KEYBLOCK. FNAME is the name of the
319 read_key_from_file (ctrl_t ctrl, const char *fname, kbnode_t *r_keyblock)
323 PACKET *pending_pkt = NULL;
324 kbnode_t keyblock = NULL;
326 int v3keys; /* Dummy */
327 int non_self; /* Dummy */
333 inp = iobuf_open (fname);
335 err = gpg_error_from_syserror ();
336 else if (is_secured_file (iobuf_get_fd (inp)))
340 err = gpg_error (GPG_ERR_EPERM);
346 log_error (_("can't open '%s': %s\n"),
347 iobuf_is_pipe_filename (fname)? "[stdin]": fname,
349 if (gpg_err_code (err) == GPG_ERR_ENOENT)
350 err = gpg_error (GPG_ERR_NO_PUBKEY);
354 /* Push the armor filter. */
356 armor_filter_context_t *afx;
357 afx = new_armor_context ();
358 afx->only_keyblocks = 1;
359 push_armor_filter (afx, inp);
360 release_armor_context (afx);
363 /* Read the first non-v3 keyblock. */
364 while (!(err = read_block (inp, 0, &pending_pkt, &keyblock, &v3keys)))
366 if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
368 log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
369 release_kbnode (keyblock);
374 if (gpg_err_code (err) != GPG_ERR_INV_KEYRING)
375 log_error (_("error reading '%s': %s\n"),
376 iobuf_is_pipe_filename (fname)? "[stdin]": fname,
381 keyid_from_pk (keyblock->pkt->pkt.public_key, keyid);
383 if (!find_next_kbnode (keyblock, PKT_USER_ID))
385 err = gpg_error (GPG_ERR_NO_USER_ID);
389 collapse_uids (&keyblock);
391 clear_kbnode_flags (keyblock);
392 if (chk_self_sigs (ctrl, keyblock, keyid, &non_self))
394 err = gpg_error (GPG_ERR_INV_KEYRING);
398 if (!delete_inv_parts (ctrl, keyblock, keyid, 0) )
400 err = gpg_error (GPG_ERR_NO_USER_ID);
404 *r_keyblock = keyblock;
411 /* Must invalidate that ugly cache to actually close the file. */
412 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
414 release_kbnode (keyblock);
415 /* FIXME: Do we need to free PENDING_PKT ? */
422 * Import the public keys from the given filename. Input may be armored.
423 * This function rejects all keys which are not validly self signed on at
424 * least one userid. Only user ids which are self signed will be imported.
425 * Other signatures are not checked.
427 * Actually this function does a merge. It works like this:
430 * - check self-signatures and remove all userids and their signatures
431 * without/invalid self-signatures.
432 * - reject the keyblock, if we have no valid userid.
433 * - See whether we have this key already in one of our pubrings.
434 * If not, simply add it to the default keyring.
435 * - Compare the key and the self-signatures of the new and the one in
436 * our keyring. If they are different something weird is going on;
438 * - See whether we have only non-self-signature on one user id; if not
439 * ask the user what to do.
440 * - compare the signatures: If we already have this signature, check
441 * that they compare okay; if not, issue a warning and ask the user.
442 * (consider looking at the timestamp and use the newest?)
443 * - Simply add the signature. Can't verify here because we may not have
444 * the signature's public key yet; verification is done when putting it
445 * into the trustdb, which is done automagically as soon as this pubkey
447 * - Proceed with next signature.
449 * Key revocation certificates have special handling.
452 import_keys_internal (ctrl_t ctrl, iobuf_t inp, char **fnames, int nnames,
453 import_stats_t stats_handle,
454 unsigned char **fpr, size_t *fpr_len,
455 unsigned int options,
456 import_screener_t screener, void *screener_arg,
457 int origin, const char *url)
461 struct import_stats_s *stats = stats_handle;
464 stats = import_new_stats_handle ();
468 err = import (ctrl, inp, "[stream]", stats, fpr, fpr_len, options,
469 screener, screener_arg, origin, url);
473 if (!fnames && !nnames)
474 nnames = 1; /* Ohh what a ugly hack to jump into the loop */
476 for (i=0; i < nnames; i++)
478 const char *fname = fnames? fnames[i] : NULL;
479 IOBUF inp2 = iobuf_open(fname);
483 if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
487 gpg_err_set_errno (EPERM);
490 log_error (_("can't open '%s': %s\n"), fname, strerror (errno));
493 err = import (ctrl, inp2, fname, stats, fpr, fpr_len, options,
494 screener, screener_arg, origin, url);
496 /* Must invalidate that ugly cache to actually close it. */
497 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
499 log_error ("import from '%s' failed: %s\n",
500 fname, gpg_strerror (err) );
509 if ((options & (IMPORT_SHOW | IMPORT_DRY_RUN))
510 != (IMPORT_SHOW | IMPORT_DRY_RUN))
511 import_print_stats (stats);
512 import_release_stats_handle (stats);
515 /* If no fast import and the trustdb is dirty (i.e. we added a key
516 or userID that had something other than a selfsig, a signature
517 that was other than a selfsig, or any revocation), then
518 update/check the trustdb if the user specified by setting
519 interactive or by not setting no-auto-check-trustdb */
521 if (!(options & IMPORT_FAST))
522 check_or_update_trustdb (ctrl);
529 import_keys (ctrl_t ctrl, char **fnames, int nnames,
530 import_stats_t stats_handle, unsigned int options,
531 int origin, const char *url)
533 import_keys_internal (ctrl, NULL, fnames, nnames, stats_handle,
534 NULL, NULL, options, NULL, NULL, origin, url);
539 import_keys_es_stream (ctrl_t ctrl, estream_t fp,
540 import_stats_t stats_handle,
541 unsigned char **fpr, size_t *fpr_len,
542 unsigned int options,
543 import_screener_t screener, void *screener_arg,
544 int origin, const char *url)
549 inp = iobuf_esopen (fp, "rb", 1);
552 err = gpg_error_from_syserror ();
553 log_error ("iobuf_esopen failed: %s\n", gpg_strerror (err));
557 err = import_keys_internal (ctrl, inp, NULL, 0, stats_handle,
558 fpr, fpr_len, options,
559 screener, screener_arg, origin, url);
567 import (ctrl_t ctrl, IOBUF inp, const char* fname,struct import_stats_s *stats,
568 unsigned char **fpr,size_t *fpr_len, unsigned int options,
569 import_screener_t screener, void *screener_arg,
570 int origin, const char *url)
572 PACKET *pending_pkt = NULL;
573 kbnode_t keyblock = NULL; /* Need to initialize because gcc can't
574 grasp the return semantics of
576 kbnode_t secattic = NULL; /* Kludge for PGP desktop percularity */
580 getkey_disable_caches ();
582 if (!opt.no_armor) /* Armored reading is not disabled. */
584 armor_filter_context_t *afx;
586 afx = new_armor_context ();
587 afx->only_keyblocks = 1;
588 push_armor_filter (afx, inp);
589 release_armor_context (afx);
592 while (!(rc = read_block (inp, options, &pending_pkt, &keyblock, &v3keys)))
594 stats->v3keys += v3keys;
595 if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
597 rc = import_one (ctrl, keyblock,
598 stats, fpr, fpr_len, options, 0, 0,
599 screener, screener_arg, origin, url, NULL);
602 byte tmpfpr[MAX_FINGERPRINT_LEN];
605 if (!rc && !(opt.dry_run || (options & IMPORT_DRY_RUN)))
607 /* Kudge for PGP desktop - see below. */
608 fingerprint_from_pk (keyblock->pkt->pkt.public_key,
610 rc = import_matching_seckeys (ctrl, secattic,
614 release_kbnode (secattic);
618 else if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
620 release_kbnode (secattic);
622 rc = import_secret_one (ctrl, keyblock, stats,
623 opt.batch, options, 0,
624 screener, screener_arg, &secattic);
625 keyblock = NULL; /* Ownership was transferred. */
628 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
629 rc = 0; /* Try import after the next pubkey. */
631 /* The attic is a workaround for the peculiar PGP
632 * Desktop method of exporting a secret key: The
633 * exported file is the concatenation of two armored
634 * keyblocks; first the private one and then the public
635 * one. The strange thing is that the secret one has no
636 * binding signatures at all and thus we have not
637 * imported it. The attic stores that secret keys and
638 * we try to import it once after the very next public
642 else if (keyblock->pkt->pkttype == PKT_SIGNATURE
643 && IS_KEY_REV (keyblock->pkt->pkt.signature) )
645 release_kbnode (secattic);
647 rc = import_revoke_cert (ctrl, keyblock, options, stats);
651 release_kbnode (secattic);
653 log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
655 release_kbnode (keyblock);
657 /* fixme: we should increment the not imported counter but
658 this does only make sense if we keep on going despite of
659 errors. For now we do this only if the imported key is too
661 if (gpg_err_code (rc) == GPG_ERR_TOO_LARGE
662 && gpg_err_source (rc) == GPG_ERR_SOURCE_KEYBOX)
664 stats->not_imported++;
669 if (!(++stats->count % 100) && !opt.quiet)
670 log_info (_("%lu keys processed so far\n"), stats->count );
672 if (origin == KEYORG_WKD && stats->count >= 5)
674 /* We limit the number of keys _received_ from the WKD to 5.
675 * In fact there should be only one key but some sites want
676 * to store a few expired keys there also. gpg's key
677 * selection will later figure out which key to use. Note
678 * that for WKD we always return the fingerprint of the
679 * first imported key. */
680 log_info ("import from WKD stopped after %d keys\n", 5);
684 stats->v3keys += v3keys;
687 else if (rc && gpg_err_code (rc) != GPG_ERR_INV_KEYRING)
688 log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (rc));
690 release_kbnode (secattic);
695 /* Helper to migrate secring.gpg to GnuPG 2.1. */
697 import_old_secring (ctrl_t ctrl, const char *fname)
701 PACKET *pending_pkt = NULL;
702 kbnode_t keyblock = NULL; /* Need to initialize because gcc can't
703 grasp the return semantics of
705 struct import_stats_s *stats;
708 inp = iobuf_open (fname);
709 if (inp && is_secured_file (iobuf_get_fd (inp)))
713 gpg_err_set_errno (EPERM);
717 err = gpg_error_from_syserror ();
718 log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
722 getkey_disable_caches();
723 stats = import_new_stats_handle ();
724 while (!(err = read_block (inp, 0, &pending_pkt, &keyblock, &v3keys)))
726 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
728 err = import_secret_one (ctrl, keyblock, stats, 1, 0, 1,
730 keyblock = NULL; /* Ownership was transferred. */
732 release_kbnode (keyblock);
736 import_release_stats_handle (stats);
739 else if (err && gpg_err_code (err) != GPG_ERR_INV_KEYRING)
740 log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
742 log_error ("import from '%s' failed: %s\n", fname, gpg_strerror (err));
745 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
752 import_print_stats (import_stats_t stats)
756 log_info(_("Total number processed: %lu\n"),
757 stats->count + stats->v3keys);
759 log_info(_(" skipped PGP-2 keys: %lu\n"), stats->v3keys);
760 if (stats->skipped_new_keys )
761 log_info(_(" skipped new keys: %lu\n"),
762 stats->skipped_new_keys );
763 if (stats->no_user_id )
764 log_info(_(" w/o user IDs: %lu\n"), stats->no_user_id );
767 log_info(_(" imported: %lu"), stats->imported );
770 if (stats->unchanged )
771 log_info(_(" unchanged: %lu\n"), stats->unchanged );
773 log_info(_(" new user IDs: %lu\n"), stats->n_uids );
775 log_info(_(" new subkeys: %lu\n"), stats->n_subk );
777 log_info(_(" new signatures: %lu\n"), stats->n_sigs );
779 log_info(_(" new key revocations: %lu\n"), stats->n_revoc );
780 if (stats->secret_read )
781 log_info(_(" secret keys read: %lu\n"), stats->secret_read );
782 if (stats->secret_imported )
783 log_info(_(" secret keys imported: %lu\n"), stats->secret_imported );
784 if (stats->secret_dups )
785 log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
786 if (stats->not_imported )
787 log_info(_(" not imported: %lu\n"), stats->not_imported );
788 if (stats->n_sigs_cleaned)
789 log_info(_(" signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
790 if (stats->n_uids_cleaned)
791 log_info(_(" user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
794 if (is_status_enabled ())
798 snprintf (buf, sizeof buf,
799 "%lu %lu %lu 0 %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
800 stats->count + stats->v3keys,
809 stats->secret_imported,
811 stats->skipped_new_keys,
814 write_status_text (STATUS_IMPORT_RES, buf);
819 /* Return true if PKTTYPE is valid in a keyblock. */
821 valid_keyblock_packet (int pkttype)
826 case PKT_PUBLIC_SUBKEY:
828 case PKT_SECRET_SUBKEY:
840 /* Read the next keyblock from stream A. Meta data (ring trust
841 * packets) are only considered if OPTIONS has the IMPORT_RESTORE flag
842 * set. PENDING_PKT should be initialized to NULL and not changed by
845 * Returns 0 for okay, -1 no more blocks, or any other errorcode. The
846 * integer at R_V3KEY counts the number of unsupported v3 keyblocks.
849 read_block( IOBUF a, unsigned int options,
850 PACKET **pending_pkt, kbnode_t *ret_root, int *r_v3keys)
853 struct parse_packet_ctx_s parsectx;
855 kbnode_t root = NULL;
856 int in_cert, in_v3key, skip_sigs;
859 unsigned int dropped_nonselfsigs = 0;
865 root = new_kbnode( *pending_pkt );
867 log_assert (root->pkt->pkttype == PKT_PUBLIC_KEY
868 || root->pkt->pkttype == PKT_SECRET_KEY);
870 keyid_from_pk (root->pkt->pkt.public_key, keyid);
876 pkt = xmalloc (sizeof *pkt);
878 init_parse_packet (&parsectx, a);
879 if (!(options & IMPORT_RESTORE))
880 parsectx.skip_meta = 1;
883 while ((rc=parse_packet (&parsectx, pkt)) != -1)
885 if (rc && ((gpg_err_code (rc) == GPG_ERR_LEGACY_KEY
886 || gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION)
887 && (pkt->pkttype == PKT_PUBLIC_KEY
888 || pkt->pkttype == PKT_SECRET_KEY)))
891 if (gpg_err_code (rc) != GPG_ERR_UNKNOWN_VERSION)
893 free_packet (pkt, &parsectx);
897 else if (rc ) /* (ignore errors) */
900 if (gpg_err_code (rc) == GPG_ERR_UNKNOWN_PACKET)
901 ; /* Do not show a diagnostic. */
902 else if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
903 && (pkt->pkttype == PKT_USER_ID
904 || pkt->pkttype == PKT_ATTRIBUTE))
906 /* This indicates a too large user id or attribute
907 * packet. We skip this packet and all following
908 * signatures. Sure, this won't allow to repair a
909 * garbled keyring in case one of the signatures belong
910 * to another user id. However, this better mitigates
911 * DoS using inserted user ids. */
914 else if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
915 && (pkt->pkttype == PKT_OLD_COMMENT
916 || pkt->pkttype == PKT_COMMENT))
917 ; /* Ignore too large comment packets. */
920 log_error("read_block: read error: %s\n", gpg_strerror (rc) );
921 rc = GPG_ERR_INV_KEYRING;
924 free_packet (pkt, &parsectx);
931 if (pkt->pkttype == PKT_SIGNATURE)
933 free_packet (pkt, &parsectx);
940 if (in_v3key && !(pkt->pkttype == PKT_PUBLIC_KEY
941 || pkt->pkttype == PKT_SECRET_KEY))
943 free_packet (pkt, &parsectx);
949 if (!root && pkt->pkttype == PKT_SIGNATURE
950 && IS_KEY_REV (pkt->pkt.signature) )
952 /* This is a revocation certificate which is handled in a
954 root = new_kbnode( pkt );
959 /* Make a linked list of all packets. */
960 switch (pkt->pkttype)
963 if (check_compress_algo (pkt->pkt.compressed->algorithm))
965 rc = GPG_ERR_COMPR_ALGO;
970 compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
971 pkt->pkt.compressed->buf = NULL;
972 if (push_compress_filter2 (a, cfx,
973 pkt->pkt.compressed->algorithm, 1))
974 xfree (cfx); /* e.g. in case of compression_algo NONE. */
976 free_packet (pkt, &parsectx);
981 /* Skip those packets unless we are in restore mode. */
982 if ((opt.import_options & IMPORT_RESTORE))
984 free_packet (pkt, &parsectx);
991 if (!(options & IMPORT_SELF_SIGS_ONLY))
993 log_assert (got_keyid);
994 if (pkt->pkt.signature->keyid[0] == keyid[0]
995 && pkt->pkt.signature->keyid[1] == keyid[1])
996 { /* This is likely a self-signature. We import this one.
997 * Eventually we should use the ISSUER_FPR to compare
998 * self-signatures, but that will work only for v5 keys
999 * which are currently not even deployed.
1000 * Note that we do not do any crypto verify here because
1001 * that would defeat this very mitigation of DoS by
1002 * importing a key with a huge amount of faked
1003 * key-signatures. A verification will be done later in
1004 * the processing anyway. Here we want a cheap an early
1005 * way to drop non-self-signatures. */
1008 /* Skip this signature. */
1009 dropped_nonselfsigs++;
1010 free_packet (pkt, &parsectx);
1014 case PKT_PUBLIC_KEY:
1015 case PKT_SECRET_KEY:
1018 keyid_from_pk (pkt->pkt.public_key, keyid);
1021 if (in_cert) /* Store this packet. */
1032 if (in_cert && valid_keyblock_packet (pkt->pkttype))
1035 root = new_kbnode (pkt);
1037 add_kbnode (root, new_kbnode (pkt));
1038 pkt = xmalloc (sizeof *pkt);
1041 free_packet (pkt, &parsectx);
1048 if (rc == -1 && root )
1052 release_kbnode( root );
1055 free_packet (pkt, &parsectx);
1056 deinit_parse_packet (&parsectx);
1058 if (!rc && dropped_nonselfsigs && opt.verbose)
1059 log_info ("key %s: number of dropped non-self-signatures: %u\n",
1060 keystr (keyid), dropped_nonselfsigs);
1066 /* Walk through the subkeys on a pk to find if we have the PKS
1067 disease: multiple subkeys with their binding sigs stripped, and the
1068 sig for the first subkey placed after the last subkey. That is,
1069 instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
1070 "pk uid sig sub1 sub2 sub3 bind1". We can't do anything about sub2
1071 and sub3, as they are already lost, but we can try and rescue sub1
1072 by reordering the keyblock so that it reads "pk uid sig sub1 bind1
1073 sub2 sub3". Returns TRUE if the keyblock was modified. */
1075 fix_pks_corruption (ctrl_t ctrl, kbnode_t keyblock)
1080 kbnode_t last = NULL;
1081 kbnode_t sknode=NULL;
1083 /* First determine if we have the problem at all. Look for 2 or
1084 more subkeys in a row, followed by a single binding sig. */
1085 for (node=keyblock; node; last=node, node=node->next)
1087 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1093 else if (node->pkt->pkttype == PKT_SIGNATURE
1094 && IS_SUBKEY_SIG (node->pkt->pkt.signature)
1098 /* We might have the problem, as this key has two subkeys in
1099 a row without any intervening packets. */
1105 /* Temporarily attach node to sknode. */
1106 node->next = sknode->next;
1107 sknode->next = node;
1110 /* Note we aren't checking whether this binding sig is a
1111 selfsig. This is not necessary here as the subkey and
1112 binding sig will be rejected later if that is the
1114 if (check_key_signature (ctrl, keyblock,node,NULL))
1116 /* Not a match, so undo the changes. */
1117 sknode->next = node->next;
1124 /* Mark it good so we don't need to check it again */
1125 sknode->flag |= NODE_GOOD_SELFSIG;
1138 /* Versions of GnuPG before 1.4.11 and 2.0.16 allowed to import bogus
1139 direct key signatures. A side effect of this was that a later
1140 import of the same good direct key signatures was not possible
1141 because the cmp_signature check in merge_blocks considered them
1142 equal. Although direct key signatures are now checked during
1143 import, there might still be bogus signatures sitting in a keyring.
1144 We need to detect and delete them before doing a merge. This
1145 function returns the number of removed sigs. */
1147 fix_bad_direct_key_sigs (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid)
1153 for (node = keyblock->next; node; node=node->next)
1155 if (node->pkt->pkttype == PKT_USER_ID)
1157 if (node->pkt->pkttype == PKT_SIGNATURE
1158 && IS_KEY_SIG (node->pkt->pkt.signature))
1160 err = check_key_signature (ctrl, keyblock, node, NULL);
1161 if (err && gpg_err_code (err) != GPG_ERR_PUBKEY_ALGO )
1163 /* If we don't know the error, we can't decide; this is
1164 not a problem because cmp_signature can't compare the
1165 signature either. */
1166 log_info ("key %s: invalid direct key signature removed\n",
1168 delete_kbnode (node);
1179 print_import_ok (PKT_public_key *pk, unsigned int reason)
1181 byte array[MAX_FINGERPRINT_LEN], *s;
1182 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
1185 snprintf (buf, sizeof buf, "%u ", reason);
1186 p = buf + strlen (buf);
1188 fingerprint_from_pk (pk, array, &n);
1190 for (i=0; i < n ; i++, s++, p += 2)
1191 sprintf (p, "%02X", *s);
1193 write_status_text (STATUS_IMPORT_OK, buf);
1198 print_import_check (PKT_public_key * pk, PKT_user_id * id)
1200 byte hexfpr[2*MAX_FINGERPRINT_LEN+1];
1203 keyid_from_pk (pk, keyid);
1204 hexfingerprint (pk, hexfpr, sizeof hexfpr);
1205 write_status_printf (STATUS_IMPORT_CHECK, "%08X%08X %s %s",
1206 keyid[0], keyid[1], hexfpr, id->name);
1212 check_prefs_warning(PKT_public_key *pk)
1214 log_info(_("WARNING: key %s contains preferences for unavailable\n"
1215 "algorithms on these user IDs:\n"), keystr_from_pk(pk));
1220 check_prefs (ctrl_t ctrl, kbnode_t keyblock)
1226 merge_keys_and_selfsig (ctrl, keyblock);
1227 pk=keyblock->pkt->pkt.public_key;
1229 for(node=keyblock;node;node=node->next)
1231 if(node->pkt->pkttype==PKT_USER_ID
1232 && node->pkt->pkt.user_id->created
1233 && node->pkt->pkt.user_id->prefs)
1235 PKT_user_id *uid = node->pkt->pkt.user_id;
1236 prefitem_t *prefs = uid->prefs;
1237 char *user = utf8_to_native(uid->name,strlen(uid->name),0);
1239 for(;prefs->type;prefs++)
1241 char num[10]; /* prefs->value is a byte, so we're over
1244 sprintf(num,"%u",prefs->value);
1246 if(prefs->type==PREFTYPE_SYM)
1248 if (openpgp_cipher_test_algo (prefs->value))
1251 (openpgp_cipher_test_algo (prefs->value)
1253 : openpgp_cipher_algo_name (prefs->value));
1255 check_prefs_warning(pk);
1256 log_info(_(" \"%s\": preference for cipher"
1257 " algorithm %s\n"), user, algo);
1261 else if(prefs->type==PREFTYPE_HASH)
1263 if(openpgp_md_test_algo(prefs->value))
1266 (gcry_md_test_algo (prefs->value)
1268 : gcry_md_algo_name (prefs->value));
1270 check_prefs_warning(pk);
1271 log_info(_(" \"%s\": preference for digest"
1272 " algorithm %s\n"), user, algo);
1276 else if(prefs->type==PREFTYPE_ZIP)
1278 if(check_compress_algo (prefs->value))
1280 const char *algo=compress_algo_to_string(prefs->value);
1282 check_prefs_warning(pk);
1283 log_info(_(" \"%s\": preference for compression"
1284 " algorithm %s\n"),user,algo?algo:num);
1296 log_info(_("it is strongly suggested that you update"
1297 " your preferences and\n"));
1298 log_info(_("re-distribute this key to avoid potential algorithm"
1299 " mismatch problems\n"));
1303 strlist_t sl = NULL;
1304 strlist_t locusr = NULL;
1306 byte fpr[MAX_FINGERPRINT_LEN], *p;
1307 char username[(MAX_FINGERPRINT_LEN*2)+1];
1310 p = fingerprint_from_pk (pk,fpr,&fprlen);
1311 for(i=0;i<fprlen;i++,p++)
1312 sprintf(username+2*i,"%02X",*p);
1313 add_to_strlist(&locusr,username);
1315 append_to_strlist(&sl,"updpref");
1316 append_to_strlist(&sl,"save");
1318 keyedit_menu (ctrl, username, locusr, sl, 1, 1 );
1320 free_strlist(locusr);
1323 log_info(_("you can update your preferences with:"
1324 " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
1329 /* Helper for apply_*_filter in import.c and export.c. */
1331 impex_filter_getval (void *cookie, const char *propname)
1333 /* FIXME: Malloc our static buffers and access them via PARM. */
1334 struct impex_filter_parm_s *parm = cookie;
1335 ctrl_t ctrl = parm->ctrl;
1336 kbnode_t node = parm->node;
1337 static char numbuf[20];
1340 log_assert (ctrl && ctrl->magic == SERVER_CONTROL_MAGIC);
1342 if (node->pkt->pkttype == PKT_USER_ID
1343 || node->pkt->pkttype == PKT_ATTRIBUTE)
1345 PKT_user_id *uid = node->pkt->pkt.user_id;
1347 if (!strcmp (propname, "uid"))
1349 else if (!strcmp (propname, "mbox"))
1353 uid->mbox = mailbox_from_userid (uid->name);
1357 else if (!strcmp (propname, "primary"))
1359 result = uid->flags.primary? "1":"0";
1361 else if (!strcmp (propname, "expired"))
1363 result = uid->flags.expired? "1":"0";
1365 else if (!strcmp (propname, "revoked"))
1367 result = uid->flags.revoked? "1":"0";
1372 else if (node->pkt->pkttype == PKT_SIGNATURE)
1374 PKT_signature *sig = node->pkt->pkt.signature;
1376 if (!strcmp (propname, "sig_created"))
1378 snprintf (numbuf, sizeof numbuf, "%lu", (ulong)sig->timestamp);
1381 else if (!strcmp (propname, "sig_created_d"))
1383 result = datestr_from_sig (sig);
1385 else if (!strcmp (propname, "sig_algo"))
1387 snprintf (numbuf, sizeof numbuf, "%d", sig->pubkey_algo);
1390 else if (!strcmp (propname, "sig_digest_algo"))
1392 snprintf (numbuf, sizeof numbuf, "%d", sig->digest_algo);
1395 else if (!strcmp (propname, "expired"))
1397 result = sig->flags.expired? "1":"0";
1402 else if (node->pkt->pkttype == PKT_PUBLIC_KEY
1403 || node->pkt->pkttype == PKT_SECRET_KEY
1404 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1405 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1407 PKT_public_key *pk = node->pkt->pkt.public_key;
1409 if (!strcmp (propname, "secret"))
1411 result = (node->pkt->pkttype == PKT_SECRET_KEY
1412 || node->pkt->pkttype == PKT_SECRET_SUBKEY)? "1":"0";
1414 else if (!strcmp (propname, "key_algo"))
1416 snprintf (numbuf, sizeof numbuf, "%d", pk->pubkey_algo);
1419 else if (!strcmp (propname, "key_created"))
1421 snprintf (numbuf, sizeof numbuf, "%lu", (ulong)pk->timestamp);
1424 else if (!strcmp (propname, "key_created_d"))
1426 result = datestr_from_pk (pk);
1428 else if (!strcmp (propname, "expired"))
1430 result = pk->has_expired? "1":"0";
1432 else if (!strcmp (propname, "revoked"))
1434 result = pk->flags.revoked? "1":"0";
1436 else if (!strcmp (propname, "disabled"))
1438 result = pk_is_disabled (pk)? "1":"0";
1440 else if (!strcmp (propname, "usage"))
1442 snprintf (numbuf, sizeof numbuf, "%s%s%s%s%s",
1443 (pk->pubkey_usage & PUBKEY_USAGE_ENC)?"e":"",
1444 (pk->pubkey_usage & PUBKEY_USAGE_SIG)?"s":"",
1445 (pk->pubkey_usage & PUBKEY_USAGE_CERT)?"c":"",
1446 (pk->pubkey_usage & PUBKEY_USAGE_AUTH)?"a":"",
1447 (pk->pubkey_usage & PUBKEY_USAGE_UNKNOWN)?"?":"");
1461 * Apply the keep-uid filter to the keyblock. The deleted nodes are
1462 * marked and thus the caller should call commit_kbnode afterwards.
1463 * KEYBLOCK must not have any blocks marked as deleted.
1466 apply_keep_uid_filter (ctrl_t ctrl, kbnode_t keyblock, recsel_expr_t selector)
1469 struct impex_filter_parm_s parm;
1473 for (node = keyblock->next; node; node = node->next )
1475 if (node->pkt->pkttype == PKT_USER_ID)
1478 if (!recsel_select (selector, impex_filter_getval, &parm))
1481 /* log_debug ("keep-uid: deleting '%s'\n", */
1482 /* node->pkt->pkt.user_id->name); */
1483 /* The UID packet and all following packets up to the
1484 * next UID or a subkey. */
1485 delete_kbnode (node);
1487 && node->next->pkt->pkttype != PKT_USER_ID
1488 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1489 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1491 delete_kbnode (node->next);
1494 /* log_debug ("keep-uid: keeping '%s'\n", */
1495 /* node->pkt->pkt.user_id->name); */
1502 * Apply the drop-sig filter to the keyblock. The deleted nodes are
1503 * marked and thus the caller should call commit_kbnode afterwards.
1504 * KEYBLOCK must not have any blocks marked as deleted.
1507 apply_drop_sig_filter (ctrl_t ctrl, kbnode_t keyblock, recsel_expr_t selector)
1513 struct impex_filter_parm_s parm;
1517 keyid_from_pk (keyblock->pkt->pkt.public_key, main_keyid);
1519 /* Loop over all signatures for user id and attribute packets which
1520 * are not self signatures. */
1521 for (node = keyblock->next; node; node = node->next )
1523 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1524 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1526 if (node->pkt->pkttype == PKT_USER_ID
1527 || node->pkt->pkttype == PKT_ATTRIBUTE)
1531 if (node->pkt->pkttype != PKT_SIGNATURE)
1534 sig = node->pkt->pkt.signature;
1535 if (main_keyid[0] == sig->keyid[0] || main_keyid[1] == sig->keyid[1])
1536 continue; /* Skip self-signatures. */
1538 if (IS_UID_SIG(sig) || IS_UID_REV(sig))
1541 if (recsel_select (selector, impex_filter_getval, &parm))
1542 delete_kbnode (node);
1548 /* Insert a key origin into a public key packet. */
1550 insert_key_origin_pk (PKT_public_key *pk, u32 curtime,
1551 int origin, const char *url)
1553 if (origin == KEYORG_WKD || origin == KEYORG_DANE)
1555 /* For WKD and DANE we insert origin information also for the
1556 * key but we don't record the URL because we have have no use
1557 * for that: An update using a keyserver has higher precedence
1558 * and will thus update this origin info. For refresh using WKD
1559 * or DANE we need to go via the User ID anyway. Recall that we
1560 * are only inserting a new key. */
1561 pk->keyorg = origin;
1562 pk->keyupdate = curtime;
1564 else if (origin == KEYORG_KS && url)
1566 /* If the key was retrieved from a keyserver using a fingerprint
1567 * request we add the meta information. Note that the use of a
1568 * fingerprint needs to be enforced by the caller of the import
1569 * function. This is commonly triggered by verifying a modern
1570 * signature which has an Issuer Fingerprint signature
1572 pk->keyorg = origin;
1573 pk->keyupdate = curtime;
1574 xfree (pk->updateurl);
1575 pk->updateurl = xtrystrdup (url);
1577 return gpg_error_from_syserror ();
1579 else if (origin == KEYORG_FILE)
1581 pk->keyorg = origin;
1582 pk->keyupdate = curtime;
1584 else if (origin == KEYORG_URL)
1586 pk->keyorg = origin;
1587 pk->keyupdate = curtime;
1590 xfree (pk->updateurl);
1591 pk->updateurl = xtrystrdup (url);
1593 return gpg_error_from_syserror ();
1601 /* Insert a key origin into a user id packet. */
1603 insert_key_origin_uid (PKT_user_id *uid, u32 curtime,
1604 int origin, const char *url)
1607 if (origin == KEYORG_WKD || origin == KEYORG_DANE)
1609 /* We insert origin information on a UID only when we received
1610 * them via the Web Key Directory or a DANE record. The key we
1611 * receive here from the WKD has been filtered to contain only
1612 * the user ID as looked up in the WKD. For a DANE origin we
1613 * this should also be the case. Thus we will see here only one
1615 uid->keyorg = origin;
1616 uid->keyupdate = curtime;
1619 xfree (uid->updateurl);
1620 uid->updateurl = xtrystrdup (url);
1621 if (!uid->updateurl)
1622 return gpg_error_from_syserror ();
1625 else if (origin == KEYORG_KS && url)
1627 /* If the key was retrieved from a keyserver using a fingerprint
1628 * request we mark that also in the user ID. However we do not
1629 * store the keyserver URL in the UID. A later update (merge)
1630 * from a more trusted source will replace this info. */
1631 uid->keyorg = origin;
1632 uid->keyupdate = curtime;
1634 else if (origin == KEYORG_FILE)
1636 uid->keyorg = origin;
1637 uid->keyupdate = curtime;
1639 else if (origin == KEYORG_URL)
1641 uid->keyorg = origin;
1642 uid->keyupdate = curtime;
1649 /* Apply meta data to KEYBLOCK. This sets the origin of the key to
1650 * ORIGIN and the updateurl to URL. Note that this function is only
1651 * used for a new key, that is not when we are merging keys. */
1653 insert_key_origin (kbnode_t keyblock, int origin, const char *url)
1657 u32 curtime = make_timestamp ();
1659 for (node = keyblock; node; node = node->next)
1661 if (is_deleted_kbnode (node))
1663 else if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1665 err = insert_key_origin_pk (node->pkt->pkt.public_key, curtime,
1670 else if (node->pkt->pkttype == PKT_USER_ID)
1672 err = insert_key_origin_uid (node->pkt->pkt.user_id, curtime,
1683 /* Update meta data on KEYBLOCK. This updates the key origin on the
1684 * public key according to ORIGIN and URL. The UIDs are already
1685 * updated when this function is called. */
1687 update_key_origin (kbnode_t keyblock, u32 curtime, int origin, const char *url)
1691 log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
1692 pk = keyblock->pkt->pkt.public_key;
1694 if (pk->keyupdate > curtime)
1695 ; /* Don't do it for a time warp. */
1696 else if (origin == KEYORG_WKD || origin == KEYORG_DANE)
1698 /* We only update the origin info if they either have never been
1699 * set or are the origin was the same as the new one. If this
1700 * is WKD we also update the UID to show from which user id this
1702 if (!pk->keyorg || pk->keyorg == KEYORG_WKD || pk->keyorg == KEYORG_DANE)
1704 pk->keyorg = origin;
1705 pk->keyupdate = curtime;
1706 xfree (pk->updateurl);
1707 pk->updateurl = NULL;
1708 if (origin == KEYORG_WKD && url)
1710 pk->updateurl = xtrystrdup (url);
1712 return gpg_error_from_syserror ();
1716 else if (origin == KEYORG_KS)
1718 /* All updates from a keyserver are considered to have the
1719 * freshed key. Thus we always set the new key origin. */
1720 pk->keyorg = origin;
1721 pk->keyupdate = curtime;
1722 xfree (pk->updateurl);
1723 pk->updateurl = NULL;
1726 pk->updateurl = xtrystrdup (url);
1728 return gpg_error_from_syserror ();
1731 else if (origin == KEYORG_FILE)
1733 /* Updates from a file are considered to be fresh. */
1734 pk->keyorg = origin;
1735 pk->keyupdate = curtime;
1736 xfree (pk->updateurl);
1737 pk->updateurl = NULL;
1739 else if (origin == KEYORG_URL)
1741 /* Updates from a URL are considered to be fresh. */
1742 pk->keyorg = origin;
1743 pk->keyupdate = curtime;
1744 xfree (pk->updateurl);
1745 pk->updateurl = NULL;
1748 pk->updateurl = xtrystrdup (url);
1750 return gpg_error_from_syserror ();
1759 * Try to import one keyblock. Return an error only in serious cases,
1760 * but never for an invalid keyblock. It uses log_error to increase
1761 * the internal errorcount, so that invalid input can be detected by
1762 * programs which called gpg. If SILENT is no messages are printed -
1763 * even most error messages are suppressed. ORIGIN is the origin of
1764 * the key (0 for unknown) and URL the corresponding URL. FROM_SK
1765 * indicates that the key has been made from a secret key. If R_SAVED
1766 * is not NULL a boolean will be stored indicating whether the keyblock
1770 import_one_real (ctrl_t ctrl,
1771 kbnode_t keyblock, struct import_stats_s *stats,
1772 unsigned char **fpr, size_t *fpr_len, unsigned int options,
1773 int from_sk, int silent,
1774 import_screener_t screener, void *screener_arg,
1775 int origin, const char *url, int *r_valid)
1777 gpg_error_t err = 0;
1779 kbnode_t node, uidnode;
1780 kbnode_t keyblock_orig = NULL;
1781 byte fpr2[MAX_FINGERPRINT_LEN];
1789 char pkstrbuf[PUBKEY_STRING_SIZE];
1790 int merge_keys_done = 0;
1792 KEYDB_HANDLE hd = NULL;
1797 /* If show-only is active we don't won't any extra output. */
1798 if ((options & (IMPORT_SHOW | IMPORT_DRY_RUN)))
1801 /* Get the key and print some info about it. */
1802 node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
1806 pk = node->pkt->pkt.public_key;
1808 fingerprint_from_pk (pk, fpr2, &fpr2len);
1809 for (an = fpr2len; an < MAX_FINGERPRINT_LEN; an++)
1811 keyid_from_pk( pk, keyid );
1812 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1814 if (opt.verbose && !opt.interactive && !silent && !from_sk)
1816 /* Note that we do not print this info in FROM_SK mode
1817 * because import_secret_one already printed that. */
1818 log_info ("pub %s/%s %s ",
1819 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
1820 keystr_from_pk(pk), datestr_from_pk(pk) );
1822 print_utf8_buffer (log_get_stream (),
1823 uidnode->pkt->pkt.user_id->name,
1824 uidnode->pkt->pkt.user_id->len );
1832 log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
1836 if (screener && screener (keyblock, screener_arg))
1838 log_error (_("key %s: %s\n"), keystr_from_pk (pk),
1839 _("rejected by import screener"));
1843 if (opt.interactive && !silent)
1845 if (is_status_enabled())
1846 print_import_check (pk, uidnode->pkt->pkt.user_id);
1847 merge_keys_and_selfsig (ctrl, keyblock);
1849 show_basic_key_info (ctrl, keyblock, from_sk);
1851 if (!cpr_get_answer_is_yes ("import.okay",
1852 "Do you want to import this key? (y/N) "))
1856 /* Remove all non-self-sigs if requested. Noe that this is a NOP if
1857 * that option has been globally set but we may also be called
1858 * latter with the already parsed keyblock and a locally changed
1859 * option. This is why we need to remove them here as well. */
1860 if ((options & IMPORT_SELF_SIGS_ONLY))
1861 remove_all_non_self_sigs (&keyblock, keyid);
1863 collapse_uids(&keyblock);
1865 /* Clean the key that we're about to import, to cut down on things
1866 that we have to clean later. This has no practical impact on the
1867 end result, but does result in less logging which might confuse
1869 if ((options & IMPORT_CLEAN))
1871 merge_keys_and_selfsig (ctrl, keyblock);
1872 clean_all_uids (ctrl, keyblock,
1873 opt.verbose, (options&IMPORT_MINIMAL), NULL, NULL);
1874 clean_all_subkeys (ctrl, keyblock, opt.verbose, KEY_CLEAN_NONE,
1878 clear_kbnode_flags( keyblock );
1880 if ((options&IMPORT_REPAIR_PKS_SUBKEY_BUG)
1881 && fix_pks_corruption (ctrl, keyblock)
1883 log_info (_("key %s: PKS subkey corruption repaired\n"),
1884 keystr_from_pk(pk));
1886 if ((options & IMPORT_REPAIR_KEYS))
1887 key_check_all_keysigs (ctrl, 1, keyblock, 0, 0);
1889 if (chk_self_sigs (ctrl, keyblock, keyid, &non_self))
1890 return 0; /* Invalid keyblock - error already printed. */
1892 /* If we allow such a thing, mark unsigned uids as valid */
1893 if (opt.allow_non_selfsigned_uid)
1895 for (node=keyblock; node; node = node->next )
1896 if (node->pkt->pkttype == PKT_USER_ID
1897 && !(node->flag & NODE_GOOD_SELFSIG)
1898 && !(node->flag & NODE_BAD_SELFSIG) )
1900 char *user=utf8_to_native(node->pkt->pkt.user_id->name,
1901 node->pkt->pkt.user_id->len,0);
1902 /* Fake a good signature status for the user id. */
1903 node->flag |= NODE_GOOD_SELFSIG;
1904 log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
1905 keystr_from_pk(pk),user);
1910 if (!delete_inv_parts (ctrl, keyblock, keyid, options ) )
1914 log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
1916 log_info(_("this may be caused by a missing self-signature\n"));
1918 stats->no_user_id++;
1922 /* Get rid of deleted nodes. */
1923 commit_kbnode (&keyblock);
1925 /* Apply import filter. */
1926 if (import_filter.keep_uid)
1928 apply_keep_uid_filter (ctrl, keyblock, import_filter.keep_uid);
1929 commit_kbnode (&keyblock);
1932 if (import_filter.drop_sig)
1934 apply_drop_sig_filter (ctrl, keyblock, import_filter.drop_sig);
1935 commit_kbnode (&keyblock);
1939 /* If we ran any filter we need to check that at least one user id
1940 * is left in the keyring. Note that we do not use log_error in
1942 if (any_filter && !any_uid_left (keyblock))
1945 log_info ( _("key %s: no valid user IDs\n"), keystr_from_pk (pk));
1946 stats->no_user_id++;
1950 /* The keyblock is valid and ready for real import. */
1954 /* Show the key in the form it is merged or inserted. We skip this
1955 * if "import-export" is also active without --armor or the output
1956 * file has explicily been given. */
1957 if ((options & IMPORT_SHOW)
1958 && !((options & IMPORT_EXPORT) && !opt.armor && !opt.outfile))
1960 merge_keys_and_selfsig (ctrl, keyblock);
1961 merge_keys_done = 1;
1962 /* Note that we do not want to show the validity because the key
1963 * has not yet imported. */
1964 list_keyblock_direct (ctrl, keyblock, from_sk, 0,
1965 opt.fingerprint || opt.with_fingerprint, 1);
1966 es_fflush (es_stdout);
1969 /* Write the keyblock to the output and do not actually import. */
1970 if ((options & IMPORT_EXPORT))
1972 if (!merge_keys_done)
1974 merge_keys_and_selfsig (ctrl, keyblock);
1975 merge_keys_done = 1;
1977 err = write_keyblock_to_output (keyblock, opt.armor, opt.export_options);
1981 if (opt.dry_run || (options & IMPORT_DRY_RUN))
1984 /* Do we have this key already in one of our pubrings ? */
1985 err = get_keyblock_byfprint_fast (&keyblock_orig, &hd,
1986 fpr2, fpr2len, 1/*locked*/);
1988 && gpg_err_code (err) != GPG_ERR_NO_PUBKEY
1989 && gpg_err_code (err) != GPG_ERR_UNUSABLE_PUBKEY)
1992 /* The !hd above is to catch a misbehaving function which
1993 * returns NO_PUBKEY for failing to allocate a handle. */
1995 log_error (_("key %s: public key not found: %s\n"),
1996 keystr(keyid), gpg_strerror (err));
1998 else if (err && (opt.import_options&IMPORT_MERGE_ONLY) )
2000 if (opt.verbose && !silent )
2001 log_info( _("key %s: new key - skipped\n"), keystr(keyid));
2003 stats->skipped_new_keys++;
2005 else if (err) /* Insert this key. */
2007 /* Note: ERR can only be NO_PUBKEY or UNUSABLE_PUBKEY. */
2008 int n_sigs_cleaned, n_uids_cleaned;
2010 err = keydb_locate_writable (hd);
2013 log_error (_("no writable keyring found: %s\n"), gpg_strerror (err));
2014 err = gpg_error (GPG_ERR_GENERAL);
2017 if (opt.verbose > 1 )
2018 log_info (_("writing to '%s'\n"), keydb_get_resource_name (hd) );
2020 if ((options & IMPORT_CLEAN))
2022 merge_keys_and_selfsig (ctrl, keyblock);
2023 clean_all_uids (ctrl, keyblock, opt.verbose, (options&IMPORT_MINIMAL),
2024 &n_uids_cleaned,&n_sigs_cleaned);
2025 clean_all_subkeys (ctrl, keyblock, opt.verbose, KEY_CLEAN_NONE,
2029 /* Unless we are in restore mode apply meta data to the
2030 * keyblock. Note that this will never change the first packet
2031 * and thus the address of KEYBLOCK won't change. */
2032 if ( !(options & IMPORT_RESTORE) )
2034 err = insert_key_origin (keyblock, origin, url);
2037 log_error ("insert_key_origin failed: %s\n", gpg_strerror (err));
2038 err = gpg_error (GPG_ERR_GENERAL);
2043 err = keydb_insert_keyblock (hd, keyblock );
2045 log_error (_("error writing keyring '%s': %s\n"),
2046 keydb_get_resource_name (hd), gpg_strerror (err));
2047 else if (!(opt.import_options & IMPORT_KEEP_OWNERTTRUST))
2049 /* This should not be possible since we delete the
2050 ownertrust when a key is deleted, but it can happen if
2051 the keyring and trustdb are out of sync. It can also
2052 be made to happen with the trusted-key command and by
2053 importing and locally exported key. */
2055 clear_ownertrusts (ctrl, pk);
2057 revalidation_mark (ctrl);
2060 /* Release the handle and thus unlock the keyring asap. */
2065 if (!err && !opt.quiet && !silent)
2067 char *p = get_user_id_byfpr_native (ctrl, fpr2);
2068 log_info (_("key %s: public key \"%s\" imported\n"),
2072 if (!err && is_status_enabled())
2074 char *us = get_long_user_id_string (ctrl, keyid);
2075 write_status_text( STATUS_IMPORTED, us );
2077 print_import_ok (pk, 1);
2085 else /* Key already exists - merge. */
2087 int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
2088 u32 curtime = make_timestamp ();
2090 /* Compare the original against the new key; just to be sure nothing
2091 * weird is going on */
2092 if (cmp_public_keys (keyblock_orig->pkt->pkt.public_key, pk))
2095 log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
2099 /* Make sure the original direct key sigs are all sane. */
2100 n_sigs_cleaned = fix_bad_direct_key_sigs (ctrl, keyblock_orig, keyid);
2102 commit_kbnode (&keyblock_orig);
2104 /* Try to merge KEYBLOCK into KEYBLOCK_ORIG. */
2105 clear_kbnode_flags( keyblock_orig );
2106 clear_kbnode_flags( keyblock );
2107 n_uids = n_sigs = n_subk = n_uids_cleaned = 0;
2108 err = merge_blocks (ctrl, options, keyblock_orig, keyblock, keyid,
2109 curtime, origin, url,
2110 &n_uids, &n_sigs, &n_subk );
2114 if ((options & IMPORT_CLEAN))
2116 merge_keys_and_selfsig (ctrl, keyblock_orig);
2117 clean_all_uids (ctrl, keyblock_orig, opt.verbose,
2118 (options&IMPORT_MINIMAL),
2119 &n_uids_cleaned,&n_sigs_cleaned);
2120 clean_all_subkeys (ctrl, keyblock_orig, opt.verbose, KEY_CLEAN_NONE,
2124 if (n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned)
2126 /* Unless we are in restore mode apply meta data to the
2127 * keyblock. Note that this will never change the first packet
2128 * and thus the address of KEYBLOCK won't change. */
2129 if ( !(options & IMPORT_RESTORE) )
2131 err = update_key_origin (keyblock_orig, curtime, origin, url);
2134 log_error ("update_key_origin failed: %s\n",
2135 gpg_strerror (err));
2141 /* KEYBLOCK_ORIG has been updated; write */
2142 err = keydb_update_keyblock (ctrl, hd, keyblock_orig);
2144 log_error (_("error writing keyring '%s': %s\n"),
2145 keydb_get_resource_name (hd), gpg_strerror (err));
2147 revalidation_mark (ctrl);
2149 /* Release the handle and thus unlock the keyring asap. */
2153 /* We are ready. Print and update stats if we got no error.
2154 * An error here comes from writing the keyblock and thus
2155 * very likely means that no update happened. */
2156 if (!err && !opt.quiet && !silent)
2158 char *p = get_user_id_byfpr_native (ctrl, fpr2);
2160 log_info( _("key %s: \"%s\" 1 new user ID\n"),
2163 log_info( _("key %s: \"%s\" %d new user IDs\n"),
2164 keystr(keyid),p,n_uids);
2166 log_info( _("key %s: \"%s\" 1 new signature\n"),
2169 log_info( _("key %s: \"%s\" %d new signatures\n"),
2170 keystr(keyid), p, n_sigs );
2172 log_info( _("key %s: \"%s\" 1 new subkey\n"),
2175 log_info( _("key %s: \"%s\" %d new subkeys\n"),
2176 keystr(keyid), p, n_subk );
2177 if (n_sigs_cleaned==1)
2178 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
2179 keystr(keyid),p,n_sigs_cleaned);
2180 else if (n_sigs_cleaned)
2181 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
2182 keystr(keyid),p,n_sigs_cleaned);
2183 if (n_uids_cleaned==1)
2184 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
2185 keystr(keyid),p,n_uids_cleaned);
2186 else if (n_uids_cleaned)
2187 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
2188 keystr(keyid),p,n_uids_cleaned);
2194 stats->n_uids +=n_uids;
2195 stats->n_sigs +=n_sigs;
2196 stats->n_subk +=n_subk;
2197 stats->n_sigs_cleaned +=n_sigs_cleaned;
2198 stats->n_uids_cleaned +=n_uids_cleaned;
2200 if (is_status_enabled () && !silent)
2201 print_import_ok (pk, ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
2206 /* Release the handle and thus unlock the keyring asap. */
2210 /* FIXME: We do not track the time we last checked a key for
2211 * updates. To do this we would need to rewrite even the
2212 * keys which have no changes. Adding this would be useful
2213 * for the automatic update of expired keys via the WKD in
2214 * case the WKD still carries the expired key. See
2215 * get_best_pubkey_byname. */
2217 if (is_status_enabled ())
2218 print_import_ok (pk, 0);
2220 if (!opt.quiet && !silent)
2222 char *p = get_user_id_byfpr_native (ctrl, fpr2);
2223 log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
2233 if (mod_key || new_key || same_key)
2235 /* A little explanation for this: we fill in the fingerprint
2236 when importing keys as it can be useful to know the
2237 fingerprint in certain keyserver-related cases (a keyserver
2238 asked for a particular name, but the key doesn't have that
2239 name). However, in cases where we're importing more than
2240 one key at a time, we cannot know which key to fingerprint.
2241 In these cases, rather than guessing, we do not
2242 fingerprinting at all, and we must hope the user ID on the
2243 keys are useful. Note that we need to do this for new
2244 keys, merged keys and even for unchanged keys. This is
2245 required because for example the --auto-key-locate feature
2246 may import an already imported key and needs to know the
2247 fingerprint of the key in all cases. */
2250 /* Note that we need to compare against 0 here because
2251 COUNT gets only incremented after returning from this
2256 *fpr = fingerprint_from_pk (pk, NULL, fpr_len);
2258 else if (origin != KEYORG_WKD)
2266 /* Now that the key is definitely incorporated into the keydb, we
2267 need to check if a designated revocation is present or if the
2268 prefs are not rational so we can warn the user. */
2272 revocation_present (ctrl, keyblock_orig);
2273 if (!from_sk && have_secret_key_with_kid (keyid))
2274 check_prefs (ctrl, keyblock_orig);
2278 revocation_present (ctrl, keyblock);
2279 if (!from_sk && have_secret_key_with_kid (keyid))
2280 check_prefs (ctrl, keyblock);
2283 release_kbnode( keyblock_orig );
2289 /* Wrapper around import_one_real to retry the import in some cases. */
2291 import_one (ctrl_t ctrl,
2292 kbnode_t keyblock, struct import_stats_s *stats,
2293 unsigned char **fpr, size_t *fpr_len, unsigned int options,
2294 int from_sk, int silent,
2295 import_screener_t screener, void *screener_arg,
2296 int origin, const char *url, int *r_valid)
2300 err = import_one_real (ctrl, keyblock, stats, fpr, fpr_len, options,
2301 from_sk, silent, screener, screener_arg,
2302 origin, url, r_valid);
2303 if (gpg_err_code (err) == GPG_ERR_TOO_LARGE
2304 && gpg_err_source (err) == GPG_ERR_SOURCE_KEYBOX
2305 && ((options & (IMPORT_SELF_SIGS_ONLY | IMPORT_CLEAN))
2306 != (IMPORT_SELF_SIGS_ONLY | IMPORT_CLEAN)))
2308 /* We hit the maximum image length. Ask the wrapper to do
2309 * everything again but this time with some extra options. */
2312 keyid_from_pk (keyblock->pkt->pkt.public_key, keyid);
2313 log_info ("key %s: keyblock too large, retrying with self-sigs-only\n",
2315 options |= IMPORT_SELF_SIGS_ONLY | IMPORT_CLEAN;
2316 err = import_one_real (ctrl, keyblock, stats, fpr, fpr_len, options,
2317 from_sk, silent, screener, screener_arg,
2318 origin, url, r_valid);
2324 /* Transfer all the secret keys in SEC_KEYBLOCK to the gpg-agent. The
2325 * function prints diagnostics and returns an error code. If BATCH is
2326 * true the secret keys are stored by gpg-agent in the transfer format
2327 * (i.e. no re-protection and aksing for passphrases). If ONLY_MARKED
2328 * is set, only those nodes with flag NODE_TRANSFER_SECKEY are
2331 transfer_secret_keys (ctrl_t ctrl, struct import_stats_s *stats,
2332 kbnode_t sec_keyblock, int batch, int force,
2335 gpg_error_t err = 0;
2338 kbnode_t ctx = NULL;
2340 PKT_public_key *main_pk, *pk;
2341 struct seckey_info *ski;
2345 void *format_args[2*PUBKEY_MAX_NSKEY];
2346 gcry_sexp_t skey, prot, tmpsexp;
2347 gcry_sexp_t curve = NULL;
2348 unsigned char *transferkey = NULL;
2349 size_t transferkeylen;
2350 gcry_cipher_hd_t cipherhd = NULL;
2351 unsigned char *wrappedkey = NULL;
2352 size_t wrappedkeylen;
2353 char *cache_nonce = NULL;
2354 int stub_key_skipped = 0;
2356 /* Get the current KEK. */
2357 err = agent_keywrap_key (ctrl, 0, &kek, &keklen);
2360 log_error ("error getting the KEK: %s\n", gpg_strerror (err));
2364 /* Prepare a cipher context. */
2365 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
2366 GCRY_CIPHER_MODE_AESWRAP, 0);
2368 err = gcry_cipher_setkey (cipherhd, kek, keklen);
2374 /* Note: We need to use walk_kbnode so that we skip nodes which are
2375 * marked as deleted. */
2377 while ((node = walk_kbnode (sec_keyblock, &ctx, 0)))
2379 if (node->pkt->pkttype != PKT_SECRET_KEY
2380 && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2382 if (only_marked && !(node->flag & NODE_TRANSFER_SECKEY))
2384 pk = node->pkt->pkt.public_key;
2388 /* Make sure the keyids are available. */
2389 keyid_from_pk (pk, NULL);
2390 if (node->pkt->pkttype == PKT_SECRET_KEY)
2392 pk->main_keyid[0] = pk->keyid[0];
2393 pk->main_keyid[1] = pk->keyid[1];
2397 pk->main_keyid[0] = main_pk->keyid[0];
2398 pk->main_keyid[1] = main_pk->keyid[1];
2402 ski = pk->seckey_info;
2409 stats->secret_read++;
2412 /* We ignore stub keys. The way we handle them in other parts
2413 of the code is by asking the agent whether any secret key is
2414 available for a given keyblock and then concluding that we
2415 have a secret key; all secret (sub)keys of the keyblock the
2416 agent does not know of are then stub keys. This works also
2417 for card stub keys. The learn command or the card-status
2418 command may be used to check with the agent whether a card
2419 has been inserted and a stub key is in turn generated by the
2421 if (ski->s2k.mode == 1001 || ski->s2k.mode == 1002)
2423 stub_key_skipped = 1;
2427 /* Convert our internal secret key object into an S-expression. */
2428 nskey = pubkey_get_nskey (pk->pubkey_algo);
2429 if (!nskey || nskey > PUBKEY_MAX_NSKEY)
2431 err = gpg_error (GPG_ERR_BAD_SECKEY);
2432 log_error ("internal error: %s\n", gpg_strerror (err));
2436 init_membuf (&mbuf, 50);
2437 put_membuf_str (&mbuf, "(skey");
2438 if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
2439 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
2440 || pk->pubkey_algo == PUBKEY_ALGO_ECDH)
2443 char *curvestr = openpgp_oid_to_str (pk->pkey[0]);
2445 err = gpg_error_from_syserror ();
2448 const char *curvename = openpgp_oid_to_curve (curvestr, 1);
2449 gcry_sexp_release (curve);
2450 err = gcry_sexp_build (&curve, NULL, "(curve %s)",
2451 curvename?curvename:curvestr);
2456 /* Append the public key element Q. */
2457 put_membuf_str (&mbuf, " _ %m");
2458 format_args[j++] = pk->pkey + 1;
2460 /* Append the secret key element D. For ECDH we
2461 skip PKEY[2] because this holds the KEK which is
2462 not needed by gpg-agent. */
2463 i = pk->pubkey_algo == PUBKEY_ALGO_ECDH? 3 : 2;
2464 if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
2465 put_membuf_str (&mbuf, " e %m");
2467 put_membuf_str (&mbuf, " _ %m");
2468 format_args[j++] = pk->pkey + i;
2474 /* Standard case for the old (non-ECC) algorithms. */
2475 for (i=j=0; i < nskey; i++)
2478 continue; /* Protected keys only have NPKEY+1 elements. */
2480 if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
2481 put_membuf_str (&mbuf, " e %m");
2483 put_membuf_str (&mbuf, " _ %m");
2484 format_args[j++] = pk->pkey + i;
2487 put_membuf_str (&mbuf, ")");
2488 put_membuf (&mbuf, "", 1);
2490 xfree (get_membuf (&mbuf, NULL));
2493 char *format = get_membuf (&mbuf, NULL);
2495 err = gpg_error_from_syserror ();
2497 err = gcry_sexp_build_array (&skey, NULL, format, format_args);
2502 log_error ("error building skey array: %s\n", gpg_strerror (err));
2506 if (ski->is_protected)
2510 /* Note that the IVLEN may be zero if we are working on a
2511 dummy key. We can't express that in an S-expression and
2512 thus we send dummy data for the IV. */
2513 snprintf (countbuf, sizeof countbuf, "%lu",
2514 (unsigned long)ski->s2k.count);
2515 err = gcry_sexp_build
2517 " (protection %s %s %b %d %s %b %s)\n",
2518 ski->sha1chk? "sha1":"sum",
2519 openpgp_cipher_algo_name (ski->algo),
2520 ski->ivlen? (int)ski->ivlen:1,
2521 ski->ivlen? ski->iv: (const unsigned char*)"X",
2523 openpgp_md_algo_name (ski->s2k.hash_algo),
2524 (int)sizeof (ski->s2k.salt), ski->s2k.salt,
2528 err = gcry_sexp_build (&prot, NULL, " (protection none)\n");
2531 xfree (transferkey);
2534 err = gcry_sexp_build (&tmpsexp, NULL,
2535 "(openpgp-private-key\n"
2542 openpgp_pk_algo_name (pk->pubkey_algo),
2544 (int)(unsigned long)ski->csum, prot);
2545 gcry_sexp_release (skey);
2546 gcry_sexp_release (prot);
2548 err = make_canon_sexp_pad (tmpsexp, 1, &transferkey, &transferkeylen);
2549 gcry_sexp_release (tmpsexp);
2552 log_error ("error building transfer key: %s\n", gpg_strerror (err));
2557 wrappedkeylen = transferkeylen + 8;
2559 wrappedkey = xtrymalloc (wrappedkeylen);
2561 err = gpg_error_from_syserror ();
2563 err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen,
2564 transferkey, transferkeylen);
2567 xfree (transferkey);
2570 /* Send the wrapped key to the agent. */
2572 char *desc = gpg_format_keydesc (ctrl, pk, FORMAT_KEYDESC_IMPORT, 1);
2573 err = agent_import_key (ctrl, desc, &cache_nonce,
2574 wrappedkey, wrappedkeylen, batch, force,
2575 pk->keyid, pk->main_keyid, pk->pubkey_algo);
2581 log_info (_("key %s: secret key imported\n"),
2582 keystr_from_pk_with_sub (main_pk, pk));
2584 stats->secret_imported++;
2586 else if ( gpg_err_code (err) == GPG_ERR_EEXIST )
2589 log_info (_("key %s: secret key already exists\n"),
2590 keystr_from_pk_with_sub (main_pk, pk));
2593 stats->secret_dups++;
2597 log_error (_("key %s: error sending to agent: %s\n"),
2598 keystr_from_pk_with_sub (main_pk, pk),
2599 gpg_strerror (err));
2600 if (gpg_err_code (err) == GPG_ERR_CANCELED
2601 || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
2602 break; /* Don't try the other subkeys. */
2606 if (!err && stub_key_skipped)
2607 /* We need to notify user how to migrate stub keys. */
2608 err = gpg_error (GPG_ERR_NOT_PROCESSED);
2611 gcry_sexp_release (curve);
2612 xfree (cache_nonce);
2614 xfree (transferkey);
2615 gcry_cipher_close (cipherhd);
2621 /* Walk a secret keyblock and produce a public keyblock out of it.
2622 * Returns a new node or NULL on error. Modifies the tag field of the
2625 sec_to_pub_keyblock (kbnode_t sec_keyblock)
2627 kbnode_t pub_keyblock = NULL;
2628 kbnode_t ctx = NULL;
2629 kbnode_t secnode, pubnode;
2630 unsigned int tag = 0;
2632 /* Set a tag to all nodes. */
2633 for (secnode = sec_keyblock; secnode; secnode = secnode->next)
2634 secnode->tag = ++tag;
2637 while ((secnode = walk_kbnode (sec_keyblock, &ctx, 0)))
2639 if (secnode->pkt->pkttype == PKT_SECRET_KEY
2640 || secnode->pkt->pkttype == PKT_SECRET_SUBKEY)
2642 /* Make a public key. */
2646 pkt = xtrycalloc (1, sizeof *pkt);
2647 pk = pkt? copy_public_key (NULL, secnode->pkt->pkt.public_key): NULL;
2651 release_kbnode (pub_keyblock);
2654 if (secnode->pkt->pkttype == PKT_SECRET_KEY)
2655 pkt->pkttype = PKT_PUBLIC_KEY;
2657 pkt->pkttype = PKT_PUBLIC_SUBKEY;
2658 pkt->pkt.public_key = pk;
2660 pubnode = new_kbnode (pkt);
2664 pubnode = clone_kbnode (secnode);
2666 pubnode->tag = secnode->tag;
2669 pub_keyblock = pubnode;
2671 add_kbnode (pub_keyblock, pubnode);
2674 return pub_keyblock;
2678 /* Delete all notes in the keyblock at R_KEYBLOCK which are not in
2679 * PUB_KEYBLOCK. Modifies the tags of both keyblock's nodes. */
2681 resync_sec_with_pub_keyblock (kbnode_t *r_keyblock, kbnode_t pub_keyblock,
2682 kbnode_t *r_removedsecs)
2684 kbnode_t sec_keyblock = *r_keyblock;
2685 kbnode_t node, prevnode;
2686 unsigned int *taglist;
2687 unsigned int ntaglist, n;
2688 kbnode_t attic = NULL;
2689 kbnode_t *attic_head = &attic;
2691 /* Collect all tags in an array for faster searching. */
2692 for (ntaglist = 0, node = pub_keyblock; node; node = node->next)
2694 taglist = xtrycalloc (ntaglist, sizeof *taglist);
2696 return gpg_error_from_syserror ();
2697 for (ntaglist = 0, node = pub_keyblock; node; node = node->next)
2698 taglist[ntaglist++] = node->tag;
2700 /* Walks over the secret keyblock and delete all nodes which are not
2701 * in the tag list. Those nodes have been deleted in the
2702 * pub_keyblock. Sequential search is a bit lazy and could be
2703 * optimized by sorting and bsearch; however secret keyrings are
2704 * short and there are easier ways to DoS the import. */
2706 for (prevnode=NULL, node=sec_keyblock; node; prevnode=node, node=node->next)
2708 for (n=0; n < ntaglist; n++)
2709 if (taglist[n] == node->tag)
2711 if (n == ntaglist) /* Not in public keyblock. */
2713 if (node->pkt->pkttype == PKT_SECRET_KEY
2714 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
2717 sec_keyblock = node->next;
2719 prevnode->next = node->next;
2722 attic_head = &node->next;
2723 goto again; /* That's lame; I know. */
2726 delete_kbnode (node);
2732 /* Commit the as deleted marked nodes and return the possibly
2733 * modified keyblock and a list of removed secret key nodes. */
2734 commit_kbnode (&sec_keyblock);
2735 *r_keyblock = sec_keyblock;
2736 *r_removedsecs = attic;
2741 /* Helper for import_secret_one. */
2743 do_transfer (ctrl_t ctrl, kbnode_t keyblock, PKT_public_key *pk,
2744 struct import_stats_s *stats, int batch, int only_marked)
2748 struct import_stats_s subkey_stats = {0};
2750 err = transfer_secret_keys (ctrl, &subkey_stats, keyblock,
2751 batch, 0, only_marked);
2752 if (gpg_err_code (err) == GPG_ERR_NOT_PROCESSED)
2754 /* TRANSLATORS: For a smartcard, each private key on host has a
2755 * reference (stub) to a smartcard and actual private key data
2756 * is stored on the card. A single smartcard can have up to
2757 * three private key data. Importing private key stub is always
2758 * skipped in 2.1, and it returns GPG_ERR_NOT_PROCESSED.
2759 * Instead, user should be suggested to run 'gpg --card-status',
2760 * then, references to a card will be automatically created
2762 log_info (_("To migrate '%s', with each smartcard, "
2763 "run: %s\n"), "secring.gpg", "gpg --card-status");
2772 log_info (_("key %s: secret key imported\n"), keystr_from_pk (pk));
2773 if (subkey_stats.secret_imported)
2776 stats->secret_imported += 1;
2778 if (subkey_stats.secret_dups)
2779 stats->secret_dups += 1;
2781 if (is_status_enabled ())
2782 print_import_ok (pk, status);
2789 /* If the secret keys (main or subkey) in SECKEYS have a corresponding
2790 * public key in the public key described by (FPR,FPRLEN) import these
2794 import_matching_seckeys (ctrl_t ctrl, kbnode_t seckeys,
2795 const byte *mainfpr, size_t mainfprlen,
2796 struct import_stats_s *stats, int batch)
2799 kbnode_t pub_keyblock = NULL;
2801 struct { byte fpr[MAX_FINGERPRINT_LEN]; size_t fprlen; } *fprlist = NULL;
2803 byte fpr[MAX_FINGERPRINT_LEN];
2807 /* Get the entire public key block from our keystore and put all its
2808 * fingerprints into an array. */
2809 err = get_pubkey_byfprint (ctrl, NULL, &pub_keyblock, mainfpr, mainfprlen);
2812 log_assert (pub_keyblock && pub_keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
2813 pk = pub_keyblock->pkt->pkt.public_key;
2815 for (nfprlist = 0, node = pub_keyblock; node; node = node->next)
2816 if (node->pkt->pkttype == PKT_PUBLIC_KEY
2817 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2819 log_assert (nfprlist);
2820 fprlist = xtrycalloc (nfprlist, sizeof *fprlist);
2823 err = gpg_error_from_syserror ();
2826 for (n = 0, node = pub_keyblock; node; node = node->next)
2827 if (node->pkt->pkttype == PKT_PUBLIC_KEY
2828 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2830 fingerprint_from_pk (node->pkt->pkt.public_key,
2831 fprlist[n].fpr, &fprlist[n].fprlen);
2834 log_assert (n == nfprlist);
2836 /* for (n=0; n < nfprlist; n++) */
2837 /* log_printhex (fprlist[n].fpr, fprlist[n].fprlen, "pubkey %zu:", n); */
2839 /* Mark all secret keys which have a matching public key part in
2841 for (node = seckeys; node; node = node->next)
2843 if (node->pkt->pkttype != PKT_SECRET_KEY
2844 && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2845 continue; /* Should not happen. */
2846 fingerprint_from_pk (node->pkt->pkt.public_key, fpr, &fprlen);
2847 node->flag &= ~NODE_TRANSFER_SECKEY;
2848 for (n=0; n < nfprlist; n++)
2849 if (fprlist[n].fprlen == fprlen && !memcmp (fprlist[n].fpr,fpr,fprlen))
2851 node->flag |= NODE_TRANSFER_SECKEY;
2852 /* log_debug ("found matching seckey\n"); */
2857 /* Transfer all marked keys. */
2858 err = do_transfer (ctrl, seckeys, pk, stats, batch, 1);
2862 release_kbnode (pub_keyblock);
2867 /* Import function for a single secret keyblock. Handling is simpler
2868 * than for public keys. We allow secret key importing only when
2869 * allow is true, this is so that a secret key can not be imported
2870 * accidentally and thereby tampering with the trust calculation.
2872 * Ownership of KEYBLOCK is transferred to this function!
2874 * If R_SECATTIC is not null the last special sec_keyblock is stored
2878 import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
2879 struct import_stats_s *stats, int batch,
2880 unsigned int options, int for_migration,
2881 import_screener_t screener, void *screener_arg,
2882 kbnode_t *r_secattic)
2885 struct seckey_info *ski;
2886 kbnode_t node, uidnode;
2888 gpg_error_t err = 0;
2890 kbnode_t pub_keyblock;
2891 kbnode_t attic = NULL;
2892 byte fpr[MAX_FINGERPRINT_LEN];
2894 char pkstrbuf[PUBKEY_STRING_SIZE];
2896 /* Get the key and print some info about it */
2897 node = find_kbnode (keyblock, PKT_SECRET_KEY);
2901 pk = node->pkt->pkt.public_key;
2903 fingerprint_from_pk (pk, fpr, &fprlen);
2904 keyid_from_pk (pk, keyid);
2905 uidnode = find_next_kbnode (keyblock, PKT_USER_ID);
2907 if (screener && screener (keyblock, screener_arg))
2909 log_error (_("secret key %s: %s\n"), keystr_from_pk (pk),
2910 _("rejected by import screener"));
2911 release_kbnode (keyblock);
2915 if (opt.verbose && !for_migration)
2917 log_info ("sec %s/%s %s ",
2918 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
2919 keystr_from_pk (pk), datestr_from_pk (pk));
2921 print_utf8_buffer (log_get_stream (), uidnode->pkt->pkt.user_id->name,
2922 uidnode->pkt->pkt.user_id->len);
2925 stats->secret_read++;
2927 if ((options & IMPORT_NO_SECKEY))
2930 log_error (_("importing secret keys not allowed\n"));
2931 release_kbnode (keyblock);
2938 log_error( _("key %s: no user ID\n"), keystr_from_pk (pk));
2939 release_kbnode (keyblock);
2943 ski = pk->seckey_info;
2946 /* Actually an internal error. */
2947 log_error ("key %s: secret key info missing\n", keystr_from_pk (pk));
2948 release_kbnode (keyblock);
2952 /* A quick check to not import keys with an invalid protection
2953 cipher algorithm (only checks the primary key, though). */
2954 if (ski->algo > 110)
2957 log_error (_("key %s: secret key with invalid cipher %d"
2958 " - skipped\n"), keystr_from_pk (pk), ski->algo);
2959 release_kbnode (keyblock);
2963 #ifdef ENABLE_SELINUX_HACKS
2966 /* We don't allow importing secret keys because that may be used
2967 to put a secret key into the keyring and the user might later
2968 be tricked into signing stuff with that key. */
2969 log_error (_("importing secret keys not allowed\n"));
2970 release_kbnode (keyblock);
2975 clear_kbnode_flags (keyblock);
2977 nr_prev = stats->skipped_new_keys;
2979 /* Make a public key out of the key. */
2980 pub_keyblock = sec_to_pub_keyblock (keyblock);
2983 err = gpg_error_from_syserror ();
2984 log_error ("key %s: failed to create public key from secret key\n",
2985 keystr_from_pk (pk));
2991 /* Note that this outputs an IMPORT_OK status message for the
2992 public key block, and below we will output another one for
2993 the secret keys. FIXME? */
2994 import_one (ctrl, pub_keyblock, stats,
2995 NULL, NULL, options, 1, for_migration,
2996 screener, screener_arg, 0, NULL, &valid);
2998 /* The secret keyblock may not have nodes which are deleted in
2999 * the public keyblock. Otherwise we would import just the
3000 * secret key without having the public key. That would be
3001 * surprising and clutters our private-keys-v1.d. */
3002 err = resync_sec_with_pub_keyblock (&keyblock, pub_keyblock, &attic);
3008 /* If the block was not valid the primary key is left in the
3009 * original keyblock because we require that for the first
3010 * node. Move it to ATTIC. */
3011 if (keyblock && keyblock->pkt->pkttype == PKT_SECRET_KEY)
3014 keyblock = node->next;
3025 /* Try to import the secret key iff we have a public key. */
3026 if (attic && !(opt.dry_run || (options & IMPORT_DRY_RUN)))
3027 err = import_matching_seckeys (ctrl, attic, fpr, fprlen,
3030 err = gpg_error (GPG_ERR_NO_SECKEY);
3034 /* log_debug ("attic is:\n"); */
3035 /* dump_kbnode (attic); */
3037 /* Proceed with the valid parts of PUBKEYBLOCK. */
3039 /* At least we cancel the secret key import when the public key
3040 import was skipped due to MERGE_ONLY option and a new
3042 if (!(opt.dry_run || (options & IMPORT_DRY_RUN))
3043 && stats->skipped_new_keys <= nr_prev)
3045 /* Read the keyblock again to get the effects of a merge for
3046 * the public key. */
3047 err = get_pubkey_byfprint (ctrl, NULL, &node, fpr, fprlen);
3049 log_error ("key %s: failed to re-lookup public key: %s\n",
3050 keystr_from_pk (pk), gpg_strerror (err));
3053 err = do_transfer (ctrl, keyblock, pk, stats, batch, 0);
3055 check_prefs (ctrl, node);
3056 release_kbnode (node);
3060 /* Try to import invalid subkeys. This can be the
3061 * case if the primary secret key was imported due
3062 * to --allow-non-selfsigned-uid. */
3063 err = import_matching_seckeys (ctrl, attic, fpr, fprlen,
3072 release_kbnode (keyblock);
3073 release_kbnode (pub_keyblock);
3075 *r_secattic = attic;
3077 release_kbnode (attic);
3083 /* Return the recocation reason from signature SIG. If no revocation
3084 * reason is availabale 0 is returned, in other cases the reason
3085 * (0..255). If R_REASON is not NULL a malloced textual
3086 * representation of the code is stored there. If R_COMMENT is not
3087 * NULL the comment from the reason is stored there and its length at
3088 * R_COMMENTLEN. Note that the value at R_COMMENT is not filtered but
3089 * user supplied data in UTF8; thus it needs to be escaped for display
3090 * purposes. Both return values are either NULL or a malloced
3093 get_revocation_reason (PKT_signature *sig, char **r_reason,
3094 char **r_comment, size_t *r_commentlen)
3098 const byte *reason_p;
3099 char reason_code_buf[20];
3100 const char *reason_text = NULL;
3101 int reason_code = 0;
3108 /* Skip over empty reason packets. */
3109 while ((reason_p = enum_sig_subpkt (sig->hashed, SIGSUBPKT_REVOC_REASON,
3110 &reason_n, &reason_seq, NULL))
3115 reason_code = *reason_p;
3116 reason_n--; reason_p++;
3117 switch (reason_code)
3119 case 0x00: reason_text = _("No reason specified"); break;
3120 case 0x01: reason_text = _("Key is superseded"); break;
3121 case 0x02: reason_text = _("Key has been compromised"); break;
3122 case 0x03: reason_text = _("Key is no longer used"); break;
3123 case 0x20: reason_text = _("User ID is no longer valid"); break;
3125 snprintf (reason_code_buf, sizeof reason_code_buf,
3126 "code=%02x", reason_code);
3127 reason_text = reason_code_buf;
3132 *r_reason = xstrdup (reason_text);
3134 if (r_comment && reason_n)
3136 *r_comment = xmalloc (reason_n);
3137 memcpy (*r_comment, reason_p, reason_n);
3138 *r_commentlen = reason_n;
3146 /* List the recocation signature as a "rvs" record. SIGRC shows the
3147 * character from the signature verification or 0 if no public key was
3150 list_standalone_revocation (ctrl_t ctrl, PKT_signature *sig, int sigrc)
3152 char *siguid = NULL;
3153 size_t siguidlen = 0;
3154 char *issuer_fpr = NULL;
3155 int reason_code = 0;
3156 char *reason_text = NULL;
3157 char *reason_comment = NULL;
3158 size_t reason_commentlen;
3160 if (sigrc != '%' && sigrc != '?' && !opt.fast_list_mode)
3163 siguid = get_user_id (ctrl, sig->keyid, &siguidlen, &nouid);
3168 reason_code = get_revocation_reason (sig, &reason_text,
3169 &reason_comment, &reason_commentlen);
3171 if (opt.with_colons)
3173 es_fputs ("rvs:", es_stdout);
3175 es_putc (sigrc, es_stdout);
3176 es_fprintf (es_stdout, "::%d:%08lX%08lX:%s:%s:::",
3178 (ulong) sig->keyid[0], (ulong) sig->keyid[1],
3179 colon_datestr_from_sig (sig),
3180 colon_expirestr_from_sig (sig));
3183 es_write_sanitized (es_stdout, siguid, siguidlen, ":", NULL);
3185 es_fprintf (es_stdout, ":%02x%c", sig->sig_class,
3186 sig->flags.exportable ? 'x' : 'l');
3188 es_fprintf (es_stdout, ",%02x", reason_code);
3189 es_fputs ("::", es_stdout);
3191 if ((issuer_fpr = issuer_fpr_string (sig)))
3192 es_fputs (issuer_fpr, es_stdout);
3194 es_fprintf (es_stdout, ":::%d:", sig->digest_algo);
3198 es_fputs ("::::", es_stdout);
3199 es_write_sanitized (es_stdout, reason_comment, reason_commentlen,
3201 es_putc (':', es_stdout);
3203 es_putc ('\n', es_stdout);
3205 if (opt.show_subpackets)
3206 print_subpackets_colon (sig);
3208 else /* Human readable. */
3210 es_fputs ("rvs", es_stdout);
3211 es_fprintf (es_stdout, "%c%c %c%c%c%c%c%c %s %s",
3212 sigrc, (sig->sig_class - 0x10 > 0 &&
3213 sig->sig_class - 0x10 <
3214 4) ? '0' + sig->sig_class - 0x10 : ' ',
3215 sig->flags.exportable ? ' ' : 'L',
3216 sig->flags.revocable ? ' ' : 'R',
3217 sig->flags.policy_url ? 'P' : ' ',
3218 sig->flags.notation ? 'N' : ' ',
3219 sig->flags.expired ? 'X' : ' ',
3220 (sig->trust_depth > 9) ? 'T' : (sig->trust_depth >
3222 sig->trust_depth : ' ', keystr (sig->keyid),
3223 datestr_from_sig (sig));
3226 es_fprintf (es_stdout, " ");
3227 print_utf8_buffer (es_stdout, siguid, siguidlen);
3229 es_putc ('\n', es_stdout);
3231 if (sig->flags.policy_url
3232 && (opt.list_options & LIST_SHOW_POLICY_URLS))
3233 show_policy_url (sig, 3, 0);
3235 if (sig->flags.notation && (opt.list_options & LIST_SHOW_NOTATIONS))
3236 show_notation (sig, 3, 0,
3237 ((opt.list_options & LIST_SHOW_STD_NOTATIONS) ? 1 : 0)
3239 ((opt.list_options & LIST_SHOW_USER_NOTATIONS) ? 2 : 0));
3241 if (sig->flags.pref_ks
3242 && (opt.list_options & LIST_SHOW_KEYSERVER_URLS))
3243 show_keyserver_url (sig, 3, 0);
3247 es_fprintf (es_stdout, " %s%s\n",
3248 _("reason for revocation: "), reason_text);
3251 const byte *s, *s_lf;
3255 n = reason_commentlen;
3259 /* We don't want any empty lines, so we skip them. */
3260 for (;n && *s == '\n'; s++, n--)
3264 s_lf = memchr (s, '\n', n);
3265 n_lf = s_lf? s_lf - s : n;
3266 es_fprintf (es_stdout, " %s",
3267 _("revocation comment: "));
3268 es_write_sanitized (es_stdout, s, n_lf, NULL, NULL);
3269 es_putc ('\n', es_stdout);
3270 s += n_lf; n -= n_lf;
3277 es_fflush (es_stdout);
3279 xfree (reason_text);
3280 xfree (reason_comment);
3287 * Import a revocation certificate; this is a single signature packet.
3290 import_revoke_cert (ctrl_t ctrl, kbnode_t node, unsigned int options,
3291 struct import_stats_s *stats)
3293 PKT_public_key *pk = NULL;
3295 kbnode_t keyblock = NULL;
3296 KEYDB_HANDLE hd = NULL;
3302 /* No error output for --show-keys. */
3303 silent = (options & (IMPORT_SHOW | IMPORT_DRY_RUN));
3305 log_assert (!node->next );
3306 log_assert (node->pkt->pkttype == PKT_SIGNATURE );
3307 log_assert (IS_KEY_REV (node->pkt->pkt.signature));
3309 keyid[0] = node->pkt->pkt.signature->keyid[0];
3310 keyid[1] = node->pkt->pkt.signature->keyid[1];
3312 pk = xmalloc_clear( sizeof *pk );
3313 rc = get_pubkey (ctrl, pk, keyid );
3314 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY )
3317 log_error (_("key %s: no public key -"
3318 " can't apply revocation certificate\n"), keystr(keyid));
3324 log_error (_("key %s: public key not found: %s\n"),
3325 keystr(keyid), gpg_strerror (rc));
3329 /* Read the original keyblock. */
3333 rc = gpg_error_from_syserror ();
3338 byte afp[MAX_FINGERPRINT_LEN];
3341 fingerprint_from_pk (pk, afp, &an);
3342 while (an < MAX_FINGERPRINT_LEN)
3344 rc = keydb_search_fpr (hd, afp);
3348 log_error (_("key %s: can't locate original keyblock: %s\n"),
3349 keystr(keyid), gpg_strerror (rc));
3352 rc = keydb_get_keyblock (hd, &keyblock );
3355 log_error (_("key %s: can't read original keyblock: %s\n"),
3356 keystr(keyid), gpg_strerror (rc));
3360 /* it is okay, that node is not in keyblock because
3361 * check_key_signature works fine for sig_class 0x20 (KEY_REV) in
3362 * this special case. SIGRC is only used for IMPORT_SHOW. */
3363 rc = check_key_signature (ctrl, keyblock, node, NULL);
3364 switch (gpg_err_code (rc))
3366 case 0: sigrc = '!'; break;
3367 case GPG_ERR_BAD_SIGNATURE: sigrc = '-'; break;
3368 case GPG_ERR_NO_PUBKEY: sigrc = '?'; break;
3369 case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break;
3370 default: sigrc = '%'; break;
3375 log_error (_("key %s: invalid revocation certificate"
3376 ": %s - rejected\n"), keystr(keyid), gpg_strerror (rc));
3380 /* check whether we already have this */
3381 for(onode=keyblock->next; onode; onode=onode->next ) {
3382 if (onode->pkt->pkttype == PKT_USER_ID )
3384 else if (onode->pkt->pkttype == PKT_SIGNATURE
3385 && !cmp_signatures(node->pkt->pkt.signature,
3386 onode->pkt->pkt.signature))
3389 goto leave; /* yes, we already know about it */
3394 insert_kbnode( keyblock, clone_kbnode(node), 0 );
3396 /* and write the keyblock back unless in dry run mode. */
3397 if (!(opt.dry_run || (options & IMPORT_DRY_RUN)))
3399 rc = keydb_update_keyblock (ctrl, hd, keyblock );
3401 log_error (_("error writing keyring '%s': %s\n"),
3402 keydb_get_resource_name (hd), gpg_strerror (rc) );
3409 char *p=get_user_id_native (ctrl, keyid);
3410 log_info( _("key %s: \"%s\" revocation certificate imported\n"),
3415 /* If the key we just revoked was ultimately trusted, remove its
3416 * ultimate trust. This doesn't stop the user from putting the
3417 * ultimate trust back, but is a reasonable solution for now. */
3418 if (get_ownertrust (ctrl, pk) == TRUST_ULTIMATE)
3419 clear_ownertrusts (ctrl, pk);
3421 revalidation_mark (ctrl);
3426 if ((options & IMPORT_SHOW))
3427 list_standalone_revocation (ctrl, node->pkt->pkt.signature, sigrc);
3430 release_kbnode( keyblock );
3431 free_public_key( pk );
3436 /* Loop over the KEYBLOCK and check all self signatures. KEYID is the
3437 * keyid of the primary key for reporting purposes. On return the
3438 * following bits in the node flags are set:
3440 * - NODE_GOOD_SELFSIG :: User ID or subkey has a self-signature
3441 * - NODE_BAD_SELFSIG :: Used ID or subkey has an invalid self-signature
3442 * - NODE_DELETION_MARK :: This node shall be deleted
3444 * NON_SELF is set to true if there are any sigs other than self-sigs
3447 * Returns 0 on success or -1 (but not an error code) if the keyblock
3451 chk_self_sigs (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid, int *non_self)
3453 kbnode_t knode = NULL; /* The node of the current subkey. */
3454 PKT_public_key *subpk = NULL; /* and its packet. */
3455 kbnode_t bsnode = NULL; /* Subkey binding signature node. */
3456 u32 bsdate = 0; /* Timestamp of that node. */
3457 kbnode_t rsnode = NULL; /* Subkey recocation signature node. */
3458 u32 rsdate = 0; /* Timestamp of tha node. */
3463 for (n=keyblock; (n = find_next_kbnode (n, 0)); )
3465 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3468 subpk = knode->pkt->pkt.public_key;
3476 if ( n->pkt->pkttype != PKT_SIGNATURE )
3479 sig = n->pkt->pkt.signature;
3480 if ( keyid[0] != sig->keyid[0] || keyid[1] != sig->keyid[1] )
3486 /* This just caches the sigs for later use. That way we
3487 import a fully-cached key which speeds things up. */
3488 if (!opt.no_sig_cache)
3489 check_key_signature (ctrl, keyblock, n, NULL);
3491 if ( IS_UID_SIG(sig) || IS_UID_REV(sig) )
3493 kbnode_t unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
3496 log_error( _("key %s: no user ID for signature\n"),
3498 return -1; /* The complete keyblock is invalid. */
3501 /* If it hasn't been marked valid yet, keep trying. */
3502 if (!(unode->flag & NODE_GOOD_SELFSIG))
3504 rc = check_key_signature (ctrl, keyblock, n, NULL);
3509 char *p = utf8_to_native
3510 (unode->pkt->pkt.user_id->name,
3511 strlen (unode->pkt->pkt.user_id->name),0);
3512 log_info (gpg_err_code(rc) == GPG_ERR_PUBKEY_ALGO ?
3513 _("key %s: unsupported public key "
3514 "algorithm on user ID \"%s\"\n"):
3515 _("key %s: invalid self-signature "
3516 "on user ID \"%s\"\n"),
3522 unode->flag |= NODE_GOOD_SELFSIG;
3525 else if (IS_KEY_SIG (sig))
3527 rc = check_key_signature (ctrl, keyblock, n, NULL);
3531 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
3532 _("key %s: unsupported public key algorithm\n"):
3533 _("key %s: invalid direct key signature\n"),
3535 n->flag |= NODE_DELETION_MARK;
3538 else if ( IS_SUBKEY_SIG (sig) )
3540 /* Note that this works based solely on the timestamps like
3541 the rest of gpg. If the standard gets revocation
3542 targets, this may need to be revised. */
3547 log_info (_("key %s: no subkey for key binding\n"),
3549 n->flag |= NODE_DELETION_MARK;
3553 rc = check_key_signature (ctrl, keyblock, n, NULL);
3558 keyid_from_pk (subpk, NULL);
3559 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
3560 _("key %s: unsupported public key"
3562 _("key %s: invalid subkey binding\n"),
3563 keystr_with_sub (keyid, subpk->keyid));
3565 n->flag |= NODE_DELETION_MARK;
3569 /* It's valid, so is it newer? */
3570 if (sig->timestamp >= bsdate)
3572 knode->flag |= NODE_GOOD_SELFSIG; /* Subkey is valid. */
3575 /* Delete the last binding sig since this
3577 bsnode->flag |= NODE_DELETION_MARK;
3580 keyid_from_pk (subpk, NULL);
3581 log_info (_("key %s: removed multiple subkey"
3583 keystr_with_sub (keyid, subpk->keyid));
3588 bsdate = sig->timestamp;
3591 n->flag |= NODE_DELETION_MARK; /* older */
3595 else if ( IS_SUBKEY_REV (sig) )
3597 /* We don't actually mark the subkey as revoked right now,
3598 so just check that the revocation sig is the most recent
3599 valid one. Note that we don't care if the binding sig is
3600 newer than the revocation sig. See the comment in
3601 getkey.c:merge_selfsigs_subkey for more. */
3605 log_info (_("key %s: no subkey for key revocation\n"),
3607 n->flag |= NODE_DELETION_MARK;
3611 rc = check_key_signature (ctrl, keyblock, n, NULL);
3615 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
3616 _("key %s: unsupported public"
3617 " key algorithm\n"):
3618 _("key %s: invalid subkey revocation\n"),
3620 n->flag |= NODE_DELETION_MARK;
3624 /* It's valid, so is it newer? */
3625 if (sig->timestamp >= rsdate)
3629 /* Delete the last revocation sig since
3630 this one is newer. */
3631 rsnode->flag |= NODE_DELETION_MARK;
3633 log_info (_("key %s: removed multiple subkey"
3634 " revocation\n"),keystr(keyid));
3638 rsdate = sig->timestamp;
3641 n->flag |= NODE_DELETION_MARK; /* older */
3651 /* Delete all parts which are invalid and those signatures whose
3652 * public key algorithm is not available in this implementation; but
3653 * consider RSA as valid, because parse/build_packets knows about it.
3655 * Returns: True if at least one valid user-id is left over.
3658 delete_inv_parts (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid,
3659 unsigned int options)
3662 int nvalid=0, uid_seen=0, subkey_seen=0;
3665 for (node=keyblock->next; node; node = node->next )
3667 if (node->pkt->pkttype == PKT_USER_ID)
3670 if ((node->flag & NODE_BAD_SELFSIG)
3671 || !(node->flag & NODE_GOOD_SELFSIG))
3675 char *p=utf8_to_native(node->pkt->pkt.user_id->name,
3676 node->pkt->pkt.user_id->len,0);
3677 log_info( _("key %s: skipped user ID \"%s\"\n"),
3681 delete_kbnode( node ); /* the user-id */
3682 /* and all following packets up to the next user-id */
3684 && node->next->pkt->pkttype != PKT_USER_ID
3685 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
3686 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
3687 delete_kbnode( node->next );
3694 else if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
3695 || node->pkt->pkttype == PKT_SECRET_SUBKEY )
3697 if ((node->flag & NODE_BAD_SELFSIG)
3698 || !(node->flag & NODE_GOOD_SELFSIG))
3702 pk = node->pkt->pkt.public_key;
3703 keyid_from_pk (pk, NULL);
3704 log_info (_("key %s: skipped subkey\n"),
3705 keystr_with_sub (keyid, pk->keyid));
3708 delete_kbnode( node ); /* the subkey */
3709 /* and all following signature packets */
3711 && node->next->pkt->pkttype == PKT_SIGNATURE ) {
3712 delete_kbnode( node->next );
3719 else if (node->pkt->pkttype == PKT_SIGNATURE
3720 && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
3721 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
3723 delete_kbnode( node ); /* build_packet() can't handle this */
3725 else if (node->pkt->pkttype == PKT_SIGNATURE
3726 && !node->pkt->pkt.signature->flags.exportable
3727 && !(options&IMPORT_LOCAL_SIGS)
3728 && !have_secret_key_with_kid (node->pkt->pkt.signature->keyid))
3730 /* here we violate the rfc a bit by still allowing
3731 * to import non-exportable signature when we have the
3732 * the secret key used to create this signature - it
3733 * seems that this makes sense */
3735 log_info( _("key %s: non exportable signature"
3736 " (class 0x%02X) - skipped\n"),
3737 keystr(keyid), node->pkt->pkt.signature->sig_class );
3738 delete_kbnode( node );
3740 else if (node->pkt->pkttype == PKT_SIGNATURE
3741 && IS_KEY_REV (node->pkt->pkt.signature))
3746 log_info( _("key %s: revocation certificate"
3747 " at wrong place - skipped\n"),keystr(keyid));
3748 delete_kbnode( node );
3752 /* If the revocation cert is from a different key than
3753 the one we're working on don't check it - it's
3754 probably from a revocation key and won't be
3755 verifiable with this key anyway. */
3757 if(node->pkt->pkt.signature->keyid[0]==keyid[0]
3758 && node->pkt->pkt.signature->keyid[1]==keyid[1])
3760 int rc = check_key_signature (ctrl, keyblock, node, NULL);
3764 log_info( _("key %s: invalid revocation"
3765 " certificate: %s - skipped\n"),
3766 keystr(keyid), gpg_strerror (rc));
3767 delete_kbnode( node );
3772 else if (node->pkt->pkttype == PKT_SIGNATURE
3773 && (IS_SUBKEY_SIG (node->pkt->pkt.signature)
3774 || IS_SUBKEY_REV (node->pkt->pkt.signature))
3778 log_info( _("key %s: subkey signature"
3779 " in wrong place - skipped\n"), keystr(keyid));
3780 delete_kbnode( node );
3782 else if (node->pkt->pkttype == PKT_SIGNATURE
3783 && !IS_CERT(node->pkt->pkt.signature))
3786 log_info(_("key %s: unexpected signature class (0x%02X) -"
3787 " skipped\n"),keystr(keyid),
3788 node->pkt->pkt.signature->sig_class);
3789 delete_kbnode(node);
3791 else if ((node->flag & NODE_DELETION_MARK))
3792 delete_kbnode( node );
3795 /* note: because keyblock is the public key, it is never marked
3796 * for deletion and so keyblock cannot change */
3797 commit_kbnode( &keyblock );
3801 /* This function returns true if any UID is left in the keyring. */
3803 any_uid_left (kbnode_t keyblock)
3807 for (node=keyblock->next; node; node = node->next)
3808 if (node->pkt->pkttype == PKT_USER_ID)
3814 /* Delete all non-self-sigs from KEYBLOCK.
3815 * Returns: True if the keyblock has changed. */
3817 remove_all_non_self_sigs (kbnode_t *keyblock, u32 *keyid)
3820 unsigned int dropped = 0;
3822 for (node = *keyblock; node; node = node->next)
3824 if (is_deleted_kbnode (node))
3827 if (node->pkt->pkttype != PKT_SIGNATURE)
3830 if (node->pkt->pkt.signature->keyid[0] == keyid[0]
3831 && node->pkt->pkt.signature->keyid[1] == keyid[1])
3833 delete_kbnode (node);
3838 commit_kbnode (keyblock);
3840 if (dropped && opt.verbose)
3841 log_info ("key %s: number of dropped non-self-signatures: %u\n",
3842 keystr (keyid), dropped);
3847 * It may happen that the imported keyblock has duplicated user IDs.
3848 * We check this here and collapse those user IDs together with their
3850 * Returns: True if the keyblock has changed.
3853 collapse_uids( kbnode_t *keyblock )
3858 for(uid1=*keyblock;uid1;uid1=uid1->next)
3862 if(is_deleted_kbnode(uid1))
3865 if(uid1->pkt->pkttype!=PKT_USER_ID)
3868 for(uid2=uid1->next;uid2;uid2=uid2->next)
3870 if(is_deleted_kbnode(uid2))
3873 if(uid2->pkt->pkttype!=PKT_USER_ID)
3876 if(cmp_user_ids(uid1->pkt->pkt.user_id,
3877 uid2->pkt->pkt.user_id)==0)
3879 /* We have a duplicated uid */
3884 /* Now take uid2's signatures, and attach them to
3886 for(last=uid2;last->next;last=last->next)
3888 if(is_deleted_kbnode(last))
3891 if(last->next->pkt->pkttype==PKT_USER_ID
3892 || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
3893 || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
3898 (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
3900 /* Now put uid2 in place as part of uid1 */
3901 last->next=uid1->next;
3903 delete_kbnode(uid2);
3905 /* Now dedupe uid1 */
3906 for(sig1=uid1->next;sig1;sig1=sig1->next)
3910 if(is_deleted_kbnode(sig1))
3913 if(sig1->pkt->pkttype==PKT_USER_ID
3914 || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
3915 || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
3918 if(sig1->pkt->pkttype!=PKT_SIGNATURE)
3921 for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
3923 if(is_deleted_kbnode(sig2))
3926 if(sig2->pkt->pkttype==PKT_USER_ID
3927 || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
3928 || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
3931 if(sig2->pkt->pkttype!=PKT_SIGNATURE)
3934 if(cmp_signatures(sig1->pkt->pkt.signature,
3935 sig2->pkt->pkt.signature)==0)
3937 /* We have a match, so delete the second
3939 delete_kbnode(sig2);
3948 commit_kbnode(keyblock);
3950 if(any && !opt.quiet)
3952 const char *key="???";
3954 if ((uid1 = find_kbnode (*keyblock, PKT_PUBLIC_KEY)) )
3955 key = keystr_from_pk (uid1->pkt->pkt.public_key);
3956 else if ((uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY)) )
3957 key = keystr_from_pk (uid1->pkt->pkt.public_key);
3959 log_info (_("key %s: duplicated user ID detected - merged\n"), key);
3966 /* Check for a 0x20 revocation from a revocation key that is not
3967 present. This may be called without the benefit of merge_xxxx so
3968 you can't rely on pk->revkey and friends. */
3970 revocation_present (ctrl_t ctrl, kbnode_t keyblock)
3972 kbnode_t onode, inode;
3973 PKT_public_key *pk = keyblock->pkt->pkt.public_key;
3975 for(onode=keyblock->next;onode;onode=onode->next)
3977 /* If we reach user IDs, we're done. */
3978 if(onode->pkt->pkttype==PKT_USER_ID)
3981 if (onode->pkt->pkttype == PKT_SIGNATURE
3982 && IS_KEY_SIG (onode->pkt->pkt.signature)
3983 && onode->pkt->pkt.signature->revkey)
3986 PKT_signature *sig=onode->pkt->pkt.signature;
3988 for(idx=0;idx<sig->numrevkeys;idx++)
3992 keyid_from_fingerprint (ctrl, sig->revkey[idx].fpr,
3993 MAX_FINGERPRINT_LEN, keyid);
3995 for(inode=keyblock->next;inode;inode=inode->next)
3997 /* If we reach user IDs, we're done. */
3998 if(inode->pkt->pkttype==PKT_USER_ID)
4001 if (inode->pkt->pkttype == PKT_SIGNATURE
4002 && IS_KEY_REV (inode->pkt->pkt.signature)
4003 && inode->pkt->pkt.signature->keyid[0]==keyid[0]
4004 && inode->pkt->pkt.signature->keyid[1]==keyid[1])
4006 /* Okay, we have a revocation key, and a
4007 * revocation issued by it. Do we have the key
4011 err = get_pubkey_byfprint_fast (NULL,
4012 sig->revkey[idx].fpr,
4013 MAX_FINGERPRINT_LEN);
4014 if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY
4015 || gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY)
4017 char *tempkeystr = xstrdup (keystr_from_pk (pk));
4019 /* No, so try and get it */
4020 if ((opt.keyserver_options.options
4021 & KEYSERVER_AUTO_KEY_RETRIEVE)
4022 && keyserver_any_configured (ctrl))
4024 log_info(_("WARNING: key %s may be revoked:"
4025 " fetching revocation key %s\n"),
4026 tempkeystr,keystr(keyid));
4027 keyserver_import_fprint (ctrl,
4028 sig->revkey[idx].fpr,
4029 MAX_FINGERPRINT_LEN,
4032 /* Do we have it now? */
4033 err = get_pubkey_byfprint_fast (NULL,
4034 sig->revkey[idx].fpr,
4035 MAX_FINGERPRINT_LEN);
4038 if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY
4039 || gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY)
4040 log_info(_("WARNING: key %s may be revoked:"
4041 " revocation key %s not present.\n"),
4042 tempkeystr,keystr(keyid));
4055 * compare and merge the blocks
4057 * o compare the signatures: If we already have this signature, check
4058 * that they compare okay; if not, issue a warning and ask the user.
4059 * o Simply add the signature. Can't verify here because we may not have
4060 * the signature's public key yet; verification is done when putting it
4061 * into the trustdb, which is done automagically as soon as this pubkey
4063 * Note: We indicate newly inserted packets with NODE_FLAG_A.
4066 merge_blocks (ctrl_t ctrl, unsigned int options,
4067 kbnode_t keyblock_orig, kbnode_t keyblock,
4068 u32 *keyid, u32 curtime, int origin, const char *url,
4069 int *n_uids, int *n_sigs, int *n_subk )
4071 kbnode_t onode, node;
4074 /* 1st: handle revocation certificates */
4075 for (node=keyblock->next; node; node=node->next )
4077 if (node->pkt->pkttype == PKT_USER_ID )
4079 else if (node->pkt->pkttype == PKT_SIGNATURE
4080 && IS_KEY_REV (node->pkt->pkt.signature))
4082 /* check whether we already have this */
4084 for (onode=keyblock_orig->next; onode; onode=onode->next)
4086 if (onode->pkt->pkttype == PKT_USER_ID )
4088 else if (onode->pkt->pkttype == PKT_SIGNATURE
4089 && IS_KEY_REV (onode->pkt->pkt.signature)
4090 && !cmp_signatures(onode->pkt->pkt.signature,
4091 node->pkt->pkt.signature))
4099 kbnode_t n2 = clone_kbnode(node);
4100 insert_kbnode( keyblock_orig, n2, 0 );
4101 n2->flag |= NODE_FLAG_A;
4105 char *p = get_user_id_native (ctrl, keyid);
4106 log_info(_("key %s: \"%s\" revocation"
4107 " certificate added\n"), keystr(keyid),p);
4114 /* 2nd: merge in any direct key (0x1F) sigs */
4115 for(node=keyblock->next; node; node=node->next)
4117 if (node->pkt->pkttype == PKT_USER_ID )
4119 else if (node->pkt->pkttype == PKT_SIGNATURE
4120 && IS_KEY_SIG (node->pkt->pkt.signature))
4122 /* check whether we already have this */
4124 for (onode=keyblock_orig->next; onode; onode=onode->next)
4126 if (onode->pkt->pkttype == PKT_USER_ID)
4128 else if (onode->pkt->pkttype == PKT_SIGNATURE
4129 && IS_KEY_SIG (onode->pkt->pkt.signature)
4130 && !cmp_signatures(onode->pkt->pkt.signature,
4131 node->pkt->pkt.signature))
4139 kbnode_t n2 = clone_kbnode(node);
4140 insert_kbnode( keyblock_orig, n2, 0 );
4141 n2->flag |= NODE_FLAG_A;
4144 log_info( _("key %s: direct key signature added\n"),
4150 /* 3rd: try to merge new certificates in */
4151 for (onode=keyblock_orig->next; onode; onode=onode->next)
4153 if (!(onode->flag & NODE_FLAG_A) && onode->pkt->pkttype == PKT_USER_ID)
4155 /* find the user id in the imported keyblock */
4156 for (node=keyblock->next; node; node=node->next)
4157 if (node->pkt->pkttype == PKT_USER_ID
4158 && !cmp_user_ids( onode->pkt->pkt.user_id,
4159 node->pkt->pkt.user_id ) )
4161 if (node ) /* found: merge */
4163 rc = merge_sigs (onode, node, n_sigs);
4170 /* 4th: add new user-ids */
4171 for (node=keyblock->next; node; node=node->next)
4173 if (node->pkt->pkttype == PKT_USER_ID)
4175 /* do we have this in the original keyblock */
4176 for (onode=keyblock_orig->next; onode; onode=onode->next )
4177 if (onode->pkt->pkttype == PKT_USER_ID
4178 && !cmp_user_ids( onode->pkt->pkt.user_id,
4179 node->pkt->pkt.user_id ) )
4181 if (!onode ) /* this is a new user id: append */
4183 rc = append_new_uid (options, keyblock_orig, node,
4184 curtime, origin, url, n_sigs);
4192 /* 5th: add new subkeys */
4193 for (node=keyblock->next; node; node=node->next)
4196 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4198 /* do we have this in the original keyblock? */
4199 for(onode=keyblock_orig->next; onode; onode=onode->next)
4200 if (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
4201 && !cmp_public_keys( onode->pkt->pkt.public_key,
4202 node->pkt->pkt.public_key))
4204 if (!onode ) /* This is a new subkey: append. */
4206 rc = append_key (keyblock_orig, node, n_sigs);
4212 else if (node->pkt->pkttype == PKT_SECRET_SUBKEY)
4214 /* do we have this in the original keyblock? */
4215 for (onode=keyblock_orig->next; onode; onode=onode->next )
4216 if (onode->pkt->pkttype == PKT_SECRET_SUBKEY
4217 && !cmp_public_keys (onode->pkt->pkt.public_key,
4218 node->pkt->pkt.public_key) )
4220 if (!onode ) /* This is a new subkey: append. */
4222 rc = append_key (keyblock_orig, node, n_sigs);
4230 /* 6th: merge subkey certificates */
4231 for (onode=keyblock_orig->next; onode; onode=onode->next)
4233 if (!(onode->flag & NODE_FLAG_A)
4234 && (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
4235 || onode->pkt->pkttype == PKT_SECRET_SUBKEY))
4237 /* find the subkey in the imported keyblock */
4238 for(node=keyblock->next; node; node=node->next)
4240 if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
4241 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
4242 && !cmp_public_keys( onode->pkt->pkt.public_key,
4243 node->pkt->pkt.public_key ) )
4246 if (node) /* Found: merge. */
4248 rc = merge_keysigs( onode, node, n_sigs);
4259 /* Helper function for merge_blocks.
4261 * Append the new userid starting with NODE and all signatures to
4262 * KEYBLOCK. ORIGIN and URL conveys the usual key origin info. The
4263 * integer at N_SIGS is updated with the number of new signatures.
4266 append_new_uid (unsigned int options,
4267 kbnode_t keyblock, kbnode_t node, u32 curtime,
4268 int origin, const char *url, int *n_sigs)
4272 kbnode_t n_where = NULL;
4274 log_assert (node->pkt->pkttype == PKT_USER_ID);
4276 /* Find the right position for the new user id and its signatures. */
4277 for (n = keyblock; n; n_where = n, n = n->next)
4279 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
4280 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
4286 /* and append/insert */
4289 /* we add a clone to the original keyblock, because this
4290 * one is released first. */
4291 n = clone_kbnode(node);
4292 if (n->pkt->pkttype == PKT_USER_ID
4293 && !(options & IMPORT_RESTORE) )
4295 err = insert_key_origin_uid (n->pkt->pkt.user_id,
4296 curtime, origin, url);
4303 insert_kbnode( n_where, n, 0 );
4307 add_kbnode( keyblock, n );
4308 n->flag |= NODE_FLAG_A;
4309 node->flag |= NODE_FLAG_A;
4310 if (n->pkt->pkttype == PKT_SIGNATURE )
4314 if (node && node->pkt->pkttype != PKT_SIGNATURE )
4322 /* Helper function for merge_blocks
4323 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
4324 * (how should we handle comment packets here?)
4327 merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs)
4332 log_assert (dst->pkt->pkttype == PKT_USER_ID);
4333 log_assert (src->pkt->pkttype == PKT_USER_ID);
4335 for (n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next)
4337 if (n->pkt->pkttype != PKT_SIGNATURE )
4339 if (IS_SUBKEY_SIG (n->pkt->pkt.signature)
4340 || IS_SUBKEY_REV (n->pkt->pkt.signature) )
4341 continue; /* skip signatures which are only valid on subkeys */
4344 for (n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
4345 if (!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
4352 /* This signature is new or newer, append N to DST.
4353 * We add a clone to the original keyblock, because this
4354 * one is released first */
4355 n2 = clone_kbnode(n);
4356 insert_kbnode( dst, n2, PKT_SIGNATURE );
4357 n2->flag |= NODE_FLAG_A;
4358 n->flag |= NODE_FLAG_A;
4367 /* Helper function for merge_blocks
4368 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
4371 merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs)
4376 log_assert (dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
4377 || dst->pkt->pkttype == PKT_SECRET_SUBKEY);
4379 for (n=src->next; n ; n = n->next)
4381 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
4382 || n->pkt->pkttype == PKT_PUBLIC_KEY )
4384 if (n->pkt->pkttype != PKT_SIGNATURE )
4388 for (n2=dst->next; n2; n2 = n2->next)
4390 if (n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
4391 || n2->pkt->pkttype == PKT_PUBLIC_KEY )
4393 if (n2->pkt->pkttype == PKT_SIGNATURE
4394 && (n->pkt->pkt.signature->keyid[0]
4395 == n2->pkt->pkt.signature->keyid[0])
4396 && (n->pkt->pkt.signature->keyid[1]
4397 == n2->pkt->pkt.signature->keyid[1])
4398 && (n->pkt->pkt.signature->timestamp
4399 <= n2->pkt->pkt.signature->timestamp)
4400 && (n->pkt->pkt.signature->sig_class
4401 == n2->pkt->pkt.signature->sig_class))
4409 /* This signature is new or newer, append N to DST.
4410 * We add a clone to the original keyblock, because this
4411 * one is released first */
4412 n2 = clone_kbnode(n);
4413 insert_kbnode( dst, n2, PKT_SIGNATURE );
4414 n2->flag |= NODE_FLAG_A;
4415 n->flag |= NODE_FLAG_A;
4424 /* Helper function for merge_blocks.
4425 * Append the subkey starting with NODE and all signatures to KEYBLOCK.
4426 * Mark all new and copied packets by setting flag bit 0.
4429 append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs)
4433 log_assert (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
4434 || node->pkt->pkttype == PKT_SECRET_SUBKEY);
4438 /* we add a clone to the original keyblock, because this
4439 * one is released first */
4440 n = clone_kbnode(node);
4441 add_kbnode( keyblock, n );
4442 n->flag |= NODE_FLAG_A;
4443 node->flag |= NODE_FLAG_A;
4444 if (n->pkt->pkttype == PKT_SIGNATURE )
4448 if (node && node->pkt->pkttype != PKT_SIGNATURE )