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 static int read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root );
64 static void revocation_present(KBNODE keyblock);
65 static int import_one(const char *fname, KBNODE keyblock,struct stats_s *stats,
66 unsigned char **fpr,size_t *fpr_len,
67 unsigned int options,int from_sk);
68 static int import_secret_one( const char *fname, KBNODE keyblock,
69 struct stats_s *stats, unsigned int options);
70 static int import_revoke_cert( const char *fname, KBNODE node,
71 struct stats_s *stats);
72 static int chk_self_sigs( const char *fname, KBNODE keyblock,
73 PKT_public_key *pk, u32 *keyid, int *non_self );
74 static int delete_inv_parts( const char *fname, KBNODE keyblock,
75 u32 *keyid, unsigned int options );
76 static int merge_blocks( const char *fname, KBNODE keyblock_orig,
77 KBNODE keyblock, u32 *keyid,
78 int *n_uids, int *n_sigs, int *n_subk );
79 static int append_uid( KBNODE keyblock, KBNODE node, int *n_sigs,
80 const char *fname, u32 *keyid );
81 static int append_key( KBNODE keyblock, KBNODE node, int *n_sigs,
82 const char *fname, u32 *keyid );
83 static int merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
84 const char *fname, u32 *keyid );
85 static int merge_keysigs( KBNODE dst, KBNODE src, int *n_sigs,
86 const char *fname, u32 *keyid );
89 parse_import_options(char *str,unsigned int *options,int noisy)
91 struct parse_options import_opts[]=
93 {"import-local-sigs",IMPORT_LOCAL_SIGS,NULL,
94 N_("import signatures that are marked as local-only")},
95 {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,
96 N_("repair damage from the pks keyserver during import")},
97 {"fast-import",IMPORT_FAST,NULL,
98 N_("do not update the trustdb after import")},
99 {"convert-sk-to-pk",IMPORT_SK2PK,NULL,
100 N_("create a public key when importing a secret key")},
101 {"merge-only",IMPORT_MERGE_ONLY,NULL,
102 N_("only accept updates to existing keys")},
103 {"import-clean",IMPORT_CLEAN,NULL,
104 N_("remove unusable parts from key after import")},
105 {"import-minimal",IMPORT_MINIMAL|IMPORT_CLEAN,NULL,
106 N_("remove as much as possible from key after import")},
107 /* Aliases for backward compatibility */
108 {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL},
109 {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL},
111 {"import-unusable-sigs",0,NULL,NULL},
112 {"import-clean-sigs",0,NULL,NULL},
113 {"import-clean-uids",0,NULL,NULL},
117 return parse_options(str,options,import_opts,noisy);
121 import_new_stats_handle (void)
123 return xmalloc_clear ( sizeof (struct stats_s) );
127 import_release_stats_handle (void *p)
133 * Import the public keys from the given filename. Input may be armored.
134 * This function rejects all keys which are not validly self signed on at
135 * least one userid. Only user ids which are self signed will be imported.
136 * Other signatures are not checked.
138 * Actually this function does a merge. It works like this:
141 * - check self-signatures and remove all userids and their signatures
142 * without/invalid self-signatures.
143 * - reject the keyblock, if we have no valid userid.
144 * - See whether we have this key already in one of our pubrings.
145 * If not, simply add it to the default keyring.
146 * - Compare the key and the self-signatures of the new and the one in
147 * our keyring. If they are different something weird is going on;
149 * - See whether we have only non-self-signature on one user id; if not
150 * ask the user what to do.
151 * - compare the signatures: If we already have this signature, check
152 * that they compare okay; if not, issue a warning and ask the user.
153 * (consider looking at the timestamp and use the newest?)
154 * - Simply add the signature. Can't verify here because we may not have
155 * the signature's public key yet; verification is done when putting it
156 * into the trustdb, which is done automagically as soon as this pubkey
158 * - Proceed with next signature.
160 * Key revocation certificates have special handling.
164 import_keys_internal( IOBUF inp, char **fnames, int nnames,
165 void *stats_handle, unsigned char **fpr, size_t *fpr_len,
166 unsigned int options )
169 struct stats_s *stats = stats_handle;
172 stats = import_new_stats_handle ();
175 rc = import( inp, "[stream]", stats, fpr, fpr_len, options);
178 int once = (!fnames && !nnames);
180 for(i=0; once || i < nnames; once=0, i++ ) {
181 const char *fname = fnames? fnames[i] : NULL;
182 IOBUF inp2 = iobuf_open(fname);
185 if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
192 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
195 rc = import( inp2, fname, stats, fpr, fpr_len, options );
197 /* Must invalidate that ugly cache to actually close it. */
198 iobuf_ioctl (NULL, 2, 0, (char*)fname);
200 log_error("import from `%s' failed: %s\n", fname,
206 import_print_stats (stats);
207 import_release_stats_handle (stats);
210 /* If no fast import and the trustdb is dirty (i.e. we added a key
211 or userID that had something other than a selfsig, a signature
212 that was other than a selfsig, or any revocation), then
213 update/check the trustdb if the user specified by setting
214 interactive or by not setting no-auto-check-trustdb */
216 if(!(options&IMPORT_FAST))
217 trustdb_check_or_update();
223 import_keys( char **fnames, int nnames,
224 void *stats_handle, unsigned int options )
226 import_keys_internal(NULL,fnames,nnames,stats_handle,NULL,NULL,options);
230 import_keys_stream( IOBUF inp, void *stats_handle,
231 unsigned char **fpr, size_t *fpr_len,unsigned int options )
233 return import_keys_internal(inp,NULL,0,stats_handle,fpr,fpr_len,options);
237 import( IOBUF inp, const char* fname,struct stats_s *stats,
238 unsigned char **fpr,size_t *fpr_len,unsigned int options )
240 PACKET *pending_pkt = NULL;
241 KBNODE keyblock = NULL; /* Need to initialize because gcc can't
242 grasp the return semantics of
246 getkey_disable_caches();
248 if( !opt.no_armor ) { /* armored reading is not disabled */
249 armor_filter_context_t *afx;
251 afx = new_armor_context ();
252 afx->only_keyblocks = 1;
253 push_armor_filter (afx, inp);
254 release_armor_context (afx);
257 while( !(rc = read_block( inp, &pending_pkt, &keyblock) )) {
258 if( keyblock->pkt->pkttype == PKT_PUBLIC_KEY )
259 rc = import_one( fname, keyblock, stats, fpr, fpr_len, options, 0);
260 else if( keyblock->pkt->pkttype == PKT_SECRET_KEY )
261 rc = import_secret_one( fname, keyblock, stats, options );
262 else if( keyblock->pkt->pkttype == PKT_SIGNATURE
263 && keyblock->pkt->pkt.signature->sig_class == 0x20 )
264 rc = import_revoke_cert( fname, keyblock, stats );
266 log_info( _("skipping block of type %d\n"),
267 keyblock->pkt->pkttype );
269 release_kbnode(keyblock);
270 /* fixme: we should increment the not imported counter but this
271 does only make sense if we keep on going despite of errors. */
274 if( !(++stats->count % 100) && !opt.quiet )
275 log_info(_("%lu keys processed so far\n"), stats->count );
279 else if( rc && rc != G10ERR_INV_KEYRING )
280 log_error( _("error reading `%s': %s\n"), fname, g10_errstr(rc));
287 import_print_stats (void *hd)
289 struct stats_s *stats = hd;
292 log_info(_("Total number processed: %lu\n"), stats->count );
293 if( stats->skipped_new_keys )
294 log_info(_(" skipped new keys: %lu\n"),
295 stats->skipped_new_keys );
296 if( stats->no_user_id )
297 log_info(_(" w/o user IDs: %lu\n"), stats->no_user_id );
298 if( stats->imported || stats->imported_rsa ) {
299 log_info(_(" imported: %lu"), stats->imported );
300 if (stats->imported_rsa)
301 log_printf (" (RSA: %lu)", stats->imported_rsa );
304 if( stats->unchanged )
305 log_info(_(" unchanged: %lu\n"), stats->unchanged );
307 log_info(_(" new user IDs: %lu\n"), stats->n_uids );
309 log_info(_(" new subkeys: %lu\n"), stats->n_subk );
311 log_info(_(" new signatures: %lu\n"), stats->n_sigs );
313 log_info(_(" new key revocations: %lu\n"), stats->n_revoc );
314 if( stats->secret_read )
315 log_info(_(" secret keys read: %lu\n"), stats->secret_read );
316 if( stats->secret_imported )
317 log_info(_(" secret keys imported: %lu\n"), stats->secret_imported );
318 if( stats->secret_dups )
319 log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
320 if( stats->not_imported )
321 log_info(_(" not imported: %lu\n"), stats->not_imported );
322 if( stats->n_sigs_cleaned)
323 log_info(_(" signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
324 if( stats->n_uids_cleaned)
325 log_info(_(" user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
328 if( is_status_enabled() ) {
330 sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
341 stats->secret_imported,
343 stats->skipped_new_keys,
344 stats->not_imported );
345 write_status_text( STATUS_IMPORT_RES, buf );
351 * Read the next keyblock from stream A.
352 * PENDING_PKT should be initialzed to NULL
353 * and not chnaged form the caller.
354 * Retunr: 0 = okay, -1 no more blocks or another errorcode.
357 read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root )
365 root = new_kbnode( *pending_pkt );
371 pkt = xmalloc( sizeof *pkt );
373 while( (rc=parse_packet(a, pkt)) != -1 ) {
374 if( rc ) { /* ignore errors */
375 if( rc != G10ERR_UNKNOWN_PACKET ) {
376 log_error("read_block: read error: %s\n", g10_errstr(rc) );
377 rc = G10ERR_INV_KEYRING;
385 if( !root && pkt->pkttype == PKT_SIGNATURE
386 && pkt->pkt.signature->sig_class == 0x20 ) {
387 /* this is a revocation certificate which is handled
388 * in a special way */
389 root = new_kbnode( pkt );
394 /* make a linked list of all packets */
395 switch( pkt->pkttype ) {
397 if(check_compress_algo(pkt->pkt.compressed->algorithm))
399 rc = G10ERR_COMPR_ALGO;
404 compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
405 pkt->pkt.compressed->buf = NULL;
406 push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1);
413 /* skip those packets */
420 if( in_cert ) { /* store this packet */
429 root = new_kbnode( pkt );
431 add_kbnode( root, new_kbnode( pkt ) );
432 pkt = xmalloc( sizeof *pkt );
439 if( rc == -1 && root )
443 release_kbnode( root );
451 /* Walk through the subkeys on a pk to find if we have the PKS
452 disease: multiple subkeys with their binding sigs stripped, and the
453 sig for the first subkey placed after the last subkey. That is,
454 instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
455 "pk uid sig sub1 sub2 sub3 bind1". We can't do anything about sub2
456 and sub3, as they are already lost, but we can try and rescue sub1
457 by reordering the keyblock so that it reads "pk uid sig sub1 bind1
458 sub2 sub3". Returns TRUE if the keyblock was modified. */
461 fix_pks_corruption(KBNODE keyblock)
463 int changed=0,keycount=0;
464 KBNODE node,last=NULL,sknode=NULL;
466 /* First determine if we have the problem at all. Look for 2 or
467 more subkeys in a row, followed by a single binding sig. */
468 for(node=keyblock;node;last=node,node=node->next)
470 if(node->pkt->pkttype==PKT_PUBLIC_SUBKEY)
476 else if(node->pkt->pkttype==PKT_SIGNATURE &&
477 node->pkt->pkt.signature->sig_class==0x18 &&
478 keycount>=2 && node->next==NULL)
480 /* We might have the problem, as this key has two subkeys in
481 a row without any intervening packets. */
487 /* Temporarily attach node to sknode. */
488 node->next=sknode->next;
492 /* Note we aren't checking whether this binding sig is a
493 selfsig. This is not necessary here as the subkey and
494 binding sig will be rejected later if that is the
496 if(check_key_signature(keyblock,node,NULL))
498 /* Not a match, so undo the changes. */
499 sknode->next=node->next;
506 sknode->flag |= 1; /* Mark it good so we don't need to
520 /* Versions of GnuPG before 1.4.11 and 2.0.16 allowed to import bogus
521 direct key signatures. A side effect of this was that a later
522 import of the same good direct key signatures was not possible
523 because the cmp_signature check in merge_blocks considered them
524 equal. Although direct key signatures are now checked during
525 import, there might still be bogus signatures sitting in a keyring.
526 We need to detect and delete them before doing a merge. This
527 fucntion returns the number of removed sigs. */
529 fix_bad_direct_key_sigs (KBNODE keyblock, u32 *keyid)
535 for (node = keyblock->next; node; node=node->next)
537 if (node->pkt->pkttype == PKT_USER_ID)
539 if (node->pkt->pkttype == PKT_SIGNATURE
540 && IS_KEY_SIG (node->pkt->pkt.signature))
542 err = check_key_signature (keyblock, node, NULL);
543 if (err && gpg_err_code (err) != GPG_ERR_PUBKEY_ALGO )
545 /* If we don't know the error, we can't decide; this is
546 not a problem because cmp_signature can't compare the
548 log_info ("key %s: invalid direct key signature removed\n",
550 delete_kbnode (node);
561 print_import_ok (PKT_public_key *pk, PKT_secret_key *sk, unsigned int reason)
563 byte array[MAX_FINGERPRINT_LEN], *s;
564 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
567 sprintf (buf, "%u ", reason);
568 p = buf + strlen (buf);
571 fingerprint_from_pk (pk, array, &n);
573 fingerprint_from_sk (sk, array, &n);
575 for (i=0; i < n ; i++, s++, p += 2)
576 sprintf (p, "%02X", *s);
578 write_status_text (STATUS_IMPORT_OK, buf);
582 print_import_check (PKT_public_key * pk, PKT_user_id * id)
587 size_t i, pos = 0, n;
589 buf = xmalloc (17+41+id->len+32);
590 keyid_from_pk (pk, keyid);
591 sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
593 fingerprint_from_pk (pk, fpr, &n);
594 for (i = 0; i < n; i++, pos += 2)
595 sprintf (buf+pos, "%02X", fpr[i]);
598 strcat (buf, id->name);
599 write_status_text (STATUS_IMPORT_CHECK, buf);
604 check_prefs_warning(PKT_public_key *pk)
606 log_info(_("WARNING: key %s contains preferences for unavailable\n"
607 "algorithms on these user IDs:\n"), keystr_from_pk(pk));
611 check_prefs(KBNODE keyblock)
617 merge_keys_and_selfsig(keyblock);
618 pk=keyblock->pkt->pkt.public_key;
620 for(node=keyblock;node;node=node->next)
622 if(node->pkt->pkttype==PKT_USER_ID
623 && node->pkt->pkt.user_id->created
624 && node->pkt->pkt.user_id->prefs)
626 PKT_user_id *uid=node->pkt->pkt.user_id;
627 prefitem_t *prefs=uid->prefs;
628 char *user=utf8_to_native(uid->name,strlen(uid->name),0);
630 for(;prefs->type;prefs++)
632 char num[10]; /* prefs->value is a byte, so we're over
635 sprintf(num,"%u",prefs->value);
637 if(prefs->type==PREFTYPE_SYM)
639 if (openpgp_cipher_test_algo (prefs->value))
642 (openpgp_cipher_test_algo (prefs->value)
644 : openpgp_cipher_algo_name (prefs->value));
646 check_prefs_warning(pk);
647 log_info(_(" \"%s\": preference for cipher"
648 " algorithm %s\n"), user, algo);
652 else if(prefs->type==PREFTYPE_HASH)
654 if(openpgp_md_test_algo(prefs->value))
657 (gcry_md_test_algo (prefs->value)
659 : gcry_md_algo_name (prefs->value));
661 check_prefs_warning(pk);
662 log_info(_(" \"%s\": preference for digest"
663 " algorithm %s\n"), user, algo);
667 else if(prefs->type==PREFTYPE_ZIP)
669 if(check_compress_algo (prefs->value))
671 const char *algo=compress_algo_to_string(prefs->value);
673 check_prefs_warning(pk);
674 log_info(_(" \"%s\": preference for compression"
675 " algorithm %s\n"),user,algo?algo:num);
687 log_info(_("it is strongly suggested that you update"
688 " your preferences and\n"));
689 log_info(_("re-distribute this key to avoid potential algorithm"
690 " mismatch problems\n"));
694 strlist_t sl=NULL,locusr=NULL;
696 byte fpr[MAX_FINGERPRINT_LEN],*p;
697 char username[(MAX_FINGERPRINT_LEN*2)+1];
700 p=fingerprint_from_pk(pk,fpr,&fprlen);
701 for(i=0;i<fprlen;i++,p++)
702 sprintf(username+2*i,"%02X",*p);
703 add_to_strlist(&locusr,username);
705 append_to_strlist(&sl,"updpref");
706 append_to_strlist(&sl,"save");
708 keyedit_menu( username, locusr, sl, 1, 1 );
710 free_strlist(locusr);
713 log_info(_("you can update your preferences with:"
714 " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
719 * Try to import one keyblock. Return an error only in serious cases, but
720 * never for an invalid keyblock. It uses log_error to increase the
721 * internal errorcount, so that invalid input can be detected by programs
725 import_one( const char *fname, KBNODE keyblock, struct stats_s *stats,
726 unsigned char **fpr,size_t *fpr_len,unsigned int options,
730 PKT_public_key *pk_orig;
731 KBNODE node, uidnode;
732 KBNODE keyblock_orig = NULL;
740 /* get the key and print some info about it */
741 node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
745 pk = node->pkt->pkt.public_key;
747 keyid_from_pk( pk, keyid );
748 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
750 if( opt.verbose && !opt.interactive )
752 log_info( "pub %4u%c/%s %s ",
754 pubkey_letter( pk->pubkey_algo ),
755 keystr_from_pk(pk), datestr_from_pk(pk) );
757 print_utf8_string (log_get_stream (),
758 uidnode->pkt->pkt.user_id->name,
759 uidnode->pkt->pkt.user_id->len );
766 log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
770 if (opt.interactive) {
771 if(is_status_enabled())
772 print_import_check (pk, uidnode->pkt->pkt.user_id);
773 merge_keys_and_selfsig (keyblock);
775 show_basic_key_info (keyblock);
777 if (!cpr_get_answer_is_yes ("import.okay",
778 "Do you want to import this key? (y/N) "))
782 collapse_uids(&keyblock);
784 /* Clean the key that we're about to import, to cut down on things
785 that we have to clean later. This has no practical impact on
786 the end result, but does result in less logging which might
788 if(options&IMPORT_CLEAN)
789 clean_key(keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL);
791 clear_kbnode_flags( keyblock );
793 if((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
795 log_info(_("key %s: PKS subkey corruption repaired\n"),
798 rc = chk_self_sigs( fname, keyblock , pk, keyid, &non_self );
800 return rc== -1? 0:rc;
802 /* If we allow such a thing, mark unsigned uids as valid */
803 if( opt.allow_non_selfsigned_uid )
804 for( node=keyblock; node; node = node->next )
805 if( node->pkt->pkttype == PKT_USER_ID && !(node->flag & 1) )
807 char *user=utf8_to_native(node->pkt->pkt.user_id->name,
808 node->pkt->pkt.user_id->len,0);
810 log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
811 keystr_from_pk(pk),user);
815 if( !delete_inv_parts( fname, keyblock, keyid, options ) ) {
816 log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
818 log_info(_("this may be caused by a missing self-signature\n"));
823 /* do we have this key already in one of our pubrings ? */
824 pk_orig = xmalloc_clear( sizeof *pk_orig );
825 rc = get_pubkey_fast ( pk_orig, keyid );
826 if( rc && rc != G10ERR_NO_PUBKEY && rc != G10ERR_UNU_PUBKEY )
828 log_error( _("key %s: public key not found: %s\n"),
829 keystr(keyid), g10_errstr(rc));
831 else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) )
834 log_info( _("key %s: new key - skipped\n"), keystr(keyid));
836 stats->skipped_new_keys++;
838 else if( rc ) { /* insert this key */
839 KEYDB_HANDLE hd = keydb_new (0);
841 rc = keydb_locate_writable (hd, NULL);
843 log_error (_("no writable keyring found: %s\n"), g10_errstr (rc));
845 return G10ERR_GENERAL;
847 if( opt.verbose > 1 )
848 log_info (_("writing to `%s'\n"), keydb_get_resource_name (hd) );
850 rc = keydb_insert_keyblock (hd, keyblock );
852 log_error (_("error writing keyring `%s': %s\n"),
853 keydb_get_resource_name (hd), g10_errstr(rc));
856 /* This should not be possible since we delete the
857 ownertrust when a key is deleted, but it can happen if
858 the keyring and trustdb are out of sync. It can also
859 be made to happen with the trusted-key command. */
861 clear_ownertrusts (pk);
863 revalidation_mark ();
870 char *p=get_user_id_native (keyid);
871 log_info( _("key %s: public key \"%s\" imported\n"),
875 if( is_status_enabled() )
877 char *us = get_long_user_id_string( keyid );
878 write_status_text( STATUS_IMPORTED, us );
880 print_import_ok (pk,NULL, 1);
883 if( is_RSA( pk->pubkey_algo ) )
884 stats->imported_rsa++;
889 int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
891 /* Compare the original against the new key; just to be sure nothing
892 * weird is going on */
893 if( cmp_public_keys( pk_orig, pk ) )
895 log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
899 /* now read the original keyblock */
902 byte afp[MAX_FINGERPRINT_LEN];
905 fingerprint_from_pk (pk_orig, afp, &an);
906 while (an < MAX_FINGERPRINT_LEN)
908 rc = keydb_search_fpr (hd, afp);
912 log_error (_("key %s: can't locate original keyblock: %s\n"),
913 keystr(keyid), g10_errstr(rc));
917 rc = keydb_get_keyblock (hd, &keyblock_orig );
920 log_error (_("key %s: can't read original keyblock: %s\n"),
921 keystr(keyid), g10_errstr(rc));
926 /* Make sure the original direct key sigs are all sane. */
927 n_sigs_cleaned = fix_bad_direct_key_sigs (keyblock_orig, keyid);
929 commit_kbnode (&keyblock_orig);
931 /* and try to merge the block */
932 clear_kbnode_flags( keyblock_orig );
933 clear_kbnode_flags( keyblock );
934 n_uids = n_sigs = n_subk = n_uids_cleaned = 0;
935 rc = merge_blocks( fname, keyblock_orig, keyblock,
936 keyid, &n_uids, &n_sigs, &n_subk );
943 if(options&IMPORT_CLEAN)
944 clean_key(keyblock_orig,opt.verbose,options&IMPORT_MINIMAL,
945 &n_uids_cleaned,&n_sigs_cleaned);
947 if( n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned) {
949 /* keyblock_orig has been updated; write */
950 rc = keydb_update_keyblock (hd, keyblock_orig);
952 log_error (_("error writing keyring `%s': %s\n"),
953 keydb_get_resource_name (hd), g10_errstr(rc) );
955 revalidation_mark ();
960 char *p=get_user_id_native(keyid);
962 log_info( _("key %s: \"%s\" 1 new user ID\n"),
965 log_info( _("key %s: \"%s\" %d new user IDs\n"),
966 keystr(keyid),p,n_uids);
968 log_info( _("key %s: \"%s\" 1 new signature\n"),
971 log_info( _("key %s: \"%s\" %d new signatures\n"),
972 keystr(keyid), p, n_sigs );
974 log_info( _("key %s: \"%s\" 1 new subkey\n"),
977 log_info( _("key %s: \"%s\" %d new subkeys\n"),
978 keystr(keyid), p, n_subk );
979 if(n_sigs_cleaned==1)
980 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
981 keystr(keyid),p,n_sigs_cleaned);
982 else if(n_sigs_cleaned)
983 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
984 keystr(keyid),p,n_sigs_cleaned);
985 if(n_uids_cleaned==1)
986 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
987 keystr(keyid),p,n_uids_cleaned);
988 else if(n_uids_cleaned)
989 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
990 keystr(keyid),p,n_uids_cleaned);
994 stats->n_uids +=n_uids;
995 stats->n_sigs +=n_sigs;
996 stats->n_subk +=n_subk;
997 stats->n_sigs_cleaned +=n_sigs_cleaned;
998 stats->n_uids_cleaned +=n_uids_cleaned;
1000 if (is_status_enabled ())
1001 print_import_ok (pk, NULL,
1002 ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
1007 if (is_status_enabled ())
1008 print_import_ok (pk, NULL, 0);
1012 char *p=get_user_id_native(keyid);
1013 log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
1020 keydb_release (hd); hd = NULL;
1024 if (mod_key || new_key || same_key)
1026 /* A little explanation for this: we fill in the fingerprint
1027 when importing keys as it can be useful to know the
1028 fingerprint in certain keyserver-related cases (a keyserver
1029 asked for a particular name, but the key doesn't have that
1030 name). However, in cases where we're importing more than
1031 one key at a time, we cannot know which key to fingerprint.
1032 In these cases, rather than guessing, we do not
1033 fingerprinting at all, and we must hope the user ID on the
1034 keys are useful. Note that we need to do this for new
1035 keys, merged keys and even for unchanged keys. This is
1036 required because for example the --auto-key-locate feature
1037 may import an already imported key and needs to know the
1038 fingerprint of the key in all cases. */
1042 /* Note that we need to compare against 0 here because
1043 COUNT gets only incremented after returning form this
1045 if (stats->count == 0)
1046 *fpr = fingerprint_from_pk (pk, NULL, fpr_len);
1052 /* Now that the key is definitely incorporated into the keydb, we
1053 need to check if a designated revocation is present or if the
1054 prefs are not rational so we can warn the user. */
1058 revocation_present(keyblock_orig);
1059 if(!from_sk && seckey_available(keyid)==0)
1060 check_prefs(keyblock_orig);
1064 revocation_present(keyblock);
1065 if(!from_sk && seckey_available(keyid)==0)
1066 check_prefs(keyblock);
1069 release_kbnode( keyblock_orig );
1070 free_public_key( pk_orig );
1075 /* Walk a secret keyblock and produce a public keyblock out of it. */
1077 sec_to_pub_keyblock(KBNODE sec_keyblock)
1079 KBNODE secnode,pub_keyblock=NULL,ctx=NULL;
1081 while((secnode=walk_kbnode(sec_keyblock,&ctx,0)))
1085 if(secnode->pkt->pkttype==PKT_SECRET_KEY ||
1086 secnode->pkt->pkttype==PKT_SECRET_SUBKEY)
1088 /* Make a public key. We only need to convert enough to
1089 write the keyblock out. */
1091 PKT_secret_key *sk=secnode->pkt->pkt.secret_key;
1092 PACKET *pkt=xmalloc_clear(sizeof(PACKET));
1093 PKT_public_key *pk=xmalloc_clear(sizeof(PKT_public_key));
1096 if(secnode->pkt->pkttype==PKT_SECRET_KEY)
1097 pkt->pkttype=PKT_PUBLIC_KEY;
1099 pkt->pkttype=PKT_PUBLIC_SUBKEY;
1101 pkt->pkt.public_key=pk;
1103 pk->version=sk->version;
1104 pk->timestamp=sk->timestamp;
1105 pk->expiredate=sk->expiredate;
1106 pk->pubkey_algo=sk->pubkey_algo;
1108 n=pubkey_get_npkey(pk->pubkey_algo);
1111 /* we can't properly extract the pubkey without knowing
1112 the number of MPIs */
1113 release_kbnode(pub_keyblock);
1121 pk->pkey[i]=mpi_copy(sk->skey[i]);
1124 pubnode=new_kbnode(pkt);
1128 pubnode=clone_kbnode(secnode);
1131 if(pub_keyblock==NULL)
1132 pub_keyblock=pubnode;
1134 add_kbnode(pub_keyblock,pubnode);
1137 return pub_keyblock;
1141 * Ditto for secret keys. Handling is simpler than for public keys.
1142 * We allow secret key importing only when allow is true, this is so
1143 * that a secret key can not be imported accidently and thereby tampering
1144 * with the trust calculation.
1147 import_secret_one( const char *fname, KBNODE keyblock,
1148 struct stats_s *stats, unsigned int options)
1151 KBNODE node, uidnode;
1155 /* get the key and print some info about it */
1156 node = find_kbnode( keyblock, PKT_SECRET_KEY );
1160 sk = node->pkt->pkt.secret_key;
1161 keyid_from_sk( sk, keyid );
1162 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1166 log_info( "sec %4u%c/%s %s ",
1167 nbits_from_sk( sk ),
1168 pubkey_letter( sk->pubkey_algo ),
1169 keystr_from_sk(sk), datestr_from_sk(sk) );
1171 print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
1172 uidnode->pkt->pkt.user_id->len );
1175 stats->secret_read++;
1179 log_error( _("key %s: no user ID\n"), keystr_from_sk(sk));
1183 if(sk->protect.algo>110)
1185 log_error(_("key %s: secret key with invalid cipher %d"
1186 " - skipped\n"),keystr_from_sk(sk),sk->protect.algo);
1190 #ifdef ENABLE_SELINUX_HACKS
1193 /* We don't allow to import secret keys because that may be used
1194 to put a secret key into the keyring and the user might later
1195 be tricked into signing stuff with that key. */
1196 log_error (_("importing secret keys not allowed\n"));
1201 clear_kbnode_flags( keyblock );
1203 /* do we have this key already in one of our secrings ? */
1204 rc = seckey_available( keyid );
1205 if( rc == G10ERR_NO_SECKEY && !(opt.import_options&IMPORT_MERGE_ONLY) )
1207 /* simply insert this key */
1208 KEYDB_HANDLE hd = keydb_new (1);
1210 /* get default resource */
1211 rc = keydb_locate_writable (hd, NULL);
1213 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
1215 return G10ERR_GENERAL;
1217 rc = keydb_insert_keyblock (hd, keyblock );
1219 log_error (_("error writing keyring `%s': %s\n"),
1220 keydb_get_resource_name (hd), g10_errstr(rc) );
1224 log_info( _("key %s: secret key imported\n"), keystr_from_sk(sk));
1225 stats->secret_imported++;
1226 if (is_status_enabled ())
1227 print_import_ok (NULL, sk, 1|16);
1229 if(options&IMPORT_SK2PK)
1231 /* Try and make a public key out of this. */
1233 KBNODE pub_keyblock=sec_to_pub_keyblock(keyblock);
1236 import_one(fname,pub_keyblock,stats,
1237 NULL,NULL,opt.import_options,1);
1238 release_kbnode(pub_keyblock);
1242 /* Now that the key is definitely incorporated into the keydb,
1243 if we have the public part of this key, we need to check if
1244 the prefs are rational. */
1245 node=get_pubkeyblock(keyid);
1249 release_kbnode(node);
1253 { /* we can't merge secret keys */
1254 log_error( _("key %s: already in secret keyring\n"),
1255 keystr_from_sk(sk));
1256 stats->secret_dups++;
1257 if (is_status_enabled ())
1258 print_import_ok (NULL, sk, 16);
1260 /* TODO: if we ever do merge secret keys, make sure to handle
1261 the sec_to_pub_keyblock feature as well. */
1264 log_error( _("key %s: secret key not found: %s\n"),
1265 keystr_from_sk(sk), g10_errstr(rc));
1272 * Import a revocation certificate; this is a single signature packet.
1275 import_revoke_cert( const char *fname, KBNODE node, struct stats_s *stats )
1277 PKT_public_key *pk=NULL;
1278 KBNODE onode, keyblock = NULL;
1279 KEYDB_HANDLE hd = NULL;
1285 assert( !node->next );
1286 assert( node->pkt->pkttype == PKT_SIGNATURE );
1287 assert( node->pkt->pkt.signature->sig_class == 0x20 );
1289 keyid[0] = node->pkt->pkt.signature->keyid[0];
1290 keyid[1] = node->pkt->pkt.signature->keyid[1];
1292 pk = xmalloc_clear( sizeof *pk );
1293 rc = get_pubkey( pk, keyid );
1294 if( rc == G10ERR_NO_PUBKEY )
1296 log_error(_("key %s: no public key -"
1297 " can't apply revocation certificate\n"), keystr(keyid));
1303 log_error(_("key %s: public key not found: %s\n"),
1304 keystr(keyid), g10_errstr(rc));
1308 /* read the original keyblock */
1311 byte afp[MAX_FINGERPRINT_LEN];
1314 fingerprint_from_pk (pk, afp, &an);
1315 while (an < MAX_FINGERPRINT_LEN)
1317 rc = keydb_search_fpr (hd, afp);
1321 log_error (_("key %s: can't locate original keyblock: %s\n"),
1322 keystr(keyid), g10_errstr(rc));
1325 rc = keydb_get_keyblock (hd, &keyblock );
1328 log_error (_("key %s: can't read original keyblock: %s\n"),
1329 keystr(keyid), g10_errstr(rc));
1333 /* it is okay, that node is not in keyblock because
1334 * check_key_signature works fine for sig_class 0x20 in this
1336 rc = check_key_signature( keyblock, node, NULL);
1339 log_error( _("key %s: invalid revocation certificate"
1340 ": %s - rejected\n"), keystr(keyid), g10_errstr(rc));
1344 /* check whether we already have this */
1345 for(onode=keyblock->next; onode; onode=onode->next ) {
1346 if( onode->pkt->pkttype == PKT_USER_ID )
1348 else if( onode->pkt->pkttype == PKT_SIGNATURE
1349 && !cmp_signatures(node->pkt->pkt.signature,
1350 onode->pkt->pkt.signature))
1353 goto leave; /* yes, we already know about it */
1359 insert_kbnode( keyblock, clone_kbnode(node), 0 );
1361 /* and write the keyblock back */
1362 rc = keydb_update_keyblock (hd, keyblock );
1364 log_error (_("error writing keyring `%s': %s\n"),
1365 keydb_get_resource_name (hd), g10_errstr(rc) );
1366 keydb_release (hd); hd = NULL;
1370 char *p=get_user_id_native (keyid);
1371 log_info( _("key %s: \"%s\" revocation certificate imported\n"),
1377 /* If the key we just revoked was ultimately trusted, remove its
1378 ultimate trust. This doesn't stop the user from putting the
1379 ultimate trust back, but is a reasonable solution for now. */
1380 if(get_ownertrust(pk)==TRUST_ULTIMATE)
1381 clear_ownertrusts(pk);
1383 revalidation_mark ();
1387 release_kbnode( keyblock );
1388 free_public_key( pk );
1394 * Loop over the keyblock and check all self signatures.
1395 * Mark all user-ids with a self-signature by setting flag bit 0.
1396 * Mark all user-ids with an invalid self-signature by setting bit 1.
1397 * This works also for subkeys, here the subkey is marked. Invalid or
1398 * extra subkey sigs (binding or revocation) are marked for deletion.
1399 * non_self is set to true if there are any sigs other than self-sigs
1403 chk_self_sigs( const char *fname, KBNODE keyblock,
1404 PKT_public_key *pk, u32 *keyid, int *non_self )
1406 KBNODE n, knode = NULL;
1409 u32 bsdate=0,rsdate=0;
1410 KBNODE bsnode = NULL, rsnode = NULL;
1415 for (n=keyblock; (n = find_next_kbnode (n, 0)); )
1417 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1427 if ( n->pkt->pkttype != PKT_SIGNATURE )
1430 sig = n->pkt->pkt.signature;
1431 if ( keyid[0] != sig->keyid[0] || keyid[1] != sig->keyid[1] )
1437 /* This just caches the sigs for later use. That way we
1438 import a fully-cached key which speeds things up. */
1439 if (!opt.no_sig_cache)
1440 check_key_signature (keyblock, n, NULL);
1442 if ( IS_UID_SIG(sig) || IS_UID_REV(sig) )
1444 KBNODE unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
1447 log_error( _("key %s: no user ID for signature\n"),
1449 return -1; /* The complete keyblock is invalid. */
1452 /* If it hasn't been marked valid yet, keep trying. */
1453 if (!(unode->flag&1))
1455 rc = check_key_signature (keyblock, n, NULL);
1460 char *p = utf8_to_native
1461 (unode->pkt->pkt.user_id->name,
1462 strlen (unode->pkt->pkt.user_id->name),0);
1463 log_info (gpg_err_code(rc) == G10ERR_PUBKEY_ALGO ?
1464 _("key %s: unsupported public key "
1465 "algorithm on user ID \"%s\"\n"):
1466 _("key %s: invalid self-signature "
1467 "on user ID \"%s\"\n"),
1473 unode->flag |= 1; /* Mark that signature checked. */
1476 else if (IS_KEY_SIG (sig))
1478 rc = check_key_signature (keyblock, n, NULL);
1482 log_info (gpg_err_code (rc) == G10ERR_PUBKEY_ALGO ?
1483 _("key %s: unsupported public key algorithm\n"):
1484 _("key %s: invalid direct key signature\n"),
1489 else if ( IS_SUBKEY_SIG (sig) )
1491 /* Note that this works based solely on the timestamps like
1492 the rest of gpg. If the standard gets revocation
1493 targets, this may need to be revised. */
1498 log_info (_("key %s: no subkey for key binding\n"),
1500 n->flag |= 4; /* delete this */
1504 rc = check_key_signature (keyblock, n, NULL);
1508 log_info (gpg_err_code (rc) == G10ERR_PUBKEY_ALGO ?
1509 _("key %s: unsupported public key"
1511 _("key %s: invalid subkey binding\n"),
1517 /* It's valid, so is it newer? */
1518 if (sig->timestamp >= bsdate)
1520 knode->flag |= 1; /* The subkey is valid. */
1523 /* Delete the last binding sig since this
1527 log_info (_("key %s: removed multiple subkey"
1528 " binding\n"),keystr(keyid));
1532 bsdate = sig->timestamp;
1535 n->flag |= 4; /* older */
1539 else if ( IS_SUBKEY_REV (sig) )
1541 /* We don't actually mark the subkey as revoked right now,
1542 so just check that the revocation sig is the most recent
1543 valid one. Note that we don't care if the binding sig is
1544 newer than the revocation sig. See the comment in
1545 getkey.c:merge_selfsigs_subkey for more. */
1549 log_info (_("key %s: no subkey for key revocation\n"),
1551 n->flag |= 4; /* delete this */
1555 rc = check_key_signature (keyblock, n, NULL);
1559 log_info (gpg_err_code (rc) == G10ERR_PUBKEY_ALGO ?
1560 _("key %s: unsupported public"
1561 " key algorithm\n"):
1562 _("key %s: invalid subkey revocation\n"),
1568 /* It's valid, so is it newer? */
1569 if (sig->timestamp >= rsdate)
1573 /* Delete the last revocation sig since
1574 this one is newer. */
1577 log_info (_("key %s: removed multiple subkey"
1578 " revocation\n"),keystr(keyid));
1582 rsdate = sig->timestamp;
1585 n->flag |= 4; /* older */
1595 * delete all parts which are invalid and those signatures whose
1596 * public key algorithm is not available in this implemenation;
1597 * but consider RSA as valid, because parse/build_packets knows
1599 * returns: true if at least one valid user-id is left over.
1602 delete_inv_parts( const char *fname, KBNODE keyblock,
1603 u32 *keyid, unsigned int options)
1606 int nvalid=0, uid_seen=0, subkey_seen=0;
1610 for(node=keyblock->next; node; node = node->next ) {
1611 if( node->pkt->pkttype == PKT_USER_ID ) {
1613 if( (node->flag & 2) || !(node->flag & 1) ) {
1616 char *p=utf8_to_native(node->pkt->pkt.user_id->name,
1617 node->pkt->pkt.user_id->len,0);
1618 log_info( _("key %s: skipped user ID \"%s\"\n"),
1622 delete_kbnode( node ); /* the user-id */
1623 /* and all following packets up to the next user-id */
1625 && node->next->pkt->pkttype != PKT_USER_ID
1626 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1627 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
1628 delete_kbnode( node->next );
1635 else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1636 || node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1637 if( (node->flag & 2) || !(node->flag & 1) ) {
1639 log_info( _("key %s: skipped subkey\n"),keystr(keyid));
1641 delete_kbnode( node ); /* the subkey */
1642 /* and all following signature packets */
1644 && node->next->pkt->pkttype == PKT_SIGNATURE ) {
1645 delete_kbnode( node->next );
1652 else if (node->pkt->pkttype == PKT_SIGNATURE
1653 && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
1654 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
1655 delete_kbnode( node ); /* build_packet() can't handle this */
1656 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1657 !node->pkt->pkt.signature->flags.exportable &&
1658 !(options&IMPORT_LOCAL_SIGS) &&
1659 seckey_available( node->pkt->pkt.signature->keyid ) )
1661 /* here we violate the rfc a bit by still allowing
1662 * to import non-exportable signature when we have the
1663 * the secret key used to create this signature - it
1664 * seems that this makes sense */
1666 log_info( _("key %s: non exportable signature"
1667 " (class 0x%02X) - skipped\n"),
1668 keystr(keyid), node->pkt->pkt.signature->sig_class );
1669 delete_kbnode( node );
1671 else if( node->pkt->pkttype == PKT_SIGNATURE
1672 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1676 log_info( _("key %s: revocation certificate"
1677 " at wrong place - skipped\n"),keystr(keyid));
1678 delete_kbnode( node );
1681 /* If the revocation cert is from a different key than
1682 the one we're working on don't check it - it's
1683 probably from a revocation key and won't be
1684 verifiable with this key anyway. */
1686 if(node->pkt->pkt.signature->keyid[0]==keyid[0] &&
1687 node->pkt->pkt.signature->keyid[1]==keyid[1])
1689 int rc = check_key_signature( keyblock, node, NULL);
1693 log_info( _("key %s: invalid revocation"
1694 " certificate: %s - skipped\n"),
1695 keystr(keyid), g10_errstr(rc));
1696 delete_kbnode( node );
1701 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1702 (node->pkt->pkt.signature->sig_class == 0x18 ||
1703 node->pkt->pkt.signature->sig_class == 0x28) &&
1707 log_info( _("key %s: subkey signature"
1708 " in wrong place - skipped\n"), keystr(keyid));
1709 delete_kbnode( node );
1711 else if( node->pkt->pkttype == PKT_SIGNATURE
1712 && !IS_CERT(node->pkt->pkt.signature))
1715 log_info(_("key %s: unexpected signature class (0x%02X) -"
1716 " skipped\n"),keystr(keyid),
1717 node->pkt->pkt.signature->sig_class);
1718 delete_kbnode(node);
1720 else if( (node->flag & 4) ) /* marked for deletion */
1721 delete_kbnode( node );
1724 /* note: because keyblock is the public key, it is never marked
1725 * for deletion and so keyblock cannot change */
1726 commit_kbnode( &keyblock );
1732 * It may happen that the imported keyblock has duplicated user IDs.
1733 * We check this here and collapse those user IDs together with their
1735 * Returns: True if the keyblock has changed.
1738 collapse_uids( KBNODE *keyblock )
1743 for(uid1=*keyblock;uid1;uid1=uid1->next)
1747 if(is_deleted_kbnode(uid1))
1750 if(uid1->pkt->pkttype!=PKT_USER_ID)
1753 for(uid2=uid1->next;uid2;uid2=uid2->next)
1755 if(is_deleted_kbnode(uid2))
1758 if(uid2->pkt->pkttype!=PKT_USER_ID)
1761 if(cmp_user_ids(uid1->pkt->pkt.user_id,
1762 uid2->pkt->pkt.user_id)==0)
1764 /* We have a duplicated uid */
1769 /* Now take uid2's signatures, and attach them to
1771 for(last=uid2;last->next;last=last->next)
1773 if(is_deleted_kbnode(last))
1776 if(last->next->pkt->pkttype==PKT_USER_ID
1777 || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
1778 || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
1783 (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
1785 /* Now put uid2 in place as part of uid1 */
1786 last->next=uid1->next;
1788 delete_kbnode(uid2);
1790 /* Now dedupe uid1 */
1791 for(sig1=uid1->next;sig1;sig1=sig1->next)
1795 if(is_deleted_kbnode(sig1))
1798 if(sig1->pkt->pkttype==PKT_USER_ID
1799 || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
1800 || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
1803 if(sig1->pkt->pkttype!=PKT_SIGNATURE)
1806 for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
1808 if(is_deleted_kbnode(sig2))
1811 if(sig2->pkt->pkttype==PKT_USER_ID
1812 || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
1813 || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
1816 if(sig2->pkt->pkttype!=PKT_SIGNATURE)
1819 if(cmp_signatures(sig1->pkt->pkt.signature,
1820 sig2->pkt->pkt.signature)==0)
1822 /* We have a match, so delete the second
1824 delete_kbnode(sig2);
1833 commit_kbnode(keyblock);
1835 if(any && !opt.quiet)
1837 const char *key="???";
1839 if( (uid1=find_kbnode( *keyblock, PKT_PUBLIC_KEY )) )
1840 key=keystr_from_pk(uid1->pkt->pkt.public_key);
1841 else if( (uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY )) )
1842 key=keystr_from_sk(uid1->pkt->pkt.secret_key);
1844 log_info(_("key %s: duplicated user ID detected - merged\n"),key);
1850 /* Check for a 0x20 revocation from a revocation key that is not
1851 present. This may be called without the benefit of merge_xxxx so
1852 you can't rely on pk->revkey and friends. */
1854 revocation_present(KBNODE keyblock)
1857 PKT_public_key *pk=keyblock->pkt->pkt.public_key;
1859 for(onode=keyblock->next;onode;onode=onode->next)
1861 /* If we reach user IDs, we're done. */
1862 if(onode->pkt->pkttype==PKT_USER_ID)
1865 if(onode->pkt->pkttype==PKT_SIGNATURE &&
1866 onode->pkt->pkt.signature->sig_class==0x1F &&
1867 onode->pkt->pkt.signature->revkey)
1870 PKT_signature *sig=onode->pkt->pkt.signature;
1872 for(idx=0;idx<sig->numrevkeys;idx++)
1876 keyid_from_fingerprint(sig->revkey[idx]->fpr,
1877 MAX_FINGERPRINT_LEN,keyid);
1879 for(inode=keyblock->next;inode;inode=inode->next)
1881 /* If we reach user IDs, we're done. */
1882 if(inode->pkt->pkttype==PKT_USER_ID)
1885 if(inode->pkt->pkttype==PKT_SIGNATURE &&
1886 inode->pkt->pkt.signature->sig_class==0x20 &&
1887 inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
1888 inode->pkt->pkt.signature->keyid[1]==keyid[1])
1890 /* Okay, we have a revocation key, and a
1891 revocation issued by it. Do we have the key
1895 rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx]->fpr,
1896 MAX_FINGERPRINT_LEN);
1897 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1899 char *tempkeystr=xstrdup(keystr_from_pk(pk));
1901 /* No, so try and get it */
1903 && (opt.keyserver_options.options
1904 & KEYSERVER_AUTO_KEY_RETRIEVE))
1906 log_info(_("WARNING: key %s may be revoked:"
1907 " fetching revocation key %s\n"),
1908 tempkeystr,keystr(keyid));
1909 keyserver_import_fprint(sig->revkey[idx]->fpr,
1910 MAX_FINGERPRINT_LEN,
1913 /* Do we have it now? */
1914 rc=get_pubkey_byfprint_fast (NULL,
1915 sig->revkey[idx]->fpr,
1916 MAX_FINGERPRINT_LEN);
1919 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1920 log_info(_("WARNING: key %s may be revoked:"
1921 " revocation key %s not present.\n"),
1922 tempkeystr,keystr(keyid));
1934 * compare and merge the blocks
1936 * o compare the signatures: If we already have this signature, check
1937 * that they compare okay; if not, issue a warning and ask the user.
1938 * o Simply add the signature. Can't verify here because we may not have
1939 * the signature's public key yet; verification is done when putting it
1940 * into the trustdb, which is done automagically as soon as this pubkey
1942 * Note: We indicate newly inserted packets with flag bit 0
1945 merge_blocks( const char *fname, KBNODE keyblock_orig, KBNODE keyblock,
1946 u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
1951 /* 1st: handle revocation certificates */
1952 for(node=keyblock->next; node; node=node->next ) {
1953 if( node->pkt->pkttype == PKT_USER_ID )
1955 else if( node->pkt->pkttype == PKT_SIGNATURE
1956 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1957 /* check whether we already have this */
1959 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1960 if( onode->pkt->pkttype == PKT_USER_ID )
1962 else if( onode->pkt->pkttype == PKT_SIGNATURE
1963 && onode->pkt->pkt.signature->sig_class == 0x20
1964 && !cmp_signatures(onode->pkt->pkt.signature,
1965 node->pkt->pkt.signature))
1972 KBNODE n2 = clone_kbnode(node);
1973 insert_kbnode( keyblock_orig, n2, 0 );
1978 char *p=get_user_id_native (keyid);
1979 log_info(_("key %s: \"%s\" revocation"
1980 " certificate added\n"), keystr(keyid),p);
1987 /* 2nd: merge in any direct key (0x1F) sigs */
1988 for(node=keyblock->next; node; node=node->next ) {
1989 if( node->pkt->pkttype == PKT_USER_ID )
1991 else if( node->pkt->pkttype == PKT_SIGNATURE
1992 && node->pkt->pkt.signature->sig_class == 0x1F ) {
1993 /* check whether we already have this */
1995 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1996 if( onode->pkt->pkttype == PKT_USER_ID )
1998 else if( onode->pkt->pkttype == PKT_SIGNATURE
1999 && onode->pkt->pkt.signature->sig_class == 0x1F
2000 && !cmp_signatures(onode->pkt->pkt.signature,
2001 node->pkt->pkt.signature)) {
2008 KBNODE n2 = clone_kbnode(node);
2009 insert_kbnode( keyblock_orig, n2, 0 );
2013 log_info( _("key %s: direct key signature added\n"),
2019 /* 3rd: try to merge new certificates in */
2020 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
2021 if( !(onode->flag & 1) && onode->pkt->pkttype == PKT_USER_ID) {
2022 /* find the user id in the imported keyblock */
2023 for(node=keyblock->next; node; node=node->next )
2024 if( node->pkt->pkttype == PKT_USER_ID
2025 && !cmp_user_ids( onode->pkt->pkt.user_id,
2026 node->pkt->pkt.user_id ) )
2028 if( node ) { /* found: merge */
2029 rc = merge_sigs( onode, node, n_sigs, fname, keyid );
2036 /* 4th: add new user-ids */
2037 for(node=keyblock->next; node; node=node->next ) {
2038 if( node->pkt->pkttype == PKT_USER_ID) {
2039 /* do we have this in the original keyblock */
2040 for(onode=keyblock_orig->next; onode; onode=onode->next )
2041 if( onode->pkt->pkttype == PKT_USER_ID
2042 && !cmp_user_ids( onode->pkt->pkt.user_id,
2043 node->pkt->pkt.user_id ) )
2045 if( !onode ) { /* this is a new user id: append */
2046 rc = append_uid( keyblock_orig, node, n_sigs, fname, keyid);
2054 /* 5th: add new subkeys */
2055 for(node=keyblock->next; node; node=node->next ) {
2057 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2058 /* do we have this in the original keyblock? */
2059 for(onode=keyblock_orig->next; onode; onode=onode->next )
2060 if( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
2061 && !cmp_public_keys( onode->pkt->pkt.public_key,
2062 node->pkt->pkt.public_key ) )
2064 if( !onode ) { /* this is a new subkey: append */
2065 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
2071 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2072 /* do we have this in the original keyblock? */
2073 for(onode=keyblock_orig->next; onode; onode=onode->next )
2074 if( onode->pkt->pkttype == PKT_SECRET_SUBKEY
2075 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
2076 node->pkt->pkt.secret_key ) )
2078 if( !onode ) { /* this is a new subkey: append */
2079 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
2087 /* 6th: merge subkey certificates */
2088 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
2089 if( !(onode->flag & 1)
2090 && ( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
2091 || onode->pkt->pkttype == PKT_SECRET_SUBKEY) ) {
2092 /* find the subkey in the imported keyblock */
2093 for(node=keyblock->next; node; node=node->next ) {
2094 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2095 && !cmp_public_keys( onode->pkt->pkt.public_key,
2096 node->pkt->pkt.public_key ) )
2098 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY
2099 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
2100 node->pkt->pkt.secret_key ) )
2103 if( node ) { /* found: merge */
2104 rc = merge_keysigs( onode, node, n_sigs, fname, keyid );
2117 * append the userid starting with NODE and all signatures to KEYBLOCK.
2120 append_uid (KBNODE keyblock, KBNODE node, int *n_sigs,
2121 const char *fname, u32 *keyid )
2123 KBNODE n, n_where=NULL;
2128 assert(node->pkt->pkttype == PKT_USER_ID );
2130 /* find the position */
2131 for( n = keyblock; n; n_where = n, n = n->next ) {
2132 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2133 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
2139 /* and append/insert */
2141 /* we add a clone to the original keyblock, because this
2142 * one is released first */
2143 n = clone_kbnode(node);
2145 insert_kbnode( n_where, n, 0 );
2149 add_kbnode( keyblock, n );
2152 if( n->pkt->pkttype == PKT_SIGNATURE )
2156 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2165 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
2166 * (how should we handle comment packets here?)
2169 merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
2170 const char *fname, u32 *keyid )
2178 assert(dst->pkt->pkttype == PKT_USER_ID );
2179 assert(src->pkt->pkttype == PKT_USER_ID );
2181 for(n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next ) {
2182 if( n->pkt->pkttype != PKT_SIGNATURE )
2184 if( n->pkt->pkt.signature->sig_class == 0x18
2185 || n->pkt->pkt.signature->sig_class == 0x28 )
2186 continue; /* skip signatures which are only valid on subkeys */
2188 for(n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
2189 if(!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
2195 /* This signature is new or newer, append N to DST.
2196 * We add a clone to the original keyblock, because this
2197 * one is released first */
2198 n2 = clone_kbnode(n);
2199 insert_kbnode( dst, n2, PKT_SIGNATURE );
2210 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
2213 merge_keysigs (KBNODE dst, KBNODE src, int *n_sigs,
2214 const char *fname, u32 *keyid)
2222 assert( dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
2223 || dst->pkt->pkttype == PKT_SECRET_SUBKEY );
2225 for(n=src->next; n ; n = n->next ) {
2226 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2227 || n->pkt->pkttype == PKT_PUBLIC_KEY )
2229 if( n->pkt->pkttype != PKT_SIGNATURE )
2232 for(n2=dst->next; n2; n2 = n2->next){
2233 if( n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
2234 || n2->pkt->pkttype == PKT_PUBLIC_KEY )
2236 if( n2->pkt->pkttype == PKT_SIGNATURE
2237 && n->pkt->pkt.signature->keyid[0]
2238 == n2->pkt->pkt.signature->keyid[0]
2239 && n->pkt->pkt.signature->keyid[1]
2240 == n2->pkt->pkt.signature->keyid[1]
2241 && n->pkt->pkt.signature->timestamp
2242 <= n2->pkt->pkt.signature->timestamp
2243 && n->pkt->pkt.signature->sig_class
2244 == n2->pkt->pkt.signature->sig_class ) {
2250 /* This signature is new or newer, append N to DST.
2251 * We add a clone to the original keyblock, because this
2252 * one is released first */
2253 n2 = clone_kbnode(n);
2254 insert_kbnode( dst, n2, PKT_SIGNATURE );
2265 * append the subkey starting with NODE and all signatures to KEYBLOCK.
2266 * Mark all new and copied packets by setting flag bit 0.
2269 append_key (KBNODE keyblock, KBNODE node, int *n_sigs,
2270 const char *fname, u32 *keyid)
2277 assert( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2278 || node->pkt->pkttype == PKT_SECRET_SUBKEY );
2281 /* we add a clone to the original keyblock, because this
2282 * one is released first */
2283 n = clone_kbnode(node);
2284 add_kbnode( keyblock, n );
2287 if( n->pkt->pkttype == PKT_SIGNATURE )
2291 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2300 /* Walk a public keyblock and produce a secret keyblock out of it.
2301 Instead of inserting the secret key parameters (which we don't
2302 have), we insert a stub. */
2304 pub_to_sec_keyblock (KBNODE pub_keyblock)
2306 KBNODE pubnode, secnode;
2307 KBNODE sec_keyblock = NULL;
2308 KBNODE walkctx = NULL;
2310 while((pubnode = walk_kbnode (pub_keyblock,&walkctx,0)))
2312 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY
2313 || pubnode->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2315 /* Make a secret key. We only need to convert enough to
2316 write the keyblock out. */
2317 PKT_public_key *pk = pubnode->pkt->pkt.public_key;
2318 PACKET *pkt = xmalloc_clear (sizeof *pkt);
2319 PKT_secret_key *sk = xmalloc_clear (sizeof *sk);
2322 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY)
2323 pkt->pkttype = PKT_SECRET_KEY;
2325 pkt->pkttype = PKT_SECRET_SUBKEY;
2327 pkt->pkt.secret_key = sk;
2329 copy_public_parts_to_secret_key ( pk, sk );
2330 sk->version = pk->version;
2331 sk->timestamp = pk->timestamp;
2333 n = pubkey_get_npkey (pk->pubkey_algo);
2335 n = 1; /* Unknown number of parameters, however the data
2336 is stored in the first mpi. */
2337 for (i=0; i < n; i++ )
2338 sk->skey[i] = mpi_copy (pk->pkey[i]);
2340 sk->is_protected = 1;
2341 sk->protect.s2k.mode = 1001;
2343 secnode = new_kbnode (pkt);
2347 secnode = clone_kbnode (pubnode);
2351 sec_keyblock = secnode;
2353 add_kbnode (sec_keyblock, secnode);
2356 return sec_keyblock;
2360 /* Walk over the secret keyring SEC_KEYBLOCK and update any simple
2361 stub keys with the serial number SNNUM of the card if one of the
2362 fingerprints FPR1, FPR2 or FPR3 match. Print a note if the key is
2363 a duplicate (may happen in case of backed uped keys).
2365 Returns: True if anything changed.
2368 update_sec_keyblock_with_cardinfo (KBNODE sec_keyblock,
2369 const unsigned char *fpr1,
2370 const unsigned char *fpr2,
2371 const unsigned char *fpr3,
2372 const char *serialnostr)
2375 KBNODE walkctx = NULL;
2377 byte array[MAX_FINGERPRINT_LEN];
2382 while((node = walk_kbnode (sec_keyblock, &walkctx, 0)))
2384 if (node->pkt->pkttype != PKT_SECRET_KEY
2385 && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2387 sk = node->pkt->pkt.secret_key;
2389 fingerprint_from_sk (sk, array, &n);
2391 continue; /* Can't be a card key. */
2392 if ( !((fpr1 && !memcmp (array, fpr1, 20))
2393 || (fpr2 && !memcmp (array, fpr2, 20))
2394 || (fpr3 && !memcmp (array, fpr3, 20))) )
2395 continue; /* No match. */
2397 if (sk->is_protected == 1 && sk->protect.s2k.mode == 1001)
2399 /* Standard case: migrate that stub to a key stub. */
2400 sk->protect.s2k.mode = 1002;
2402 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2403 sk->protect.ivlen++, s += 2)
2404 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
2407 else if (sk->is_protected == 1 && sk->protect.s2k.mode == 1002)
2410 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2411 sk->protect.ivlen++, s += 2)
2412 if (sk->protect.iv[sk->protect.ivlen] != xtoi_2 (s))
2414 log_info (_("NOTE: a key's S/N does not "
2415 "match the card's one\n"));
2421 if (node->pkt->pkttype != PKT_SECRET_KEY)
2422 log_info (_("NOTE: primary key is online and stored on card\n"));
2424 log_info (_("NOTE: secondary key is online and stored on card\n"));
2433 /* Check whether a secret key stub exists for the public key PK. If
2434 not create such a stub key and store it into the secring. If it
2435 exists, add appropriate subkey stubs and update the secring.
2436 Return 0 if the key could be created. */
2438 auto_create_card_key_stub ( const char *serialnostr,
2439 const unsigned char *fpr1,
2440 const unsigned char *fpr2,
2441 const unsigned char *fpr3)
2443 KBNODE pub_keyblock;
2444 KBNODE sec_keyblock;
2448 /* We only want to do this for an OpenPGP card. */
2449 if (!serialnostr || strncmp (serialnostr, "D27600012401", 12)
2450 || strlen (serialnostr) != 32 )
2451 return G10ERR_GENERAL;
2453 /* First get the public keyring from any of the provided fingerprints. */
2454 if ( (fpr1 && !get_keyblock_byfprint (&pub_keyblock, fpr1, 20))
2455 || (fpr2 && !get_keyblock_byfprint (&pub_keyblock, fpr2, 20))
2456 || (fpr3 && !get_keyblock_byfprint (&pub_keyblock, fpr3, 20)))
2459 return G10ERR_GENERAL;
2463 /* Now check whether there is a secret keyring. */
2465 PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key;
2466 byte afp[MAX_FINGERPRINT_LEN];
2469 fingerprint_from_pk (pk, afp, &an);
2470 if (an < MAX_FINGERPRINT_LEN)
2471 memset (afp+an, 0, MAX_FINGERPRINT_LEN-an);
2472 rc = keydb_search_fpr (hd, afp);
2477 rc = keydb_get_keyblock (hd, &sec_keyblock);
2480 log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
2481 rc = G10ERR_GENERAL;
2485 merge_keys_and_selfsig (sec_keyblock);
2487 /* FIXME: We need to add new subkeys first. */
2488 if (update_sec_keyblock_with_cardinfo (sec_keyblock,
2492 rc = keydb_update_keyblock (hd, sec_keyblock );
2494 log_error (_("error writing keyring `%s': %s\n"),
2495 keydb_get_resource_name (hd), g10_errstr(rc) );
2499 else /* A secret key does not exists - create it. */
2501 sec_keyblock = pub_to_sec_keyblock (pub_keyblock);
2502 update_sec_keyblock_with_cardinfo (sec_keyblock,
2506 rc = keydb_locate_writable (hd, NULL);
2509 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
2510 rc = G10ERR_GENERAL;
2514 rc = keydb_insert_keyblock (hd, sec_keyblock );
2516 log_error (_("error writing keyring `%s': %s\n"),
2517 keydb_get_resource_name (hd), g10_errstr(rc) );
2521 release_kbnode (sec_keyblock);
2522 release_kbnode (pub_keyblock);