1 /* import.c - import a key into our key storage.
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006 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 2 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, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
41 #include "keyserver-internal.h"
54 ulong secret_imported;
56 ulong skipped_new_keys;
63 static int import( IOBUF inp, const char* fname,struct stats_s *stats,
64 unsigned char **fpr,size_t *fpr_len,unsigned int options );
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);
70 static int import_secret_one( const char *fname, KBNODE keyblock,
71 struct stats_s *stats, unsigned int options);
72 static int import_revoke_cert( const char *fname, KBNODE node,
73 struct stats_s *stats);
74 static int chk_self_sigs( const char *fname, KBNODE keyblock,
75 PKT_public_key *pk, u32 *keyid, int *non_self );
76 static int delete_inv_parts( const char *fname, KBNODE keyblock,
77 u32 *keyid, unsigned int options );
78 static int merge_blocks( const char *fname, KBNODE keyblock_orig,
79 KBNODE keyblock, u32 *keyid,
80 int *n_uids, int *n_sigs, int *n_subk );
81 static int append_uid( KBNODE keyblock, KBNODE node, int *n_sigs,
82 const char *fname, u32 *keyid );
83 static int append_key( KBNODE keyblock, KBNODE node, int *n_sigs,
84 const char *fname, u32 *keyid );
85 static int merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
86 const char *fname, u32 *keyid );
87 static int merge_keysigs( KBNODE dst, KBNODE src, int *n_sigs,
88 const char *fname, u32 *keyid );
91 parse_import_options(char *str,unsigned int *options,int noisy)
93 struct parse_options import_opts[]=
95 {"import-local-sigs",IMPORT_LOCAL_SIGS,NULL,
96 N_("import signatures that are marked as local-only")},
97 {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,
98 N_("repair damage from the pks keyserver during import")},
99 {"fast-import",IMPORT_FAST,NULL,
100 N_("do not update the trustdb after import")},
101 {"convert-sk-to-pk",IMPORT_SK2PK,NULL,
102 N_("create a public key when importing a secret key")},
103 {"merge-only",IMPORT_MERGE_ONLY,NULL,
104 N_("only accept updates to existing keys")},
105 {"import-clean",IMPORT_CLEAN,NULL,
106 N_("remove unusable parts from key after import")},
107 {"import-minimal",IMPORT_MINIMAL|IMPORT_CLEAN,NULL,
108 N_("remove as much as possible from key after import")},
109 /* Aliases for backward compatibility */
110 {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL},
111 {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL},
113 {"import-unusable-sigs",0,NULL,NULL},
114 {"import-clean-sigs",0,NULL,NULL},
115 {"import-clean-uids",0,NULL,NULL},
119 return parse_options(str,options,import_opts,noisy);
123 import_new_stats_handle (void)
125 return xmalloc_clear ( sizeof (struct stats_s) );
129 import_release_stats_handle (void *p)
135 * Import the public keys from the given filename. Input may be armored.
136 * This function rejects all keys which are not validly self signed on at
137 * least one userid. Only user ids which are self signed will be imported.
138 * Other signatures are not checked.
140 * Actually this function does a merge. It works like this:
143 * - check self-signatures and remove all userids and their signatures
144 * without/invalid self-signatures.
145 * - reject the keyblock, if we have no valid userid.
146 * - See whether we have this key already in one of our pubrings.
147 * If not, simply add it to the default keyring.
148 * - Compare the key and the self-signatures of the new and the one in
149 * our keyring. If they are different something weird is going on;
151 * - See whether we have only non-self-signature on one user id; if not
152 * ask the user what to do.
153 * - compare the signatures: If we already have this signature, check
154 * that they compare okay; if not, issue a warning and ask the user.
155 * (consider looking at the timestamp and use the newest?)
156 * - Simply add the signature. Can't verify here because we may not have
157 * the signature's public key yet; verification is done when putting it
158 * into the trustdb, which is done automagically as soon as this pubkey
160 * - Proceed with next signature.
162 * Key revocation certificates have special handling.
166 import_keys_internal( IOBUF inp, char **fnames, int nnames,
167 void *stats_handle, unsigned char **fpr, size_t *fpr_len,
168 unsigned int options )
171 struct stats_s *stats = stats_handle;
174 stats = import_new_stats_handle ();
177 rc = import( inp, "[stream]", stats, fpr, fpr_len, options);
180 if( !fnames && !nnames )
181 nnames = 1; /* Ohh what a ugly hack to jump into the loop */
183 for(i=0; i < nnames; i++ ) {
184 const char *fname = fnames? fnames[i] : NULL;
185 IOBUF inp2 = iobuf_open(fname);
188 if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
195 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
198 rc = import( inp2, fname, stats, fpr, fpr_len, options );
200 /* Must invalidate that ugly cache to actually close it. */
201 iobuf_ioctl (NULL, 2, 0, (char*)fname);
203 log_error("import from `%s' failed: %s\n", fname,
211 import_print_stats (stats);
212 import_release_stats_handle (stats);
215 /* If no fast import and the trustdb is dirty (i.e. we added a key
216 or userID that had something other than a selfsig, a signature
217 that was other than a selfsig, or any revocation), then
218 update/check the trustdb if the user specified by setting
219 interactive or by not setting no-auto-check-trustdb */
221 if(!(options&IMPORT_FAST))
222 trustdb_check_or_update();
228 import_keys( char **fnames, int nnames,
229 void *stats_handle, unsigned int options )
231 import_keys_internal(NULL,fnames,nnames,stats_handle,NULL,NULL,options);
235 import_keys_stream( IOBUF inp, void *stats_handle,
236 unsigned char **fpr, size_t *fpr_len,unsigned int options )
238 return import_keys_internal(inp,NULL,0,stats_handle,fpr,fpr_len,options);
242 import( IOBUF inp, const char* fname,struct stats_s *stats,
243 unsigned char **fpr,size_t *fpr_len,unsigned int options )
245 PACKET *pending_pkt = NULL;
249 getkey_disable_caches();
251 if( !opt.no_armor ) { /* armored reading is not disabled */
252 armor_filter_context_t *afx = xmalloc_clear( sizeof *afx );
253 afx->only_keyblocks = 1;
254 iobuf_push_filter2( inp, armor_filter, afx, 1 );
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 );
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 fprintf(stderr, " (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
521 print_import_ok (PKT_public_key *pk, PKT_secret_key *sk, unsigned int reason)
523 byte array[MAX_FINGERPRINT_LEN], *s;
524 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
527 sprintf (buf, "%u ", reason);
528 p = buf + strlen (buf);
531 fingerprint_from_pk (pk, array, &n);
533 fingerprint_from_sk (sk, array, &n);
535 for (i=0; i < n ; i++, s++, p += 2)
536 sprintf (p, "%02X", *s);
538 write_status_text (STATUS_IMPORT_OK, buf);
542 print_import_check (PKT_public_key * pk, PKT_user_id * id)
547 size_t i, pos = 0, n;
549 buf = xmalloc (17+41+id->len+32);
550 keyid_from_pk (pk, keyid);
551 sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
553 fingerprint_from_pk (pk, fpr, &n);
554 for (i = 0; i < n; i++, pos += 2)
555 sprintf (buf+pos, "%02X", fpr[i]);
558 strcat (buf, id->name);
559 write_status_text (STATUS_IMPORT_CHECK, buf);
564 check_prefs_warning(PKT_public_key *pk)
566 log_info(_("WARNING: key %s contains preferences for unavailable\n"),
568 log_info(_("algorithms on these user IDs:\n"));
572 check_prefs(KBNODE keyblock)
578 merge_keys_and_selfsig(keyblock);
579 pk=keyblock->pkt->pkt.public_key;
581 for(node=keyblock;node;node=node->next)
583 if(node->pkt->pkttype==PKT_USER_ID
584 && node->pkt->pkt.user_id->created
585 && node->pkt->pkt.user_id->prefs)
587 PKT_user_id *uid=node->pkt->pkt.user_id;
588 prefitem_t *prefs=uid->prefs;
589 char *user=utf8_to_native(uid->name,strlen(uid->name),0);
591 for(;prefs->type;prefs++)
593 char num[10]; /* prefs->value is a byte, so we're over
596 sprintf(num,"%u",prefs->value);
598 if(prefs->type==PREFTYPE_SYM)
600 if(check_cipher_algo(prefs->value))
602 const char *algo=cipher_algo_to_string(prefs->value);
604 check_prefs_warning(pk);
605 log_info(_(" \"%s\": preference for cipher"
606 " algorithm %s\n"),user,algo?algo:num);
610 else if(prefs->type==PREFTYPE_HASH)
612 if(check_digest_algo(prefs->value))
614 const char *algo=digest_algo_to_string(prefs->value);
616 check_prefs_warning(pk);
617 log_info(_(" \"%s\": preference for digest"
618 " algorithm %s\n"),user,algo?algo:num);
622 else if(prefs->type==PREFTYPE_ZIP)
624 if(check_compress_algo(prefs->value))
626 const char *algo=compress_algo_to_string(prefs->value);
628 check_prefs_warning(pk);
629 log_info(_(" \"%s\": preference for compression"
630 " algorithm %s\n"),user,algo?algo:num);
642 log_info(_("it is strongly suggested that you update"
643 " your preferences and\n"));
644 log_info(_("re-distribute this key to avoid potential algorithm"
645 " mismatch problems\n"));
649 STRLIST sl=NULL,locusr=NULL;
651 byte fpr[MAX_FINGERPRINT_LEN],*p;
652 char username[(MAX_FINGERPRINT_LEN*2)+1];
655 p=fingerprint_from_pk(pk,fpr,&fprlen);
656 for(i=0;i<fprlen;i++,p++)
657 sprintf(username+2*i,"%02X",*p);
658 add_to_strlist(&locusr,username);
660 append_to_strlist(&sl,"updpref");
661 append_to_strlist(&sl,"save");
663 keyedit_menu( username, locusr, sl, 1, 1 );
665 free_strlist(locusr);
668 log_info(_("you can update your preferences with:"
669 " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
674 * Try to import one keyblock. Return an error only in serious cases, but
675 * never for an invalid keyblock. It uses log_error to increase the
676 * internal errorcount, so that invalid input can be detected by programs
680 import_one( const char *fname, KBNODE keyblock, struct stats_s *stats,
681 unsigned char **fpr,size_t *fpr_len,unsigned int options )
684 PKT_public_key *pk_orig;
685 KBNODE node, uidnode;
686 KBNODE keyblock_orig = NULL;
693 /* get the key and print some info about it */
694 node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
698 pk = node->pkt->pkt.public_key;
701 *fpr=fingerprint_from_pk(pk,NULL,fpr_len);
703 keyid_from_pk( pk, keyid );
704 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
706 if( opt.verbose && !opt.interactive )
708 log_info( "pub %4u%c/%s %s ",
710 pubkey_letter( pk->pubkey_algo ),
711 keystr_from_pk(pk), datestr_from_pk(pk) );
713 print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
714 uidnode->pkt->pkt.user_id->len );
720 log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
724 if (opt.interactive) {
725 if(is_status_enabled())
726 print_import_check (pk, uidnode->pkt->pkt.user_id);
727 merge_keys_and_selfsig (keyblock);
729 show_basic_key_info (keyblock);
731 if (!cpr_get_answer_is_yes ("import.okay",
732 "Do you want to import this key? (y/N) "))
736 collapse_uids(&keyblock);
738 /* Clean the key that we're about to import, to cut down on things
739 that we have to clean later. This has no practical impact on
740 the end result, but does result in less logging which might
742 if(options&IMPORT_CLEAN)
743 clean_key(keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL);
745 clear_kbnode_flags( keyblock );
747 if((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
749 log_info(_("key %s: PKS subkey corruption repaired\n"),
752 rc = chk_self_sigs( fname, keyblock , pk, keyid, &non_self );
754 return rc== -1? 0:rc;
756 /* If we allow such a thing, mark unsigned uids as valid */
757 if( opt.allow_non_selfsigned_uid )
758 for( node=keyblock; node; node = node->next )
759 if( node->pkt->pkttype == PKT_USER_ID && !(node->flag & 1) )
761 char *user=utf8_to_native(node->pkt->pkt.user_id->name,
762 node->pkt->pkt.user_id->len,0);
764 log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
765 keystr_from_pk(pk),user);
769 if( !delete_inv_parts( fname, keyblock, keyid, options ) ) {
770 log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
772 log_info(_("this may be caused by a missing self-signature\n"));
777 /* do we have this key already in one of our pubrings ? */
778 pk_orig = xmalloc_clear( sizeof *pk_orig );
779 rc = get_pubkey_fast ( pk_orig, keyid );
780 if( rc && rc != G10ERR_NO_PUBKEY && rc != G10ERR_UNU_PUBKEY )
782 log_error( _("key %s: public key not found: %s\n"),
783 keystr(keyid), g10_errstr(rc));
785 else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) )
788 log_info( _("key %s: new key - skipped\n"), keystr(keyid));
790 stats->skipped_new_keys++;
792 else if( rc ) { /* insert this key */
793 KEYDB_HANDLE hd = keydb_new (0);
795 rc = keydb_locate_writable (hd, NULL);
797 log_error (_("no writable keyring found: %s\n"), g10_errstr (rc));
799 return G10ERR_GENERAL;
801 if( opt.verbose > 1 )
802 log_info (_("writing to `%s'\n"), keydb_get_resource_name (hd) );
804 rc = keydb_insert_keyblock (hd, keyblock );
806 log_error (_("error writing keyring `%s': %s\n"),
807 keydb_get_resource_name (hd), g10_errstr(rc));
810 /* This should not be possible since we delete the
811 ownertrust when a key is deleted, but it can happen if
812 the keyring and trustdb are out of sync. It can also
813 be made to happen with the trusted-key command. */
815 clear_ownertrusts (pk);
817 revalidation_mark ();
824 char *p=get_user_id_native (keyid);
825 log_info( _("key %s: public key \"%s\" imported\n"),
829 if( is_status_enabled() )
831 char *us = get_long_user_id_string( keyid );
832 write_status_text( STATUS_IMPORTED, us );
834 print_import_ok (pk,NULL, 1);
837 if( is_RSA( pk->pubkey_algo ) )
838 stats->imported_rsa++;
843 int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
845 /* Compare the original against the new key; just to be sure nothing
846 * weird is going on */
847 if( cmp_public_keys( pk_orig, pk ) )
849 log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
853 /* now read the original keyblock */
856 byte afp[MAX_FINGERPRINT_LEN];
859 fingerprint_from_pk (pk_orig, afp, &an);
860 while (an < MAX_FINGERPRINT_LEN)
862 rc = keydb_search_fpr (hd, afp);
866 log_error (_("key %s: can't locate original keyblock: %s\n"),
867 keystr(keyid), g10_errstr(rc));
871 rc = keydb_get_keyblock (hd, &keyblock_orig );
874 log_error (_("key %s: can't read original keyblock: %s\n"),
875 keystr(keyid), g10_errstr(rc));
880 /* and try to merge the block */
881 clear_kbnode_flags( keyblock_orig );
882 clear_kbnode_flags( keyblock );
883 n_uids = n_sigs = n_subk = n_sigs_cleaned = n_uids_cleaned = 0;
884 rc = merge_blocks( fname, keyblock_orig, keyblock,
885 keyid, &n_uids, &n_sigs, &n_subk );
892 if(options&IMPORT_CLEAN)
893 clean_key(keyblock_orig,opt.verbose,options&IMPORT_MINIMAL,
894 &n_uids_cleaned,&n_sigs_cleaned);
896 if( n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned) {
898 /* keyblock_orig has been updated; write */
899 rc = keydb_update_keyblock (hd, keyblock_orig);
901 log_error (_("error writing keyring `%s': %s\n"),
902 keydb_get_resource_name (hd), g10_errstr(rc) );
904 revalidation_mark ();
909 char *p=get_user_id_native(keyid);
911 log_info( _("key %s: \"%s\" 1 new user ID\n"),
914 log_info( _("key %s: \"%s\" %d new user IDs\n"),
915 keystr(keyid),p,n_uids);
917 log_info( _("key %s: \"%s\" 1 new signature\n"),
920 log_info( _("key %s: \"%s\" %d new signatures\n"),
921 keystr(keyid), p, n_sigs );
923 log_info( _("key %s: \"%s\" 1 new subkey\n"),
926 log_info( _("key %s: \"%s\" %d new subkeys\n"),
927 keystr(keyid), p, n_subk );
928 if(n_sigs_cleaned==1)
929 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
930 keystr(keyid),p,n_sigs_cleaned);
931 else if(n_sigs_cleaned)
932 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
933 keystr(keyid),p,n_sigs_cleaned);
934 if(n_uids_cleaned==1)
935 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
936 keystr(keyid),p,n_uids_cleaned);
937 else if(n_uids_cleaned)
938 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
939 keystr(keyid),p,n_uids_cleaned);
943 stats->n_uids +=n_uids;
944 stats->n_sigs +=n_sigs;
945 stats->n_subk +=n_subk;
946 stats->n_sigs_cleaned +=n_sigs_cleaned;
947 stats->n_uids_cleaned +=n_uids_cleaned;
949 if (is_status_enabled ())
950 print_import_ok (pk, NULL,
951 ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
955 if (is_status_enabled ())
956 print_import_ok (pk, NULL, 0);
960 char *p=get_user_id_native(keyid);
961 log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
968 keydb_release (hd); hd = NULL;
973 /* Now that the key is definitely incorporated into the keydb, we
974 need to check if a designated revocation is present or if the
975 prefs are not rational so we can warn the user. */
979 revocation_present(keyblock_orig);
980 if(seckey_available(keyid)==0)
981 check_prefs(keyblock_orig);
985 revocation_present(keyblock);
986 if(seckey_available(keyid)==0)
987 check_prefs(keyblock);
990 release_kbnode( keyblock_orig );
991 free_public_key( pk_orig );
996 /* Walk a secret keyblock and produce a public keyblock out of it. */
998 sec_to_pub_keyblock(KBNODE sec_keyblock)
1000 KBNODE secnode,pub_keyblock=NULL,ctx=NULL;
1002 while((secnode=walk_kbnode(sec_keyblock,&ctx,0)))
1006 if(secnode->pkt->pkttype==PKT_SECRET_KEY ||
1007 secnode->pkt->pkttype==PKT_SECRET_SUBKEY)
1009 /* Make a public key. We only need to convert enough to
1010 write the keyblock out. */
1012 PKT_secret_key *sk=secnode->pkt->pkt.secret_key;
1013 PACKET *pkt=xmalloc_clear(sizeof(PACKET));
1014 PKT_public_key *pk=xmalloc_clear(sizeof(PKT_public_key));
1017 if(secnode->pkt->pkttype==PKT_SECRET_KEY)
1018 pkt->pkttype=PKT_PUBLIC_KEY;
1020 pkt->pkttype=PKT_PUBLIC_SUBKEY;
1022 pkt->pkt.public_key=pk;
1024 pk->version=sk->version;
1025 pk->timestamp=sk->timestamp;
1026 pk->expiredate=sk->expiredate;
1027 pk->pubkey_algo=sk->pubkey_algo;
1029 n=pubkey_get_npkey(pk->pubkey_algo);
1032 /* we can't properly extract the pubkey without knowing
1033 the number of MPIs */
1034 release_kbnode(pub_keyblock);
1042 pk->pkey[i]=mpi_copy(sk->skey[i]);
1045 pubnode=new_kbnode(pkt);
1049 pubnode=clone_kbnode(secnode);
1052 if(pub_keyblock==NULL)
1053 pub_keyblock=pubnode;
1055 add_kbnode(pub_keyblock,pubnode);
1058 return pub_keyblock;
1062 * Ditto for secret keys. Handling is simpler than for public keys.
1063 * We allow secret key importing only when allow is true, this is so
1064 * that a secret key can not be imported accidently and thereby tampering
1065 * with the trust calculation.
1068 import_secret_one( const char *fname, KBNODE keyblock,
1069 struct stats_s *stats, unsigned int options)
1072 KBNODE node, uidnode;
1076 /* get the key and print some info about it */
1077 node = find_kbnode( keyblock, PKT_SECRET_KEY );
1081 sk = node->pkt->pkt.secret_key;
1082 keyid_from_sk( sk, keyid );
1083 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1087 log_info( "sec %4u%c/%s %s ",
1088 nbits_from_sk( sk ),
1089 pubkey_letter( sk->pubkey_algo ),
1090 keystr_from_sk(sk), datestr_from_sk(sk) );
1092 print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
1093 uidnode->pkt->pkt.user_id->len );
1096 stats->secret_read++;
1100 log_error( _("key %s: no user ID\n"), keystr_from_sk(sk));
1104 if(sk->protect.algo>110)
1106 log_error(_("key %s: secret key with invalid cipher %d"
1107 " - skipped\n"),keystr_from_sk(sk),sk->protect.algo);
1111 #ifdef ENABLE_SELINUX_HACKS
1114 /* We don't allow to import secret keys because that may be used
1115 to put a secret key into the keyring and the user might later
1116 be tricked into signing stuff with that key. */
1117 log_error (_("importing secret keys not allowed\n"));
1122 clear_kbnode_flags( keyblock );
1124 /* do we have this key already in one of our secrings ? */
1125 rc = seckey_available( keyid );
1126 if( rc == G10ERR_NO_SECKEY && !(opt.import_options&IMPORT_MERGE_ONLY) )
1128 /* simply insert this key */
1129 KEYDB_HANDLE hd = keydb_new (1);
1131 /* get default resource */
1132 rc = keydb_locate_writable (hd, NULL);
1134 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
1136 return G10ERR_GENERAL;
1138 rc = keydb_insert_keyblock (hd, keyblock );
1140 log_error (_("error writing keyring `%s': %s\n"),
1141 keydb_get_resource_name (hd), g10_errstr(rc) );
1145 log_info( _("key %s: secret key imported\n"), keystr_from_sk(sk));
1146 stats->secret_imported++;
1147 if (is_status_enabled ())
1148 print_import_ok (NULL, sk, 1|16);
1150 if(options&IMPORT_SK2PK)
1152 /* Try and make a public key out of this. */
1154 KBNODE pub_keyblock=sec_to_pub_keyblock(keyblock);
1157 import_one(fname,pub_keyblock,stats,
1158 NULL,NULL,opt.import_options);
1159 release_kbnode(pub_keyblock);
1163 /* Now that the key is definitely incorporated into the keydb,
1164 if we have the public part of this key, we need to check if
1165 the prefs are rational. */
1166 node=get_pubkeyblock(keyid);
1170 release_kbnode(node);
1174 { /* we can't merge secret keys */
1175 log_error( _("key %s: already in secret keyring\n"),
1176 keystr_from_sk(sk));
1177 stats->secret_dups++;
1178 if (is_status_enabled ())
1179 print_import_ok (NULL, sk, 16);
1181 /* TODO: if we ever do merge secret keys, make sure to handle
1182 the sec_to_pub_keyblock feature as well. */
1185 log_error( _("key %s: secret key not found: %s\n"),
1186 keystr_from_sk(sk), g10_errstr(rc));
1193 * Import a revocation certificate; this is a single signature packet.
1196 import_revoke_cert( const char *fname, KBNODE node, struct stats_s *stats )
1198 PKT_public_key *pk=NULL;
1199 KBNODE onode, keyblock = NULL;
1200 KEYDB_HANDLE hd = NULL;
1204 assert( !node->next );
1205 assert( node->pkt->pkttype == PKT_SIGNATURE );
1206 assert( node->pkt->pkt.signature->sig_class == 0x20 );
1208 keyid[0] = node->pkt->pkt.signature->keyid[0];
1209 keyid[1] = node->pkt->pkt.signature->keyid[1];
1211 pk = xmalloc_clear( sizeof *pk );
1212 rc = get_pubkey( pk, keyid );
1213 if( rc == G10ERR_NO_PUBKEY )
1215 log_error(_("key %s: no public key -"
1216 " can't apply revocation certificate\n"), keystr(keyid));
1222 log_error(_("key %s: public key not found: %s\n"),
1223 keystr(keyid), g10_errstr(rc));
1227 /* read the original keyblock */
1230 byte afp[MAX_FINGERPRINT_LEN];
1233 fingerprint_from_pk (pk, afp, &an);
1234 while (an < MAX_FINGERPRINT_LEN)
1236 rc = keydb_search_fpr (hd, afp);
1240 log_error (_("key %s: can't locate original keyblock: %s\n"),
1241 keystr(keyid), g10_errstr(rc));
1244 rc = keydb_get_keyblock (hd, &keyblock );
1247 log_error (_("key %s: can't read original keyblock: %s\n"),
1248 keystr(keyid), g10_errstr(rc));
1252 /* it is okay, that node is not in keyblock because
1253 * check_key_signature works fine for sig_class 0x20 in this
1255 rc = check_key_signature( keyblock, node, NULL);
1258 log_error( _("key %s: invalid revocation certificate"
1259 ": %s - rejected\n"), keystr(keyid), g10_errstr(rc));
1263 /* check whether we already have this */
1264 for(onode=keyblock->next; onode; onode=onode->next ) {
1265 if( onode->pkt->pkttype == PKT_USER_ID )
1267 else if( onode->pkt->pkttype == PKT_SIGNATURE
1268 && !cmp_signatures(node->pkt->pkt.signature,
1269 onode->pkt->pkt.signature))
1272 goto leave; /* yes, we already know about it */
1278 insert_kbnode( keyblock, clone_kbnode(node), 0 );
1280 /* and write the keyblock back */
1281 rc = keydb_update_keyblock (hd, keyblock );
1283 log_error (_("error writing keyring `%s': %s\n"),
1284 keydb_get_resource_name (hd), g10_errstr(rc) );
1285 keydb_release (hd); hd = NULL;
1289 char *p=get_user_id_native (keyid);
1290 log_info( _("key %s: \"%s\" revocation certificate imported\n"),
1296 /* If the key we just revoked was ultimately trusted, remove its
1297 ultimate trust. This doesn't stop the user from putting the
1298 ultimate trust back, but is a reasonable solution for now. */
1299 if(get_ownertrust(pk)==TRUST_ULTIMATE)
1300 clear_ownertrusts(pk);
1302 revalidation_mark ();
1306 release_kbnode( keyblock );
1307 free_public_key( pk );
1313 * loop over the keyblock and check all self signatures.
1314 * Mark all user-ids with a self-signature by setting flag bit 0.
1315 * Mark all user-ids with an invalid self-signature by setting bit 1.
1316 * This works also for subkeys, here the subkey is marked. Invalid or
1317 * extra subkey sigs (binding or revocation) are marked for deletion.
1318 * non_self is set to true if there are any sigs other than self-sigs
1322 chk_self_sigs( const char *fname, KBNODE keyblock,
1323 PKT_public_key *pk, u32 *keyid, int *non_self )
1325 KBNODE n,knode=NULL;
1328 u32 bsdate=0,rsdate=0;
1329 KBNODE bsnode=NULL,rsnode=NULL;
1331 for( n=keyblock; (n = find_next_kbnode(n, 0)); ) {
1332 if(n->pkt->pkttype==PKT_PUBLIC_SUBKEY)
1341 else if( n->pkt->pkttype != PKT_SIGNATURE )
1343 sig = n->pkt->pkt.signature;
1344 if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] ) {
1346 /* This just caches the sigs for later use. That way we
1347 import a fully-cached key which speeds things up. */
1348 if(!opt.no_sig_cache)
1349 check_key_signature(keyblock,n,NULL);
1351 if( IS_UID_SIG(sig) || IS_UID_REV(sig) )
1353 KBNODE unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
1356 log_error( _("key %s: no user ID for signature\n"),
1358 return -1; /* the complete keyblock is invalid */
1361 /* If it hasn't been marked valid yet, keep trying */
1362 if(!(unode->flag&1)) {
1363 rc = check_key_signature( keyblock, n, NULL);
1368 char *p=utf8_to_native(unode->pkt->pkt.user_id->name,
1369 strlen(unode->pkt->pkt.user_id->name),0);
1370 log_info( rc == G10ERR_PUBKEY_ALGO ?
1371 _("key %s: unsupported public key "
1372 "algorithm on user ID \"%s\"\n"):
1373 _("key %s: invalid self-signature "
1374 "on user ID \"%s\"\n"),
1380 unode->flag |= 1; /* mark that signature checked */
1383 else if( sig->sig_class == 0x18 ) {
1384 /* Note that this works based solely on the timestamps
1385 like the rest of gpg. If the standard gets
1386 revocation targets, this may need to be revised. */
1391 log_info( _("key %s: no subkey for key binding\n"),
1393 n->flag |= 4; /* delete this */
1397 rc = check_key_signature( keyblock, n, NULL);
1401 log_info(rc == G10ERR_PUBKEY_ALGO ?
1402 _("key %s: unsupported public key"
1404 _("key %s: invalid subkey binding\n"),
1410 /* It's valid, so is it newer? */
1411 if(sig->timestamp>=bsdate) {
1412 knode->flag |= 1; /* the subkey is valid */
1415 bsnode->flag|=4; /* Delete the last binding
1416 sig since this one is
1419 log_info(_("key %s: removed multiple subkey"
1420 " binding\n"),keystr(keyid));
1424 bsdate=sig->timestamp;
1427 n->flag|=4; /* older */
1431 else if( sig->sig_class == 0x28 ) {
1432 /* We don't actually mark the subkey as revoked right
1433 now, so just check that the revocation sig is the
1434 most recent valid one. Note that we don't care if
1435 the binding sig is newer than the revocation sig.
1436 See the comment in getkey.c:merge_selfsigs_subkey for
1441 log_info( _("key %s: no subkey for key revocation\n"),
1443 n->flag |= 4; /* delete this */
1447 rc = check_key_signature( keyblock, n, NULL);
1451 log_info(rc == G10ERR_PUBKEY_ALGO ?
1452 _("key %s: unsupported public"
1453 " key algorithm\n"):
1454 _("key %s: invalid subkey revocation\n"),
1460 /* It's valid, so is it newer? */
1461 if(sig->timestamp>=rsdate)
1465 rsnode->flag|=4; /* Delete the last revocation
1466 sig since this one is
1469 log_info(_("key %s: removed multiple subkey"
1470 " revocation\n"),keystr(keyid));
1474 rsdate=sig->timestamp;
1477 n->flag|=4; /* older */
1490 * delete all parts which are invalid and those signatures whose
1491 * public key algorithm is not available in this implemenation;
1492 * but consider RSA as valid, because parse/build_packets knows
1494 * returns: true if at least one valid user-id is left over.
1497 delete_inv_parts( const char *fname, KBNODE keyblock,
1498 u32 *keyid, unsigned int options)
1501 int nvalid=0, uid_seen=0, subkey_seen=0;
1503 for(node=keyblock->next; node; node = node->next ) {
1504 if( node->pkt->pkttype == PKT_USER_ID ) {
1506 if( (node->flag & 2) || !(node->flag & 1) ) {
1509 char *p=utf8_to_native(node->pkt->pkt.user_id->name,
1510 node->pkt->pkt.user_id->len,0);
1511 log_info( _("key %s: skipped user ID \"%s\"\n"),
1515 delete_kbnode( node ); /* the user-id */
1516 /* and all following packets up to the next user-id */
1518 && node->next->pkt->pkttype != PKT_USER_ID
1519 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1520 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
1521 delete_kbnode( node->next );
1528 else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1529 || node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1530 if( (node->flag & 2) || !(node->flag & 1) ) {
1532 log_info( _("key %s: skipped subkey\n"),keystr(keyid));
1534 delete_kbnode( node ); /* the subkey */
1535 /* and all following signature packets */
1537 && node->next->pkt->pkttype == PKT_SIGNATURE ) {
1538 delete_kbnode( node->next );
1545 else if( node->pkt->pkttype == PKT_SIGNATURE
1546 && check_pubkey_algo( node->pkt->pkt.signature->pubkey_algo)
1547 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
1548 delete_kbnode( node ); /* build_packet() can't handle this */
1549 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1550 !node->pkt->pkt.signature->flags.exportable &&
1551 !(options&IMPORT_LOCAL_SIGS) &&
1552 seckey_available( node->pkt->pkt.signature->keyid ) )
1554 /* here we violate the rfc a bit by still allowing
1555 * to import non-exportable signature when we have the
1556 * the secret key used to create this signature - it
1557 * seems that this makes sense */
1559 log_info( _("key %s: non exportable signature"
1560 " (class 0x%02X) - skipped\n"),
1561 keystr(keyid), node->pkt->pkt.signature->sig_class );
1562 delete_kbnode( node );
1564 else if( node->pkt->pkttype == PKT_SIGNATURE
1565 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1569 log_info( _("key %s: revocation certificate"
1570 " at wrong place - skipped\n"),keystr(keyid));
1571 delete_kbnode( node );
1574 /* If the revocation cert is from a different key than
1575 the one we're working on don't check it - it's
1576 probably from a revocation key and won't be
1577 verifiable with this key anyway. */
1579 if(node->pkt->pkt.signature->keyid[0]==keyid[0] &&
1580 node->pkt->pkt.signature->keyid[1]==keyid[1])
1582 int rc = check_key_signature( keyblock, node, NULL);
1586 log_info( _("key %s: invalid revocation"
1587 " certificate: %s - skipped\n"),
1588 keystr(keyid), g10_errstr(rc));
1589 delete_kbnode( node );
1594 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1595 (node->pkt->pkt.signature->sig_class == 0x18 ||
1596 node->pkt->pkt.signature->sig_class == 0x28) &&
1600 log_info( _("key %s: subkey signature"
1601 " in wrong place - skipped\n"), keystr(keyid));
1602 delete_kbnode( node );
1604 else if( node->pkt->pkttype == PKT_SIGNATURE
1605 && !IS_CERT(node->pkt->pkt.signature))
1608 log_info(_("key %s: unexpected signature class (0x%02X) -"
1609 " skipped\n"),keystr(keyid),
1610 node->pkt->pkt.signature->sig_class);
1611 delete_kbnode(node);
1613 else if( (node->flag & 4) ) /* marked for deletion */
1614 delete_kbnode( node );
1617 /* note: because keyblock is the public key, it is never marked
1618 * for deletion and so keyblock cannot change */
1619 commit_kbnode( &keyblock );
1625 * It may happen that the imported keyblock has duplicated user IDs.
1626 * We check this here and collapse those user IDs together with their
1628 * Returns: True if the keyblock hash changed.
1631 collapse_uids( KBNODE *keyblock )
1638 for( n = *keyblock; n; n = n->next ) {
1639 if( n->pkt->pkttype != PKT_USER_ID )
1641 for( n2 = n->next; n2; n2 = n2->next ) {
1642 if( n2->pkt->pkttype == PKT_USER_ID
1643 && !cmp_user_ids( n->pkt->pkt.user_id,
1644 n2->pkt->pkt.user_id ) ) {
1645 /* found a duplicate */
1648 || n2->next->pkt->pkttype == PKT_USER_ID
1649 || n2->next->pkt->pkttype == PKT_PUBLIC_SUBKEY
1650 || n2->next->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1651 /* no more signatures: delete the user ID
1653 remove_kbnode( keyblock, n2 );
1656 /* The simple approach: Move one signature and
1657 * then start over to delete the next one :-( */
1658 move_kbnode( keyblock, n2->next, n->next );
1668 /* now we may have duplicate signatures on one user ID: fix this */
1669 for( in_uid = 0, n = *keyblock; n; n = n->next ) {
1670 if( n->pkt->pkttype == PKT_USER_ID )
1672 else if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
1673 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
1679 for( ; n2; n2 = n2->next ) {
1680 if( n2->pkt->pkttype == PKT_USER_ID
1681 || n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
1682 || n2->pkt->pkttype == PKT_SECRET_SUBKEY )
1684 if( n2->pkt->pkttype != PKT_SIGNATURE )
1688 else if( !cmp_signatures( ncmp->pkt->pkt.signature,
1689 n2->pkt->pkt.signature )) {
1690 remove_kbnode( keyblock, n2 );
1694 n2 = ncmp? ncmp->next : NULL;
1701 const char *key="???";
1703 if( (n = find_kbnode( *keyblock, PKT_PUBLIC_KEY )) )
1704 key=keystr_from_pk(n->pkt->pkt.public_key);
1705 else if( (n = find_kbnode( *keyblock, PKT_SECRET_KEY )) )
1706 key=keystr_from_sk(n->pkt->pkt.secret_key);
1708 log_info(_("key %s: duplicated user ID detected - merged\n"),key);
1714 /* Check for a 0x20 revocation from a revocation key that is not
1715 present. This may be called without the benefit of merge_xxxx so
1716 you can't rely on pk->revkey and friends. */
1718 revocation_present(KBNODE keyblock)
1721 PKT_public_key *pk=keyblock->pkt->pkt.public_key;
1723 for(onode=keyblock->next;onode;onode=onode->next)
1725 /* If we reach user IDs, we're done. */
1726 if(onode->pkt->pkttype==PKT_USER_ID)
1729 if(onode->pkt->pkttype==PKT_SIGNATURE &&
1730 onode->pkt->pkt.signature->sig_class==0x1F &&
1731 onode->pkt->pkt.signature->revkey)
1734 PKT_signature *sig=onode->pkt->pkt.signature;
1736 for(idx=0;idx<sig->numrevkeys;idx++)
1740 keyid_from_fingerprint(sig->revkey[idx]->fpr,
1741 MAX_FINGERPRINT_LEN,keyid);
1743 for(inode=keyblock->next;inode;inode=inode->next)
1745 /* If we reach user IDs, we're done. */
1746 if(inode->pkt->pkttype==PKT_USER_ID)
1749 if(inode->pkt->pkttype==PKT_SIGNATURE &&
1750 inode->pkt->pkt.signature->sig_class==0x20 &&
1751 inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
1752 inode->pkt->pkt.signature->keyid[1]==keyid[1])
1754 /* Okay, we have a revocation key, and a
1755 revocation issued by it. Do we have the key
1759 rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx]->fpr,
1760 MAX_FINGERPRINT_LEN);
1761 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1763 char *tempkeystr=xstrdup(keystr_from_pk(pk));
1765 /* No, so try and get it */
1767 && (opt.keyserver_options.options
1768 & KEYSERVER_AUTO_KEY_RETRIEVE))
1770 log_info(_("WARNING: key %s may be revoked:"
1771 " fetching revocation key %s\n"),
1772 tempkeystr,keystr(keyid));
1773 keyserver_import_fprint(sig->revkey[idx]->fpr,
1774 MAX_FINGERPRINT_LEN,
1777 /* Do we have it now? */
1778 rc=get_pubkey_byfprint_fast (NULL,
1779 sig->revkey[idx]->fpr,
1780 MAX_FINGERPRINT_LEN);
1783 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1784 log_info(_("WARNING: key %s may be revoked:"
1785 " revocation key %s not present.\n"),
1786 tempkeystr,keystr(keyid));
1798 * compare and merge the blocks
1800 * o compare the signatures: If we already have this signature, check
1801 * that they compare okay; if not, issue a warning and ask the user.
1802 * o Simply add the signature. Can't verify here because we may not have
1803 * the signature's public key yet; verification is done when putting it
1804 * into the trustdb, which is done automagically as soon as this pubkey
1806 * Note: We indicate newly inserted packets with flag bit 0
1809 merge_blocks( const char *fname, KBNODE keyblock_orig, KBNODE keyblock,
1810 u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
1815 /* 1st: handle revocation certificates */
1816 for(node=keyblock->next; node; node=node->next ) {
1817 if( node->pkt->pkttype == PKT_USER_ID )
1819 else if( node->pkt->pkttype == PKT_SIGNATURE
1820 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1821 /* check whether we already have this */
1823 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1824 if( onode->pkt->pkttype == PKT_USER_ID )
1826 else if( onode->pkt->pkttype == PKT_SIGNATURE
1827 && onode->pkt->pkt.signature->sig_class == 0x20
1828 && !cmp_signatures(onode->pkt->pkt.signature,
1829 node->pkt->pkt.signature))
1836 KBNODE n2 = clone_kbnode(node);
1837 insert_kbnode( keyblock_orig, n2, 0 );
1842 char *p=get_user_id_native (keyid);
1843 log_info(_("key %s: \"%s\" revocation"
1844 " certificate added\n"), keystr(keyid),p);
1851 /* 2nd: merge in any direct key (0x1F) sigs */
1852 for(node=keyblock->next; node; node=node->next ) {
1853 if( node->pkt->pkttype == PKT_USER_ID )
1855 else if( node->pkt->pkttype == PKT_SIGNATURE
1856 && node->pkt->pkt.signature->sig_class == 0x1F ) {
1857 /* check whether we already have this */
1859 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1860 if( onode->pkt->pkttype == PKT_USER_ID )
1862 else if( onode->pkt->pkttype == PKT_SIGNATURE
1863 && onode->pkt->pkt.signature->sig_class == 0x1F
1864 && !cmp_signatures(onode->pkt->pkt.signature,
1865 node->pkt->pkt.signature)) {
1872 KBNODE n2 = clone_kbnode(node);
1873 insert_kbnode( keyblock_orig, n2, 0 );
1877 log_info( _("key %s: direct key signature added\n"),
1883 /* 3rd: try to merge new certificates in */
1884 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1885 if( !(onode->flag & 1) && onode->pkt->pkttype == PKT_USER_ID) {
1886 /* find the user id in the imported keyblock */
1887 for(node=keyblock->next; node; node=node->next )
1888 if( node->pkt->pkttype == PKT_USER_ID
1889 && !cmp_user_ids( onode->pkt->pkt.user_id,
1890 node->pkt->pkt.user_id ) )
1892 if( node ) { /* found: merge */
1893 rc = merge_sigs( onode, node, n_sigs, fname, keyid );
1900 /* 4th: add new user-ids */
1901 for(node=keyblock->next; node; node=node->next ) {
1902 if( node->pkt->pkttype == PKT_USER_ID) {
1903 /* do we have this in the original keyblock */
1904 for(onode=keyblock_orig->next; onode; onode=onode->next )
1905 if( onode->pkt->pkttype == PKT_USER_ID
1906 && !cmp_user_ids( onode->pkt->pkt.user_id,
1907 node->pkt->pkt.user_id ) )
1909 if( !onode ) { /* this is a new user id: append */
1910 rc = append_uid( keyblock_orig, node, n_sigs, fname, keyid);
1918 /* 5th: add new subkeys */
1919 for(node=keyblock->next; node; node=node->next ) {
1921 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1922 /* do we have this in the original keyblock? */
1923 for(onode=keyblock_orig->next; onode; onode=onode->next )
1924 if( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
1925 && !cmp_public_keys( onode->pkt->pkt.public_key,
1926 node->pkt->pkt.public_key ) )
1928 if( !onode ) { /* this is a new subkey: append */
1929 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
1935 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1936 /* do we have this in the original keyblock? */
1937 for(onode=keyblock_orig->next; onode; onode=onode->next )
1938 if( onode->pkt->pkttype == PKT_SECRET_SUBKEY
1939 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
1940 node->pkt->pkt.secret_key ) )
1942 if( !onode ) { /* this is a new subkey: append */
1943 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
1951 /* 6th: merge subkey certificates */
1952 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1953 if( !(onode->flag & 1)
1954 && ( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
1955 || onode->pkt->pkttype == PKT_SECRET_SUBKEY) ) {
1956 /* find the subkey in the imported keyblock */
1957 for(node=keyblock->next; node; node=node->next ) {
1958 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1959 && !cmp_public_keys( onode->pkt->pkt.public_key,
1960 node->pkt->pkt.public_key ) )
1962 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY
1963 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
1964 node->pkt->pkt.secret_key ) )
1967 if( node ) { /* found: merge */
1968 rc = merge_keysigs( onode, node, n_sigs, fname, keyid );
1981 * append the userid starting with NODE and all signatures to KEYBLOCK.
1984 append_uid( KBNODE keyblock, KBNODE node, int *n_sigs,
1985 const char *fname, u32 *keyid )
1987 KBNODE n, n_where=NULL;
1989 assert(node->pkt->pkttype == PKT_USER_ID );
1991 /* find the position */
1992 for( n = keyblock; n; n_where = n, n = n->next ) {
1993 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
1994 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
2000 /* and append/insert */
2002 /* we add a clone to the original keyblock, because this
2003 * one is released first */
2004 n = clone_kbnode(node);
2006 insert_kbnode( n_where, n, 0 );
2010 add_kbnode( keyblock, n );
2013 if( n->pkt->pkttype == PKT_SIGNATURE )
2017 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2026 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
2027 * (how should we handle comment packets here?)
2030 merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
2031 const char *fname, u32 *keyid )
2036 assert(dst->pkt->pkttype == PKT_USER_ID );
2037 assert(src->pkt->pkttype == PKT_USER_ID );
2039 for(n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next ) {
2040 if( n->pkt->pkttype != PKT_SIGNATURE )
2042 if( n->pkt->pkt.signature->sig_class == 0x18
2043 || n->pkt->pkt.signature->sig_class == 0x28 )
2044 continue; /* skip signatures which are only valid on subkeys */
2046 for(n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
2047 if(!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
2053 /* This signature is new or newer, append N to DST.
2054 * We add a clone to the original keyblock, because this
2055 * one is released first */
2056 n2 = clone_kbnode(n);
2057 insert_kbnode( dst, n2, PKT_SIGNATURE );
2068 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
2071 merge_keysigs( KBNODE dst, KBNODE src, int *n_sigs,
2072 const char *fname, u32 *keyid )
2077 assert( dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
2078 || dst->pkt->pkttype == PKT_SECRET_SUBKEY );
2080 for(n=src->next; n ; n = n->next ) {
2081 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2082 || n->pkt->pkttype == PKT_PUBLIC_KEY )
2084 if( n->pkt->pkttype != PKT_SIGNATURE )
2087 for(n2=dst->next; n2; n2 = n2->next){
2088 if( n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
2089 || n2->pkt->pkttype == PKT_PUBLIC_KEY )
2091 if( n2->pkt->pkttype == PKT_SIGNATURE
2092 && n->pkt->pkt.signature->keyid[0]
2093 == n2->pkt->pkt.signature->keyid[0]
2094 && n->pkt->pkt.signature->keyid[1]
2095 == n2->pkt->pkt.signature->keyid[1]
2096 && n->pkt->pkt.signature->timestamp
2097 <= n2->pkt->pkt.signature->timestamp
2098 && n->pkt->pkt.signature->sig_class
2099 == n2->pkt->pkt.signature->sig_class ) {
2105 /* This signature is new or newer, append N to DST.
2106 * We add a clone to the original keyblock, because this
2107 * one is released first */
2108 n2 = clone_kbnode(n);
2109 insert_kbnode( dst, n2, PKT_SIGNATURE );
2120 * append the subkey starting with NODE and all signatures to KEYBLOCK.
2121 * Mark all new and copied packets by setting flag bit 0.
2124 append_key( KBNODE keyblock, KBNODE node, int *n_sigs,
2125 const char *fname, u32 *keyid )
2129 assert( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2130 || node->pkt->pkttype == PKT_SECRET_SUBKEY );
2133 /* we add a clone to the original keyblock, because this
2134 * one is released first */
2135 n = clone_kbnode(node);
2136 add_kbnode( keyblock, n );
2139 if( n->pkt->pkttype == PKT_SIGNATURE )
2143 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2152 /* Walk a public keyblock and produce a secret keyblock out of it.
2153 Instead of inserting the secret key parameters (which we don't
2154 have), we insert a stub. */
2156 pub_to_sec_keyblock (KBNODE pub_keyblock)
2158 KBNODE pubnode, secnode;
2159 KBNODE sec_keyblock = NULL;
2160 KBNODE walkctx = NULL;
2162 while((pubnode = walk_kbnode (pub_keyblock,&walkctx,0)))
2164 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY
2165 || pubnode->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2167 /* Make a secret key. We only need to convert enough to
2168 write the keyblock out. */
2169 PKT_public_key *pk = pubnode->pkt->pkt.public_key;
2170 PACKET *pkt = xmalloc_clear (sizeof *pkt);
2171 PKT_secret_key *sk = xmalloc_clear (sizeof *sk);
2174 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY)
2175 pkt->pkttype = PKT_SECRET_KEY;
2177 pkt->pkttype = PKT_SECRET_SUBKEY;
2179 pkt->pkt.secret_key = sk;
2181 copy_public_parts_to_secret_key ( pk, sk );
2182 sk->version = pk->version;
2183 sk->timestamp = pk->timestamp;
2185 n = pubkey_get_npkey (pk->pubkey_algo);
2187 n = 1; /* Unknown number of parameters, however the data
2188 is stored in the first mpi. */
2189 for (i=0; i < n; i++ )
2190 sk->skey[i] = mpi_copy (pk->pkey[i]);
2192 sk->is_protected = 1;
2193 sk->protect.s2k.mode = 1001;
2195 secnode = new_kbnode (pkt);
2199 secnode = clone_kbnode (pubnode);
2203 sec_keyblock = secnode;
2205 add_kbnode (sec_keyblock, secnode);
2208 return sec_keyblock;
2212 /* Walk over the secret keyring SEC_KEYBLOCK and update any simple
2213 stub keys with the serial number SNNUM of the card if one of the
2214 fingerprints FPR1, FPR2 or FPR3 match. Print a note if the key is
2215 a duplicate (may happen in case of backed uped keys).
2217 Returns: True if anything changed.
2220 update_sec_keyblock_with_cardinfo (KBNODE sec_keyblock,
2221 const unsigned char *fpr1,
2222 const unsigned char *fpr2,
2223 const unsigned char *fpr3,
2224 const char *serialnostr)
2227 KBNODE walkctx = NULL;
2229 byte array[MAX_FINGERPRINT_LEN];
2234 while((node = walk_kbnode (sec_keyblock, &walkctx, 0)))
2236 if (node->pkt->pkttype != PKT_SECRET_KEY
2237 && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2239 sk = node->pkt->pkt.secret_key;
2241 fingerprint_from_sk (sk, array, &n);
2243 continue; /* Can't be a card key. */
2244 if ( !((fpr1 && !memcmp (array, fpr1, 20))
2245 || (fpr2 && !memcmp (array, fpr2, 20))
2246 || (fpr3 && !memcmp (array, fpr3, 20))) )
2247 continue; /* No match. */
2249 if (sk->is_protected == 1 && sk->protect.s2k.mode == 1001)
2251 /* Standard case: migrate that stub to a key stub. */
2252 sk->protect.s2k.mode = 1002;
2254 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2255 sk->protect.ivlen++, s += 2)
2256 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
2259 else if (sk->is_protected == 1 && sk->protect.s2k.mode == 1002)
2262 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2263 sk->protect.ivlen++, s += 2)
2264 if (sk->protect.iv[sk->protect.ivlen] != xtoi_2 (s))
2266 log_info (_("NOTE: a key's S/N does not "
2267 "match the card's one\n"));
2273 if (node->pkt->pkttype != PKT_SECRET_KEY)
2274 log_info (_("NOTE: primary key is online and stored on card\n"));
2276 log_info (_("NOTE: secondary key is online and stored on card\n"));
2285 /* Check whether a secret key stub exists for the public key PK. If
2286 not create such a stub key and store it into the secring. If it
2287 exists, add appropriate subkey stubs and update the secring.
2288 Return 0 if the key could be created. */
2290 auto_create_card_key_stub ( const char *serialnostr,
2291 const unsigned char *fpr1,
2292 const unsigned char *fpr2,
2293 const unsigned char *fpr3)
2295 KBNODE pub_keyblock;
2296 KBNODE sec_keyblock;
2300 /* We only want to do this for an OpenPGP card. */
2301 if (!serialnostr || strncmp (serialnostr, "D27600012401", 12)
2302 || strlen (serialnostr) != 32 )
2303 return G10ERR_GENERAL;
2305 /* First get the public keyring from any of the provided fingerprints. */
2306 if ( (fpr1 && !get_keyblock_byfprint (&pub_keyblock, fpr1, 20))
2307 || (fpr2 && !get_keyblock_byfprint (&pub_keyblock, fpr2, 20))
2308 || (fpr3 && !get_keyblock_byfprint (&pub_keyblock, fpr3, 20)))
2311 return G10ERR_GENERAL;
2315 /* Now check whether there is a secret keyring. */
2317 PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key;
2318 byte afp[MAX_FINGERPRINT_LEN];
2321 fingerprint_from_pk (pk, afp, &an);
2322 memset (afp, 0, MAX_FINGERPRINT_LEN);
2323 rc = keydb_search_fpr (hd, afp);
2328 rc = keydb_get_keyblock (hd, &sec_keyblock);
2331 log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
2332 rc = G10ERR_GENERAL;
2336 merge_keys_and_selfsig (sec_keyblock);
2338 /* FIXME: We need to add new subkeys first. */
2339 if (update_sec_keyblock_with_cardinfo (sec_keyblock,
2343 rc = keydb_update_keyblock (hd, sec_keyblock );
2345 log_error (_("error writing keyring `%s': %s\n"),
2346 keydb_get_resource_name (hd), g10_errstr(rc) );
2350 else /* A secret key does not exists - create it. */
2352 sec_keyblock = pub_to_sec_keyblock (pub_keyblock);
2353 update_sec_keyblock_with_cardinfo (sec_keyblock,
2357 rc = keydb_locate_writable (hd, NULL);
2360 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
2361 rc = G10ERR_GENERAL;
2365 rc = keydb_insert_keyblock (hd, sec_keyblock );
2367 log_error (_("error writing keyring `%s': %s\n"),
2368 keydb_get_resource_name (hd), g10_errstr(rc) );
2372 release_kbnode (sec_keyblock);
2373 release_kbnode (pub_keyblock);