Better reset the PIN verification stati after changing the key attributes.
[gnupg.git] / g10 / import.c
blob88eb24e57d7701fbeedd072ac989e6e460050ef0
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/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <assert.h>
28 #include "gpg.h"
29 #include "options.h"
30 #include "packet.h"
31 #include "status.h"
32 #include "keydb.h"
33 #include "util.h"
34 #include "trustdb.h"
35 #include "main.h"
36 #include "i18n.h"
37 #include "ttyio.h"
38 #include "status.h"
39 #include "keyserver-internal.h"
41 struct stats_s {
42 ulong count;
43 ulong no_user_id;
44 ulong imported;
45 ulong imported_rsa;
46 ulong n_uids;
47 ulong n_sigs;
48 ulong n_subk;
49 ulong unchanged;
50 ulong n_revoc;
51 ulong secret_read;
52 ulong secret_imported;
53 ulong secret_dups;
54 ulong skipped_new_keys;
55 ulong not_imported;
56 ulong n_sigs_cleaned;
57 ulong n_uids_cleaned;
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 );
88 int
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},
110 /* dummy */
111 {"import-unusable-sigs",0,NULL,NULL},
112 {"import-clean-sigs",0,NULL,NULL},
113 {"import-clean-uids",0,NULL,NULL},
114 {NULL,0,NULL,NULL}
117 return parse_options(str,options,import_opts,noisy);
120 void *
121 import_new_stats_handle (void)
123 return xmalloc_clear ( sizeof (struct stats_s) );
126 void
127 import_release_stats_handle (void *p)
129 xfree (p);
132 /****************
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:
140 * - get the keyblock
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;
148 * ask what to do.
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
157 * is used.
158 * - Proceed with next signature.
160 * Key revocation certificates have special handling.
163 static int
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 )
168 int i, rc = 0;
169 struct stats_s *stats = stats_handle;
171 if (!stats)
172 stats = import_new_stats_handle ();
174 if (inp) {
175 rc = import( inp, "[stream]", stats, fpr, fpr_len, options);
177 else {
178 if( !fnames && !nnames )
179 nnames = 1; /* Ohh what a ugly hack to jump into the loop */
181 for(i=0; i < nnames; i++ ) {
182 const char *fname = fnames? fnames[i] : NULL;
183 IOBUF inp2 = iobuf_open(fname);
184 if( !fname )
185 fname = "[stdin]";
186 if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
188 iobuf_close (inp2);
189 inp2 = NULL;
190 errno = EPERM;
192 if( !inp2 )
193 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
194 else
196 rc = import( inp2, fname, stats, fpr, fpr_len, options );
197 iobuf_close(inp2);
198 /* Must invalidate that ugly cache to actually close it. */
199 iobuf_ioctl (NULL, 2, 0, (char*)fname);
200 if( rc )
201 log_error("import from `%s' failed: %s\n", fname,
202 g10_errstr(rc) );
204 if( !fname )
205 break;
208 if (!stats_handle) {
209 import_print_stats (stats);
210 import_release_stats_handle (stats);
213 /* If no fast import and the trustdb is dirty (i.e. we added a key
214 or userID that had something other than a selfsig, a signature
215 that was other than a selfsig, or any revocation), then
216 update/check the trustdb if the user specified by setting
217 interactive or by not setting no-auto-check-trustdb */
219 if(!(options&IMPORT_FAST))
220 trustdb_check_or_update();
222 return rc;
225 void
226 import_keys( char **fnames, int nnames,
227 void *stats_handle, unsigned int options )
229 import_keys_internal(NULL,fnames,nnames,stats_handle,NULL,NULL,options);
233 import_keys_stream( IOBUF inp, void *stats_handle,
234 unsigned char **fpr, size_t *fpr_len,unsigned int options )
236 return import_keys_internal(inp,NULL,0,stats_handle,fpr,fpr_len,options);
239 static int
240 import( IOBUF inp, const char* fname,struct stats_s *stats,
241 unsigned char **fpr,size_t *fpr_len,unsigned int options )
243 PACKET *pending_pkt = NULL;
244 KBNODE keyblock = NULL; /* Need to initialize because gcc can't
245 grasp the return semantics of
246 read_block. */
247 int rc = 0;
249 getkey_disable_caches();
251 if( !opt.no_armor ) { /* armored reading is not disabled */
252 armor_filter_context_t *afx;
254 afx = new_armor_context ();
255 afx->only_keyblocks = 1;
256 push_armor_filter (afx, inp);
257 release_armor_context (afx);
260 while( !(rc = read_block( inp, &pending_pkt, &keyblock) )) {
261 if( keyblock->pkt->pkttype == PKT_PUBLIC_KEY )
262 rc = import_one( fname, keyblock, stats, fpr, fpr_len, options, 0);
263 else if( keyblock->pkt->pkttype == PKT_SECRET_KEY )
264 rc = import_secret_one( fname, keyblock, stats, options );
265 else if( keyblock->pkt->pkttype == PKT_SIGNATURE
266 && keyblock->pkt->pkt.signature->sig_class == 0x20 )
267 rc = import_revoke_cert( fname, keyblock, stats );
268 else {
269 log_info( _("skipping block of type %d\n"),
270 keyblock->pkt->pkttype );
272 release_kbnode(keyblock);
273 /* fixme: we should increment the not imported counter but this
274 does only make sense if we keep on going despite of errors. */
275 if( rc )
276 break;
277 if( !(++stats->count % 100) && !opt.quiet )
278 log_info(_("%lu keys processed so far\n"), stats->count );
280 if( rc == -1 )
281 rc = 0;
282 else if( rc && rc != G10ERR_INV_KEYRING )
283 log_error( _("error reading `%s': %s\n"), fname, g10_errstr(rc));
285 return rc;
289 void
290 import_print_stats (void *hd)
292 struct stats_s *stats = hd;
294 if( !opt.quiet ) {
295 log_info(_("Total number processed: %lu\n"), stats->count );
296 if( stats->skipped_new_keys )
297 log_info(_(" skipped new keys: %lu\n"),
298 stats->skipped_new_keys );
299 if( stats->no_user_id )
300 log_info(_(" w/o user IDs: %lu\n"), stats->no_user_id );
301 if( stats->imported || stats->imported_rsa ) {
302 log_info(_(" imported: %lu"), stats->imported );
303 if (stats->imported_rsa)
304 log_printf (" (RSA: %lu)", stats->imported_rsa );
305 log_printf ("\n");
307 if( stats->unchanged )
308 log_info(_(" unchanged: %lu\n"), stats->unchanged );
309 if( stats->n_uids )
310 log_info(_(" new user IDs: %lu\n"), stats->n_uids );
311 if( stats->n_subk )
312 log_info(_(" new subkeys: %lu\n"), stats->n_subk );
313 if( stats->n_sigs )
314 log_info(_(" new signatures: %lu\n"), stats->n_sigs );
315 if( stats->n_revoc )
316 log_info(_(" new key revocations: %lu\n"), stats->n_revoc );
317 if( stats->secret_read )
318 log_info(_(" secret keys read: %lu\n"), stats->secret_read );
319 if( stats->secret_imported )
320 log_info(_(" secret keys imported: %lu\n"), stats->secret_imported );
321 if( stats->secret_dups )
322 log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
323 if( stats->not_imported )
324 log_info(_(" not imported: %lu\n"), stats->not_imported );
325 if( stats->n_sigs_cleaned)
326 log_info(_(" signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
327 if( stats->n_uids_cleaned)
328 log_info(_(" user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
331 if( is_status_enabled() ) {
332 char buf[14*20];
333 sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
334 stats->count,
335 stats->no_user_id,
336 stats->imported,
337 stats->imported_rsa,
338 stats->unchanged,
339 stats->n_uids,
340 stats->n_subk,
341 stats->n_sigs,
342 stats->n_revoc,
343 stats->secret_read,
344 stats->secret_imported,
345 stats->secret_dups,
346 stats->skipped_new_keys,
347 stats->not_imported );
348 write_status_text( STATUS_IMPORT_RES, buf );
353 /****************
354 * Read the next keyblock from stream A.
355 * PENDING_PKT should be initialzed to NULL
356 * and not chnaged form the caller.
357 * Retunr: 0 = okay, -1 no more blocks or another errorcode.
359 static int
360 read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root )
362 int rc;
363 PACKET *pkt;
364 KBNODE root = NULL;
365 int in_cert;
367 if( *pending_pkt ) {
368 root = new_kbnode( *pending_pkt );
369 *pending_pkt = NULL;
370 in_cert = 1;
372 else
373 in_cert = 0;
374 pkt = xmalloc( sizeof *pkt );
375 init_packet(pkt);
376 while( (rc=parse_packet(a, pkt)) != -1 ) {
377 if( rc ) { /* ignore errors */
378 if( rc != G10ERR_UNKNOWN_PACKET ) {
379 log_error("read_block: read error: %s\n", g10_errstr(rc) );
380 rc = G10ERR_INV_KEYRING;
381 goto ready;
383 free_packet( pkt );
384 init_packet(pkt);
385 continue;
388 if( !root && pkt->pkttype == PKT_SIGNATURE
389 && pkt->pkt.signature->sig_class == 0x20 ) {
390 /* this is a revocation certificate which is handled
391 * in a special way */
392 root = new_kbnode( pkt );
393 pkt = NULL;
394 goto ready;
397 /* make a linked list of all packets */
398 switch( pkt->pkttype ) {
399 case PKT_COMPRESSED:
400 if(check_compress_algo(pkt->pkt.compressed->algorithm))
402 rc = G10ERR_COMPR_ALGO;
403 goto ready;
405 else
407 compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
408 pkt->pkt.compressed->buf = NULL;
409 push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1);
411 free_packet( pkt );
412 init_packet(pkt);
413 break;
415 case PKT_RING_TRUST:
416 /* skip those packets */
417 free_packet( pkt );
418 init_packet(pkt);
419 break;
421 case PKT_PUBLIC_KEY:
422 case PKT_SECRET_KEY:
423 if( in_cert ) { /* store this packet */
424 *pending_pkt = pkt;
425 pkt = NULL;
426 goto ready;
428 in_cert = 1;
429 default:
430 if( in_cert ) {
431 if( !root )
432 root = new_kbnode( pkt );
433 else
434 add_kbnode( root, new_kbnode( pkt ) );
435 pkt = xmalloc( sizeof *pkt );
437 init_packet(pkt);
438 break;
441 ready:
442 if( rc == -1 && root )
443 rc = 0;
445 if( rc )
446 release_kbnode( root );
447 else
448 *ret_root = root;
449 free_packet( pkt );
450 xfree( pkt );
451 return rc;
454 /* Walk through the subkeys on a pk to find if we have the PKS
455 disease: multiple subkeys with their binding sigs stripped, and the
456 sig for the first subkey placed after the last subkey. That is,
457 instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
458 "pk uid sig sub1 sub2 sub3 bind1". We can't do anything about sub2
459 and sub3, as they are already lost, but we can try and rescue sub1
460 by reordering the keyblock so that it reads "pk uid sig sub1 bind1
461 sub2 sub3". Returns TRUE if the keyblock was modified. */
463 static int
464 fix_pks_corruption(KBNODE keyblock)
466 int changed=0,keycount=0;
467 KBNODE node,last=NULL,sknode=NULL;
469 /* First determine if we have the problem at all. Look for 2 or
470 more subkeys in a row, followed by a single binding sig. */
471 for(node=keyblock;node;last=node,node=node->next)
473 if(node->pkt->pkttype==PKT_PUBLIC_SUBKEY)
475 keycount++;
476 if(!sknode)
477 sknode=node;
479 else if(node->pkt->pkttype==PKT_SIGNATURE &&
480 node->pkt->pkt.signature->sig_class==0x18 &&
481 keycount>=2 && node->next==NULL)
483 /* We might have the problem, as this key has two subkeys in
484 a row without any intervening packets. */
486 /* Sanity check */
487 if(last==NULL)
488 break;
490 /* Temporarily attach node to sknode. */
491 node->next=sknode->next;
492 sknode->next=node;
493 last->next=NULL;
495 /* Note we aren't checking whether this binding sig is a
496 selfsig. This is not necessary here as the subkey and
497 binding sig will be rejected later if that is the
498 case. */
499 if(check_key_signature(keyblock,node,NULL))
501 /* Not a match, so undo the changes. */
502 sknode->next=node->next;
503 last->next=node;
504 node->next=NULL;
505 break;
507 else
509 sknode->flag |= 1; /* Mark it good so we don't need to
510 check it again */
511 changed=1;
512 break;
515 else
516 keycount=0;
519 return changed;
523 static void
524 print_import_ok (PKT_public_key *pk, PKT_secret_key *sk, unsigned int reason)
526 byte array[MAX_FINGERPRINT_LEN], *s;
527 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
528 size_t i, n;
530 sprintf (buf, "%u ", reason);
531 p = buf + strlen (buf);
533 if (pk)
534 fingerprint_from_pk (pk, array, &n);
535 else
536 fingerprint_from_sk (sk, array, &n);
537 s = array;
538 for (i=0; i < n ; i++, s++, p += 2)
539 sprintf (p, "%02X", *s);
541 write_status_text (STATUS_IMPORT_OK, buf);
544 static void
545 print_import_check (PKT_public_key * pk, PKT_user_id * id)
547 char * buf;
548 byte fpr[24];
549 u32 keyid[2];
550 size_t i, pos = 0, n;
552 buf = xmalloc (17+41+id->len+32);
553 keyid_from_pk (pk, keyid);
554 sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
555 pos = 17;
556 fingerprint_from_pk (pk, fpr, &n);
557 for (i = 0; i < n; i++, pos += 2)
558 sprintf (buf+pos, "%02X", fpr[i]);
559 strcat (buf, " ");
560 pos += 1;
561 strcat (buf, id->name);
562 write_status_text (STATUS_IMPORT_CHECK, buf);
563 xfree (buf);
566 static void
567 check_prefs_warning(PKT_public_key *pk)
569 log_info(_("WARNING: key %s contains preferences for unavailable\n"
570 "algorithms on these user IDs:\n"), keystr_from_pk(pk));
573 static void
574 check_prefs(KBNODE keyblock)
576 KBNODE node;
577 PKT_public_key *pk;
578 int problem=0;
580 merge_keys_and_selfsig(keyblock);
581 pk=keyblock->pkt->pkt.public_key;
583 for(node=keyblock;node;node=node->next)
585 if(node->pkt->pkttype==PKT_USER_ID
586 && node->pkt->pkt.user_id->created
587 && node->pkt->pkt.user_id->prefs)
589 PKT_user_id *uid=node->pkt->pkt.user_id;
590 prefitem_t *prefs=uid->prefs;
591 char *user=utf8_to_native(uid->name,strlen(uid->name),0);
593 for(;prefs->type;prefs++)
595 char num[10]; /* prefs->value is a byte, so we're over
596 safe here */
598 sprintf(num,"%u",prefs->value);
600 if(prefs->type==PREFTYPE_SYM)
602 if (openpgp_cipher_test_algo (prefs->value))
604 const char *algo =
605 (openpgp_cipher_test_algo (prefs->value)
606 ? num
607 : openpgp_cipher_algo_name (prefs->value));
608 if(!problem)
609 check_prefs_warning(pk);
610 log_info(_(" \"%s\": preference for cipher"
611 " algorithm %s\n"), user, algo);
612 problem=1;
615 else if(prefs->type==PREFTYPE_HASH)
617 if(openpgp_md_test_algo(prefs->value))
619 const char *algo =
620 (gcry_md_test_algo (prefs->value)
621 ? num
622 : gcry_md_algo_name (prefs->value));
623 if(!problem)
624 check_prefs_warning(pk);
625 log_info(_(" \"%s\": preference for digest"
626 " algorithm %s\n"), user, algo);
627 problem=1;
630 else if(prefs->type==PREFTYPE_ZIP)
632 if(check_compress_algo (prefs->value))
634 const char *algo=compress_algo_to_string(prefs->value);
635 if(!problem)
636 check_prefs_warning(pk);
637 log_info(_(" \"%s\": preference for compression"
638 " algorithm %s\n"),user,algo?algo:num);
639 problem=1;
644 xfree(user);
648 if(problem)
650 log_info(_("it is strongly suggested that you update"
651 " your preferences and\n"));
652 log_info(_("re-distribute this key to avoid potential algorithm"
653 " mismatch problems\n"));
655 if(!opt.batch)
657 strlist_t sl=NULL,locusr=NULL;
658 size_t fprlen=0;
659 byte fpr[MAX_FINGERPRINT_LEN],*p;
660 char username[(MAX_FINGERPRINT_LEN*2)+1];
661 unsigned int i;
663 p=fingerprint_from_pk(pk,fpr,&fprlen);
664 for(i=0;i<fprlen;i++,p++)
665 sprintf(username+2*i,"%02X",*p);
666 add_to_strlist(&locusr,username);
668 append_to_strlist(&sl,"updpref");
669 append_to_strlist(&sl,"save");
671 keyedit_menu( username, locusr, sl, 1, 1 );
672 free_strlist(sl);
673 free_strlist(locusr);
675 else if(!opt.quiet)
676 log_info(_("you can update your preferences with:"
677 " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
681 /****************
682 * Try to import one keyblock. Return an error only in serious cases, but
683 * never for an invalid keyblock. It uses log_error to increase the
684 * internal errorcount, so that invalid input can be detected by programs
685 * which called gpg.
687 static int
688 import_one( const char *fname, KBNODE keyblock, struct stats_s *stats,
689 unsigned char **fpr,size_t *fpr_len,unsigned int options,
690 int from_sk )
692 PKT_public_key *pk;
693 PKT_public_key *pk_orig;
694 KBNODE node, uidnode;
695 KBNODE keyblock_orig = NULL;
696 u32 keyid[2];
697 int rc = 0;
698 int new_key = 0;
699 int mod_key = 0;
700 int same_key = 0;
701 int non_self = 0;
703 /* get the key and print some info about it */
704 node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
705 if( !node )
706 BUG();
708 pk = node->pkt->pkt.public_key;
710 keyid_from_pk( pk, keyid );
711 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
713 if( opt.verbose && !opt.interactive )
715 log_info( "pub %4u%c/%s %s ",
716 nbits_from_pk( pk ),
717 pubkey_letter( pk->pubkey_algo ),
718 keystr_from_pk(pk), datestr_from_pk(pk) );
719 if (uidnode)
720 print_utf8_string (log_get_stream (),
721 uidnode->pkt->pkt.user_id->name,
722 uidnode->pkt->pkt.user_id->len );
723 log_printf ("\n");
727 if( !uidnode )
729 log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
730 return 0;
733 if (opt.interactive) {
734 if(is_status_enabled())
735 print_import_check (pk, uidnode->pkt->pkt.user_id);
736 merge_keys_and_selfsig (keyblock);
737 tty_printf ("\n");
738 show_basic_key_info (keyblock);
739 tty_printf ("\n");
740 if (!cpr_get_answer_is_yes ("import.okay",
741 "Do you want to import this key? (y/N) "))
742 return 0;
745 collapse_uids(&keyblock);
747 /* Clean the key that we're about to import, to cut down on things
748 that we have to clean later. This has no practical impact on
749 the end result, but does result in less logging which might
750 confuse the user. */
751 if(options&IMPORT_CLEAN)
752 clean_key(keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL);
754 clear_kbnode_flags( keyblock );
756 if((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
757 && opt.verbose)
758 log_info(_("key %s: PKS subkey corruption repaired\n"),
759 keystr_from_pk(pk));
761 rc = chk_self_sigs( fname, keyblock , pk, keyid, &non_self );
762 if( rc )
763 return rc== -1? 0:rc;
765 /* If we allow such a thing, mark unsigned uids as valid */
766 if( opt.allow_non_selfsigned_uid )
767 for( node=keyblock; node; node = node->next )
768 if( node->pkt->pkttype == PKT_USER_ID && !(node->flag & 1) )
770 char *user=utf8_to_native(node->pkt->pkt.user_id->name,
771 node->pkt->pkt.user_id->len,0);
772 node->flag |= 1;
773 log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
774 keystr_from_pk(pk),user);
775 xfree(user);
778 if( !delete_inv_parts( fname, keyblock, keyid, options ) ) {
779 log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
780 if( !opt.quiet )
781 log_info(_("this may be caused by a missing self-signature\n"));
782 stats->no_user_id++;
783 return 0;
786 /* do we have this key already in one of our pubrings ? */
787 pk_orig = xmalloc_clear( sizeof *pk_orig );
788 rc = get_pubkey_fast ( pk_orig, keyid );
789 if( rc && rc != G10ERR_NO_PUBKEY && rc != G10ERR_UNU_PUBKEY )
791 log_error( _("key %s: public key not found: %s\n"),
792 keystr(keyid), g10_errstr(rc));
794 else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) )
796 if( opt.verbose )
797 log_info( _("key %s: new key - skipped\n"), keystr(keyid));
798 rc = 0;
799 stats->skipped_new_keys++;
801 else if( rc ) { /* insert this key */
802 KEYDB_HANDLE hd = keydb_new (0);
804 rc = keydb_locate_writable (hd, NULL);
805 if (rc) {
806 log_error (_("no writable keyring found: %s\n"), g10_errstr (rc));
807 keydb_release (hd);
808 return G10ERR_GENERAL;
810 if( opt.verbose > 1 )
811 log_info (_("writing to `%s'\n"), keydb_get_resource_name (hd) );
813 rc = keydb_insert_keyblock (hd, keyblock );
814 if (rc)
815 log_error (_("error writing keyring `%s': %s\n"),
816 keydb_get_resource_name (hd), g10_errstr(rc));
817 else
819 /* This should not be possible since we delete the
820 ownertrust when a key is deleted, but it can happen if
821 the keyring and trustdb are out of sync. It can also
822 be made to happen with the trusted-key command. */
824 clear_ownertrusts (pk);
825 if(non_self)
826 revalidation_mark ();
828 keydb_release (hd);
830 /* we are ready */
831 if( !opt.quiet )
833 char *p=get_user_id_native (keyid);
834 log_info( _("key %s: public key \"%s\" imported\n"),
835 keystr(keyid),p);
836 xfree(p);
838 if( is_status_enabled() )
840 char *us = get_long_user_id_string( keyid );
841 write_status_text( STATUS_IMPORTED, us );
842 xfree(us);
843 print_import_ok (pk,NULL, 1);
845 stats->imported++;
846 if( is_RSA( pk->pubkey_algo ) )
847 stats->imported_rsa++;
848 new_key = 1;
850 else { /* merge */
851 KEYDB_HANDLE hd;
852 int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
854 /* Compare the original against the new key; just to be sure nothing
855 * weird is going on */
856 if( cmp_public_keys( pk_orig, pk ) )
858 log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
859 goto leave;
862 /* now read the original keyblock */
863 hd = keydb_new (0);
865 byte afp[MAX_FINGERPRINT_LEN];
866 size_t an;
868 fingerprint_from_pk (pk_orig, afp, &an);
869 while (an < MAX_FINGERPRINT_LEN)
870 afp[an++] = 0;
871 rc = keydb_search_fpr (hd, afp);
873 if( rc )
875 log_error (_("key %s: can't locate original keyblock: %s\n"),
876 keystr(keyid), g10_errstr(rc));
877 keydb_release (hd);
878 goto leave;
880 rc = keydb_get_keyblock (hd, &keyblock_orig );
881 if (rc)
883 log_error (_("key %s: can't read original keyblock: %s\n"),
884 keystr(keyid), g10_errstr(rc));
885 keydb_release (hd);
886 goto leave;
889 /* and try to merge the block */
890 clear_kbnode_flags( keyblock_orig );
891 clear_kbnode_flags( keyblock );
892 n_uids = n_sigs = n_subk = n_sigs_cleaned = n_uids_cleaned = 0;
893 rc = merge_blocks( fname, keyblock_orig, keyblock,
894 keyid, &n_uids, &n_sigs, &n_subk );
895 if( rc )
897 keydb_release (hd);
898 goto leave;
901 if(options&IMPORT_CLEAN)
902 clean_key(keyblock_orig,opt.verbose,options&IMPORT_MINIMAL,
903 &n_uids_cleaned,&n_sigs_cleaned);
905 if( n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned) {
906 mod_key = 1;
907 /* keyblock_orig has been updated; write */
908 rc = keydb_update_keyblock (hd, keyblock_orig);
909 if (rc)
910 log_error (_("error writing keyring `%s': %s\n"),
911 keydb_get_resource_name (hd), g10_errstr(rc) );
912 else if(non_self)
913 revalidation_mark ();
915 /* we are ready */
916 if( !opt.quiet )
918 char *p=get_user_id_native(keyid);
919 if( n_uids == 1 )
920 log_info( _("key %s: \"%s\" 1 new user ID\n"),
921 keystr(keyid),p);
922 else if( n_uids )
923 log_info( _("key %s: \"%s\" %d new user IDs\n"),
924 keystr(keyid),p,n_uids);
925 if( n_sigs == 1 )
926 log_info( _("key %s: \"%s\" 1 new signature\n"),
927 keystr(keyid), p);
928 else if( n_sigs )
929 log_info( _("key %s: \"%s\" %d new signatures\n"),
930 keystr(keyid), p, n_sigs );
931 if( n_subk == 1 )
932 log_info( _("key %s: \"%s\" 1 new subkey\n"),
933 keystr(keyid), p);
934 else if( n_subk )
935 log_info( _("key %s: \"%s\" %d new subkeys\n"),
936 keystr(keyid), p, n_subk );
937 if(n_sigs_cleaned==1)
938 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
939 keystr(keyid),p,n_sigs_cleaned);
940 else if(n_sigs_cleaned)
941 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
942 keystr(keyid),p,n_sigs_cleaned);
943 if(n_uids_cleaned==1)
944 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
945 keystr(keyid),p,n_uids_cleaned);
946 else if(n_uids_cleaned)
947 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
948 keystr(keyid),p,n_uids_cleaned);
949 xfree(p);
952 stats->n_uids +=n_uids;
953 stats->n_sigs +=n_sigs;
954 stats->n_subk +=n_subk;
955 stats->n_sigs_cleaned +=n_sigs_cleaned;
956 stats->n_uids_cleaned +=n_uids_cleaned;
958 if (is_status_enabled ())
959 print_import_ok (pk, NULL,
960 ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
962 else
964 same_key = 1;
965 if (is_status_enabled ())
966 print_import_ok (pk, NULL, 0);
968 if( !opt.quiet )
970 char *p=get_user_id_native(keyid);
971 log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
972 xfree(p);
975 stats->unchanged++;
978 keydb_release (hd); hd = NULL;
981 leave:
982 if (mod_key || new_key || same_key)
984 /* A little explanation for this: we fill in the fingerprint
985 when importing keys as it can be useful to know the
986 fingerprint in certain keyserver-related cases (a keyserver
987 asked for a particular name, but the key doesn't have that
988 name). However, in cases where we're importing more than
989 one key at a time, we cannot know which key to fingerprint.
990 In these cases, rather than guessing, we do not
991 fingerprinting at all, and we must hope the user ID on the
992 keys are useful. Note that we need to do this for new
993 keys, merged keys and even for unchanged keys. This is
994 required because for example the --auto-key-locate feature
995 may import an already imported key and needs to know the
996 fingerprint of the key in all cases. */
997 if (fpr)
999 xfree (*fpr);
1000 /* Note that we need to compare against 0 here because
1001 COUNT gets only incremented after returning form this
1002 function. */
1003 if (stats->count == 0)
1004 *fpr = fingerprint_from_pk (pk, NULL, fpr_len);
1005 else
1006 *fpr = NULL;
1010 /* Now that the key is definitely incorporated into the keydb, we
1011 need to check if a designated revocation is present or if the
1012 prefs are not rational so we can warn the user. */
1014 if(mod_key)
1016 revocation_present(keyblock_orig);
1017 if(!from_sk && seckey_available(keyid)==0)
1018 check_prefs(keyblock_orig);
1020 else if(new_key)
1022 revocation_present(keyblock);
1023 if(!from_sk && seckey_available(keyid)==0)
1024 check_prefs(keyblock);
1027 release_kbnode( keyblock_orig );
1028 free_public_key( pk_orig );
1030 return rc;
1033 /* Walk a secret keyblock and produce a public keyblock out of it. */
1034 static KBNODE
1035 sec_to_pub_keyblock(KBNODE sec_keyblock)
1037 KBNODE secnode,pub_keyblock=NULL,ctx=NULL;
1039 while((secnode=walk_kbnode(sec_keyblock,&ctx,0)))
1041 KBNODE pubnode;
1043 if(secnode->pkt->pkttype==PKT_SECRET_KEY ||
1044 secnode->pkt->pkttype==PKT_SECRET_SUBKEY)
1046 /* Make a public key. We only need to convert enough to
1047 write the keyblock out. */
1049 PKT_secret_key *sk=secnode->pkt->pkt.secret_key;
1050 PACKET *pkt=xmalloc_clear(sizeof(PACKET));
1051 PKT_public_key *pk=xmalloc_clear(sizeof(PKT_public_key));
1052 int n;
1054 if(secnode->pkt->pkttype==PKT_SECRET_KEY)
1055 pkt->pkttype=PKT_PUBLIC_KEY;
1056 else
1057 pkt->pkttype=PKT_PUBLIC_SUBKEY;
1059 pkt->pkt.public_key=pk;
1061 pk->version=sk->version;
1062 pk->timestamp=sk->timestamp;
1063 pk->expiredate=sk->expiredate;
1064 pk->pubkey_algo=sk->pubkey_algo;
1066 n=pubkey_get_npkey(pk->pubkey_algo);
1067 if(n==0)
1069 /* we can't properly extract the pubkey without knowing
1070 the number of MPIs */
1071 release_kbnode(pub_keyblock);
1072 return NULL;
1074 else
1076 int i;
1078 for(i=0;i<n;i++)
1079 pk->pkey[i]=mpi_copy(sk->skey[i]);
1082 pubnode=new_kbnode(pkt);
1084 else
1086 pubnode=clone_kbnode(secnode);
1089 if(pub_keyblock==NULL)
1090 pub_keyblock=pubnode;
1091 else
1092 add_kbnode(pub_keyblock,pubnode);
1095 return pub_keyblock;
1098 /****************
1099 * Ditto for secret keys. Handling is simpler than for public keys.
1100 * We allow secret key importing only when allow is true, this is so
1101 * that a secret key can not be imported accidently and thereby tampering
1102 * with the trust calculation.
1104 static int
1105 import_secret_one( const char *fname, KBNODE keyblock,
1106 struct stats_s *stats, unsigned int options)
1108 PKT_secret_key *sk;
1109 KBNODE node, uidnode;
1110 u32 keyid[2];
1111 int rc = 0;
1113 /* get the key and print some info about it */
1114 node = find_kbnode( keyblock, PKT_SECRET_KEY );
1115 if( !node )
1116 BUG();
1118 sk = node->pkt->pkt.secret_key;
1119 keyid_from_sk( sk, keyid );
1120 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1122 if( opt.verbose )
1124 log_info( "sec %4u%c/%s %s ",
1125 nbits_from_sk( sk ),
1126 pubkey_letter( sk->pubkey_algo ),
1127 keystr_from_sk(sk), datestr_from_sk(sk) );
1128 if( uidnode )
1129 print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
1130 uidnode->pkt->pkt.user_id->len );
1131 log_printf ("\n");
1133 stats->secret_read++;
1135 if( !uidnode )
1137 log_error( _("key %s: no user ID\n"), keystr_from_sk(sk));
1138 return 0;
1141 if(sk->protect.algo>110)
1143 log_error(_("key %s: secret key with invalid cipher %d"
1144 " - skipped\n"),keystr_from_sk(sk),sk->protect.algo);
1145 return 0;
1148 #ifdef ENABLE_SELINUX_HACKS
1149 if (1)
1151 /* We don't allow to import secret keys because that may be used
1152 to put a secret key into the keyring and the user might later
1153 be tricked into signing stuff with that key. */
1154 log_error (_("importing secret keys not allowed\n"));
1155 return 0;
1157 #endif
1159 clear_kbnode_flags( keyblock );
1161 /* do we have this key already in one of our secrings ? */
1162 rc = seckey_available( keyid );
1163 if( rc == G10ERR_NO_SECKEY && !(opt.import_options&IMPORT_MERGE_ONLY) )
1165 /* simply insert this key */
1166 KEYDB_HANDLE hd = keydb_new (1);
1168 /* get default resource */
1169 rc = keydb_locate_writable (hd, NULL);
1170 if (rc) {
1171 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
1172 keydb_release (hd);
1173 return G10ERR_GENERAL;
1175 rc = keydb_insert_keyblock (hd, keyblock );
1176 if (rc)
1177 log_error (_("error writing keyring `%s': %s\n"),
1178 keydb_get_resource_name (hd), g10_errstr(rc) );
1179 keydb_release (hd);
1180 /* we are ready */
1181 if( !opt.quiet )
1182 log_info( _("key %s: secret key imported\n"), keystr_from_sk(sk));
1183 stats->secret_imported++;
1184 if (is_status_enabled ())
1185 print_import_ok (NULL, sk, 1|16);
1187 if(options&IMPORT_SK2PK)
1189 /* Try and make a public key out of this. */
1191 KBNODE pub_keyblock=sec_to_pub_keyblock(keyblock);
1192 if(pub_keyblock)
1194 import_one(fname,pub_keyblock,stats,
1195 NULL,NULL,opt.import_options,1);
1196 release_kbnode(pub_keyblock);
1200 /* Now that the key is definitely incorporated into the keydb,
1201 if we have the public part of this key, we need to check if
1202 the prefs are rational. */
1203 node=get_pubkeyblock(keyid);
1204 if(node)
1206 check_prefs(node);
1207 release_kbnode(node);
1210 else if( !rc )
1211 { /* we can't merge secret keys */
1212 log_error( _("key %s: already in secret keyring\n"),
1213 keystr_from_sk(sk));
1214 stats->secret_dups++;
1215 if (is_status_enabled ())
1216 print_import_ok (NULL, sk, 16);
1218 /* TODO: if we ever do merge secret keys, make sure to handle
1219 the sec_to_pub_keyblock feature as well. */
1221 else
1222 log_error( _("key %s: secret key not found: %s\n"),
1223 keystr_from_sk(sk), g10_errstr(rc));
1225 return rc;
1229 /****************
1230 * Import a revocation certificate; this is a single signature packet.
1232 static int
1233 import_revoke_cert( const char *fname, KBNODE node, struct stats_s *stats )
1235 PKT_public_key *pk=NULL;
1236 KBNODE onode, keyblock = NULL;
1237 KEYDB_HANDLE hd = NULL;
1238 u32 keyid[2];
1239 int rc = 0;
1241 (void)fname;
1243 assert( !node->next );
1244 assert( node->pkt->pkttype == PKT_SIGNATURE );
1245 assert( node->pkt->pkt.signature->sig_class == 0x20 );
1247 keyid[0] = node->pkt->pkt.signature->keyid[0];
1248 keyid[1] = node->pkt->pkt.signature->keyid[1];
1250 pk = xmalloc_clear( sizeof *pk );
1251 rc = get_pubkey( pk, keyid );
1252 if( rc == G10ERR_NO_PUBKEY )
1254 log_error(_("key %s: no public key -"
1255 " can't apply revocation certificate\n"), keystr(keyid));
1256 rc = 0;
1257 goto leave;
1259 else if( rc )
1261 log_error(_("key %s: public key not found: %s\n"),
1262 keystr(keyid), g10_errstr(rc));
1263 goto leave;
1266 /* read the original keyblock */
1267 hd = keydb_new (0);
1269 byte afp[MAX_FINGERPRINT_LEN];
1270 size_t an;
1272 fingerprint_from_pk (pk, afp, &an);
1273 while (an < MAX_FINGERPRINT_LEN)
1274 afp[an++] = 0;
1275 rc = keydb_search_fpr (hd, afp);
1277 if (rc)
1279 log_error (_("key %s: can't locate original keyblock: %s\n"),
1280 keystr(keyid), g10_errstr(rc));
1281 goto leave;
1283 rc = keydb_get_keyblock (hd, &keyblock );
1284 if (rc)
1286 log_error (_("key %s: can't read original keyblock: %s\n"),
1287 keystr(keyid), g10_errstr(rc));
1288 goto leave;
1291 /* it is okay, that node is not in keyblock because
1292 * check_key_signature works fine for sig_class 0x20 in this
1293 * special case. */
1294 rc = check_key_signature( keyblock, node, NULL);
1295 if( rc )
1297 log_error( _("key %s: invalid revocation certificate"
1298 ": %s - rejected\n"), keystr(keyid), g10_errstr(rc));
1299 goto leave;
1302 /* check whether we already have this */
1303 for(onode=keyblock->next; onode; onode=onode->next ) {
1304 if( onode->pkt->pkttype == PKT_USER_ID )
1305 break;
1306 else if( onode->pkt->pkttype == PKT_SIGNATURE
1307 && !cmp_signatures(node->pkt->pkt.signature,
1308 onode->pkt->pkt.signature))
1310 rc = 0;
1311 goto leave; /* yes, we already know about it */
1316 /* insert it */
1317 insert_kbnode( keyblock, clone_kbnode(node), 0 );
1319 /* and write the keyblock back */
1320 rc = keydb_update_keyblock (hd, keyblock );
1321 if (rc)
1322 log_error (_("error writing keyring `%s': %s\n"),
1323 keydb_get_resource_name (hd), g10_errstr(rc) );
1324 keydb_release (hd); hd = NULL;
1325 /* we are ready */
1326 if( !opt.quiet )
1328 char *p=get_user_id_native (keyid);
1329 log_info( _("key %s: \"%s\" revocation certificate imported\n"),
1330 keystr(keyid),p);
1331 xfree(p);
1333 stats->n_revoc++;
1335 /* If the key we just revoked was ultimately trusted, remove its
1336 ultimate trust. This doesn't stop the user from putting the
1337 ultimate trust back, but is a reasonable solution for now. */
1338 if(get_ownertrust(pk)==TRUST_ULTIMATE)
1339 clear_ownertrusts(pk);
1341 revalidation_mark ();
1343 leave:
1344 keydb_release (hd);
1345 release_kbnode( keyblock );
1346 free_public_key( pk );
1347 return rc;
1351 /****************
1352 * loop over the keyblock and check all self signatures.
1353 * Mark all user-ids with a self-signature by setting flag bit 0.
1354 * Mark all user-ids with an invalid self-signature by setting bit 1.
1355 * This works also for subkeys, here the subkey is marked. Invalid or
1356 * extra subkey sigs (binding or revocation) are marked for deletion.
1357 * non_self is set to true if there are any sigs other than self-sigs
1358 * in this keyblock.
1360 static int
1361 chk_self_sigs( const char *fname, KBNODE keyblock,
1362 PKT_public_key *pk, u32 *keyid, int *non_self )
1364 KBNODE n,knode=NULL;
1365 PKT_signature *sig;
1366 int rc;
1367 u32 bsdate=0,rsdate=0;
1368 KBNODE bsnode=NULL,rsnode=NULL;
1370 (void)fname;
1371 (void)pk;
1373 for( n=keyblock; (n = find_next_kbnode(n, 0)); ) {
1374 if(n->pkt->pkttype==PKT_PUBLIC_SUBKEY)
1376 knode=n;
1377 bsdate=0;
1378 rsdate=0;
1379 bsnode=NULL;
1380 rsnode=NULL;
1381 continue;
1383 else if( n->pkt->pkttype != PKT_SIGNATURE )
1384 continue;
1385 sig = n->pkt->pkt.signature;
1386 if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] ) {
1388 /* This just caches the sigs for later use. That way we
1389 import a fully-cached key which speeds things up. */
1390 if(!opt.no_sig_cache)
1391 check_key_signature(keyblock,n,NULL);
1393 if( IS_UID_SIG(sig) || IS_UID_REV(sig) )
1395 KBNODE unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
1396 if( !unode )
1398 log_error( _("key %s: no user ID for signature\n"),
1399 keystr(keyid));
1400 return -1; /* the complete keyblock is invalid */
1403 /* If it hasn't been marked valid yet, keep trying */
1404 if(!(unode->flag&1)) {
1405 rc = check_key_signature( keyblock, n, NULL);
1406 if( rc )
1408 if( opt.verbose )
1410 char *p=utf8_to_native(unode->pkt->pkt.user_id->name,
1411 strlen(unode->pkt->pkt.user_id->name),0);
1412 log_info( rc == G10ERR_PUBKEY_ALGO ?
1413 _("key %s: unsupported public key "
1414 "algorithm on user ID \"%s\"\n"):
1415 _("key %s: invalid self-signature "
1416 "on user ID \"%s\"\n"),
1417 keystr(keyid),p);
1418 xfree(p);
1421 else
1422 unode->flag |= 1; /* mark that signature checked */
1425 else if( sig->sig_class == 0x18 ) {
1426 /* Note that this works based solely on the timestamps
1427 like the rest of gpg. If the standard gets
1428 revocation targets, this may need to be revised. */
1430 if( !knode )
1432 if(opt.verbose)
1433 log_info( _("key %s: no subkey for key binding\n"),
1434 keystr(keyid));
1435 n->flag |= 4; /* delete this */
1437 else
1439 rc = check_key_signature( keyblock, n, NULL);
1440 if( rc )
1442 if(opt.verbose)
1443 log_info(rc == G10ERR_PUBKEY_ALGO ?
1444 _("key %s: unsupported public key"
1445 " algorithm\n"):
1446 _("key %s: invalid subkey binding\n"),
1447 keystr(keyid));
1448 n->flag|=4;
1450 else
1452 /* It's valid, so is it newer? */
1453 if(sig->timestamp>=bsdate) {
1454 knode->flag |= 1; /* the subkey is valid */
1455 if(bsnode)
1457 bsnode->flag|=4; /* Delete the last binding
1458 sig since this one is
1459 newer */
1460 if(opt.verbose)
1461 log_info(_("key %s: removed multiple subkey"
1462 " binding\n"),keystr(keyid));
1465 bsnode=n;
1466 bsdate=sig->timestamp;
1468 else
1469 n->flag|=4; /* older */
1473 else if( sig->sig_class == 0x28 ) {
1474 /* We don't actually mark the subkey as revoked right
1475 now, so just check that the revocation sig is the
1476 most recent valid one. Note that we don't care if
1477 the binding sig is newer than the revocation sig.
1478 See the comment in getkey.c:merge_selfsigs_subkey for
1479 more */
1480 if( !knode )
1482 if(opt.verbose)
1483 log_info( _("key %s: no subkey for key revocation\n"),
1484 keystr(keyid));
1485 n->flag |= 4; /* delete this */
1487 else
1489 rc = check_key_signature( keyblock, n, NULL);
1490 if( rc )
1492 if(opt.verbose)
1493 log_info(rc == G10ERR_PUBKEY_ALGO ?
1494 _("key %s: unsupported public"
1495 " key algorithm\n"):
1496 _("key %s: invalid subkey revocation\n"),
1497 keystr(keyid));
1498 n->flag|=4;
1500 else
1502 /* It's valid, so is it newer? */
1503 if(sig->timestamp>=rsdate)
1505 if(rsnode)
1507 rsnode->flag|=4; /* Delete the last revocation
1508 sig since this one is
1509 newer */
1510 if(opt.verbose)
1511 log_info(_("key %s: removed multiple subkey"
1512 " revocation\n"),keystr(keyid));
1515 rsnode=n;
1516 rsdate=sig->timestamp;
1518 else
1519 n->flag|=4; /* older */
1524 else
1525 *non_self=1;
1528 return 0;
1531 /****************
1532 * delete all parts which are invalid and those signatures whose
1533 * public key algorithm is not available in this implemenation;
1534 * but consider RSA as valid, because parse/build_packets knows
1535 * about it.
1536 * returns: true if at least one valid user-id is left over.
1538 static int
1539 delete_inv_parts( const char *fname, KBNODE keyblock,
1540 u32 *keyid, unsigned int options)
1542 KBNODE node;
1543 int nvalid=0, uid_seen=0, subkey_seen=0;
1545 (void)fname;
1547 for(node=keyblock->next; node; node = node->next ) {
1548 if( node->pkt->pkttype == PKT_USER_ID ) {
1549 uid_seen = 1;
1550 if( (node->flag & 2) || !(node->flag & 1) ) {
1551 if( opt.verbose )
1553 char *p=utf8_to_native(node->pkt->pkt.user_id->name,
1554 node->pkt->pkt.user_id->len,0);
1555 log_info( _("key %s: skipped user ID \"%s\"\n"),
1556 keystr(keyid),p);
1557 xfree(p);
1559 delete_kbnode( node ); /* the user-id */
1560 /* and all following packets up to the next user-id */
1561 while( node->next
1562 && node->next->pkt->pkttype != PKT_USER_ID
1563 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1564 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
1565 delete_kbnode( node->next );
1566 node = node->next;
1569 else
1570 nvalid++;
1572 else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1573 || node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1574 if( (node->flag & 2) || !(node->flag & 1) ) {
1575 if( opt.verbose )
1576 log_info( _("key %s: skipped subkey\n"),keystr(keyid));
1578 delete_kbnode( node ); /* the subkey */
1579 /* and all following signature packets */
1580 while( node->next
1581 && node->next->pkt->pkttype == PKT_SIGNATURE ) {
1582 delete_kbnode( node->next );
1583 node = node->next;
1586 else
1587 subkey_seen = 1;
1589 else if (node->pkt->pkttype == PKT_SIGNATURE
1590 && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
1591 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
1592 delete_kbnode( node ); /* build_packet() can't handle this */
1593 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1594 !node->pkt->pkt.signature->flags.exportable &&
1595 !(options&IMPORT_LOCAL_SIGS) &&
1596 seckey_available( node->pkt->pkt.signature->keyid ) )
1598 /* here we violate the rfc a bit by still allowing
1599 * to import non-exportable signature when we have the
1600 * the secret key used to create this signature - it
1601 * seems that this makes sense */
1602 if(opt.verbose)
1603 log_info( _("key %s: non exportable signature"
1604 " (class 0x%02X) - skipped\n"),
1605 keystr(keyid), node->pkt->pkt.signature->sig_class );
1606 delete_kbnode( node );
1608 else if( node->pkt->pkttype == PKT_SIGNATURE
1609 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1610 if( uid_seen )
1612 if(opt.verbose)
1613 log_info( _("key %s: revocation certificate"
1614 " at wrong place - skipped\n"),keystr(keyid));
1615 delete_kbnode( node );
1617 else {
1618 /* If the revocation cert is from a different key than
1619 the one we're working on don't check it - it's
1620 probably from a revocation key and won't be
1621 verifiable with this key anyway. */
1623 if(node->pkt->pkt.signature->keyid[0]==keyid[0] &&
1624 node->pkt->pkt.signature->keyid[1]==keyid[1])
1626 int rc = check_key_signature( keyblock, node, NULL);
1627 if( rc )
1629 if(opt.verbose)
1630 log_info( _("key %s: invalid revocation"
1631 " certificate: %s - skipped\n"),
1632 keystr(keyid), g10_errstr(rc));
1633 delete_kbnode( node );
1638 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1639 (node->pkt->pkt.signature->sig_class == 0x18 ||
1640 node->pkt->pkt.signature->sig_class == 0x28) &&
1641 !subkey_seen )
1643 if(opt.verbose)
1644 log_info( _("key %s: subkey signature"
1645 " in wrong place - skipped\n"), keystr(keyid));
1646 delete_kbnode( node );
1648 else if( node->pkt->pkttype == PKT_SIGNATURE
1649 && !IS_CERT(node->pkt->pkt.signature))
1651 if(opt.verbose)
1652 log_info(_("key %s: unexpected signature class (0x%02X) -"
1653 " skipped\n"),keystr(keyid),
1654 node->pkt->pkt.signature->sig_class);
1655 delete_kbnode(node);
1657 else if( (node->flag & 4) ) /* marked for deletion */
1658 delete_kbnode( node );
1661 /* note: because keyblock is the public key, it is never marked
1662 * for deletion and so keyblock cannot change */
1663 commit_kbnode( &keyblock );
1664 return nvalid;
1668 /****************
1669 * It may happen that the imported keyblock has duplicated user IDs.
1670 * We check this here and collapse those user IDs together with their
1671 * sigs into one.
1672 * Returns: True if the keyblock has changed.
1675 collapse_uids( KBNODE *keyblock )
1677 KBNODE uid1;
1678 int any=0;
1680 for(uid1=*keyblock;uid1;uid1=uid1->next)
1682 KBNODE uid2;
1684 if(is_deleted_kbnode(uid1))
1685 continue;
1687 if(uid1->pkt->pkttype!=PKT_USER_ID)
1688 continue;
1690 for(uid2=uid1->next;uid2;uid2=uid2->next)
1692 if(is_deleted_kbnode(uid2))
1693 continue;
1695 if(uid2->pkt->pkttype!=PKT_USER_ID)
1696 continue;
1698 if(cmp_user_ids(uid1->pkt->pkt.user_id,
1699 uid2->pkt->pkt.user_id)==0)
1701 /* We have a duplicated uid */
1702 KBNODE sig1,last;
1704 any=1;
1706 /* Now take uid2's signatures, and attach them to
1707 uid1 */
1708 for(last=uid2;last->next;last=last->next)
1710 if(is_deleted_kbnode(last))
1711 continue;
1713 if(last->next->pkt->pkttype==PKT_USER_ID
1714 || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
1715 || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
1716 break;
1719 /* Snip out uid2 */
1720 (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
1722 /* Now put uid2 in place as part of uid1 */
1723 last->next=uid1->next;
1724 uid1->next=uid2;
1725 delete_kbnode(uid2);
1727 /* Now dedupe uid1 */
1728 for(sig1=uid1->next;sig1;sig1=sig1->next)
1730 KBNODE sig2;
1732 if(is_deleted_kbnode(sig1))
1733 continue;
1735 if(sig1->pkt->pkttype==PKT_USER_ID
1736 || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
1737 || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
1738 break;
1740 if(sig1->pkt->pkttype!=PKT_SIGNATURE)
1741 continue;
1743 for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
1745 if(is_deleted_kbnode(sig2))
1746 continue;
1748 if(sig2->pkt->pkttype==PKT_USER_ID
1749 || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
1750 || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
1751 break;
1753 if(sig2->pkt->pkttype!=PKT_SIGNATURE)
1754 continue;
1756 if(cmp_signatures(sig1->pkt->pkt.signature,
1757 sig2->pkt->pkt.signature)==0)
1759 /* We have a match, so delete the second
1760 signature */
1761 delete_kbnode(sig2);
1762 sig2=last;
1770 commit_kbnode(keyblock);
1772 if(any && !opt.quiet)
1774 const char *key="???";
1776 if( (uid1=find_kbnode( *keyblock, PKT_PUBLIC_KEY )) )
1777 key=keystr_from_pk(uid1->pkt->pkt.public_key);
1778 else if( (uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY )) )
1779 key=keystr_from_sk(uid1->pkt->pkt.secret_key);
1781 log_info(_("key %s: duplicated user ID detected - merged\n"),key);
1784 return any;
1787 /* Check for a 0x20 revocation from a revocation key that is not
1788 present. This may be called without the benefit of merge_xxxx so
1789 you can't rely on pk->revkey and friends. */
1790 static void
1791 revocation_present(KBNODE keyblock)
1793 KBNODE onode,inode;
1794 PKT_public_key *pk=keyblock->pkt->pkt.public_key;
1796 for(onode=keyblock->next;onode;onode=onode->next)
1798 /* If we reach user IDs, we're done. */
1799 if(onode->pkt->pkttype==PKT_USER_ID)
1800 break;
1802 if(onode->pkt->pkttype==PKT_SIGNATURE &&
1803 onode->pkt->pkt.signature->sig_class==0x1F &&
1804 onode->pkt->pkt.signature->revkey)
1806 int idx;
1807 PKT_signature *sig=onode->pkt->pkt.signature;
1809 for(idx=0;idx<sig->numrevkeys;idx++)
1811 u32 keyid[2];
1813 keyid_from_fingerprint(sig->revkey[idx]->fpr,
1814 MAX_FINGERPRINT_LEN,keyid);
1816 for(inode=keyblock->next;inode;inode=inode->next)
1818 /* If we reach user IDs, we're done. */
1819 if(inode->pkt->pkttype==PKT_USER_ID)
1820 break;
1822 if(inode->pkt->pkttype==PKT_SIGNATURE &&
1823 inode->pkt->pkt.signature->sig_class==0x20 &&
1824 inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
1825 inode->pkt->pkt.signature->keyid[1]==keyid[1])
1827 /* Okay, we have a revocation key, and a
1828 revocation issued by it. Do we have the key
1829 itself? */
1830 int rc;
1832 rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx]->fpr,
1833 MAX_FINGERPRINT_LEN);
1834 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1836 char *tempkeystr=xstrdup(keystr_from_pk(pk));
1838 /* No, so try and get it */
1839 if(opt.keyserver
1840 && (opt.keyserver_options.options
1841 & KEYSERVER_AUTO_KEY_RETRIEVE))
1843 log_info(_("WARNING: key %s may be revoked:"
1844 " fetching revocation key %s\n"),
1845 tempkeystr,keystr(keyid));
1846 keyserver_import_fprint(sig->revkey[idx]->fpr,
1847 MAX_FINGERPRINT_LEN,
1848 opt.keyserver);
1850 /* Do we have it now? */
1851 rc=get_pubkey_byfprint_fast (NULL,
1852 sig->revkey[idx]->fpr,
1853 MAX_FINGERPRINT_LEN);
1856 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1857 log_info(_("WARNING: key %s may be revoked:"
1858 " revocation key %s not present.\n"),
1859 tempkeystr,keystr(keyid));
1861 xfree(tempkeystr);
1870 /****************
1871 * compare and merge the blocks
1873 * o compare the signatures: If we already have this signature, check
1874 * that they compare okay; if not, issue a warning and ask the user.
1875 * o Simply add the signature. Can't verify here because we may not have
1876 * the signature's public key yet; verification is done when putting it
1877 * into the trustdb, which is done automagically as soon as this pubkey
1878 * is used.
1879 * Note: We indicate newly inserted packets with flag bit 0
1881 static int
1882 merge_blocks( const char *fname, KBNODE keyblock_orig, KBNODE keyblock,
1883 u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
1885 KBNODE onode, node;
1886 int rc, found;
1888 /* 1st: handle revocation certificates */
1889 for(node=keyblock->next; node; node=node->next ) {
1890 if( node->pkt->pkttype == PKT_USER_ID )
1891 break;
1892 else if( node->pkt->pkttype == PKT_SIGNATURE
1893 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1894 /* check whether we already have this */
1895 found = 0;
1896 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1897 if( onode->pkt->pkttype == PKT_USER_ID )
1898 break;
1899 else if( onode->pkt->pkttype == PKT_SIGNATURE
1900 && onode->pkt->pkt.signature->sig_class == 0x20
1901 && !cmp_signatures(onode->pkt->pkt.signature,
1902 node->pkt->pkt.signature))
1904 found = 1;
1905 break;
1908 if( !found ) {
1909 KBNODE n2 = clone_kbnode(node);
1910 insert_kbnode( keyblock_orig, n2, 0 );
1911 n2->flag |= 1;
1912 ++*n_sigs;
1913 if(!opt.quiet)
1915 char *p=get_user_id_native (keyid);
1916 log_info(_("key %s: \"%s\" revocation"
1917 " certificate added\n"), keystr(keyid),p);
1918 xfree(p);
1924 /* 2nd: merge in any direct key (0x1F) sigs */
1925 for(node=keyblock->next; node; node=node->next ) {
1926 if( node->pkt->pkttype == PKT_USER_ID )
1927 break;
1928 else if( node->pkt->pkttype == PKT_SIGNATURE
1929 && node->pkt->pkt.signature->sig_class == 0x1F ) {
1930 /* check whether we already have this */
1931 found = 0;
1932 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1933 if( onode->pkt->pkttype == PKT_USER_ID )
1934 break;
1935 else if( onode->pkt->pkttype == PKT_SIGNATURE
1936 && onode->pkt->pkt.signature->sig_class == 0x1F
1937 && !cmp_signatures(onode->pkt->pkt.signature,
1938 node->pkt->pkt.signature)) {
1939 found = 1;
1940 break;
1943 if( !found )
1945 KBNODE n2 = clone_kbnode(node);
1946 insert_kbnode( keyblock_orig, n2, 0 );
1947 n2->flag |= 1;
1948 ++*n_sigs;
1949 if(!opt.quiet)
1950 log_info( _("key %s: direct key signature added\n"),
1951 keystr(keyid));
1956 /* 3rd: try to merge new certificates in */
1957 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1958 if( !(onode->flag & 1) && onode->pkt->pkttype == PKT_USER_ID) {
1959 /* find the user id in the imported keyblock */
1960 for(node=keyblock->next; node; node=node->next )
1961 if( node->pkt->pkttype == PKT_USER_ID
1962 && !cmp_user_ids( onode->pkt->pkt.user_id,
1963 node->pkt->pkt.user_id ) )
1964 break;
1965 if( node ) { /* found: merge */
1966 rc = merge_sigs( onode, node, n_sigs, fname, keyid );
1967 if( rc )
1968 return rc;
1973 /* 4th: add new user-ids */
1974 for(node=keyblock->next; node; node=node->next ) {
1975 if( node->pkt->pkttype == PKT_USER_ID) {
1976 /* do we have this in the original keyblock */
1977 for(onode=keyblock_orig->next; onode; onode=onode->next )
1978 if( onode->pkt->pkttype == PKT_USER_ID
1979 && !cmp_user_ids( onode->pkt->pkt.user_id,
1980 node->pkt->pkt.user_id ) )
1981 break;
1982 if( !onode ) { /* this is a new user id: append */
1983 rc = append_uid( keyblock_orig, node, n_sigs, fname, keyid);
1984 if( rc )
1985 return rc;
1986 ++*n_uids;
1991 /* 5th: add new subkeys */
1992 for(node=keyblock->next; node; node=node->next ) {
1993 onode = NULL;
1994 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1995 /* do we have this in the original keyblock? */
1996 for(onode=keyblock_orig->next; onode; onode=onode->next )
1997 if( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
1998 && !cmp_public_keys( onode->pkt->pkt.public_key,
1999 node->pkt->pkt.public_key ) )
2000 break;
2001 if( !onode ) { /* this is a new subkey: append */
2002 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
2003 if( rc )
2004 return rc;
2005 ++*n_subk;
2008 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2009 /* do we have this in the original keyblock? */
2010 for(onode=keyblock_orig->next; onode; onode=onode->next )
2011 if( onode->pkt->pkttype == PKT_SECRET_SUBKEY
2012 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
2013 node->pkt->pkt.secret_key ) )
2014 break;
2015 if( !onode ) { /* this is a new subkey: append */
2016 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
2017 if( rc )
2018 return rc;
2019 ++*n_subk;
2024 /* 6th: merge subkey certificates */
2025 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
2026 if( !(onode->flag & 1)
2027 && ( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
2028 || onode->pkt->pkttype == PKT_SECRET_SUBKEY) ) {
2029 /* find the subkey in the imported keyblock */
2030 for(node=keyblock->next; node; node=node->next ) {
2031 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2032 && !cmp_public_keys( onode->pkt->pkt.public_key,
2033 node->pkt->pkt.public_key ) )
2034 break;
2035 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY
2036 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
2037 node->pkt->pkt.secret_key ) )
2038 break;
2040 if( node ) { /* found: merge */
2041 rc = merge_keysigs( onode, node, n_sigs, fname, keyid );
2042 if( rc )
2043 return rc;
2049 return 0;
2053 /****************
2054 * append the userid starting with NODE and all signatures to KEYBLOCK.
2056 static int
2057 append_uid (KBNODE keyblock, KBNODE node, int *n_sigs,
2058 const char *fname, u32 *keyid )
2060 KBNODE n, n_where=NULL;
2062 (void)fname;
2063 (void)keyid;
2065 assert(node->pkt->pkttype == PKT_USER_ID );
2067 /* find the position */
2068 for( n = keyblock; n; n_where = n, n = n->next ) {
2069 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2070 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
2071 break;
2073 if( !n )
2074 n_where = NULL;
2076 /* and append/insert */
2077 while( node ) {
2078 /* we add a clone to the original keyblock, because this
2079 * one is released first */
2080 n = clone_kbnode(node);
2081 if( n_where ) {
2082 insert_kbnode( n_where, n, 0 );
2083 n_where = n;
2085 else
2086 add_kbnode( keyblock, n );
2087 n->flag |= 1;
2088 node->flag |= 1;
2089 if( n->pkt->pkttype == PKT_SIGNATURE )
2090 ++*n_sigs;
2092 node = node->next;
2093 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2094 break;
2097 return 0;
2101 /****************
2102 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
2103 * (how should we handle comment packets here?)
2105 static int
2106 merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
2107 const char *fname, u32 *keyid )
2109 KBNODE n, n2;
2110 int found=0;
2112 (void)fname;
2113 (void)keyid;
2115 assert(dst->pkt->pkttype == PKT_USER_ID );
2116 assert(src->pkt->pkttype == PKT_USER_ID );
2118 for(n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next ) {
2119 if( n->pkt->pkttype != PKT_SIGNATURE )
2120 continue;
2121 if( n->pkt->pkt.signature->sig_class == 0x18
2122 || n->pkt->pkt.signature->sig_class == 0x28 )
2123 continue; /* skip signatures which are only valid on subkeys */
2124 found = 0;
2125 for(n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
2126 if(!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
2128 found++;
2129 break;
2131 if( !found ) {
2132 /* This signature is new or newer, append N to DST.
2133 * We add a clone to the original keyblock, because this
2134 * one is released first */
2135 n2 = clone_kbnode(n);
2136 insert_kbnode( dst, n2, PKT_SIGNATURE );
2137 n2->flag |= 1;
2138 n->flag |= 1;
2139 ++*n_sigs;
2143 return 0;
2146 /****************
2147 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
2149 static int
2150 merge_keysigs (KBNODE dst, KBNODE src, int *n_sigs,
2151 const char *fname, u32 *keyid)
2153 KBNODE n, n2;
2154 int found=0;
2156 (void)fname;
2157 (void)keyid;
2159 assert( dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
2160 || dst->pkt->pkttype == PKT_SECRET_SUBKEY );
2162 for(n=src->next; n ; n = n->next ) {
2163 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2164 || n->pkt->pkttype == PKT_PUBLIC_KEY )
2165 break;
2166 if( n->pkt->pkttype != PKT_SIGNATURE )
2167 continue;
2168 found = 0;
2169 for(n2=dst->next; n2; n2 = n2->next){
2170 if( n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
2171 || n2->pkt->pkttype == PKT_PUBLIC_KEY )
2172 break;
2173 if( n2->pkt->pkttype == PKT_SIGNATURE
2174 && n->pkt->pkt.signature->keyid[0]
2175 == n2->pkt->pkt.signature->keyid[0]
2176 && n->pkt->pkt.signature->keyid[1]
2177 == n2->pkt->pkt.signature->keyid[1]
2178 && n->pkt->pkt.signature->timestamp
2179 <= n2->pkt->pkt.signature->timestamp
2180 && n->pkt->pkt.signature->sig_class
2181 == n2->pkt->pkt.signature->sig_class ) {
2182 found++;
2183 break;
2186 if( !found ) {
2187 /* This signature is new or newer, append N to DST.
2188 * We add a clone to the original keyblock, because this
2189 * one is released first */
2190 n2 = clone_kbnode(n);
2191 insert_kbnode( dst, n2, PKT_SIGNATURE );
2192 n2->flag |= 1;
2193 n->flag |= 1;
2194 ++*n_sigs;
2198 return 0;
2201 /****************
2202 * append the subkey starting with NODE and all signatures to KEYBLOCK.
2203 * Mark all new and copied packets by setting flag bit 0.
2205 static int
2206 append_key (KBNODE keyblock, KBNODE node, int *n_sigs,
2207 const char *fname, u32 *keyid)
2209 KBNODE n;
2211 (void)fname;
2212 (void)keyid;
2214 assert( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2215 || node->pkt->pkttype == PKT_SECRET_SUBKEY );
2217 while( node ) {
2218 /* we add a clone to the original keyblock, because this
2219 * one is released first */
2220 n = clone_kbnode(node);
2221 add_kbnode( keyblock, n );
2222 n->flag |= 1;
2223 node->flag |= 1;
2224 if( n->pkt->pkttype == PKT_SIGNATURE )
2225 ++*n_sigs;
2227 node = node->next;
2228 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2229 break;
2232 return 0;
2237 /* Walk a public keyblock and produce a secret keyblock out of it.
2238 Instead of inserting the secret key parameters (which we don't
2239 have), we insert a stub. */
2240 static KBNODE
2241 pub_to_sec_keyblock (KBNODE pub_keyblock)
2243 KBNODE pubnode, secnode;
2244 KBNODE sec_keyblock = NULL;
2245 KBNODE walkctx = NULL;
2247 while((pubnode = walk_kbnode (pub_keyblock,&walkctx,0)))
2249 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY
2250 || pubnode->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2252 /* Make a secret key. We only need to convert enough to
2253 write the keyblock out. */
2254 PKT_public_key *pk = pubnode->pkt->pkt.public_key;
2255 PACKET *pkt = xmalloc_clear (sizeof *pkt);
2256 PKT_secret_key *sk = xmalloc_clear (sizeof *sk);
2257 int i, n;
2259 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY)
2260 pkt->pkttype = PKT_SECRET_KEY;
2261 else
2262 pkt->pkttype = PKT_SECRET_SUBKEY;
2264 pkt->pkt.secret_key = sk;
2266 copy_public_parts_to_secret_key ( pk, sk );
2267 sk->version = pk->version;
2268 sk->timestamp = pk->timestamp;
2270 n = pubkey_get_npkey (pk->pubkey_algo);
2271 if (!n)
2272 n = 1; /* Unknown number of parameters, however the data
2273 is stored in the first mpi. */
2274 for (i=0; i < n; i++ )
2275 sk->skey[i] = mpi_copy (pk->pkey[i]);
2277 sk->is_protected = 1;
2278 sk->protect.s2k.mode = 1001;
2280 secnode = new_kbnode (pkt);
2282 else
2284 secnode = clone_kbnode (pubnode);
2287 if(!sec_keyblock)
2288 sec_keyblock = secnode;
2289 else
2290 add_kbnode (sec_keyblock, secnode);
2293 return sec_keyblock;
2297 /* Walk over the secret keyring SEC_KEYBLOCK and update any simple
2298 stub keys with the serial number SNNUM of the card if one of the
2299 fingerprints FPR1, FPR2 or FPR3 match. Print a note if the key is
2300 a duplicate (may happen in case of backed uped keys).
2302 Returns: True if anything changed.
2304 static int
2305 update_sec_keyblock_with_cardinfo (KBNODE sec_keyblock,
2306 const unsigned char *fpr1,
2307 const unsigned char *fpr2,
2308 const unsigned char *fpr3,
2309 const char *serialnostr)
2311 KBNODE node;
2312 KBNODE walkctx = NULL;
2313 PKT_secret_key *sk;
2314 byte array[MAX_FINGERPRINT_LEN];
2315 size_t n;
2316 int result = 0;
2317 const char *s;
2319 while((node = walk_kbnode (sec_keyblock, &walkctx, 0)))
2321 if (node->pkt->pkttype != PKT_SECRET_KEY
2322 && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2323 continue;
2324 sk = node->pkt->pkt.secret_key;
2326 fingerprint_from_sk (sk, array, &n);
2327 if (n != 20)
2328 continue; /* Can't be a card key. */
2329 if ( !((fpr1 && !memcmp (array, fpr1, 20))
2330 || (fpr2 && !memcmp (array, fpr2, 20))
2331 || (fpr3 && !memcmp (array, fpr3, 20))) )
2332 continue; /* No match. */
2334 if (sk->is_protected == 1 && sk->protect.s2k.mode == 1001)
2336 /* Standard case: migrate that stub to a key stub. */
2337 sk->protect.s2k.mode = 1002;
2338 s = serialnostr;
2339 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2340 sk->protect.ivlen++, s += 2)
2341 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
2342 result = 1;
2344 else if (sk->is_protected == 1 && sk->protect.s2k.mode == 1002)
2346 s = serialnostr;
2347 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2348 sk->protect.ivlen++, s += 2)
2349 if (sk->protect.iv[sk->protect.ivlen] != xtoi_2 (s))
2351 log_info (_("NOTE: a key's S/N does not "
2352 "match the card's one\n"));
2353 break;
2356 else
2358 if (node->pkt->pkttype != PKT_SECRET_KEY)
2359 log_info (_("NOTE: primary key is online and stored on card\n"));
2360 else
2361 log_info (_("NOTE: secondary key is online and stored on card\n"));
2365 return result;
2370 /* Check whether a secret key stub exists for the public key PK. If
2371 not create such a stub key and store it into the secring. If it
2372 exists, add appropriate subkey stubs and update the secring.
2373 Return 0 if the key could be created. */
2375 auto_create_card_key_stub ( const char *serialnostr,
2376 const unsigned char *fpr1,
2377 const unsigned char *fpr2,
2378 const unsigned char *fpr3)
2380 KBNODE pub_keyblock;
2381 KBNODE sec_keyblock;
2382 KEYDB_HANDLE hd;
2383 int rc;
2385 /* We only want to do this for an OpenPGP card. */
2386 if (!serialnostr || strncmp (serialnostr, "D27600012401", 12)
2387 || strlen (serialnostr) != 32 )
2388 return G10ERR_GENERAL;
2390 /* First get the public keyring from any of the provided fingerprints. */
2391 if ( (fpr1 && !get_keyblock_byfprint (&pub_keyblock, fpr1, 20))
2392 || (fpr2 && !get_keyblock_byfprint (&pub_keyblock, fpr2, 20))
2393 || (fpr3 && !get_keyblock_byfprint (&pub_keyblock, fpr3, 20)))
2395 else
2396 return G10ERR_GENERAL;
2398 hd = keydb_new (1);
2400 /* Now check whether there is a secret keyring. */
2402 PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key;
2403 byte afp[MAX_FINGERPRINT_LEN];
2404 size_t an;
2406 fingerprint_from_pk (pk, afp, &an);
2407 if (an < MAX_FINGERPRINT_LEN)
2408 memset (afp+an, 0, MAX_FINGERPRINT_LEN-an);
2409 rc = keydb_search_fpr (hd, afp);
2412 if (!rc)
2414 rc = keydb_get_keyblock (hd, &sec_keyblock);
2415 if (rc)
2417 log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
2418 rc = G10ERR_GENERAL;
2420 else
2422 merge_keys_and_selfsig (sec_keyblock);
2424 /* FIXME: We need to add new subkeys first. */
2425 if (update_sec_keyblock_with_cardinfo (sec_keyblock,
2426 fpr1, fpr2, fpr3,
2427 serialnostr))
2429 rc = keydb_update_keyblock (hd, sec_keyblock );
2430 if (rc)
2431 log_error (_("error writing keyring `%s': %s\n"),
2432 keydb_get_resource_name (hd), g10_errstr(rc) );
2436 else /* A secret key does not exists - create it. */
2438 sec_keyblock = pub_to_sec_keyblock (pub_keyblock);
2439 update_sec_keyblock_with_cardinfo (sec_keyblock,
2440 fpr1, fpr2, fpr3,
2441 serialnostr);
2443 rc = keydb_locate_writable (hd, NULL);
2444 if (rc)
2446 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
2447 rc = G10ERR_GENERAL;
2449 else
2451 rc = keydb_insert_keyblock (hd, sec_keyblock );
2452 if (rc)
2453 log_error (_("error writing keyring `%s': %s\n"),
2454 keydb_get_resource_name (hd), g10_errstr(rc) );
2458 release_kbnode (sec_keyblock);
2459 release_kbnode (pub_keyblock);
2460 keydb_release (hd);
2461 return rc;