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 /* Aliases for backward compatibility */
179 {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL},
180 {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL},
182 {"import-unusable-sigs",0,NULL,NULL},
183 {"import-clean-sigs",0,NULL,NULL},
184 {"import-clean-uids",0,NULL,NULL},
185 {"convert-sk-to-pk",0, NULL,NULL}, /* Not anymore needed due to
190 return parse_options(str,options,import_opts,noisy);
194 /* Parse and set an import filter from string. STRING has the format
195 * "NAME=EXPR" with NAME being the name of the filter. Spaces before
196 * and after NAME are not allowed. If this function is all called
197 * several times all expressions for the same NAME are concatenated.
198 * Supported filter names are:
200 * - keep-uid :: If the expression evaluates to true for a certain
201 * user ID packet, that packet and all it dependencies
202 * will be imported. The expression may use these
205 * - uid :: The entire user ID.
206 * - mbox :: The mail box part of the user ID.
207 * - primary :: Evaluate to true for the primary user ID.
210 parse_and_set_import_filter (const char *string)
214 /* Auto register the cleanup function. */
215 register_mem_cleanup_func (cleanup_import_globals);
217 if (!strncmp (string, "keep-uid=", 9))
218 err = recsel_parse_expr (&import_filter.keep_uid, string+9);
219 else if (!strncmp (string, "drop-sig=", 9))
220 err = recsel_parse_expr (&import_filter.drop_sig, string+9);
222 err = gpg_error (GPG_ERR_INV_NAME);
228 /* Save the current import filters, return them, and clear the current
229 * filters. Returns NULL on error and sets ERRNO. */
231 save_and_clear_import_filter (void)
233 import_filter_t filt;
235 filt = xtrycalloc (1, sizeof *filt);
238 *filt = import_filter;
239 memset (&import_filter, 0, sizeof import_filter);
245 /* Release the current import filters and restore them from NEWFILT.
246 * Ownership of NEWFILT is moved to this function. */
248 restore_import_filter (import_filter_t filt)
252 release_import_filter (&import_filter);
253 import_filter = *filt;
260 import_new_stats_handle (void)
262 return xmalloc_clear ( sizeof (struct import_stats_s) );
267 import_release_stats_handle (import_stats_t p)
273 /* Read a key from a file. Only the first key in the file is
274 * considered and stored at R_KEYBLOCK. FNAME is the name of the
278 read_key_from_file (ctrl_t ctrl, const char *fname, kbnode_t *r_keyblock)
282 PACKET *pending_pkt = NULL;
283 kbnode_t keyblock = NULL;
285 int v3keys; /* Dummy */
286 int non_self; /* Dummy */
292 inp = iobuf_open (fname);
294 err = gpg_error_from_syserror ();
295 else if (is_secured_file (iobuf_get_fd (inp)))
299 err = gpg_error (GPG_ERR_EPERM);
305 log_error (_("can't open '%s': %s\n"),
306 iobuf_is_pipe_filename (fname)? "[stdin]": fname,
308 if (gpg_err_code (err) == GPG_ERR_ENOENT)
309 err = gpg_error (GPG_ERR_NO_PUBKEY);
313 /* Push the armor filter. */
315 armor_filter_context_t *afx;
316 afx = new_armor_context ();
317 afx->only_keyblocks = 1;
318 push_armor_filter (afx, inp);
319 release_armor_context (afx);
322 /* Read the first non-v3 keyblock. */
323 while (!(err = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
325 if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
327 log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
328 release_kbnode (keyblock);
333 if (gpg_err_code (err) != GPG_ERR_INV_KEYRING)
334 log_error (_("error reading '%s': %s\n"),
335 iobuf_is_pipe_filename (fname)? "[stdin]": fname,
340 keyid_from_pk (keyblock->pkt->pkt.public_key, keyid);
342 if (!find_next_kbnode (keyblock, PKT_USER_ID))
344 err = gpg_error (GPG_ERR_NO_USER_ID);
348 collapse_uids (&keyblock);
350 clear_kbnode_flags (keyblock);
351 if (chk_self_sigs (keyblock, keyid, &non_self))
353 err = gpg_error (GPG_ERR_INV_KEYRING);
357 if (!delete_inv_parts (keyblock, keyid, 0) )
359 err = gpg_error (GPG_ERR_NO_USER_ID);
363 *r_keyblock = keyblock;
370 /* Must invalidate that ugly cache to actually close the file. */
371 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
373 release_kbnode (keyblock);
374 /* FIXME: Do we need to free PENDING_PKT ? */
381 * Import the public keys from the given filename. Input may be armored.
382 * This function rejects all keys which are not validly self signed on at
383 * least one userid. Only user ids which are self signed will be imported.
384 * Other signatures are not checked.
386 * Actually this function does a merge. It works like this:
389 * - check self-signatures and remove all userids and their signatures
390 * without/invalid self-signatures.
391 * - reject the keyblock, if we have no valid userid.
392 * - See whether we have this key already in one of our pubrings.
393 * If not, simply add it to the default keyring.
394 * - Compare the key and the self-signatures of the new and the one in
395 * our keyring. If they are different something weird is going on;
397 * - See whether we have only non-self-signature on one user id; if not
398 * ask the user what to do.
399 * - compare the signatures: If we already have this signature, check
400 * that they compare okay; if not, issue a warning and ask the user.
401 * (consider looking at the timestamp and use the newest?)
402 * - Simply add the signature. Can't verify here because we may not have
403 * the signature's public key yet; verification is done when putting it
404 * into the trustdb, which is done automagically as soon as this pubkey
406 * - Proceed with next signature.
408 * Key revocation certificates have special handling.
411 import_keys_internal (ctrl_t ctrl, iobuf_t inp, char **fnames, int nnames,
412 import_stats_t stats_handle,
413 unsigned char **fpr, size_t *fpr_len,
414 unsigned int options,
415 import_screener_t screener, void *screener_arg)
419 struct import_stats_s *stats = stats_handle;
422 stats = import_new_stats_handle ();
426 rc = import (ctrl, inp, "[stream]", stats, fpr, fpr_len, options,
427 screener, screener_arg);
431 if (!fnames && !nnames)
432 nnames = 1; /* Ohh what a ugly hack to jump into the loop */
434 for (i=0; i < nnames; i++)
436 const char *fname = fnames? fnames[i] : NULL;
437 IOBUF inp2 = iobuf_open(fname);
441 if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
445 gpg_err_set_errno (EPERM);
448 log_error (_("can't open '%s': %s\n"), fname, strerror (errno));
451 rc = import (ctrl, inp2, fname, stats, fpr, fpr_len, options,
452 screener, screener_arg);
454 /* Must invalidate that ugly cache to actually close it. */
455 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
457 log_error ("import from '%s' failed: %s\n",
458 fname, gpg_strerror (rc) );
467 import_print_stats (stats);
468 import_release_stats_handle (stats);
471 /* If no fast import and the trustdb is dirty (i.e. we added a key
472 or userID that had something other than a selfsig, a signature
473 that was other than a selfsig, or any revocation), then
474 update/check the trustdb if the user specified by setting
475 interactive or by not setting no-auto-check-trustdb */
477 if (!(options & IMPORT_FAST))
478 check_or_update_trustdb (ctrl);
485 import_keys (ctrl_t ctrl, char **fnames, int nnames,
486 import_stats_t stats_handle, unsigned int options )
488 import_keys_internal (ctrl, NULL, fnames, nnames, stats_handle,
489 NULL, NULL, options, NULL, NULL);
493 import_keys_stream (ctrl_t ctrl, IOBUF inp, import_stats_t stats_handle,
494 unsigned char **fpr, size_t *fpr_len, unsigned int options)
496 return import_keys_internal (ctrl, inp, NULL, 0, stats_handle,
497 fpr, fpr_len, options, NULL, NULL);
501 /* Variant of import_keys_stream reading from an estream_t. */
503 import_keys_es_stream (ctrl_t ctrl, estream_t fp,
504 import_stats_t stats_handle,
505 unsigned char **fpr, size_t *fpr_len,
506 unsigned int options,
507 import_screener_t screener, void *screener_arg)
512 inp = iobuf_esopen (fp, "rb", 1);
515 rc = gpg_error_from_syserror ();
516 log_error ("iobuf_esopen failed: %s\n", gpg_strerror (rc));
520 rc = import_keys_internal (ctrl, inp, NULL, 0, stats_handle,
521 fpr, fpr_len, options,
522 screener, screener_arg);
530 import (ctrl_t ctrl, IOBUF inp, const char* fname,struct import_stats_s *stats,
531 unsigned char **fpr,size_t *fpr_len, unsigned int options,
532 import_screener_t screener, void *screener_arg)
534 PACKET *pending_pkt = NULL;
535 kbnode_t keyblock = NULL; /* Need to initialize because gcc can't
536 grasp the return semantics of
541 getkey_disable_caches ();
543 if (!opt.no_armor) /* Armored reading is not disabled. */
545 armor_filter_context_t *afx;
547 afx = new_armor_context ();
548 afx->only_keyblocks = 1;
549 push_armor_filter (afx, inp);
550 release_armor_context (afx);
553 while (!(rc = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
555 stats->v3keys += v3keys;
556 if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
557 rc = import_one (ctrl, keyblock,
558 stats, fpr, fpr_len, options, 0, 0,
559 screener, screener_arg);
560 else if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
561 rc = import_secret_one (ctrl, keyblock, stats,
562 opt.batch, options, 0,
563 screener, screener_arg);
564 else if (keyblock->pkt->pkttype == PKT_SIGNATURE
565 && keyblock->pkt->pkt.signature->sig_class == 0x20 )
566 rc = import_revoke_cert (ctrl, keyblock, stats);
569 log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
571 release_kbnode (keyblock);
573 /* fixme: we should increment the not imported counter but
574 this does only make sense if we keep on going despite of
575 errors. For now we do this only if the imported key is too
577 if (gpg_err_code (rc) == GPG_ERR_TOO_LARGE
578 && gpg_err_source (rc) == GPG_ERR_SOURCE_KEYBOX)
580 stats->not_imported++;
585 if (!(++stats->count % 100) && !opt.quiet)
586 log_info (_("%lu keys processed so far\n"), stats->count );
588 stats->v3keys += v3keys;
591 else if (rc && gpg_err_code (rc) != GPG_ERR_INV_KEYRING)
592 log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (rc));
598 /* Helper to migrate secring.gpg to GnuPG 2.1. */
600 import_old_secring (ctrl_t ctrl, const char *fname)
604 PACKET *pending_pkt = NULL;
605 kbnode_t keyblock = NULL; /* Need to initialize because gcc can't
606 grasp the return semantics of
608 struct import_stats_s *stats;
611 inp = iobuf_open (fname);
612 if (inp && is_secured_file (iobuf_get_fd (inp)))
616 gpg_err_set_errno (EPERM);
620 err = gpg_error_from_syserror ();
621 log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
625 getkey_disable_caches();
626 stats = import_new_stats_handle ();
627 while (!(err = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
629 if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
630 err = import_secret_one (ctrl, keyblock, stats, 1, 0, 1,
632 release_kbnode (keyblock);
636 import_release_stats_handle (stats);
639 else if (err && gpg_err_code (err) != GPG_ERR_INV_KEYRING)
640 log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
642 log_error ("import from '%s' failed: %s\n", fname, gpg_strerror (err));
645 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
652 import_print_stats (import_stats_t stats)
656 log_info(_("Total number processed: %lu\n"),
657 stats->count + stats->v3keys);
659 log_info(_(" skipped PGP-2 keys: %lu\n"), stats->v3keys);
660 if (stats->skipped_new_keys )
661 log_info(_(" skipped new keys: %lu\n"),
662 stats->skipped_new_keys );
663 if (stats->no_user_id )
664 log_info(_(" w/o user IDs: %lu\n"), stats->no_user_id );
667 log_info(_(" imported: %lu"), stats->imported );
670 if (stats->unchanged )
671 log_info(_(" unchanged: %lu\n"), stats->unchanged );
673 log_info(_(" new user IDs: %lu\n"), stats->n_uids );
675 log_info(_(" new subkeys: %lu\n"), stats->n_subk );
677 log_info(_(" new signatures: %lu\n"), stats->n_sigs );
679 log_info(_(" new key revocations: %lu\n"), stats->n_revoc );
680 if (stats->secret_read )
681 log_info(_(" secret keys read: %lu\n"), stats->secret_read );
682 if (stats->secret_imported )
683 log_info(_(" secret keys imported: %lu\n"), stats->secret_imported );
684 if (stats->secret_dups )
685 log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
686 if (stats->not_imported )
687 log_info(_(" not imported: %lu\n"), stats->not_imported );
688 if (stats->n_sigs_cleaned)
689 log_info(_(" signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
690 if (stats->n_uids_cleaned)
691 log_info(_(" user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
694 if (is_status_enabled ())
698 snprintf (buf, sizeof buf,
699 "%lu %lu %lu 0 %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
700 stats->count + stats->v3keys,
709 stats->secret_imported,
711 stats->skipped_new_keys,
714 write_status_text (STATUS_IMPORT_RES, buf);
719 /* Return true if PKTTYPE is valid in a keyblock. */
721 valid_keyblock_packet (int pkttype)
726 case PKT_PUBLIC_SUBKEY:
728 case PKT_SECRET_SUBKEY:
741 * Read the next keyblock from stream A.
742 * PENDING_PKT should be initialzed to NULL
743 * and not changed by the caller.
744 * Return: 0 = okay, -1 no more blocks or another errorcode.
745 * The int at at R_V3KEY counts the number of unsupported v3
749 read_block( IOBUF a, PACKET **pending_pkt, kbnode_t *ret_root, int *r_v3keys)
753 kbnode_t root = NULL;
754 int in_cert, in_v3key;
760 root = new_kbnode( *pending_pkt );
767 pkt = xmalloc (sizeof *pkt);
770 while ((rc=parse_packet(a, pkt)) != -1)
772 if (rc && (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY
773 && (pkt->pkttype == PKT_PUBLIC_KEY
774 || pkt->pkttype == PKT_SECRET_KEY)))
782 else if (rc ) /* (ignore errors) */
784 if (gpg_err_code (rc) == GPG_ERR_UNKNOWN_PACKET)
785 ; /* Do not show a diagnostic. */
788 log_error("read_block: read error: %s\n", gpg_strerror (rc) );
789 rc = GPG_ERR_INV_KEYRING;
797 if (in_v3key && !(pkt->pkttype == PKT_PUBLIC_KEY
798 || pkt->pkttype == PKT_SECRET_KEY))
806 if (!root && pkt->pkttype == PKT_SIGNATURE
807 && pkt->pkt.signature->sig_class == 0x20 )
809 /* This is a revocation certificate which is handled in a
811 root = new_kbnode( pkt );
816 /* Make a linked list of all packets. */
817 switch (pkt->pkttype)
820 if (check_compress_algo (pkt->pkt.compressed->algorithm))
822 rc = GPG_ERR_COMPR_ALGO;
827 compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
828 pkt->pkt.compressed->buf = NULL;
829 push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1);
836 /* Skip those packets. */
843 if (in_cert ) /* Store this packet. */
851 if (in_cert && valid_keyblock_packet (pkt->pkttype))
854 root = new_kbnode (pkt);
856 add_kbnode (root, new_kbnode (pkt));
857 pkt = xmalloc (sizeof *pkt);
865 if (rc == -1 && root )
869 release_kbnode( root );
878 /* Walk through the subkeys on a pk to find if we have the PKS
879 disease: multiple subkeys with their binding sigs stripped, and the
880 sig for the first subkey placed after the last subkey. That is,
881 instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
882 "pk uid sig sub1 sub2 sub3 bind1". We can't do anything about sub2
883 and sub3, as they are already lost, but we can try and rescue sub1
884 by reordering the keyblock so that it reads "pk uid sig sub1 bind1
885 sub2 sub3". Returns TRUE if the keyblock was modified. */
887 fix_pks_corruption (kbnode_t keyblock)
892 kbnode_t last = NULL;
893 kbnode_t sknode=NULL;
895 /* First determine if we have the problem at all. Look for 2 or
896 more subkeys in a row, followed by a single binding sig. */
897 for (node=keyblock; node; last=node, node=node->next)
899 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
905 else if (node->pkt->pkttype == PKT_SIGNATURE
906 && node->pkt->pkt.signature->sig_class == 0x18
910 /* We might have the problem, as this key has two subkeys in
911 a row without any intervening packets. */
917 /* Temporarily attach node to sknode. */
918 node->next = sknode->next;
922 /* Note we aren't checking whether this binding sig is a
923 selfsig. This is not necessary here as the subkey and
924 binding sig will be rejected later if that is the
926 if (check_key_signature (keyblock,node,NULL))
928 /* Not a match, so undo the changes. */
929 sknode->next = node->next;
936 /* Mark it good so we don't need to check it again */
937 sknode->flag |= NODE_GOOD_SELFSIG;
950 /* Versions of GnuPG before 1.4.11 and 2.0.16 allowed to import bogus
951 direct key signatures. A side effect of this was that a later
952 import of the same good direct key signatures was not possible
953 because the cmp_signature check in merge_blocks considered them
954 equal. Although direct key signatures are now checked during
955 import, there might still be bogus signatures sitting in a keyring.
956 We need to detect and delete them before doing a merge. This
957 function returns the number of removed sigs. */
959 fix_bad_direct_key_sigs (kbnode_t keyblock, u32 *keyid)
965 for (node = keyblock->next; node; node=node->next)
967 if (node->pkt->pkttype == PKT_USER_ID)
969 if (node->pkt->pkttype == PKT_SIGNATURE
970 && IS_KEY_SIG (node->pkt->pkt.signature))
972 err = check_key_signature (keyblock, node, NULL);
973 if (err && gpg_err_code (err) != GPG_ERR_PUBKEY_ALGO )
975 /* If we don't know the error, we can't decide; this is
976 not a problem because cmp_signature can't compare the
978 log_info ("key %s: invalid direct key signature removed\n",
980 delete_kbnode (node);
991 print_import_ok (PKT_public_key *pk, unsigned int reason)
993 byte array[MAX_FINGERPRINT_LEN], *s;
994 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
997 snprintf (buf, sizeof buf, "%u ", reason);
998 p = buf + strlen (buf);
1000 fingerprint_from_pk (pk, array, &n);
1002 for (i=0; i < n ; i++, s++, p += 2)
1003 sprintf (p, "%02X", *s);
1005 write_status_text (STATUS_IMPORT_OK, buf);
1010 print_import_check (PKT_public_key * pk, PKT_user_id * id)
1018 buf = xmalloc (17+41+id->len+32);
1019 keyid_from_pk (pk, keyid);
1020 sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
1022 fingerprint_from_pk (pk, fpr, &n);
1023 for (i = 0; i < n; i++, pos += 2)
1024 sprintf (buf+pos, "%02X", fpr[i]);
1026 strcat (buf, id->name);
1027 write_status_text (STATUS_IMPORT_CHECK, buf);
1033 check_prefs_warning(PKT_public_key *pk)
1035 log_info(_("WARNING: key %s contains preferences for unavailable\n"
1036 "algorithms on these user IDs:\n"), keystr_from_pk(pk));
1041 check_prefs (ctrl_t ctrl, kbnode_t keyblock)
1047 merge_keys_and_selfsig(keyblock);
1048 pk=keyblock->pkt->pkt.public_key;
1050 for(node=keyblock;node;node=node->next)
1052 if(node->pkt->pkttype==PKT_USER_ID
1053 && node->pkt->pkt.user_id->created
1054 && node->pkt->pkt.user_id->prefs)
1056 PKT_user_id *uid = node->pkt->pkt.user_id;
1057 prefitem_t *prefs = uid->prefs;
1058 char *user = utf8_to_native(uid->name,strlen(uid->name),0);
1060 for(;prefs->type;prefs++)
1062 char num[10]; /* prefs->value is a byte, so we're over
1065 sprintf(num,"%u",prefs->value);
1067 if(prefs->type==PREFTYPE_SYM)
1069 if (openpgp_cipher_test_algo (prefs->value))
1072 (openpgp_cipher_test_algo (prefs->value)
1074 : openpgp_cipher_algo_name (prefs->value));
1076 check_prefs_warning(pk);
1077 log_info(_(" \"%s\": preference for cipher"
1078 " algorithm %s\n"), user, algo);
1082 else if(prefs->type==PREFTYPE_HASH)
1084 if(openpgp_md_test_algo(prefs->value))
1087 (gcry_md_test_algo (prefs->value)
1089 : gcry_md_algo_name (prefs->value));
1091 check_prefs_warning(pk);
1092 log_info(_(" \"%s\": preference for digest"
1093 " algorithm %s\n"), user, algo);
1097 else if(prefs->type==PREFTYPE_ZIP)
1099 if(check_compress_algo (prefs->value))
1101 const char *algo=compress_algo_to_string(prefs->value);
1103 check_prefs_warning(pk);
1104 log_info(_(" \"%s\": preference for compression"
1105 " algorithm %s\n"),user,algo?algo:num);
1117 log_info(_("it is strongly suggested that you update"
1118 " your preferences and\n"));
1119 log_info(_("re-distribute this key to avoid potential algorithm"
1120 " mismatch problems\n"));
1124 strlist_t sl = NULL;
1125 strlist_t locusr = NULL;
1127 byte fpr[MAX_FINGERPRINT_LEN], *p;
1128 char username[(MAX_FINGERPRINT_LEN*2)+1];
1131 p = fingerprint_from_pk (pk,fpr,&fprlen);
1132 for(i=0;i<fprlen;i++,p++)
1133 sprintf(username+2*i,"%02X",*p);
1134 add_to_strlist(&locusr,username);
1136 append_to_strlist(&sl,"updpref");
1137 append_to_strlist(&sl,"save");
1139 keyedit_menu (ctrl, username, locusr, sl, 1, 1 );
1141 free_strlist(locusr);
1144 log_info(_("you can update your preferences with:"
1145 " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
1150 /* Helper for apply_*_filter in im,port.c and export.c. */
1152 impex_filter_getval (void *cookie, const char *propname)
1154 /* FIXME: Malloc our static buffers and access them via the cookie. */
1155 kbnode_t node = cookie;
1156 static char numbuf[20];
1159 if (node->pkt->pkttype == PKT_USER_ID)
1161 if (!strcmp (propname, "uid"))
1162 result = node->pkt->pkt.user_id->name;
1163 else if (!strcmp (propname, "mbox"))
1165 if (!node->pkt->pkt.user_id->mbox)
1167 node->pkt->pkt.user_id->mbox
1168 = mailbox_from_userid (node->pkt->pkt.user_id->name);
1170 result = node->pkt->pkt.user_id->mbox;
1172 else if (!strcmp (propname, "primary"))
1173 result = node->pkt->pkt.user_id->is_primary? "1":"0";
1177 else if (node->pkt->pkttype == PKT_SIGNATURE
1178 || node->pkt->pkttype == PKT_ATTRIBUTE)
1180 PKT_signature *sig = node->pkt->pkt.signature;
1182 if (!strcmp (propname, "sig_created"))
1184 snprintf (numbuf, sizeof numbuf, "%lu", (ulong)sig->timestamp);
1187 else if (!strcmp (propname, "sig_created_d"))
1189 result = datestr_from_sig (sig);
1191 else if (!strcmp (propname, "sig_algo"))
1193 snprintf (numbuf, sizeof numbuf, "%d", sig->pubkey_algo);
1196 else if (!strcmp (propname, "sig_digest_algo"))
1198 snprintf (numbuf, sizeof numbuf, "%d", sig->digest_algo);
1204 else if (node->pkt->pkttype == PKT_PUBLIC_KEY
1205 || node->pkt->pkttype == PKT_SECRET_KEY
1206 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1207 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1209 PKT_public_key *pk = node->pkt->pkt.public_key;
1211 if (!strcmp (propname, "secret"))
1213 result = (node->pkt->pkttype == PKT_SECRET_KEY
1214 || node->pkt->pkttype == PKT_SECRET_SUBKEY)? "1":"0";
1216 else if (!strcmp (propname, "key_algo"))
1218 snprintf (numbuf, sizeof numbuf, "%d", pk->pubkey_algo);
1221 if (!strcmp (propname, "key_created"))
1223 snprintf (numbuf, sizeof numbuf, "%lu", (ulong)pk->timestamp);
1226 else if (!strcmp (propname, "key_created_d"))
1228 result = datestr_from_pk (pk);
1241 * Apply the keep-uid filter to the keyblock. The deleted nodes are
1242 * marked and thus the caller should call commit_kbnode afterwards.
1243 * KEYBLOCK must not have any blocks marked as deleted.
1246 apply_keep_uid_filter (kbnode_t keyblock, recsel_expr_t selector)
1250 for (node = keyblock->next; node; node = node->next )
1252 if (node->pkt->pkttype == PKT_USER_ID)
1254 if (!recsel_select (selector, impex_filter_getval, node))
1257 /* log_debug ("keep-uid: deleting '%s'\n", */
1258 /* node->pkt->pkt.user_id->name); */
1259 /* The UID packet and all following packets up to the
1260 * next UID or a subkey. */
1261 delete_kbnode (node);
1263 && node->next->pkt->pkttype != PKT_USER_ID
1264 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1265 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1267 delete_kbnode (node->next);
1270 /* log_debug ("keep-uid: keeping '%s'\n", */
1271 /* node->pkt->pkt.user_id->name); */
1278 * Apply the drop-sig filter to the keyblock. The deleted nodes are
1279 * marked and thus the caller should call commit_kbnode afterwards.
1280 * KEYBLOCK must not have any blocks marked as deleted.
1283 apply_drop_sig_filter (kbnode_t keyblock, recsel_expr_t selector)
1290 keyid_from_pk (keyblock->pkt->pkt.public_key, main_keyid);
1292 /* Loop over all signatures for user id and attribute packets which
1293 * are not self signatures. */
1294 for (node = keyblock->next; node; node = node->next )
1296 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1297 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1299 if (node->pkt->pkttype == PKT_USER_ID)
1303 if (node->pkt->pkttype != PKT_SIGNATURE
1304 && node->pkt->pkttype != PKT_ATTRIBUTE)
1307 sig = node->pkt->pkt.signature;
1308 if (main_keyid[0] == sig->keyid[0] || main_keyid[1] == sig->keyid[1])
1309 continue; /* Skip self-signatures. */
1311 if (IS_UID_SIG(sig) || IS_UID_REV(sig))
1313 if (recsel_select (selector, impex_filter_getval, node))
1314 delete_kbnode (node);
1321 * Try to import one keyblock. Return an error only in serious cases,
1322 * but never for an invalid keyblock. It uses log_error to increase
1323 * the internal errorcount, so that invalid input can be detected by
1324 * programs which called gpg. If SILENT is no messages are printed -
1325 * even most error messages are suppressed.
1328 import_one (ctrl_t ctrl,
1329 kbnode_t keyblock, struct import_stats_s *stats,
1330 unsigned char **fpr, size_t *fpr_len, unsigned int options,
1331 int from_sk, int silent,
1332 import_screener_t screener, void *screener_arg)
1335 PKT_public_key *pk_orig = NULL;
1336 kbnode_t node, uidnode;
1337 kbnode_t keyblock_orig = NULL;
1338 byte fpr2[MAX_FINGERPRINT_LEN];
1347 char pkstrbuf[PUBKEY_STRING_SIZE];
1348 int merge_keys_done = 0;
1351 /* Get the key and print some info about it. */
1352 node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
1356 pk = node->pkt->pkt.public_key;
1358 fingerprint_from_pk (pk, fpr2, &fpr2len);
1359 for (an = fpr2len; an < MAX_FINGERPRINT_LEN; an++)
1361 keyid_from_pk( pk, keyid );
1362 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1364 if (opt.verbose && !opt.interactive && !silent)
1366 log_info( "pub %s/%s %s ",
1367 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
1368 keystr_from_pk(pk), datestr_from_pk(pk) );
1370 print_utf8_buffer (log_get_stream (),
1371 uidnode->pkt->pkt.user_id->name,
1372 uidnode->pkt->pkt.user_id->len );
1380 log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
1384 if (screener && screener (keyblock, screener_arg))
1386 log_error (_("key %s: %s\n"), keystr_from_pk (pk),
1387 _("rejected by import screener"));
1391 if (opt.interactive && !silent)
1393 if (is_status_enabled())
1394 print_import_check (pk, uidnode->pkt->pkt.user_id);
1395 merge_keys_and_selfsig (keyblock);
1397 show_basic_key_info (keyblock);
1399 if (!cpr_get_answer_is_yes ("import.okay",
1400 "Do you want to import this key? (y/N) "))
1404 collapse_uids(&keyblock);
1406 /* Clean the key that we're about to import, to cut down on things
1407 that we have to clean later. This has no practical impact on the
1408 end result, but does result in less logging which might confuse
1410 if (options&IMPORT_CLEAN)
1411 clean_key (keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL);
1413 clear_kbnode_flags( keyblock );
1415 if ((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
1417 log_info (_("key %s: PKS subkey corruption repaired\n"),
1418 keystr_from_pk(pk));
1420 if (chk_self_sigs (keyblock, keyid, &non_self))
1421 return 0; /* Invalid keyblock - error already printed. */
1423 /* If we allow such a thing, mark unsigned uids as valid */
1424 if (opt.allow_non_selfsigned_uid)
1426 for (node=keyblock; node; node = node->next )
1427 if (node->pkt->pkttype == PKT_USER_ID
1428 && !(node->flag & NODE_GOOD_SELFSIG)
1429 && !(node->flag & NODE_BAD_SELFSIG) )
1431 char *user=utf8_to_native(node->pkt->pkt.user_id->name,
1432 node->pkt->pkt.user_id->len,0);
1433 /* Fake a good signature status for the user id. */
1434 node->flag |= NODE_GOOD_SELFSIG;
1435 log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
1436 keystr_from_pk(pk),user);
1441 if (!delete_inv_parts (keyblock, keyid, options ) )
1445 log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
1447 log_info(_("this may be caused by a missing self-signature\n"));
1449 stats->no_user_id++;
1453 /* Get rid of deleted nodes. */
1454 commit_kbnode (&keyblock);
1456 /* Apply import filter. */
1457 if (import_filter.keep_uid)
1459 apply_keep_uid_filter (keyblock, import_filter.keep_uid);
1460 commit_kbnode (&keyblock);
1463 if (import_filter.drop_sig)
1465 apply_drop_sig_filter (keyblock, import_filter.drop_sig);
1466 commit_kbnode (&keyblock);
1470 /* If we ran any filter we need to check that at least one user id
1471 * is left in the keyring. Note that we do not use log_error in
1473 if (any_filter && !any_uid_left (keyblock))
1476 log_info ( _("key %s: no valid user IDs\n"), keystr_from_pk (pk));
1477 stats->no_user_id++;
1481 /* Show the key in the form it is merged or inserted. We skip this
1482 * if "import-export" is also active without --armor or the output
1483 * file has explicily been given. */
1484 if ((options & IMPORT_SHOW)
1485 && !((options & IMPORT_EXPORT) && !opt.armor && !opt.outfile))
1487 merge_keys_and_selfsig (keyblock);
1488 merge_keys_done = 1;
1489 /* Note that we do not want to show the validity because the key
1490 * has not yet imported. */
1491 list_keyblock_direct (ctrl, keyblock, 0, 0, 1, 1);
1492 es_fflush (es_stdout);
1495 /* Write the keyblock to the output and do not actually import. */
1496 if ((options & IMPORT_EXPORT))
1498 if (!merge_keys_done)
1500 merge_keys_and_selfsig (keyblock);
1501 merge_keys_done = 1;
1503 rc = write_keyblock_to_output (keyblock, opt.armor, opt.export_options);
1510 /* Do we have this key already in one of our pubrings ? */
1511 pk_orig = xmalloc_clear( sizeof *pk_orig );
1512 rc = get_pubkey_byfprint_fast (pk_orig, fpr2, fpr2len);
1513 if (rc && gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1514 && gpg_err_code (rc) != GPG_ERR_UNUSABLE_PUBKEY )
1517 log_error (_("key %s: public key not found: %s\n"),
1518 keystr(keyid), gpg_strerror (rc));
1520 else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) )
1522 if (opt.verbose && !silent )
1523 log_info( _("key %s: new key - skipped\n"), keystr(keyid));
1525 stats->skipped_new_keys++;
1527 else if (rc ) /* Insert this key. */
1533 return gpg_error_from_syserror ();
1535 rc = keydb_locate_writable (hd);
1538 log_error (_("no writable keyring found: %s\n"), gpg_strerror (rc));
1540 return GPG_ERR_GENERAL;
1542 if (opt.verbose > 1 )
1543 log_info (_("writing to '%s'\n"), keydb_get_resource_name (hd) );
1545 rc = keydb_insert_keyblock (hd, keyblock );
1547 log_error (_("error writing keyring '%s': %s\n"),
1548 keydb_get_resource_name (hd), gpg_strerror (rc));
1549 else if (!(opt.import_options & IMPORT_KEEP_OWNERTTRUST))
1551 /* This should not be possible since we delete the
1552 ownertrust when a key is deleted, but it can happen if
1553 the keyring and trustdb are out of sync. It can also
1554 be made to happen with the trusted-key command and by
1555 importing and locally exported key. */
1557 clear_ownertrusts (pk);
1559 revalidation_mark ();
1564 if (!opt.quiet && !silent)
1566 char *p = get_user_id_byfpr_native (fpr2);
1567 log_info (_("key %s: public key \"%s\" imported\n"),
1571 if (is_status_enabled())
1573 char *us = get_long_user_id_string( keyid );
1574 write_status_text( STATUS_IMPORTED, us );
1576 print_import_ok (pk, 1);
1584 int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
1586 /* Compare the original against the new key; just to be sure nothing
1587 * weird is going on */
1588 if (cmp_public_keys( pk_orig, pk ) )
1591 log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
1595 /* Now read the original keyblock again so that we can use
1596 that handle for updating the keyblock. */
1600 rc = gpg_error_from_syserror ();
1603 keydb_disable_caching (hd);
1604 rc = keydb_search_fpr (hd, fpr2);
1607 log_error (_("key %s: can't locate original keyblock: %s\n"),
1608 keystr(keyid), gpg_strerror (rc));
1612 rc = keydb_get_keyblock (hd, &keyblock_orig);
1615 log_error (_("key %s: can't read original keyblock: %s\n"),
1616 keystr(keyid), gpg_strerror (rc));
1621 /* Make sure the original direct key sigs are all sane. */
1622 n_sigs_cleaned = fix_bad_direct_key_sigs (keyblock_orig, keyid);
1624 commit_kbnode (&keyblock_orig);
1626 /* and try to merge the block */
1627 clear_kbnode_flags( keyblock_orig );
1628 clear_kbnode_flags( keyblock );
1629 n_uids = n_sigs = n_subk = n_uids_cleaned = 0;
1630 rc = merge_blocks (keyblock_orig, keyblock,
1631 keyid, &n_uids, &n_sigs, &n_subk );
1638 if ((options & IMPORT_CLEAN))
1639 clean_key (keyblock_orig,opt.verbose,options&IMPORT_MINIMAL,
1640 &n_uids_cleaned,&n_sigs_cleaned);
1642 if (n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned)
1645 /* KEYBLOCK_ORIG has been updated; write */
1646 rc = keydb_update_keyblock (ctrl, hd, keyblock_orig);
1648 log_error (_("error writing keyring '%s': %s\n"),
1649 keydb_get_resource_name (hd), gpg_strerror (rc) );
1651 revalidation_mark ();
1654 if (!opt.quiet && !silent)
1656 char *p = get_user_id_byfpr_native (fpr2);
1658 log_info( _("key %s: \"%s\" 1 new user ID\n"),
1661 log_info( _("key %s: \"%s\" %d new user IDs\n"),
1662 keystr(keyid),p,n_uids);
1664 log_info( _("key %s: \"%s\" 1 new signature\n"),
1667 log_info( _("key %s: \"%s\" %d new signatures\n"),
1668 keystr(keyid), p, n_sigs );
1670 log_info( _("key %s: \"%s\" 1 new subkey\n"),
1673 log_info( _("key %s: \"%s\" %d new subkeys\n"),
1674 keystr(keyid), p, n_subk );
1675 if (n_sigs_cleaned==1)
1676 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
1677 keystr(keyid),p,n_sigs_cleaned);
1678 else if (n_sigs_cleaned)
1679 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
1680 keystr(keyid),p,n_sigs_cleaned);
1681 if (n_uids_cleaned==1)
1682 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
1683 keystr(keyid),p,n_uids_cleaned);
1684 else if (n_uids_cleaned)
1685 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
1686 keystr(keyid),p,n_uids_cleaned);
1690 stats->n_uids +=n_uids;
1691 stats->n_sigs +=n_sigs;
1692 stats->n_subk +=n_subk;
1693 stats->n_sigs_cleaned +=n_sigs_cleaned;
1694 stats->n_uids_cleaned +=n_uids_cleaned;
1696 if (is_status_enabled () && !silent)
1697 print_import_ok (pk, ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
1702 if (is_status_enabled ())
1703 print_import_ok (pk, 0);
1705 if (!opt.quiet && !silent)
1707 char *p = get_user_id_byfpr_native (fpr2);
1708 log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
1715 keydb_release (hd); hd = NULL;
1719 if (mod_key || new_key || same_key)
1721 /* A little explanation for this: we fill in the fingerprint
1722 when importing keys as it can be useful to know the
1723 fingerprint in certain keyserver-related cases (a keyserver
1724 asked for a particular name, but the key doesn't have that
1725 name). However, in cases where we're importing more than
1726 one key at a time, we cannot know which key to fingerprint.
1727 In these cases, rather than guessing, we do not
1728 fingerprinting at all, and we must hope the user ID on the
1729 keys are useful. Note that we need to do this for new
1730 keys, merged keys and even for unchanged keys. This is
1731 required because for example the --auto-key-locate feature
1732 may import an already imported key and needs to know the
1733 fingerprint of the key in all cases. */
1737 /* Note that we need to compare against 0 here because
1738 COUNT gets only incremented after returning from this
1741 *fpr = fingerprint_from_pk (pk, NULL, fpr_len);
1747 /* Now that the key is definitely incorporated into the keydb, we
1748 need to check if a designated revocation is present or if the
1749 prefs are not rational so we can warn the user. */
1753 revocation_present (ctrl, keyblock_orig);
1754 if (!from_sk && have_secret_key_with_kid (keyid))
1755 check_prefs (ctrl, keyblock_orig);
1759 revocation_present (ctrl, keyblock);
1760 if (!from_sk && have_secret_key_with_kid (keyid))
1761 check_prefs (ctrl, keyblock);
1764 release_kbnode( keyblock_orig );
1765 free_public_key( pk_orig );
1771 /* Transfer all the secret keys in SEC_KEYBLOCK to the gpg-agent. The
1772 function prints diagnostics and returns an error code. If BATCH is
1773 true the secret keys are stored by gpg-agent in the transfer format
1774 (i.e. no re-protection and aksing for passphrases). */
1776 transfer_secret_keys (ctrl_t ctrl, struct import_stats_s *stats,
1777 kbnode_t sec_keyblock, int batch, int force)
1779 gpg_error_t err = 0;
1782 kbnode_t ctx = NULL;
1784 PKT_public_key *main_pk, *pk;
1785 struct seckey_info *ski;
1789 void *format_args[2*PUBKEY_MAX_NSKEY];
1790 gcry_sexp_t skey, prot, tmpsexp;
1791 gcry_sexp_t curve = NULL;
1792 unsigned char *transferkey = NULL;
1793 size_t transferkeylen;
1794 gcry_cipher_hd_t cipherhd = NULL;
1795 unsigned char *wrappedkey = NULL;
1796 size_t wrappedkeylen;
1797 char *cache_nonce = NULL;
1798 int stub_key_skipped = 0;
1800 /* Get the current KEK. */
1801 err = agent_keywrap_key (ctrl, 0, &kek, &keklen);
1804 log_error ("error getting the KEK: %s\n", gpg_strerror (err));
1808 /* Prepare a cipher context. */
1809 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
1810 GCRY_CIPHER_MODE_AESWRAP, 0);
1812 err = gcry_cipher_setkey (cipherhd, kek, keklen);
1819 while ((node = walk_kbnode (sec_keyblock, &ctx, 0)))
1821 if (node->pkt->pkttype != PKT_SECRET_KEY
1822 && node->pkt->pkttype != PKT_SECRET_SUBKEY)
1824 pk = node->pkt->pkt.public_key;
1828 /* Make sure the keyids are available. */
1829 keyid_from_pk (pk, NULL);
1830 if (node->pkt->pkttype == PKT_SECRET_KEY)
1832 pk->main_keyid[0] = pk->keyid[0];
1833 pk->main_keyid[1] = pk->keyid[1];
1837 pk->main_keyid[0] = main_pk->keyid[0];
1838 pk->main_keyid[1] = main_pk->keyid[1];
1842 ski = pk->seckey_info;
1849 stats->secret_read++;
1852 /* We ignore stub keys. The way we handle them in other parts
1853 of the code is by asking the agent whether any secret key is
1854 available for a given keyblock and then concluding that we
1855 have a secret key; all secret (sub)keys of the keyblock the
1856 agent does not know of are then stub keys. This works also
1857 for card stub keys. The learn command or the card-status
1858 command may be used to check with the agent whether a card
1859 has been inserted and a stub key is in turn generated by the
1861 if (ski->s2k.mode == 1001 || ski->s2k.mode == 1002)
1863 stub_key_skipped = 1;
1867 /* Convert our internal secret key object into an S-expression. */
1868 nskey = pubkey_get_nskey (pk->pubkey_algo);
1869 if (!nskey || nskey > PUBKEY_MAX_NSKEY)
1871 err = gpg_error (GPG_ERR_BAD_SECKEY);
1872 log_error ("internal error: %s\n", gpg_strerror (err));
1876 init_membuf (&mbuf, 50);
1877 put_membuf_str (&mbuf, "(skey");
1878 if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
1879 || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
1880 || pk->pubkey_algo == PUBKEY_ALGO_ECDH)
1883 char *curvestr = openpgp_oid_to_str (pk->pkey[0]);
1885 err = gpg_error_from_syserror ();
1888 const char *curvename = openpgp_oid_to_curve (curvestr, 1);
1889 gcry_sexp_release (curve);
1890 err = gcry_sexp_build (&curve, NULL, "(curve %s)",
1891 curvename?curvename:curvestr);
1896 /* Append the public key element Q. */
1897 put_membuf_str (&mbuf, " _ %m");
1898 format_args[j++] = pk->pkey + 1;
1900 /* Append the secret key element D. For ECDH we
1901 skip PKEY[2] because this holds the KEK which is
1902 not needed by gpg-agent. */
1903 i = pk->pubkey_algo == PUBKEY_ALGO_ECDH? 3 : 2;
1904 if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
1905 put_membuf_str (&mbuf, " e %m");
1907 put_membuf_str (&mbuf, " _ %m");
1908 format_args[j++] = pk->pkey + i;
1914 /* Standard case for the old (non-ECC) algorithms. */
1915 for (i=j=0; i < nskey; i++)
1918 continue; /* Protected keys only have NPKEY+1 elements. */
1920 if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
1921 put_membuf_str (&mbuf, " e %m");
1923 put_membuf_str (&mbuf, " _ %m");
1924 format_args[j++] = pk->pkey + i;
1927 put_membuf_str (&mbuf, ")");
1928 put_membuf (&mbuf, "", 1);
1930 xfree (get_membuf (&mbuf, NULL));
1933 char *format = get_membuf (&mbuf, NULL);
1935 err = gpg_error_from_syserror ();
1937 err = gcry_sexp_build_array (&skey, NULL, format, format_args);
1942 log_error ("error building skey array: %s\n", gpg_strerror (err));
1946 if (ski->is_protected)
1950 /* Note that the IVLEN may be zero if we are working on a
1951 dummy key. We can't express that in an S-expression and
1952 thus we send dummy data for the IV. */
1953 snprintf (countbuf, sizeof countbuf, "%lu",
1954 (unsigned long)ski->s2k.count);
1955 err = gcry_sexp_build
1957 " (protection %s %s %b %d %s %b %s)\n",
1958 ski->sha1chk? "sha1":"sum",
1959 openpgp_cipher_algo_name (ski->algo),
1960 ski->ivlen? (int)ski->ivlen:1,
1961 ski->ivlen? ski->iv: (const unsigned char*)"X",
1963 openpgp_md_algo_name (ski->s2k.hash_algo),
1964 (int)sizeof (ski->s2k.salt), ski->s2k.salt,
1968 err = gcry_sexp_build (&prot, NULL, " (protection none)\n");
1971 xfree (transferkey);
1974 err = gcry_sexp_build (&tmpsexp, NULL,
1975 "(openpgp-private-key\n"
1982 openpgp_pk_algo_name (pk->pubkey_algo),
1984 (int)(unsigned long)ski->csum, prot);
1985 gcry_sexp_release (skey);
1986 gcry_sexp_release (prot);
1988 err = make_canon_sexp_pad (tmpsexp, 1, &transferkey, &transferkeylen);
1989 gcry_sexp_release (tmpsexp);
1992 log_error ("error building transfer key: %s\n", gpg_strerror (err));
1997 wrappedkeylen = transferkeylen + 8;
1999 wrappedkey = xtrymalloc (wrappedkeylen);
2001 err = gpg_error_from_syserror ();
2003 err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen,
2004 transferkey, transferkeylen);
2007 xfree (transferkey);
2010 /* Send the wrapped key to the agent. */
2012 char *desc = gpg_format_keydesc (pk, FORMAT_KEYDESC_IMPORT, 1);
2013 err = agent_import_key (ctrl, desc, &cache_nonce,
2014 wrappedkey, wrappedkeylen, batch, force);
2020 log_info (_("key %s: secret key imported\n"),
2021 keystr_from_pk_with_sub (main_pk, pk));
2023 stats->secret_imported++;
2025 else if ( gpg_err_code (err) == GPG_ERR_EEXIST )
2028 log_info (_("key %s: secret key already exists\n"),
2029 keystr_from_pk_with_sub (main_pk, pk));
2032 stats->secret_dups++;
2036 log_error (_("key %s: error sending to agent: %s\n"),
2037 keystr_from_pk_with_sub (main_pk, pk),
2038 gpg_strerror (err));
2039 if (gpg_err_code (err) == GPG_ERR_CANCELED
2040 || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
2041 break; /* Don't try the other subkeys. */
2045 if (!err && stub_key_skipped)
2046 /* We need to notify user how to migrate stub keys. */
2047 err = gpg_error (GPG_ERR_NOT_PROCESSED);
2050 gcry_sexp_release (curve);
2051 xfree (cache_nonce);
2053 xfree (transferkey);
2054 gcry_cipher_close (cipherhd);
2060 /* Walk a secret keyblock and produce a public keyblock out of it.
2061 Returns a new node or NULL on error. */
2063 sec_to_pub_keyblock (kbnode_t sec_keyblock)
2065 kbnode_t pub_keyblock = NULL;
2066 kbnode_t ctx = NULL;
2067 kbnode_t secnode, pubnode;
2069 while ((secnode = walk_kbnode (sec_keyblock, &ctx, 0)))
2071 if (secnode->pkt->pkttype == PKT_SECRET_KEY
2072 || secnode->pkt->pkttype == PKT_SECRET_SUBKEY)
2074 /* Make a public key. */
2078 pkt = xtrycalloc (1, sizeof *pkt);
2079 pk = pkt? copy_public_key (NULL, secnode->pkt->pkt.public_key): NULL;
2083 release_kbnode (pub_keyblock);
2086 if (secnode->pkt->pkttype == PKT_SECRET_KEY)
2087 pkt->pkttype = PKT_PUBLIC_KEY;
2089 pkt->pkttype = PKT_PUBLIC_SUBKEY;
2090 pkt->pkt.public_key = pk;
2092 pubnode = new_kbnode (pkt);
2096 pubnode = clone_kbnode (secnode);
2100 pub_keyblock = pubnode;
2102 add_kbnode (pub_keyblock, pubnode);
2105 return pub_keyblock;
2109 * Ditto for secret keys. Handling is simpler than for public keys.
2110 * We allow secret key importing only when allow is true, this is so
2111 * that a secret key can not be imported accidentally and thereby tampering
2112 * with the trust calculation.
2115 import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
2116 struct import_stats_s *stats, int batch, unsigned int options,
2118 import_screener_t screener, void *screener_arg)
2121 struct seckey_info *ski;
2122 kbnode_t node, uidnode;
2126 kbnode_t pub_keyblock;
2127 char pkstrbuf[PUBKEY_STRING_SIZE];
2129 /* Get the key and print some info about it */
2130 node = find_kbnode (keyblock, PKT_SECRET_KEY);
2134 pk = node->pkt->pkt.public_key;
2136 keyid_from_pk (pk, keyid);
2137 uidnode = find_next_kbnode (keyblock, PKT_USER_ID);
2139 if (screener && screener (keyblock, screener_arg))
2141 log_error (_("secret key %s: %s\n"), keystr_from_pk (pk),
2142 _("rejected by import screener"));
2146 if (opt.verbose && !for_migration)
2148 log_info ("sec %s/%s %s ",
2149 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
2150 keystr_from_pk (pk), datestr_from_pk (pk));
2152 print_utf8_buffer (log_get_stream (), uidnode->pkt->pkt.user_id->name,
2153 uidnode->pkt->pkt.user_id->len);
2156 stats->secret_read++;
2158 if ((options & IMPORT_NO_SECKEY))
2161 log_error (_("importing secret keys not allowed\n"));
2168 log_error( _("key %s: no user ID\n"), keystr_from_pk (pk));
2172 ski = pk->seckey_info;
2175 /* Actually an internal error. */
2176 log_error ("key %s: secret key info missing\n", keystr_from_pk (pk));
2180 /* A quick check to not import keys with an invalid protection
2181 cipher algorithm (only checks the primary key, though). */
2182 if (ski->algo > 110)
2185 log_error (_("key %s: secret key with invalid cipher %d"
2186 " - skipped\n"), keystr_from_pk (pk), ski->algo);
2190 #ifdef ENABLE_SELINUX_HACKS
2193 /* We don't allow importing secret keys because that may be used
2194 to put a secret key into the keyring and the user might later
2195 be tricked into signing stuff with that key. */
2196 log_error (_("importing secret keys not allowed\n"));
2201 clear_kbnode_flags (keyblock);
2203 nr_prev = stats->skipped_new_keys;
2205 /* Make a public key out of the key. */
2206 pub_keyblock = sec_to_pub_keyblock (keyblock);
2208 log_error ("key %s: failed to create public key from secret key\n",
2209 keystr_from_pk (pk));
2212 /* Note that this outputs an IMPORT_OK status message for the
2213 public key block, and below we will output another one for
2214 the secret keys. FIXME? */
2215 import_one (ctrl, pub_keyblock, stats,
2216 NULL, NULL, options, 1, for_migration,
2217 screener, screener_arg);
2219 /* Fixme: We should check for an invalid keyblock and
2220 cancel the secret key import in this case. */
2221 release_kbnode (pub_keyblock);
2223 /* At least we cancel the secret key import when the public key
2224 import was skipped due to MERGE_ONLY option and a new
2226 if (stats->skipped_new_keys <= nr_prev)
2228 /* Read the keyblock again to get the effects of a merge. */
2229 /* Fixme: we should do this based on the fingerprint or
2230 even better let import_one return the merged
2232 node = get_pubkeyblock (keyid);
2234 log_error ("key %s: failed to re-lookup public key\n",
2235 keystr_from_pk (pk));
2240 /* transfer_secret_keys collects subkey stats. */
2241 struct import_stats_s subkey_stats = {0};
2243 err = transfer_secret_keys (ctrl, &subkey_stats, keyblock,
2245 if (gpg_err_code (err) == GPG_ERR_NOT_PROCESSED)
2247 /* TRANSLATORS: For smartcard, each private key on
2248 host has a reference (stub) to a smartcard and
2249 actual private key data is stored on the card. A
2250 single smartcard can have up to three private key
2251 data. Importing private key stub is always
2252 skipped in 2.1, and it returns
2253 GPG_ERR_NOT_PROCESSED. Instead, user should be
2254 suggested to run 'gpg --card-status', then,
2255 references to a card will be automatically
2257 log_info (_("To migrate '%s', with each smartcard, "
2258 "run: %s\n"), "secring.gpg", "gpg --card-status");
2265 log_info (_("key %s: secret key imported\n"),
2266 keystr_from_pk (pk));
2267 if (subkey_stats.secret_imported)
2270 stats->secret_imported += 1;
2272 if (subkey_stats.secret_dups)
2273 stats->secret_dups += 1;
2275 if (is_status_enabled ())
2276 print_import_ok (pk, status);
2277 check_prefs (ctrl, node);
2279 release_kbnode (node);
2289 * Import a revocation certificate; this is a single signature packet.
2292 import_revoke_cert (ctrl_t ctrl, kbnode_t node, struct import_stats_s *stats)
2294 PKT_public_key *pk = NULL;
2296 kbnode_t keyblock = NULL;
2297 KEYDB_HANDLE hd = NULL;
2301 log_assert (!node->next );
2302 log_assert (node->pkt->pkttype == PKT_SIGNATURE );
2303 log_assert (node->pkt->pkt.signature->sig_class == 0x20 );
2305 keyid[0] = node->pkt->pkt.signature->keyid[0];
2306 keyid[1] = node->pkt->pkt.signature->keyid[1];
2308 pk = xmalloc_clear( sizeof *pk );
2309 rc = get_pubkey( pk, keyid );
2310 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY )
2312 log_error(_("key %s: no public key -"
2313 " can't apply revocation certificate\n"), keystr(keyid));
2319 log_error(_("key %s: public key not found: %s\n"),
2320 keystr(keyid), gpg_strerror (rc));
2324 /* Read the original keyblock. */
2328 rc = gpg_error_from_syserror ();
2333 byte afp[MAX_FINGERPRINT_LEN];
2336 fingerprint_from_pk (pk, afp, &an);
2337 while (an < MAX_FINGERPRINT_LEN)
2339 rc = keydb_search_fpr (hd, afp);
2343 log_error (_("key %s: can't locate original keyblock: %s\n"),
2344 keystr(keyid), gpg_strerror (rc));
2347 rc = keydb_get_keyblock (hd, &keyblock );
2350 log_error (_("key %s: can't read original keyblock: %s\n"),
2351 keystr(keyid), gpg_strerror (rc));
2355 /* it is okay, that node is not in keyblock because
2356 * check_key_signature works fine for sig_class 0x20 in this
2358 rc = check_key_signature( keyblock, node, NULL);
2361 log_error( _("key %s: invalid revocation certificate"
2362 ": %s - rejected\n"), keystr(keyid), gpg_strerror (rc));
2366 /* check whether we already have this */
2367 for(onode=keyblock->next; onode; onode=onode->next ) {
2368 if (onode->pkt->pkttype == PKT_USER_ID )
2370 else if (onode->pkt->pkttype == PKT_SIGNATURE
2371 && !cmp_signatures(node->pkt->pkt.signature,
2372 onode->pkt->pkt.signature))
2375 goto leave; /* yes, we already know about it */
2380 insert_kbnode( keyblock, clone_kbnode(node), 0 );
2382 /* and write the keyblock back */
2383 rc = keydb_update_keyblock (ctrl, hd, keyblock );
2385 log_error (_("error writing keyring '%s': %s\n"),
2386 keydb_get_resource_name (hd), gpg_strerror (rc) );
2393 char *p=get_user_id_native (keyid);
2394 log_info( _("key %s: \"%s\" revocation certificate imported\n"),
2400 /* If the key we just revoked was ultimately trusted, remove its
2401 ultimate trust. This doesn't stop the user from putting the
2402 ultimate trust back, but is a reasonable solution for now. */
2403 if(get_ownertrust(pk)==TRUST_ULTIMATE)
2404 clear_ownertrusts(pk);
2406 revalidation_mark ();
2410 release_kbnode( keyblock );
2411 free_public_key( pk );
2416 /* Loop over the keyblock and check all self signatures. On return
2417 * the following bis in the node flags are set:
2419 * - NODE_GOOD_SELFSIG :: User ID or subkey has a self-signature
2420 * - NODE_BAD_SELFSIG :: Used ID or subkey has an invalid self-signature
2421 * - NODE_DELETION_MARK :: This node shall be deleted
2423 * NON_SELF is set to true if there are any sigs other than self-sigs
2426 * Returns 0 on success or -1 (but not an error code) if the keyblock
2430 chk_self_sigs (kbnode_t keyblock, u32 *keyid, int *non_self )
2432 kbnode_t n, knode = NULL;
2435 u32 bsdate=0, rsdate=0;
2436 kbnode_t bsnode = NULL, rsnode = NULL;
2438 for (n=keyblock; (n = find_next_kbnode (n, 0)); )
2440 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2450 if ( n->pkt->pkttype != PKT_SIGNATURE )
2453 sig = n->pkt->pkt.signature;
2454 if ( keyid[0] != sig->keyid[0] || keyid[1] != sig->keyid[1] )
2460 /* This just caches the sigs for later use. That way we
2461 import a fully-cached key which speeds things up. */
2462 if (!opt.no_sig_cache)
2463 check_key_signature (keyblock, n, NULL);
2465 if ( IS_UID_SIG(sig) || IS_UID_REV(sig) )
2467 kbnode_t unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
2470 log_error( _("key %s: no user ID for signature\n"),
2472 return -1; /* The complete keyblock is invalid. */
2475 /* If it hasn't been marked valid yet, keep trying. */
2476 if (!(unode->flag & NODE_GOOD_SELFSIG))
2478 rc = check_key_signature (keyblock, n, NULL);
2483 char *p = utf8_to_native
2484 (unode->pkt->pkt.user_id->name,
2485 strlen (unode->pkt->pkt.user_id->name),0);
2486 log_info (gpg_err_code(rc) == GPG_ERR_PUBKEY_ALGO ?
2487 _("key %s: unsupported public key "
2488 "algorithm on user ID \"%s\"\n"):
2489 _("key %s: invalid self-signature "
2490 "on user ID \"%s\"\n"),
2496 unode->flag |= NODE_GOOD_SELFSIG;
2499 else if (IS_KEY_SIG (sig))
2501 rc = check_key_signature (keyblock, n, NULL);
2505 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
2506 _("key %s: unsupported public key algorithm\n"):
2507 _("key %s: invalid direct key signature\n"),
2509 n->flag |= NODE_DELETION_MARK;
2512 else if ( IS_SUBKEY_SIG (sig) )
2514 /* Note that this works based solely on the timestamps like
2515 the rest of gpg. If the standard gets revocation
2516 targets, this may need to be revised. */
2521 log_info (_("key %s: no subkey for key binding\n"),
2523 n->flag |= NODE_DELETION_MARK;
2527 rc = check_key_signature (keyblock, n, NULL);
2531 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
2532 _("key %s: unsupported public key"
2534 _("key %s: invalid subkey binding\n"),
2536 n->flag |= NODE_DELETION_MARK;
2540 /* It's valid, so is it newer? */
2541 if (sig->timestamp >= bsdate)
2543 knode->flag |= NODE_GOOD_SELFSIG; /* Subkey is valid. */
2546 /* Delete the last binding sig since this
2548 bsnode->flag |= NODE_DELETION_MARK;
2550 log_info (_("key %s: removed multiple subkey"
2551 " binding\n"),keystr(keyid));
2555 bsdate = sig->timestamp;
2558 n->flag |= NODE_DELETION_MARK; /* older */
2562 else if ( IS_SUBKEY_REV (sig) )
2564 /* We don't actually mark the subkey as revoked right now,
2565 so just check that the revocation sig is the most recent
2566 valid one. Note that we don't care if the binding sig is
2567 newer than the revocation sig. See the comment in
2568 getkey.c:merge_selfsigs_subkey for more. */
2572 log_info (_("key %s: no subkey for key revocation\n"),
2574 n->flag |= NODE_DELETION_MARK;
2578 rc = check_key_signature (keyblock, n, NULL);
2582 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
2583 _("key %s: unsupported public"
2584 " key algorithm\n"):
2585 _("key %s: invalid subkey revocation\n"),
2587 n->flag |= NODE_DELETION_MARK;
2591 /* It's valid, so is it newer? */
2592 if (sig->timestamp >= rsdate)
2596 /* Delete the last revocation sig since
2597 this one is newer. */
2598 rsnode->flag |= NODE_DELETION_MARK;
2600 log_info (_("key %s: removed multiple subkey"
2601 " revocation\n"),keystr(keyid));
2605 rsdate = sig->timestamp;
2608 n->flag |= NODE_DELETION_MARK; /* older */
2618 /* Delete all parts which are invalid and those signatures whose
2619 * public key algorithm is not available in this implemenation; but
2620 * consider RSA as valid, because parse/build_packets knows about it.
2622 * Returns: True if at least one valid user-id is left over.
2625 delete_inv_parts (kbnode_t keyblock, u32 *keyid, unsigned int options)
2628 int nvalid=0, uid_seen=0, subkey_seen=0;
2630 for (node=keyblock->next; node; node = node->next )
2632 if (node->pkt->pkttype == PKT_USER_ID)
2635 if ((node->flag & NODE_BAD_SELFSIG)
2636 || !(node->flag & NODE_GOOD_SELFSIG))
2640 char *p=utf8_to_native(node->pkt->pkt.user_id->name,
2641 node->pkt->pkt.user_id->len,0);
2642 log_info( _("key %s: skipped user ID \"%s\"\n"),
2646 delete_kbnode( node ); /* the user-id */
2647 /* and all following packets up to the next user-id */
2649 && node->next->pkt->pkttype != PKT_USER_ID
2650 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
2651 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
2652 delete_kbnode( node->next );
2659 else if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2660 || node->pkt->pkttype == PKT_SECRET_SUBKEY )
2662 if ((node->flag & NODE_BAD_SELFSIG)
2663 || !(node->flag & NODE_GOOD_SELFSIG))
2666 log_info( _("key %s: skipped subkey\n"),keystr(keyid));
2668 delete_kbnode( node ); /* the subkey */
2669 /* and all following signature packets */
2671 && node->next->pkt->pkttype == PKT_SIGNATURE ) {
2672 delete_kbnode( node->next );
2679 else if (node->pkt->pkttype == PKT_SIGNATURE
2680 && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
2681 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
2683 delete_kbnode( node ); /* build_packet() can't handle this */
2685 else if (node->pkt->pkttype == PKT_SIGNATURE
2686 && !node->pkt->pkt.signature->flags.exportable
2687 && !(options&IMPORT_LOCAL_SIGS)
2688 && !have_secret_key_with_kid (node->pkt->pkt.signature->keyid))
2690 /* here we violate the rfc a bit by still allowing
2691 * to import non-exportable signature when we have the
2692 * the secret key used to create this signature - it
2693 * seems that this makes sense */
2695 log_info( _("key %s: non exportable signature"
2696 " (class 0x%02X) - skipped\n"),
2697 keystr(keyid), node->pkt->pkt.signature->sig_class );
2698 delete_kbnode( node );
2700 else if (node->pkt->pkttype == PKT_SIGNATURE
2701 && node->pkt->pkt.signature->sig_class == 0x20)
2706 log_info( _("key %s: revocation certificate"
2707 " at wrong place - skipped\n"),keystr(keyid));
2708 delete_kbnode( node );
2712 /* If the revocation cert is from a different key than
2713 the one we're working on don't check it - it's
2714 probably from a revocation key and won't be
2715 verifiable with this key anyway. */
2717 if(node->pkt->pkt.signature->keyid[0]==keyid[0]
2718 && node->pkt->pkt.signature->keyid[1]==keyid[1])
2720 int rc = check_key_signature( keyblock, node, NULL);
2724 log_info( _("key %s: invalid revocation"
2725 " certificate: %s - skipped\n"),
2726 keystr(keyid), gpg_strerror (rc));
2727 delete_kbnode( node );
2732 else if (node->pkt->pkttype == PKT_SIGNATURE
2733 && (node->pkt->pkt.signature->sig_class == 0x18
2734 || node->pkt->pkt.signature->sig_class == 0x28)
2738 log_info( _("key %s: subkey signature"
2739 " in wrong place - skipped\n"), keystr(keyid));
2740 delete_kbnode( node );
2742 else if (node->pkt->pkttype == PKT_SIGNATURE
2743 && !IS_CERT(node->pkt->pkt.signature))
2746 log_info(_("key %s: unexpected signature class (0x%02X) -"
2747 " skipped\n"),keystr(keyid),
2748 node->pkt->pkt.signature->sig_class);
2749 delete_kbnode(node);
2751 else if ((node->flag & NODE_DELETION_MARK))
2752 delete_kbnode( node );
2755 /* note: because keyblock is the public key, it is never marked
2756 * for deletion and so keyblock cannot change */
2757 commit_kbnode( &keyblock );
2761 /* This function returns true if any UID is left in the keyring. */
2763 any_uid_left (kbnode_t keyblock)
2767 for (node=keyblock->next; node; node = node->next)
2768 if (node->pkt->pkttype == PKT_USER_ID)
2776 * It may happen that the imported keyblock has duplicated user IDs.
2777 * We check this here and collapse those user IDs together with their
2779 * Returns: True if the keyblock has changed.
2782 collapse_uids( kbnode_t *keyblock )
2787 for(uid1=*keyblock;uid1;uid1=uid1->next)
2791 if(is_deleted_kbnode(uid1))
2794 if(uid1->pkt->pkttype!=PKT_USER_ID)
2797 for(uid2=uid1->next;uid2;uid2=uid2->next)
2799 if(is_deleted_kbnode(uid2))
2802 if(uid2->pkt->pkttype!=PKT_USER_ID)
2805 if(cmp_user_ids(uid1->pkt->pkt.user_id,
2806 uid2->pkt->pkt.user_id)==0)
2808 /* We have a duplicated uid */
2813 /* Now take uid2's signatures, and attach them to
2815 for(last=uid2;last->next;last=last->next)
2817 if(is_deleted_kbnode(last))
2820 if(last->next->pkt->pkttype==PKT_USER_ID
2821 || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
2822 || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
2827 (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
2829 /* Now put uid2 in place as part of uid1 */
2830 last->next=uid1->next;
2832 delete_kbnode(uid2);
2834 /* Now dedupe uid1 */
2835 for(sig1=uid1->next;sig1;sig1=sig1->next)
2839 if(is_deleted_kbnode(sig1))
2842 if(sig1->pkt->pkttype==PKT_USER_ID
2843 || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
2844 || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
2847 if(sig1->pkt->pkttype!=PKT_SIGNATURE)
2850 for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
2852 if(is_deleted_kbnode(sig2))
2855 if(sig2->pkt->pkttype==PKT_USER_ID
2856 || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
2857 || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
2860 if(sig2->pkt->pkttype!=PKT_SIGNATURE)
2863 if(cmp_signatures(sig1->pkt->pkt.signature,
2864 sig2->pkt->pkt.signature)==0)
2866 /* We have a match, so delete the second
2868 delete_kbnode(sig2);
2877 commit_kbnode(keyblock);
2879 if(any && !opt.quiet)
2881 const char *key="???";
2883 if ((uid1 = find_kbnode (*keyblock, PKT_PUBLIC_KEY)) )
2884 key = keystr_from_pk (uid1->pkt->pkt.public_key);
2885 else if ((uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY)) )
2886 key = keystr_from_pk (uid1->pkt->pkt.public_key);
2888 log_info (_("key %s: duplicated user ID detected - merged\n"), key);
2895 /* Check for a 0x20 revocation from a revocation key that is not
2896 present. This may be called without the benefit of merge_xxxx so
2897 you can't rely on pk->revkey and friends. */
2899 revocation_present (ctrl_t ctrl, kbnode_t keyblock)
2901 kbnode_t onode, inode;
2902 PKT_public_key *pk = keyblock->pkt->pkt.public_key;
2904 for(onode=keyblock->next;onode;onode=onode->next)
2906 /* If we reach user IDs, we're done. */
2907 if(onode->pkt->pkttype==PKT_USER_ID)
2910 if(onode->pkt->pkttype==PKT_SIGNATURE &&
2911 onode->pkt->pkt.signature->sig_class==0x1F &&
2912 onode->pkt->pkt.signature->revkey)
2915 PKT_signature *sig=onode->pkt->pkt.signature;
2917 for(idx=0;idx<sig->numrevkeys;idx++)
2921 keyid_from_fingerprint(sig->revkey[idx].fpr,
2922 MAX_FINGERPRINT_LEN,keyid);
2924 for(inode=keyblock->next;inode;inode=inode->next)
2926 /* If we reach user IDs, we're done. */
2927 if(inode->pkt->pkttype==PKT_USER_ID)
2930 if(inode->pkt->pkttype==PKT_SIGNATURE &&
2931 inode->pkt->pkt.signature->sig_class==0x20 &&
2932 inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
2933 inode->pkt->pkt.signature->keyid[1]==keyid[1])
2935 /* Okay, we have a revocation key, and a
2936 revocation issued by it. Do we have the key
2940 rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx].fpr,
2941 MAX_FINGERPRINT_LEN);
2942 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2943 || gpg_err_code (rc) == GPG_ERR_UNUSABLE_PUBKEY)
2945 char *tempkeystr=xstrdup(keystr_from_pk(pk));
2947 /* No, so try and get it */
2948 if ((opt.keyserver_options.options
2949 & KEYSERVER_AUTO_KEY_RETRIEVE)
2950 && keyserver_any_configured (ctrl))
2952 log_info(_("WARNING: key %s may be revoked:"
2953 " fetching revocation key %s\n"),
2954 tempkeystr,keystr(keyid));
2955 keyserver_import_fprint (ctrl,
2956 sig->revkey[idx].fpr,
2957 MAX_FINGERPRINT_LEN,
2960 /* Do we have it now? */
2961 rc=get_pubkey_byfprint_fast (NULL,
2962 sig->revkey[idx].fpr,
2963 MAX_FINGERPRINT_LEN);
2966 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2967 || gpg_err_code (rc) == GPG_ERR_UNUSABLE_PUBKEY)
2968 log_info(_("WARNING: key %s may be revoked:"
2969 " revocation key %s not present.\n"),
2970 tempkeystr,keystr(keyid));
2983 * compare and merge the blocks
2985 * o compare the signatures: If we already have this signature, check
2986 * that they compare okay; if not, issue a warning and ask the user.
2987 * o Simply add the signature. Can't verify here because we may not have
2988 * the signature's public key yet; verification is done when putting it
2989 * into the trustdb, which is done automagically as soon as this pubkey
2991 * Note: We indicate newly inserted packets with NODE_FLAG_A.
2994 merge_blocks (kbnode_t keyblock_orig, kbnode_t keyblock,
2995 u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
2997 kbnode_t onode, node;
3000 /* 1st: handle revocation certificates */
3001 for (node=keyblock->next; node; node=node->next )
3003 if (node->pkt->pkttype == PKT_USER_ID )
3005 else if (node->pkt->pkttype == PKT_SIGNATURE
3006 && node->pkt->pkt.signature->sig_class == 0x20)
3008 /* check whether we already have this */
3010 for (onode=keyblock_orig->next; onode; onode=onode->next)
3012 if (onode->pkt->pkttype == PKT_USER_ID )
3014 else if (onode->pkt->pkttype == PKT_SIGNATURE
3015 && onode->pkt->pkt.signature->sig_class == 0x20
3016 && !cmp_signatures(onode->pkt->pkt.signature,
3017 node->pkt->pkt.signature))
3025 kbnode_t n2 = clone_kbnode(node);
3026 insert_kbnode( keyblock_orig, n2, 0 );
3027 n2->flag |= NODE_FLAG_A;
3031 char *p=get_user_id_native (keyid);
3032 log_info(_("key %s: \"%s\" revocation"
3033 " certificate added\n"), keystr(keyid),p);
3040 /* 2nd: merge in any direct key (0x1F) sigs */
3041 for(node=keyblock->next; node; node=node->next)
3043 if (node->pkt->pkttype == PKT_USER_ID )
3045 else if (node->pkt->pkttype == PKT_SIGNATURE
3046 && node->pkt->pkt.signature->sig_class == 0x1F)
3048 /* check whether we already have this */
3050 for (onode=keyblock_orig->next; onode; onode=onode->next)
3052 if (onode->pkt->pkttype == PKT_USER_ID)
3054 else if (onode->pkt->pkttype == PKT_SIGNATURE
3055 && onode->pkt->pkt.signature->sig_class == 0x1F
3056 && !cmp_signatures(onode->pkt->pkt.signature,
3057 node->pkt->pkt.signature))
3065 kbnode_t n2 = clone_kbnode(node);
3066 insert_kbnode( keyblock_orig, n2, 0 );
3067 n2->flag |= NODE_FLAG_A;
3070 log_info( _("key %s: direct key signature added\n"),
3076 /* 3rd: try to merge new certificates in */
3077 for (onode=keyblock_orig->next; onode; onode=onode->next)
3079 if (!(onode->flag & NODE_FLAG_A) && onode->pkt->pkttype == PKT_USER_ID)
3081 /* find the user id in the imported keyblock */
3082 for (node=keyblock->next; node; node=node->next)
3083 if (node->pkt->pkttype == PKT_USER_ID
3084 && !cmp_user_ids( onode->pkt->pkt.user_id,
3085 node->pkt->pkt.user_id ) )
3087 if (node ) /* found: merge */
3089 rc = merge_sigs (onode, node, n_sigs);
3096 /* 4th: add new user-ids */
3097 for (node=keyblock->next; node; node=node->next)
3099 if (node->pkt->pkttype == PKT_USER_ID)
3101 /* do we have this in the original keyblock */
3102 for (onode=keyblock_orig->next; onode; onode=onode->next )
3103 if (onode->pkt->pkttype == PKT_USER_ID
3104 && !cmp_user_ids( onode->pkt->pkt.user_id,
3105 node->pkt->pkt.user_id ) )
3107 if (!onode ) /* this is a new user id: append */
3109 rc = append_uid (keyblock_orig, node, n_sigs);
3117 /* 5th: add new subkeys */
3118 for (node=keyblock->next; node; node=node->next)
3121 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3123 /* do we have this in the original keyblock? */
3124 for(onode=keyblock_orig->next; onode; onode=onode->next)
3125 if (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
3126 && !cmp_public_keys( onode->pkt->pkt.public_key,
3127 node->pkt->pkt.public_key))
3129 if (!onode ) /* This is a new subkey: append. */
3131 rc = append_key (keyblock_orig, node, n_sigs);
3137 else if (node->pkt->pkttype == PKT_SECRET_SUBKEY)
3139 /* do we have this in the original keyblock? */
3140 for (onode=keyblock_orig->next; onode; onode=onode->next )
3141 if (onode->pkt->pkttype == PKT_SECRET_SUBKEY
3142 && !cmp_public_keys (onode->pkt->pkt.public_key,
3143 node->pkt->pkt.public_key) )
3145 if (!onode ) /* This is a new subkey: append. */
3147 rc = append_key (keyblock_orig, node, n_sigs);
3155 /* 6th: merge subkey certificates */
3156 for (onode=keyblock_orig->next; onode; onode=onode->next)
3158 if (!(onode->flag & NODE_FLAG_A)
3159 && (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
3160 || onode->pkt->pkttype == PKT_SECRET_SUBKEY))
3162 /* find the subkey in the imported keyblock */
3163 for(node=keyblock->next; node; node=node->next)
3165 if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
3166 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
3167 && !cmp_public_keys( onode->pkt->pkt.public_key,
3168 node->pkt->pkt.public_key ) )
3171 if (node) /* Found: merge. */
3173 rc = merge_keysigs( onode, node, n_sigs);
3184 /* Helper function for merge_blocks.
3185 * Append the userid starting with NODE and all signatures to KEYBLOCK.
3188 append_uid (kbnode_t keyblock, kbnode_t node, int *n_sigs)
3191 kbnode_t n_where = NULL;
3193 log_assert (node->pkt->pkttype == PKT_USER_ID );
3195 /* find the position */
3196 for (n = keyblock; n; n_where = n, n = n->next)
3198 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
3199 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
3205 /* and append/insert */
3208 /* we add a clone to the original keyblock, because this
3209 * one is released first */
3210 n = clone_kbnode(node);
3213 insert_kbnode( n_where, n, 0 );
3217 add_kbnode( keyblock, n );
3218 n->flag |= NODE_FLAG_A;
3219 node->flag |= NODE_FLAG_A;
3220 if (n->pkt->pkttype == PKT_SIGNATURE )
3224 if (node && node->pkt->pkttype != PKT_SIGNATURE )
3232 /* Helper function for merge_blocks
3233 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
3234 * (how should we handle comment packets here?)
3237 merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs)
3242 log_assert (dst->pkt->pkttype == PKT_USER_ID);
3243 log_assert (src->pkt->pkttype == PKT_USER_ID);
3245 for (n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next)
3247 if (n->pkt->pkttype != PKT_SIGNATURE )
3249 if (n->pkt->pkt.signature->sig_class == 0x18
3250 || n->pkt->pkt.signature->sig_class == 0x28 )
3251 continue; /* skip signatures which are only valid on subkeys */
3254 for (n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
3255 if (!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
3262 /* This signature is new or newer, append N to DST.
3263 * We add a clone to the original keyblock, because this
3264 * one is released first */
3265 n2 = clone_kbnode(n);
3266 insert_kbnode( dst, n2, PKT_SIGNATURE );
3267 n2->flag |= NODE_FLAG_A;
3268 n->flag |= NODE_FLAG_A;
3277 /* Helper function for merge_blocks
3278 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
3281 merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs)
3286 log_assert (dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
3287 || dst->pkt->pkttype == PKT_SECRET_SUBKEY);
3289 for (n=src->next; n ; n = n->next)
3291 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
3292 || n->pkt->pkttype == PKT_PUBLIC_KEY )
3294 if (n->pkt->pkttype != PKT_SIGNATURE )
3298 for (n2=dst->next; n2; n2 = n2->next)
3300 if (n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
3301 || n2->pkt->pkttype == PKT_PUBLIC_KEY )
3303 if (n2->pkt->pkttype == PKT_SIGNATURE
3304 && (n->pkt->pkt.signature->keyid[0]
3305 == n2->pkt->pkt.signature->keyid[0])
3306 && (n->pkt->pkt.signature->keyid[1]
3307 == n2->pkt->pkt.signature->keyid[1])
3308 && (n->pkt->pkt.signature->timestamp
3309 <= n2->pkt->pkt.signature->timestamp)
3310 && (n->pkt->pkt.signature->sig_class
3311 == n2->pkt->pkt.signature->sig_class))
3319 /* This signature is new or newer, append N to DST.
3320 * We add a clone to the original keyblock, because this
3321 * one is released first */
3322 n2 = clone_kbnode(n);
3323 insert_kbnode( dst, n2, PKT_SIGNATURE );
3324 n2->flag |= NODE_FLAG_A;
3325 n->flag |= NODE_FLAG_A;
3334 /* Helper function for merge_blocks.
3335 * Append the subkey starting with NODE and all signatures to KEYBLOCK.
3336 * Mark all new and copied packets by setting flag bit 0.
3339 append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs)
3343 log_assert (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
3344 || node->pkt->pkttype == PKT_SECRET_SUBKEY);
3348 /* we add a clone to the original keyblock, because this
3349 * one is released first */
3350 n = clone_kbnode(node);
3351 add_kbnode( keyblock, n );
3352 n->flag |= NODE_FLAG_A;
3353 node->flag |= NODE_FLAG_A;
3354 if (n->pkt->pkttype == PKT_SIGNATURE )
3358 if (node && node->pkt->pkttype != PKT_SIGNATURE )