1 /* import.c - import a key into our key storage.
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3 * 2007 Free Software Foundation, Inc.
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 <http://www.gnu.org/licenses/>.
39 #include "keyserver-internal.h"
52 ulong secret_imported;
54 ulong skipped_new_keys;
61 static int import( IOBUF inp, const char* fname,struct stats_s *stats,
62 unsigned char **fpr,size_t *fpr_len,unsigned int options,
63 import_filter_t filter, void *filter_arg,
65 static int read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root );
66 static void revocation_present(KBNODE keyblock);
67 static int import_one(const char *fname, KBNODE keyblock,struct stats_s *stats,
68 unsigned char **fpr,size_t *fpr_len,
69 unsigned int options,int from_sk,
70 import_filter_t filter, void *filter_arg);
71 static int import_secret_one( const char *fname, KBNODE keyblock,
72 struct stats_s *stats, unsigned int options,
73 import_filter_t filter, void *filter_arg);
74 static int import_revoke_cert( const char *fname, KBNODE node,
75 struct stats_s *stats);
76 static int chk_self_sigs( const char *fname, KBNODE keyblock,
77 PKT_public_key *pk, u32 *keyid, int *non_self );
78 static int delete_inv_parts( const char *fname, KBNODE keyblock,
79 u32 *keyid, unsigned int options );
80 static int merge_blocks( const char *fname, KBNODE keyblock_orig,
81 KBNODE keyblock, u32 *keyid,
82 int *n_uids, int *n_sigs, int *n_subk );
83 static int append_uid( KBNODE keyblock, KBNODE node, int *n_sigs,
84 const char *fname, u32 *keyid );
85 static int append_key( KBNODE keyblock, KBNODE node, int *n_sigs,
86 const char *fname, u32 *keyid );
87 static int merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
88 const char *fname, u32 *keyid );
89 static int merge_keysigs( KBNODE dst, KBNODE src, int *n_sigs,
90 const char *fname, u32 *keyid );
93 parse_import_options(char *str,unsigned int *options,int noisy)
95 struct parse_options import_opts[]=
97 {"import-local-sigs",IMPORT_LOCAL_SIGS,NULL,
98 N_("import signatures that are marked as local-only")},
100 {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,
101 N_("repair damage from the pks keyserver during import")},
103 {"keep-ownertrust", IMPORT_KEEP_OWNERTTRUST, NULL,
104 N_("do not clear the ownertrust values during import")},
106 {"fast-import",IMPORT_FAST,NULL,
107 N_("do not update the trustdb after import")},
109 {"convert-sk-to-pk",IMPORT_SK2PK,NULL,
110 N_("create a public key when importing a secret key")},
112 {"merge-only",IMPORT_MERGE_ONLY,NULL,
113 N_("only accept updates to existing keys")},
115 {"import-clean",IMPORT_CLEAN,NULL,
116 N_("remove unusable parts from key after import")},
118 {"import-minimal",IMPORT_MINIMAL|IMPORT_CLEAN,NULL,
119 N_("remove as much as possible from key after import")},
121 /* Aliases for backward compatibility */
122 {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL},
123 {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL},
125 {"import-unusable-sigs",0,NULL,NULL},
126 {"import-clean-sigs",0,NULL,NULL},
127 {"import-clean-uids",0,NULL,NULL},
131 return parse_options(str,options,import_opts,noisy);
135 import_new_stats_handle (void)
137 return xmalloc_clear ( sizeof (struct stats_s) );
141 import_release_stats_handle (void *p)
147 * Import the public keys from the given filename. Input may be armored.
148 * This function rejects all keys which are not validly self signed on at
149 * least one userid. Only user ids which are self signed will be imported.
150 * Other signatures are not checked.
152 * Actually this function does a merge. It works like this:
155 * - check self-signatures and remove all userids and their signatures
156 * without/invalid self-signatures.
157 * - reject the keyblock, if we have no valid userid.
158 * - See whether we have this key already in one of our pubrings.
159 * If not, simply add it to the default keyring.
160 * - Compare the key and the self-signatures of the new and the one in
161 * our keyring. If they are different something weird is going on;
163 * - See whether we have only non-self-signature on one user id; if not
164 * ask the user what to do.
165 * - compare the signatures: If we already have this signature, check
166 * that they compare okay; if not, issue a warning and ask the user.
167 * (consider looking at the timestamp and use the newest?)
168 * - Simply add the signature. Can't verify here because we may not have
169 * the signature's public key yet; verification is done when putting it
170 * into the trustdb, which is done automagically as soon as this pubkey
172 * - Proceed with next signature.
174 * Key revocation certificates have special handling.
178 import_keys_internal( IOBUF inp, char **fnames, int nnames,
179 void *stats_handle, unsigned char **fpr, size_t *fpr_len,
180 unsigned int options,
181 import_filter_t filter, void *filter_arg,
185 struct stats_s *stats = stats_handle;
188 stats = import_new_stats_handle ();
191 rc = import (inp, "[stream]", stats, fpr, fpr_len, options,
192 filter, filter_arg, r_gpgkeys_err);
195 int once = (!fnames && !nnames);
197 for(i=0; once || i < nnames; once=0, i++ ) {
198 const char *fname = fnames? fnames[i] : NULL;
199 IOBUF inp2 = iobuf_open(fname);
202 if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
209 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
212 rc = import (inp2, fname, stats, fpr, fpr_len, options,
213 NULL, NULL, r_gpgkeys_err);
215 /* Must invalidate that ugly cache to actually close it. */
216 iobuf_ioctl (NULL, 2, 0, (char*)fname);
218 log_error("import from `%s' failed: %s\n", fname,
224 import_print_stats (stats);
225 import_release_stats_handle (stats);
228 /* If no fast import and the trustdb is dirty (i.e. we added a key
229 or userID that had something other than a selfsig, a signature
230 that was other than a selfsig, or any revocation), then
231 update/check the trustdb if the user specified by setting
232 interactive or by not setting no-auto-check-trustdb */
234 if(!(options&IMPORT_FAST))
235 trustdb_check_or_update();
241 import_keys( char **fnames, int nnames,
242 void *stats_handle, unsigned int options )
244 import_keys_internal (NULL, fnames, nnames, stats_handle, NULL, NULL,
245 options, NULL, NULL, NULL);
249 /* Import keys from an open stream. */
251 import_keys_stream( IOBUF inp, void *stats_handle,
252 unsigned char **fpr, size_t *fpr_len,unsigned int options,
253 import_filter_t filter, void *filter_arg,
256 return import_keys_internal (inp, NULL, 0, stats_handle, fpr, fpr_len,
257 options, filter, filter_arg, r_gpgkeys_err);
261 /* Note: If R_GPGKEYS_ERR is not NULL an error code from the keyserver
262 helpers will be stored there. */
264 import (IOBUF inp, const char* fname,struct stats_s *stats,
265 unsigned char **fpr, size_t *fpr_len, unsigned int options,
266 import_filter_t filter, void *filter_arg, int *r_gpgkeys_err)
268 PACKET *pending_pkt = NULL;
269 KBNODE keyblock = NULL;
271 armor_filter_context_t *afx = NULL;
273 getkey_disable_caches();
275 if (!opt.no_armor || r_gpgkeys_err) {
276 /* armored reading is not disabled or enforced. */
277 afx = new_armor_context ();
278 afx->only_keyblocks = 1;
279 push_armor_filter (afx, inp);
282 while( !(rc = read_block( inp, &pending_pkt, &keyblock) )) {
283 if( keyblock->pkt->pkttype == PKT_PUBLIC_KEY )
284 rc = import_one (fname, keyblock, stats, fpr, fpr_len, options, 0,
286 else if( keyblock->pkt->pkttype == PKT_SECRET_KEY )
287 rc = import_secret_one (fname, keyblock, stats, options,
289 else if( keyblock->pkt->pkttype == PKT_SIGNATURE
290 && keyblock->pkt->pkt.signature->sig_class == 0x20 )
291 rc = import_revoke_cert( fname, keyblock, stats );
293 log_info( _("skipping block of type %d\n"),
294 keyblock->pkt->pkttype );
296 release_kbnode(keyblock);
297 /* fixme: we should increment the not imported counter but this
298 does only make sense if we keep on going despite of errors. */
301 if( !(++stats->count % 100) && !opt.quiet )
302 log_info(_("%lu keys processed so far\n"), stats->count );
306 else if( rc && rc != G10ERR_INV_KEYRING )
307 log_error( _("error reading `%s': %s\n"), fname, g10_errstr(rc));
309 if (afx && r_gpgkeys_err)
310 *r_gpgkeys_err = afx->key_failed_code;
312 release_armor_context (afx);
319 import_print_stats (void *hd)
321 struct stats_s *stats = hd;
324 log_info(_("Total number processed: %lu\n"), stats->count );
325 if( stats->skipped_new_keys )
326 log_info(_(" skipped new keys: %lu\n"),
327 stats->skipped_new_keys );
328 if( stats->no_user_id )
329 log_info(_(" w/o user IDs: %lu\n"), stats->no_user_id );
330 if( stats->imported || stats->imported_rsa ) {
331 log_info(_(" imported: %lu"), stats->imported );
332 if (stats->imported_rsa)
333 log_printf (" (RSA: %lu)", stats->imported_rsa );
336 if( stats->unchanged )
337 log_info(_(" unchanged: %lu\n"), stats->unchanged );
339 log_info(_(" new user IDs: %lu\n"), stats->n_uids );
341 log_info(_(" new subkeys: %lu\n"), stats->n_subk );
343 log_info(_(" new signatures: %lu\n"), stats->n_sigs );
345 log_info(_(" new key revocations: %lu\n"), stats->n_revoc );
346 if( stats->secret_read )
347 log_info(_(" secret keys read: %lu\n"), stats->secret_read );
348 if( stats->secret_imported )
349 log_info(_(" secret keys imported: %lu\n"), stats->secret_imported );
350 if( stats->secret_dups )
351 log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
352 if( stats->not_imported )
353 log_info(_(" not imported: %lu\n"), stats->not_imported );
354 if( stats->n_sigs_cleaned)
355 log_info(_(" signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
356 if( stats->n_uids_cleaned)
357 log_info(_(" user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
360 if( is_status_enabled() ) {
362 sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
373 stats->secret_imported,
375 stats->skipped_new_keys,
376 stats->not_imported );
377 write_status_text( STATUS_IMPORT_RES, buf );
382 /* Return true if PKTTYPE is valid in a keyblock. */
384 valid_keyblock_packet (int pkttype)
389 case PKT_PUBLIC_SUBKEY:
391 case PKT_SECRET_SUBKEY:
404 * Read the next keyblock from stream A.
405 * PENDING_PKT should be initialzed to NULL
406 * and not chnaged form the caller.
407 * Retunr: 0 = okay, -1 no more blocks or another errorcode.
410 read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root )
418 root = new_kbnode( *pending_pkt );
424 pkt = xmalloc( sizeof *pkt );
426 while( (rc=parse_packet(a, pkt)) != -1 ) {
427 if( rc ) { /* ignore errors */
428 if( rc != G10ERR_UNKNOWN_PACKET ) {
429 log_error("read_block: read error: %s\n", g10_errstr(rc) );
430 rc = G10ERR_INV_KEYRING;
438 if( !root && pkt->pkttype == PKT_SIGNATURE
439 && pkt->pkt.signature->sig_class == 0x20 ) {
440 /* this is a revocation certificate which is handled
441 * in a special way */
442 root = new_kbnode( pkt );
447 /* make a linked list of all packets */
448 switch( pkt->pkttype ) {
450 if(check_compress_algo(pkt->pkt.compressed->algorithm))
452 rc = G10ERR_COMPR_ALGO;
457 compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
458 pkt->pkt.compressed->buf = NULL;
459 push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1);
466 /* skip those packets */
473 if( in_cert ) { /* store this packet */
480 if (in_cert && valid_keyblock_packet (pkt->pkttype)) {
482 root = new_kbnode( pkt );
484 add_kbnode( root, new_kbnode( pkt ) );
485 pkt = xmalloc( sizeof *pkt );
492 if( rc == -1 && root )
496 release_kbnode( root );
504 /* Walk through the subkeys on a pk to find if we have the PKS
505 disease: multiple subkeys with their binding sigs stripped, and the
506 sig for the first subkey placed after the last subkey. That is,
507 instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
508 "pk uid sig sub1 sub2 sub3 bind1". We can't do anything about sub2
509 and sub3, as they are already lost, but we can try and rescue sub1
510 by reordering the keyblock so that it reads "pk uid sig sub1 bind1
511 sub2 sub3". Returns TRUE if the keyblock was modified. */
514 fix_pks_corruption(KBNODE keyblock)
516 int changed=0,keycount=0;
517 KBNODE node,last=NULL,sknode=NULL;
519 /* First determine if we have the problem at all. Look for 2 or
520 more subkeys in a row, followed by a single binding sig. */
521 for(node=keyblock;node;last=node,node=node->next)
523 if(node->pkt->pkttype==PKT_PUBLIC_SUBKEY)
529 else if(node->pkt->pkttype==PKT_SIGNATURE &&
530 node->pkt->pkt.signature->sig_class==0x18 &&
531 keycount>=2 && node->next==NULL)
533 /* We might have the problem, as this key has two subkeys in
534 a row without any intervening packets. */
540 /* Temporarily attach node to sknode. */
541 node->next=sknode->next;
545 /* Note we aren't checking whether this binding sig is a
546 selfsig. This is not necessary here as the subkey and
547 binding sig will be rejected later if that is the
549 if(check_key_signature(keyblock,node,NULL))
551 /* Not a match, so undo the changes. */
552 sknode->next=node->next;
559 sknode->flag |= 1; /* Mark it good so we don't need to
573 /* Versions of GnuPG before 1.4.11 and 2.0.16 allowed to import bogus
574 direct key signatures. A side effect of this was that a later
575 import of the same good direct key signatures was not possible
576 because the cmp_signature check in merge_blocks considered them
577 equal. Although direct key signatures are now checked during
578 import, there might still be bogus signatures sitting in a keyring.
579 We need to detect and delete them before doing a merge. This
580 fucntion returns the number of removed sigs. */
582 fix_bad_direct_key_sigs (KBNODE keyblock, u32 *keyid)
588 for (node = keyblock->next; node; node=node->next)
590 if (node->pkt->pkttype == PKT_USER_ID)
592 if (node->pkt->pkttype == PKT_SIGNATURE
593 && IS_KEY_SIG (node->pkt->pkt.signature))
595 err = check_key_signature (keyblock, node, NULL);
596 if (err && gpg_err_code (err) != GPG_ERR_PUBKEY_ALGO )
598 /* If we don't know the error, we can't decide; this is
599 not a problem because cmp_signature can't compare the
601 log_info ("key %s: invalid direct key signature removed\n",
603 delete_kbnode (node);
614 print_import_ok (PKT_public_key *pk, PKT_secret_key *sk, unsigned int reason)
616 byte array[MAX_FINGERPRINT_LEN], *s;
617 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
620 sprintf (buf, "%u ", reason);
621 p = buf + strlen (buf);
624 fingerprint_from_pk (pk, array, &n);
626 fingerprint_from_sk (sk, array, &n);
628 for (i=0; i < n ; i++, s++, p += 2)
629 sprintf (p, "%02X", *s);
631 write_status_text (STATUS_IMPORT_OK, buf);
635 print_import_check (PKT_public_key * pk, PKT_user_id * id)
640 size_t i, pos = 0, n;
642 buf = xmalloc (17+41+id->len+32);
643 keyid_from_pk (pk, keyid);
644 sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
646 fingerprint_from_pk (pk, fpr, &n);
647 for (i = 0; i < n; i++, pos += 2)
648 sprintf (buf+pos, "%02X", fpr[i]);
651 strcat (buf, id->name);
652 write_status_text (STATUS_IMPORT_CHECK, buf);
657 check_prefs_warning(PKT_public_key *pk)
659 log_info(_("WARNING: key %s contains preferences for unavailable\n"
660 "algorithms on these user IDs:\n"), keystr_from_pk(pk));
664 check_prefs(KBNODE keyblock)
670 merge_keys_and_selfsig(keyblock);
671 pk=keyblock->pkt->pkt.public_key;
673 for(node=keyblock;node;node=node->next)
675 if(node->pkt->pkttype==PKT_USER_ID
676 && node->pkt->pkt.user_id->created
677 && node->pkt->pkt.user_id->prefs)
679 PKT_user_id *uid=node->pkt->pkt.user_id;
680 prefitem_t *prefs=uid->prefs;
681 char *user=utf8_to_native(uid->name,strlen(uid->name),0);
683 for(;prefs->type;prefs++)
685 char num[10]; /* prefs->value is a byte, so we're over
688 sprintf(num,"%u",prefs->value);
690 if(prefs->type==PREFTYPE_SYM)
692 if (openpgp_cipher_test_algo (prefs->value))
695 (openpgp_cipher_test_algo (prefs->value)
697 : openpgp_cipher_algo_name (prefs->value));
699 check_prefs_warning(pk);
700 log_info(_(" \"%s\": preference for cipher"
701 " algorithm %s\n"), user, algo);
705 else if(prefs->type==PREFTYPE_HASH)
707 if(openpgp_md_test_algo(prefs->value))
710 (gcry_md_test_algo (prefs->value)
712 : gcry_md_algo_name (prefs->value));
714 check_prefs_warning(pk);
715 log_info(_(" \"%s\": preference for digest"
716 " algorithm %s\n"), user, algo);
720 else if(prefs->type==PREFTYPE_ZIP)
722 if(check_compress_algo (prefs->value))
724 const char *algo=compress_algo_to_string(prefs->value);
726 check_prefs_warning(pk);
727 log_info(_(" \"%s\": preference for compression"
728 " algorithm %s\n"),user,algo?algo:num);
740 log_info(_("it is strongly suggested that you update"
741 " your preferences and\n"));
742 log_info(_("re-distribute this key to avoid potential algorithm"
743 " mismatch problems\n"));
747 strlist_t sl=NULL,locusr=NULL;
749 byte fpr[MAX_FINGERPRINT_LEN],*p;
750 char username[(MAX_FINGERPRINT_LEN*2)+1];
753 p=fingerprint_from_pk(pk,fpr,&fprlen);
754 for(i=0;i<fprlen;i++,p++)
755 sprintf(username+2*i,"%02X",*p);
756 add_to_strlist(&locusr,username);
758 append_to_strlist(&sl,"updpref");
759 append_to_strlist(&sl,"save");
761 keyedit_menu( username, locusr, sl, 1, 1 );
763 free_strlist(locusr);
766 log_info(_("you can update your preferences with:"
767 " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
772 * Try to import one keyblock. Return an error only in serious cases, but
773 * never for an invalid keyblock. It uses log_error to increase the
774 * internal errorcount, so that invalid input can be detected by programs
778 import_one( const char *fname, KBNODE keyblock, struct stats_s *stats,
779 unsigned char **fpr,size_t *fpr_len,unsigned int options,
780 int from_sk, import_filter_t filter, void *filter_arg)
783 PKT_public_key *pk_orig;
784 KBNODE node, uidnode;
785 KBNODE keyblock_orig = NULL;
793 /* get the key and print some info about it */
794 node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
798 pk = node->pkt->pkt.public_key;
800 keyid_from_pk( pk, keyid );
801 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
803 if( opt.verbose && !opt.interactive )
805 log_info( "pub %4u%c/%s %s ",
807 pubkey_letter( pk->pubkey_algo ),
808 keystr_from_pk(pk), datestr_from_pk(pk) );
810 print_utf8_string (log_get_stream (),
811 uidnode->pkt->pkt.user_id->name,
812 uidnode->pkt->pkt.user_id->len );
819 log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
823 if (filter && filter (keyblock, filter_arg))
825 log_error (_("key %s: %s\n"), keystr_from_pk(pk),
826 _("rejected by import filter"));
830 if (opt.interactive) {
831 if(is_status_enabled())
832 print_import_check (pk, uidnode->pkt->pkt.user_id);
833 merge_keys_and_selfsig (keyblock);
835 show_basic_key_info (keyblock);
837 if (!cpr_get_answer_is_yes ("import.okay",
838 "Do you want to import this key? (y/N) "))
842 collapse_uids(&keyblock);
844 /* Clean the key that we're about to import, to cut down on things
845 that we have to clean later. This has no practical impact on
846 the end result, but does result in less logging which might
848 if(options&IMPORT_CLEAN)
849 clean_key(keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL);
851 clear_kbnode_flags( keyblock );
853 if((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
855 log_info(_("key %s: PKS subkey corruption repaired\n"),
858 rc = chk_self_sigs( fname, keyblock , pk, keyid, &non_self );
860 return rc== -1? 0:rc;
862 /* If we allow such a thing, mark unsigned uids as valid */
863 if( opt.allow_non_selfsigned_uid )
864 for( node=keyblock; node; node = node->next )
865 if( node->pkt->pkttype == PKT_USER_ID && !(node->flag & 1) )
867 char *user=utf8_to_native(node->pkt->pkt.user_id->name,
868 node->pkt->pkt.user_id->len,0);
870 log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
871 keystr_from_pk(pk),user);
875 if( !delete_inv_parts( fname, keyblock, keyid, options ) ) {
876 log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
878 log_info(_("this may be caused by a missing self-signature\n"));
883 /* do we have this key already in one of our pubrings ? */
884 pk_orig = xmalloc_clear( sizeof *pk_orig );
885 rc = get_pubkey_fast ( pk_orig, keyid );
886 if( rc && rc != G10ERR_NO_PUBKEY && rc != G10ERR_UNU_PUBKEY )
888 log_error( _("key %s: public key not found: %s\n"),
889 keystr(keyid), g10_errstr(rc));
891 else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) )
894 log_info( _("key %s: new key - skipped\n"), keystr(keyid));
896 stats->skipped_new_keys++;
898 else if( rc ) { /* insert this key */
899 KEYDB_HANDLE hd = keydb_new (0);
901 rc = keydb_locate_writable (hd, NULL);
903 log_error (_("no writable keyring found: %s\n"), g10_errstr (rc));
905 return G10ERR_GENERAL;
907 if( opt.verbose > 1 )
908 log_info (_("writing to `%s'\n"), keydb_get_resource_name (hd) );
910 rc = keydb_insert_keyblock (hd, keyblock );
912 log_error (_("error writing keyring `%s': %s\n"),
913 keydb_get_resource_name (hd), g10_errstr(rc));
914 else if (!(opt.import_options & IMPORT_KEEP_OWNERTTRUST))
916 /* This should not be possible since we delete the
917 ownertrust when a key is deleted, but it can happen if
918 the keyring and trustdb are out of sync. It can also
919 be made to happen with the trusted-key command and by
920 importing and locally exported key. */
922 clear_ownertrusts (pk);
924 revalidation_mark ();
931 char *p=get_user_id_native (keyid);
932 log_info( _("key %s: public key \"%s\" imported\n"),
936 if( is_status_enabled() )
938 char *us = get_long_user_id_string( keyid );
939 write_status_text( STATUS_IMPORTED, us );
941 print_import_ok (pk,NULL, 1);
944 if( is_RSA( pk->pubkey_algo ) )
945 stats->imported_rsa++;
950 int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
952 /* Compare the original against the new key; just to be sure nothing
953 * weird is going on */
954 if( cmp_public_keys( pk_orig, pk ) )
956 log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
960 /* now read the original keyblock */
963 byte afp[MAX_FINGERPRINT_LEN];
966 fingerprint_from_pk (pk_orig, afp, &an);
967 while (an < MAX_FINGERPRINT_LEN)
969 rc = keydb_search_fpr (hd, afp);
973 log_error (_("key %s: can't locate original keyblock: %s\n"),
974 keystr(keyid), g10_errstr(rc));
978 rc = keydb_get_keyblock (hd, &keyblock_orig );
981 log_error (_("key %s: can't read original keyblock: %s\n"),
982 keystr(keyid), g10_errstr(rc));
987 /* Make sure the original direct key sigs are all sane. */
988 n_sigs_cleaned = fix_bad_direct_key_sigs (keyblock_orig, keyid);
990 commit_kbnode (&keyblock_orig);
992 /* and try to merge the block */
993 clear_kbnode_flags( keyblock_orig );
994 clear_kbnode_flags( keyblock );
995 n_uids = n_sigs = n_subk = n_uids_cleaned = 0;
996 rc = merge_blocks( fname, keyblock_orig, keyblock,
997 keyid, &n_uids, &n_sigs, &n_subk );
1004 if(options&IMPORT_CLEAN)
1005 clean_key(keyblock_orig,opt.verbose,options&IMPORT_MINIMAL,
1006 &n_uids_cleaned,&n_sigs_cleaned);
1008 if( n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned) {
1010 /* keyblock_orig has been updated; write */
1011 rc = keydb_update_keyblock (hd, keyblock_orig);
1013 log_error (_("error writing keyring `%s': %s\n"),
1014 keydb_get_resource_name (hd), g10_errstr(rc) );
1016 revalidation_mark ();
1021 char *p=get_user_id_native(keyid);
1023 log_info( _("key %s: \"%s\" 1 new user ID\n"),
1026 log_info( _("key %s: \"%s\" %d new user IDs\n"),
1027 keystr(keyid),p,n_uids);
1029 log_info( _("key %s: \"%s\" 1 new signature\n"),
1032 log_info( _("key %s: \"%s\" %d new signatures\n"),
1033 keystr(keyid), p, n_sigs );
1035 log_info( _("key %s: \"%s\" 1 new subkey\n"),
1038 log_info( _("key %s: \"%s\" %d new subkeys\n"),
1039 keystr(keyid), p, n_subk );
1040 if(n_sigs_cleaned==1)
1041 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
1042 keystr(keyid),p,n_sigs_cleaned);
1043 else if(n_sigs_cleaned)
1044 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
1045 keystr(keyid),p,n_sigs_cleaned);
1046 if(n_uids_cleaned==1)
1047 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
1048 keystr(keyid),p,n_uids_cleaned);
1049 else if(n_uids_cleaned)
1050 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
1051 keystr(keyid),p,n_uids_cleaned);
1055 stats->n_uids +=n_uids;
1056 stats->n_sigs +=n_sigs;
1057 stats->n_subk +=n_subk;
1058 stats->n_sigs_cleaned +=n_sigs_cleaned;
1059 stats->n_uids_cleaned +=n_uids_cleaned;
1061 if (is_status_enabled ())
1062 print_import_ok (pk, NULL,
1063 ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
1068 if (is_status_enabled ())
1069 print_import_ok (pk, NULL, 0);
1073 char *p=get_user_id_native(keyid);
1074 log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
1081 keydb_release (hd); hd = NULL;
1085 if (mod_key || new_key || same_key)
1087 /* A little explanation for this: we fill in the fingerprint
1088 when importing keys as it can be useful to know the
1089 fingerprint in certain keyserver-related cases (a keyserver
1090 asked for a particular name, but the key doesn't have that
1091 name). However, in cases where we're importing more than
1092 one key at a time, we cannot know which key to fingerprint.
1093 In these cases, rather than guessing, we do not
1094 fingerprinting at all, and we must hope the user ID on the
1095 keys are useful. Note that we need to do this for new
1096 keys, merged keys and even for unchanged keys. This is
1097 required because for example the --auto-key-locate feature
1098 may import an already imported key and needs to know the
1099 fingerprint of the key in all cases. */
1103 /* Note that we need to compare against 0 here because
1104 COUNT gets only incremented after returning form this
1106 if (stats->count == 0)
1107 *fpr = fingerprint_from_pk (pk, NULL, fpr_len);
1113 /* Now that the key is definitely incorporated into the keydb, we
1114 need to check if a designated revocation is present or if the
1115 prefs are not rational so we can warn the user. */
1119 revocation_present(keyblock_orig);
1120 if(!from_sk && seckey_available(keyid)==0)
1121 check_prefs(keyblock_orig);
1125 revocation_present(keyblock);
1126 if(!from_sk && seckey_available(keyid)==0)
1127 check_prefs(keyblock);
1130 release_kbnode( keyblock_orig );
1131 free_public_key( pk_orig );
1136 /* Walk a secret keyblock and produce a public keyblock out of it. */
1138 sec_to_pub_keyblock(KBNODE sec_keyblock)
1140 KBNODE secnode,pub_keyblock=NULL,ctx=NULL;
1142 while((secnode=walk_kbnode(sec_keyblock,&ctx,0)))
1146 if(secnode->pkt->pkttype==PKT_SECRET_KEY ||
1147 secnode->pkt->pkttype==PKT_SECRET_SUBKEY)
1149 /* Make a public key. We only need to convert enough to
1150 write the keyblock out. */
1152 PKT_secret_key *sk=secnode->pkt->pkt.secret_key;
1153 PACKET *pkt=xmalloc_clear(sizeof(PACKET));
1154 PKT_public_key *pk=xmalloc_clear(sizeof(PKT_public_key));
1157 if(secnode->pkt->pkttype==PKT_SECRET_KEY)
1158 pkt->pkttype=PKT_PUBLIC_KEY;
1160 pkt->pkttype=PKT_PUBLIC_SUBKEY;
1162 pkt->pkt.public_key=pk;
1164 pk->version=sk->version;
1165 pk->timestamp=sk->timestamp;
1166 pk->expiredate=sk->expiredate;
1167 pk->pubkey_algo=sk->pubkey_algo;
1169 n=pubkey_get_npkey(pk->pubkey_algo);
1172 /* we can't properly extract the pubkey without knowing
1173 the number of MPIs */
1174 release_kbnode(pub_keyblock);
1182 pk->pkey[i]=mpi_copy(sk->skey[i]);
1185 pubnode=new_kbnode(pkt);
1189 pubnode=clone_kbnode(secnode);
1192 if(pub_keyblock==NULL)
1193 pub_keyblock=pubnode;
1195 add_kbnode(pub_keyblock,pubnode);
1198 return pub_keyblock;
1202 * Ditto for secret keys. Handling is simpler than for public keys.
1203 * We allow secret key importing only when allow is true, this is so
1204 * that a secret key can not be imported accidently and thereby tampering
1205 * with the trust calculation.
1208 import_secret_one (const char *fname, KBNODE keyblock,
1209 struct stats_s *stats, unsigned int options,
1210 import_filter_t filter, void *filter_arg)
1213 KBNODE node, uidnode;
1217 /* Get the key and print some info about it. */
1218 node = find_kbnode( keyblock, PKT_SECRET_KEY );
1222 sk = node->pkt->pkt.secret_key;
1223 keyid_from_sk( sk, keyid );
1224 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1226 if (filter && filter (keyblock, filter_arg)) {
1227 log_error (_("secret key %s: %s\n"), keystr_from_sk(sk),
1228 _("rejected by import filter"));
1234 log_info( "sec %4u%c/%s %s ",
1235 nbits_from_sk( sk ),
1236 pubkey_letter( sk->pubkey_algo ),
1237 keystr_from_sk(sk), datestr_from_sk(sk) );
1239 print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
1240 uidnode->pkt->pkt.user_id->len );
1243 stats->secret_read++;
1245 if ((options & IMPORT_NO_SECKEY))
1247 log_error (_("importing secret keys not allowed\n"));
1253 log_error( _("key %s: no user ID\n"), keystr_from_sk(sk));
1257 if(sk->protect.algo>110)
1259 log_error(_("key %s: secret key with invalid cipher %d"
1260 " - skipped\n"),keystr_from_sk(sk),sk->protect.algo);
1264 #ifdef ENABLE_SELINUX_HACKS
1267 /* We don't allow to import secret keys because that may be used
1268 to put a secret key into the keyring and the user might later
1269 be tricked into signing stuff with that key. */
1270 log_error (_("importing secret keys not allowed\n"));
1275 clear_kbnode_flags( keyblock );
1277 /* do we have this key already in one of our secrings ? */
1278 rc = seckey_available( keyid );
1279 if( rc == G10ERR_NO_SECKEY && !(opt.import_options&IMPORT_MERGE_ONLY) )
1281 /* simply insert this key */
1282 KEYDB_HANDLE hd = keydb_new (1);
1284 /* get default resource */
1285 rc = keydb_locate_writable (hd, NULL);
1287 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
1289 return G10ERR_GENERAL;
1291 rc = keydb_insert_keyblock (hd, keyblock );
1293 log_error (_("error writing keyring `%s': %s\n"),
1294 keydb_get_resource_name (hd), g10_errstr(rc) );
1298 log_info( _("key %s: secret key imported\n"), keystr_from_sk(sk));
1299 stats->secret_imported++;
1300 if (is_status_enabled ())
1301 print_import_ok (NULL, sk, 1|16);
1303 if(options&IMPORT_SK2PK)
1305 /* Try and make a public key out of this. */
1307 KBNODE pub_keyblock=sec_to_pub_keyblock(keyblock);
1310 import_one (fname, pub_keyblock, stats,
1311 NULL, NULL, opt.import_options, 1,
1313 release_kbnode(pub_keyblock);
1317 /* Now that the key is definitely incorporated into the keydb,
1318 if we have the public part of this key, we need to check if
1319 the prefs are rational. */
1320 node=get_pubkeyblock(keyid);
1324 release_kbnode(node);
1328 { /* we can't merge secret keys */
1329 log_error( _("key %s: already in secret keyring\n"),
1330 keystr_from_sk(sk));
1331 stats->secret_dups++;
1332 if (is_status_enabled ())
1333 print_import_ok (NULL, sk, 16);
1335 /* TODO: if we ever do merge secret keys, make sure to handle
1336 the sec_to_pub_keyblock feature as well. */
1339 log_error( _("key %s: secret key not found: %s\n"),
1340 keystr_from_sk(sk), g10_errstr(rc));
1347 * Import a revocation certificate; this is a single signature packet.
1350 import_revoke_cert( const char *fname, KBNODE node, struct stats_s *stats )
1352 PKT_public_key *pk=NULL;
1353 KBNODE onode, keyblock = NULL;
1354 KEYDB_HANDLE hd = NULL;
1360 assert( !node->next );
1361 assert( node->pkt->pkttype == PKT_SIGNATURE );
1362 assert( node->pkt->pkt.signature->sig_class == 0x20 );
1364 keyid[0] = node->pkt->pkt.signature->keyid[0];
1365 keyid[1] = node->pkt->pkt.signature->keyid[1];
1367 pk = xmalloc_clear( sizeof *pk );
1368 rc = get_pubkey( pk, keyid );
1369 if( rc == G10ERR_NO_PUBKEY )
1371 log_error(_("key %s: no public key -"
1372 " can't apply revocation certificate\n"), keystr(keyid));
1378 log_error(_("key %s: public key not found: %s\n"),
1379 keystr(keyid), g10_errstr(rc));
1383 /* read the original keyblock */
1386 byte afp[MAX_FINGERPRINT_LEN];
1389 fingerprint_from_pk (pk, afp, &an);
1390 while (an < MAX_FINGERPRINT_LEN)
1392 rc = keydb_search_fpr (hd, afp);
1396 log_error (_("key %s: can't locate original keyblock: %s\n"),
1397 keystr(keyid), g10_errstr(rc));
1400 rc = keydb_get_keyblock (hd, &keyblock );
1403 log_error (_("key %s: can't read original keyblock: %s\n"),
1404 keystr(keyid), g10_errstr(rc));
1408 /* it is okay, that node is not in keyblock because
1409 * check_key_signature works fine for sig_class 0x20 in this
1411 rc = check_key_signature( keyblock, node, NULL);
1414 log_error( _("key %s: invalid revocation certificate"
1415 ": %s - rejected\n"), keystr(keyid), g10_errstr(rc));
1419 /* check whether we already have this */
1420 for(onode=keyblock->next; onode; onode=onode->next ) {
1421 if( onode->pkt->pkttype == PKT_USER_ID )
1423 else if( onode->pkt->pkttype == PKT_SIGNATURE
1424 && !cmp_signatures(node->pkt->pkt.signature,
1425 onode->pkt->pkt.signature))
1428 goto leave; /* yes, we already know about it */
1434 insert_kbnode( keyblock, clone_kbnode(node), 0 );
1436 /* and write the keyblock back */
1437 rc = keydb_update_keyblock (hd, keyblock );
1439 log_error (_("error writing keyring `%s': %s\n"),
1440 keydb_get_resource_name (hd), g10_errstr(rc) );
1441 keydb_release (hd); hd = NULL;
1445 char *p=get_user_id_native (keyid);
1446 log_info( _("key %s: \"%s\" revocation certificate imported\n"),
1452 /* If the key we just revoked was ultimately trusted, remove its
1453 ultimate trust. This doesn't stop the user from putting the
1454 ultimate trust back, but is a reasonable solution for now. */
1455 if(get_ownertrust(pk)==TRUST_ULTIMATE)
1456 clear_ownertrusts(pk);
1458 revalidation_mark ();
1462 release_kbnode( keyblock );
1463 free_public_key( pk );
1469 * Loop over the keyblock and check all self signatures.
1470 * Mark all user-ids with a self-signature by setting flag bit 0.
1471 * Mark all user-ids with an invalid self-signature by setting bit 1.
1472 * This works also for subkeys, here the subkey is marked. Invalid or
1473 * extra subkey sigs (binding or revocation) are marked for deletion.
1474 * non_self is set to true if there are any sigs other than self-sigs
1478 chk_self_sigs( const char *fname, KBNODE keyblock,
1479 PKT_public_key *pk, u32 *keyid, int *non_self )
1481 KBNODE n, knode = NULL;
1484 u32 bsdate=0,rsdate=0;
1485 KBNODE bsnode = NULL, rsnode = NULL;
1490 for (n=keyblock; (n = find_next_kbnode (n, 0)); )
1492 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1502 if ( n->pkt->pkttype != PKT_SIGNATURE )
1505 sig = n->pkt->pkt.signature;
1506 if ( keyid[0] != sig->keyid[0] || keyid[1] != sig->keyid[1] )
1512 /* This just caches the sigs for later use. That way we
1513 import a fully-cached key which speeds things up. */
1514 if (!opt.no_sig_cache)
1515 check_key_signature (keyblock, n, NULL);
1517 if ( IS_UID_SIG(sig) || IS_UID_REV(sig) )
1519 KBNODE unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
1522 log_error( _("key %s: no user ID for signature\n"),
1524 return -1; /* The complete keyblock is invalid. */
1527 /* If it hasn't been marked valid yet, keep trying. */
1528 if (!(unode->flag&1))
1530 rc = check_key_signature (keyblock, n, NULL);
1535 char *p = utf8_to_native
1536 (unode->pkt->pkt.user_id->name,
1537 strlen (unode->pkt->pkt.user_id->name),0);
1538 log_info (gpg_err_code(rc) == G10ERR_PUBKEY_ALGO ?
1539 _("key %s: unsupported public key "
1540 "algorithm on user ID \"%s\"\n"):
1541 _("key %s: invalid self-signature "
1542 "on user ID \"%s\"\n"),
1548 unode->flag |= 1; /* Mark that signature checked. */
1551 else if (IS_KEY_SIG (sig))
1553 rc = check_key_signature (keyblock, n, NULL);
1557 log_info (gpg_err_code (rc) == G10ERR_PUBKEY_ALGO ?
1558 _("key %s: unsupported public key algorithm\n"):
1559 _("key %s: invalid direct key signature\n"),
1564 else if ( IS_SUBKEY_SIG (sig) )
1566 /* Note that this works based solely on the timestamps like
1567 the rest of gpg. If the standard gets revocation
1568 targets, this may need to be revised. */
1573 log_info (_("key %s: no subkey for key binding\n"),
1575 n->flag |= 4; /* delete this */
1579 rc = check_key_signature (keyblock, n, NULL);
1583 log_info (gpg_err_code (rc) == G10ERR_PUBKEY_ALGO ?
1584 _("key %s: unsupported public key"
1586 _("key %s: invalid subkey binding\n"),
1592 /* It's valid, so is it newer? */
1593 if (sig->timestamp >= bsdate)
1595 knode->flag |= 1; /* The subkey is valid. */
1598 /* Delete the last binding sig since this
1602 log_info (_("key %s: removed multiple subkey"
1603 " binding\n"),keystr(keyid));
1607 bsdate = sig->timestamp;
1610 n->flag |= 4; /* older */
1614 else if ( IS_SUBKEY_REV (sig) )
1616 /* We don't actually mark the subkey as revoked right now,
1617 so just check that the revocation sig is the most recent
1618 valid one. Note that we don't care if the binding sig is
1619 newer than the revocation sig. See the comment in
1620 getkey.c:merge_selfsigs_subkey for more. */
1624 log_info (_("key %s: no subkey for key revocation\n"),
1626 n->flag |= 4; /* delete this */
1630 rc = check_key_signature (keyblock, n, NULL);
1634 log_info (gpg_err_code (rc) == G10ERR_PUBKEY_ALGO ?
1635 _("key %s: unsupported public"
1636 " key algorithm\n"):
1637 _("key %s: invalid subkey revocation\n"),
1643 /* It's valid, so is it newer? */
1644 if (sig->timestamp >= rsdate)
1648 /* Delete the last revocation sig since
1649 this one is newer. */
1652 log_info (_("key %s: removed multiple subkey"
1653 " revocation\n"),keystr(keyid));
1657 rsdate = sig->timestamp;
1660 n->flag |= 4; /* older */
1670 * delete all parts which are invalid and those signatures whose
1671 * public key algorithm is not available in this implemenation;
1672 * but consider RSA as valid, because parse/build_packets knows
1674 * returns: true if at least one valid user-id is left over.
1677 delete_inv_parts( const char *fname, KBNODE keyblock,
1678 u32 *keyid, unsigned int options)
1681 int nvalid=0, uid_seen=0, subkey_seen=0;
1685 for(node=keyblock->next; node; node = node->next ) {
1686 if( node->pkt->pkttype == PKT_USER_ID ) {
1688 if( (node->flag & 2) || !(node->flag & 1) ) {
1691 char *p=utf8_to_native(node->pkt->pkt.user_id->name,
1692 node->pkt->pkt.user_id->len,0);
1693 log_info( _("key %s: skipped user ID \"%s\"\n"),
1697 delete_kbnode( node ); /* the user-id */
1698 /* and all following packets up to the next user-id */
1700 && node->next->pkt->pkttype != PKT_USER_ID
1701 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1702 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
1703 delete_kbnode( node->next );
1710 else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1711 || node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1712 if( (node->flag & 2) || !(node->flag & 1) ) {
1714 log_info( _("key %s: skipped subkey\n"),keystr(keyid));
1716 delete_kbnode( node ); /* the subkey */
1717 /* and all following signature packets */
1719 && node->next->pkt->pkttype == PKT_SIGNATURE ) {
1720 delete_kbnode( node->next );
1727 else if (node->pkt->pkttype == PKT_SIGNATURE
1728 && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
1729 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
1730 delete_kbnode( node ); /* build_packet() can't handle this */
1731 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1732 !node->pkt->pkt.signature->flags.exportable &&
1733 !(options&IMPORT_LOCAL_SIGS) &&
1734 seckey_available( node->pkt->pkt.signature->keyid ) )
1736 /* here we violate the rfc a bit by still allowing
1737 * to import non-exportable signature when we have the
1738 * the secret key used to create this signature - it
1739 * seems that this makes sense */
1741 log_info( _("key %s: non exportable signature"
1742 " (class 0x%02X) - skipped\n"),
1743 keystr(keyid), node->pkt->pkt.signature->sig_class );
1744 delete_kbnode( node );
1746 else if( node->pkt->pkttype == PKT_SIGNATURE
1747 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1751 log_info( _("key %s: revocation certificate"
1752 " at wrong place - skipped\n"),keystr(keyid));
1753 delete_kbnode( node );
1756 /* If the revocation cert is from a different key than
1757 the one we're working on don't check it - it's
1758 probably from a revocation key and won't be
1759 verifiable with this key anyway. */
1761 if(node->pkt->pkt.signature->keyid[0]==keyid[0] &&
1762 node->pkt->pkt.signature->keyid[1]==keyid[1])
1764 int rc = check_key_signature( keyblock, node, NULL);
1768 log_info( _("key %s: invalid revocation"
1769 " certificate: %s - skipped\n"),
1770 keystr(keyid), g10_errstr(rc));
1771 delete_kbnode( node );
1776 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1777 (node->pkt->pkt.signature->sig_class == 0x18 ||
1778 node->pkt->pkt.signature->sig_class == 0x28) &&
1782 log_info( _("key %s: subkey signature"
1783 " in wrong place - skipped\n"), keystr(keyid));
1784 delete_kbnode( node );
1786 else if( node->pkt->pkttype == PKT_SIGNATURE
1787 && !IS_CERT(node->pkt->pkt.signature))
1790 log_info(_("key %s: unexpected signature class (0x%02X) -"
1791 " skipped\n"),keystr(keyid),
1792 node->pkt->pkt.signature->sig_class);
1793 delete_kbnode(node);
1795 else if( (node->flag & 4) ) /* marked for deletion */
1796 delete_kbnode( node );
1799 /* note: because keyblock is the public key, it is never marked
1800 * for deletion and so keyblock cannot change */
1801 commit_kbnode( &keyblock );
1807 * It may happen that the imported keyblock has duplicated user IDs.
1808 * We check this here and collapse those user IDs together with their
1810 * Returns: True if the keyblock has changed.
1813 collapse_uids( KBNODE *keyblock )
1818 for(uid1=*keyblock;uid1;uid1=uid1->next)
1822 if(is_deleted_kbnode(uid1))
1825 if(uid1->pkt->pkttype!=PKT_USER_ID)
1828 for(uid2=uid1->next;uid2;uid2=uid2->next)
1830 if(is_deleted_kbnode(uid2))
1833 if(uid2->pkt->pkttype!=PKT_USER_ID)
1836 if(cmp_user_ids(uid1->pkt->pkt.user_id,
1837 uid2->pkt->pkt.user_id)==0)
1839 /* We have a duplicated uid */
1844 /* Now take uid2's signatures, and attach them to
1846 for(last=uid2;last->next;last=last->next)
1848 if(is_deleted_kbnode(last))
1851 if(last->next->pkt->pkttype==PKT_USER_ID
1852 || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
1853 || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
1858 (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
1860 /* Now put uid2 in place as part of uid1 */
1861 last->next=uid1->next;
1863 delete_kbnode(uid2);
1865 /* Now dedupe uid1 */
1866 for(sig1=uid1->next;sig1;sig1=sig1->next)
1870 if(is_deleted_kbnode(sig1))
1873 if(sig1->pkt->pkttype==PKT_USER_ID
1874 || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
1875 || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
1878 if(sig1->pkt->pkttype!=PKT_SIGNATURE)
1881 for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
1883 if(is_deleted_kbnode(sig2))
1886 if(sig2->pkt->pkttype==PKT_USER_ID
1887 || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
1888 || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
1891 if(sig2->pkt->pkttype!=PKT_SIGNATURE)
1894 if(cmp_signatures(sig1->pkt->pkt.signature,
1895 sig2->pkt->pkt.signature)==0)
1897 /* We have a match, so delete the second
1899 delete_kbnode(sig2);
1908 commit_kbnode(keyblock);
1910 if(any && !opt.quiet)
1912 const char *key="???";
1914 if( (uid1=find_kbnode( *keyblock, PKT_PUBLIC_KEY )) )
1915 key=keystr_from_pk(uid1->pkt->pkt.public_key);
1916 else if( (uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY )) )
1917 key=keystr_from_sk(uid1->pkt->pkt.secret_key);
1919 log_info(_("key %s: duplicated user ID detected - merged\n"),key);
1925 /* Check for a 0x20 revocation from a revocation key that is not
1926 present. This may be called without the benefit of merge_xxxx so
1927 you can't rely on pk->revkey and friends. */
1929 revocation_present(KBNODE keyblock)
1932 PKT_public_key *pk=keyblock->pkt->pkt.public_key;
1934 for(onode=keyblock->next;onode;onode=onode->next)
1936 /* If we reach user IDs, we're done. */
1937 if(onode->pkt->pkttype==PKT_USER_ID)
1940 if(onode->pkt->pkttype==PKT_SIGNATURE &&
1941 onode->pkt->pkt.signature->sig_class==0x1F &&
1942 onode->pkt->pkt.signature->revkey)
1945 PKT_signature *sig=onode->pkt->pkt.signature;
1947 for(idx=0;idx<sig->numrevkeys;idx++)
1951 keyid_from_fingerprint(sig->revkey[idx]->fpr,
1952 MAX_FINGERPRINT_LEN,keyid);
1954 for(inode=keyblock->next;inode;inode=inode->next)
1956 /* If we reach user IDs, we're done. */
1957 if(inode->pkt->pkttype==PKT_USER_ID)
1960 if(inode->pkt->pkttype==PKT_SIGNATURE &&
1961 inode->pkt->pkt.signature->sig_class==0x20 &&
1962 inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
1963 inode->pkt->pkt.signature->keyid[1]==keyid[1])
1965 /* Okay, we have a revocation key, and a
1966 revocation issued by it. Do we have the key
1970 rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx]->fpr,
1971 MAX_FINGERPRINT_LEN);
1972 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1974 char *tempkeystr=xstrdup(keystr_from_pk(pk));
1976 /* No, so try and get it */
1978 && (opt.keyserver_options.options
1979 & KEYSERVER_AUTO_KEY_RETRIEVE))
1981 log_info(_("WARNING: key %s may be revoked:"
1982 " fetching revocation key %s\n"),
1983 tempkeystr,keystr(keyid));
1984 keyserver_import_fprint(sig->revkey[idx]->fpr,
1985 MAX_FINGERPRINT_LEN,
1988 /* Do we have it now? */
1989 rc=get_pubkey_byfprint_fast (NULL,
1990 sig->revkey[idx]->fpr,
1991 MAX_FINGERPRINT_LEN);
1994 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1995 log_info(_("WARNING: key %s may be revoked:"
1996 " revocation key %s not present.\n"),
1997 tempkeystr,keystr(keyid));
2009 * compare and merge the blocks
2011 * o compare the signatures: If we already have this signature, check
2012 * that they compare okay; if not, issue a warning and ask the user.
2013 * o Simply add the signature. Can't verify here because we may not have
2014 * the signature's public key yet; verification is done when putting it
2015 * into the trustdb, which is done automagically as soon as this pubkey
2017 * Note: We indicate newly inserted packets with flag bit 0
2020 merge_blocks( const char *fname, KBNODE keyblock_orig, KBNODE keyblock,
2021 u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
2026 /* 1st: handle revocation certificates */
2027 for(node=keyblock->next; node; node=node->next ) {
2028 if( node->pkt->pkttype == PKT_USER_ID )
2030 else if( node->pkt->pkttype == PKT_SIGNATURE
2031 && node->pkt->pkt.signature->sig_class == 0x20 ) {
2032 /* check whether we already have this */
2034 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
2035 if( onode->pkt->pkttype == PKT_USER_ID )
2037 else if( onode->pkt->pkttype == PKT_SIGNATURE
2038 && onode->pkt->pkt.signature->sig_class == 0x20
2039 && !cmp_signatures(onode->pkt->pkt.signature,
2040 node->pkt->pkt.signature))
2047 KBNODE n2 = clone_kbnode(node);
2048 insert_kbnode( keyblock_orig, n2, 0 );
2053 char *p=get_user_id_native (keyid);
2054 log_info(_("key %s: \"%s\" revocation"
2055 " certificate added\n"), keystr(keyid),p);
2062 /* 2nd: merge in any direct key (0x1F) sigs */
2063 for(node=keyblock->next; node; node=node->next ) {
2064 if( node->pkt->pkttype == PKT_USER_ID )
2066 else if( node->pkt->pkttype == PKT_SIGNATURE
2067 && node->pkt->pkt.signature->sig_class == 0x1F ) {
2068 /* check whether we already have this */
2070 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
2071 if( onode->pkt->pkttype == PKT_USER_ID )
2073 else if( onode->pkt->pkttype == PKT_SIGNATURE
2074 && onode->pkt->pkt.signature->sig_class == 0x1F
2075 && !cmp_signatures(onode->pkt->pkt.signature,
2076 node->pkt->pkt.signature)) {
2083 KBNODE n2 = clone_kbnode(node);
2084 insert_kbnode( keyblock_orig, n2, 0 );
2088 log_info( _("key %s: direct key signature added\n"),
2094 /* 3rd: try to merge new certificates in */
2095 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
2096 if( !(onode->flag & 1) && onode->pkt->pkttype == PKT_USER_ID) {
2097 /* find the user id in the imported keyblock */
2098 for(node=keyblock->next; node; node=node->next )
2099 if( node->pkt->pkttype == PKT_USER_ID
2100 && !cmp_user_ids( onode->pkt->pkt.user_id,
2101 node->pkt->pkt.user_id ) )
2103 if( node ) { /* found: merge */
2104 rc = merge_sigs( onode, node, n_sigs, fname, keyid );
2111 /* 4th: add new user-ids */
2112 for(node=keyblock->next; node; node=node->next ) {
2113 if( node->pkt->pkttype == PKT_USER_ID) {
2114 /* do we have this in the original keyblock */
2115 for(onode=keyblock_orig->next; onode; onode=onode->next )
2116 if( onode->pkt->pkttype == PKT_USER_ID
2117 && !cmp_user_ids( onode->pkt->pkt.user_id,
2118 node->pkt->pkt.user_id ) )
2120 if( !onode ) { /* this is a new user id: append */
2121 rc = append_uid( keyblock_orig, node, n_sigs, fname, keyid);
2129 /* 5th: add new subkeys */
2130 for(node=keyblock->next; node; node=node->next ) {
2132 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2133 /* do we have this in the original keyblock? */
2134 for(onode=keyblock_orig->next; onode; onode=onode->next )
2135 if( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
2136 && !cmp_public_keys( onode->pkt->pkt.public_key,
2137 node->pkt->pkt.public_key ) )
2139 if( !onode ) { /* this is a new subkey: append */
2140 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
2146 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2147 /* do we have this in the original keyblock? */
2148 for(onode=keyblock_orig->next; onode; onode=onode->next )
2149 if( onode->pkt->pkttype == PKT_SECRET_SUBKEY
2150 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
2151 node->pkt->pkt.secret_key ) )
2153 if( !onode ) { /* this is a new subkey: append */
2154 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
2162 /* 6th: merge subkey certificates */
2163 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
2164 if( !(onode->flag & 1)
2165 && ( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
2166 || onode->pkt->pkttype == PKT_SECRET_SUBKEY) ) {
2167 /* find the subkey in the imported keyblock */
2168 for(node=keyblock->next; node; node=node->next ) {
2169 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2170 && !cmp_public_keys( onode->pkt->pkt.public_key,
2171 node->pkt->pkt.public_key ) )
2173 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY
2174 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
2175 node->pkt->pkt.secret_key ) )
2178 if( node ) { /* found: merge */
2179 rc = merge_keysigs( onode, node, n_sigs, fname, keyid );
2192 * append the userid starting with NODE and all signatures to KEYBLOCK.
2195 append_uid (KBNODE keyblock, KBNODE node, int *n_sigs,
2196 const char *fname, u32 *keyid )
2198 KBNODE n, n_where=NULL;
2203 assert(node->pkt->pkttype == PKT_USER_ID );
2205 /* find the position */
2206 for( n = keyblock; n; n_where = n, n = n->next ) {
2207 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2208 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
2214 /* and append/insert */
2216 /* we add a clone to the original keyblock, because this
2217 * one is released first */
2218 n = clone_kbnode(node);
2220 insert_kbnode( n_where, n, 0 );
2224 add_kbnode( keyblock, n );
2227 if( n->pkt->pkttype == PKT_SIGNATURE )
2231 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2240 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
2241 * (how should we handle comment packets here?)
2244 merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
2245 const char *fname, u32 *keyid )
2253 assert(dst->pkt->pkttype == PKT_USER_ID );
2254 assert(src->pkt->pkttype == PKT_USER_ID );
2256 for(n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next ) {
2257 if( n->pkt->pkttype != PKT_SIGNATURE )
2259 if( n->pkt->pkt.signature->sig_class == 0x18
2260 || n->pkt->pkt.signature->sig_class == 0x28 )
2261 continue; /* skip signatures which are only valid on subkeys */
2263 for(n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
2264 if(!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
2270 /* This signature is new or newer, append N to DST.
2271 * We add a clone to the original keyblock, because this
2272 * one is released first */
2273 n2 = clone_kbnode(n);
2274 insert_kbnode( dst, n2, PKT_SIGNATURE );
2285 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
2288 merge_keysigs (KBNODE dst, KBNODE src, int *n_sigs,
2289 const char *fname, u32 *keyid)
2297 assert( dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
2298 || dst->pkt->pkttype == PKT_SECRET_SUBKEY );
2300 for(n=src->next; n ; n = n->next ) {
2301 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2302 || n->pkt->pkttype == PKT_PUBLIC_KEY )
2304 if( n->pkt->pkttype != PKT_SIGNATURE )
2307 for(n2=dst->next; n2; n2 = n2->next){
2308 if( n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
2309 || n2->pkt->pkttype == PKT_PUBLIC_KEY )
2311 if( n2->pkt->pkttype == PKT_SIGNATURE
2312 && n->pkt->pkt.signature->keyid[0]
2313 == n2->pkt->pkt.signature->keyid[0]
2314 && n->pkt->pkt.signature->keyid[1]
2315 == n2->pkt->pkt.signature->keyid[1]
2316 && n->pkt->pkt.signature->timestamp
2317 <= n2->pkt->pkt.signature->timestamp
2318 && n->pkt->pkt.signature->sig_class
2319 == n2->pkt->pkt.signature->sig_class ) {
2325 /* This signature is new or newer, append N to DST.
2326 * We add a clone to the original keyblock, because this
2327 * one is released first */
2328 n2 = clone_kbnode(n);
2329 insert_kbnode( dst, n2, PKT_SIGNATURE );
2340 * append the subkey starting with NODE and all signatures to KEYBLOCK.
2341 * Mark all new and copied packets by setting flag bit 0.
2344 append_key (KBNODE keyblock, KBNODE node, int *n_sigs,
2345 const char *fname, u32 *keyid)
2352 assert( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2353 || node->pkt->pkttype == PKT_SECRET_SUBKEY );
2356 /* we add a clone to the original keyblock, because this
2357 * one is released first */
2358 n = clone_kbnode(node);
2359 add_kbnode( keyblock, n );
2362 if( n->pkt->pkttype == PKT_SIGNATURE )
2366 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2375 /* Walk a public keyblock and produce a secret keyblock out of it.
2376 Instead of inserting the secret key parameters (which we don't
2377 have), we insert a stub. */
2379 pub_to_sec_keyblock (KBNODE pub_keyblock)
2381 KBNODE pubnode, secnode;
2382 KBNODE sec_keyblock = NULL;
2383 KBNODE walkctx = NULL;
2385 while((pubnode = walk_kbnode (pub_keyblock,&walkctx,0)))
2387 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY
2388 || pubnode->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2390 /* Make a secret key. We only need to convert enough to
2391 write the keyblock out. */
2392 PKT_public_key *pk = pubnode->pkt->pkt.public_key;
2393 PACKET *pkt = xmalloc_clear (sizeof *pkt);
2394 PKT_secret_key *sk = xmalloc_clear (sizeof *sk);
2397 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY)
2398 pkt->pkttype = PKT_SECRET_KEY;
2400 pkt->pkttype = PKT_SECRET_SUBKEY;
2402 pkt->pkt.secret_key = sk;
2404 copy_public_parts_to_secret_key ( pk, sk );
2405 sk->version = pk->version;
2406 sk->timestamp = pk->timestamp;
2408 n = pubkey_get_npkey (pk->pubkey_algo);
2410 n = 1; /* Unknown number of parameters, however the data
2411 is stored in the first mpi. */
2412 for (i=0; i < n; i++ )
2413 sk->skey[i] = mpi_copy (pk->pkey[i]);
2415 sk->is_protected = 1;
2416 sk->protect.s2k.mode = 1001;
2418 secnode = new_kbnode (pkt);
2422 secnode = clone_kbnode (pubnode);
2426 sec_keyblock = secnode;
2428 add_kbnode (sec_keyblock, secnode);
2431 return sec_keyblock;
2435 /* Walk over the secret keyring SEC_KEYBLOCK and update any simple
2436 stub keys with the serial number SNNUM of the card if one of the
2437 fingerprints FPR1, FPR2 or FPR3 match. Print a note if the key is
2438 a duplicate (may happen in case of backed uped keys).
2440 Returns: True if anything changed.
2443 update_sec_keyblock_with_cardinfo (KBNODE sec_keyblock,
2444 const unsigned char *fpr1,
2445 const unsigned char *fpr2,
2446 const unsigned char *fpr3,
2447 const char *serialnostr)
2450 KBNODE walkctx = NULL;
2452 byte array[MAX_FINGERPRINT_LEN];
2457 while((node = walk_kbnode (sec_keyblock, &walkctx, 0)))
2459 if (node->pkt->pkttype != PKT_SECRET_KEY
2460 && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2462 sk = node->pkt->pkt.secret_key;
2464 fingerprint_from_sk (sk, array, &n);
2466 continue; /* Can't be a card key. */
2467 if ( !((fpr1 && !memcmp (array, fpr1, 20))
2468 || (fpr2 && !memcmp (array, fpr2, 20))
2469 || (fpr3 && !memcmp (array, fpr3, 20))) )
2470 continue; /* No match. */
2472 if (sk->is_protected == 1 && sk->protect.s2k.mode == 1001)
2474 /* Standard case: migrate that stub to a key stub. */
2475 sk->protect.s2k.mode = 1002;
2477 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2478 sk->protect.ivlen++, s += 2)
2479 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
2482 else if (sk->is_protected == 1 && sk->protect.s2k.mode == 1002)
2485 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2486 sk->protect.ivlen++, s += 2)
2487 if (sk->protect.iv[sk->protect.ivlen] != xtoi_2 (s))
2489 log_info (_("NOTE: a key's S/N does not "
2490 "match the card's one\n"));
2496 if (node->pkt->pkttype != PKT_SECRET_KEY)
2497 log_info (_("NOTE: primary key is online and stored on card\n"));
2499 log_info (_("NOTE: secondary key is online and stored on card\n"));
2508 /* Check whether a secret key stub exists for the public key PK. If
2509 not create such a stub key and store it into the secring. If it
2510 exists, add appropriate subkey stubs and update the secring.
2511 Return 0 if the key could be created. */
2513 auto_create_card_key_stub ( const char *serialnostr,
2514 const unsigned char *fpr1,
2515 const unsigned char *fpr2,
2516 const unsigned char *fpr3)
2518 KBNODE pub_keyblock;
2519 KBNODE sec_keyblock;
2523 /* We only want to do this for an OpenPGP card. */
2524 if (!serialnostr || strncmp (serialnostr, "D27600012401", 12)
2525 || strlen (serialnostr) != 32 )
2526 return G10ERR_GENERAL;
2528 /* First get the public keyring from any of the provided fingerprints. */
2529 if ( (fpr1 && !get_keyblock_byfprint (&pub_keyblock, fpr1, 20))
2530 || (fpr2 && !get_keyblock_byfprint (&pub_keyblock, fpr2, 20))
2531 || (fpr3 && !get_keyblock_byfprint (&pub_keyblock, fpr3, 20)))
2534 return G10ERR_GENERAL;
2538 /* Now check whether there is a secret keyring. */
2540 PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key;
2541 byte afp[MAX_FINGERPRINT_LEN];
2544 fingerprint_from_pk (pk, afp, &an);
2545 if (an < MAX_FINGERPRINT_LEN)
2546 memset (afp+an, 0, MAX_FINGERPRINT_LEN-an);
2547 rc = keydb_search_fpr (hd, afp);
2552 rc = keydb_get_keyblock (hd, &sec_keyblock);
2555 log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
2556 rc = G10ERR_GENERAL;
2560 merge_keys_and_selfsig (sec_keyblock);
2562 /* FIXME: We need to add new subkeys first. */
2563 if (update_sec_keyblock_with_cardinfo (sec_keyblock,
2567 rc = keydb_update_keyblock (hd, sec_keyblock );
2569 log_error (_("error writing keyring `%s': %s\n"),
2570 keydb_get_resource_name (hd), g10_errstr(rc) );
2574 else /* A secret key does not exists - create it. */
2576 sec_keyblock = pub_to_sec_keyblock (pub_keyblock);
2577 update_sec_keyblock_with_cardinfo (sec_keyblock,
2581 rc = keydb_locate_writable (hd, NULL);
2584 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
2585 rc = G10ERR_GENERAL;
2589 rc = keydb_insert_keyblock (hd, sec_keyblock );
2591 log_error (_("error writing keyring `%s': %s\n"),
2592 keydb_get_resource_name (hd), g10_errstr(rc) );
2596 release_kbnode (sec_keyblock);
2597 release_kbnode (pub_keyblock);