2008-02-01 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / import.c
blob41198b687714cb47158e8588524812177bed9107
1 /* import.c - import a key into our key storage.
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3 * 2007 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <assert.h>
28 #include "gpg.h"
29 #include "options.h"
30 #include "packet.h"
31 #include "status.h"
32 #include "keydb.h"
33 #include "util.h"
34 #include "trustdb.h"
35 #include "main.h"
36 #include "i18n.h"
37 #include "ttyio.h"
38 #include "status.h"
39 #include "keyserver-internal.h"
41 struct stats_s {
42 ulong count;
43 ulong no_user_id;
44 ulong imported;
45 ulong imported_rsa;
46 ulong n_uids;
47 ulong n_sigs;
48 ulong n_subk;
49 ulong unchanged;
50 ulong n_revoc;
51 ulong secret_read;
52 ulong secret_imported;
53 ulong secret_dups;
54 ulong skipped_new_keys;
55 ulong not_imported;
56 ulong n_sigs_cleaned;
57 ulong n_uids_cleaned;
61 static int import( IOBUF inp, const char* fname,struct stats_s *stats,
62 unsigned char **fpr,size_t *fpr_len,unsigned int options );
63 static int read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root );
64 static void revocation_present(KBNODE keyblock);
65 static int import_one(const char *fname, KBNODE keyblock,struct stats_s *stats,
66 unsigned char **fpr,size_t *fpr_len,
67 unsigned int options,int from_sk);
68 static int import_secret_one( const char *fname, KBNODE keyblock,
69 struct stats_s *stats, unsigned int options);
70 static int import_revoke_cert( const char *fname, KBNODE node,
71 struct stats_s *stats);
72 static int chk_self_sigs( const char *fname, KBNODE keyblock,
73 PKT_public_key *pk, u32 *keyid, int *non_self );
74 static int delete_inv_parts( const char *fname, KBNODE keyblock,
75 u32 *keyid, unsigned int options );
76 static int merge_blocks( const char *fname, KBNODE keyblock_orig,
77 KBNODE keyblock, u32 *keyid,
78 int *n_uids, int *n_sigs, int *n_subk );
79 static int append_uid( KBNODE keyblock, KBNODE node, int *n_sigs,
80 const char *fname, u32 *keyid );
81 static int append_key( KBNODE keyblock, KBNODE node, int *n_sigs,
82 const char *fname, u32 *keyid );
83 static int merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
84 const char *fname, u32 *keyid );
85 static int merge_keysigs( KBNODE dst, KBNODE src, int *n_sigs,
86 const char *fname, u32 *keyid );
88 int
89 parse_import_options(char *str,unsigned int *options,int noisy)
91 struct parse_options import_opts[]=
93 {"import-local-sigs",IMPORT_LOCAL_SIGS,NULL,
94 N_("import signatures that are marked as local-only")},
95 {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,
96 N_("repair damage from the pks keyserver during import")},
97 {"fast-import",IMPORT_FAST,NULL,
98 N_("do not update the trustdb after import")},
99 {"convert-sk-to-pk",IMPORT_SK2PK,NULL,
100 N_("create a public key when importing a secret key")},
101 {"merge-only",IMPORT_MERGE_ONLY,NULL,
102 N_("only accept updates to existing keys")},
103 {"import-clean",IMPORT_CLEAN,NULL,
104 N_("remove unusable parts from key after import")},
105 {"import-minimal",IMPORT_MINIMAL|IMPORT_CLEAN,NULL,
106 N_("remove as much as possible from key after import")},
107 /* Aliases for backward compatibility */
108 {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL},
109 {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL},
110 /* dummy */
111 {"import-unusable-sigs",0,NULL,NULL},
112 {"import-clean-sigs",0,NULL,NULL},
113 {"import-clean-uids",0,NULL,NULL},
114 {NULL,0,NULL,NULL}
117 return parse_options(str,options,import_opts,noisy);
120 void *
121 import_new_stats_handle (void)
123 return xmalloc_clear ( sizeof (struct stats_s) );
126 void
127 import_release_stats_handle (void *p)
129 xfree (p);
132 /****************
133 * Import the public keys from the given filename. Input may be armored.
134 * This function rejects all keys which are not validly self signed on at
135 * least one userid. Only user ids which are self signed will be imported.
136 * Other signatures are not checked.
138 * Actually this function does a merge. It works like this:
140 * - get the keyblock
141 * - check self-signatures and remove all userids and their signatures
142 * without/invalid self-signatures.
143 * - reject the keyblock, if we have no valid userid.
144 * - See whether we have this key already in one of our pubrings.
145 * If not, simply add it to the default keyring.
146 * - Compare the key and the self-signatures of the new and the one in
147 * our keyring. If they are different something weird is going on;
148 * ask what to do.
149 * - See whether we have only non-self-signature on one user id; if not
150 * ask the user what to do.
151 * - compare the signatures: If we already have this signature, check
152 * that they compare okay; if not, issue a warning and ask the user.
153 * (consider looking at the timestamp and use the newest?)
154 * - Simply add the signature. Can't verify here because we may not have
155 * the signature's public key yet; verification is done when putting it
156 * into the trustdb, which is done automagically as soon as this pubkey
157 * is used.
158 * - Proceed with next signature.
160 * Key revocation certificates have special handling.
163 static int
164 import_keys_internal( IOBUF inp, char **fnames, int nnames,
165 void *stats_handle, unsigned char **fpr, size_t *fpr_len,
166 unsigned int options )
168 int i, rc = 0;
169 struct stats_s *stats = stats_handle;
171 if (!stats)
172 stats = import_new_stats_handle ();
174 if (inp) {
175 rc = import( inp, "[stream]", stats, fpr, fpr_len, options);
177 else {
178 if( !fnames && !nnames )
179 nnames = 1; /* Ohh what a ugly hack to jump into the loop */
181 for(i=0; i < nnames; i++ ) {
182 const char *fname = fnames? fnames[i] : NULL;
183 IOBUF inp2 = iobuf_open(fname);
184 if( !fname )
185 fname = "[stdin]";
186 if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
188 iobuf_close (inp2);
189 inp2 = NULL;
190 errno = EPERM;
192 if( !inp2 )
193 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
194 else
196 rc = import( inp2, fname, stats, fpr, fpr_len, options );
197 iobuf_close(inp2);
198 /* Must invalidate that ugly cache to actually close it. */
199 iobuf_ioctl (NULL, 2, 0, (char*)fname);
200 if( rc )
201 log_error("import from `%s' failed: %s\n", fname,
202 g10_errstr(rc) );
204 if( !fname )
205 break;
208 if (!stats_handle) {
209 import_print_stats (stats);
210 import_release_stats_handle (stats);
213 /* If no fast import and the trustdb is dirty (i.e. we added a key
214 or userID that had something other than a selfsig, a signature
215 that was other than a selfsig, or any revocation), then
216 update/check the trustdb if the user specified by setting
217 interactive or by not setting no-auto-check-trustdb */
219 if(!(options&IMPORT_FAST))
220 trustdb_check_or_update();
222 return rc;
225 void
226 import_keys( char **fnames, int nnames,
227 void *stats_handle, unsigned int options )
229 import_keys_internal(NULL,fnames,nnames,stats_handle,NULL,NULL,options);
233 import_keys_stream( IOBUF inp, void *stats_handle,
234 unsigned char **fpr, size_t *fpr_len,unsigned int options )
236 return import_keys_internal(inp,NULL,0,stats_handle,fpr,fpr_len,options);
239 static int
240 import( IOBUF inp, const char* fname,struct stats_s *stats,
241 unsigned char **fpr,size_t *fpr_len,unsigned int options )
243 PACKET *pending_pkt = NULL;
244 KBNODE keyblock = NULL; /* Need to initialize because gcc can't
245 grasp the return semantics of
246 read_block. */
247 int rc = 0;
249 getkey_disable_caches();
251 if( !opt.no_armor ) { /* armored reading is not disabled */
252 armor_filter_context_t *afx;
254 afx = new_armor_context ();
255 afx->only_keyblocks = 1;
256 push_armor_filter (afx, inp);
257 release_armor_context (afx);
260 while( !(rc = read_block( inp, &pending_pkt, &keyblock) )) {
261 if( keyblock->pkt->pkttype == PKT_PUBLIC_KEY )
262 rc = import_one( fname, keyblock, stats, fpr, fpr_len, options, 0);
263 else if( keyblock->pkt->pkttype == PKT_SECRET_KEY )
264 rc = import_secret_one( fname, keyblock, stats, options );
265 else if( keyblock->pkt->pkttype == PKT_SIGNATURE
266 && keyblock->pkt->pkt.signature->sig_class == 0x20 )
267 rc = import_revoke_cert( fname, keyblock, stats );
268 else {
269 log_info( _("skipping block of type %d\n"),
270 keyblock->pkt->pkttype );
272 release_kbnode(keyblock);
273 /* fixme: we should increment the not imported counter but this
274 does only make sense if we keep on going despite of errors. */
275 if( rc )
276 break;
277 if( !(++stats->count % 100) && !opt.quiet )
278 log_info(_("%lu keys processed so far\n"), stats->count );
280 if( rc == -1 )
281 rc = 0;
282 else if( rc && rc != G10ERR_INV_KEYRING )
283 log_error( _("error reading `%s': %s\n"), fname, g10_errstr(rc));
285 return rc;
289 void
290 import_print_stats (void *hd)
292 struct stats_s *stats = hd;
294 if( !opt.quiet ) {
295 log_info(_("Total number processed: %lu\n"), stats->count );
296 if( stats->skipped_new_keys )
297 log_info(_(" skipped new keys: %lu\n"),
298 stats->skipped_new_keys );
299 if( stats->no_user_id )
300 log_info(_(" w/o user IDs: %lu\n"), stats->no_user_id );
301 if( stats->imported || stats->imported_rsa ) {
302 log_info(_(" imported: %lu"), stats->imported );
303 if (stats->imported_rsa)
304 log_printf (" (RSA: %lu)", stats->imported_rsa );
305 log_printf ("\n");
307 if( stats->unchanged )
308 log_info(_(" unchanged: %lu\n"), stats->unchanged );
309 if( stats->n_uids )
310 log_info(_(" new user IDs: %lu\n"), stats->n_uids );
311 if( stats->n_subk )
312 log_info(_(" new subkeys: %lu\n"), stats->n_subk );
313 if( stats->n_sigs )
314 log_info(_(" new signatures: %lu\n"), stats->n_sigs );
315 if( stats->n_revoc )
316 log_info(_(" new key revocations: %lu\n"), stats->n_revoc );
317 if( stats->secret_read )
318 log_info(_(" secret keys read: %lu\n"), stats->secret_read );
319 if( stats->secret_imported )
320 log_info(_(" secret keys imported: %lu\n"), stats->secret_imported );
321 if( stats->secret_dups )
322 log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
323 if( stats->not_imported )
324 log_info(_(" not imported: %lu\n"), stats->not_imported );
325 if( stats->n_sigs_cleaned)
326 log_info(_(" signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
327 if( stats->n_uids_cleaned)
328 log_info(_(" user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
331 if( is_status_enabled() ) {
332 char buf[14*20];
333 sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
334 stats->count,
335 stats->no_user_id,
336 stats->imported,
337 stats->imported_rsa,
338 stats->unchanged,
339 stats->n_uids,
340 stats->n_subk,
341 stats->n_sigs,
342 stats->n_revoc,
343 stats->secret_read,
344 stats->secret_imported,
345 stats->secret_dups,
346 stats->skipped_new_keys,
347 stats->not_imported );
348 write_status_text( STATUS_IMPORT_RES, buf );
353 /****************
354 * Read the next keyblock from stream A.
355 * PENDING_PKT should be initialzed to NULL
356 * and not chnaged form the caller.
357 * Retunr: 0 = okay, -1 no more blocks or another errorcode.
359 static int
360 read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root )
362 int rc;
363 PACKET *pkt;
364 KBNODE root = NULL;
365 int in_cert;
367 if( *pending_pkt ) {
368 root = new_kbnode( *pending_pkt );
369 *pending_pkt = NULL;
370 in_cert = 1;
372 else
373 in_cert = 0;
374 pkt = xmalloc( sizeof *pkt );
375 init_packet(pkt);
376 while( (rc=parse_packet(a, pkt)) != -1 ) {
377 if( rc ) { /* ignore errors */
378 if( rc != G10ERR_UNKNOWN_PACKET ) {
379 log_error("read_block: read error: %s\n", g10_errstr(rc) );
380 rc = G10ERR_INV_KEYRING;
381 goto ready;
383 free_packet( pkt );
384 init_packet(pkt);
385 continue;
388 if( !root && pkt->pkttype == PKT_SIGNATURE
389 && pkt->pkt.signature->sig_class == 0x20 ) {
390 /* this is a revocation certificate which is handled
391 * in a special way */
392 root = new_kbnode( pkt );
393 pkt = NULL;
394 goto ready;
397 /* make a linked list of all packets */
398 switch( pkt->pkttype ) {
399 case PKT_COMPRESSED:
400 if(check_compress_algo(pkt->pkt.compressed->algorithm))
402 rc = G10ERR_COMPR_ALGO;
403 goto ready;
405 else
407 compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
408 pkt->pkt.compressed->buf = NULL;
409 push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1);
411 free_packet( pkt );
412 init_packet(pkt);
413 break;
415 case PKT_RING_TRUST:
416 /* skip those packets */
417 free_packet( pkt );
418 init_packet(pkt);
419 break;
421 case PKT_PUBLIC_KEY:
422 case PKT_SECRET_KEY:
423 if( in_cert ) { /* store this packet */
424 *pending_pkt = pkt;
425 pkt = NULL;
426 goto ready;
428 in_cert = 1;
429 default:
430 if( in_cert ) {
431 if( !root )
432 root = new_kbnode( pkt );
433 else
434 add_kbnode( root, new_kbnode( pkt ) );
435 pkt = xmalloc( sizeof *pkt );
437 init_packet(pkt);
438 break;
441 ready:
442 if( rc == -1 && root )
443 rc = 0;
445 if( rc )
446 release_kbnode( root );
447 else
448 *ret_root = root;
449 free_packet( pkt );
450 xfree( pkt );
451 return rc;
454 /* Walk through the subkeys on a pk to find if we have the PKS
455 disease: multiple subkeys with their binding sigs stripped, and the
456 sig for the first subkey placed after the last subkey. That is,
457 instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
458 "pk uid sig sub1 sub2 sub3 bind1". We can't do anything about sub2
459 and sub3, as they are already lost, but we can try and rescue sub1
460 by reordering the keyblock so that it reads "pk uid sig sub1 bind1
461 sub2 sub3". Returns TRUE if the keyblock was modified. */
463 static int
464 fix_pks_corruption(KBNODE keyblock)
466 int changed=0,keycount=0;
467 KBNODE node,last=NULL,sknode=NULL;
469 /* First determine if we have the problem at all. Look for 2 or
470 more subkeys in a row, followed by a single binding sig. */
471 for(node=keyblock;node;last=node,node=node->next)
473 if(node->pkt->pkttype==PKT_PUBLIC_SUBKEY)
475 keycount++;
476 if(!sknode)
477 sknode=node;
479 else if(node->pkt->pkttype==PKT_SIGNATURE &&
480 node->pkt->pkt.signature->sig_class==0x18 &&
481 keycount>=2 && node->next==NULL)
483 /* We might have the problem, as this key has two subkeys in
484 a row without any intervening packets. */
486 /* Sanity check */
487 if(last==NULL)
488 break;
490 /* Temporarily attach node to sknode. */
491 node->next=sknode->next;
492 sknode->next=node;
493 last->next=NULL;
495 /* Note we aren't checking whether this binding sig is a
496 selfsig. This is not necessary here as the subkey and
497 binding sig will be rejected later if that is the
498 case. */
499 if(check_key_signature(keyblock,node,NULL))
501 /* Not a match, so undo the changes. */
502 sknode->next=node->next;
503 last->next=node;
504 node->next=NULL;
505 break;
507 else
509 sknode->flag |= 1; /* Mark it good so we don't need to
510 check it again */
511 changed=1;
512 break;
515 else
516 keycount=0;
519 return changed;
523 static void
524 print_import_ok (PKT_public_key *pk, PKT_secret_key *sk, unsigned int reason)
526 byte array[MAX_FINGERPRINT_LEN], *s;
527 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
528 size_t i, n;
530 sprintf (buf, "%u ", reason);
531 p = buf + strlen (buf);
533 if (pk)
534 fingerprint_from_pk (pk, array, &n);
535 else
536 fingerprint_from_sk (sk, array, &n);
537 s = array;
538 for (i=0; i < n ; i++, s++, p += 2)
539 sprintf (p, "%02X", *s);
541 write_status_text (STATUS_IMPORT_OK, buf);
544 static void
545 print_import_check (PKT_public_key * pk, PKT_user_id * id)
547 char * buf;
548 byte fpr[24];
549 u32 keyid[2];
550 size_t i, pos = 0, n;
552 buf = xmalloc (17+41+id->len+32);
553 keyid_from_pk (pk, keyid);
554 sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
555 pos = 17;
556 fingerprint_from_pk (pk, fpr, &n);
557 for (i = 0; i < n; i++, pos += 2)
558 sprintf (buf+pos, "%02X", fpr[i]);
559 strcat (buf, " ");
560 pos += 1;
561 strcat (buf, id->name);
562 write_status_text (STATUS_IMPORT_CHECK, buf);
563 xfree (buf);
566 static void
567 check_prefs_warning(PKT_public_key *pk)
569 log_info(_("WARNING: key %s contains preferences for unavailable\n"
570 "algorithms on these user IDs:\n"), keystr_from_pk(pk));
573 static void
574 check_prefs(KBNODE keyblock)
576 KBNODE node;
577 PKT_public_key *pk;
578 int problem=0;
580 merge_keys_and_selfsig(keyblock);
581 pk=keyblock->pkt->pkt.public_key;
583 for(node=keyblock;node;node=node->next)
585 if(node->pkt->pkttype==PKT_USER_ID
586 && node->pkt->pkt.user_id->created
587 && node->pkt->pkt.user_id->prefs)
589 PKT_user_id *uid=node->pkt->pkt.user_id;
590 prefitem_t *prefs=uid->prefs;
591 char *user=utf8_to_native(uid->name,strlen(uid->name),0);
593 for(;prefs->type;prefs++)
595 char num[10]; /* prefs->value is a byte, so we're over
596 safe here */
598 sprintf(num,"%u",prefs->value);
600 if(prefs->type==PREFTYPE_SYM)
602 if (openpgp_cipher_test_algo (prefs->value))
604 const char *algo =
605 (openpgp_cipher_test_algo (prefs->value)
606 ? num
607 : openpgp_cipher_algo_name (prefs->value));
608 if(!problem)
609 check_prefs_warning(pk);
610 log_info(_(" \"%s\": preference for cipher"
611 " algorithm %s\n"), user, algo);
612 problem=1;
615 else if(prefs->type==PREFTYPE_HASH)
617 if(openpgp_md_test_algo(prefs->value))
619 const char *algo =
620 (gcry_md_test_algo (prefs->value)
621 ? num
622 : gcry_md_algo_name (prefs->value));
623 if(!problem)
624 check_prefs_warning(pk);
625 log_info(_(" \"%s\": preference for digest"
626 " algorithm %s\n"), user, algo);
627 problem=1;
630 else if(prefs->type==PREFTYPE_ZIP)
632 if(check_compress_algo (prefs->value))
634 const char *algo=compress_algo_to_string(prefs->value);
635 if(!problem)
636 check_prefs_warning(pk);
637 log_info(_(" \"%s\": preference for compression"
638 " algorithm %s\n"),user,algo?algo:num);
639 problem=1;
644 xfree(user);
648 if(problem)
650 log_info(_("it is strongly suggested that you update"
651 " your preferences and\n"));
652 log_info(_("re-distribute this key to avoid potential algorithm"
653 " mismatch problems\n"));
655 if(!opt.batch)
657 strlist_t sl=NULL,locusr=NULL;
658 size_t fprlen=0;
659 byte fpr[MAX_FINGERPRINT_LEN],*p;
660 char username[(MAX_FINGERPRINT_LEN*2)+1];
661 unsigned int i;
663 p=fingerprint_from_pk(pk,fpr,&fprlen);
664 for(i=0;i<fprlen;i++,p++)
665 sprintf(username+2*i,"%02X",*p);
666 add_to_strlist(&locusr,username);
668 append_to_strlist(&sl,"updpref");
669 append_to_strlist(&sl,"save");
671 keyedit_menu( username, locusr, sl, 1, 1 );
672 free_strlist(sl);
673 free_strlist(locusr);
675 else if(!opt.quiet)
676 log_info(_("you can update your preferences with:"
677 " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
681 /****************
682 * Try to import one keyblock. Return an error only in serious cases, but
683 * never for an invalid keyblock. It uses log_error to increase the
684 * internal errorcount, so that invalid input can be detected by programs
685 * which called g10.
687 static int
688 import_one( const char *fname, KBNODE keyblock, struct stats_s *stats,
689 unsigned char **fpr,size_t *fpr_len,unsigned int options,
690 int from_sk )
692 PKT_public_key *pk;
693 PKT_public_key *pk_orig;
694 KBNODE node, uidnode;
695 KBNODE keyblock_orig = NULL;
696 u32 keyid[2];
697 int rc = 0;
698 int new_key = 0;
699 int mod_key = 0;
700 int non_self = 0;
702 /* get the key and print some info about it */
703 node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
704 if( !node )
705 BUG();
707 pk = node->pkt->pkt.public_key;
709 keyid_from_pk( pk, keyid );
710 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
712 if( opt.verbose && !opt.interactive )
714 log_info( "pub %4u%c/%s %s ",
715 nbits_from_pk( pk ),
716 pubkey_letter( pk->pubkey_algo ),
717 keystr_from_pk(pk), datestr_from_pk(pk) );
718 if( uidnode )
719 print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
720 uidnode->pkt->pkt.user_id->len );
721 log_printf ("\n");
724 if( !uidnode )
726 log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
727 return 0;
730 if (opt.interactive) {
731 if(is_status_enabled())
732 print_import_check (pk, uidnode->pkt->pkt.user_id);
733 merge_keys_and_selfsig (keyblock);
734 tty_printf ("\n");
735 show_basic_key_info (keyblock);
736 tty_printf ("\n");
737 if (!cpr_get_answer_is_yes ("import.okay",
738 "Do you want to import this key? (y/N) "))
739 return 0;
742 collapse_uids(&keyblock);
744 /* Clean the key that we're about to import, to cut down on things
745 that we have to clean later. This has no practical impact on
746 the end result, but does result in less logging which might
747 confuse the user. */
748 if(options&IMPORT_CLEAN)
749 clean_key(keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL);
751 clear_kbnode_flags( keyblock );
753 if((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
754 && opt.verbose)
755 log_info(_("key %s: PKS subkey corruption repaired\n"),
756 keystr_from_pk(pk));
758 rc = chk_self_sigs( fname, keyblock , pk, keyid, &non_self );
759 if( rc )
760 return rc== -1? 0:rc;
762 /* If we allow such a thing, mark unsigned uids as valid */
763 if( opt.allow_non_selfsigned_uid )
764 for( node=keyblock; node; node = node->next )
765 if( node->pkt->pkttype == PKT_USER_ID && !(node->flag & 1) )
767 char *user=utf8_to_native(node->pkt->pkt.user_id->name,
768 node->pkt->pkt.user_id->len,0);
769 node->flag |= 1;
770 log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
771 keystr_from_pk(pk),user);
772 xfree(user);
775 if( !delete_inv_parts( fname, keyblock, keyid, options ) ) {
776 log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
777 if( !opt.quiet )
778 log_info(_("this may be caused by a missing self-signature\n"));
779 stats->no_user_id++;
780 return 0;
783 /* do we have this key already in one of our pubrings ? */
784 pk_orig = xmalloc_clear( sizeof *pk_orig );
785 rc = get_pubkey_fast ( pk_orig, keyid );
786 if( rc && rc != G10ERR_NO_PUBKEY && rc != G10ERR_UNU_PUBKEY )
788 log_error( _("key %s: public key not found: %s\n"),
789 keystr(keyid), g10_errstr(rc));
791 else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) )
793 if( opt.verbose )
794 log_info( _("key %s: new key - skipped\n"), keystr(keyid));
795 rc = 0;
796 stats->skipped_new_keys++;
798 else if( rc ) { /* insert this key */
799 KEYDB_HANDLE hd = keydb_new (0);
801 rc = keydb_locate_writable (hd, NULL);
802 if (rc) {
803 log_error (_("no writable keyring found: %s\n"), g10_errstr (rc));
804 keydb_release (hd);
805 return G10ERR_GENERAL;
807 if( opt.verbose > 1 )
808 log_info (_("writing to `%s'\n"), keydb_get_resource_name (hd) );
810 rc = keydb_insert_keyblock (hd, keyblock );
811 if (rc)
812 log_error (_("error writing keyring `%s': %s\n"),
813 keydb_get_resource_name (hd), g10_errstr(rc));
814 else
816 /* This should not be possible since we delete the
817 ownertrust when a key is deleted, but it can happen if
818 the keyring and trustdb are out of sync. It can also
819 be made to happen with the trusted-key command. */
821 clear_ownertrusts (pk);
822 if(non_self)
823 revalidation_mark ();
825 keydb_release (hd);
827 /* we are ready */
828 if( !opt.quiet )
830 char *p=get_user_id_native (keyid);
831 log_info( _("key %s: public key \"%s\" imported\n"),
832 keystr(keyid),p);
833 xfree(p);
835 if( is_status_enabled() )
837 char *us = get_long_user_id_string( keyid );
838 write_status_text( STATUS_IMPORTED, us );
839 xfree(us);
840 print_import_ok (pk,NULL, 1);
842 stats->imported++;
843 if( is_RSA( pk->pubkey_algo ) )
844 stats->imported_rsa++;
845 new_key = 1;
847 else { /* merge */
848 KEYDB_HANDLE hd;
849 int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
851 /* Compare the original against the new key; just to be sure nothing
852 * weird is going on */
853 if( cmp_public_keys( pk_orig, pk ) )
855 log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
856 goto leave;
859 /* now read the original keyblock */
860 hd = keydb_new (0);
862 byte afp[MAX_FINGERPRINT_LEN];
863 size_t an;
865 fingerprint_from_pk (pk_orig, afp, &an);
866 while (an < MAX_FINGERPRINT_LEN)
867 afp[an++] = 0;
868 rc = keydb_search_fpr (hd, afp);
870 if( rc )
872 log_error (_("key %s: can't locate original keyblock: %s\n"),
873 keystr(keyid), g10_errstr(rc));
874 keydb_release (hd);
875 goto leave;
877 rc = keydb_get_keyblock (hd, &keyblock_orig );
878 if (rc)
880 log_error (_("key %s: can't read original keyblock: %s\n"),
881 keystr(keyid), g10_errstr(rc));
882 keydb_release (hd);
883 goto leave;
886 /* and try to merge the block */
887 clear_kbnode_flags( keyblock_orig );
888 clear_kbnode_flags( keyblock );
889 n_uids = n_sigs = n_subk = n_sigs_cleaned = n_uids_cleaned = 0;
890 rc = merge_blocks( fname, keyblock_orig, keyblock,
891 keyid, &n_uids, &n_sigs, &n_subk );
892 if( rc )
894 keydb_release (hd);
895 goto leave;
898 if(options&IMPORT_CLEAN)
899 clean_key(keyblock_orig,opt.verbose,options&IMPORT_MINIMAL,
900 &n_uids_cleaned,&n_sigs_cleaned);
902 if( n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned) {
903 mod_key = 1;
904 /* keyblock_orig has been updated; write */
905 rc = keydb_update_keyblock (hd, keyblock_orig);
906 if (rc)
907 log_error (_("error writing keyring `%s': %s\n"),
908 keydb_get_resource_name (hd), g10_errstr(rc) );
909 else if(non_self)
910 revalidation_mark ();
912 /* we are ready */
913 if( !opt.quiet )
915 char *p=get_user_id_native(keyid);
916 if( n_uids == 1 )
917 log_info( _("key %s: \"%s\" 1 new user ID\n"),
918 keystr(keyid),p);
919 else if( n_uids )
920 log_info( _("key %s: \"%s\" %d new user IDs\n"),
921 keystr(keyid),p,n_uids);
922 if( n_sigs == 1 )
923 log_info( _("key %s: \"%s\" 1 new signature\n"),
924 keystr(keyid), p);
925 else if( n_sigs )
926 log_info( _("key %s: \"%s\" %d new signatures\n"),
927 keystr(keyid), p, n_sigs );
928 if( n_subk == 1 )
929 log_info( _("key %s: \"%s\" 1 new subkey\n"),
930 keystr(keyid), p);
931 else if( n_subk )
932 log_info( _("key %s: \"%s\" %d new subkeys\n"),
933 keystr(keyid), p, n_subk );
934 if(n_sigs_cleaned==1)
935 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
936 keystr(keyid),p,n_sigs_cleaned);
937 else if(n_sigs_cleaned)
938 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
939 keystr(keyid),p,n_sigs_cleaned);
940 if(n_uids_cleaned==1)
941 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
942 keystr(keyid),p,n_uids_cleaned);
943 else if(n_uids_cleaned)
944 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
945 keystr(keyid),p,n_uids_cleaned);
946 xfree(p);
949 stats->n_uids +=n_uids;
950 stats->n_sigs +=n_sigs;
951 stats->n_subk +=n_subk;
952 stats->n_sigs_cleaned +=n_sigs_cleaned;
953 stats->n_uids_cleaned +=n_uids_cleaned;
955 if (is_status_enabled ())
956 print_import_ok (pk, NULL,
957 ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
959 else
961 if (is_status_enabled ())
962 print_import_ok (pk, NULL, 0);
964 if( !opt.quiet )
966 char *p=get_user_id_native(keyid);
967 log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
968 xfree(p);
971 stats->unchanged++;
974 keydb_release (hd); hd = NULL;
977 leave:
979 /* Now that the key is definitely incorporated into the keydb, we
980 need to check if a designated revocation is present or if the
981 prefs are not rational so we can warn the user. */
983 if(mod_key)
985 revocation_present(keyblock_orig);
986 if(!from_sk && seckey_available(keyid)==0)
987 check_prefs(keyblock_orig);
989 else if(new_key)
991 /* A little explanation for this: we fill in the fingerprint
992 when importing keys as it can be useful to know the
993 fingerprint in certain keyserver-related cases (a keyserver
994 asked for a particular name, but the key doesn't have that
995 name). However, in cases where we're importing more than
996 one key at a time, we cannot know which key to fingerprint.
997 In these cases, rather than guessing, we do not fingerpring
998 at all, and we must hope the user ID on the keys are
999 useful. */
1000 if(fpr)
1002 xfree(*fpr);
1003 if(stats->imported==1)
1004 *fpr=fingerprint_from_pk(pk,NULL,fpr_len);
1005 else
1006 *fpr=NULL;
1009 revocation_present(keyblock);
1010 if(!from_sk && seckey_available(keyid)==0)
1011 check_prefs(keyblock);
1014 release_kbnode( keyblock_orig );
1015 free_public_key( pk_orig );
1017 return rc;
1020 /* Walk a secret keyblock and produce a public keyblock out of it. */
1021 static KBNODE
1022 sec_to_pub_keyblock(KBNODE sec_keyblock)
1024 KBNODE secnode,pub_keyblock=NULL,ctx=NULL;
1026 while((secnode=walk_kbnode(sec_keyblock,&ctx,0)))
1028 KBNODE pubnode;
1030 if(secnode->pkt->pkttype==PKT_SECRET_KEY ||
1031 secnode->pkt->pkttype==PKT_SECRET_SUBKEY)
1033 /* Make a public key. We only need to convert enough to
1034 write the keyblock out. */
1036 PKT_secret_key *sk=secnode->pkt->pkt.secret_key;
1037 PACKET *pkt=xmalloc_clear(sizeof(PACKET));
1038 PKT_public_key *pk=xmalloc_clear(sizeof(PKT_public_key));
1039 int n;
1041 if(secnode->pkt->pkttype==PKT_SECRET_KEY)
1042 pkt->pkttype=PKT_PUBLIC_KEY;
1043 else
1044 pkt->pkttype=PKT_PUBLIC_SUBKEY;
1046 pkt->pkt.public_key=pk;
1048 pk->version=sk->version;
1049 pk->timestamp=sk->timestamp;
1050 pk->expiredate=sk->expiredate;
1051 pk->pubkey_algo=sk->pubkey_algo;
1053 n=pubkey_get_npkey(pk->pubkey_algo);
1054 if(n==0)
1056 /* we can't properly extract the pubkey without knowing
1057 the number of MPIs */
1058 release_kbnode(pub_keyblock);
1059 return NULL;
1061 else
1063 int i;
1065 for(i=0;i<n;i++)
1066 pk->pkey[i]=mpi_copy(sk->skey[i]);
1069 pubnode=new_kbnode(pkt);
1071 else
1073 pubnode=clone_kbnode(secnode);
1076 if(pub_keyblock==NULL)
1077 pub_keyblock=pubnode;
1078 else
1079 add_kbnode(pub_keyblock,pubnode);
1082 return pub_keyblock;
1085 /****************
1086 * Ditto for secret keys. Handling is simpler than for public keys.
1087 * We allow secret key importing only when allow is true, this is so
1088 * that a secret key can not be imported accidently and thereby tampering
1089 * with the trust calculation.
1091 static int
1092 import_secret_one( const char *fname, KBNODE keyblock,
1093 struct stats_s *stats, unsigned int options)
1095 PKT_secret_key *sk;
1096 KBNODE node, uidnode;
1097 u32 keyid[2];
1098 int rc = 0;
1100 /* get the key and print some info about it */
1101 node = find_kbnode( keyblock, PKT_SECRET_KEY );
1102 if( !node )
1103 BUG();
1105 sk = node->pkt->pkt.secret_key;
1106 keyid_from_sk( sk, keyid );
1107 uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1109 if( opt.verbose )
1111 log_info( "sec %4u%c/%s %s ",
1112 nbits_from_sk( sk ),
1113 pubkey_letter( sk->pubkey_algo ),
1114 keystr_from_sk(sk), datestr_from_sk(sk) );
1115 if( uidnode )
1116 print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
1117 uidnode->pkt->pkt.user_id->len );
1118 log_printf ("\n");
1120 stats->secret_read++;
1122 if( !uidnode )
1124 log_error( _("key %s: no user ID\n"), keystr_from_sk(sk));
1125 return 0;
1128 if(sk->protect.algo>110)
1130 log_error(_("key %s: secret key with invalid cipher %d"
1131 " - skipped\n"),keystr_from_sk(sk),sk->protect.algo);
1132 return 0;
1135 #ifdef ENABLE_SELINUX_HACKS
1136 if (1)
1138 /* We don't allow to import secret keys because that may be used
1139 to put a secret key into the keyring and the user might later
1140 be tricked into signing stuff with that key. */
1141 log_error (_("importing secret keys not allowed\n"));
1142 return 0;
1144 #endif
1146 clear_kbnode_flags( keyblock );
1148 /* do we have this key already in one of our secrings ? */
1149 rc = seckey_available( keyid );
1150 if( rc == G10ERR_NO_SECKEY && !(opt.import_options&IMPORT_MERGE_ONLY) )
1152 /* simply insert this key */
1153 KEYDB_HANDLE hd = keydb_new (1);
1155 /* get default resource */
1156 rc = keydb_locate_writable (hd, NULL);
1157 if (rc) {
1158 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
1159 keydb_release (hd);
1160 return G10ERR_GENERAL;
1162 rc = keydb_insert_keyblock (hd, keyblock );
1163 if (rc)
1164 log_error (_("error writing keyring `%s': %s\n"),
1165 keydb_get_resource_name (hd), g10_errstr(rc) );
1166 keydb_release (hd);
1167 /* we are ready */
1168 if( !opt.quiet )
1169 log_info( _("key %s: secret key imported\n"), keystr_from_sk(sk));
1170 stats->secret_imported++;
1171 if (is_status_enabled ())
1172 print_import_ok (NULL, sk, 1|16);
1174 if(options&IMPORT_SK2PK)
1176 /* Try and make a public key out of this. */
1178 KBNODE pub_keyblock=sec_to_pub_keyblock(keyblock);
1179 if(pub_keyblock)
1181 import_one(fname,pub_keyblock,stats,
1182 NULL,NULL,opt.import_options,1);
1183 release_kbnode(pub_keyblock);
1187 /* Now that the key is definitely incorporated into the keydb,
1188 if we have the public part of this key, we need to check if
1189 the prefs are rational. */
1190 node=get_pubkeyblock(keyid);
1191 if(node)
1193 check_prefs(node);
1194 release_kbnode(node);
1197 else if( !rc )
1198 { /* we can't merge secret keys */
1199 log_error( _("key %s: already in secret keyring\n"),
1200 keystr_from_sk(sk));
1201 stats->secret_dups++;
1202 if (is_status_enabled ())
1203 print_import_ok (NULL, sk, 16);
1205 /* TODO: if we ever do merge secret keys, make sure to handle
1206 the sec_to_pub_keyblock feature as well. */
1208 else
1209 log_error( _("key %s: secret key not found: %s\n"),
1210 keystr_from_sk(sk), g10_errstr(rc));
1212 return rc;
1216 /****************
1217 * Import a revocation certificate; this is a single signature packet.
1219 static int
1220 import_revoke_cert( const char *fname, KBNODE node, struct stats_s *stats )
1222 PKT_public_key *pk=NULL;
1223 KBNODE onode, keyblock = NULL;
1224 KEYDB_HANDLE hd = NULL;
1225 u32 keyid[2];
1226 int rc = 0;
1228 assert( !node->next );
1229 assert( node->pkt->pkttype == PKT_SIGNATURE );
1230 assert( node->pkt->pkt.signature->sig_class == 0x20 );
1232 keyid[0] = node->pkt->pkt.signature->keyid[0];
1233 keyid[1] = node->pkt->pkt.signature->keyid[1];
1235 pk = xmalloc_clear( sizeof *pk );
1236 rc = get_pubkey( pk, keyid );
1237 if( rc == G10ERR_NO_PUBKEY )
1239 log_error(_("key %s: no public key -"
1240 " can't apply revocation certificate\n"), keystr(keyid));
1241 rc = 0;
1242 goto leave;
1244 else if( rc )
1246 log_error(_("key %s: public key not found: %s\n"),
1247 keystr(keyid), g10_errstr(rc));
1248 goto leave;
1251 /* read the original keyblock */
1252 hd = keydb_new (0);
1254 byte afp[MAX_FINGERPRINT_LEN];
1255 size_t an;
1257 fingerprint_from_pk (pk, afp, &an);
1258 while (an < MAX_FINGERPRINT_LEN)
1259 afp[an++] = 0;
1260 rc = keydb_search_fpr (hd, afp);
1262 if (rc)
1264 log_error (_("key %s: can't locate original keyblock: %s\n"),
1265 keystr(keyid), g10_errstr(rc));
1266 goto leave;
1268 rc = keydb_get_keyblock (hd, &keyblock );
1269 if (rc)
1271 log_error (_("key %s: can't read original keyblock: %s\n"),
1272 keystr(keyid), g10_errstr(rc));
1273 goto leave;
1276 /* it is okay, that node is not in keyblock because
1277 * check_key_signature works fine for sig_class 0x20 in this
1278 * special case. */
1279 rc = check_key_signature( keyblock, node, NULL);
1280 if( rc )
1282 log_error( _("key %s: invalid revocation certificate"
1283 ": %s - rejected\n"), keystr(keyid), g10_errstr(rc));
1284 goto leave;
1287 /* check whether we already have this */
1288 for(onode=keyblock->next; onode; onode=onode->next ) {
1289 if( onode->pkt->pkttype == PKT_USER_ID )
1290 break;
1291 else if( onode->pkt->pkttype == PKT_SIGNATURE
1292 && !cmp_signatures(node->pkt->pkt.signature,
1293 onode->pkt->pkt.signature))
1295 rc = 0;
1296 goto leave; /* yes, we already know about it */
1301 /* insert it */
1302 insert_kbnode( keyblock, clone_kbnode(node), 0 );
1304 /* and write the keyblock back */
1305 rc = keydb_update_keyblock (hd, keyblock );
1306 if (rc)
1307 log_error (_("error writing keyring `%s': %s\n"),
1308 keydb_get_resource_name (hd), g10_errstr(rc) );
1309 keydb_release (hd); hd = NULL;
1310 /* we are ready */
1311 if( !opt.quiet )
1313 char *p=get_user_id_native (keyid);
1314 log_info( _("key %s: \"%s\" revocation certificate imported\n"),
1315 keystr(keyid),p);
1316 xfree(p);
1318 stats->n_revoc++;
1320 /* If the key we just revoked was ultimately trusted, remove its
1321 ultimate trust. This doesn't stop the user from putting the
1322 ultimate trust back, but is a reasonable solution for now. */
1323 if(get_ownertrust(pk)==TRUST_ULTIMATE)
1324 clear_ownertrusts(pk);
1326 revalidation_mark ();
1328 leave:
1329 keydb_release (hd);
1330 release_kbnode( keyblock );
1331 free_public_key( pk );
1332 return rc;
1336 /****************
1337 * loop over the keyblock and check all self signatures.
1338 * Mark all user-ids with a self-signature by setting flag bit 0.
1339 * Mark all user-ids with an invalid self-signature by setting bit 1.
1340 * This works also for subkeys, here the subkey is marked. Invalid or
1341 * extra subkey sigs (binding or revocation) are marked for deletion.
1342 * non_self is set to true if there are any sigs other than self-sigs
1343 * in this keyblock.
1345 static int
1346 chk_self_sigs( const char *fname, KBNODE keyblock,
1347 PKT_public_key *pk, u32 *keyid, int *non_self )
1349 KBNODE n,knode=NULL;
1350 PKT_signature *sig;
1351 int rc;
1352 u32 bsdate=0,rsdate=0;
1353 KBNODE bsnode=NULL,rsnode=NULL;
1355 for( n=keyblock; (n = find_next_kbnode(n, 0)); ) {
1356 if(n->pkt->pkttype==PKT_PUBLIC_SUBKEY)
1358 knode=n;
1359 bsdate=0;
1360 rsdate=0;
1361 bsnode=NULL;
1362 rsnode=NULL;
1363 continue;
1365 else if( n->pkt->pkttype != PKT_SIGNATURE )
1366 continue;
1367 sig = n->pkt->pkt.signature;
1368 if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] ) {
1370 /* This just caches the sigs for later use. That way we
1371 import a fully-cached key which speeds things up. */
1372 if(!opt.no_sig_cache)
1373 check_key_signature(keyblock,n,NULL);
1375 if( IS_UID_SIG(sig) || IS_UID_REV(sig) )
1377 KBNODE unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
1378 if( !unode )
1380 log_error( _("key %s: no user ID for signature\n"),
1381 keystr(keyid));
1382 return -1; /* the complete keyblock is invalid */
1385 /* If it hasn't been marked valid yet, keep trying */
1386 if(!(unode->flag&1)) {
1387 rc = check_key_signature( keyblock, n, NULL);
1388 if( rc )
1390 if( opt.verbose )
1392 char *p=utf8_to_native(unode->pkt->pkt.user_id->name,
1393 strlen(unode->pkt->pkt.user_id->name),0);
1394 log_info( rc == G10ERR_PUBKEY_ALGO ?
1395 _("key %s: unsupported public key "
1396 "algorithm on user ID \"%s\"\n"):
1397 _("key %s: invalid self-signature "
1398 "on user ID \"%s\"\n"),
1399 keystr(keyid),p);
1400 xfree(p);
1403 else
1404 unode->flag |= 1; /* mark that signature checked */
1407 else if( sig->sig_class == 0x18 ) {
1408 /* Note that this works based solely on the timestamps
1409 like the rest of gpg. If the standard gets
1410 revocation targets, this may need to be revised. */
1412 if( !knode )
1414 if(opt.verbose)
1415 log_info( _("key %s: no subkey for key binding\n"),
1416 keystr(keyid));
1417 n->flag |= 4; /* delete this */
1419 else
1421 rc = check_key_signature( keyblock, n, NULL);
1422 if( rc )
1424 if(opt.verbose)
1425 log_info(rc == G10ERR_PUBKEY_ALGO ?
1426 _("key %s: unsupported public key"
1427 " algorithm\n"):
1428 _("key %s: invalid subkey binding\n"),
1429 keystr(keyid));
1430 n->flag|=4;
1432 else
1434 /* It's valid, so is it newer? */
1435 if(sig->timestamp>=bsdate) {
1436 knode->flag |= 1; /* the subkey is valid */
1437 if(bsnode)
1439 bsnode->flag|=4; /* Delete the last binding
1440 sig since this one is
1441 newer */
1442 if(opt.verbose)
1443 log_info(_("key %s: removed multiple subkey"
1444 " binding\n"),keystr(keyid));
1447 bsnode=n;
1448 bsdate=sig->timestamp;
1450 else
1451 n->flag|=4; /* older */
1455 else if( sig->sig_class == 0x28 ) {
1456 /* We don't actually mark the subkey as revoked right
1457 now, so just check that the revocation sig is the
1458 most recent valid one. Note that we don't care if
1459 the binding sig is newer than the revocation sig.
1460 See the comment in getkey.c:merge_selfsigs_subkey for
1461 more */
1462 if( !knode )
1464 if(opt.verbose)
1465 log_info( _("key %s: no subkey for key revocation\n"),
1466 keystr(keyid));
1467 n->flag |= 4; /* delete this */
1469 else
1471 rc = check_key_signature( keyblock, n, NULL);
1472 if( rc )
1474 if(opt.verbose)
1475 log_info(rc == G10ERR_PUBKEY_ALGO ?
1476 _("key %s: unsupported public"
1477 " key algorithm\n"):
1478 _("key %s: invalid subkey revocation\n"),
1479 keystr(keyid));
1480 n->flag|=4;
1482 else
1484 /* It's valid, so is it newer? */
1485 if(sig->timestamp>=rsdate)
1487 if(rsnode)
1489 rsnode->flag|=4; /* Delete the last revocation
1490 sig since this one is
1491 newer */
1492 if(opt.verbose)
1493 log_info(_("key %s: removed multiple subkey"
1494 " revocation\n"),keystr(keyid));
1497 rsnode=n;
1498 rsdate=sig->timestamp;
1500 else
1501 n->flag|=4; /* older */
1506 else
1507 *non_self=1;
1510 return 0;
1513 /****************
1514 * delete all parts which are invalid and those signatures whose
1515 * public key algorithm is not available in this implemenation;
1516 * but consider RSA as valid, because parse/build_packets knows
1517 * about it.
1518 * returns: true if at least one valid user-id is left over.
1520 static int
1521 delete_inv_parts( const char *fname, KBNODE keyblock,
1522 u32 *keyid, unsigned int options)
1524 KBNODE node;
1525 int nvalid=0, uid_seen=0, subkey_seen=0;
1527 for(node=keyblock->next; node; node = node->next ) {
1528 if( node->pkt->pkttype == PKT_USER_ID ) {
1529 uid_seen = 1;
1530 if( (node->flag & 2) || !(node->flag & 1) ) {
1531 if( opt.verbose )
1533 char *p=utf8_to_native(node->pkt->pkt.user_id->name,
1534 node->pkt->pkt.user_id->len,0);
1535 log_info( _("key %s: skipped user ID \"%s\"\n"),
1536 keystr(keyid),p);
1537 xfree(p);
1539 delete_kbnode( node ); /* the user-id */
1540 /* and all following packets up to the next user-id */
1541 while( node->next
1542 && node->next->pkt->pkttype != PKT_USER_ID
1543 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1544 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
1545 delete_kbnode( node->next );
1546 node = node->next;
1549 else
1550 nvalid++;
1552 else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1553 || node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1554 if( (node->flag & 2) || !(node->flag & 1) ) {
1555 if( opt.verbose )
1556 log_info( _("key %s: skipped subkey\n"),keystr(keyid));
1558 delete_kbnode( node ); /* the subkey */
1559 /* and all following signature packets */
1560 while( node->next
1561 && node->next->pkt->pkttype == PKT_SIGNATURE ) {
1562 delete_kbnode( node->next );
1563 node = node->next;
1566 else
1567 subkey_seen = 1;
1569 else if (node->pkt->pkttype == PKT_SIGNATURE
1570 && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
1571 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
1572 delete_kbnode( node ); /* build_packet() can't handle this */
1573 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1574 !node->pkt->pkt.signature->flags.exportable &&
1575 !(options&IMPORT_LOCAL_SIGS) &&
1576 seckey_available( node->pkt->pkt.signature->keyid ) )
1578 /* here we violate the rfc a bit by still allowing
1579 * to import non-exportable signature when we have the
1580 * the secret key used to create this signature - it
1581 * seems that this makes sense */
1582 if(opt.verbose)
1583 log_info( _("key %s: non exportable signature"
1584 " (class 0x%02X) - skipped\n"),
1585 keystr(keyid), node->pkt->pkt.signature->sig_class );
1586 delete_kbnode( node );
1588 else if( node->pkt->pkttype == PKT_SIGNATURE
1589 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1590 if( uid_seen )
1592 if(opt.verbose)
1593 log_info( _("key %s: revocation certificate"
1594 " at wrong place - skipped\n"),keystr(keyid));
1595 delete_kbnode( node );
1597 else {
1598 /* If the revocation cert is from a different key than
1599 the one we're working on don't check it - it's
1600 probably from a revocation key and won't be
1601 verifiable with this key anyway. */
1603 if(node->pkt->pkt.signature->keyid[0]==keyid[0] &&
1604 node->pkt->pkt.signature->keyid[1]==keyid[1])
1606 int rc = check_key_signature( keyblock, node, NULL);
1607 if( rc )
1609 if(opt.verbose)
1610 log_info( _("key %s: invalid revocation"
1611 " certificate: %s - skipped\n"),
1612 keystr(keyid), g10_errstr(rc));
1613 delete_kbnode( node );
1618 else if( node->pkt->pkttype == PKT_SIGNATURE &&
1619 (node->pkt->pkt.signature->sig_class == 0x18 ||
1620 node->pkt->pkt.signature->sig_class == 0x28) &&
1621 !subkey_seen )
1623 if(opt.verbose)
1624 log_info( _("key %s: subkey signature"
1625 " in wrong place - skipped\n"), keystr(keyid));
1626 delete_kbnode( node );
1628 else if( node->pkt->pkttype == PKT_SIGNATURE
1629 && !IS_CERT(node->pkt->pkt.signature))
1631 if(opt.verbose)
1632 log_info(_("key %s: unexpected signature class (0x%02X) -"
1633 " skipped\n"),keystr(keyid),
1634 node->pkt->pkt.signature->sig_class);
1635 delete_kbnode(node);
1637 else if( (node->flag & 4) ) /* marked for deletion */
1638 delete_kbnode( node );
1641 /* note: because keyblock is the public key, it is never marked
1642 * for deletion and so keyblock cannot change */
1643 commit_kbnode( &keyblock );
1644 return nvalid;
1648 /****************
1649 * It may happen that the imported keyblock has duplicated user IDs.
1650 * We check this here and collapse those user IDs together with their
1651 * sigs into one.
1652 * Returns: True if the keyblock has changed.
1655 collapse_uids( KBNODE *keyblock )
1657 KBNODE uid1;
1658 int any=0;
1660 for(uid1=*keyblock;uid1;uid1=uid1->next)
1662 KBNODE uid2;
1664 if(uid1->pkt->pkttype!=PKT_USER_ID)
1665 continue;
1667 for(uid2=uid1->next;uid2;uid2=uid2->next)
1669 if(uid2->pkt->pkttype!=PKT_USER_ID)
1670 continue;
1672 if(cmp_user_ids(uid1->pkt->pkt.user_id,
1673 uid2->pkt->pkt.user_id)==0)
1675 /* We have a duplicated uid */
1676 KBNODE sig1,last;
1678 any=1;
1680 /* Now take uid2's signatures, and attach them to
1681 uid1 */
1682 for(last=uid2;last->next;last=last->next)
1684 if(last->next->pkt->pkttype==PKT_USER_ID
1685 || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
1686 || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
1687 break;
1690 /* Snip out uid2 */
1691 (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
1693 /* Now put uid2 in place as part of uid1 */
1694 last->next=uid1->next;
1695 uid1->next=uid2;
1696 remove_kbnode(keyblock,uid2);
1698 /* Now dedupe uid1 */
1699 for(sig1=uid1->next;sig1;sig1=sig1->next)
1701 KBNODE sig2;
1703 if(sig1->pkt->pkttype==PKT_USER_ID
1704 || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
1705 || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
1706 break;
1708 if(sig1->pkt->pkttype!=PKT_SIGNATURE)
1709 continue;
1711 for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
1713 if(sig2->pkt->pkttype==PKT_USER_ID
1714 || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
1715 || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
1716 break;
1718 if(sig2->pkt->pkttype!=PKT_SIGNATURE)
1719 continue;
1721 if(cmp_signatures(sig1->pkt->pkt.signature,
1722 sig2->pkt->pkt.signature)==0)
1724 /* We have a match, so delete the second
1725 signature */
1726 remove_kbnode(&uid1,sig2);
1727 sig2=last;
1735 if(any && !opt.quiet)
1737 const char *key="???";
1739 if( (uid1=find_kbnode( *keyblock, PKT_PUBLIC_KEY )) )
1740 key=keystr_from_pk(uid1->pkt->pkt.public_key);
1741 else if( (uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY )) )
1742 key=keystr_from_sk(uid1->pkt->pkt.secret_key);
1744 log_info(_("key %s: duplicated user ID detected - merged\n"),key);
1747 return any;
1750 /* Check for a 0x20 revocation from a revocation key that is not
1751 present. This may be called without the benefit of merge_xxxx so
1752 you can't rely on pk->revkey and friends. */
1753 static void
1754 revocation_present(KBNODE keyblock)
1756 KBNODE onode,inode;
1757 PKT_public_key *pk=keyblock->pkt->pkt.public_key;
1759 for(onode=keyblock->next;onode;onode=onode->next)
1761 /* If we reach user IDs, we're done. */
1762 if(onode->pkt->pkttype==PKT_USER_ID)
1763 break;
1765 if(onode->pkt->pkttype==PKT_SIGNATURE &&
1766 onode->pkt->pkt.signature->sig_class==0x1F &&
1767 onode->pkt->pkt.signature->revkey)
1769 int idx;
1770 PKT_signature *sig=onode->pkt->pkt.signature;
1772 for(idx=0;idx<sig->numrevkeys;idx++)
1774 u32 keyid[2];
1776 keyid_from_fingerprint(sig->revkey[idx]->fpr,
1777 MAX_FINGERPRINT_LEN,keyid);
1779 for(inode=keyblock->next;inode;inode=inode->next)
1781 /* If we reach user IDs, we're done. */
1782 if(inode->pkt->pkttype==PKT_USER_ID)
1783 break;
1785 if(inode->pkt->pkttype==PKT_SIGNATURE &&
1786 inode->pkt->pkt.signature->sig_class==0x20 &&
1787 inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
1788 inode->pkt->pkt.signature->keyid[1]==keyid[1])
1790 /* Okay, we have a revocation key, and a
1791 revocation issued by it. Do we have the key
1792 itself? */
1793 int rc;
1795 rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx]->fpr,
1796 MAX_FINGERPRINT_LEN);
1797 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1799 char *tempkeystr=xstrdup(keystr_from_pk(pk));
1801 /* No, so try and get it */
1802 if(opt.keyserver
1803 && (opt.keyserver_options.options
1804 & KEYSERVER_AUTO_KEY_RETRIEVE))
1806 log_info(_("WARNING: key %s may be revoked:"
1807 " fetching revocation key %s\n"),
1808 tempkeystr,keystr(keyid));
1809 keyserver_import_fprint(sig->revkey[idx]->fpr,
1810 MAX_FINGERPRINT_LEN,
1811 opt.keyserver);
1813 /* Do we have it now? */
1814 rc=get_pubkey_byfprint_fast (NULL,
1815 sig->revkey[idx]->fpr,
1816 MAX_FINGERPRINT_LEN);
1819 if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1820 log_info(_("WARNING: key %s may be revoked:"
1821 " revocation key %s not present.\n"),
1822 tempkeystr,keystr(keyid));
1824 xfree(tempkeystr);
1833 /****************
1834 * compare and merge the blocks
1836 * o compare the signatures: If we already have this signature, check
1837 * that they compare okay; if not, issue a warning and ask the user.
1838 * o Simply add the signature. Can't verify here because we may not have
1839 * the signature's public key yet; verification is done when putting it
1840 * into the trustdb, which is done automagically as soon as this pubkey
1841 * is used.
1842 * Note: We indicate newly inserted packets with flag bit 0
1844 static int
1845 merge_blocks( const char *fname, KBNODE keyblock_orig, KBNODE keyblock,
1846 u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
1848 KBNODE onode, node;
1849 int rc, found;
1851 /* 1st: handle revocation certificates */
1852 for(node=keyblock->next; node; node=node->next ) {
1853 if( node->pkt->pkttype == PKT_USER_ID )
1854 break;
1855 else if( node->pkt->pkttype == PKT_SIGNATURE
1856 && node->pkt->pkt.signature->sig_class == 0x20 ) {
1857 /* check whether we already have this */
1858 found = 0;
1859 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1860 if( onode->pkt->pkttype == PKT_USER_ID )
1861 break;
1862 else if( onode->pkt->pkttype == PKT_SIGNATURE
1863 && onode->pkt->pkt.signature->sig_class == 0x20
1864 && !cmp_signatures(onode->pkt->pkt.signature,
1865 node->pkt->pkt.signature))
1867 found = 1;
1868 break;
1871 if( !found ) {
1872 KBNODE n2 = clone_kbnode(node);
1873 insert_kbnode( keyblock_orig, n2, 0 );
1874 n2->flag |= 1;
1875 ++*n_sigs;
1876 if(!opt.quiet)
1878 char *p=get_user_id_native (keyid);
1879 log_info(_("key %s: \"%s\" revocation"
1880 " certificate added\n"), keystr(keyid),p);
1881 xfree(p);
1887 /* 2nd: merge in any direct key (0x1F) sigs */
1888 for(node=keyblock->next; node; node=node->next ) {
1889 if( node->pkt->pkttype == PKT_USER_ID )
1890 break;
1891 else if( node->pkt->pkttype == PKT_SIGNATURE
1892 && node->pkt->pkt.signature->sig_class == 0x1F ) {
1893 /* check whether we already have this */
1894 found = 0;
1895 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1896 if( onode->pkt->pkttype == PKT_USER_ID )
1897 break;
1898 else if( onode->pkt->pkttype == PKT_SIGNATURE
1899 && onode->pkt->pkt.signature->sig_class == 0x1F
1900 && !cmp_signatures(onode->pkt->pkt.signature,
1901 node->pkt->pkt.signature)) {
1902 found = 1;
1903 break;
1906 if( !found )
1908 KBNODE n2 = clone_kbnode(node);
1909 insert_kbnode( keyblock_orig, n2, 0 );
1910 n2->flag |= 1;
1911 ++*n_sigs;
1912 if(!opt.quiet)
1913 log_info( _("key %s: direct key signature added\n"),
1914 keystr(keyid));
1919 /* 3rd: try to merge new certificates in */
1920 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1921 if( !(onode->flag & 1) && onode->pkt->pkttype == PKT_USER_ID) {
1922 /* find the user id in the imported keyblock */
1923 for(node=keyblock->next; node; node=node->next )
1924 if( node->pkt->pkttype == PKT_USER_ID
1925 && !cmp_user_ids( onode->pkt->pkt.user_id,
1926 node->pkt->pkt.user_id ) )
1927 break;
1928 if( node ) { /* found: merge */
1929 rc = merge_sigs( onode, node, n_sigs, fname, keyid );
1930 if( rc )
1931 return rc;
1936 /* 4th: add new user-ids */
1937 for(node=keyblock->next; node; node=node->next ) {
1938 if( node->pkt->pkttype == PKT_USER_ID) {
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_USER_ID
1942 && !cmp_user_ids( onode->pkt->pkt.user_id,
1943 node->pkt->pkt.user_id ) )
1944 break;
1945 if( !onode ) { /* this is a new user id: append */
1946 rc = append_uid( keyblock_orig, node, n_sigs, fname, keyid);
1947 if( rc )
1948 return rc;
1949 ++*n_uids;
1954 /* 5th: add new subkeys */
1955 for(node=keyblock->next; node; node=node->next ) {
1956 onode = NULL;
1957 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1958 /* do we have this in the original keyblock? */
1959 for(onode=keyblock_orig->next; onode; onode=onode->next )
1960 if( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
1961 && !cmp_public_keys( onode->pkt->pkt.public_key,
1962 node->pkt->pkt.public_key ) )
1963 break;
1964 if( !onode ) { /* this is a new subkey: append */
1965 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
1966 if( rc )
1967 return rc;
1968 ++*n_subk;
1971 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1972 /* do we have this in the original keyblock? */
1973 for(onode=keyblock_orig->next; onode; onode=onode->next )
1974 if( onode->pkt->pkttype == PKT_SECRET_SUBKEY
1975 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
1976 node->pkt->pkt.secret_key ) )
1977 break;
1978 if( !onode ) { /* this is a new subkey: append */
1979 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
1980 if( rc )
1981 return rc;
1982 ++*n_subk;
1987 /* 6th: merge subkey certificates */
1988 for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1989 if( !(onode->flag & 1)
1990 && ( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
1991 || onode->pkt->pkttype == PKT_SECRET_SUBKEY) ) {
1992 /* find the subkey in the imported keyblock */
1993 for(node=keyblock->next; node; node=node->next ) {
1994 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1995 && !cmp_public_keys( onode->pkt->pkt.public_key,
1996 node->pkt->pkt.public_key ) )
1997 break;
1998 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY
1999 && !cmp_secret_keys( onode->pkt->pkt.secret_key,
2000 node->pkt->pkt.secret_key ) )
2001 break;
2003 if( node ) { /* found: merge */
2004 rc = merge_keysigs( onode, node, n_sigs, fname, keyid );
2005 if( rc )
2006 return rc;
2012 return 0;
2016 /****************
2017 * append the userid starting with NODE and all signatures to KEYBLOCK.
2019 static int
2020 append_uid( KBNODE keyblock, KBNODE node, int *n_sigs,
2021 const char *fname, u32 *keyid )
2023 KBNODE n, n_where=NULL;
2025 assert(node->pkt->pkttype == PKT_USER_ID );
2027 /* find the position */
2028 for( n = keyblock; n; n_where = n, n = n->next ) {
2029 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2030 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
2031 break;
2033 if( !n )
2034 n_where = NULL;
2036 /* and append/insert */
2037 while( node ) {
2038 /* we add a clone to the original keyblock, because this
2039 * one is released first */
2040 n = clone_kbnode(node);
2041 if( n_where ) {
2042 insert_kbnode( n_where, n, 0 );
2043 n_where = n;
2045 else
2046 add_kbnode( keyblock, n );
2047 n->flag |= 1;
2048 node->flag |= 1;
2049 if( n->pkt->pkttype == PKT_SIGNATURE )
2050 ++*n_sigs;
2052 node = node->next;
2053 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2054 break;
2057 return 0;
2061 /****************
2062 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
2063 * (how should we handle comment packets here?)
2065 static int
2066 merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
2067 const char *fname, u32 *keyid )
2069 KBNODE n, n2;
2070 int found=0;
2072 assert(dst->pkt->pkttype == PKT_USER_ID );
2073 assert(src->pkt->pkttype == PKT_USER_ID );
2075 for(n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next ) {
2076 if( n->pkt->pkttype != PKT_SIGNATURE )
2077 continue;
2078 if( n->pkt->pkt.signature->sig_class == 0x18
2079 || n->pkt->pkt.signature->sig_class == 0x28 )
2080 continue; /* skip signatures which are only valid on subkeys */
2081 found = 0;
2082 for(n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
2083 if(!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
2085 found++;
2086 break;
2088 if( !found ) {
2089 /* This signature is new or newer, append N to DST.
2090 * We add a clone to the original keyblock, because this
2091 * one is released first */
2092 n2 = clone_kbnode(n);
2093 insert_kbnode( dst, n2, PKT_SIGNATURE );
2094 n2->flag |= 1;
2095 n->flag |= 1;
2096 ++*n_sigs;
2100 return 0;
2103 /****************
2104 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
2106 static int
2107 merge_keysigs( KBNODE dst, KBNODE src, int *n_sigs,
2108 const char *fname, u32 *keyid )
2110 KBNODE n, n2;
2111 int found=0;
2113 assert( dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
2114 || dst->pkt->pkttype == PKT_SECRET_SUBKEY );
2116 for(n=src->next; n ; n = n->next ) {
2117 if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2118 || n->pkt->pkttype == PKT_PUBLIC_KEY )
2119 break;
2120 if( n->pkt->pkttype != PKT_SIGNATURE )
2121 continue;
2122 found = 0;
2123 for(n2=dst->next; n2; n2 = n2->next){
2124 if( n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
2125 || n2->pkt->pkttype == PKT_PUBLIC_KEY )
2126 break;
2127 if( n2->pkt->pkttype == PKT_SIGNATURE
2128 && n->pkt->pkt.signature->keyid[0]
2129 == n2->pkt->pkt.signature->keyid[0]
2130 && n->pkt->pkt.signature->keyid[1]
2131 == n2->pkt->pkt.signature->keyid[1]
2132 && n->pkt->pkt.signature->timestamp
2133 <= n2->pkt->pkt.signature->timestamp
2134 && n->pkt->pkt.signature->sig_class
2135 == n2->pkt->pkt.signature->sig_class ) {
2136 found++;
2137 break;
2140 if( !found ) {
2141 /* This signature is new or newer, append N to DST.
2142 * We add a clone to the original keyblock, because this
2143 * one is released first */
2144 n2 = clone_kbnode(n);
2145 insert_kbnode( dst, n2, PKT_SIGNATURE );
2146 n2->flag |= 1;
2147 n->flag |= 1;
2148 ++*n_sigs;
2152 return 0;
2155 /****************
2156 * append the subkey starting with NODE and all signatures to KEYBLOCK.
2157 * Mark all new and copied packets by setting flag bit 0.
2159 static int
2160 append_key( KBNODE keyblock, KBNODE node, int *n_sigs,
2161 const char *fname, u32 *keyid )
2163 KBNODE n;
2165 assert( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2166 || node->pkt->pkttype == PKT_SECRET_SUBKEY );
2168 while( node ) {
2169 /* we add a clone to the original keyblock, because this
2170 * one is released first */
2171 n = clone_kbnode(node);
2172 add_kbnode( keyblock, n );
2173 n->flag |= 1;
2174 node->flag |= 1;
2175 if( n->pkt->pkttype == PKT_SIGNATURE )
2176 ++*n_sigs;
2178 node = node->next;
2179 if( node && node->pkt->pkttype != PKT_SIGNATURE )
2180 break;
2183 return 0;
2188 /* Walk a public keyblock and produce a secret keyblock out of it.
2189 Instead of inserting the secret key parameters (which we don't
2190 have), we insert a stub. */
2191 static KBNODE
2192 pub_to_sec_keyblock (KBNODE pub_keyblock)
2194 KBNODE pubnode, secnode;
2195 KBNODE sec_keyblock = NULL;
2196 KBNODE walkctx = NULL;
2198 while((pubnode = walk_kbnode (pub_keyblock,&walkctx,0)))
2200 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY
2201 || pubnode->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2203 /* Make a secret key. We only need to convert enough to
2204 write the keyblock out. */
2205 PKT_public_key *pk = pubnode->pkt->pkt.public_key;
2206 PACKET *pkt = xmalloc_clear (sizeof *pkt);
2207 PKT_secret_key *sk = xmalloc_clear (sizeof *sk);
2208 int i, n;
2210 if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY)
2211 pkt->pkttype = PKT_SECRET_KEY;
2212 else
2213 pkt->pkttype = PKT_SECRET_SUBKEY;
2215 pkt->pkt.secret_key = sk;
2217 copy_public_parts_to_secret_key ( pk, sk );
2218 sk->version = pk->version;
2219 sk->timestamp = pk->timestamp;
2221 n = pubkey_get_npkey (pk->pubkey_algo);
2222 if (!n)
2223 n = 1; /* Unknown number of parameters, however the data
2224 is stored in the first mpi. */
2225 for (i=0; i < n; i++ )
2226 sk->skey[i] = mpi_copy (pk->pkey[i]);
2228 sk->is_protected = 1;
2229 sk->protect.s2k.mode = 1001;
2231 secnode = new_kbnode (pkt);
2233 else
2235 secnode = clone_kbnode (pubnode);
2238 if(!sec_keyblock)
2239 sec_keyblock = secnode;
2240 else
2241 add_kbnode (sec_keyblock, secnode);
2244 return sec_keyblock;
2248 /* Walk over the secret keyring SEC_KEYBLOCK and update any simple
2249 stub keys with the serial number SNNUM of the card if one of the
2250 fingerprints FPR1, FPR2 or FPR3 match. Print a note if the key is
2251 a duplicate (may happen in case of backed uped keys).
2253 Returns: True if anything changed.
2255 static int
2256 update_sec_keyblock_with_cardinfo (KBNODE sec_keyblock,
2257 const unsigned char *fpr1,
2258 const unsigned char *fpr2,
2259 const unsigned char *fpr3,
2260 const char *serialnostr)
2262 KBNODE node;
2263 KBNODE walkctx = NULL;
2264 PKT_secret_key *sk;
2265 byte array[MAX_FINGERPRINT_LEN];
2266 size_t n;
2267 int result = 0;
2268 const char *s;
2270 while((node = walk_kbnode (sec_keyblock, &walkctx, 0)))
2272 if (node->pkt->pkttype != PKT_SECRET_KEY
2273 && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2274 continue;
2275 sk = node->pkt->pkt.secret_key;
2277 fingerprint_from_sk (sk, array, &n);
2278 if (n != 20)
2279 continue; /* Can't be a card key. */
2280 if ( !((fpr1 && !memcmp (array, fpr1, 20))
2281 || (fpr2 && !memcmp (array, fpr2, 20))
2282 || (fpr3 && !memcmp (array, fpr3, 20))) )
2283 continue; /* No match. */
2285 if (sk->is_protected == 1 && sk->protect.s2k.mode == 1001)
2287 /* Standard case: migrate that stub to a key stub. */
2288 sk->protect.s2k.mode = 1002;
2289 s = serialnostr;
2290 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2291 sk->protect.ivlen++, s += 2)
2292 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
2293 result = 1;
2295 else if (sk->is_protected == 1 && sk->protect.s2k.mode == 1002)
2297 s = serialnostr;
2298 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2299 sk->protect.ivlen++, s += 2)
2300 if (sk->protect.iv[sk->protect.ivlen] != xtoi_2 (s))
2302 log_info (_("NOTE: a key's S/N does not "
2303 "match the card's one\n"));
2304 break;
2307 else
2309 if (node->pkt->pkttype != PKT_SECRET_KEY)
2310 log_info (_("NOTE: primary key is online and stored on card\n"));
2311 else
2312 log_info (_("NOTE: secondary key is online and stored on card\n"));
2316 return result;
2321 /* Check whether a secret key stub exists for the public key PK. If
2322 not create such a stub key and store it into the secring. If it
2323 exists, add appropriate subkey stubs and update the secring.
2324 Return 0 if the key could be created. */
2326 auto_create_card_key_stub ( const char *serialnostr,
2327 const unsigned char *fpr1,
2328 const unsigned char *fpr2,
2329 const unsigned char *fpr3)
2331 KBNODE pub_keyblock;
2332 KBNODE sec_keyblock;
2333 KEYDB_HANDLE hd;
2334 int rc;
2336 /* We only want to do this for an OpenPGP card. */
2337 if (!serialnostr || strncmp (serialnostr, "D27600012401", 12)
2338 || strlen (serialnostr) != 32 )
2339 return G10ERR_GENERAL;
2341 /* First get the public keyring from any of the provided fingerprints. */
2342 if ( (fpr1 && !get_keyblock_byfprint (&pub_keyblock, fpr1, 20))
2343 || (fpr2 && !get_keyblock_byfprint (&pub_keyblock, fpr2, 20))
2344 || (fpr3 && !get_keyblock_byfprint (&pub_keyblock, fpr3, 20)))
2346 else
2347 return G10ERR_GENERAL;
2349 hd = keydb_new (1);
2351 /* Now check whether there is a secret keyring. */
2353 PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key;
2354 byte afp[MAX_FINGERPRINT_LEN];
2355 size_t an;
2357 fingerprint_from_pk (pk, afp, &an);
2358 if (an < MAX_FINGERPRINT_LEN)
2359 memset (afp+an, 0, MAX_FINGERPRINT_LEN-an);
2360 rc = keydb_search_fpr (hd, afp);
2363 if (!rc)
2365 rc = keydb_get_keyblock (hd, &sec_keyblock);
2366 if (rc)
2368 log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
2369 rc = G10ERR_GENERAL;
2371 else
2373 merge_keys_and_selfsig (sec_keyblock);
2375 /* FIXME: We need to add new subkeys first. */
2376 if (update_sec_keyblock_with_cardinfo (sec_keyblock,
2377 fpr1, fpr2, fpr3,
2378 serialnostr))
2380 rc = keydb_update_keyblock (hd, sec_keyblock );
2381 if (rc)
2382 log_error (_("error writing keyring `%s': %s\n"),
2383 keydb_get_resource_name (hd), g10_errstr(rc) );
2387 else /* A secret key does not exists - create it. */
2389 sec_keyblock = pub_to_sec_keyblock (pub_keyblock);
2390 update_sec_keyblock_with_cardinfo (sec_keyblock,
2391 fpr1, fpr2, fpr3,
2392 serialnostr);
2394 rc = keydb_locate_writable (hd, NULL);
2395 if (rc)
2397 log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
2398 rc = G10ERR_GENERAL;
2400 else
2402 rc = keydb_insert_keyblock (hd, sec_keyblock );
2403 if (rc)
2404 log_error (_("error writing keyring `%s': %s\n"),
2405 keydb_get_resource_name (hd), g10_errstr(rc) );
2409 release_kbnode (sec_keyblock);
2410 release_kbnode (pub_keyblock);
2411 keydb_release (hd);
2412 return rc;