2006-09-06 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / import.c
blob3b41e08cf8ae818937d3041b88644533f7218fd3
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,
20 * USA.
23 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <assert.h>
30 #include "gpg.h"
31 #include "options.h"
32 #include "packet.h"
33 #include "errors.h"
34 #include "keydb.h"
35 #include "util.h"
36 #include "trustdb.h"
37 #include "main.h"
38 #include "i18n.h"
39 #include "ttyio.h"
40 #include "status.h"
41 #include "keyserver-internal.h"
43 struct stats_s {
44 ulong count;
45 ulong no_user_id;
46 ulong imported;
47 ulong imported_rsa;
48 ulong n_uids;
49 ulong n_sigs;
50 ulong n_subk;
51 ulong unchanged;
52 ulong n_revoc;
53 ulong secret_read;
54 ulong secret_imported;
55 ulong secret_dups;
56 ulong skipped_new_keys;
57 ulong not_imported;
58 ulong n_sigs_cleaned;
59 ulong n_uids_cleaned;
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,int from_sk);
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 );
90 int
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},
112 /* dummy */
113 {"import-unusable-sigs",0,NULL,NULL},
114 {"import-clean-sigs",0,NULL,NULL},
115 {"import-clean-uids",0,NULL,NULL},
116 {NULL,0,NULL,NULL}
119 return parse_options(str,options,import_opts,noisy);
122 void *
123 import_new_stats_handle (void)
125 return xmalloc_clear ( sizeof (struct stats_s) );
128 void
129 import_release_stats_handle (void *p)
131 xfree (p);
134 /****************
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:
142 * - get the keyblock
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;
150 * ask what to do.
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
159 * is used.
160 * - Proceed with next signature.
162 * Key revocation certificates have special handling.
165 static int
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 )
170 int i, rc = 0;
171 struct stats_s *stats = stats_handle;
173 if (!stats)
174 stats = import_new_stats_handle ();
176 if (inp) {
177 rc = import( inp, "[stream]", stats, fpr, fpr_len, options);
179 else {
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);
186 if( !fname )
187 fname = "[stdin]";
188 if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
190 iobuf_close (inp2);
191 inp2 = NULL;
192 errno = EPERM;
194 if( !inp2 )
195 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
196 else
198 rc = import( inp2, fname, stats, fpr, fpr_len, options );
199 iobuf_close(inp2);
200 /* Must invalidate that ugly cache to actually close it. */
201 iobuf_ioctl (NULL, 2, 0, (char*)fname);
202 if( rc )
203 log_error("import from `%s' failed: %s\n", fname,
204 g10_errstr(rc) );
206 if( !fname )
207 break;
210 if (!stats_handle) {
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();
224 return rc;
227 void
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);
241 static int
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;
246 KBNODE keyblock = NULL; /* Need to initialize because gcc can't
247 grasp the return semantics of
248 read_block. */
249 int rc = 0;
251 getkey_disable_caches();
253 if( !opt.no_armor ) { /* armored reading is not disabled */
254 armor_filter_context_t *afx = xmalloc_clear( sizeof *afx );
255 afx->only_keyblocks = 1;
256 iobuf_push_filter2( inp, armor_filter, afx, 1 );
259 while( !(rc = read_block( inp, &pending_pkt, &keyblock) )) {
260 if( keyblock->pkt->pkttype == PKT_PUBLIC_KEY )
261 rc = import_one( fname, keyblock, stats, fpr, fpr_len, options, 0);
262 else if( keyblock->pkt->pkttype == PKT_SECRET_KEY )
263 rc = import_secret_one( fname, keyblock, stats, options );
264 else if( keyblock->pkt->pkttype == PKT_SIGNATURE
265 && keyblock->pkt->pkt.signature->sig_class == 0x20 )
266 rc = import_revoke_cert( fname, keyblock, stats );
267 else {
268 log_info( _("skipping block of type %d\n"),
269 keyblock->pkt->pkttype );
271 release_kbnode(keyblock);
272 /* fixme: we should increment the not imported counter but this
273 does only make sense if we keep on going despite of errors. */
274 if( rc )
275 break;
276 if( !(++stats->count % 100) && !opt.quiet )
277 log_info(_("%lu keys processed so far\n"), stats->count );
279 if( rc == -1 )
280 rc = 0;
281 else if( rc && rc != G10ERR_INV_KEYRING )
282 log_error( _("error reading `%s': %s\n"), fname, g10_errstr(rc));
284 return rc;
288 void
289 import_print_stats (void *hd)
291 struct stats_s *stats = hd;
293 if( !opt.quiet ) {
294 log_info(_("Total number processed: %lu\n"), stats->count );
295 if( stats->skipped_new_keys )
296 log_info(_(" skipped new keys: %lu\n"),
297 stats->skipped_new_keys );
298 if( stats->no_user_id )
299 log_info(_(" w/o user IDs: %lu\n"), stats->no_user_id );
300 if( stats->imported || stats->imported_rsa ) {
301 log_info(_(" imported: %lu"), stats->imported );
302 if( stats->imported_rsa )
303 fprintf(stderr, " (RSA: %lu)", stats->imported_rsa );
304 putc('\n', stderr);
306 if( stats->unchanged )
307 log_info(_(" unchanged: %lu\n"), stats->unchanged );
308 if( stats->n_uids )
309 log_info(_(" new user IDs: %lu\n"), stats->n_uids );
310 if( stats->n_subk )
311 log_info(_(" new subkeys: %lu\n"), stats->n_subk );
312 if( stats->n_sigs )
313 log_info(_(" new signatures: %lu\n"), stats->n_sigs );
314 if( stats->n_revoc )
315 log_info(_(" new key revocations: %lu\n"), stats->n_revoc );
316 if( stats->secret_read )
317 log_info(_(" secret keys read: %lu\n"), stats->secret_read );
318 if( stats->secret_imported )
319 log_info(_(" secret keys imported: %lu\n"), stats->secret_imported );
320 if( stats->secret_dups )
321 log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
322 if( stats->not_imported )
323 log_info(_(" not imported: %lu\n"), stats->not_imported );
324 if( stats->n_sigs_cleaned)
325 log_info(_(" signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
326 if( stats->n_uids_cleaned)
327 log_info(_(" user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
330 if( is_status_enabled() ) {
331 char buf[14*20];
332 sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
333 stats->count,
334 stats->no_user_id,
335 stats->imported,
336 stats->imported_rsa,
337 stats->unchanged,
338 stats->n_uids,
339 stats->n_subk,
340 stats->n_sigs,
341 stats->n_revoc,
342 stats->secret_read,
343 stats->secret_imported,
344 stats->secret_dups,
345 stats->skipped_new_keys,
346 stats->not_imported );
347 write_status_text( STATUS_IMPORT_RES, buf );
352 /****************
353 * Read the next keyblock from stream A.
354 * PENDING_PKT should be initialzed to NULL
355 * and not chnaged form the caller.
356 * Retunr: 0 = okay, -1 no more blocks or another errorcode.
358 static int
359 read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root )
361 int rc;
362 PACKET *pkt;
363 KBNODE root = NULL;
364 int in_cert;
366 if( *pending_pkt ) {
367 root = new_kbnode( *pending_pkt );
368 *pending_pkt = NULL;
369 in_cert = 1;
371 else
372 in_cert = 0;
373 pkt = xmalloc( sizeof *pkt );
374 init_packet(pkt);
375 while( (rc=parse_packet(a, pkt)) != -1 ) {
376 if( rc ) { /* ignore errors */
377 if( rc != G10ERR_UNKNOWN_PACKET ) {
378 log_error("read_block: read error: %s\n", g10_errstr(rc) );
379 rc = G10ERR_INV_KEYRING;
380 goto ready;
382 free_packet( pkt );
383 init_packet(pkt);
384 continue;
387 if( !root && pkt->pkttype == PKT_SIGNATURE
388 && pkt->pkt.signature->sig_class == 0x20 ) {
389 /* this is a revocation certificate which is handled
390 * in a special way */
391 root = new_kbnode( pkt );
392 pkt = NULL;
393 goto ready;
396 /* make a linked list of all packets */
397 switch( pkt->pkttype ) {
398 case PKT_COMPRESSED:
399 if(check_compress_algo(pkt->pkt.compressed->algorithm))
401 rc = G10ERR_COMPR_ALGO;
402 goto ready;
404 else
406 compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
407 pkt->pkt.compressed->buf = NULL;
408 push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1);
410 free_packet( pkt );
411 init_packet(pkt);
412 break;
414 case PKT_RING_TRUST:
415 /* skip those packets */
416 free_packet( pkt );
417 init_packet(pkt);
418 break;
420 case PKT_PUBLIC_KEY:
421 case PKT_SECRET_KEY:
422 if( in_cert ) { /* store this packet */
423 *pending_pkt = pkt;
424 pkt = NULL;
425 goto ready;
427 in_cert = 1;
428 default:
429 if( in_cert ) {
430 if( !root )
431 root = new_kbnode( pkt );
432 else
433 add_kbnode( root, new_kbnode( pkt ) );
434 pkt = xmalloc( sizeof *pkt );
436 init_packet(pkt);
437 break;
440 ready:
441 if( rc == -1 && root )
442 rc = 0;
444 if( rc )
445 release_kbnode( root );
446 else
447 *ret_root = root;
448 free_packet( pkt );
449 xfree( pkt );
450 return rc;
453 /* Walk through the subkeys on a pk to find if we have the PKS
454 disease: multiple subkeys with their binding sigs stripped, and the
455 sig for the first subkey placed after the last subkey. That is,
456 instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
457 "pk uid sig sub1 sub2 sub3 bind1". We can't do anything about sub2
458 and sub3, as they are already lost, but we can try and rescue sub1
459 by reordering the keyblock so that it reads "pk uid sig sub1 bind1
460 sub2 sub3". Returns TRUE if the keyblock was modified. */
462 static int
463 fix_pks_corruption(KBNODE keyblock)
465 int changed=0,keycount=0;
466 KBNODE node,last=NULL,sknode=NULL;
468 /* First determine if we have the problem at all. Look for 2 or
469 more subkeys in a row, followed by a single binding sig. */
470 for(node=keyblock;node;last=node,node=node->next)
472 if(node->pkt->pkttype==PKT_PUBLIC_SUBKEY)
474 keycount++;
475 if(!sknode)
476 sknode=node;
478 else if(node->pkt->pkttype==PKT_SIGNATURE &&
479 node->pkt->pkt.signature->sig_class==0x18 &&
480 keycount>=2 && node->next==NULL)
482 /* We might have the problem, as this key has two subkeys in
483 a row without any intervening packets. */
485 /* Sanity check */
486 if(last==NULL)
487 break;
489 /* Temporarily attach node to sknode. */
490 node->next=sknode->next;
491 sknode->next=node;
492 last->next=NULL;
494 /* Note we aren't checking whether this binding sig is a
495 selfsig. This is not necessary here as the subkey and
496 binding sig will be rejected later if that is the
497 case. */
498 if(check_key_signature(keyblock,node,NULL))
500 /* Not a match, so undo the changes. */
501 sknode->next=node->next;
502 last->next=node;
503 node->next=NULL;
504 break;
506 else
508 sknode->flag |= 1; /* Mark it good so we don't need to
509 check it again */
510 changed=1;
511 break;
514 else
515 keycount=0;
518 return changed;
522 static void
523 print_import_ok (PKT_public_key *pk, PKT_secret_key *sk, unsigned int reason)
525 byte array[MAX_FINGERPRINT_LEN], *s;
526 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
527 size_t i, n;
529 sprintf (buf, "%u ", reason);
530 p = buf + strlen (buf);
532 if (pk)
533 fingerprint_from_pk (pk, array, &n);
534 else
535 fingerprint_from_sk (sk, array, &n);
536 s = array;
537 for (i=0; i < n ; i++, s++, p += 2)
538 sprintf (p, "%02X", *s);
540 write_status_text (STATUS_IMPORT_OK, buf);
543 static void
544 print_import_check (PKT_public_key * pk, PKT_user_id * id)
546 char * buf;
547 byte fpr[24];
548 u32 keyid[2];
549 size_t i, pos = 0, n;
551 buf = xmalloc (17+41+id->len+32);
552 keyid_from_pk (pk, keyid);
553 sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
554 pos = 17;
555 fingerprint_from_pk (pk, fpr, &n);
556 for (i = 0; i < n; i++, pos += 2)
557 sprintf (buf+pos, "%02X", fpr[i]);
558 strcat (buf, " ");
559 pos += 1;
560 strcat (buf, id->name);
561 write_status_text (STATUS_IMPORT_CHECK, buf);
562 xfree (buf);
565 static void
566 check_prefs_warning(PKT_public_key *pk)
568 log_info(_("WARNING: key %s contains preferences for unavailable\n"
569 "algorithms on these user IDs:\n"), keystr_from_pk(pk));
572 static void
573 check_prefs(KBNODE keyblock)
575 KBNODE node;
576 PKT_public_key *pk;
577 int problem=0;
579 merge_keys_and_selfsig(keyblock);
580 pk=keyblock->pkt->pkt.public_key;
582 for(node=keyblock;node;node=node->next)
584 if(node->pkt->pkttype==PKT_USER_ID
585 && node->pkt->pkt.user_id->created
586 && node->pkt->pkt.user_id->prefs)
588 PKT_user_id *uid=node->pkt->pkt.user_id;
589 prefitem_t *prefs=uid->prefs;
590 char *user=utf8_to_native(uid->name,strlen(uid->name),0);
592 for(;prefs->type;prefs++)
594 char num[10]; /* prefs->value is a byte, so we're over
595 safe here */
597 sprintf(num,"%u",prefs->value);
599 if(prefs->type==PREFTYPE_SYM)
601 if (openpgp_cipher_test_algo (prefs->value))
603 const char *algo = gcry_cipher_algo_name (prefs->value);
604 if(!problem)
605 check_prefs_warning(pk);
606 log_info(_(" \"%s\": preference for cipher"
607 " algorithm %s\n"),user,algo?algo:num);
608 problem=1;
611 else if(prefs->type==PREFTYPE_HASH)
613 if(openpgp_md_test_algo(prefs->value))
615 const char *algo = gcry_md_algo_name (prefs->value);
616 if(!problem)
617 check_prefs_warning(pk);
618 log_info(_(" \"%s\": preference for digest"
619 " algorithm %s\n"),user,algo?algo:num);
620 problem=1;
623 else if(prefs->type==PREFTYPE_ZIP)
625 if(check_compress_algo (prefs->value))
627 const char *algo=compress_algo_to_string(prefs->value);
628 if(!problem)
629 check_prefs_warning(pk);
630 log_info(_(" \"%s\": preference for compression"
631 " algorithm %s\n"),user,algo?algo:num);
632 problem=1;
637 xfree(user);
641 if(problem)
643 log_info(_("it is strongly suggested that you update"
644 " your preferences and\n"));
645 log_info(_("re-distribute this key to avoid potential algorithm"
646 " mismatch problems\n"));
648 if(!opt.batch)
650 STRLIST sl=NULL,locusr=NULL;
651 size_t fprlen=0;
652 byte fpr[MAX_FINGERPRINT_LEN],*p;
653 char username[(MAX_FINGERPRINT_LEN*2)+1];
654 unsigned int i;
656 p=fingerprint_from_pk(pk,fpr,&fprlen);
657 for(i=0;i<fprlen;i++,p++)
658 sprintf(username+2*i,"%02X",*p);
659 add_to_strlist(&locusr,username);
661 append_to_strlist(&sl,"updpref");
662 append_to_strlist(&sl,"save");
664 keyedit_menu( username, locusr, sl, 1, 1 );
665 free_strlist(sl);
666 free_strlist(locusr);
668 else if(!opt.quiet)
669 log_info(_("you can update your preferences with:"
670 " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
674 /****************
675 * Try to import one keyblock. Return an error only in serious cases, but
676 * never for an invalid keyblock. It uses log_error to increase the
677 * internal errorcount, so that invalid input can be detected by programs
678 * which called g10.
680 static int
681 import_one( const char *fname, KBNODE keyblock, struct stats_s *stats,
682 unsigned char **fpr,size_t *fpr_len,unsigned int options,
683 int from_sk )
685 PKT_public_key *pk;
686 PKT_public_key *pk_orig;
687 KBNODE node, uidnode;
688 KBNODE keyblock_orig = NULL;
689 u32 keyid[2];
690 int rc = 0;
691 int new_key = 0;
692 int mod_key = 0;
693 int non_self = 0;
695 /* get the key and print some info about it */
696 node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
697 if( !node )
698 BUG();
700 pk = node->pkt->pkt.public_key;
702 keyid_from_pk( pk, keyid );
703 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
705 if( opt.verbose && !opt.interactive )
707 log_info( "pub %4u%c/%s %s ",
708 nbits_from_pk( pk ),
709 pubkey_letter( pk->pubkey_algo ),
710 keystr_from_pk(pk), datestr_from_pk(pk) );
711 if( uidnode )
712 print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
713 uidnode->pkt->pkt.user_id->len );
714 putc('\n', stderr);
717 if( !uidnode )
719 log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
720 return 0;
723 if (opt.interactive) {
724 if(is_status_enabled())
725 print_import_check (pk, uidnode->pkt->pkt.user_id);
726 merge_keys_and_selfsig (keyblock);
727 tty_printf ("\n");
728 show_basic_key_info (keyblock);
729 tty_printf ("\n");
730 if (!cpr_get_answer_is_yes ("import.okay",
731 "Do you want to import this key? (y/N) "))
732 return 0;
735 collapse_uids(&keyblock);
737 /* Clean the key that we're about to import, to cut down on things
738 that we have to clean later. This has no practical impact on
739 the end result, but does result in less logging which might
740 confuse the user. */
741 if(options&IMPORT_CLEAN)
742 clean_key(keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL);
744 clear_kbnode_flags( keyblock );
746 if((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
747 && opt.verbose)
748 log_info(_("key %s: PKS subkey corruption repaired\n"),
749 keystr_from_pk(pk));
751 rc = chk_self_sigs( fname, keyblock , pk, keyid, &non_self );
752 if( rc )
753 return rc== -1? 0:rc;
755 /* If we allow such a thing, mark unsigned uids as valid */
756 if( opt.allow_non_selfsigned_uid )
757 for( node=keyblock; node; node = node->next )
758 if( node->pkt->pkttype == PKT_USER_ID && !(node->flag & 1) )
760 char *user=utf8_to_native(node->pkt->pkt.user_id->name,
761 node->pkt->pkt.user_id->len,0);
762 node->flag |= 1;
763 log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
764 keystr_from_pk(pk),user);
765 xfree(user);
768 if( !delete_inv_parts( fname, keyblock, keyid, options ) ) {
769 log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
770 if( !opt.quiet )
771 log_info(_("this may be caused by a missing self-signature\n"));
772 stats->no_user_id++;
773 return 0;
776 /* do we have this key already in one of our pubrings ? */
777 pk_orig = xmalloc_clear( sizeof *pk_orig );
778 rc = get_pubkey_fast ( pk_orig, keyid );
779 if( rc && rc != G10ERR_NO_PUBKEY && rc != G10ERR_UNU_PUBKEY )
781 log_error( _("key %s: public key not found: %s\n"),
782 keystr(keyid), g10_errstr(rc));
784 else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) )
786 if( opt.verbose )
787 log_info( _("key %s: new key - skipped\n"), keystr(keyid));
788 rc = 0;
789 stats->skipped_new_keys++;
791 else if( rc ) { /* insert this key */
792 KEYDB_HANDLE hd = keydb_new (0);
794 rc = keydb_locate_writable (hd, NULL);
795 if (rc) {
796 log_error (_("no writable keyring found: %s\n"), g10_errstr (rc));
797 keydb_release (hd);
798 return G10ERR_GENERAL;
800 if( opt.verbose > 1 )
801 log_info (_("writing to `%s'\n"), keydb_get_resource_name (hd) );
803 rc = keydb_insert_keyblock (hd, keyblock );
804 if (rc)
805 log_error (_("error writing keyring `%s': %s\n"),
806 keydb_get_resource_name (hd), g10_errstr(rc));
807 else
809 /* This should not be possible since we delete the
810 ownertrust when a key is deleted, but it can happen if
811 the keyring and trustdb are out of sync. It can also
812 be made to happen with the trusted-key command. */
814 clear_ownertrusts (pk);
815 if(non_self)
816 revalidation_mark ();
818 keydb_release (hd);
820 /* we are ready */
821 if( !opt.quiet )
823 char *p=get_user_id_native (keyid);
824 log_info( _("key %s: public key \"%s\" imported\n"),
825 keystr(keyid),p);
826 xfree(p);
828 if( is_status_enabled() )
830 char *us = get_long_user_id_string( keyid );
831 write_status_text( STATUS_IMPORTED, us );
832 xfree(us);
833 print_import_ok (pk,NULL, 1);
835 stats->imported++;
836 if( is_RSA( pk->pubkey_algo ) )
837 stats->imported_rsa++;
838 new_key = 1;
840 else { /* merge */
841 KEYDB_HANDLE hd;
842 int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
844 /* Compare the original against the new key; just to be sure nothing
845 * weird is going on */
846 if( cmp_public_keys( pk_orig, pk ) )
848 log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
849 goto leave;
852 /* now read the original keyblock */
853 hd = keydb_new (0);
855 byte afp[MAX_FINGERPRINT_LEN];
856 size_t an;
858 fingerprint_from_pk (pk_orig, afp, &an);
859 while (an < MAX_FINGERPRINT_LEN)
860 afp[an++] = 0;
861 rc = keydb_search_fpr (hd, afp);
863 if( rc )
865 log_error (_("key %s: can't locate original keyblock: %s\n"),
866 keystr(keyid), g10_errstr(rc));
867 keydb_release (hd);
868 goto leave;
870 rc = keydb_get_keyblock (hd, &keyblock_orig );
871 if (rc)
873 log_error (_("key %s: can't read original keyblock: %s\n"),
874 keystr(keyid), g10_errstr(rc));
875 keydb_release (hd);
876 goto leave;
879 /* and try to merge the block */
880 clear_kbnode_flags( keyblock_orig );
881 clear_kbnode_flags( keyblock );
882 n_uids = n_sigs = n_subk = n_sigs_cleaned = n_uids_cleaned = 0;
883 rc = merge_blocks( fname, keyblock_orig, keyblock,
884 keyid, &n_uids, &n_sigs, &n_subk );
885 if( rc )
887 keydb_release (hd);
888 goto leave;
891 if(options&IMPORT_CLEAN)
892 clean_key(keyblock_orig,opt.verbose,options&IMPORT_MINIMAL,
893 &n_uids_cleaned,&n_sigs_cleaned);
895 if( n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned) {
896 mod_key = 1;
897 /* keyblock_orig has been updated; write */
898 rc = keydb_update_keyblock (hd, keyblock_orig);
899 if (rc)
900 log_error (_("error writing keyring `%s': %s\n"),
901 keydb_get_resource_name (hd), g10_errstr(rc) );
902 else if(non_self)
903 revalidation_mark ();
905 /* we are ready */
906 if( !opt.quiet )
908 char *p=get_user_id_native(keyid);
909 if( n_uids == 1 )
910 log_info( _("key %s: \"%s\" 1 new user ID\n"),
911 keystr(keyid),p);
912 else if( n_uids )
913 log_info( _("key %s: \"%s\" %d new user IDs\n"),
914 keystr(keyid),p,n_uids);
915 if( n_sigs == 1 )
916 log_info( _("key %s: \"%s\" 1 new signature\n"),
917 keystr(keyid), p);
918 else if( n_sigs )
919 log_info( _("key %s: \"%s\" %d new signatures\n"),
920 keystr(keyid), p, n_sigs );
921 if( n_subk == 1 )
922 log_info( _("key %s: \"%s\" 1 new subkey\n"),
923 keystr(keyid), p);
924 else if( n_subk )
925 log_info( _("key %s: \"%s\" %d new subkeys\n"),
926 keystr(keyid), p, n_subk );
927 if(n_sigs_cleaned==1)
928 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
929 keystr(keyid),p,n_sigs_cleaned);
930 else if(n_sigs_cleaned)
931 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
932 keystr(keyid),p,n_sigs_cleaned);
933 if(n_uids_cleaned==1)
934 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
935 keystr(keyid),p,n_uids_cleaned);
936 else if(n_uids_cleaned)
937 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
938 keystr(keyid),p,n_uids_cleaned);
939 xfree(p);
942 stats->n_uids +=n_uids;
943 stats->n_sigs +=n_sigs;
944 stats->n_subk +=n_subk;
945 stats->n_sigs_cleaned +=n_sigs_cleaned;
946 stats->n_uids_cleaned +=n_uids_cleaned;
948 if (is_status_enabled ())
949 print_import_ok (pk, NULL,
950 ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
952 else
954 if (is_status_enabled ())
955 print_import_ok (pk, NULL, 0);
957 if( !opt.quiet )
959 char *p=get_user_id_native(keyid);
960 log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
961 xfree(p);
964 stats->unchanged++;
967 keydb_release (hd); hd = NULL;
970 leave:
972 /* Now that the key is definitely incorporated into the keydb, we
973 need to check if a designated revocation is present or if the
974 prefs are not rational so we can warn the user. */
976 if(mod_key)
978 revocation_present(keyblock_orig);
979 if(!from_sk && seckey_available(keyid)==0)
980 check_prefs(keyblock_orig);
982 else if(new_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 fingerpring
991 at all, and we must hope the user ID on the keys are
992 useful. */
993 if(fpr)
995 xfree(*fpr);
996 if(stats->imported==1)
997 *fpr=fingerprint_from_pk(pk,NULL,fpr_len);
998 else
999 *fpr=NULL;
1002 revocation_present(keyblock);
1003 if(!from_sk && seckey_available(keyid)==0)
1004 check_prefs(keyblock);
1007 release_kbnode( keyblock_orig );
1008 free_public_key( pk_orig );
1010 return rc;
1013 /* Walk a secret keyblock and produce a public keyblock out of it. */
1014 static KBNODE
1015 sec_to_pub_keyblock(KBNODE sec_keyblock)
1017 KBNODE secnode,pub_keyblock=NULL,ctx=NULL;
1019 while((secnode=walk_kbnode(sec_keyblock,&ctx,0)))
1021 KBNODE pubnode;
1023 if(secnode->pkt->pkttype==PKT_SECRET_KEY ||
1024 secnode->pkt->pkttype==PKT_SECRET_SUBKEY)
1026 /* Make a public key. We only need to convert enough to
1027 write the keyblock out. */
1029 PKT_secret_key *sk=secnode->pkt->pkt.secret_key;
1030 PACKET *pkt=xmalloc_clear(sizeof(PACKET));
1031 PKT_public_key *pk=xmalloc_clear(sizeof(PKT_public_key));
1032 int n;
1034 if(secnode->pkt->pkttype==PKT_SECRET_KEY)
1035 pkt->pkttype=PKT_PUBLIC_KEY;
1036 else
1037 pkt->pkttype=PKT_PUBLIC_SUBKEY;
1039 pkt->pkt.public_key=pk;
1041 pk->version=sk->version;
1042 pk->timestamp=sk->timestamp;
1043 pk->expiredate=sk->expiredate;
1044 pk->pubkey_algo=sk->pubkey_algo;
1046 n=pubkey_get_npkey(pk->pubkey_algo);
1047 if(n==0)
1049 /* we can't properly extract the pubkey without knowing
1050 the number of MPIs */
1051 release_kbnode(pub_keyblock);
1052 return NULL;
1054 else
1056 int i;
1058 for(i=0;i<n;i++)
1059 pk->pkey[i]=mpi_copy(sk->skey[i]);
1062 pubnode=new_kbnode(pkt);
1064 else
1066 pubnode=clone_kbnode(secnode);
1069 if(pub_keyblock==NULL)
1070 pub_keyblock=pubnode;
1071 else
1072 add_kbnode(pub_keyblock,pubnode);
1075 return pub_keyblock;
1078 /****************
1079 * Ditto for secret keys. Handling is simpler than for public keys.
1080 * We allow secret key importing only when allow is true, this is so
1081 * that a secret key can not be imported accidently and thereby tampering
1082 * with the trust calculation.
1084 static int
1085 import_secret_one( const char *fname, KBNODE keyblock,
1086 struct stats_s *stats, unsigned int options)
1088 PKT_secret_key *sk;
1089 KBNODE node, uidnode;
1090 u32 keyid[2];
1091 int rc = 0;
1093 /* get the key and print some info about it */
1094 node = find_kbnode( keyblock, PKT_SECRET_KEY );
1095 if( !node )
1096 BUG();
1098 sk = node->pkt->pkt.secret_key;
1099 keyid_from_sk( sk, keyid );
1100 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1102 if( opt.verbose )
1104 log_info( "sec %4u%c/%s %s ",
1105 nbits_from_sk( sk ),
1106 pubkey_letter( sk->pubkey_algo ),
1107 keystr_from_sk(sk), datestr_from_sk(sk) );
1108 if( uidnode )
1109 print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
1110 uidnode->pkt->pkt.user_id->len );
1111 putc('\n', stderr);
1113 stats->secret_read++;
1115 if( !uidnode )
1117 log_error( _("key %s: no user ID\n"), keystr_from_sk(sk));
1118 return 0;
1121 if(sk->protect.algo>110)
1123 log_error(_("key %s: secret key with invalid cipher %d"
1124 " - skipped\n"),keystr_from_sk(sk),sk->protect.algo);
1125 return 0;
1128 #ifdef ENABLE_SELINUX_HACKS
1129 if (1)
1131 /* We don't allow to import secret keys because that may be used
1132 to put a secret key into the keyring and the user might later
1133 be tricked into signing stuff with that key. */
1134 log_error (_("importing secret keys not allowed\n"));
1135 return 0;
1137 #endif
1139 clear_kbnode_flags( keyblock );
1141 /* do we have this key already in one of our secrings ? */
1142 rc = seckey_available( keyid );
1143 if( rc == G10ERR_NO_SECKEY && !(opt.import_options&IMPORT_MERGE_ONLY) )
1145 /* simply insert this key */
1146 KEYDB_HANDLE hd = keydb_new (1);
1148 /* get default resource */
1149 rc = keydb_locate_writable (hd, NULL);
1150 if (rc) {
1151 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
1152 keydb_release (hd);
1153 return G10ERR_GENERAL;
1155 rc = keydb_insert_keyblock (hd, keyblock );
1156 if (rc)
1157 log_error (_("error writing keyring `%s': %s\n"),
1158 keydb_get_resource_name (hd), g10_errstr(rc) );
1159 keydb_release (hd);
1160 /* we are ready */
1161 if( !opt.quiet )
1162 log_info( _("key %s: secret key imported\n"), keystr_from_sk(sk));
1163 stats->secret_imported++;
1164 if (is_status_enabled ())
1165 print_import_ok (NULL, sk, 1|16);
1167 if(options&IMPORT_SK2PK)
1169 /* Try and make a public key out of this. */
1171 KBNODE pub_keyblock=sec_to_pub_keyblock(keyblock);
1172 if(pub_keyblock)
1174 import_one(fname,pub_keyblock,stats,
1175 NULL,NULL,opt.import_options,1);
1176 release_kbnode(pub_keyblock);
1180 /* Now that the key is definitely incorporated into the keydb,
1181 if we have the public part of this key, we need to check if
1182 the prefs are rational. */
1183 node=get_pubkeyblock(keyid);
1184 if(node)
1186 check_prefs(node);
1187 release_kbnode(node);
1190 else if( !rc )
1191 { /* we can't merge secret keys */
1192 log_error( _("key %s: already in secret keyring\n"),
1193 keystr_from_sk(sk));
1194 stats->secret_dups++;
1195 if (is_status_enabled ())
1196 print_import_ok (NULL, sk, 16);
1198 /* TODO: if we ever do merge secret keys, make sure to handle
1199 the sec_to_pub_keyblock feature as well. */
1201 else
1202 log_error( _("key %s: secret key not found: %s\n"),
1203 keystr_from_sk(sk), g10_errstr(rc));
1205 return rc;
1209 /****************
1210 * Import a revocation certificate; this is a single signature packet.
1212 static int
1213 import_revoke_cert( const char *fname, KBNODE node, struct stats_s *stats )
1215 PKT_public_key *pk=NULL;
1216 KBNODE onode, keyblock = NULL;
1217 KEYDB_HANDLE hd = NULL;
1218 u32 keyid[2];
1219 int rc = 0;
1221 assert( !node->next );
1222 assert( node->pkt->pkttype == PKT_SIGNATURE );
1223 assert( node->pkt->pkt.signature->sig_class == 0x20 );
1225 keyid[0] = node->pkt->pkt.signature->keyid[0];
1226 keyid[1] = node->pkt->pkt.signature->keyid[1];
1228 pk = xmalloc_clear( sizeof *pk );
1229 rc = get_pubkey( pk, keyid );
1230 if( rc == G10ERR_NO_PUBKEY )
1232 log_error(_("key %s: no public key -"
1233 " can't apply revocation certificate\n"), keystr(keyid));
1234 rc = 0;
1235 goto leave;
1237 else if( rc )
1239 log_error(_("key %s: public key not found: %s\n"),
1240 keystr(keyid), g10_errstr(rc));
1241 goto leave;
1244 /* read the original keyblock */
1245 hd = keydb_new (0);
1247 byte afp[MAX_FINGERPRINT_LEN];
1248 size_t an;
1250 fingerprint_from_pk (pk, afp, &an);
1251 while (an < MAX_FINGERPRINT_LEN)
1252 afp[an++] = 0;
1253 rc = keydb_search_fpr (hd, afp);
1255 if (rc)
1257 log_error (_("key %s: can't locate original keyblock: %s\n"),
1258 keystr(keyid), g10_errstr(rc));
1259 goto leave;
1261 rc = keydb_get_keyblock (hd, &keyblock );
1262 if (rc)
1264 log_error (_("key %s: can't read original keyblock: %s\n"),
1265 keystr(keyid), g10_errstr(rc));
1266 goto leave;
1269 /* it is okay, that node is not in keyblock because
1270 * check_key_signature works fine for sig_class 0x20 in this
1271 * special case. */
1272 rc = check_key_signature( keyblock, node, NULL);
1273 if( rc )
1275 log_error( _("key %s: invalid revocation certificate"
1276 ": %s - rejected\n"), keystr(keyid), g10_errstr(rc));
1277 goto leave;
1280 /* check whether we already have this */
1281 for(onode=keyblock->next; onode; onode=onode->next ) {
1282 if( onode->pkt->pkttype == PKT_USER_ID )
1283 break;
1284 else if( onode->pkt->pkttype == PKT_SIGNATURE
1285 && !cmp_signatures(node->pkt->pkt.signature,
1286 onode->pkt->pkt.signature))
1288 rc = 0;
1289 goto leave; /* yes, we already know about it */
1294 /* insert it */
1295 insert_kbnode( keyblock, clone_kbnode(node), 0 );
1297 /* and write the keyblock back */
1298 rc = keydb_update_keyblock (hd, keyblock );
1299 if (rc)
1300 log_error (_("error writing keyring `%s': %s\n"),
1301 keydb_get_resource_name (hd), g10_errstr(rc) );
1302 keydb_release (hd); hd = NULL;
1303 /* we are ready */
1304 if( !opt.quiet )
1306 char *p=get_user_id_native (keyid);
1307 log_info( _("key %s: \"%s\" revocation certificate imported\n"),
1308 keystr(keyid),p);
1309 xfree(p);
1311 stats->n_revoc++;
1313 /* If the key we just revoked was ultimately trusted, remove its
1314 ultimate trust. This doesn't stop the user from putting the
1315 ultimate trust back, but is a reasonable solution for now. */
1316 if(get_ownertrust(pk)==TRUST_ULTIMATE)
1317 clear_ownertrusts(pk);
1319 revalidation_mark ();
1321 leave:
1322 keydb_release (hd);
1323 release_kbnode( keyblock );
1324 free_public_key( pk );
1325 return rc;
1329 /****************
1330 * loop over the keyblock and check all self signatures.
1331 * Mark all user-ids with a self-signature by setting flag bit 0.
1332 * Mark all user-ids with an invalid self-signature by setting bit 1.
1333 * This works also for subkeys, here the subkey is marked. Invalid or
1334 * extra subkey sigs (binding or revocation) are marked for deletion.
1335 * non_self is set to true if there are any sigs other than self-sigs
1336 * in this keyblock.
1338 static int
1339 chk_self_sigs( const char *fname, KBNODE keyblock,
1340 PKT_public_key *pk, u32 *keyid, int *non_self )
1342 KBNODE n,knode=NULL;
1343 PKT_signature *sig;
1344 int rc;
1345 u32 bsdate=0,rsdate=0;
1346 KBNODE bsnode=NULL,rsnode=NULL;
1348 for( n=keyblock; (n = find_next_kbnode(n, 0)); ) {
1349 if(n->pkt->pkttype==PKT_PUBLIC_SUBKEY)
1351 knode=n;
1352 bsdate=0;
1353 rsdate=0;
1354 bsnode=NULL;
1355 rsnode=NULL;
1356 continue;
1358 else if( n->pkt->pkttype != PKT_SIGNATURE )
1359 continue;
1360 sig = n->pkt->pkt.signature;
1361 if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] ) {
1363 /* This just caches the sigs for later use. That way we
1364 import a fully-cached key which speeds things up. */
1365 if(!opt.no_sig_cache)
1366 check_key_signature(keyblock,n,NULL);
1368 if( IS_UID_SIG(sig) || IS_UID_REV(sig) )
1370 KBNODE unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
1371 if( !unode )
1373 log_error( _("key %s: no user ID for signature\n"),
1374 keystr(keyid));
1375 return -1; /* the complete keyblock is invalid */
1378 /* If it hasn't been marked valid yet, keep trying */
1379 if(!(unode->flag&1)) {
1380 rc = check_key_signature( keyblock, n, NULL);
1381 if( rc )
1383 if( opt.verbose )
1385 char *p=utf8_to_native(unode->pkt->pkt.user_id->name,
1386 strlen(unode->pkt->pkt.user_id->name),0);
1387 log_info( rc == G10ERR_PUBKEY_ALGO ?
1388 _("key %s: unsupported public key "
1389 "algorithm on user ID \"%s\"\n"):
1390 _("key %s: invalid self-signature "
1391 "on user ID \"%s\"\n"),
1392 keystr(keyid),p);
1393 xfree(p);
1396 else
1397 unode->flag |= 1; /* mark that signature checked */
1400 else if( sig->sig_class == 0x18 ) {
1401 /* Note that this works based solely on the timestamps
1402 like the rest of gpg. If the standard gets
1403 revocation targets, this may need to be revised. */
1405 if( !knode )
1407 if(opt.verbose)
1408 log_info( _("key %s: no subkey for key binding\n"),
1409 keystr(keyid));
1410 n->flag |= 4; /* delete this */
1412 else
1414 rc = check_key_signature( keyblock, n, NULL);
1415 if( rc )
1417 if(opt.verbose)
1418 log_info(rc == G10ERR_PUBKEY_ALGO ?
1419 _("key %s: unsupported public key"
1420 " algorithm\n"):
1421 _("key %s: invalid subkey binding\n"),
1422 keystr(keyid));
1423 n->flag|=4;
1425 else
1427 /* It's valid, so is it newer? */
1428 if(sig->timestamp>=bsdate) {
1429 knode->flag |= 1; /* the subkey is valid */
1430 if(bsnode)
1432 bsnode->flag|=4; /* Delete the last binding
1433 sig since this one is
1434 newer */
1435 if(opt.verbose)
1436 log_info(_("key %s: removed multiple subkey"
1437 " binding\n"),keystr(keyid));
1440 bsnode=n;
1441 bsdate=sig->timestamp;
1443 else
1444 n->flag|=4; /* older */
1448 else if( sig->sig_class == 0x28 ) {
1449 /* We don't actually mark the subkey as revoked right
1450 now, so just check that the revocation sig is the
1451 most recent valid one. Note that we don't care if
1452 the binding sig is newer than the revocation sig.
1453 See the comment in getkey.c:merge_selfsigs_subkey for
1454 more */
1455 if( !knode )
1457 if(opt.verbose)
1458 log_info( _("key %s: no subkey for key revocation\n"),
1459 keystr(keyid));
1460 n->flag |= 4; /* delete this */
1462 else
1464 rc = check_key_signature( keyblock, n, NULL);
1465 if( rc )
1467 if(opt.verbose)
1468 log_info(rc == G10ERR_PUBKEY_ALGO ?
1469 _("key %s: unsupported public"
1470 " key algorithm\n"):
1471 _("key %s: invalid subkey revocation\n"),
1472 keystr(keyid));
1473 n->flag|=4;
1475 else
1477 /* It's valid, so is it newer? */
1478 if(sig->timestamp>=rsdate)
1480 if(rsnode)
1482 rsnode->flag|=4; /* Delete the last revocation
1483 sig since this one is
1484 newer */
1485 if(opt.verbose)
1486 log_info(_("key %s: removed multiple subkey"
1487 " revocation\n"),keystr(keyid));
1490 rsnode=n;
1491 rsdate=sig->timestamp;
1493 else
1494 n->flag|=4; /* older */
1499 else
1500 *non_self=1;
1503 return 0;
1506 /****************
1507 * delete all parts which are invalid and those signatures whose
1508 * public key algorithm is not available in this implemenation;
1509 * but consider RSA as valid, because parse/build_packets knows
1510 * about it.
1511 * returns: true if at least one valid user-id is left over.
1513 static int
1514 delete_inv_parts( const char *fname, KBNODE keyblock,
1515 u32 *keyid, unsigned int options)
1517 KBNODE node;
1518 int nvalid=0, uid_seen=0, subkey_seen=0;
1520 for(node=keyblock->next; node; node = node->next ) {
1521 if( node->pkt->pkttype == PKT_USER_ID ) {
1522 uid_seen = 1;
1523 if( (node->flag & 2) || !(node->flag & 1) ) {
1524 if( opt.verbose )
1526 char *p=utf8_to_native(node->pkt->pkt.user_id->name,
1527 node->pkt->pkt.user_id->len,0);
1528 log_info( _("key %s: skipped user ID \"%s\"\n"),
1529 keystr(keyid),p);
1530 xfree(p);
1532 delete_kbnode( node ); /* the user-id */
1533 /* and all following packets up to the next user-id */
1534 while( node->next
1535 && node->next->pkt->pkttype != PKT_USER_ID
1536 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1537 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
1538 delete_kbnode( node->next );
1539 node = node->next;
1542 else
1543 nvalid++;
1545 else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1546 || node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1547 if( (node->flag & 2) || !(node->flag & 1) ) {
1548 if( opt.verbose )
1549 log_info( _("key %s: skipped subkey\n"),keystr(keyid));
1551 delete_kbnode( node ); /* the subkey */
1552 /* and all following signature packets */
1553 while( node->next
1554 && node->next->pkt->pkttype == PKT_SIGNATURE ) {
1555 delete_kbnode( node->next );
1556 node = node->next;
1559 else
1560 subkey_seen = 1;
1562 else if (node->pkt->pkttype == PKT_SIGNATURE
1563 && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
1564 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
1565 delete_kbnode( node ); /* build_packet() can't handle this */
1566 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1567 !node->pkt->pkt.signature->flags.exportable &&
1568 !(options&IMPORT_LOCAL_SIGS) &&
1569 seckey_available( node->pkt->pkt.signature->keyid ) )
1571 /* here we violate the rfc a bit by still allowing
1572 * to import non-exportable signature when we have the
1573 * the secret key used to create this signature - it
1574 * seems that this makes sense */
1575 if(opt.verbose)
1576 log_info( _("key %s: non exportable signature"
1577 " (class 0x%02X) - skipped\n"),
1578 keystr(keyid), node->pkt->pkt.signature->sig_class );
1579 delete_kbnode( node );
1581 else if( node->pkt->pkttype == PKT_SIGNATURE
1582 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1583 if( uid_seen )
1585 if(opt.verbose)
1586 log_info( _("key %s: revocation certificate"
1587 " at wrong place - skipped\n"),keystr(keyid));
1588 delete_kbnode( node );
1590 else {
1591 /* If the revocation cert is from a different key than
1592 the one we're working on don't check it - it's
1593 probably from a revocation key and won't be
1594 verifiable with this key anyway. */
1596 if(node->pkt->pkt.signature->keyid[0]==keyid[0] &&
1597 node->pkt->pkt.signature->keyid[1]==keyid[1])
1599 int rc = check_key_signature( keyblock, node, NULL);
1600 if( rc )
1602 if(opt.verbose)
1603 log_info( _("key %s: invalid revocation"
1604 " certificate: %s - skipped\n"),
1605 keystr(keyid), g10_errstr(rc));
1606 delete_kbnode( node );
1611 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1612 (node->pkt->pkt.signature->sig_class == 0x18 ||
1613 node->pkt->pkt.signature->sig_class == 0x28) &&
1614 !subkey_seen )
1616 if(opt.verbose)
1617 log_info( _("key %s: subkey signature"
1618 " in wrong place - skipped\n"), keystr(keyid));
1619 delete_kbnode( node );
1621 else if( node->pkt->pkttype == PKT_SIGNATURE
1622 && !IS_CERT(node->pkt->pkt.signature))
1624 if(opt.verbose)
1625 log_info(_("key %s: unexpected signature class (0x%02X) -"
1626 " skipped\n"),keystr(keyid),
1627 node->pkt->pkt.signature->sig_class);
1628 delete_kbnode(node);
1630 else if( (node->flag & 4) ) /* marked for deletion */
1631 delete_kbnode( node );
1634 /* note: because keyblock is the public key, it is never marked
1635 * for deletion and so keyblock cannot change */
1636 commit_kbnode( &keyblock );
1637 return nvalid;
1641 /****************
1642 * It may happen that the imported keyblock has duplicated user IDs.
1643 * We check this here and collapse those user IDs together with their
1644 * sigs into one.
1645 * Returns: True if the keyblock hash changed.
1648 collapse_uids( KBNODE *keyblock )
1650 KBNODE n, n2;
1651 int in_uid;
1652 int any=0;
1654 restart:
1655 for( n = *keyblock; n; n = n->next ) {
1656 if( n->pkt->pkttype != PKT_USER_ID )
1657 continue;
1658 for( n2 = n->next; n2; n2 = n2->next ) {
1659 if( n2->pkt->pkttype == PKT_USER_ID
1660 && !cmp_user_ids( n->pkt->pkt.user_id,
1661 n2->pkt->pkt.user_id ) ) {
1662 /* found a duplicate */
1663 any = 1;
1664 if( !n2->next
1665 || n2->next->pkt->pkttype == PKT_USER_ID
1666 || n2->next->pkt->pkttype == PKT_PUBLIC_SUBKEY
1667 || n2->next->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1668 /* no more signatures: delete the user ID
1669 * and start over */
1670 remove_kbnode( keyblock, n2 );
1672 else {
1673 /* The simple approach: Move one signature and
1674 * then start over to delete the next one :-( */
1675 move_kbnode( keyblock, n2->next, n->next );
1677 goto restart;
1681 if( !any )
1682 return 0;
1684 restart_sig:
1685 /* now we may have duplicate signatures on one user ID: fix this */
1686 for( in_uid = 0, n = *keyblock; n; n = n->next ) {
1687 if( n->pkt->pkttype == PKT_USER_ID )
1688 in_uid = 1;
1689 else if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
1690 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
1691 in_uid = 0;
1692 else if( in_uid ) {
1693 n2 = n;
1694 do {
1695 KBNODE ncmp = NULL;
1696 for( ; n2; n2 = n2->next ) {
1697 if( n2->pkt->pkttype == PKT_USER_ID
1698 || n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
1699 || n2->pkt->pkttype == PKT_SECRET_SUBKEY )
1700 break;
1701 if( n2->pkt->pkttype != PKT_SIGNATURE )
1703 else if( !ncmp )
1704 ncmp = n2;
1705 else if( !cmp_signatures( ncmp->pkt->pkt.signature,
1706 n2->pkt->pkt.signature )) {
1707 remove_kbnode( keyblock, n2 );
1708 goto restart_sig;
1711 n2 = ncmp? ncmp->next : NULL;
1712 } while( n2 );
1716 if(!opt.quiet)
1718 const char *key="???";
1720 if( (n = find_kbnode( *keyblock, PKT_PUBLIC_KEY )) )
1721 key=keystr_from_pk(n->pkt->pkt.public_key);
1722 else if( (n = find_kbnode( *keyblock, PKT_SECRET_KEY )) )
1723 key=keystr_from_sk(n->pkt->pkt.secret_key);
1725 log_info(_("key %s: duplicated user ID detected - merged\n"),key);
1728 return 1;
1731 /* Check for a 0x20 revocation from a revocation key that is not
1732 present. This may be called without the benefit of merge_xxxx so
1733 you can't rely on pk->revkey and friends. */
1734 static void
1735 revocation_present(KBNODE keyblock)
1737 KBNODE onode,inode;
1738 PKT_public_key *pk=keyblock->pkt->pkt.public_key;
1740 for(onode=keyblock->next;onode;onode=onode->next)
1742 /* If we reach user IDs, we're done. */
1743 if(onode->pkt->pkttype==PKT_USER_ID)
1744 break;
1746 if(onode->pkt->pkttype==PKT_SIGNATURE &&
1747 onode->pkt->pkt.signature->sig_class==0x1F &&
1748 onode->pkt->pkt.signature->revkey)
1750 int idx;
1751 PKT_signature *sig=onode->pkt->pkt.signature;
1753 for(idx=0;idx<sig->numrevkeys;idx++)
1755 u32 keyid[2];
1757 keyid_from_fingerprint(sig->revkey[idx]->fpr,
1758 MAX_FINGERPRINT_LEN,keyid);
1760 for(inode=keyblock->next;inode;inode=inode->next)
1762 /* If we reach user IDs, we're done. */
1763 if(inode->pkt->pkttype==PKT_USER_ID)
1764 break;
1766 if(inode->pkt->pkttype==PKT_SIGNATURE &&
1767 inode->pkt->pkt.signature->sig_class==0x20 &&
1768 inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
1769 inode->pkt->pkt.signature->keyid[1]==keyid[1])
1771 /* Okay, we have a revocation key, and a
1772 revocation issued by it. Do we have the key
1773 itself? */
1774 int rc;
1776 rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx]->fpr,
1777 MAX_FINGERPRINT_LEN);
1778 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1780 char *tempkeystr=xstrdup(keystr_from_pk(pk));
1782 /* No, so try and get it */
1783 if(opt.keyserver
1784 && (opt.keyserver_options.options
1785 & KEYSERVER_AUTO_KEY_RETRIEVE))
1787 log_info(_("WARNING: key %s may be revoked:"
1788 " fetching revocation key %s\n"),
1789 tempkeystr,keystr(keyid));
1790 keyserver_import_fprint(sig->revkey[idx]->fpr,
1791 MAX_FINGERPRINT_LEN,
1792 opt.keyserver);
1794 /* Do we have it now? */
1795 rc=get_pubkey_byfprint_fast (NULL,
1796 sig->revkey[idx]->fpr,
1797 MAX_FINGERPRINT_LEN);
1800 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1801 log_info(_("WARNING: key %s may be revoked:"
1802 " revocation key %s not present.\n"),
1803 tempkeystr,keystr(keyid));
1805 xfree(tempkeystr);
1814 /****************
1815 * compare and merge the blocks
1817 * o compare the signatures: If we already have this signature, check
1818 * that they compare okay; if not, issue a warning and ask the user.
1819 * o Simply add the signature. Can't verify here because we may not have
1820 * the signature's public key yet; verification is done when putting it
1821 * into the trustdb, which is done automagically as soon as this pubkey
1822 * is used.
1823 * Note: We indicate newly inserted packets with flag bit 0
1825 static int
1826 merge_blocks( const char *fname, KBNODE keyblock_orig, KBNODE keyblock,
1827 u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
1829 KBNODE onode, node;
1830 int rc, found;
1832 /* 1st: handle revocation certificates */
1833 for(node=keyblock->next; node; node=node->next ) {
1834 if( node->pkt->pkttype == PKT_USER_ID )
1835 break;
1836 else if( node->pkt->pkttype == PKT_SIGNATURE
1837 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1838 /* check whether we already have this */
1839 found = 0;
1840 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1841 if( onode->pkt->pkttype == PKT_USER_ID )
1842 break;
1843 else if( onode->pkt->pkttype == PKT_SIGNATURE
1844 && onode->pkt->pkt.signature->sig_class == 0x20
1845 && !cmp_signatures(onode->pkt->pkt.signature,
1846 node->pkt->pkt.signature))
1848 found = 1;
1849 break;
1852 if( !found ) {
1853 KBNODE n2 = clone_kbnode(node);
1854 insert_kbnode( keyblock_orig, n2, 0 );
1855 n2->flag |= 1;
1856 ++*n_sigs;
1857 if(!opt.quiet)
1859 char *p=get_user_id_native (keyid);
1860 log_info(_("key %s: \"%s\" revocation"
1861 " certificate added\n"), keystr(keyid),p);
1862 xfree(p);
1868 /* 2nd: merge in any direct key (0x1F) sigs */
1869 for(node=keyblock->next; node; node=node->next ) {
1870 if( node->pkt->pkttype == PKT_USER_ID )
1871 break;
1872 else if( node->pkt->pkttype == PKT_SIGNATURE
1873 && node->pkt->pkt.signature->sig_class == 0x1F ) {
1874 /* check whether we already have this */
1875 found = 0;
1876 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1877 if( onode->pkt->pkttype == PKT_USER_ID )
1878 break;
1879 else if( onode->pkt->pkttype == PKT_SIGNATURE
1880 && onode->pkt->pkt.signature->sig_class == 0x1F
1881 && !cmp_signatures(onode->pkt->pkt.signature,
1882 node->pkt->pkt.signature)) {
1883 found = 1;
1884 break;
1887 if( !found )
1889 KBNODE n2 = clone_kbnode(node);
1890 insert_kbnode( keyblock_orig, n2, 0 );
1891 n2->flag |= 1;
1892 ++*n_sigs;
1893 if(!opt.quiet)
1894 log_info( _("key %s: direct key signature added\n"),
1895 keystr(keyid));
1900 /* 3rd: try to merge new certificates in */
1901 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1902 if( !(onode->flag & 1) && onode->pkt->pkttype == PKT_USER_ID) {
1903 /* find the user id in the imported keyblock */
1904 for(node=keyblock->next; node; node=node->next )
1905 if( node->pkt->pkttype == PKT_USER_ID
1906 && !cmp_user_ids( onode->pkt->pkt.user_id,
1907 node->pkt->pkt.user_id ) )
1908 break;
1909 if( node ) { /* found: merge */
1910 rc = merge_sigs( onode, node, n_sigs, fname, keyid );
1911 if( rc )
1912 return rc;
1917 /* 4th: add new user-ids */
1918 for(node=keyblock->next; node; node=node->next ) {
1919 if( node->pkt->pkttype == PKT_USER_ID) {
1920 /* do we have this in the original keyblock */
1921 for(onode=keyblock_orig->next; onode; onode=onode->next )
1922 if( onode->pkt->pkttype == PKT_USER_ID
1923 && !cmp_user_ids( onode->pkt->pkt.user_id,
1924 node->pkt->pkt.user_id ) )
1925 break;
1926 if( !onode ) { /* this is a new user id: append */
1927 rc = append_uid( keyblock_orig, node, n_sigs, fname, keyid);
1928 if( rc )
1929 return rc;
1930 ++*n_uids;
1935 /* 5th: add new subkeys */
1936 for(node=keyblock->next; node; node=node->next ) {
1937 onode = NULL;
1938 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1939 /* do we have this in the original keyblock? */
1940 for(onode=keyblock_orig->next; onode; onode=onode->next )
1941 if( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
1942 && !cmp_public_keys( onode->pkt->pkt.public_key,
1943 node->pkt->pkt.public_key ) )
1944 break;
1945 if( !onode ) { /* this is a new subkey: append */
1946 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
1947 if( rc )
1948 return rc;
1949 ++*n_subk;
1952 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1953 /* do we have this in the original keyblock? */
1954 for(onode=keyblock_orig->next; onode; onode=onode->next )
1955 if( onode->pkt->pkttype == PKT_SECRET_SUBKEY
1956 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
1957 node->pkt->pkt.secret_key ) )
1958 break;
1959 if( !onode ) { /* this is a new subkey: append */
1960 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
1961 if( rc )
1962 return rc;
1963 ++*n_subk;
1968 /* 6th: merge subkey certificates */
1969 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1970 if( !(onode->flag & 1)
1971 && ( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
1972 || onode->pkt->pkttype == PKT_SECRET_SUBKEY) ) {
1973 /* find the subkey in the imported keyblock */
1974 for(node=keyblock->next; node; node=node->next ) {
1975 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1976 && !cmp_public_keys( onode->pkt->pkt.public_key,
1977 node->pkt->pkt.public_key ) )
1978 break;
1979 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY
1980 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
1981 node->pkt->pkt.secret_key ) )
1982 break;
1984 if( node ) { /* found: merge */
1985 rc = merge_keysigs( onode, node, n_sigs, fname, keyid );
1986 if( rc )
1987 return rc;
1993 return 0;
1997 /****************
1998 * append the userid starting with NODE and all signatures to KEYBLOCK.
2000 static int
2001 append_uid( KBNODE keyblock, KBNODE node, int *n_sigs,
2002 const char *fname, u32 *keyid )
2004 KBNODE n, n_where=NULL;
2006 assert(node->pkt->pkttype == PKT_USER_ID );
2008 /* find the position */
2009 for( n = keyblock; n; n_where = n, n = n->next ) {
2010 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2011 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
2012 break;
2014 if( !n )
2015 n_where = NULL;
2017 /* and append/insert */
2018 while( node ) {
2019 /* we add a clone to the original keyblock, because this
2020 * one is released first */
2021 n = clone_kbnode(node);
2022 if( n_where ) {
2023 insert_kbnode( n_where, n, 0 );
2024 n_where = n;
2026 else
2027 add_kbnode( keyblock, n );
2028 n->flag |= 1;
2029 node->flag |= 1;
2030 if( n->pkt->pkttype == PKT_SIGNATURE )
2031 ++*n_sigs;
2033 node = node->next;
2034 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2035 break;
2038 return 0;
2042 /****************
2043 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
2044 * (how should we handle comment packets here?)
2046 static int
2047 merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
2048 const char *fname, u32 *keyid )
2050 KBNODE n, n2;
2051 int found=0;
2053 assert(dst->pkt->pkttype == PKT_USER_ID );
2054 assert(src->pkt->pkttype == PKT_USER_ID );
2056 for(n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next ) {
2057 if( n->pkt->pkttype != PKT_SIGNATURE )
2058 continue;
2059 if( n->pkt->pkt.signature->sig_class == 0x18
2060 || n->pkt->pkt.signature->sig_class == 0x28 )
2061 continue; /* skip signatures which are only valid on subkeys */
2062 found = 0;
2063 for(n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
2064 if(!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
2066 found++;
2067 break;
2069 if( !found ) {
2070 /* This signature is new or newer, append N to DST.
2071 * We add a clone to the original keyblock, because this
2072 * one is released first */
2073 n2 = clone_kbnode(n);
2074 insert_kbnode( dst, n2, PKT_SIGNATURE );
2075 n2->flag |= 1;
2076 n->flag |= 1;
2077 ++*n_sigs;
2081 return 0;
2084 /****************
2085 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
2087 static int
2088 merge_keysigs( KBNODE dst, KBNODE src, int *n_sigs,
2089 const char *fname, u32 *keyid )
2091 KBNODE n, n2;
2092 int found=0;
2094 assert( dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
2095 || dst->pkt->pkttype == PKT_SECRET_SUBKEY );
2097 for(n=src->next; n ; n = n->next ) {
2098 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2099 || n->pkt->pkttype == PKT_PUBLIC_KEY )
2100 break;
2101 if( n->pkt->pkttype != PKT_SIGNATURE )
2102 continue;
2103 found = 0;
2104 for(n2=dst->next; n2; n2 = n2->next){
2105 if( n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
2106 || n2->pkt->pkttype == PKT_PUBLIC_KEY )
2107 break;
2108 if( n2->pkt->pkttype == PKT_SIGNATURE
2109 && n->pkt->pkt.signature->keyid[0]
2110 == n2->pkt->pkt.signature->keyid[0]
2111 && n->pkt->pkt.signature->keyid[1]
2112 == n2->pkt->pkt.signature->keyid[1]
2113 && n->pkt->pkt.signature->timestamp
2114 <= n2->pkt->pkt.signature->timestamp
2115 && n->pkt->pkt.signature->sig_class
2116 == n2->pkt->pkt.signature->sig_class ) {
2117 found++;
2118 break;
2121 if( !found ) {
2122 /* This signature is new or newer, append N to DST.
2123 * We add a clone to the original keyblock, because this
2124 * one is released first */
2125 n2 = clone_kbnode(n);
2126 insert_kbnode( dst, n2, PKT_SIGNATURE );
2127 n2->flag |= 1;
2128 n->flag |= 1;
2129 ++*n_sigs;
2133 return 0;
2136 /****************
2137 * append the subkey starting with NODE and all signatures to KEYBLOCK.
2138 * Mark all new and copied packets by setting flag bit 0.
2140 static int
2141 append_key( KBNODE keyblock, KBNODE node, int *n_sigs,
2142 const char *fname, u32 *keyid )
2144 KBNODE n;
2146 assert( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2147 || node->pkt->pkttype == PKT_SECRET_SUBKEY );
2149 while( node ) {
2150 /* we add a clone to the original keyblock, because this
2151 * one is released first */
2152 n = clone_kbnode(node);
2153 add_kbnode( keyblock, n );
2154 n->flag |= 1;
2155 node->flag |= 1;
2156 if( n->pkt->pkttype == PKT_SIGNATURE )
2157 ++*n_sigs;
2159 node = node->next;
2160 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2161 break;
2164 return 0;
2169 /* Walk a public keyblock and produce a secret keyblock out of it.
2170 Instead of inserting the secret key parameters (which we don't
2171 have), we insert a stub. */
2172 static KBNODE
2173 pub_to_sec_keyblock (KBNODE pub_keyblock)
2175 KBNODE pubnode, secnode;
2176 KBNODE sec_keyblock = NULL;
2177 KBNODE walkctx = NULL;
2179 while((pubnode = walk_kbnode (pub_keyblock,&walkctx,0)))
2181 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY
2182 || pubnode->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2184 /* Make a secret key. We only need to convert enough to
2185 write the keyblock out. */
2186 PKT_public_key *pk = pubnode->pkt->pkt.public_key;
2187 PACKET *pkt = xmalloc_clear (sizeof *pkt);
2188 PKT_secret_key *sk = xmalloc_clear (sizeof *sk);
2189 int i, n;
2191 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY)
2192 pkt->pkttype = PKT_SECRET_KEY;
2193 else
2194 pkt->pkttype = PKT_SECRET_SUBKEY;
2196 pkt->pkt.secret_key = sk;
2198 copy_public_parts_to_secret_key ( pk, sk );
2199 sk->version = pk->version;
2200 sk->timestamp = pk->timestamp;
2202 n = pubkey_get_npkey (pk->pubkey_algo);
2203 if (!n)
2204 n = 1; /* Unknown number of parameters, however the data
2205 is stored in the first mpi. */
2206 for (i=0; i < n; i++ )
2207 sk->skey[i] = mpi_copy (pk->pkey[i]);
2209 sk->is_protected = 1;
2210 sk->protect.s2k.mode = 1001;
2212 secnode = new_kbnode (pkt);
2214 else
2216 secnode = clone_kbnode (pubnode);
2219 if(!sec_keyblock)
2220 sec_keyblock = secnode;
2221 else
2222 add_kbnode (sec_keyblock, secnode);
2225 return sec_keyblock;
2229 /* Walk over the secret keyring SEC_KEYBLOCK and update any simple
2230 stub keys with the serial number SNNUM of the card if one of the
2231 fingerprints FPR1, FPR2 or FPR3 match. Print a note if the key is
2232 a duplicate (may happen in case of backed uped keys).
2234 Returns: True if anything changed.
2236 static int
2237 update_sec_keyblock_with_cardinfo (KBNODE sec_keyblock,
2238 const unsigned char *fpr1,
2239 const unsigned char *fpr2,
2240 const unsigned char *fpr3,
2241 const char *serialnostr)
2243 KBNODE node;
2244 KBNODE walkctx = NULL;
2245 PKT_secret_key *sk;
2246 byte array[MAX_FINGERPRINT_LEN];
2247 size_t n;
2248 int result = 0;
2249 const char *s;
2251 while((node = walk_kbnode (sec_keyblock, &walkctx, 0)))
2253 if (node->pkt->pkttype != PKT_SECRET_KEY
2254 && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2255 continue;
2256 sk = node->pkt->pkt.secret_key;
2258 fingerprint_from_sk (sk, array, &n);
2259 if (n != 20)
2260 continue; /* Can't be a card key. */
2261 if ( !((fpr1 && !memcmp (array, fpr1, 20))
2262 || (fpr2 && !memcmp (array, fpr2, 20))
2263 || (fpr3 && !memcmp (array, fpr3, 20))) )
2264 continue; /* No match. */
2266 if (sk->is_protected == 1 && sk->protect.s2k.mode == 1001)
2268 /* Standard case: migrate that stub to a key stub. */
2269 sk->protect.s2k.mode = 1002;
2270 s = serialnostr;
2271 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2272 sk->protect.ivlen++, s += 2)
2273 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
2274 result = 1;
2276 else if (sk->is_protected == 1 && sk->protect.s2k.mode == 1002)
2278 s = serialnostr;
2279 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2280 sk->protect.ivlen++, s += 2)
2281 if (sk->protect.iv[sk->protect.ivlen] != xtoi_2 (s))
2283 log_info (_("NOTE: a key's S/N does not "
2284 "match the card's one\n"));
2285 break;
2288 else
2290 if (node->pkt->pkttype != PKT_SECRET_KEY)
2291 log_info (_("NOTE: primary key is online and stored on card\n"));
2292 else
2293 log_info (_("NOTE: secondary key is online and stored on card\n"));
2297 return result;
2302 /* Check whether a secret key stub exists for the public key PK. If
2303 not create such a stub key and store it into the secring. If it
2304 exists, add appropriate subkey stubs and update the secring.
2305 Return 0 if the key could be created. */
2307 auto_create_card_key_stub ( const char *serialnostr,
2308 const unsigned char *fpr1,
2309 const unsigned char *fpr2,
2310 const unsigned char *fpr3)
2312 KBNODE pub_keyblock;
2313 KBNODE sec_keyblock;
2314 KEYDB_HANDLE hd;
2315 int rc;
2317 /* We only want to do this for an OpenPGP card. */
2318 if (!serialnostr || strncmp (serialnostr, "D27600012401", 12)
2319 || strlen (serialnostr) != 32 )
2320 return G10ERR_GENERAL;
2322 /* First get the public keyring from any of the provided fingerprints. */
2323 if ( (fpr1 && !get_keyblock_byfprint (&pub_keyblock, fpr1, 20))
2324 || (fpr2 && !get_keyblock_byfprint (&pub_keyblock, fpr2, 20))
2325 || (fpr3 && !get_keyblock_byfprint (&pub_keyblock, fpr3, 20)))
2327 else
2328 return G10ERR_GENERAL;
2330 hd = keydb_new (1);
2332 /* Now check whether there is a secret keyring. */
2334 PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key;
2335 byte afp[MAX_FINGERPRINT_LEN];
2336 size_t an;
2338 fingerprint_from_pk (pk, afp, &an);
2339 memset (afp, 0, MAX_FINGERPRINT_LEN);
2340 rc = keydb_search_fpr (hd, afp);
2343 if (!rc)
2345 rc = keydb_get_keyblock (hd, &sec_keyblock);
2346 if (rc)
2348 log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
2349 rc = G10ERR_GENERAL;
2351 else
2353 merge_keys_and_selfsig (sec_keyblock);
2355 /* FIXME: We need to add new subkeys first. */
2356 if (update_sec_keyblock_with_cardinfo (sec_keyblock,
2357 fpr1, fpr2, fpr3,
2358 serialnostr))
2360 rc = keydb_update_keyblock (hd, sec_keyblock );
2361 if (rc)
2362 log_error (_("error writing keyring `%s': %s\n"),
2363 keydb_get_resource_name (hd), g10_errstr(rc) );
2367 else /* A secret key does not exists - create it. */
2369 sec_keyblock = pub_to_sec_keyblock (pub_keyblock);
2370 update_sec_keyblock_with_cardinfo (sec_keyblock,
2371 fpr1, fpr2, fpr3,
2372 serialnostr);
2374 rc = keydb_locate_writable (hd, NULL);
2375 if (rc)
2377 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
2378 rc = G10ERR_GENERAL;
2380 else
2382 rc = keydb_insert_keyblock (hd, sec_keyblock );
2383 if (rc)
2384 log_error (_("error writing keyring `%s': %s\n"),
2385 keydb_get_resource_name (hd), g10_errstr(rc) );
2389 release_kbnode (sec_keyblock);
2390 release_kbnode (pub_keyblock);
2391 keydb_release (hd);
2392 return rc;