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 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/>.
39 #include "keyserver-internal.h"
40 #include "call-agent.h"
41 #include "../common/membuf.h"
42 #include "../common/init.h"
43 #include "../common/mbox-util.h"
57 ulong secret_imported;
59 ulong skipped_new_keys;
63 ulong v3keys; /* Number of V3 keys seen. */
67 /* Node flag to indicate that a user ID or a subkey has a
68 * valid self-signature. */
69 #define NODE_GOOD_SELFSIG 1
70 /* Node flag to indicate that a user ID or subkey has
71 * an invalid self-signature. */
72 #define NODE_BAD_SELFSIG 2
73 /* Node flag to indicate that the node shall be deleted. */
74 #define NODE_DELETION_MARK 4
75 /* A node flag used to temporary mark a node. */
79 /* A an object and a global instance to store selectors created from
80 * --import-filter keep-uid=EXPR.
81 * --import-filter drop-sig=EXPR.
83 * FIXME: We should put this into the CTRL object but that requires a
84 * lot more changes right now. For now we use save and restore
85 * function to temporary change them.
87 /* Definition of the import filters. */
88 struct import_filter_s
90 recsel_expr_t keep_uid;
91 recsel_expr_t drop_sig;
93 /* The current instance. */
94 struct import_filter_s import_filter;
97 static int import (ctrl_t ctrl,
98 IOBUF inp, const char* fname, struct import_stats_s *stats,
99 unsigned char **fpr, size_t *fpr_len, unsigned int options,
100 import_screener_t screener, void *screener_arg);
101 static int read_block (IOBUF a, PACKET **pending_pkt, kbnode_t *ret_root,
103 static void revocation_present (ctrl_t ctrl, kbnode_t keyblock);
104 static int import_one (ctrl_t ctrl,
106 struct import_stats_s *stats,
107 unsigned char **fpr, size_t *fpr_len,
108 unsigned int options, int from_sk, int silent,
109 import_screener_t screener, void *screener_arg);
110 static int import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
111 struct import_stats_s *stats, int batch,
112 unsigned int options, int for_migration,
113 import_screener_t screener, void *screener_arg);
114 static int import_revoke_cert (ctrl_t ctrl,
115 kbnode_t node, struct import_stats_s *stats);
116 static int chk_self_sigs (kbnode_t keyblock, u32 *keyid, int *non_self);
117 static int delete_inv_parts (kbnode_t keyblock,
118 u32 *keyid, unsigned int options);
119 static int any_uid_left (kbnode_t keyblock);
120 static int merge_blocks (kbnode_t keyblock_orig,
121 kbnode_t keyblock, u32 *keyid,
122 int *n_uids, int *n_sigs, int *n_subk );
123 static int append_uid (kbnode_t keyblock, kbnode_t node, int *n_sigs);
124 static int append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs);
125 static int merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs);
126 static int merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs);
131 release_import_filter (import_filter_t filt)
133 recsel_release (filt->keep_uid);
134 filt->keep_uid = NULL;
135 recsel_release (filt->drop_sig);
136 filt->drop_sig = NULL;
140 cleanup_import_globals (void)
142 release_import_filter (&import_filter);
147 parse_import_options(char *str,unsigned int *options,int noisy)
149 struct parse_options import_opts[]=
151 {"import-local-sigs",IMPORT_LOCAL_SIGS,NULL,
152 N_("import signatures that are marked as local-only")},
154 {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,
155 N_("repair damage from the pks keyserver during import")},
157 {"keep-ownertrust", IMPORT_KEEP_OWNERTTRUST, NULL,
158 N_("do not clear the ownertrust values during import")},
160 {"fast-import",IMPORT_FAST,NULL,
161 N_("do not update the trustdb after import")},
163 {"import-show",IMPORT_SHOW,NULL,
164 N_("show key during import")},
166 {"merge-only",IMPORT_MERGE_ONLY,NULL,
167 N_("only accept updates to existing keys")},
169 {"import-clean",IMPORT_CLEAN,NULL,
170 N_("remove unusable parts from key after import")},
172 {"import-minimal",IMPORT_MINIMAL|IMPORT_CLEAN,NULL,
173 N_("remove as much as possible from key after import")},
175 {"import-export", IMPORT_EXPORT, NULL,
176 N_("run import filters and export key immediately")},
178 {"restore", IMPORT_RESTORE, NULL,
179 N_("assume the GnuPG key backup format")},
180 {"import-restore", IMPORT_RESTORE, NULL, NULL},
182 /* Aliases for backward compatibility */
183 {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL},
184 {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL},
186 {"import-unusable-sigs",0,NULL,NULL},
187 {"import-clean-sigs",0,NULL,NULL},
188 {"import-clean-uids",0,NULL,NULL},
189 {"convert-sk-to-pk",0, NULL,NULL}, /* Not anymore needed due to
195 rc = parse_options (str, options, import_opts, noisy);
196 if (rc && (*options & IMPORT_RESTORE))
198 /* Alter other options we want or don't want for restore. */
199 *options |= (IMPORT_LOCAL_SIGS | IMPORT_KEEP_OWNERTTRUST);
200 *options &= ~(IMPORT_MINIMAL | IMPORT_CLEAN
201 | IMPORT_REPAIR_PKS_SUBKEY_BUG
202 | IMPORT_MERGE_ONLY);
208 /* Parse and set an import filter from string. STRING has the format
209 * "NAME=EXPR" with NAME being the name of the filter. Spaces before
210 * and after NAME are not allowed. If this function is all called
211 * several times all expressions for the same NAME are concatenated.
212 * Supported filter names are:
214 * - keep-uid :: If the expression evaluates to true for a certain
215 * user ID packet, that packet and all it dependencies
216 * will be imported. The expression may use these
219 * - uid :: The entire user ID.
220 * - mbox :: The mail box part of the user ID.
221 * - primary :: Evaluate to true for the primary user ID.
224 parse_and_set_import_filter (const char *string)
228 /* Auto register the cleanup function. */
229 register_mem_cleanup_func (cleanup_import_globals);
231 if (!strncmp (string, "keep-uid=", 9))
232 err = recsel_parse_expr (&import_filter.keep_uid, string+9);
233 else if (!strncmp (string, "drop-sig=", 9))
234 err = recsel_parse_expr (&import_filter.drop_sig, string+9);
236 err = gpg_error (GPG_ERR_INV_NAME);
242 /* Save the current import filters, return them, and clear the current
243 * filters. Returns NULL on error and sets ERRNO. */
245 save_and_clear_import_filter (void)
247 import_filter_t filt;
249 filt = xtrycalloc (1, sizeof *filt);
252 *filt = import_filter;
253 memset (&import_filter, 0, sizeof import_filter);
259 /* Release the current import filters and restore them from NEWFILT.
260 * Ownership of NEWFILT is moved to this function. */
262 restore_import_filter (import_filter_t filt)
266 release_import_filter (&import_filter);
267 import_filter = *filt;
274 import_new_stats_handle (void)
276 return xmalloc_clear ( sizeof (struct import_stats_s) );
281 import_release_stats_handle (import_stats_t p)
287 /* Read a key from a file. Only the first key in the file is
288 * considered and stored at R_KEYBLOCK. FNAME is the name of the
292 read_key_from_file (ctrl_t ctrl, const char *fname, kbnode_t *r_keyblock)
296 PACKET *pending_pkt = NULL;
297 kbnode_t keyblock = NULL;
299 int v3keys; /* Dummy */
300 int non_self; /* Dummy */
306 inp = iobuf_open (fname);
308 err = gpg_error_from_syserror ();
309 else if (is_secured_file (iobuf_get_fd (inp)))
313 err = gpg_error (GPG_ERR_EPERM);
319 log_error (_("can't open '%s': %s\n"),
320 iobuf_is_pipe_filename (fname)? "[stdin]": fname,
322 if (gpg_err_code (err) == GPG_ERR_ENOENT)
323 err = gpg_error (GPG_ERR_NO_PUBKEY);
327 /* Push the armor filter. */
329 armor_filter_context_t *afx;
330 afx = new_armor_context ();
331 afx->only_keyblocks = 1;
332 push_armor_filter (afx, inp);
333 release_armor_context (afx);
336 /* Read the first non-v3 keyblock. */
337 while (!(err = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
339 if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
341 log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
342 release_kbnode (keyblock);
347 if (gpg_err_code (err) != GPG_ERR_INV_KEYRING)
348 log_error (_("error reading '%s': %s\n"),
349 iobuf_is_pipe_filename (fname)? "[stdin]": fname,
354 keyid_from_pk (keyblock->pkt->pkt.public_key, keyid);
356 if (!find_next_kbnode (keyblock, PKT_USER_ID))
358 err = gpg_error (GPG_ERR_NO_USER_ID);
362 collapse_uids (&keyblock);
364 clear_kbnode_flags (keyblock);
365 if (chk_self_sigs (keyblock, keyid, &non_self))
367 err = gpg_error (GPG_ERR_INV_KEYRING);
371 if (!delete_inv_parts (keyblock, keyid, 0) )
373 err = gpg_error (GPG_ERR_NO_USER_ID);
377 *r_keyblock = keyblock;
384 /* Must invalidate that ugly cache to actually close the file. */
385 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
387 release_kbnode (keyblock);
388 /* FIXME: Do we need to free PENDING_PKT ? */
395 * Import the public keys from the given filename. Input may be armored.
396 * This function rejects all keys which are not validly self signed on at
397 * least one userid. Only user ids which are self signed will be imported.
398 * Other signatures are not checked.
400 * Actually this function does a merge. It works like this:
403 * - check self-signatures and remove all userids and their signatures
404 * without/invalid self-signatures.
405 * - reject the keyblock, if we have no valid userid.
406 * - See whether we have this key already in one of our pubrings.
407 * If not, simply add it to the default keyring.
408 * - Compare the key and the self-signatures of the new and the one in
409 * our keyring. If they are different something weird is going on;
411 * - See whether we have only non-self-signature on one user id; if not
412 * ask the user what to do.
413 * - compare the signatures: If we already have this signature, check
414 * that they compare okay; if not, issue a warning and ask the user.
415 * (consider looking at the timestamp and use the newest?)
416 * - Simply add the signature. Can't verify here because we may not have
417 * the signature's public key yet; verification is done when putting it
418 * into the trustdb, which is done automagically as soon as this pubkey
420 * - Proceed with next signature.
422 * Key revocation certificates have special handling.
425 import_keys_internal (ctrl_t ctrl, iobuf_t inp, char **fnames, int nnames,
426 import_stats_t stats_handle,
427 unsigned char **fpr, size_t *fpr_len,
428 unsigned int options,
429 import_screener_t screener, void *screener_arg)
433 struct import_stats_s *stats = stats_handle;
436 stats = import_new_stats_handle ();
440 rc = import (ctrl, inp, "[stream]", stats, fpr, fpr_len, options,
441 screener, screener_arg);
445 if (!fnames && !nnames)
446 nnames = 1; /* Ohh what a ugly hack to jump into the loop */
448 for (i=0; i < nnames; i++)
450 const char *fname = fnames? fnames[i] : NULL;
451 IOBUF inp2 = iobuf_open(fname);
455 if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
459 gpg_err_set_errno (EPERM);
462 log_error (_("can't open '%s': %s\n"), fname, strerror (errno));
465 rc = import (ctrl, inp2, fname, stats, fpr, fpr_len, options,
466 screener, screener_arg);
468 /* Must invalidate that ugly cache to actually close it. */
469 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
471 log_error ("import from '%s' failed: %s\n",
472 fname, gpg_strerror (rc) );
481 import_print_stats (stats);
482 import_release_stats_handle (stats);
485 /* If no fast import and the trustdb is dirty (i.e. we added a key
486 or userID that had something other than a selfsig, a signature
487 that was other than a selfsig, or any revocation), then
488 update/check the trustdb if the user specified by setting
489 interactive or by not setting no-auto-check-trustdb */
491 if (!(options & IMPORT_FAST))
492 check_or_update_trustdb (ctrl);
499 import_keys (ctrl_t ctrl, char **fnames, int nnames,
500 import_stats_t stats_handle, unsigned int options )
502 import_keys_internal (ctrl, NULL, fnames, nnames, stats_handle,
503 NULL, NULL, options, NULL, NULL);
507 import_keys_stream (ctrl_t ctrl, IOBUF inp, import_stats_t stats_handle,
508 unsigned char **fpr, size_t *fpr_len, unsigned int options)
510 return import_keys_internal (ctrl, inp, NULL, 0, stats_handle,
511 fpr, fpr_len, options, NULL, NULL);
515 /* Variant of import_keys_stream reading from an estream_t. */
517 import_keys_es_stream (ctrl_t ctrl, estream_t fp,
518 import_stats_t stats_handle,
519 unsigned char **fpr, size_t *fpr_len,
520 unsigned int options,
521 import_screener_t screener, void *screener_arg)
526 inp = iobuf_esopen (fp, "rb", 1);
529 rc = gpg_error_from_syserror ();
530 log_error ("iobuf_esopen failed: %s\n", gpg_strerror (rc));
534 rc = import_keys_internal (ctrl, inp, NULL, 0, stats_handle,
535 fpr, fpr_len, options,
536 screener, screener_arg);
544 import (ctrl_t ctrl, IOBUF inp, const char* fname,struct import_stats_s *stats,
545 unsigned char **fpr,size_t *fpr_len, unsigned int options,
546 import_screener_t screener, void *screener_arg)
548 PACKET *pending_pkt = NULL;
549 kbnode_t keyblock = NULL; /* Need to initialize because gcc can't
550 grasp the return semantics of
555 getkey_disable_caches ();
557 if (!opt.no_armor) /* Armored reading is not disabled. */
559 armor_filter_context_t *afx;
561 afx = new_armor_context ();
562 afx->only_keyblocks = 1;
563 push_armor_filter (afx, inp);
564 release_armor_context (afx);
567 while (!(rc = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
569 stats->v3keys += v3keys;
570 if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
571 rc = import_one (ctrl, keyblock,
572 stats, fpr, fpr_len, options, 0, 0,
573 screener, screener_arg);
574 else if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
575 rc = import_secret_one (ctrl, keyblock, stats,
576 opt.batch, options, 0,
577 screener, screener_arg);
578 else if (keyblock->pkt->pkttype == PKT_SIGNATURE
579 && keyblock->pkt->pkt.signature->sig_class == 0x20 )
580 rc = import_revoke_cert (ctrl, keyblock, stats);
583 log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
585 release_kbnode (keyblock);
587 /* fixme: we should increment the not imported counter but
588 this does only make sense if we keep on going despite of
589 errors. For now we do this only if the imported key is too
591 if (gpg_err_code (rc) == GPG_ERR_TOO_LARGE
592 && gpg_err_source (rc) == GPG_ERR_SOURCE_KEYBOX)
594 stats->not_imported++;
599 if (!(++stats->count % 100) && !opt.quiet)
600 log_info (_("%lu keys processed so far\n"), stats->count );
602 stats->v3keys += v3keys;
605 else if (rc && gpg_err_code (rc) != GPG_ERR_INV_KEYRING)
606 log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (rc));
612 /* Helper to migrate secring.gpg to GnuPG 2.1. */
614 import_old_secring (ctrl_t ctrl, const char *fname)
618 PACKET *pending_pkt = NULL;
619 kbnode_t keyblock = NULL; /* Need to initialize because gcc can't
620 grasp the return semantics of
622 struct import_stats_s *stats;
625 inp = iobuf_open (fname);
626 if (inp && is_secured_file (iobuf_get_fd (inp)))
630 gpg_err_set_errno (EPERM);
634 err = gpg_error_from_syserror ();
635 log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
639 getkey_disable_caches();
640 stats = import_new_stats_handle ();
641 while (!(err = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
643 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
644 err = import_secret_one (ctrl, keyblock, stats, 1, 0, 1,
646 release_kbnode (keyblock);
650 import_release_stats_handle (stats);
653 else if (err && gpg_err_code (err) != GPG_ERR_INV_KEYRING)
654 log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
656 log_error ("import from '%s' failed: %s\n", fname, gpg_strerror (err));
659 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
666 import_print_stats (import_stats_t stats)
670 log_info(_("Total number processed: %lu\n"),
671 stats->count + stats->v3keys);
673 log_info(_(" skipped PGP-2 keys: %lu\n"), stats->v3keys);
674 if (stats->skipped_new_keys )
675 log_info(_(" skipped new keys: %lu\n"),
676 stats->skipped_new_keys );
677 if (stats->no_user_id )
678 log_info(_(" w/o user IDs: %lu\n"), stats->no_user_id );
681 log_info(_(" imported: %lu"), stats->imported );
684 if (stats->unchanged )
685 log_info(_(" unchanged: %lu\n"), stats->unchanged );
687 log_info(_(" new user IDs: %lu\n"), stats->n_uids );
689 log_info(_(" new subkeys: %lu\n"), stats->n_subk );
691 log_info(_(" new signatures: %lu\n"), stats->n_sigs );
693 log_info(_(" new key revocations: %lu\n"), stats->n_revoc );
694 if (stats->secret_read )
695 log_info(_(" secret keys read: %lu\n"), stats->secret_read );
696 if (stats->secret_imported )
697 log_info(_(" secret keys imported: %lu\n"), stats->secret_imported );
698 if (stats->secret_dups )
699 log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
700 if (stats->not_imported )
701 log_info(_(" not imported: %lu\n"), stats->not_imported );
702 if (stats->n_sigs_cleaned)
703 log_info(_(" signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
704 if (stats->n_uids_cleaned)
705 log_info(_(" user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
708 if (is_status_enabled ())
712 snprintf (buf, sizeof buf,
713 "%lu %lu %lu 0 %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
714 stats->count + stats->v3keys,
723 stats->secret_imported,
725 stats->skipped_new_keys,
728 write_status_text (STATUS_IMPORT_RES, buf);
733 /* Return true if PKTTYPE is valid in a keyblock. */
735 valid_keyblock_packet (int pkttype)
740 case PKT_PUBLIC_SUBKEY:
742 case PKT_SECRET_SUBKEY:
755 * Read the next keyblock from stream A.
756 * PENDING_PKT should be initialzed to NULL
757 * and not changed by the caller.
758 * Return: 0 = okay, -1 no more blocks or another errorcode.
759 * The int at at R_V3KEY counts the number of unsupported v3
763 read_block( IOBUF a, PACKET **pending_pkt, kbnode_t *ret_root, int *r_v3keys)
767 kbnode_t root = NULL;
768 int in_cert, in_v3key;
774 root = new_kbnode( *pending_pkt );
781 pkt = xmalloc (sizeof *pkt);
784 while ((rc=parse_packet(a, pkt)) != -1)
786 if (rc && (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY
787 && (pkt->pkttype == PKT_PUBLIC_KEY
788 || pkt->pkttype == PKT_SECRET_KEY)))
796 else if (rc ) /* (ignore errors) */
798 if (gpg_err_code (rc) == GPG_ERR_UNKNOWN_PACKET)
799 ; /* Do not show a diagnostic. */
802 log_error("read_block: read error: %s\n", gpg_strerror (rc) );
803 rc = GPG_ERR_INV_KEYRING;
811 if (in_v3key && !(pkt->pkttype == PKT_PUBLIC_KEY
812 || pkt->pkttype == PKT_SECRET_KEY))
820 if (!root && pkt->pkttype == PKT_SIGNATURE
821 && pkt->pkt.signature->sig_class == 0x20 )
823 /* This is a revocation certificate which is handled in a
825 root = new_kbnode( pkt );
830 /* Make a linked list of all packets. */
831 switch (pkt->pkttype)
834 if (check_compress_algo (pkt->pkt.compressed->algorithm))
836 rc = GPG_ERR_COMPR_ALGO;
841 compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
842 pkt->pkt.compressed->buf = NULL;
843 push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1);
850 /* Skip those packets unless we are in restore mode. */
851 if ((opt.import_options & IMPORT_RESTORE))
859 if (in_cert ) /* Store this packet. */
868 if (in_cert && valid_keyblock_packet (pkt->pkttype))
871 root = new_kbnode (pkt);
873 add_kbnode (root, new_kbnode (pkt));
874 pkt = xmalloc (sizeof *pkt);
882 if (rc == -1 && root )
886 release_kbnode( root );
895 /* Walk through the subkeys on a pk to find if we have the PKS
896 disease: multiple subkeys with their binding sigs stripped, and the
897 sig for the first subkey placed after the last subkey. That is,
898 instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
899 "pk uid sig sub1 sub2 sub3 bind1". We can't do anything about sub2
900 and sub3, as they are already lost, but we can try and rescue sub1
901 by reordering the keyblock so that it reads "pk uid sig sub1 bind1
902 sub2 sub3". Returns TRUE if the keyblock was modified. */
904 fix_pks_corruption (kbnode_t keyblock)
909 kbnode_t last = NULL;
910 kbnode_t sknode=NULL;
912 /* First determine if we have the problem at all. Look for 2 or
913 more subkeys in a row, followed by a single binding sig. */
914 for (node=keyblock; node; last=node, node=node->next)
916 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
922 else if (node->pkt->pkttype == PKT_SIGNATURE
923 && node->pkt->pkt.signature->sig_class == 0x18
927 /* We might have the problem, as this key has two subkeys in
928 a row without any intervening packets. */
934 /* Temporarily attach node to sknode. */
935 node->next = sknode->next;
939 /* Note we aren't checking whether this binding sig is a
940 selfsig. This is not necessary here as the subkey and
941 binding sig will be rejected later if that is the
943 if (check_key_signature (keyblock,node,NULL))
945 /* Not a match, so undo the changes. */
946 sknode->next = node->next;
953 /* Mark it good so we don't need to check it again */
954 sknode->flag |= NODE_GOOD_SELFSIG;
967 /* Versions of GnuPG before 1.4.11 and 2.0.16 allowed to import bogus
968 direct key signatures. A side effect of this was that a later
969 import of the same good direct key signatures was not possible
970 because the cmp_signature check in merge_blocks considered them
971 equal. Although direct key signatures are now checked during
972 import, there might still be bogus signatures sitting in a keyring.
973 We need to detect and delete them before doing a merge. This
974 function returns the number of removed sigs. */
976 fix_bad_direct_key_sigs (kbnode_t keyblock, u32 *keyid)
982 for (node = keyblock->next; node; node=node->next)
984 if (node->pkt->pkttype == PKT_USER_ID)
986 if (node->pkt->pkttype == PKT_SIGNATURE
987 && IS_KEY_SIG (node->pkt->pkt.signature))
989 err = check_key_signature (keyblock, node, NULL);
990 if (err && gpg_err_code (err) != GPG_ERR_PUBKEY_ALGO )
992 /* If we don't know the error, we can't decide; this is
993 not a problem because cmp_signature can't compare the
995 log_info ("key %s: invalid direct key signature removed\n",
997 delete_kbnode (node);
1008 print_import_ok (PKT_public_key *pk, unsigned int reason)
1010 byte array[MAX_FINGERPRINT_LEN], *s;
1011 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
1014 snprintf (buf, sizeof buf, "%u ", reason);
1015 p = buf + strlen (buf);
1017 fingerprint_from_pk (pk, array, &n);
1019 for (i=0; i < n ; i++, s++, p += 2)
1020 sprintf (p, "%02X", *s);
1022 write_status_text (STATUS_IMPORT_OK, buf);
1027 print_import_check (PKT_public_key * pk, PKT_user_id * id)
1035 buf = xmalloc (17+41+id->len+32);
1036 keyid_from_pk (pk, keyid);
1037 sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
1039 fingerprint_from_pk (pk, fpr, &n);
1040 for (i = 0; i < n; i++, pos += 2)
1041 sprintf (buf+pos, "%02X", fpr[i]);
1043 strcat (buf, id->name);
1044 write_status_text (STATUS_IMPORT_CHECK, buf);
1050 check_prefs_warning(PKT_public_key *pk)
1052 log_info(_("WARNING: key %s contains preferences for unavailable\n"
1053 "algorithms on these user IDs:\n"), keystr_from_pk(pk));
1058 check_prefs (ctrl_t ctrl, kbnode_t keyblock)
1064 merge_keys_and_selfsig(keyblock);
1065 pk=keyblock->pkt->pkt.public_key;
1067 for(node=keyblock;node;node=node->next)
1069 if(node->pkt->pkttype==PKT_USER_ID
1070 && node->pkt->pkt.user_id->created
1071 && node->pkt->pkt.user_id->prefs)
1073 PKT_user_id *uid = node->pkt->pkt.user_id;
1074 prefitem_t *prefs = uid->prefs;
1075 char *user = utf8_to_native(uid->name,strlen(uid->name),0);
1077 for(;prefs->type;prefs++)
1079 char num[10]; /* prefs->value is a byte, so we're over
1082 sprintf(num,"%u",prefs->value);
1084 if(prefs->type==PREFTYPE_SYM)
1086 if (openpgp_cipher_test_algo (prefs->value))
1089 (openpgp_cipher_test_algo (prefs->value)
1091 : openpgp_cipher_algo_name (prefs->value));
1093 check_prefs_warning(pk);
1094 log_info(_(" \"%s\": preference for cipher"
1095 " algorithm %s\n"), user, algo);
1099 else if(prefs->type==PREFTYPE_HASH)
1101 if(openpgp_md_test_algo(prefs->value))
1104 (gcry_md_test_algo (prefs->value)
1106 : gcry_md_algo_name (prefs->value));
1108 check_prefs_warning(pk);
1109 log_info(_(" \"%s\": preference for digest"
1110 " algorithm %s\n"), user, algo);
1114 else if(prefs->type==PREFTYPE_ZIP)
1116 if(check_compress_algo (prefs->value))
1118 const char *algo=compress_algo_to_string(prefs->value);
1120 check_prefs_warning(pk);
1121 log_info(_(" \"%s\": preference for compression"
1122 " algorithm %s\n"),user,algo?algo:num);
1134 log_info(_("it is strongly suggested that you update"
1135 " your preferences and\n"));
1136 log_info(_("re-distribute this key to avoid potential algorithm"
1137 " mismatch problems\n"));
1141 strlist_t sl = NULL;
1142 strlist_t locusr = NULL;
1144 byte fpr[MAX_FINGERPRINT_LEN], *p;
1145 char username[(MAX_FINGERPRINT_LEN*2)+1];
1148 p = fingerprint_from_pk (pk,fpr,&fprlen);
1149 for(i=0;i<fprlen;i++,p++)
1150 sprintf(username+2*i,"%02X",*p);
1151 add_to_strlist(&locusr,username);
1153 append_to_strlist(&sl,"updpref");
1154 append_to_strlist(&sl,"save");
1156 keyedit_menu (ctrl, username, locusr, sl, 1, 1 );
1158 free_strlist(locusr);
1161 log_info(_("you can update your preferences with:"
1162 " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
1167 /* Helper for apply_*_filter in im,port.c and export.c. */
1169 impex_filter_getval (void *cookie, const char *propname)
1171 /* FIXME: Malloc our static buffers and access them via the cookie. */
1172 kbnode_t node = cookie;
1173 static char numbuf[20];
1176 if (node->pkt->pkttype == PKT_USER_ID)
1178 if (!strcmp (propname, "uid"))
1179 result = node->pkt->pkt.user_id->name;
1180 else if (!strcmp (propname, "mbox"))
1182 if (!node->pkt->pkt.user_id->mbox)
1184 node->pkt->pkt.user_id->mbox
1185 = mailbox_from_userid (node->pkt->pkt.user_id->name);
1187 result = node->pkt->pkt.user_id->mbox;
1189 else if (!strcmp (propname, "primary"))
1190 result = node->pkt->pkt.user_id->is_primary? "1":"0";
1194 else if (node->pkt->pkttype == PKT_SIGNATURE
1195 || node->pkt->pkttype == PKT_ATTRIBUTE)
1197 PKT_signature *sig = node->pkt->pkt.signature;
1199 if (!strcmp (propname, "sig_created"))
1201 snprintf (numbuf, sizeof numbuf, "%lu", (ulong)sig->timestamp);
1204 else if (!strcmp (propname, "sig_created_d"))
1206 result = datestr_from_sig (sig);
1208 else if (!strcmp (propname, "sig_algo"))
1210 snprintf (numbuf, sizeof numbuf, "%d", sig->pubkey_algo);
1213 else if (!strcmp (propname, "sig_digest_algo"))
1215 snprintf (numbuf, sizeof numbuf, "%d", sig->digest_algo);
1221 else if (node->pkt->pkttype == PKT_PUBLIC_KEY
1222 || node->pkt->pkttype == PKT_SECRET_KEY
1223 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1224 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1226 PKT_public_key *pk = node->pkt->pkt.public_key;
1228 if (!strcmp (propname, "secret"))
1230 result = (node->pkt->pkttype == PKT_SECRET_KEY
1231 || node->pkt->pkttype == PKT_SECRET_SUBKEY)? "1":"0";
1233 else if (!strcmp (propname, "key_algo"))
1235 snprintf (numbuf, sizeof numbuf, "%d", pk->pubkey_algo);
1238 if (!strcmp (propname, "key_created"))
1240 snprintf (numbuf, sizeof numbuf, "%lu", (ulong)pk->timestamp);
1243 else if (!strcmp (propname, "key_created_d"))
1245 result = datestr_from_pk (pk);
1258 * Apply the keep-uid filter to the keyblock. The deleted nodes are
1259 * marked and thus the caller should call commit_kbnode afterwards.
1260 * KEYBLOCK must not have any blocks marked as deleted.
1263 apply_keep_uid_filter (kbnode_t keyblock, recsel_expr_t selector)
1267 for (node = keyblock->next; node; node = node->next )
1269 if (node->pkt->pkttype == PKT_USER_ID)
1271 if (!recsel_select (selector, impex_filter_getval, node))
1274 /* log_debug ("keep-uid: deleting '%s'\n", */
1275 /* node->pkt->pkt.user_id->name); */
1276 /* The UID packet and all following packets up to the
1277 * next UID or a subkey. */
1278 delete_kbnode (node);
1280 && node->next->pkt->pkttype != PKT_USER_ID
1281 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1282 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1284 delete_kbnode (node->next);
1287 /* log_debug ("keep-uid: keeping '%s'\n", */
1288 /* node->pkt->pkt.user_id->name); */
1295 * Apply the drop-sig filter to the keyblock. The deleted nodes are
1296 * marked and thus the caller should call commit_kbnode afterwards.
1297 * KEYBLOCK must not have any blocks marked as deleted.
1300 apply_drop_sig_filter (kbnode_t keyblock, recsel_expr_t selector)
1307 keyid_from_pk (keyblock->pkt->pkt.public_key, main_keyid);
1309 /* Loop over all signatures for user id and attribute packets which
1310 * are not self signatures. */
1311 for (node = keyblock->next; node; node = node->next )
1313 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1314 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1316 if (node->pkt->pkttype == PKT_USER_ID)
1320 if (node->pkt->pkttype != PKT_SIGNATURE
1321 && node->pkt->pkttype != PKT_ATTRIBUTE)
1324 sig = node->pkt->pkt.signature;
1325 if (main_keyid[0] == sig->keyid[0] || main_keyid[1] == sig->keyid[1])
1326 continue; /* Skip self-signatures. */
1328 if (IS_UID_SIG(sig) || IS_UID_REV(sig))
1330 if (recsel_select (selector, impex_filter_getval, node))
1331 delete_kbnode (node);
1338 * Try to import one keyblock. Return an error only in serious cases,
1339 * but never for an invalid keyblock. It uses log_error to increase
1340 * the internal errorcount, so that invalid input can be detected by
1341 * programs which called gpg. If SILENT is no messages are printed -
1342 * even most error messages are suppressed.
1345 import_one (ctrl_t ctrl,
1346 kbnode_t keyblock, struct import_stats_s *stats,
1347 unsigned char **fpr, size_t *fpr_len, unsigned int options,
1348 int from_sk, int silent,
1349 import_screener_t screener, void *screener_arg)
1352 PKT_public_key *pk_orig = NULL;
1353 kbnode_t node, uidnode;
1354 kbnode_t keyblock_orig = NULL;
1355 byte fpr2[MAX_FINGERPRINT_LEN];
1364 char pkstrbuf[PUBKEY_STRING_SIZE];
1365 int merge_keys_done = 0;
1368 /* Get the key and print some info about it. */
1369 node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
1373 pk = node->pkt->pkt.public_key;
1375 fingerprint_from_pk (pk, fpr2, &fpr2len);
1376 for (an = fpr2len; an < MAX_FINGERPRINT_LEN; an++)
1378 keyid_from_pk( pk, keyid );
1379 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1381 if (opt.verbose && !opt.interactive && !silent)
1383 log_info( "pub %s/%s %s ",
1384 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
1385 keystr_from_pk(pk), datestr_from_pk(pk) );
1387 print_utf8_buffer (log_get_stream (),
1388 uidnode->pkt->pkt.user_id->name,
1389 uidnode->pkt->pkt.user_id->len );
1397 log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
1401 if (screener && screener (keyblock, screener_arg))
1403 log_error (_("key %s: %s\n"), keystr_from_pk (pk),
1404 _("rejected by import screener"));
1408 if (opt.interactive && !silent)
1410 if (is_status_enabled())
1411 print_import_check (pk, uidnode->pkt->pkt.user_id);
1412 merge_keys_and_selfsig (keyblock);
1414 show_basic_key_info (keyblock);
1416 if (!cpr_get_answer_is_yes ("import.okay",
1417 "Do you want to import this key? (y/N) "))
1421 collapse_uids(&keyblock);
1423 /* Clean the key that we're about to import, to cut down on things
1424 that we have to clean later. This has no practical impact on the
1425 end result, but does result in less logging which might confuse
1427 if (options&IMPORT_CLEAN)
1428 clean_key (keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL);
1430 clear_kbnode_flags( keyblock );
1432 if ((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
1434 log_info (_("key %s: PKS subkey corruption repaired\n"),
1435 keystr_from_pk(pk));
1437 if (chk_self_sigs (keyblock, keyid, &non_self))
1438 return 0; /* Invalid keyblock - error already printed. */
1440 /* If we allow such a thing, mark unsigned uids as valid */
1441 if (opt.allow_non_selfsigned_uid)
1443 for (node=keyblock; node; node = node->next )
1444 if (node->pkt->pkttype == PKT_USER_ID
1445 && !(node->flag & NODE_GOOD_SELFSIG)
1446 && !(node->flag & NODE_BAD_SELFSIG) )
1448 char *user=utf8_to_native(node->pkt->pkt.user_id->name,
1449 node->pkt->pkt.user_id->len,0);
1450 /* Fake a good signature status for the user id. */
1451 node->flag |= NODE_GOOD_SELFSIG;
1452 log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
1453 keystr_from_pk(pk),user);
1458 if (!delete_inv_parts (keyblock, keyid, options ) )
1462 log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
1464 log_info(_("this may be caused by a missing self-signature\n"));
1466 stats->no_user_id++;
1470 /* Get rid of deleted nodes. */
1471 commit_kbnode (&keyblock);
1473 /* Apply import filter. */
1474 if (import_filter.keep_uid)
1476 apply_keep_uid_filter (keyblock, import_filter.keep_uid);
1477 commit_kbnode (&keyblock);
1480 if (import_filter.drop_sig)
1482 apply_drop_sig_filter (keyblock, import_filter.drop_sig);
1483 commit_kbnode (&keyblock);
1487 /* If we ran any filter we need to check that at least one user id
1488 * is left in the keyring. Note that we do not use log_error in
1490 if (any_filter && !any_uid_left (keyblock))
1493 log_info ( _("key %s: no valid user IDs\n"), keystr_from_pk (pk));
1494 stats->no_user_id++;
1498 /* Show the key in the form it is merged or inserted. We skip this
1499 * if "import-export" is also active without --armor or the output
1500 * file has explicily been given. */
1501 if ((options & IMPORT_SHOW)
1502 && !((options & IMPORT_EXPORT) && !opt.armor && !opt.outfile))
1504 merge_keys_and_selfsig (keyblock);
1505 merge_keys_done = 1;
1506 /* Note that we do not want to show the validity because the key
1507 * has not yet imported. */
1508 list_keyblock_direct (ctrl, keyblock, 0, 0, 1, 1);
1509 es_fflush (es_stdout);
1512 /* Write the keyblock to the output and do not actually import. */
1513 if ((options & IMPORT_EXPORT))
1515 if (!merge_keys_done)
1517 merge_keys_and_selfsig (keyblock);
1518 merge_keys_done = 1;
1520 rc = write_keyblock_to_output (keyblock, opt.armor, opt.export_options);
1527 /* Do we have this key already in one of our pubrings ? */
1528 pk_orig = xmalloc_clear( sizeof *pk_orig );
1529 rc = get_pubkey_byfprint_fast (pk_orig, fpr2, fpr2len);
1530 if (rc && gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1531 && gpg_err_code (rc) != GPG_ERR_UNUSABLE_PUBKEY )
1534 log_error (_("key %s: public key not found: %s\n"),
1535 keystr(keyid), gpg_strerror (rc));
1537 else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) )
1539 if (opt.verbose && !silent )
1540 log_info( _("key %s: new key - skipped\n"), keystr(keyid));
1542 stats->skipped_new_keys++;
1544 else if (rc ) /* Insert this key. */
1550 return gpg_error_from_syserror ();
1552 rc = keydb_locate_writable (hd);
1555 log_error (_("no writable keyring found: %s\n"), gpg_strerror (rc));
1557 return GPG_ERR_GENERAL;
1559 if (opt.verbose > 1 )
1560 log_info (_("writing to '%s'\n"), keydb_get_resource_name (hd) );
1562 rc = keydb_insert_keyblock (hd, keyblock );
1564 log_error (_("error writing keyring '%s': %s\n"),
1565 keydb_get_resource_name (hd), gpg_strerror (rc));
1566 else if (!(opt.import_options & IMPORT_KEEP_OWNERTTRUST))
1568 /* This should not be possible since we delete the
1569 ownertrust when a key is deleted, but it can happen if
1570 the keyring and trustdb are out of sync. It can also
1571 be made to happen with the trusted-key command and by
1572 importing and locally exported key. */
1574 clear_ownertrusts (pk);
1576 revalidation_mark ();
1581 if (!opt.quiet && !silent)
1583 char *p = get_user_id_byfpr_native (fpr2);
1584 log_info (_("key %s: public key \"%s\" imported\n"),
1588 if (is_status_enabled())
1590 char *us = get_long_user_id_string( keyid );
1591 write_status_text( STATUS_IMPORTED, us );
1593 print_import_ok (pk, 1);
1601 int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
1603 /* Compare the original against the new key; just to be sure nothing
1604 * weird is going on */
1605 if (cmp_public_keys( pk_orig, pk ) )
1608 log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
1612 /* Now read the original keyblock again so that we can use
1613 that handle for updating the keyblock. */
1617 rc = gpg_error_from_syserror ();
1620 keydb_disable_caching (hd);
1621 rc = keydb_search_fpr (hd, fpr2);
1624 log_error (_("key %s: can't locate original keyblock: %s\n"),
1625 keystr(keyid), gpg_strerror (rc));
1629 rc = keydb_get_keyblock (hd, &keyblock_orig);
1632 log_error (_("key %s: can't read original keyblock: %s\n"),
1633 keystr(keyid), gpg_strerror (rc));
1638 /* Make sure the original direct key sigs are all sane. */
1639 n_sigs_cleaned = fix_bad_direct_key_sigs (keyblock_orig, keyid);
1641 commit_kbnode (&keyblock_orig);
1643 /* and try to merge the block */
1644 clear_kbnode_flags( keyblock_orig );
1645 clear_kbnode_flags( keyblock );
1646 n_uids = n_sigs = n_subk = n_uids_cleaned = 0;
1647 rc = merge_blocks (keyblock_orig, keyblock,
1648 keyid, &n_uids, &n_sigs, &n_subk );
1655 if ((options & IMPORT_CLEAN))
1656 clean_key (keyblock_orig,opt.verbose,options&IMPORT_MINIMAL,
1657 &n_uids_cleaned,&n_sigs_cleaned);
1659 if (n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned)
1662 /* KEYBLOCK_ORIG has been updated; write */
1663 rc = keydb_update_keyblock (ctrl, hd, keyblock_orig);
1665 log_error (_("error writing keyring '%s': %s\n"),
1666 keydb_get_resource_name (hd), gpg_strerror (rc) );
1668 revalidation_mark ();
1671 if (!opt.quiet && !silent)
1673 char *p = get_user_id_byfpr_native (fpr2);
1675 log_info( _("key %s: \"%s\" 1 new user ID\n"),
1678 log_info( _("key %s: \"%s\" %d new user IDs\n"),
1679 keystr(keyid),p,n_uids);
1681 log_info( _("key %s: \"%s\" 1 new signature\n"),
1684 log_info( _("key %s: \"%s\" %d new signatures\n"),
1685 keystr(keyid), p, n_sigs );
1687 log_info( _("key %s: \"%s\" 1 new subkey\n"),
1690 log_info( _("key %s: \"%s\" %d new subkeys\n"),
1691 keystr(keyid), p, n_subk );
1692 if (n_sigs_cleaned==1)
1693 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
1694 keystr(keyid),p,n_sigs_cleaned);
1695 else if (n_sigs_cleaned)
1696 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
1697 keystr(keyid),p,n_sigs_cleaned);
1698 if (n_uids_cleaned==1)
1699 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
1700 keystr(keyid),p,n_uids_cleaned);
1701 else if (n_uids_cleaned)
1702 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
1703 keystr(keyid),p,n_uids_cleaned);
1707 stats->n_uids +=n_uids;
1708 stats->n_sigs +=n_sigs;
1709 stats->n_subk +=n_subk;
1710 stats->n_sigs_cleaned +=n_sigs_cleaned;
1711 stats->n_uids_cleaned +=n_uids_cleaned;
1713 if (is_status_enabled () && !silent)
1714 print_import_ok (pk, ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
1719 if (is_status_enabled ())
1720 print_import_ok (pk, 0);
1722 if (!opt.quiet && !silent)
1724 char *p = get_user_id_byfpr_native (fpr2);
1725 log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
1732 keydb_release (hd); hd = NULL;
1736 if (mod_key || new_key || same_key)
1738 /* A little explanation for this: we fill in the fingerprint
1739 when importing keys as it can be useful to know the
1740 fingerprint in certain keyserver-related cases (a keyserver
1741 asked for a particular name, but the key doesn't have that
1742 name). However, in cases where we're importing more than
1743 one key at a time, we cannot know which key to fingerprint.
1744 In these cases, rather than guessing, we do not
1745 fingerprinting at all, and we must hope the user ID on the
1746 keys are useful. Note that we need to do this for new
1747 keys, merged keys and even for unchanged keys. This is
1748 required because for example the --auto-key-locate feature
1749 may import an already imported key and needs to know the
1750 fingerprint of the key in all cases. */
1754 /* Note that we need to compare against 0 here because
1755 COUNT gets only incremented after returning from this
1758 *fpr = fingerprint_from_pk (pk, NULL, fpr_len);
1764 /* Now that the key is definitely incorporated into the keydb, we
1765 need to check if a designated revocation is present or if the
1766 prefs are not rational so we can warn the user. */
1770 revocation_present (ctrl, keyblock_orig);
1771 if (!from_sk && have_secret_key_with_kid (keyid))
1772 check_prefs (ctrl, keyblock_orig);
1776 revocation_present (ctrl, keyblock);
1777 if (!from_sk && have_secret_key_with_kid (keyid))
1778 check_prefs (ctrl, keyblock);
1781 release_kbnode( keyblock_orig );
1782 free_public_key( pk_orig );
1788 /* Transfer all the secret keys in SEC_KEYBLOCK to the gpg-agent. The
1789 function prints diagnostics and returns an error code. If BATCH is
1790 true the secret keys are stored by gpg-agent in the transfer format
1791 (i.e. no re-protection and aksing for passphrases). */
1793 transfer_secret_keys (ctrl_t ctrl, struct import_stats_s *stats,
1794 kbnode_t sec_keyblock, int batch, int force)
1796 gpg_error_t err = 0;
1799 kbnode_t ctx = NULL;
1801 PKT_public_key *main_pk, *pk;
1802 struct seckey_info *ski;
1806 void *format_args[2*PUBKEY_MAX_NSKEY];
1807 gcry_sexp_t skey, prot, tmpsexp;
1808 gcry_sexp_t curve = NULL;
1809 unsigned char *transferkey = NULL;
1810 size_t transferkeylen;
1811 gcry_cipher_hd_t cipherhd = NULL;
1812 unsigned char *wrappedkey = NULL;
1813 size_t wrappedkeylen;
1814 char *cache_nonce = NULL;
1815 int stub_key_skipped = 0;
1817 /* Get the current KEK. */
1818 err = agent_keywrap_key (ctrl, 0, &kek, &keklen);
1821 log_error ("error getting the KEK: %s\n", gpg_strerror (err));
1825 /* Prepare a cipher context. */
1826 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
1827 GCRY_CIPHER_MODE_AESWRAP, 0);
1829 err = gcry_cipher_setkey (cipherhd, kek, keklen);
1836 while ((node = walk_kbnode (sec_keyblock, &ctx, 0)))
1838 if (node->pkt->pkttype != PKT_SECRET_KEY
1839 && node->pkt->pkttype != PKT_SECRET_SUBKEY)
1841 pk = node->pkt->pkt.public_key;
1845 /* Make sure the keyids are available. */
1846 keyid_from_pk (pk, NULL);
1847 if (node->pkt->pkttype == PKT_SECRET_KEY)
1849 pk->main_keyid[0] = pk->keyid[0];
1850 pk->main_keyid[1] = pk->keyid[1];
1854 pk->main_keyid[0] = main_pk->keyid[0];
1855 pk->main_keyid[1] = main_pk->keyid[1];
1859 ski = pk->seckey_info;
1866 stats->secret_read++;
1869 /* We ignore stub keys. The way we handle them in other parts
1870 of the code is by asking the agent whether any secret key is
1871 available for a given keyblock and then concluding that we
1872 have a secret key; all secret (sub)keys of the keyblock the
1873 agent does not know of are then stub keys. This works also
1874 for card stub keys. The learn command or the card-status
1875 command may be used to check with the agent whether a card
1876 has been inserted and a stub key is in turn generated by the
1878 if (ski->s2k.mode == 1001 || ski->s2k.mode == 1002)
1880 stub_key_skipped = 1;
1884 /* Convert our internal secret key object into an S-expression. */
1885 nskey = pubkey_get_nskey (pk->pubkey_algo);
1886 if (!nskey || nskey > PUBKEY_MAX_NSKEY)
1888 err = gpg_error (GPG_ERR_BAD_SECKEY);
1889 log_error ("internal error: %s\n", gpg_strerror (err));
1893 init_membuf (&mbuf, 50);
1894 put_membuf_str (&mbuf, "(skey");
1895 if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
1896 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
1897 || pk->pubkey_algo == PUBKEY_ALGO_ECDH)
1900 char *curvestr = openpgp_oid_to_str (pk->pkey[0]);
1902 err = gpg_error_from_syserror ();
1905 const char *curvename = openpgp_oid_to_curve (curvestr, 1);
1906 gcry_sexp_release (curve);
1907 err = gcry_sexp_build (&curve, NULL, "(curve %s)",
1908 curvename?curvename:curvestr);
1913 /* Append the public key element Q. */
1914 put_membuf_str (&mbuf, " _ %m");
1915 format_args[j++] = pk->pkey + 1;
1917 /* Append the secret key element D. For ECDH we
1918 skip PKEY[2] because this holds the KEK which is
1919 not needed by gpg-agent. */
1920 i = pk->pubkey_algo == PUBKEY_ALGO_ECDH? 3 : 2;
1921 if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
1922 put_membuf_str (&mbuf, " e %m");
1924 put_membuf_str (&mbuf, " _ %m");
1925 format_args[j++] = pk->pkey + i;
1931 /* Standard case for the old (non-ECC) algorithms. */
1932 for (i=j=0; i < nskey; i++)
1935 continue; /* Protected keys only have NPKEY+1 elements. */
1937 if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
1938 put_membuf_str (&mbuf, " e %m");
1940 put_membuf_str (&mbuf, " _ %m");
1941 format_args[j++] = pk->pkey + i;
1944 put_membuf_str (&mbuf, ")");
1945 put_membuf (&mbuf, "", 1);
1947 xfree (get_membuf (&mbuf, NULL));
1950 char *format = get_membuf (&mbuf, NULL);
1952 err = gpg_error_from_syserror ();
1954 err = gcry_sexp_build_array (&skey, NULL, format, format_args);
1959 log_error ("error building skey array: %s\n", gpg_strerror (err));
1963 if (ski->is_protected)
1967 /* Note that the IVLEN may be zero if we are working on a
1968 dummy key. We can't express that in an S-expression and
1969 thus we send dummy data for the IV. */
1970 snprintf (countbuf, sizeof countbuf, "%lu",
1971 (unsigned long)ski->s2k.count);
1972 err = gcry_sexp_build
1974 " (protection %s %s %b %d %s %b %s)\n",
1975 ski->sha1chk? "sha1":"sum",
1976 openpgp_cipher_algo_name (ski->algo),
1977 ski->ivlen? (int)ski->ivlen:1,
1978 ski->ivlen? ski->iv: (const unsigned char*)"X",
1980 openpgp_md_algo_name (ski->s2k.hash_algo),
1981 (int)sizeof (ski->s2k.salt), ski->s2k.salt,
1985 err = gcry_sexp_build (&prot, NULL, " (protection none)\n");
1988 xfree (transferkey);
1991 err = gcry_sexp_build (&tmpsexp, NULL,
1992 "(openpgp-private-key\n"
1999 openpgp_pk_algo_name (pk->pubkey_algo),
2001 (int)(unsigned long)ski->csum, prot);
2002 gcry_sexp_release (skey);
2003 gcry_sexp_release (prot);
2005 err = make_canon_sexp_pad (tmpsexp, 1, &transferkey, &transferkeylen);
2006 gcry_sexp_release (tmpsexp);
2009 log_error ("error building transfer key: %s\n", gpg_strerror (err));
2014 wrappedkeylen = transferkeylen + 8;
2016 wrappedkey = xtrymalloc (wrappedkeylen);
2018 err = gpg_error_from_syserror ();
2020 err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen,
2021 transferkey, transferkeylen);
2024 xfree (transferkey);
2027 /* Send the wrapped key to the agent. */
2029 char *desc = gpg_format_keydesc (pk, FORMAT_KEYDESC_IMPORT, 1);
2030 err = agent_import_key (ctrl, desc, &cache_nonce,
2031 wrappedkey, wrappedkeylen, batch, force);
2037 log_info (_("key %s: secret key imported\n"),
2038 keystr_from_pk_with_sub (main_pk, pk));
2040 stats->secret_imported++;
2042 else if ( gpg_err_code (err) == GPG_ERR_EEXIST )
2045 log_info (_("key %s: secret key already exists\n"),
2046 keystr_from_pk_with_sub (main_pk, pk));
2049 stats->secret_dups++;
2053 log_error (_("key %s: error sending to agent: %s\n"),
2054 keystr_from_pk_with_sub (main_pk, pk),
2055 gpg_strerror (err));
2056 if (gpg_err_code (err) == GPG_ERR_CANCELED
2057 || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
2058 break; /* Don't try the other subkeys. */
2062 if (!err && stub_key_skipped)
2063 /* We need to notify user how to migrate stub keys. */
2064 err = gpg_error (GPG_ERR_NOT_PROCESSED);
2067 gcry_sexp_release (curve);
2068 xfree (cache_nonce);
2070 xfree (transferkey);
2071 gcry_cipher_close (cipherhd);
2077 /* Walk a secret keyblock and produce a public keyblock out of it.
2078 Returns a new node or NULL on error. */
2080 sec_to_pub_keyblock (kbnode_t sec_keyblock)
2082 kbnode_t pub_keyblock = NULL;
2083 kbnode_t ctx = NULL;
2084 kbnode_t secnode, pubnode;
2086 while ((secnode = walk_kbnode (sec_keyblock, &ctx, 0)))
2088 if (secnode->pkt->pkttype == PKT_SECRET_KEY
2089 || secnode->pkt->pkttype == PKT_SECRET_SUBKEY)
2091 /* Make a public key. */
2095 pkt = xtrycalloc (1, sizeof *pkt);
2096 pk = pkt? copy_public_key (NULL, secnode->pkt->pkt.public_key): NULL;
2100 release_kbnode (pub_keyblock);
2103 if (secnode->pkt->pkttype == PKT_SECRET_KEY)
2104 pkt->pkttype = PKT_PUBLIC_KEY;
2106 pkt->pkttype = PKT_PUBLIC_SUBKEY;
2107 pkt->pkt.public_key = pk;
2109 pubnode = new_kbnode (pkt);
2113 pubnode = clone_kbnode (secnode);
2117 pub_keyblock = pubnode;
2119 add_kbnode (pub_keyblock, pubnode);
2122 return pub_keyblock;
2126 * Ditto for secret keys. Handling is simpler than for public keys.
2127 * We allow secret key importing only when allow is true, this is so
2128 * that a secret key can not be imported accidentally and thereby tampering
2129 * with the trust calculation.
2132 import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
2133 struct import_stats_s *stats, int batch, unsigned int options,
2135 import_screener_t screener, void *screener_arg)
2138 struct seckey_info *ski;
2139 kbnode_t node, uidnode;
2143 kbnode_t pub_keyblock;
2144 char pkstrbuf[PUBKEY_STRING_SIZE];
2146 /* Get the key and print some info about it */
2147 node = find_kbnode (keyblock, PKT_SECRET_KEY);
2151 pk = node->pkt->pkt.public_key;
2153 keyid_from_pk (pk, keyid);
2154 uidnode = find_next_kbnode (keyblock, PKT_USER_ID);
2156 if (screener && screener (keyblock, screener_arg))
2158 log_error (_("secret key %s: %s\n"), keystr_from_pk (pk),
2159 _("rejected by import screener"));
2163 if (opt.verbose && !for_migration)
2165 log_info ("sec %s/%s %s ",
2166 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
2167 keystr_from_pk (pk), datestr_from_pk (pk));
2169 print_utf8_buffer (log_get_stream (), uidnode->pkt->pkt.user_id->name,
2170 uidnode->pkt->pkt.user_id->len);
2173 stats->secret_read++;
2175 if ((options & IMPORT_NO_SECKEY))
2178 log_error (_("importing secret keys not allowed\n"));
2185 log_error( _("key %s: no user ID\n"), keystr_from_pk (pk));
2189 ski = pk->seckey_info;
2192 /* Actually an internal error. */
2193 log_error ("key %s: secret key info missing\n", keystr_from_pk (pk));
2197 /* A quick check to not import keys with an invalid protection
2198 cipher algorithm (only checks the primary key, though). */
2199 if (ski->algo > 110)
2202 log_error (_("key %s: secret key with invalid cipher %d"
2203 " - skipped\n"), keystr_from_pk (pk), ski->algo);
2207 #ifdef ENABLE_SELINUX_HACKS
2210 /* We don't allow importing secret keys because that may be used
2211 to put a secret key into the keyring and the user might later
2212 be tricked into signing stuff with that key. */
2213 log_error (_("importing secret keys not allowed\n"));
2218 clear_kbnode_flags (keyblock);
2220 nr_prev = stats->skipped_new_keys;
2222 /* Make a public key out of the key. */
2223 pub_keyblock = sec_to_pub_keyblock (keyblock);
2225 log_error ("key %s: failed to create public key from secret key\n",
2226 keystr_from_pk (pk));
2229 /* Note that this outputs an IMPORT_OK status message for the
2230 public key block, and below we will output another one for
2231 the secret keys. FIXME? */
2232 import_one (ctrl, pub_keyblock, stats,
2233 NULL, NULL, options, 1, for_migration,
2234 screener, screener_arg);
2236 /* Fixme: We should check for an invalid keyblock and
2237 cancel the secret key import in this case. */
2238 release_kbnode (pub_keyblock);
2240 /* At least we cancel the secret key import when the public key
2241 import was skipped due to MERGE_ONLY option and a new
2243 if (stats->skipped_new_keys <= nr_prev)
2245 /* Read the keyblock again to get the effects of a merge. */
2246 /* Fixme: we should do this based on the fingerprint or
2247 even better let import_one return the merged
2249 node = get_pubkeyblock (keyid);
2251 log_error ("key %s: failed to re-lookup public key\n",
2252 keystr_from_pk (pk));
2257 /* transfer_secret_keys collects subkey stats. */
2258 struct import_stats_s subkey_stats = {0};
2260 err = transfer_secret_keys (ctrl, &subkey_stats, keyblock,
2262 if (gpg_err_code (err) == GPG_ERR_NOT_PROCESSED)
2264 /* TRANSLATORS: For smartcard, each private key on
2265 host has a reference (stub) to a smartcard and
2266 actual private key data is stored on the card. A
2267 single smartcard can have up to three private key
2268 data. Importing private key stub is always
2269 skipped in 2.1, and it returns
2270 GPG_ERR_NOT_PROCESSED. Instead, user should be
2271 suggested to run 'gpg --card-status', then,
2272 references to a card will be automatically
2274 log_info (_("To migrate '%s', with each smartcard, "
2275 "run: %s\n"), "secring.gpg", "gpg --card-status");
2282 log_info (_("key %s: secret key imported\n"),
2283 keystr_from_pk (pk));
2284 if (subkey_stats.secret_imported)
2287 stats->secret_imported += 1;
2289 if (subkey_stats.secret_dups)
2290 stats->secret_dups += 1;
2292 if (is_status_enabled ())
2293 print_import_ok (pk, status);
2294 check_prefs (ctrl, node);
2296 release_kbnode (node);
2306 * Import a revocation certificate; this is a single signature packet.
2309 import_revoke_cert (ctrl_t ctrl, kbnode_t node, struct import_stats_s *stats)
2311 PKT_public_key *pk = NULL;
2313 kbnode_t keyblock = NULL;
2314 KEYDB_HANDLE hd = NULL;
2318 log_assert (!node->next );
2319 log_assert (node->pkt->pkttype == PKT_SIGNATURE );
2320 log_assert (node->pkt->pkt.signature->sig_class == 0x20 );
2322 keyid[0] = node->pkt->pkt.signature->keyid[0];
2323 keyid[1] = node->pkt->pkt.signature->keyid[1];
2325 pk = xmalloc_clear( sizeof *pk );
2326 rc = get_pubkey( pk, keyid );
2327 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY )
2329 log_error(_("key %s: no public key -"
2330 " can't apply revocation certificate\n"), keystr(keyid));
2336 log_error(_("key %s: public key not found: %s\n"),
2337 keystr(keyid), gpg_strerror (rc));
2341 /* Read the original keyblock. */
2345 rc = gpg_error_from_syserror ();
2350 byte afp[MAX_FINGERPRINT_LEN];
2353 fingerprint_from_pk (pk, afp, &an);
2354 while (an < MAX_FINGERPRINT_LEN)
2356 rc = keydb_search_fpr (hd, afp);
2360 log_error (_("key %s: can't locate original keyblock: %s\n"),
2361 keystr(keyid), gpg_strerror (rc));
2364 rc = keydb_get_keyblock (hd, &keyblock );
2367 log_error (_("key %s: can't read original keyblock: %s\n"),
2368 keystr(keyid), gpg_strerror (rc));
2372 /* it is okay, that node is not in keyblock because
2373 * check_key_signature works fine for sig_class 0x20 in this
2375 rc = check_key_signature( keyblock, node, NULL);
2378 log_error( _("key %s: invalid revocation certificate"
2379 ": %s - rejected\n"), keystr(keyid), gpg_strerror (rc));
2383 /* check whether we already have this */
2384 for(onode=keyblock->next; onode; onode=onode->next ) {
2385 if (onode->pkt->pkttype == PKT_USER_ID )
2387 else if (onode->pkt->pkttype == PKT_SIGNATURE
2388 && !cmp_signatures(node->pkt->pkt.signature,
2389 onode->pkt->pkt.signature))
2392 goto leave; /* yes, we already know about it */
2397 insert_kbnode( keyblock, clone_kbnode(node), 0 );
2399 /* and write the keyblock back */
2400 rc = keydb_update_keyblock (ctrl, hd, keyblock );
2402 log_error (_("error writing keyring '%s': %s\n"),
2403 keydb_get_resource_name (hd), gpg_strerror (rc) );
2410 char *p=get_user_id_native (keyid);
2411 log_info( _("key %s: \"%s\" revocation certificate imported\n"),
2417 /* If the key we just revoked was ultimately trusted, remove its
2418 ultimate trust. This doesn't stop the user from putting the
2419 ultimate trust back, but is a reasonable solution for now. */
2420 if(get_ownertrust(pk)==TRUST_ULTIMATE)
2421 clear_ownertrusts(pk);
2423 revalidation_mark ();
2427 release_kbnode( keyblock );
2428 free_public_key( pk );
2433 /* Loop over the keyblock and check all self signatures. On return
2434 * the following bis in the node flags are set:
2436 * - NODE_GOOD_SELFSIG :: User ID or subkey has a self-signature
2437 * - NODE_BAD_SELFSIG :: Used ID or subkey has an invalid self-signature
2438 * - NODE_DELETION_MARK :: This node shall be deleted
2440 * NON_SELF is set to true if there are any sigs other than self-sigs
2443 * Returns 0 on success or -1 (but not an error code) if the keyblock
2447 chk_self_sigs (kbnode_t keyblock, u32 *keyid, int *non_self )
2449 kbnode_t n, knode = NULL;
2452 u32 bsdate=0, rsdate=0;
2453 kbnode_t bsnode = NULL, rsnode = NULL;
2455 for (n=keyblock; (n = find_next_kbnode (n, 0)); )
2457 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2467 if ( n->pkt->pkttype != PKT_SIGNATURE )
2470 sig = n->pkt->pkt.signature;
2471 if ( keyid[0] != sig->keyid[0] || keyid[1] != sig->keyid[1] )
2477 /* This just caches the sigs for later use. That way we
2478 import a fully-cached key which speeds things up. */
2479 if (!opt.no_sig_cache)
2480 check_key_signature (keyblock, n, NULL);
2482 if ( IS_UID_SIG(sig) || IS_UID_REV(sig) )
2484 kbnode_t unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
2487 log_error( _("key %s: no user ID for signature\n"),
2489 return -1; /* The complete keyblock is invalid. */
2492 /* If it hasn't been marked valid yet, keep trying. */
2493 if (!(unode->flag & NODE_GOOD_SELFSIG))
2495 rc = check_key_signature (keyblock, n, NULL);
2500 char *p = utf8_to_native
2501 (unode->pkt->pkt.user_id->name,
2502 strlen (unode->pkt->pkt.user_id->name),0);
2503 log_info (gpg_err_code(rc) == GPG_ERR_PUBKEY_ALGO ?
2504 _("key %s: unsupported public key "
2505 "algorithm on user ID \"%s\"\n"):
2506 _("key %s: invalid self-signature "
2507 "on user ID \"%s\"\n"),
2513 unode->flag |= NODE_GOOD_SELFSIG;
2516 else if (IS_KEY_SIG (sig))
2518 rc = check_key_signature (keyblock, n, NULL);
2522 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
2523 _("key %s: unsupported public key algorithm\n"):
2524 _("key %s: invalid direct key signature\n"),
2526 n->flag |= NODE_DELETION_MARK;
2529 else if ( IS_SUBKEY_SIG (sig) )
2531 /* Note that this works based solely on the timestamps like
2532 the rest of gpg. If the standard gets revocation
2533 targets, this may need to be revised. */
2538 log_info (_("key %s: no subkey for key binding\n"),
2540 n->flag |= NODE_DELETION_MARK;
2544 rc = check_key_signature (keyblock, n, NULL);
2548 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
2549 _("key %s: unsupported public key"
2551 _("key %s: invalid subkey binding\n"),
2553 n->flag |= NODE_DELETION_MARK;
2557 /* It's valid, so is it newer? */
2558 if (sig->timestamp >= bsdate)
2560 knode->flag |= NODE_GOOD_SELFSIG; /* Subkey is valid. */
2563 /* Delete the last binding sig since this
2565 bsnode->flag |= NODE_DELETION_MARK;
2567 log_info (_("key %s: removed multiple subkey"
2568 " binding\n"),keystr(keyid));
2572 bsdate = sig->timestamp;
2575 n->flag |= NODE_DELETION_MARK; /* older */
2579 else if ( IS_SUBKEY_REV (sig) )
2581 /* We don't actually mark the subkey as revoked right now,
2582 so just check that the revocation sig is the most recent
2583 valid one. Note that we don't care if the binding sig is
2584 newer than the revocation sig. See the comment in
2585 getkey.c:merge_selfsigs_subkey for more. */
2589 log_info (_("key %s: no subkey for key revocation\n"),
2591 n->flag |= NODE_DELETION_MARK;
2595 rc = check_key_signature (keyblock, n, NULL);
2599 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
2600 _("key %s: unsupported public"
2601 " key algorithm\n"):
2602 _("key %s: invalid subkey revocation\n"),
2604 n->flag |= NODE_DELETION_MARK;
2608 /* It's valid, so is it newer? */
2609 if (sig->timestamp >= rsdate)
2613 /* Delete the last revocation sig since
2614 this one is newer. */
2615 rsnode->flag |= NODE_DELETION_MARK;
2617 log_info (_("key %s: removed multiple subkey"
2618 " revocation\n"),keystr(keyid));
2622 rsdate = sig->timestamp;
2625 n->flag |= NODE_DELETION_MARK; /* older */
2635 /* Delete all parts which are invalid and those signatures whose
2636 * public key algorithm is not available in this implemenation; but
2637 * consider RSA as valid, because parse/build_packets knows about it.
2639 * Returns: True if at least one valid user-id is left over.
2642 delete_inv_parts (kbnode_t keyblock, u32 *keyid, unsigned int options)
2645 int nvalid=0, uid_seen=0, subkey_seen=0;
2647 for (node=keyblock->next; node; node = node->next )
2649 if (node->pkt->pkttype == PKT_USER_ID)
2652 if ((node->flag & NODE_BAD_SELFSIG)
2653 || !(node->flag & NODE_GOOD_SELFSIG))
2657 char *p=utf8_to_native(node->pkt->pkt.user_id->name,
2658 node->pkt->pkt.user_id->len,0);
2659 log_info( _("key %s: skipped user ID \"%s\"\n"),
2663 delete_kbnode( node ); /* the user-id */
2664 /* and all following packets up to the next user-id */
2666 && node->next->pkt->pkttype != PKT_USER_ID
2667 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
2668 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
2669 delete_kbnode( node->next );
2676 else if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2677 || node->pkt->pkttype == PKT_SECRET_SUBKEY )
2679 if ((node->flag & NODE_BAD_SELFSIG)
2680 || !(node->flag & NODE_GOOD_SELFSIG))
2683 log_info( _("key %s: skipped subkey\n"),keystr(keyid));
2685 delete_kbnode( node ); /* the subkey */
2686 /* and all following signature packets */
2688 && node->next->pkt->pkttype == PKT_SIGNATURE ) {
2689 delete_kbnode( node->next );
2696 else if (node->pkt->pkttype == PKT_SIGNATURE
2697 && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
2698 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
2700 delete_kbnode( node ); /* build_packet() can't handle this */
2702 else if (node->pkt->pkttype == PKT_SIGNATURE
2703 && !node->pkt->pkt.signature->flags.exportable
2704 && !(options&IMPORT_LOCAL_SIGS)
2705 && !have_secret_key_with_kid (node->pkt->pkt.signature->keyid))
2707 /* here we violate the rfc a bit by still allowing
2708 * to import non-exportable signature when we have the
2709 * the secret key used to create this signature - it
2710 * seems that this makes sense */
2712 log_info( _("key %s: non exportable signature"
2713 " (class 0x%02X) - skipped\n"),
2714 keystr(keyid), node->pkt->pkt.signature->sig_class );
2715 delete_kbnode( node );
2717 else if (node->pkt->pkttype == PKT_SIGNATURE
2718 && node->pkt->pkt.signature->sig_class == 0x20)
2723 log_info( _("key %s: revocation certificate"
2724 " at wrong place - skipped\n"),keystr(keyid));
2725 delete_kbnode( node );
2729 /* If the revocation cert is from a different key than
2730 the one we're working on don't check it - it's
2731 probably from a revocation key and won't be
2732 verifiable with this key anyway. */
2734 if(node->pkt->pkt.signature->keyid[0]==keyid[0]
2735 && node->pkt->pkt.signature->keyid[1]==keyid[1])
2737 int rc = check_key_signature( keyblock, node, NULL);
2741 log_info( _("key %s: invalid revocation"
2742 " certificate: %s - skipped\n"),
2743 keystr(keyid), gpg_strerror (rc));
2744 delete_kbnode( node );
2749 else if (node->pkt->pkttype == PKT_SIGNATURE
2750 && (node->pkt->pkt.signature->sig_class == 0x18
2751 || node->pkt->pkt.signature->sig_class == 0x28)
2755 log_info( _("key %s: subkey signature"
2756 " in wrong place - skipped\n"), keystr(keyid));
2757 delete_kbnode( node );
2759 else if (node->pkt->pkttype == PKT_SIGNATURE
2760 && !IS_CERT(node->pkt->pkt.signature))
2763 log_info(_("key %s: unexpected signature class (0x%02X) -"
2764 " skipped\n"),keystr(keyid),
2765 node->pkt->pkt.signature->sig_class);
2766 delete_kbnode(node);
2768 else if ((node->flag & NODE_DELETION_MARK))
2769 delete_kbnode( node );
2772 /* note: because keyblock is the public key, it is never marked
2773 * for deletion and so keyblock cannot change */
2774 commit_kbnode( &keyblock );
2778 /* This function returns true if any UID is left in the keyring. */
2780 any_uid_left (kbnode_t keyblock)
2784 for (node=keyblock->next; node; node = node->next)
2785 if (node->pkt->pkttype == PKT_USER_ID)
2793 * It may happen that the imported keyblock has duplicated user IDs.
2794 * We check this here and collapse those user IDs together with their
2796 * Returns: True if the keyblock has changed.
2799 collapse_uids( kbnode_t *keyblock )
2804 for(uid1=*keyblock;uid1;uid1=uid1->next)
2808 if(is_deleted_kbnode(uid1))
2811 if(uid1->pkt->pkttype!=PKT_USER_ID)
2814 for(uid2=uid1->next;uid2;uid2=uid2->next)
2816 if(is_deleted_kbnode(uid2))
2819 if(uid2->pkt->pkttype!=PKT_USER_ID)
2822 if(cmp_user_ids(uid1->pkt->pkt.user_id,
2823 uid2->pkt->pkt.user_id)==0)
2825 /* We have a duplicated uid */
2830 /* Now take uid2's signatures, and attach them to
2832 for(last=uid2;last->next;last=last->next)
2834 if(is_deleted_kbnode(last))
2837 if(last->next->pkt->pkttype==PKT_USER_ID
2838 || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
2839 || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
2844 (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
2846 /* Now put uid2 in place as part of uid1 */
2847 last->next=uid1->next;
2849 delete_kbnode(uid2);
2851 /* Now dedupe uid1 */
2852 for(sig1=uid1->next;sig1;sig1=sig1->next)
2856 if(is_deleted_kbnode(sig1))
2859 if(sig1->pkt->pkttype==PKT_USER_ID
2860 || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
2861 || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
2864 if(sig1->pkt->pkttype!=PKT_SIGNATURE)
2867 for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
2869 if(is_deleted_kbnode(sig2))
2872 if(sig2->pkt->pkttype==PKT_USER_ID
2873 || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
2874 || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
2877 if(sig2->pkt->pkttype!=PKT_SIGNATURE)
2880 if(cmp_signatures(sig1->pkt->pkt.signature,
2881 sig2->pkt->pkt.signature)==0)
2883 /* We have a match, so delete the second
2885 delete_kbnode(sig2);
2894 commit_kbnode(keyblock);
2896 if(any && !opt.quiet)
2898 const char *key="???";
2900 if ((uid1 = find_kbnode (*keyblock, PKT_PUBLIC_KEY)) )
2901 key = keystr_from_pk (uid1->pkt->pkt.public_key);
2902 else if ((uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY)) )
2903 key = keystr_from_pk (uid1->pkt->pkt.public_key);
2905 log_info (_("key %s: duplicated user ID detected - merged\n"), key);
2912 /* Check for a 0x20 revocation from a revocation key that is not
2913 present. This may be called without the benefit of merge_xxxx so
2914 you can't rely on pk->revkey and friends. */
2916 revocation_present (ctrl_t ctrl, kbnode_t keyblock)
2918 kbnode_t onode, inode;
2919 PKT_public_key *pk = keyblock->pkt->pkt.public_key;
2921 for(onode=keyblock->next;onode;onode=onode->next)
2923 /* If we reach user IDs, we're done. */
2924 if(onode->pkt->pkttype==PKT_USER_ID)
2927 if(onode->pkt->pkttype==PKT_SIGNATURE &&
2928 onode->pkt->pkt.signature->sig_class==0x1F &&
2929 onode->pkt->pkt.signature->revkey)
2932 PKT_signature *sig=onode->pkt->pkt.signature;
2934 for(idx=0;idx<sig->numrevkeys;idx++)
2938 keyid_from_fingerprint(sig->revkey[idx].fpr,
2939 MAX_FINGERPRINT_LEN,keyid);
2941 for(inode=keyblock->next;inode;inode=inode->next)
2943 /* If we reach user IDs, we're done. */
2944 if(inode->pkt->pkttype==PKT_USER_ID)
2947 if(inode->pkt->pkttype==PKT_SIGNATURE &&
2948 inode->pkt->pkt.signature->sig_class==0x20 &&
2949 inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
2950 inode->pkt->pkt.signature->keyid[1]==keyid[1])
2952 /* Okay, we have a revocation key, and a
2953 revocation issued by it. Do we have the key
2957 rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx].fpr,
2958 MAX_FINGERPRINT_LEN);
2959 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2960 || gpg_err_code (rc) == GPG_ERR_UNUSABLE_PUBKEY)
2962 char *tempkeystr=xstrdup(keystr_from_pk(pk));
2964 /* No, so try and get it */
2965 if ((opt.keyserver_options.options
2966 & KEYSERVER_AUTO_KEY_RETRIEVE)
2967 && keyserver_any_configured (ctrl))
2969 log_info(_("WARNING: key %s may be revoked:"
2970 " fetching revocation key %s\n"),
2971 tempkeystr,keystr(keyid));
2972 keyserver_import_fprint (ctrl,
2973 sig->revkey[idx].fpr,
2974 MAX_FINGERPRINT_LEN,
2977 /* Do we have it now? */
2978 rc=get_pubkey_byfprint_fast (NULL,
2979 sig->revkey[idx].fpr,
2980 MAX_FINGERPRINT_LEN);
2983 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2984 || gpg_err_code (rc) == GPG_ERR_UNUSABLE_PUBKEY)
2985 log_info(_("WARNING: key %s may be revoked:"
2986 " revocation key %s not present.\n"),
2987 tempkeystr,keystr(keyid));
3000 * compare and merge the blocks
3002 * o compare the signatures: If we already have this signature, check
3003 * that they compare okay; if not, issue a warning and ask the user.
3004 * o Simply add the signature. Can't verify here because we may not have
3005 * the signature's public key yet; verification is done when putting it
3006 * into the trustdb, which is done automagically as soon as this pubkey
3008 * Note: We indicate newly inserted packets with NODE_FLAG_A.
3011 merge_blocks (kbnode_t keyblock_orig, kbnode_t keyblock,
3012 u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
3014 kbnode_t onode, node;
3017 /* 1st: handle revocation certificates */
3018 for (node=keyblock->next; node; node=node->next )
3020 if (node->pkt->pkttype == PKT_USER_ID )
3022 else if (node->pkt->pkttype == PKT_SIGNATURE
3023 && node->pkt->pkt.signature->sig_class == 0x20)
3025 /* check whether we already have this */
3027 for (onode=keyblock_orig->next; onode; onode=onode->next)
3029 if (onode->pkt->pkttype == PKT_USER_ID )
3031 else if (onode->pkt->pkttype == PKT_SIGNATURE
3032 && onode->pkt->pkt.signature->sig_class == 0x20
3033 && !cmp_signatures(onode->pkt->pkt.signature,
3034 node->pkt->pkt.signature))
3042 kbnode_t n2 = clone_kbnode(node);
3043 insert_kbnode( keyblock_orig, n2, 0 );
3044 n2->flag |= NODE_FLAG_A;
3048 char *p=get_user_id_native (keyid);
3049 log_info(_("key %s: \"%s\" revocation"
3050 " certificate added\n"), keystr(keyid),p);
3057 /* 2nd: merge in any direct key (0x1F) sigs */
3058 for(node=keyblock->next; node; node=node->next)
3060 if (node->pkt->pkttype == PKT_USER_ID )
3062 else if (node->pkt->pkttype == PKT_SIGNATURE
3063 && node->pkt->pkt.signature->sig_class == 0x1F)
3065 /* check whether we already have this */
3067 for (onode=keyblock_orig->next; onode; onode=onode->next)
3069 if (onode->pkt->pkttype == PKT_USER_ID)
3071 else if (onode->pkt->pkttype == PKT_SIGNATURE
3072 && onode->pkt->pkt.signature->sig_class == 0x1F
3073 && !cmp_signatures(onode->pkt->pkt.signature,
3074 node->pkt->pkt.signature))
3082 kbnode_t n2 = clone_kbnode(node);
3083 insert_kbnode( keyblock_orig, n2, 0 );
3084 n2->flag |= NODE_FLAG_A;
3087 log_info( _("key %s: direct key signature added\n"),
3093 /* 3rd: try to merge new certificates in */
3094 for (onode=keyblock_orig->next; onode; onode=onode->next)
3096 if (!(onode->flag & NODE_FLAG_A) && onode->pkt->pkttype == PKT_USER_ID)
3098 /* find the user id in the imported keyblock */
3099 for (node=keyblock->next; node; node=node->next)
3100 if (node->pkt->pkttype == PKT_USER_ID
3101 && !cmp_user_ids( onode->pkt->pkt.user_id,
3102 node->pkt->pkt.user_id ) )
3104 if (node ) /* found: merge */
3106 rc = merge_sigs (onode, node, n_sigs);
3113 /* 4th: add new user-ids */
3114 for (node=keyblock->next; node; node=node->next)
3116 if (node->pkt->pkttype == PKT_USER_ID)
3118 /* do we have this in the original keyblock */
3119 for (onode=keyblock_orig->next; onode; onode=onode->next )
3120 if (onode->pkt->pkttype == PKT_USER_ID
3121 && !cmp_user_ids( onode->pkt->pkt.user_id,
3122 node->pkt->pkt.user_id ) )
3124 if (!onode ) /* this is a new user id: append */
3126 rc = append_uid (keyblock_orig, node, n_sigs);
3134 /* 5th: add new subkeys */
3135 for (node=keyblock->next; node; node=node->next)
3138 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3140 /* do we have this in the original keyblock? */
3141 for(onode=keyblock_orig->next; onode; onode=onode->next)
3142 if (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
3143 && !cmp_public_keys( onode->pkt->pkt.public_key,
3144 node->pkt->pkt.public_key))
3146 if (!onode ) /* This is a new subkey: append. */
3148 rc = append_key (keyblock_orig, node, n_sigs);
3154 else if (node->pkt->pkttype == PKT_SECRET_SUBKEY)
3156 /* do we have this in the original keyblock? */
3157 for (onode=keyblock_orig->next; onode; onode=onode->next )
3158 if (onode->pkt->pkttype == PKT_SECRET_SUBKEY
3159 && !cmp_public_keys (onode->pkt->pkt.public_key,
3160 node->pkt->pkt.public_key) )
3162 if (!onode ) /* This is a new subkey: append. */
3164 rc = append_key (keyblock_orig, node, n_sigs);
3172 /* 6th: merge subkey certificates */
3173 for (onode=keyblock_orig->next; onode; onode=onode->next)
3175 if (!(onode->flag & NODE_FLAG_A)
3176 && (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
3177 || onode->pkt->pkttype == PKT_SECRET_SUBKEY))
3179 /* find the subkey in the imported keyblock */
3180 for(node=keyblock->next; node; node=node->next)
3182 if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
3183 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
3184 && !cmp_public_keys( onode->pkt->pkt.public_key,
3185 node->pkt->pkt.public_key ) )
3188 if (node) /* Found: merge. */
3190 rc = merge_keysigs( onode, node, n_sigs);
3201 /* Helper function for merge_blocks.
3202 * Append the userid starting with NODE and all signatures to KEYBLOCK.
3205 append_uid (kbnode_t keyblock, kbnode_t node, int *n_sigs)
3208 kbnode_t n_where = NULL;
3210 log_assert (node->pkt->pkttype == PKT_USER_ID );
3212 /* find the position */
3213 for (n = keyblock; n; n_where = n, n = n->next)
3215 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
3216 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
3222 /* and append/insert */
3225 /* we add a clone to the original keyblock, because this
3226 * one is released first */
3227 n = clone_kbnode(node);
3230 insert_kbnode( n_where, n, 0 );
3234 add_kbnode( keyblock, n );
3235 n->flag |= NODE_FLAG_A;
3236 node->flag |= NODE_FLAG_A;
3237 if (n->pkt->pkttype == PKT_SIGNATURE )
3241 if (node && node->pkt->pkttype != PKT_SIGNATURE )
3249 /* Helper function for merge_blocks
3250 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
3251 * (how should we handle comment packets here?)
3254 merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs)
3259 log_assert (dst->pkt->pkttype == PKT_USER_ID);
3260 log_assert (src->pkt->pkttype == PKT_USER_ID);
3262 for (n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next)
3264 if (n->pkt->pkttype != PKT_SIGNATURE )
3266 if (n->pkt->pkt.signature->sig_class == 0x18
3267 || n->pkt->pkt.signature->sig_class == 0x28 )
3268 continue; /* skip signatures which are only valid on subkeys */
3271 for (n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
3272 if (!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
3279 /* This signature is new or newer, append N to DST.
3280 * We add a clone to the original keyblock, because this
3281 * one is released first */
3282 n2 = clone_kbnode(n);
3283 insert_kbnode( dst, n2, PKT_SIGNATURE );
3284 n2->flag |= NODE_FLAG_A;
3285 n->flag |= NODE_FLAG_A;
3294 /* Helper function for merge_blocks
3295 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
3298 merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs)
3303 log_assert (dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
3304 || dst->pkt->pkttype == PKT_SECRET_SUBKEY);
3306 for (n=src->next; n ; n = n->next)
3308 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
3309 || n->pkt->pkttype == PKT_PUBLIC_KEY )
3311 if (n->pkt->pkttype != PKT_SIGNATURE )
3315 for (n2=dst->next; n2; n2 = n2->next)
3317 if (n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
3318 || n2->pkt->pkttype == PKT_PUBLIC_KEY )
3320 if (n2->pkt->pkttype == PKT_SIGNATURE
3321 && (n->pkt->pkt.signature->keyid[0]
3322 == n2->pkt->pkt.signature->keyid[0])
3323 && (n->pkt->pkt.signature->keyid[1]
3324 == n2->pkt->pkt.signature->keyid[1])
3325 && (n->pkt->pkt.signature->timestamp
3326 <= n2->pkt->pkt.signature->timestamp)
3327 && (n->pkt->pkt.signature->sig_class
3328 == n2->pkt->pkt.signature->sig_class))
3336 /* This signature is new or newer, append N to DST.
3337 * We add a clone to the original keyblock, because this
3338 * one is released first */
3339 n2 = clone_kbnode(n);
3340 insert_kbnode( dst, n2, PKT_SIGNATURE );
3341 n2->flag |= NODE_FLAG_A;
3342 n->flag |= NODE_FLAG_A;
3351 /* Helper function for merge_blocks.
3352 * Append the subkey starting with NODE and all signatures to KEYBLOCK.
3353 * Mark all new and copied packets by setting flag bit 0.
3356 append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs)
3360 log_assert (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
3361 || node->pkt->pkttype == PKT_SECRET_SUBKEY);
3365 /* we add a clone to the original keyblock, because this
3366 * one is released first */
3367 n = clone_kbnode(node);
3368 add_kbnode( keyblock, n );
3369 n->flag |= NODE_FLAG_A;
3370 node->flag |= NODE_FLAG_A;
3371 if (n->pkt->pkttype == PKT_SIGNATURE )
3375 if (node && node->pkt->pkttype != PKT_SIGNATURE )