* keyserver.c (path_makes_direct): New. (keyserver_spawn): Used here
[gnupg.git] / g10 / import.c
blob3b7fa5e72586a6646a91a4a931817d2479978906
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 "options.h"
31 #include "packet.h"
32 #include "errors.h"
33 #include "keydb.h"
34 #include "memory.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);
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;
247 int rc = 0;
249 getkey_disable_caches();
251 if( !opt.no_armor ) { /* armored reading is not disabled */
252 armor_filter_context_t *afx = xmalloc_clear( sizeof *afx );
253 afx->only_keyblocks = 1;
254 iobuf_push_filter2( inp, armor_filter, afx, 1 );
257 while( !(rc = read_block( inp, &pending_pkt, &keyblock) )) {
258 if( keyblock->pkt->pkttype == PKT_PUBLIC_KEY )
259 rc = import_one( fname, keyblock, stats, fpr, fpr_len, options );
260 else if( keyblock->pkt->pkttype == PKT_SECRET_KEY )
261 rc = import_secret_one( fname, keyblock, stats, options );
262 else if( keyblock->pkt->pkttype == PKT_SIGNATURE
263 && keyblock->pkt->pkt.signature->sig_class == 0x20 )
264 rc = import_revoke_cert( fname, keyblock, stats );
265 else {
266 log_info( _("skipping block of type %d\n"),
267 keyblock->pkt->pkttype );
269 release_kbnode(keyblock);
270 /* fixme: we should increment the not imported counter but this
271 does only make sense if we keep on going despite of errors. */
272 if( rc )
273 break;
274 if( !(++stats->count % 100) && !opt.quiet )
275 log_info(_("%lu keys processed so far\n"), stats->count );
277 if( rc == -1 )
278 rc = 0;
279 else if( rc && rc != G10ERR_INV_KEYRING )
280 log_error( _("error reading `%s': %s\n"), fname, g10_errstr(rc));
282 return rc;
286 void
287 import_print_stats (void *hd)
289 struct stats_s *stats = hd;
291 if( !opt.quiet ) {
292 log_info(_("Total number processed: %lu\n"), stats->count );
293 if( stats->skipped_new_keys )
294 log_info(_(" skipped new keys: %lu\n"),
295 stats->skipped_new_keys );
296 if( stats->no_user_id )
297 log_info(_(" w/o user IDs: %lu\n"), stats->no_user_id );
298 if( stats->imported || stats->imported_rsa ) {
299 log_info(_(" imported: %lu"), stats->imported );
300 if( stats->imported_rsa )
301 fprintf(stderr, " (RSA: %lu)", stats->imported_rsa );
302 putc('\n', stderr);
304 if( stats->unchanged )
305 log_info(_(" unchanged: %lu\n"), stats->unchanged );
306 if( stats->n_uids )
307 log_info(_(" new user IDs: %lu\n"), stats->n_uids );
308 if( stats->n_subk )
309 log_info(_(" new subkeys: %lu\n"), stats->n_subk );
310 if( stats->n_sigs )
311 log_info(_(" new signatures: %lu\n"), stats->n_sigs );
312 if( stats->n_revoc )
313 log_info(_(" new key revocations: %lu\n"), stats->n_revoc );
314 if( stats->secret_read )
315 log_info(_(" secret keys read: %lu\n"), stats->secret_read );
316 if( stats->secret_imported )
317 log_info(_(" secret keys imported: %lu\n"), stats->secret_imported );
318 if( stats->secret_dups )
319 log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
320 if( stats->not_imported )
321 log_info(_(" not imported: %lu\n"), stats->not_imported );
322 if( stats->n_sigs_cleaned)
323 log_info(_(" signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
324 if( stats->n_uids_cleaned)
325 log_info(_(" user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
328 if( is_status_enabled() ) {
329 char buf[14*20];
330 sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
331 stats->count,
332 stats->no_user_id,
333 stats->imported,
334 stats->imported_rsa,
335 stats->unchanged,
336 stats->n_uids,
337 stats->n_subk,
338 stats->n_sigs,
339 stats->n_revoc,
340 stats->secret_read,
341 stats->secret_imported,
342 stats->secret_dups,
343 stats->skipped_new_keys,
344 stats->not_imported );
345 write_status_text( STATUS_IMPORT_RES, buf );
350 /****************
351 * Read the next keyblock from stream A.
352 * PENDING_PKT should be initialzed to NULL
353 * and not chnaged form the caller.
354 * Retunr: 0 = okay, -1 no more blocks or another errorcode.
356 static int
357 read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root )
359 int rc;
360 PACKET *pkt;
361 KBNODE root = NULL;
362 int in_cert;
364 if( *pending_pkt ) {
365 root = new_kbnode( *pending_pkt );
366 *pending_pkt = NULL;
367 in_cert = 1;
369 else
370 in_cert = 0;
371 pkt = xmalloc( sizeof *pkt );
372 init_packet(pkt);
373 while( (rc=parse_packet(a, pkt)) != -1 ) {
374 if( rc ) { /* ignore errors */
375 if( rc != G10ERR_UNKNOWN_PACKET ) {
376 log_error("read_block: read error: %s\n", g10_errstr(rc) );
377 rc = G10ERR_INV_KEYRING;
378 goto ready;
380 free_packet( pkt );
381 init_packet(pkt);
382 continue;
385 if( !root && pkt->pkttype == PKT_SIGNATURE
386 && pkt->pkt.signature->sig_class == 0x20 ) {
387 /* this is a revocation certificate which is handled
388 * in a special way */
389 root = new_kbnode( pkt );
390 pkt = NULL;
391 goto ready;
394 /* make a linked list of all packets */
395 switch( pkt->pkttype ) {
396 case PKT_COMPRESSED:
397 if(check_compress_algo(pkt->pkt.compressed->algorithm))
399 rc = G10ERR_COMPR_ALGO;
400 goto ready;
402 else
404 compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
405 pkt->pkt.compressed->buf = NULL;
406 push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1);
408 free_packet( pkt );
409 init_packet(pkt);
410 break;
412 case PKT_RING_TRUST:
413 /* skip those packets */
414 free_packet( pkt );
415 init_packet(pkt);
416 break;
418 case PKT_PUBLIC_KEY:
419 case PKT_SECRET_KEY:
420 if( in_cert ) { /* store this packet */
421 *pending_pkt = pkt;
422 pkt = NULL;
423 goto ready;
425 in_cert = 1;
426 default:
427 if( in_cert ) {
428 if( !root )
429 root = new_kbnode( pkt );
430 else
431 add_kbnode( root, new_kbnode( pkt ) );
432 pkt = xmalloc( sizeof *pkt );
434 init_packet(pkt);
435 break;
438 ready:
439 if( rc == -1 && root )
440 rc = 0;
442 if( rc )
443 release_kbnode( root );
444 else
445 *ret_root = root;
446 free_packet( pkt );
447 xfree( pkt );
448 return rc;
451 /* Walk through the subkeys on a pk to find if we have the PKS
452 disease: multiple subkeys with their binding sigs stripped, and the
453 sig for the first subkey placed after the last subkey. That is,
454 instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
455 "pk uid sig sub1 sub2 sub3 bind1". We can't do anything about sub2
456 and sub3, as they are already lost, but we can try and rescue sub1
457 by reordering the keyblock so that it reads "pk uid sig sub1 bind1
458 sub2 sub3". Returns TRUE if the keyblock was modified. */
460 static int
461 fix_pks_corruption(KBNODE keyblock)
463 int changed=0,keycount=0;
464 KBNODE node,last=NULL,sknode=NULL;
466 /* First determine if we have the problem at all. Look for 2 or
467 more subkeys in a row, followed by a single binding sig. */
468 for(node=keyblock;node;last=node,node=node->next)
470 if(node->pkt->pkttype==PKT_PUBLIC_SUBKEY)
472 keycount++;
473 if(!sknode)
474 sknode=node;
476 else if(node->pkt->pkttype==PKT_SIGNATURE &&
477 node->pkt->pkt.signature->sig_class==0x18 &&
478 keycount>=2 && node->next==NULL)
480 /* We might have the problem, as this key has two subkeys in
481 a row without any intervening packets. */
483 /* Sanity check */
484 if(last==NULL)
485 break;
487 /* Temporarily attach node to sknode. */
488 node->next=sknode->next;
489 sknode->next=node;
490 last->next=NULL;
492 /* Note we aren't checking whether this binding sig is a
493 selfsig. This is not necessary here as the subkey and
494 binding sig will be rejected later if that is the
495 case. */
496 if(check_key_signature(keyblock,node,NULL))
498 /* Not a match, so undo the changes. */
499 sknode->next=node->next;
500 last->next=node;
501 node->next=NULL;
502 break;
504 else
506 sknode->flag |= 1; /* Mark it good so we don't need to
507 check it again */
508 changed=1;
509 break;
512 else
513 keycount=0;
516 return changed;
520 static void
521 print_import_ok (PKT_public_key *pk, PKT_secret_key *sk, unsigned int reason)
523 byte array[MAX_FINGERPRINT_LEN], *s;
524 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
525 size_t i, n;
527 sprintf (buf, "%u ", reason);
528 p = buf + strlen (buf);
530 if (pk)
531 fingerprint_from_pk (pk, array, &n);
532 else
533 fingerprint_from_sk (sk, array, &n);
534 s = array;
535 for (i=0; i < n ; i++, s++, p += 2)
536 sprintf (p, "%02X", *s);
538 write_status_text (STATUS_IMPORT_OK, buf);
541 static void
542 print_import_check (PKT_public_key * pk, PKT_user_id * id)
544 char * buf;
545 byte fpr[24];
546 u32 keyid[2];
547 size_t i, pos = 0, n;
549 buf = xmalloc (17+41+id->len+32);
550 keyid_from_pk (pk, keyid);
551 sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
552 pos = 17;
553 fingerprint_from_pk (pk, fpr, &n);
554 for (i = 0; i < n; i++, pos += 2)
555 sprintf (buf+pos, "%02X", fpr[i]);
556 strcat (buf, " ");
557 pos += 1;
558 strcat (buf, id->name);
559 write_status_text (STATUS_IMPORT_CHECK, buf);
560 xfree (buf);
563 static void
564 check_prefs_warning(PKT_public_key *pk)
566 log_info(_("WARNING: key %s contains preferences for unavailable\n"
567 "algorithms on these user IDs:\n"), keystr_from_pk(pk));
570 static void
571 check_prefs(KBNODE keyblock)
573 KBNODE node;
574 PKT_public_key *pk;
575 int problem=0;
577 merge_keys_and_selfsig(keyblock);
578 pk=keyblock->pkt->pkt.public_key;
580 for(node=keyblock;node;node=node->next)
582 if(node->pkt->pkttype==PKT_USER_ID
583 && node->pkt->pkt.user_id->created
584 && node->pkt->pkt.user_id->prefs)
586 PKT_user_id *uid=node->pkt->pkt.user_id;
587 prefitem_t *prefs=uid->prefs;
588 char *user=utf8_to_native(uid->name,strlen(uid->name),0);
590 for(;prefs->type;prefs++)
592 char num[10]; /* prefs->value is a byte, so we're over
593 safe here */
595 sprintf(num,"%u",prefs->value);
597 if(prefs->type==PREFTYPE_SYM)
599 if(check_cipher_algo(prefs->value))
601 const char *algo=cipher_algo_to_string(prefs->value);
602 if(!problem)
603 check_prefs_warning(pk);
604 log_info(_(" \"%s\": preference for cipher"
605 " algorithm %s\n"),user,algo?algo:num);
606 problem=1;
609 else if(prefs->type==PREFTYPE_HASH)
611 if(check_digest_algo(prefs->value))
613 const char *algo=digest_algo_to_string(prefs->value);
614 if(!problem)
615 check_prefs_warning(pk);
616 log_info(_(" \"%s\": preference for digest"
617 " algorithm %s\n"),user,algo?algo:num);
618 problem=1;
621 else if(prefs->type==PREFTYPE_ZIP)
623 if(check_compress_algo(prefs->value))
625 const char *algo=compress_algo_to_string(prefs->value);
626 if(!problem)
627 check_prefs_warning(pk);
628 log_info(_(" \"%s\": preference for compression"
629 " algorithm %s\n"),user,algo?algo:num);
630 problem=1;
635 xfree(user);
639 if(problem)
641 log_info(_("it is strongly suggested that you update"
642 " your preferences and\n"));
643 log_info(_("re-distribute this key to avoid potential algorithm"
644 " mismatch problems\n"));
646 if(!opt.batch)
648 STRLIST sl=NULL,locusr=NULL;
649 size_t fprlen=0;
650 byte fpr[MAX_FINGERPRINT_LEN],*p;
651 char username[(MAX_FINGERPRINT_LEN*2)+1];
652 unsigned int i;
654 p=fingerprint_from_pk(pk,fpr,&fprlen);
655 for(i=0;i<fprlen;i++,p++)
656 sprintf(username+2*i,"%02X",*p);
657 add_to_strlist(&locusr,username);
659 append_to_strlist(&sl,"updpref");
660 append_to_strlist(&sl,"save");
662 keyedit_menu( username, locusr, sl, 1, 1 );
663 free_strlist(sl);
664 free_strlist(locusr);
666 else if(!opt.quiet)
667 log_info(_("you can update your preferences with:"
668 " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
672 /****************
673 * Try to import one keyblock. Return an error only in serious cases, but
674 * never for an invalid keyblock. It uses log_error to increase the
675 * internal errorcount, so that invalid input can be detected by programs
676 * which called g10.
678 static int
679 import_one( const char *fname, KBNODE keyblock, struct stats_s *stats,
680 unsigned char **fpr,size_t *fpr_len,unsigned int options )
682 PKT_public_key *pk;
683 PKT_public_key *pk_orig;
684 KBNODE node, uidnode;
685 KBNODE keyblock_orig = NULL;
686 u32 keyid[2];
687 int rc = 0;
688 int new_key = 0;
689 int mod_key = 0;
690 int non_self = 0;
692 /* get the key and print some info about it */
693 node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
694 if( !node )
695 BUG();
697 pk = node->pkt->pkt.public_key;
699 if(fpr)
700 *fpr=fingerprint_from_pk(pk,NULL,fpr_len);
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(seckey_available(keyid)==0)
980 check_prefs(keyblock_orig);
982 else if(new_key)
984 revocation_present(keyblock);
985 if(seckey_available(keyid)==0)
986 check_prefs(keyblock);
989 release_kbnode( keyblock_orig );
990 free_public_key( pk_orig );
992 return rc;
995 /* Walk a secret keyblock and produce a public keyblock out of it. */
996 static KBNODE
997 sec_to_pub_keyblock(KBNODE sec_keyblock)
999 KBNODE secnode,pub_keyblock=NULL,ctx=NULL;
1001 while((secnode=walk_kbnode(sec_keyblock,&ctx,0)))
1003 KBNODE pubnode;
1005 if(secnode->pkt->pkttype==PKT_SECRET_KEY ||
1006 secnode->pkt->pkttype==PKT_SECRET_SUBKEY)
1008 /* Make a public key. We only need to convert enough to
1009 write the keyblock out. */
1011 PKT_secret_key *sk=secnode->pkt->pkt.secret_key;
1012 PACKET *pkt=xmalloc_clear(sizeof(PACKET));
1013 PKT_public_key *pk=xmalloc_clear(sizeof(PKT_public_key));
1014 int n;
1016 if(secnode->pkt->pkttype==PKT_SECRET_KEY)
1017 pkt->pkttype=PKT_PUBLIC_KEY;
1018 else
1019 pkt->pkttype=PKT_PUBLIC_SUBKEY;
1021 pkt->pkt.public_key=pk;
1023 pk->version=sk->version;
1024 pk->timestamp=sk->timestamp;
1025 pk->expiredate=sk->expiredate;
1026 pk->pubkey_algo=sk->pubkey_algo;
1028 n=pubkey_get_npkey(pk->pubkey_algo);
1029 if(n==0)
1031 /* we can't properly extract the pubkey without knowing
1032 the number of MPIs */
1033 release_kbnode(pub_keyblock);
1034 return NULL;
1036 else
1038 int i;
1040 for(i=0;i<n;i++)
1041 pk->pkey[i]=mpi_copy(sk->skey[i]);
1044 pubnode=new_kbnode(pkt);
1046 else
1048 pubnode=clone_kbnode(secnode);
1051 if(pub_keyblock==NULL)
1052 pub_keyblock=pubnode;
1053 else
1054 add_kbnode(pub_keyblock,pubnode);
1057 return pub_keyblock;
1060 /****************
1061 * Ditto for secret keys. Handling is simpler than for public keys.
1062 * We allow secret key importing only when allow is true, this is so
1063 * that a secret key can not be imported accidently and thereby tampering
1064 * with the trust calculation.
1066 static int
1067 import_secret_one( const char *fname, KBNODE keyblock,
1068 struct stats_s *stats, unsigned int options)
1070 PKT_secret_key *sk;
1071 KBNODE node, uidnode;
1072 u32 keyid[2];
1073 int rc = 0;
1075 /* get the key and print some info about it */
1076 node = find_kbnode( keyblock, PKT_SECRET_KEY );
1077 if( !node )
1078 BUG();
1080 sk = node->pkt->pkt.secret_key;
1081 keyid_from_sk( sk, keyid );
1082 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1084 if( opt.verbose )
1086 log_info( "sec %4u%c/%s %s ",
1087 nbits_from_sk( sk ),
1088 pubkey_letter( sk->pubkey_algo ),
1089 keystr_from_sk(sk), datestr_from_sk(sk) );
1090 if( uidnode )
1091 print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
1092 uidnode->pkt->pkt.user_id->len );
1093 putc('\n', stderr);
1095 stats->secret_read++;
1097 if( !uidnode )
1099 log_error( _("key %s: no user ID\n"), keystr_from_sk(sk));
1100 return 0;
1103 if(sk->protect.algo>110)
1105 log_error(_("key %s: secret key with invalid cipher %d"
1106 " - skipped\n"),keystr_from_sk(sk),sk->protect.algo);
1107 return 0;
1110 #ifdef ENABLE_SELINUX_HACKS
1111 if (1)
1113 /* We don't allow to import secret keys because that may be used
1114 to put a secret key into the keyring and the user might later
1115 be tricked into signing stuff with that key. */
1116 log_error (_("importing secret keys not allowed\n"));
1117 return 0;
1119 #endif
1121 clear_kbnode_flags( keyblock );
1123 /* do we have this key already in one of our secrings ? */
1124 rc = seckey_available( keyid );
1125 if( rc == G10ERR_NO_SECKEY && !(opt.import_options&IMPORT_MERGE_ONLY) )
1127 /* simply insert this key */
1128 KEYDB_HANDLE hd = keydb_new (1);
1130 /* get default resource */
1131 rc = keydb_locate_writable (hd, NULL);
1132 if (rc) {
1133 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
1134 keydb_release (hd);
1135 return G10ERR_GENERAL;
1137 rc = keydb_insert_keyblock (hd, keyblock );
1138 if (rc)
1139 log_error (_("error writing keyring `%s': %s\n"),
1140 keydb_get_resource_name (hd), g10_errstr(rc) );
1141 keydb_release (hd);
1142 /* we are ready */
1143 if( !opt.quiet )
1144 log_info( _("key %s: secret key imported\n"), keystr_from_sk(sk));
1145 stats->secret_imported++;
1146 if (is_status_enabled ())
1147 print_import_ok (NULL, sk, 1|16);
1149 if(options&IMPORT_SK2PK)
1151 /* Try and make a public key out of this. */
1153 KBNODE pub_keyblock=sec_to_pub_keyblock(keyblock);
1154 if(pub_keyblock)
1156 import_one(fname,pub_keyblock,stats,
1157 NULL,NULL,opt.import_options);
1158 release_kbnode(pub_keyblock);
1162 /* Now that the key is definitely incorporated into the keydb,
1163 if we have the public part of this key, we need to check if
1164 the prefs are rational. */
1165 node=get_pubkeyblock(keyid);
1166 if(node)
1168 check_prefs(node);
1169 release_kbnode(node);
1172 else if( !rc )
1173 { /* we can't merge secret keys */
1174 log_error( _("key %s: already in secret keyring\n"),
1175 keystr_from_sk(sk));
1176 stats->secret_dups++;
1177 if (is_status_enabled ())
1178 print_import_ok (NULL, sk, 16);
1180 /* TODO: if we ever do merge secret keys, make sure to handle
1181 the sec_to_pub_keyblock feature as well. */
1183 else
1184 log_error( _("key %s: secret key not found: %s\n"),
1185 keystr_from_sk(sk), g10_errstr(rc));
1187 return rc;
1191 /****************
1192 * Import a revocation certificate; this is a single signature packet.
1194 static int
1195 import_revoke_cert( const char *fname, KBNODE node, struct stats_s *stats )
1197 PKT_public_key *pk=NULL;
1198 KBNODE onode, keyblock = NULL;
1199 KEYDB_HANDLE hd = NULL;
1200 u32 keyid[2];
1201 int rc = 0;
1203 assert( !node->next );
1204 assert( node->pkt->pkttype == PKT_SIGNATURE );
1205 assert( node->pkt->pkt.signature->sig_class == 0x20 );
1207 keyid[0] = node->pkt->pkt.signature->keyid[0];
1208 keyid[1] = node->pkt->pkt.signature->keyid[1];
1210 pk = xmalloc_clear( sizeof *pk );
1211 rc = get_pubkey( pk, keyid );
1212 if( rc == G10ERR_NO_PUBKEY )
1214 log_error(_("key %s: no public key -"
1215 " can't apply revocation certificate\n"), keystr(keyid));
1216 rc = 0;
1217 goto leave;
1219 else if( rc )
1221 log_error(_("key %s: public key not found: %s\n"),
1222 keystr(keyid), g10_errstr(rc));
1223 goto leave;
1226 /* read the original keyblock */
1227 hd = keydb_new (0);
1229 byte afp[MAX_FINGERPRINT_LEN];
1230 size_t an;
1232 fingerprint_from_pk (pk, afp, &an);
1233 while (an < MAX_FINGERPRINT_LEN)
1234 afp[an++] = 0;
1235 rc = keydb_search_fpr (hd, afp);
1237 if (rc)
1239 log_error (_("key %s: can't locate original keyblock: %s\n"),
1240 keystr(keyid), g10_errstr(rc));
1241 goto leave;
1243 rc = keydb_get_keyblock (hd, &keyblock );
1244 if (rc)
1246 log_error (_("key %s: can't read original keyblock: %s\n"),
1247 keystr(keyid), g10_errstr(rc));
1248 goto leave;
1251 /* it is okay, that node is not in keyblock because
1252 * check_key_signature works fine for sig_class 0x20 in this
1253 * special case. */
1254 rc = check_key_signature( keyblock, node, NULL);
1255 if( rc )
1257 log_error( _("key %s: invalid revocation certificate"
1258 ": %s - rejected\n"), keystr(keyid), g10_errstr(rc));
1259 goto leave;
1262 /* check whether we already have this */
1263 for(onode=keyblock->next; onode; onode=onode->next ) {
1264 if( onode->pkt->pkttype == PKT_USER_ID )
1265 break;
1266 else if( onode->pkt->pkttype == PKT_SIGNATURE
1267 && !cmp_signatures(node->pkt->pkt.signature,
1268 onode->pkt->pkt.signature))
1270 rc = 0;
1271 goto leave; /* yes, we already know about it */
1276 /* insert it */
1277 insert_kbnode( keyblock, clone_kbnode(node), 0 );
1279 /* and write the keyblock back */
1280 rc = keydb_update_keyblock (hd, keyblock );
1281 if (rc)
1282 log_error (_("error writing keyring `%s': %s\n"),
1283 keydb_get_resource_name (hd), g10_errstr(rc) );
1284 keydb_release (hd); hd = NULL;
1285 /* we are ready */
1286 if( !opt.quiet )
1288 char *p=get_user_id_native (keyid);
1289 log_info( _("key %s: \"%s\" revocation certificate imported\n"),
1290 keystr(keyid),p);
1291 xfree(p);
1293 stats->n_revoc++;
1295 /* If the key we just revoked was ultimately trusted, remove its
1296 ultimate trust. This doesn't stop the user from putting the
1297 ultimate trust back, but is a reasonable solution for now. */
1298 if(get_ownertrust(pk)==TRUST_ULTIMATE)
1299 clear_ownertrusts(pk);
1301 revalidation_mark ();
1303 leave:
1304 keydb_release (hd);
1305 release_kbnode( keyblock );
1306 free_public_key( pk );
1307 return rc;
1311 /****************
1312 * loop over the keyblock and check all self signatures.
1313 * Mark all user-ids with a self-signature by setting flag bit 0.
1314 * Mark all user-ids with an invalid self-signature by setting bit 1.
1315 * This works also for subkeys, here the subkey is marked. Invalid or
1316 * extra subkey sigs (binding or revocation) are marked for deletion.
1317 * non_self is set to true if there are any sigs other than self-sigs
1318 * in this keyblock.
1320 static int
1321 chk_self_sigs( const char *fname, KBNODE keyblock,
1322 PKT_public_key *pk, u32 *keyid, int *non_self )
1324 KBNODE n,knode=NULL;
1325 PKT_signature *sig;
1326 int rc;
1327 u32 bsdate=0,rsdate=0;
1328 KBNODE bsnode=NULL,rsnode=NULL;
1330 for( n=keyblock; (n = find_next_kbnode(n, 0)); ) {
1331 if(n->pkt->pkttype==PKT_PUBLIC_SUBKEY)
1333 knode=n;
1334 bsdate=0;
1335 rsdate=0;
1336 bsnode=NULL;
1337 rsnode=NULL;
1338 continue;
1340 else if( n->pkt->pkttype != PKT_SIGNATURE )
1341 continue;
1342 sig = n->pkt->pkt.signature;
1343 if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] ) {
1345 /* This just caches the sigs for later use. That way we
1346 import a fully-cached key which speeds things up. */
1347 if(!opt.no_sig_cache)
1348 check_key_signature(keyblock,n,NULL);
1350 if( IS_UID_SIG(sig) || IS_UID_REV(sig) )
1352 KBNODE unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
1353 if( !unode )
1355 log_error( _("key %s: no user ID for signature\n"),
1356 keystr(keyid));
1357 return -1; /* the complete keyblock is invalid */
1360 /* If it hasn't been marked valid yet, keep trying */
1361 if(!(unode->flag&1)) {
1362 rc = check_key_signature( keyblock, n, NULL);
1363 if( rc )
1365 if( opt.verbose )
1367 char *p=utf8_to_native(unode->pkt->pkt.user_id->name,
1368 strlen(unode->pkt->pkt.user_id->name),0);
1369 log_info( rc == G10ERR_PUBKEY_ALGO ?
1370 _("key %s: unsupported public key "
1371 "algorithm on user ID \"%s\"\n"):
1372 _("key %s: invalid self-signature "
1373 "on user ID \"%s\"\n"),
1374 keystr(keyid),p);
1375 xfree(p);
1378 else
1379 unode->flag |= 1; /* mark that signature checked */
1382 else if( sig->sig_class == 0x18 ) {
1383 /* Note that this works based solely on the timestamps
1384 like the rest of gpg. If the standard gets
1385 revocation targets, this may need to be revised. */
1387 if( !knode )
1389 if(opt.verbose)
1390 log_info( _("key %s: no subkey for key binding\n"),
1391 keystr(keyid));
1392 n->flag |= 4; /* delete this */
1394 else
1396 rc = check_key_signature( keyblock, n, NULL);
1397 if( rc )
1399 if(opt.verbose)
1400 log_info(rc == G10ERR_PUBKEY_ALGO ?
1401 _("key %s: unsupported public key"
1402 " algorithm\n"):
1403 _("key %s: invalid subkey binding\n"),
1404 keystr(keyid));
1405 n->flag|=4;
1407 else
1409 /* It's valid, so is it newer? */
1410 if(sig->timestamp>=bsdate) {
1411 knode->flag |= 1; /* the subkey is valid */
1412 if(bsnode)
1414 bsnode->flag|=4; /* Delete the last binding
1415 sig since this one is
1416 newer */
1417 if(opt.verbose)
1418 log_info(_("key %s: removed multiple subkey"
1419 " binding\n"),keystr(keyid));
1422 bsnode=n;
1423 bsdate=sig->timestamp;
1425 else
1426 n->flag|=4; /* older */
1430 else if( sig->sig_class == 0x28 ) {
1431 /* We don't actually mark the subkey as revoked right
1432 now, so just check that the revocation sig is the
1433 most recent valid one. Note that we don't care if
1434 the binding sig is newer than the revocation sig.
1435 See the comment in getkey.c:merge_selfsigs_subkey for
1436 more */
1437 if( !knode )
1439 if(opt.verbose)
1440 log_info( _("key %s: no subkey for key revocation\n"),
1441 keystr(keyid));
1442 n->flag |= 4; /* delete this */
1444 else
1446 rc = check_key_signature( keyblock, n, NULL);
1447 if( rc )
1449 if(opt.verbose)
1450 log_info(rc == G10ERR_PUBKEY_ALGO ?
1451 _("key %s: unsupported public"
1452 " key algorithm\n"):
1453 _("key %s: invalid subkey revocation\n"),
1454 keystr(keyid));
1455 n->flag|=4;
1457 else
1459 /* It's valid, so is it newer? */
1460 if(sig->timestamp>=rsdate)
1462 if(rsnode)
1464 rsnode->flag|=4; /* Delete the last revocation
1465 sig since this one is
1466 newer */
1467 if(opt.verbose)
1468 log_info(_("key %s: removed multiple subkey"
1469 " revocation\n"),keystr(keyid));
1472 rsnode=n;
1473 rsdate=sig->timestamp;
1475 else
1476 n->flag|=4; /* older */
1481 else
1482 *non_self=1;
1485 return 0;
1488 /****************
1489 * delete all parts which are invalid and those signatures whose
1490 * public key algorithm is not available in this implemenation;
1491 * but consider RSA as valid, because parse/build_packets knows
1492 * about it.
1493 * returns: true if at least one valid user-id is left over.
1495 static int
1496 delete_inv_parts( const char *fname, KBNODE keyblock,
1497 u32 *keyid, unsigned int options)
1499 KBNODE node;
1500 int nvalid=0, uid_seen=0, subkey_seen=0;
1502 for(node=keyblock->next; node; node = node->next ) {
1503 if( node->pkt->pkttype == PKT_USER_ID ) {
1504 uid_seen = 1;
1505 if( (node->flag & 2) || !(node->flag & 1) ) {
1506 if( opt.verbose )
1508 char *p=utf8_to_native(node->pkt->pkt.user_id->name,
1509 node->pkt->pkt.user_id->len,0);
1510 log_info( _("key %s: skipped user ID \"%s\"\n"),
1511 keystr(keyid),p);
1512 xfree(p);
1514 delete_kbnode( node ); /* the user-id */
1515 /* and all following packets up to the next user-id */
1516 while( node->next
1517 && node->next->pkt->pkttype != PKT_USER_ID
1518 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1519 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
1520 delete_kbnode( node->next );
1521 node = node->next;
1524 else
1525 nvalid++;
1527 else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1528 || node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1529 if( (node->flag & 2) || !(node->flag & 1) ) {
1530 if( opt.verbose )
1531 log_info( _("key %s: skipped subkey\n"),keystr(keyid));
1533 delete_kbnode( node ); /* the subkey */
1534 /* and all following signature packets */
1535 while( node->next
1536 && node->next->pkt->pkttype == PKT_SIGNATURE ) {
1537 delete_kbnode( node->next );
1538 node = node->next;
1541 else
1542 subkey_seen = 1;
1544 else if( node->pkt->pkttype == PKT_SIGNATURE
1545 && check_pubkey_algo( node->pkt->pkt.signature->pubkey_algo)
1546 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
1547 delete_kbnode( node ); /* build_packet() can't handle this */
1548 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1549 !node->pkt->pkt.signature->flags.exportable &&
1550 !(options&IMPORT_LOCAL_SIGS) &&
1551 seckey_available( node->pkt->pkt.signature->keyid ) )
1553 /* here we violate the rfc a bit by still allowing
1554 * to import non-exportable signature when we have the
1555 * the secret key used to create this signature - it
1556 * seems that this makes sense */
1557 if(opt.verbose)
1558 log_info( _("key %s: non exportable signature"
1559 " (class 0x%02X) - skipped\n"),
1560 keystr(keyid), node->pkt->pkt.signature->sig_class );
1561 delete_kbnode( node );
1563 else if( node->pkt->pkttype == PKT_SIGNATURE
1564 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1565 if( uid_seen )
1567 if(opt.verbose)
1568 log_info( _("key %s: revocation certificate"
1569 " at wrong place - skipped\n"),keystr(keyid));
1570 delete_kbnode( node );
1572 else {
1573 /* If the revocation cert is from a different key than
1574 the one we're working on don't check it - it's
1575 probably from a revocation key and won't be
1576 verifiable with this key anyway. */
1578 if(node->pkt->pkt.signature->keyid[0]==keyid[0] &&
1579 node->pkt->pkt.signature->keyid[1]==keyid[1])
1581 int rc = check_key_signature( keyblock, node, NULL);
1582 if( rc )
1584 if(opt.verbose)
1585 log_info( _("key %s: invalid revocation"
1586 " certificate: %s - skipped\n"),
1587 keystr(keyid), g10_errstr(rc));
1588 delete_kbnode( node );
1593 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1594 (node->pkt->pkt.signature->sig_class == 0x18 ||
1595 node->pkt->pkt.signature->sig_class == 0x28) &&
1596 !subkey_seen )
1598 if(opt.verbose)
1599 log_info( _("key %s: subkey signature"
1600 " in wrong place - skipped\n"), keystr(keyid));
1601 delete_kbnode( node );
1603 else if( node->pkt->pkttype == PKT_SIGNATURE
1604 && !IS_CERT(node->pkt->pkt.signature))
1606 if(opt.verbose)
1607 log_info(_("key %s: unexpected signature class (0x%02X) -"
1608 " skipped\n"),keystr(keyid),
1609 node->pkt->pkt.signature->sig_class);
1610 delete_kbnode(node);
1612 else if( (node->flag & 4) ) /* marked for deletion */
1613 delete_kbnode( node );
1616 /* note: because keyblock is the public key, it is never marked
1617 * for deletion and so keyblock cannot change */
1618 commit_kbnode( &keyblock );
1619 return nvalid;
1623 /****************
1624 * It may happen that the imported keyblock has duplicated user IDs.
1625 * We check this here and collapse those user IDs together with their
1626 * sigs into one.
1627 * Returns: True if the keyblock hash changed.
1630 collapse_uids( KBNODE *keyblock )
1632 KBNODE n, n2;
1633 int in_uid;
1634 int any=0;
1636 restart:
1637 for( n = *keyblock; n; n = n->next ) {
1638 if( n->pkt->pkttype != PKT_USER_ID )
1639 continue;
1640 for( n2 = n->next; n2; n2 = n2->next ) {
1641 if( n2->pkt->pkttype == PKT_USER_ID
1642 && !cmp_user_ids( n->pkt->pkt.user_id,
1643 n2->pkt->pkt.user_id ) ) {
1644 /* found a duplicate */
1645 any = 1;
1646 if( !n2->next
1647 || n2->next->pkt->pkttype == PKT_USER_ID
1648 || n2->next->pkt->pkttype == PKT_PUBLIC_SUBKEY
1649 || n2->next->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1650 /* no more signatures: delete the user ID
1651 * and start over */
1652 remove_kbnode( keyblock, n2 );
1654 else {
1655 /* The simple approach: Move one signature and
1656 * then start over to delete the next one :-( */
1657 move_kbnode( keyblock, n2->next, n->next );
1659 goto restart;
1663 if( !any )
1664 return 0;
1666 restart_sig:
1667 /* now we may have duplicate signatures on one user ID: fix this */
1668 for( in_uid = 0, n = *keyblock; n; n = n->next ) {
1669 if( n->pkt->pkttype == PKT_USER_ID )
1670 in_uid = 1;
1671 else if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
1672 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
1673 in_uid = 0;
1674 else if( in_uid ) {
1675 n2 = n;
1676 do {
1677 KBNODE ncmp = NULL;
1678 for( ; n2; n2 = n2->next ) {
1679 if( n2->pkt->pkttype == PKT_USER_ID
1680 || n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
1681 || n2->pkt->pkttype == PKT_SECRET_SUBKEY )
1682 break;
1683 if( n2->pkt->pkttype != PKT_SIGNATURE )
1685 else if( !ncmp )
1686 ncmp = n2;
1687 else if( !cmp_signatures( ncmp->pkt->pkt.signature,
1688 n2->pkt->pkt.signature )) {
1689 remove_kbnode( keyblock, n2 );
1690 goto restart_sig;
1693 n2 = ncmp? ncmp->next : NULL;
1694 } while( n2 );
1698 if(!opt.quiet)
1700 const char *key="???";
1702 if( (n = find_kbnode( *keyblock, PKT_PUBLIC_KEY )) )
1703 key=keystr_from_pk(n->pkt->pkt.public_key);
1704 else if( (n = find_kbnode( *keyblock, PKT_SECRET_KEY )) )
1705 key=keystr_from_sk(n->pkt->pkt.secret_key);
1707 log_info(_("key %s: duplicated user ID detected - merged\n"),key);
1710 return 1;
1713 /* Check for a 0x20 revocation from a revocation key that is not
1714 present. This may be called without the benefit of merge_xxxx so
1715 you can't rely on pk->revkey and friends. */
1716 static void
1717 revocation_present(KBNODE keyblock)
1719 KBNODE onode,inode;
1720 PKT_public_key *pk=keyblock->pkt->pkt.public_key;
1722 for(onode=keyblock->next;onode;onode=onode->next)
1724 /* If we reach user IDs, we're done. */
1725 if(onode->pkt->pkttype==PKT_USER_ID)
1726 break;
1728 if(onode->pkt->pkttype==PKT_SIGNATURE &&
1729 onode->pkt->pkt.signature->sig_class==0x1F &&
1730 onode->pkt->pkt.signature->revkey)
1732 int idx;
1733 PKT_signature *sig=onode->pkt->pkt.signature;
1735 for(idx=0;idx<sig->numrevkeys;idx++)
1737 u32 keyid[2];
1739 keyid_from_fingerprint(sig->revkey[idx]->fpr,
1740 MAX_FINGERPRINT_LEN,keyid);
1742 for(inode=keyblock->next;inode;inode=inode->next)
1744 /* If we reach user IDs, we're done. */
1745 if(inode->pkt->pkttype==PKT_USER_ID)
1746 break;
1748 if(inode->pkt->pkttype==PKT_SIGNATURE &&
1749 inode->pkt->pkt.signature->sig_class==0x20 &&
1750 inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
1751 inode->pkt->pkt.signature->keyid[1]==keyid[1])
1753 /* Okay, we have a revocation key, and a
1754 revocation issued by it. Do we have the key
1755 itself? */
1756 int rc;
1758 rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx]->fpr,
1759 MAX_FINGERPRINT_LEN);
1760 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1762 char *tempkeystr=xstrdup(keystr_from_pk(pk));
1764 /* No, so try and get it */
1765 if(opt.keyserver
1766 && (opt.keyserver_options.options
1767 & KEYSERVER_AUTO_KEY_RETRIEVE))
1769 log_info(_("WARNING: key %s may be revoked:"
1770 " fetching revocation key %s\n"),
1771 tempkeystr,keystr(keyid));
1772 keyserver_import_fprint(sig->revkey[idx]->fpr,
1773 MAX_FINGERPRINT_LEN,
1774 opt.keyserver);
1776 /* Do we have it now? */
1777 rc=get_pubkey_byfprint_fast (NULL,
1778 sig->revkey[idx]->fpr,
1779 MAX_FINGERPRINT_LEN);
1782 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1783 log_info(_("WARNING: key %s may be revoked:"
1784 " revocation key %s not present.\n"),
1785 tempkeystr,keystr(keyid));
1787 xfree(tempkeystr);
1796 /****************
1797 * compare and merge the blocks
1799 * o compare the signatures: If we already have this signature, check
1800 * that they compare okay; if not, issue a warning and ask the user.
1801 * o Simply add the signature. Can't verify here because we may not have
1802 * the signature's public key yet; verification is done when putting it
1803 * into the trustdb, which is done automagically as soon as this pubkey
1804 * is used.
1805 * Note: We indicate newly inserted packets with flag bit 0
1807 static int
1808 merge_blocks( const char *fname, KBNODE keyblock_orig, KBNODE keyblock,
1809 u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
1811 KBNODE onode, node;
1812 int rc, found;
1814 /* 1st: handle revocation certificates */
1815 for(node=keyblock->next; node; node=node->next ) {
1816 if( node->pkt->pkttype == PKT_USER_ID )
1817 break;
1818 else if( node->pkt->pkttype == PKT_SIGNATURE
1819 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1820 /* check whether we already have this */
1821 found = 0;
1822 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1823 if( onode->pkt->pkttype == PKT_USER_ID )
1824 break;
1825 else if( onode->pkt->pkttype == PKT_SIGNATURE
1826 && onode->pkt->pkt.signature->sig_class == 0x20
1827 && !cmp_signatures(onode->pkt->pkt.signature,
1828 node->pkt->pkt.signature))
1830 found = 1;
1831 break;
1834 if( !found ) {
1835 KBNODE n2 = clone_kbnode(node);
1836 insert_kbnode( keyblock_orig, n2, 0 );
1837 n2->flag |= 1;
1838 ++*n_sigs;
1839 if(!opt.quiet)
1841 char *p=get_user_id_native (keyid);
1842 log_info(_("key %s: \"%s\" revocation"
1843 " certificate added\n"), keystr(keyid),p);
1844 xfree(p);
1850 /* 2nd: merge in any direct key (0x1F) sigs */
1851 for(node=keyblock->next; node; node=node->next ) {
1852 if( node->pkt->pkttype == PKT_USER_ID )
1853 break;
1854 else if( node->pkt->pkttype == PKT_SIGNATURE
1855 && node->pkt->pkt.signature->sig_class == 0x1F ) {
1856 /* check whether we already have this */
1857 found = 0;
1858 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1859 if( onode->pkt->pkttype == PKT_USER_ID )
1860 break;
1861 else if( onode->pkt->pkttype == PKT_SIGNATURE
1862 && onode->pkt->pkt.signature->sig_class == 0x1F
1863 && !cmp_signatures(onode->pkt->pkt.signature,
1864 node->pkt->pkt.signature)) {
1865 found = 1;
1866 break;
1869 if( !found )
1871 KBNODE n2 = clone_kbnode(node);
1872 insert_kbnode( keyblock_orig, n2, 0 );
1873 n2->flag |= 1;
1874 ++*n_sigs;
1875 if(!opt.quiet)
1876 log_info( _("key %s: direct key signature added\n"),
1877 keystr(keyid));
1882 /* 3rd: try to merge new certificates in */
1883 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1884 if( !(onode->flag & 1) && onode->pkt->pkttype == PKT_USER_ID) {
1885 /* find the user id in the imported keyblock */
1886 for(node=keyblock->next; node; node=node->next )
1887 if( node->pkt->pkttype == PKT_USER_ID
1888 && !cmp_user_ids( onode->pkt->pkt.user_id,
1889 node->pkt->pkt.user_id ) )
1890 break;
1891 if( node ) { /* found: merge */
1892 rc = merge_sigs( onode, node, n_sigs, fname, keyid );
1893 if( rc )
1894 return rc;
1899 /* 4th: add new user-ids */
1900 for(node=keyblock->next; node; node=node->next ) {
1901 if( node->pkt->pkttype == PKT_USER_ID) {
1902 /* do we have this in the original keyblock */
1903 for(onode=keyblock_orig->next; onode; onode=onode->next )
1904 if( onode->pkt->pkttype == PKT_USER_ID
1905 && !cmp_user_ids( onode->pkt->pkt.user_id,
1906 node->pkt->pkt.user_id ) )
1907 break;
1908 if( !onode ) { /* this is a new user id: append */
1909 rc = append_uid( keyblock_orig, node, n_sigs, fname, keyid);
1910 if( rc )
1911 return rc;
1912 ++*n_uids;
1917 /* 5th: add new subkeys */
1918 for(node=keyblock->next; node; node=node->next ) {
1919 onode = NULL;
1920 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1921 /* do we have this in the original keyblock? */
1922 for(onode=keyblock_orig->next; onode; onode=onode->next )
1923 if( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
1924 && !cmp_public_keys( onode->pkt->pkt.public_key,
1925 node->pkt->pkt.public_key ) )
1926 break;
1927 if( !onode ) { /* this is a new subkey: append */
1928 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
1929 if( rc )
1930 return rc;
1931 ++*n_subk;
1934 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1935 /* do we have this in the original keyblock? */
1936 for(onode=keyblock_orig->next; onode; onode=onode->next )
1937 if( onode->pkt->pkttype == PKT_SECRET_SUBKEY
1938 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
1939 node->pkt->pkt.secret_key ) )
1940 break;
1941 if( !onode ) { /* this is a new subkey: append */
1942 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
1943 if( rc )
1944 return rc;
1945 ++*n_subk;
1950 /* 6th: merge subkey certificates */
1951 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1952 if( !(onode->flag & 1)
1953 && ( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
1954 || onode->pkt->pkttype == PKT_SECRET_SUBKEY) ) {
1955 /* find the subkey in the imported keyblock */
1956 for(node=keyblock->next; node; node=node->next ) {
1957 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1958 && !cmp_public_keys( onode->pkt->pkt.public_key,
1959 node->pkt->pkt.public_key ) )
1960 break;
1961 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY
1962 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
1963 node->pkt->pkt.secret_key ) )
1964 break;
1966 if( node ) { /* found: merge */
1967 rc = merge_keysigs( onode, node, n_sigs, fname, keyid );
1968 if( rc )
1969 return rc;
1975 return 0;
1979 /****************
1980 * append the userid starting with NODE and all signatures to KEYBLOCK.
1982 static int
1983 append_uid( KBNODE keyblock, KBNODE node, int *n_sigs,
1984 const char *fname, u32 *keyid )
1986 KBNODE n, n_where=NULL;
1988 assert(node->pkt->pkttype == PKT_USER_ID );
1990 /* find the position */
1991 for( n = keyblock; n; n_where = n, n = n->next ) {
1992 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
1993 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
1994 break;
1996 if( !n )
1997 n_where = NULL;
1999 /* and append/insert */
2000 while( node ) {
2001 /* we add a clone to the original keyblock, because this
2002 * one is released first */
2003 n = clone_kbnode(node);
2004 if( n_where ) {
2005 insert_kbnode( n_where, n, 0 );
2006 n_where = n;
2008 else
2009 add_kbnode( keyblock, n );
2010 n->flag |= 1;
2011 node->flag |= 1;
2012 if( n->pkt->pkttype == PKT_SIGNATURE )
2013 ++*n_sigs;
2015 node = node->next;
2016 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2017 break;
2020 return 0;
2024 /****************
2025 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
2026 * (how should we handle comment packets here?)
2028 static int
2029 merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
2030 const char *fname, u32 *keyid )
2032 KBNODE n, n2;
2033 int found=0;
2035 assert(dst->pkt->pkttype == PKT_USER_ID );
2036 assert(src->pkt->pkttype == PKT_USER_ID );
2038 for(n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next ) {
2039 if( n->pkt->pkttype != PKT_SIGNATURE )
2040 continue;
2041 if( n->pkt->pkt.signature->sig_class == 0x18
2042 || n->pkt->pkt.signature->sig_class == 0x28 )
2043 continue; /* skip signatures which are only valid on subkeys */
2044 found = 0;
2045 for(n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
2046 if(!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
2048 found++;
2049 break;
2051 if( !found ) {
2052 /* This signature is new or newer, append N to DST.
2053 * We add a clone to the original keyblock, because this
2054 * one is released first */
2055 n2 = clone_kbnode(n);
2056 insert_kbnode( dst, n2, PKT_SIGNATURE );
2057 n2->flag |= 1;
2058 n->flag |= 1;
2059 ++*n_sigs;
2063 return 0;
2066 /****************
2067 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
2069 static int
2070 merge_keysigs( KBNODE dst, KBNODE src, int *n_sigs,
2071 const char *fname, u32 *keyid )
2073 KBNODE n, n2;
2074 int found=0;
2076 assert( dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
2077 || dst->pkt->pkttype == PKT_SECRET_SUBKEY );
2079 for(n=src->next; n ; n = n->next ) {
2080 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2081 || n->pkt->pkttype == PKT_PUBLIC_KEY )
2082 break;
2083 if( n->pkt->pkttype != PKT_SIGNATURE )
2084 continue;
2085 found = 0;
2086 for(n2=dst->next; n2; n2 = n2->next){
2087 if( n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
2088 || n2->pkt->pkttype == PKT_PUBLIC_KEY )
2089 break;
2090 if( n2->pkt->pkttype == PKT_SIGNATURE
2091 && n->pkt->pkt.signature->keyid[0]
2092 == n2->pkt->pkt.signature->keyid[0]
2093 && n->pkt->pkt.signature->keyid[1]
2094 == n2->pkt->pkt.signature->keyid[1]
2095 && n->pkt->pkt.signature->timestamp
2096 <= n2->pkt->pkt.signature->timestamp
2097 && n->pkt->pkt.signature->sig_class
2098 == n2->pkt->pkt.signature->sig_class ) {
2099 found++;
2100 break;
2103 if( !found ) {
2104 /* This signature is new or newer, append N to DST.
2105 * We add a clone to the original keyblock, because this
2106 * one is released first */
2107 n2 = clone_kbnode(n);
2108 insert_kbnode( dst, n2, PKT_SIGNATURE );
2109 n2->flag |= 1;
2110 n->flag |= 1;
2111 ++*n_sigs;
2115 return 0;
2118 /****************
2119 * append the subkey starting with NODE and all signatures to KEYBLOCK.
2120 * Mark all new and copied packets by setting flag bit 0.
2122 static int
2123 append_key( KBNODE keyblock, KBNODE node, int *n_sigs,
2124 const char *fname, u32 *keyid )
2126 KBNODE n;
2128 assert( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2129 || node->pkt->pkttype == PKT_SECRET_SUBKEY );
2131 while( node ) {
2132 /* we add a clone to the original keyblock, because this
2133 * one is released first */
2134 n = clone_kbnode(node);
2135 add_kbnode( keyblock, n );
2136 n->flag |= 1;
2137 node->flag |= 1;
2138 if( n->pkt->pkttype == PKT_SIGNATURE )
2139 ++*n_sigs;
2141 node = node->next;
2142 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2143 break;
2146 return 0;
2151 /* Walk a public keyblock and produce a secret keyblock out of it.
2152 Instead of inserting the secret key parameters (which we don't
2153 have), we insert a stub. */
2154 static KBNODE
2155 pub_to_sec_keyblock (KBNODE pub_keyblock)
2157 KBNODE pubnode, secnode;
2158 KBNODE sec_keyblock = NULL;
2159 KBNODE walkctx = NULL;
2161 while((pubnode = walk_kbnode (pub_keyblock,&walkctx,0)))
2163 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY
2164 || pubnode->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2166 /* Make a secret key. We only need to convert enough to
2167 write the keyblock out. */
2168 PKT_public_key *pk = pubnode->pkt->pkt.public_key;
2169 PACKET *pkt = xmalloc_clear (sizeof *pkt);
2170 PKT_secret_key *sk = xmalloc_clear (sizeof *sk);
2171 int i, n;
2173 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY)
2174 pkt->pkttype = PKT_SECRET_KEY;
2175 else
2176 pkt->pkttype = PKT_SECRET_SUBKEY;
2178 pkt->pkt.secret_key = sk;
2180 copy_public_parts_to_secret_key ( pk, sk );
2181 sk->version = pk->version;
2182 sk->timestamp = pk->timestamp;
2184 n = pubkey_get_npkey (pk->pubkey_algo);
2185 if (!n)
2186 n = 1; /* Unknown number of parameters, however the data
2187 is stored in the first mpi. */
2188 for (i=0; i < n; i++ )
2189 sk->skey[i] = mpi_copy (pk->pkey[i]);
2191 sk->is_protected = 1;
2192 sk->protect.s2k.mode = 1001;
2194 secnode = new_kbnode (pkt);
2196 else
2198 secnode = clone_kbnode (pubnode);
2201 if(!sec_keyblock)
2202 sec_keyblock = secnode;
2203 else
2204 add_kbnode (sec_keyblock, secnode);
2207 return sec_keyblock;
2211 /* Walk over the secret keyring SEC_KEYBLOCK and update any simple
2212 stub keys with the serial number SNNUM of the card if one of the
2213 fingerprints FPR1, FPR2 or FPR3 match. Print a note if the key is
2214 a duplicate (may happen in case of backed uped keys).
2216 Returns: True if anything changed.
2218 static int
2219 update_sec_keyblock_with_cardinfo (KBNODE sec_keyblock,
2220 const unsigned char *fpr1,
2221 const unsigned char *fpr2,
2222 const unsigned char *fpr3,
2223 const char *serialnostr)
2225 KBNODE node;
2226 KBNODE walkctx = NULL;
2227 PKT_secret_key *sk;
2228 byte array[MAX_FINGERPRINT_LEN];
2229 size_t n;
2230 int result = 0;
2231 const char *s;
2233 while((node = walk_kbnode (sec_keyblock, &walkctx, 0)))
2235 if (node->pkt->pkttype != PKT_SECRET_KEY
2236 && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2237 continue;
2238 sk = node->pkt->pkt.secret_key;
2240 fingerprint_from_sk (sk, array, &n);
2241 if (n != 20)
2242 continue; /* Can't be a card key. */
2243 if ( !((fpr1 && !memcmp (array, fpr1, 20))
2244 || (fpr2 && !memcmp (array, fpr2, 20))
2245 || (fpr3 && !memcmp (array, fpr3, 20))) )
2246 continue; /* No match. */
2248 if (sk->is_protected == 1 && sk->protect.s2k.mode == 1001)
2250 /* Standard case: migrate that stub to a key stub. */
2251 sk->protect.s2k.mode = 1002;
2252 s = serialnostr;
2253 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2254 sk->protect.ivlen++, s += 2)
2255 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
2256 result = 1;
2258 else if (sk->is_protected == 1 && sk->protect.s2k.mode == 1002)
2260 s = serialnostr;
2261 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2262 sk->protect.ivlen++, s += 2)
2263 if (sk->protect.iv[sk->protect.ivlen] != xtoi_2 (s))
2265 log_info (_("NOTE: a key's S/N does not "
2266 "match the card's one\n"));
2267 break;
2270 else
2272 if (node->pkt->pkttype != PKT_SECRET_KEY)
2273 log_info (_("NOTE: primary key is online and stored on card\n"));
2274 else
2275 log_info (_("NOTE: secondary key is online and stored on card\n"));
2279 return result;
2284 /* Check whether a secret key stub exists for the public key PK. If
2285 not create such a stub key and store it into the secring. If it
2286 exists, add appropriate subkey stubs and update the secring.
2287 Return 0 if the key could be created. */
2289 auto_create_card_key_stub ( const char *serialnostr,
2290 const unsigned char *fpr1,
2291 const unsigned char *fpr2,
2292 const unsigned char *fpr3)
2294 KBNODE pub_keyblock;
2295 KBNODE sec_keyblock;
2296 KEYDB_HANDLE hd;
2297 int rc;
2299 /* We only want to do this for an OpenPGP card. */
2300 if (!serialnostr || strncmp (serialnostr, "D27600012401", 12)
2301 || strlen (serialnostr) != 32 )
2302 return G10ERR_GENERAL;
2304 /* First get the public keyring from any of the provided fingerprints. */
2305 if ( (fpr1 && !get_keyblock_byfprint (&pub_keyblock, fpr1, 20))
2306 || (fpr2 && !get_keyblock_byfprint (&pub_keyblock, fpr2, 20))
2307 || (fpr3 && !get_keyblock_byfprint (&pub_keyblock, fpr3, 20)))
2309 else
2310 return G10ERR_GENERAL;
2312 hd = keydb_new (1);
2314 /* Now check whether there is a secret keyring. */
2316 PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key;
2317 byte afp[MAX_FINGERPRINT_LEN];
2318 size_t an;
2320 fingerprint_from_pk (pk, afp, &an);
2321 memset (afp, 0, MAX_FINGERPRINT_LEN);
2322 rc = keydb_search_fpr (hd, afp);
2325 if (!rc)
2327 rc = keydb_get_keyblock (hd, &sec_keyblock);
2328 if (rc)
2330 log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
2331 rc = G10ERR_GENERAL;
2333 else
2335 merge_keys_and_selfsig (sec_keyblock);
2337 /* FIXME: We need to add new subkeys first. */
2338 if (update_sec_keyblock_with_cardinfo (sec_keyblock,
2339 fpr1, fpr2, fpr3,
2340 serialnostr))
2342 rc = keydb_update_keyblock (hd, sec_keyblock );
2343 if (rc)
2344 log_error (_("error writing keyring `%s': %s\n"),
2345 keydb_get_resource_name (hd), g10_errstr(rc) );
2349 else /* A secret key does not exists - create it. */
2351 sec_keyblock = pub_to_sec_keyblock (pub_keyblock);
2352 update_sec_keyblock_with_cardinfo (sec_keyblock,
2353 fpr1, fpr2, fpr3,
2354 serialnostr);
2356 rc = keydb_locate_writable (hd, NULL);
2357 if (rc)
2359 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
2360 rc = G10ERR_GENERAL;
2362 else
2364 rc = keydb_insert_keyblock (hd, sec_keyblock );
2365 if (rc)
2366 log_error (_("error writing keyring `%s': %s\n"),
2367 keydb_get_resource_name (hd), g10_errstr(rc) );
2371 release_kbnode (sec_keyblock);
2372 release_kbnode (pub_keyblock);
2373 keydb_release (hd);
2374 return rc;