Imported Upstream version 2.0.19
[platform/upstream/gpg2.git] / g10 / import.c
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.
4  *
5  * This file is part of GnuPG.
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <assert.h>
27
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"
40
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;
58 };
59
60
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 );
87
88 int
89 parse_import_options(char *str,unsigned int *options,int noisy)
90 {
91   struct parse_options import_opts[]=
92     {
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}
115     };
116
117   return parse_options(str,options,import_opts,noisy);
118 }
119
120 void *
121 import_new_stats_handle (void)
122 {
123     return xmalloc_clear ( sizeof (struct stats_s) );
124 }
125
126 void
127 import_release_stats_handle (void *p)
128 {
129     xfree (p);
130 }
131
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.
137  *
138  * Actually this function does a merge. It works like this:
139  *
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.
159  *
160  *  Key revocation certificates have special handling.
161  *
162  */
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 )
167 {
168     int i, rc = 0;
169     struct stats_s *stats = stats_handle;
170
171     if (!stats)
172         stats = import_new_stats_handle ();
173
174     if (inp) {
175         rc = import( inp, "[stream]", stats, fpr, fpr_len, options);
176     }
177     else {
178         int once = (!fnames && !nnames);
179
180         for(i=0; once || i < nnames; once=0, i++ ) {
181             const char *fname = fnames? fnames[i] : NULL;
182             IOBUF inp2 = iobuf_open(fname);
183             if( !fname )
184                 fname = "[stdin]";
185             if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
186               {
187                 iobuf_close (inp2);
188                 inp2 = NULL;
189                 errno = EPERM;
190               }
191             if( !inp2 )
192                 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
193             else
194               {
195                 rc = import( inp2, fname, stats, fpr, fpr_len, options );
196                 iobuf_close(inp2);
197                 /* Must invalidate that ugly cache to actually close it. */
198                 iobuf_ioctl (NULL, 2, 0, (char*)fname);
199                 if( rc )
200                   log_error("import from `%s' failed: %s\n", fname,
201                             g10_errstr(rc) );
202               }
203         }
204     }
205     if (!stats_handle) {
206         import_print_stats (stats);
207         import_release_stats_handle (stats);
208     }
209
210     /* If no fast import and the trustdb is dirty (i.e. we added a key
211        or userID that had something other than a selfsig, a signature
212        that was other than a selfsig, or any revocation), then
213        update/check the trustdb if the user specified by setting
214        interactive or by not setting no-auto-check-trustdb */
215
216     if(!(options&IMPORT_FAST))
217       trustdb_check_or_update();
218
219     return rc;
220 }
221
222 void
223 import_keys( char **fnames, int nnames,
224              void *stats_handle, unsigned int options )
225 {
226   import_keys_internal(NULL,fnames,nnames,stats_handle,NULL,NULL,options);
227 }
228
229 int
230 import_keys_stream( IOBUF inp, void *stats_handle,
231                     unsigned char **fpr, size_t *fpr_len,unsigned int options )
232 {
233   return import_keys_internal(inp,NULL,0,stats_handle,fpr,fpr_len,options);
234 }
235
236 static int
237 import( IOBUF inp, const char* fname,struct stats_s *stats,
238         unsigned char **fpr,size_t *fpr_len,unsigned int options )
239 {
240     PACKET *pending_pkt = NULL;
241     KBNODE keyblock = NULL;  /* Need to initialize because gcc can't
242                                 grasp the return semantics of
243                                 read_block. */
244     int rc = 0;
245
246     getkey_disable_caches();
247
248     if( !opt.no_armor ) { /* armored reading is not disabled */
249         armor_filter_context_t *afx;
250
251         afx = new_armor_context ();
252         afx->only_keyblocks = 1;
253         push_armor_filter (afx, inp);
254         release_armor_context (afx);
255     }
256
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, 0);
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 );
268         }
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 );
276     }
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));
281
282     return rc;
283 }
284
285
286 void
287 import_print_stats (void *hd)
288 {
289     struct stats_s *stats = hd;
290
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               log_printf ("  (RSA: %lu)", stats->imported_rsa );
302             log_printf ("\n");
303         }
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);
326     }
327
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 );
346     }
347 }
348
349
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.
355  */
356 static int
357 read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root )
358 {
359     int rc;
360     PACKET *pkt;
361     KBNODE root = NULL;
362     int in_cert;
363
364     if( *pending_pkt ) {
365         root = new_kbnode( *pending_pkt );
366         *pending_pkt = NULL;
367         in_cert = 1;
368     }
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;
379             }
380             free_packet( pkt );
381             init_packet(pkt);
382             continue;
383         }
384
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;
392         }
393
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))
398               {
399                 rc = G10ERR_COMPR_ALGO;
400                 goto ready;
401               }
402             else
403               {
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);
407               }
408             free_packet( pkt );
409             init_packet(pkt);
410             break;
411
412           case PKT_RING_TRUST:
413             /* skip those packets */
414             free_packet( pkt );
415             init_packet(pkt);
416             break;
417
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;
424             }
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 );
433             }
434             init_packet(pkt);
435             break;
436         }
437     }
438   ready:
439     if( rc == -1 && root )
440         rc = 0;
441
442     if( rc )
443         release_kbnode( root );
444     else
445         *ret_root = root;
446     free_packet( pkt );
447     xfree( pkt );
448     return rc;
449 }
450
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. */
459
460 static int
461 fix_pks_corruption(KBNODE keyblock)
462 {
463   int changed=0,keycount=0;
464   KBNODE node,last=NULL,sknode=NULL;
465
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)
469     {
470       if(node->pkt->pkttype==PKT_PUBLIC_SUBKEY)
471         {
472           keycount++;
473           if(!sknode)
474             sknode=node;
475         }
476       else if(node->pkt->pkttype==PKT_SIGNATURE &&
477               node->pkt->pkt.signature->sig_class==0x18 &&
478               keycount>=2 && node->next==NULL)
479         {
480           /* We might have the problem, as this key has two subkeys in
481              a row without any intervening packets. */
482
483           /* Sanity check */
484           if(last==NULL)
485             break;
486
487           /* Temporarily attach node to sknode. */
488           node->next=sknode->next;
489           sknode->next=node;
490           last->next=NULL;
491
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))
497             {
498               /* Not a match, so undo the changes. */
499               sknode->next=node->next;
500               last->next=node;
501               node->next=NULL;
502               break;
503             }
504           else
505             {
506               sknode->flag |= 1; /* Mark it good so we don't need to
507                                     check it again */
508               changed=1;
509               break;
510             }
511         }
512       else
513         keycount=0;
514     }
515
516   return changed;
517 }
518
519
520 /* Versions of GnuPG before 1.4.11 and 2.0.16 allowed to import bogus
521    direct key signatures.  A side effect of this was that a later
522    import of the same good direct key signatures was not possible
523    because the cmp_signature check in merge_blocks considered them
524    equal.  Although direct key signatures are now checked during
525    import, there might still be bogus signatures sitting in a keyring.
526    We need to detect and delete them before doing a merge.  This
527    fucntion returns the number of removed sigs.  */
528 static int
529 fix_bad_direct_key_sigs (KBNODE keyblock, u32 *keyid)
530 {
531   gpg_error_t err;
532   KBNODE node;
533   int count = 0;
534
535   for (node = keyblock->next; node; node=node->next)
536     {
537       if (node->pkt->pkttype == PKT_USER_ID)
538         break;
539       if (node->pkt->pkttype == PKT_SIGNATURE
540           && IS_KEY_SIG (node->pkt->pkt.signature))
541         {
542           err = check_key_signature (keyblock, node, NULL);
543           if (err && gpg_err_code (err) != GPG_ERR_PUBKEY_ALGO )
544             {
545               /* If we don't know the error, we can't decide; this is
546                  not a problem because cmp_signature can't compare the
547                  signature either.  */
548               log_info ("key %s: invalid direct key signature removed\n",
549                         keystr (keyid));
550               delete_kbnode (node);
551               count++;
552             }
553         }
554     }
555
556   return count;
557 }
558
559
560 static void
561 print_import_ok (PKT_public_key *pk, PKT_secret_key *sk, unsigned int reason)
562 {
563   byte array[MAX_FINGERPRINT_LEN], *s;
564   char buf[MAX_FINGERPRINT_LEN*2+30], *p;
565   size_t i, n;
566
567   sprintf (buf, "%u ", reason);
568   p = buf + strlen (buf);
569
570   if (pk)
571     fingerprint_from_pk (pk, array, &n);
572   else
573     fingerprint_from_sk (sk, array, &n);
574   s = array;
575   for (i=0; i < n ; i++, s++, p += 2)
576     sprintf (p, "%02X", *s);
577
578   write_status_text (STATUS_IMPORT_OK, buf);
579 }
580
581 static void
582 print_import_check (PKT_public_key * pk, PKT_user_id * id)
583 {
584     char * buf;
585     byte fpr[24];
586     u32 keyid[2];
587     size_t i, pos = 0, n;
588
589     buf = xmalloc (17+41+id->len+32);
590     keyid_from_pk (pk, keyid);
591     sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
592     pos = 17;
593     fingerprint_from_pk (pk, fpr, &n);
594     for (i = 0; i < n; i++, pos += 2)
595         sprintf (buf+pos, "%02X", fpr[i]);
596     strcat (buf, " ");
597     pos += 1;
598     strcat (buf, id->name);
599     write_status_text (STATUS_IMPORT_CHECK, buf);
600     xfree (buf);
601 }
602
603 static void
604 check_prefs_warning(PKT_public_key *pk)
605 {
606   log_info(_("WARNING: key %s contains preferences for unavailable\n"
607              "algorithms on these user IDs:\n"), keystr_from_pk(pk));
608 }
609
610 static void
611 check_prefs(KBNODE keyblock)
612 {
613   KBNODE node;
614   PKT_public_key *pk;
615   int problem=0;
616   
617   merge_keys_and_selfsig(keyblock);
618   pk=keyblock->pkt->pkt.public_key;
619
620   for(node=keyblock;node;node=node->next)
621     {
622       if(node->pkt->pkttype==PKT_USER_ID
623          && node->pkt->pkt.user_id->created
624          && node->pkt->pkt.user_id->prefs)
625         {
626           PKT_user_id *uid=node->pkt->pkt.user_id;
627           prefitem_t *prefs=uid->prefs;
628           char *user=utf8_to_native(uid->name,strlen(uid->name),0);
629
630           for(;prefs->type;prefs++)
631             {
632               char num[10]; /* prefs->value is a byte, so we're over
633                                safe here */
634
635               sprintf(num,"%u",prefs->value);
636
637               if(prefs->type==PREFTYPE_SYM)
638                 {
639                   if (openpgp_cipher_test_algo (prefs->value))
640                     {
641                       const char *algo = 
642                         (openpgp_cipher_test_algo (prefs->value)
643                          ? num 
644                          : openpgp_cipher_algo_name (prefs->value));
645                       if(!problem)
646                         check_prefs_warning(pk);
647                       log_info(_("         \"%s\": preference for cipher"
648                                  " algorithm %s\n"), user, algo);
649                       problem=1;
650                     }
651                 }
652               else if(prefs->type==PREFTYPE_HASH)
653                 {
654                   if(openpgp_md_test_algo(prefs->value))
655                     {
656                       const char *algo =
657                         (gcry_md_test_algo (prefs->value)
658                          ? num 
659                          : gcry_md_algo_name (prefs->value));
660                       if(!problem)
661                         check_prefs_warning(pk);
662                       log_info(_("         \"%s\": preference for digest"
663                                  " algorithm %s\n"), user, algo);
664                       problem=1;
665                     }
666                 }
667               else if(prefs->type==PREFTYPE_ZIP)
668                 {
669                   if(check_compress_algo (prefs->value))
670                     {
671                       const char *algo=compress_algo_to_string(prefs->value);
672                       if(!problem)
673                         check_prefs_warning(pk);
674                       log_info(_("         \"%s\": preference for compression"
675                                  " algorithm %s\n"),user,algo?algo:num);
676                       problem=1;
677                     }
678                 }
679             }
680
681           xfree(user);
682         }
683     }
684
685   if(problem)
686     {
687       log_info(_("it is strongly suggested that you update"
688                  " your preferences and\n"));
689       log_info(_("re-distribute this key to avoid potential algorithm"
690                  " mismatch problems\n"));
691
692       if(!opt.batch)
693         {
694           strlist_t sl=NULL,locusr=NULL;
695           size_t fprlen=0;
696           byte fpr[MAX_FINGERPRINT_LEN],*p;
697           char username[(MAX_FINGERPRINT_LEN*2)+1];
698           unsigned int i;
699
700           p=fingerprint_from_pk(pk,fpr,&fprlen);
701           for(i=0;i<fprlen;i++,p++)
702             sprintf(username+2*i,"%02X",*p);
703           add_to_strlist(&locusr,username);
704
705           append_to_strlist(&sl,"updpref");
706           append_to_strlist(&sl,"save");
707
708           keyedit_menu( username, locusr, sl, 1, 1 );
709           free_strlist(sl);
710           free_strlist(locusr);
711         }
712       else if(!opt.quiet)
713         log_info(_("you can update your preferences with:"
714                    " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
715     }
716 }
717
718 /****************
719  * Try to import one keyblock.  Return an error only in serious cases, but
720  * never for an invalid keyblock.  It uses log_error to increase the
721  * internal errorcount, so that invalid input can be detected by programs
722  * which called gpg.
723  */
724 static int
725 import_one( const char *fname, KBNODE keyblock, struct stats_s *stats,
726             unsigned char **fpr,size_t *fpr_len,unsigned int options,
727             int from_sk )
728 {
729     PKT_public_key *pk;
730     PKT_public_key *pk_orig;
731     KBNODE node, uidnode;
732     KBNODE keyblock_orig = NULL;
733     u32 keyid[2];
734     int rc = 0;
735     int new_key = 0;
736     int mod_key = 0;
737     int same_key = 0;
738     int non_self = 0;
739
740     /* get the key and print some info about it */
741     node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
742     if( !node )
743         BUG();
744
745     pk = node->pkt->pkt.public_key;
746
747     keyid_from_pk( pk, keyid );
748     uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
749
750     if( opt.verbose && !opt.interactive )
751       {
752         log_info( "pub  %4u%c/%s %s  ",
753                   nbits_from_pk( pk ),
754                   pubkey_letter( pk->pubkey_algo ),
755                   keystr_from_pk(pk), datestr_from_pk(pk) );
756         if (uidnode)
757           print_utf8_string (log_get_stream (),
758                              uidnode->pkt->pkt.user_id->name,
759                              uidnode->pkt->pkt.user_id->len );
760         log_printf ("\n");
761       }
762
763
764     if( !uidnode )
765       {
766         log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
767         return 0;
768       }
769     
770     if (opt.interactive) {
771         if(is_status_enabled())
772           print_import_check (pk, uidnode->pkt->pkt.user_id);
773         merge_keys_and_selfsig (keyblock);
774         tty_printf ("\n");
775         show_basic_key_info (keyblock);
776         tty_printf ("\n");
777         if (!cpr_get_answer_is_yes ("import.okay",
778                                     "Do you want to import this key? (y/N) "))
779             return 0;
780     }
781
782     collapse_uids(&keyblock);
783
784     /* Clean the key that we're about to import, to cut down on things
785        that we have to clean later.  This has no practical impact on
786        the end result, but does result in less logging which might
787        confuse the user. */
788     if(options&IMPORT_CLEAN)
789       clean_key(keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL);
790
791     clear_kbnode_flags( keyblock );
792
793     if((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
794        && opt.verbose)
795       log_info(_("key %s: PKS subkey corruption repaired\n"),
796                keystr_from_pk(pk));
797
798     rc = chk_self_sigs( fname, keyblock , pk, keyid, &non_self );
799     if( rc )
800         return rc== -1? 0:rc;
801
802     /* If we allow such a thing, mark unsigned uids as valid */
803     if( opt.allow_non_selfsigned_uid )
804       for( node=keyblock; node; node = node->next )
805         if( node->pkt->pkttype == PKT_USER_ID && !(node->flag & 1) )
806           {
807             char *user=utf8_to_native(node->pkt->pkt.user_id->name,
808                                       node->pkt->pkt.user_id->len,0);
809             node->flag |= 1;
810             log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
811                       keystr_from_pk(pk),user);
812             xfree(user);
813           }
814
815     if( !delete_inv_parts( fname, keyblock, keyid, options ) ) {
816         log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
817         if( !opt.quiet )
818           log_info(_("this may be caused by a missing self-signature\n"));
819         stats->no_user_id++;
820         return 0;
821     }
822
823     /* do we have this key already in one of our pubrings ? */
824     pk_orig = xmalloc_clear( sizeof *pk_orig );
825     rc = get_pubkey_fast ( pk_orig, keyid );
826     if( rc && rc != G10ERR_NO_PUBKEY && rc != G10ERR_UNU_PUBKEY )
827       {
828         log_error( _("key %s: public key not found: %s\n"),
829                    keystr(keyid), g10_errstr(rc));
830       }
831     else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) )
832       {
833         if( opt.verbose )
834           log_info( _("key %s: new key - skipped\n"), keystr(keyid));
835         rc = 0;
836         stats->skipped_new_keys++;
837       }
838     else if( rc ) { /* insert this key */
839         KEYDB_HANDLE hd = keydb_new (0);
840
841         rc = keydb_locate_writable (hd, NULL);
842         if (rc) {
843             log_error (_("no writable keyring found: %s\n"), g10_errstr (rc));
844             keydb_release (hd);
845             return G10ERR_GENERAL;
846         }
847         if( opt.verbose > 1 )
848             log_info (_("writing to `%s'\n"), keydb_get_resource_name (hd) );
849
850         rc = keydb_insert_keyblock (hd, keyblock );
851         if (rc)
852            log_error (_("error writing keyring `%s': %s\n"),
853                        keydb_get_resource_name (hd), g10_errstr(rc));
854         else
855           {
856             /* This should not be possible since we delete the
857                ownertrust when a key is deleted, but it can happen if
858                the keyring and trustdb are out of sync.  It can also
859                be made to happen with the trusted-key command. */
860
861             clear_ownertrusts (pk);
862             if(non_self)
863               revalidation_mark ();
864           }
865         keydb_release (hd);
866
867         /* we are ready */
868         if( !opt.quiet )
869           {
870             char *p=get_user_id_native (keyid);
871             log_info( _("key %s: public key \"%s\" imported\n"),
872                       keystr(keyid),p);
873             xfree(p);
874           }
875         if( is_status_enabled() )
876           {
877             char *us = get_long_user_id_string( keyid );
878             write_status_text( STATUS_IMPORTED, us );
879             xfree(us);
880             print_import_ok (pk,NULL, 1);
881           }
882         stats->imported++;
883         if( is_RSA( pk->pubkey_algo ) )
884             stats->imported_rsa++;
885         new_key = 1;
886     }
887     else { /* merge */
888         KEYDB_HANDLE hd;
889         int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
890
891         /* Compare the original against the new key; just to be sure nothing
892          * weird is going on */
893         if( cmp_public_keys( pk_orig, pk ) )
894           {
895             log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
896             goto leave;
897           }
898
899         /* now read the original keyblock */
900         hd = keydb_new (0);
901         {
902             byte afp[MAX_FINGERPRINT_LEN];
903             size_t an;
904
905             fingerprint_from_pk (pk_orig, afp, &an);
906             while (an < MAX_FINGERPRINT_LEN) 
907                 afp[an++] = 0;
908             rc = keydb_search_fpr (hd, afp);
909         }
910         if( rc )
911           {
912             log_error (_("key %s: can't locate original keyblock: %s\n"),
913                        keystr(keyid), g10_errstr(rc));
914             keydb_release (hd);
915             goto leave;
916           }
917         rc = keydb_get_keyblock (hd, &keyblock_orig );
918         if (rc)
919           {
920             log_error (_("key %s: can't read original keyblock: %s\n"),
921                        keystr(keyid), g10_errstr(rc));
922             keydb_release (hd);
923             goto leave;
924           }
925
926         /* Make sure the original direct key sigs are all sane.  */
927         n_sigs_cleaned = fix_bad_direct_key_sigs (keyblock_orig, keyid);
928         if (n_sigs_cleaned)
929           commit_kbnode (&keyblock_orig);
930             
931         /* and try to merge the block */
932         clear_kbnode_flags( keyblock_orig );
933         clear_kbnode_flags( keyblock );
934         n_uids = n_sigs = n_subk = n_uids_cleaned = 0;
935         rc = merge_blocks( fname, keyblock_orig, keyblock,
936                            keyid, &n_uids, &n_sigs, &n_subk );
937         if( rc )
938           {
939             keydb_release (hd);
940             goto leave;
941           }
942
943         if(options&IMPORT_CLEAN)
944           clean_key(keyblock_orig,opt.verbose,options&IMPORT_MINIMAL,
945                     &n_uids_cleaned,&n_sigs_cleaned);
946
947         if( n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned) {
948             mod_key = 1;
949             /* keyblock_orig has been updated; write */
950             rc = keydb_update_keyblock (hd, keyblock_orig);
951             if (rc)
952                 log_error (_("error writing keyring `%s': %s\n"),
953                              keydb_get_resource_name (hd), g10_errstr(rc) );
954             else if(non_self)
955               revalidation_mark ();
956
957             /* we are ready */
958             if( !opt.quiet )
959               {
960                 char *p=get_user_id_native(keyid);
961                 if( n_uids == 1 )
962                   log_info( _("key %s: \"%s\" 1 new user ID\n"),
963                            keystr(keyid),p);
964                 else if( n_uids )
965                   log_info( _("key %s: \"%s\" %d new user IDs\n"),
966                             keystr(keyid),p,n_uids);
967                 if( n_sigs == 1 )
968                   log_info( _("key %s: \"%s\" 1 new signature\n"),
969                             keystr(keyid), p);
970                 else if( n_sigs )
971                   log_info( _("key %s: \"%s\" %d new signatures\n"),
972                             keystr(keyid), p, n_sigs );
973                 if( n_subk == 1 )
974                   log_info( _("key %s: \"%s\" 1 new subkey\n"),
975                             keystr(keyid), p);
976                 else if( n_subk )
977                   log_info( _("key %s: \"%s\" %d new subkeys\n"),
978                             keystr(keyid), p, n_subk );
979                 if(n_sigs_cleaned==1)
980                   log_info(_("key %s: \"%s\" %d signature cleaned\n"),
981                            keystr(keyid),p,n_sigs_cleaned);
982                 else if(n_sigs_cleaned)
983                   log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
984                            keystr(keyid),p,n_sigs_cleaned);
985                 if(n_uids_cleaned==1)
986                   log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
987                            keystr(keyid),p,n_uids_cleaned);
988                 else if(n_uids_cleaned)
989                   log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
990                            keystr(keyid),p,n_uids_cleaned);
991                 xfree(p);
992               }
993
994             stats->n_uids +=n_uids;
995             stats->n_sigs +=n_sigs;
996             stats->n_subk +=n_subk;
997             stats->n_sigs_cleaned +=n_sigs_cleaned;
998             stats->n_uids_cleaned +=n_uids_cleaned;
999
1000             if (is_status_enabled ()) 
1001                  print_import_ok (pk, NULL,
1002                                   ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
1003         }
1004         else
1005           {
1006             same_key = 1;
1007             if (is_status_enabled ()) 
1008               print_import_ok (pk, NULL, 0);
1009
1010             if( !opt.quiet )
1011               {
1012                 char *p=get_user_id_native(keyid);
1013                 log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
1014                 xfree(p);
1015               }
1016
1017             stats->unchanged++;
1018           }
1019
1020         keydb_release (hd); hd = NULL;
1021     }
1022
1023   leave:
1024     if (mod_key || new_key || same_key)
1025       {
1026         /* A little explanation for this: we fill in the fingerprint
1027            when importing keys as it can be useful to know the
1028            fingerprint in certain keyserver-related cases (a keyserver
1029            asked for a particular name, but the key doesn't have that
1030            name).  However, in cases where we're importing more than
1031            one key at a time, we cannot know which key to fingerprint.
1032            In these cases, rather than guessing, we do not
1033            fingerprinting at all, and we must hope the user ID on the
1034            keys are useful.  Note that we need to do this for new
1035            keys, merged keys and even for unchanged keys.  This is
1036            required because for example the --auto-key-locate feature
1037            may import an already imported key and needs to know the
1038            fingerprint of the key in all cases.  */
1039         if (fpr)
1040           {
1041             xfree (*fpr);
1042             /* Note that we need to compare against 0 here because
1043                COUNT gets only incremented after returning form this
1044                function.  */
1045             if (stats->count == 0)
1046               *fpr = fingerprint_from_pk (pk, NULL, fpr_len);
1047             else
1048               *fpr = NULL;
1049           }
1050       }
1051
1052     /* Now that the key is definitely incorporated into the keydb, we
1053        need to check if a designated revocation is present or if the
1054        prefs are not rational so we can warn the user. */
1055
1056     if(mod_key)
1057       {
1058         revocation_present(keyblock_orig);
1059         if(!from_sk && seckey_available(keyid)==0)
1060           check_prefs(keyblock_orig);
1061       }
1062     else if(new_key)
1063       {
1064         revocation_present(keyblock);
1065         if(!from_sk && seckey_available(keyid)==0)
1066           check_prefs(keyblock);
1067       }
1068
1069     release_kbnode( keyblock_orig );
1070     free_public_key( pk_orig );
1071
1072     return rc;
1073 }
1074
1075 /* Walk a secret keyblock and produce a public keyblock out of it. */
1076 static KBNODE
1077 sec_to_pub_keyblock(KBNODE sec_keyblock)
1078 {
1079   KBNODE secnode,pub_keyblock=NULL,ctx=NULL;
1080
1081   while((secnode=walk_kbnode(sec_keyblock,&ctx,0)))
1082     {
1083       KBNODE pubnode;
1084
1085       if(secnode->pkt->pkttype==PKT_SECRET_KEY ||
1086          secnode->pkt->pkttype==PKT_SECRET_SUBKEY)
1087         {
1088           /* Make a public key.  We only need to convert enough to
1089              write the keyblock out. */
1090
1091           PKT_secret_key *sk=secnode->pkt->pkt.secret_key;
1092           PACKET *pkt=xmalloc_clear(sizeof(PACKET));
1093           PKT_public_key *pk=xmalloc_clear(sizeof(PKT_public_key));
1094           int n;
1095
1096           if(secnode->pkt->pkttype==PKT_SECRET_KEY)
1097             pkt->pkttype=PKT_PUBLIC_KEY;
1098           else
1099             pkt->pkttype=PKT_PUBLIC_SUBKEY;
1100
1101           pkt->pkt.public_key=pk;
1102
1103           pk->version=sk->version;
1104           pk->timestamp=sk->timestamp;
1105           pk->expiredate=sk->expiredate;
1106           pk->pubkey_algo=sk->pubkey_algo;
1107
1108           n=pubkey_get_npkey(pk->pubkey_algo);
1109           if(n==0)
1110             {
1111               /* we can't properly extract the pubkey without knowing
1112                  the number of MPIs */
1113               release_kbnode(pub_keyblock);
1114               return NULL;
1115             }
1116           else
1117             {
1118               int i;
1119
1120               for(i=0;i<n;i++)
1121                 pk->pkey[i]=mpi_copy(sk->skey[i]);
1122             }
1123
1124           pubnode=new_kbnode(pkt);
1125         }
1126       else
1127         {
1128           pubnode=clone_kbnode(secnode);
1129         }
1130
1131       if(pub_keyblock==NULL)
1132         pub_keyblock=pubnode;
1133       else
1134         add_kbnode(pub_keyblock,pubnode);
1135     }
1136
1137   return pub_keyblock;
1138 }
1139
1140 /****************
1141  * Ditto for secret keys.  Handling is simpler than for public keys.
1142  * We allow secret key importing only when allow is true, this is so
1143  * that a secret key can not be imported accidently and thereby tampering
1144  * with the trust calculation.
1145  */
1146 static int
1147 import_secret_one( const char *fname, KBNODE keyblock, 
1148                    struct stats_s *stats, unsigned int options)
1149 {
1150     PKT_secret_key *sk;
1151     KBNODE node, uidnode;
1152     u32 keyid[2];
1153     int rc = 0;
1154
1155     /* get the key and print some info about it */
1156     node = find_kbnode( keyblock, PKT_SECRET_KEY );
1157     if( !node )
1158         BUG();
1159
1160     sk = node->pkt->pkt.secret_key;
1161     keyid_from_sk( sk, keyid );
1162     uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
1163
1164     if( opt.verbose )
1165       {
1166         log_info( "sec  %4u%c/%s %s   ",
1167                   nbits_from_sk( sk ),
1168                   pubkey_letter( sk->pubkey_algo ),
1169                   keystr_from_sk(sk), datestr_from_sk(sk) );
1170         if( uidnode )
1171           print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
1172                              uidnode->pkt->pkt.user_id->len );
1173         log_printf ("\n");
1174       }
1175     stats->secret_read++;
1176
1177     if( !uidnode )
1178       {
1179         log_error( _("key %s: no user ID\n"), keystr_from_sk(sk));
1180         return 0;
1181       }
1182
1183     if(sk->protect.algo>110)
1184       {
1185         log_error(_("key %s: secret key with invalid cipher %d"
1186                     " - skipped\n"),keystr_from_sk(sk),sk->protect.algo);
1187         return 0;
1188       }
1189
1190 #ifdef ENABLE_SELINUX_HACKS
1191     if (1)
1192       {
1193         /* We don't allow to import secret keys because that may be used
1194            to put a secret key into the keyring and the user might later
1195            be tricked into signing stuff with that key.  */
1196         log_error (_("importing secret keys not allowed\n"));
1197         return 0;
1198       }
1199 #endif 
1200     
1201     clear_kbnode_flags( keyblock );
1202
1203     /* do we have this key already in one of our secrings ? */
1204     rc = seckey_available( keyid );
1205     if( rc == G10ERR_NO_SECKEY && !(opt.import_options&IMPORT_MERGE_ONLY) )
1206       {
1207         /* simply insert this key */
1208         KEYDB_HANDLE hd = keydb_new (1);
1209
1210         /* get default resource */
1211         rc = keydb_locate_writable (hd, NULL);
1212         if (rc) {
1213           log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
1214           keydb_release (hd);
1215           return G10ERR_GENERAL;
1216         }
1217         rc = keydb_insert_keyblock (hd, keyblock );
1218         if (rc)
1219           log_error (_("error writing keyring `%s': %s\n"),
1220                      keydb_get_resource_name (hd), g10_errstr(rc) );
1221         keydb_release (hd);
1222         /* we are ready */
1223         if( !opt.quiet )
1224           log_info( _("key %s: secret key imported\n"), keystr_from_sk(sk));
1225         stats->secret_imported++;
1226         if (is_status_enabled ()) 
1227           print_import_ok (NULL, sk, 1|16);
1228
1229         if(options&IMPORT_SK2PK)
1230           {
1231             /* Try and make a public key out of this. */
1232
1233             KBNODE pub_keyblock=sec_to_pub_keyblock(keyblock);
1234             if(pub_keyblock)
1235               {
1236                 import_one(fname,pub_keyblock,stats,
1237                            NULL,NULL,opt.import_options,1);
1238                 release_kbnode(pub_keyblock);
1239               }
1240           }
1241
1242         /* Now that the key is definitely incorporated into the keydb,
1243            if we have the public part of this key, we need to check if
1244            the prefs are rational. */
1245         node=get_pubkeyblock(keyid);
1246         if(node)
1247           {
1248             check_prefs(node);
1249             release_kbnode(node);
1250           }
1251       }
1252     else if( !rc )
1253       { /* we can't merge secret keys */
1254         log_error( _("key %s: already in secret keyring\n"),
1255                    keystr_from_sk(sk));
1256         stats->secret_dups++;
1257         if (is_status_enabled ()) 
1258           print_import_ok (NULL, sk, 16);
1259
1260         /* TODO: if we ever do merge secret keys, make sure to handle
1261            the sec_to_pub_keyblock feature as well. */
1262       }
1263     else
1264       log_error( _("key %s: secret key not found: %s\n"),
1265                  keystr_from_sk(sk), g10_errstr(rc));
1266
1267     return rc;
1268 }
1269
1270
1271 /****************
1272  * Import a revocation certificate; this is a single signature packet.
1273  */
1274 static int
1275 import_revoke_cert( const char *fname, KBNODE node, struct stats_s *stats )
1276 {
1277     PKT_public_key *pk=NULL;
1278     KBNODE onode, keyblock = NULL;
1279     KEYDB_HANDLE hd = NULL;
1280     u32 keyid[2];
1281     int rc = 0;
1282
1283     (void)fname;
1284
1285     assert( !node->next );
1286     assert( node->pkt->pkttype == PKT_SIGNATURE );
1287     assert( node->pkt->pkt.signature->sig_class == 0x20 );
1288
1289     keyid[0] = node->pkt->pkt.signature->keyid[0];
1290     keyid[1] = node->pkt->pkt.signature->keyid[1];
1291
1292     pk = xmalloc_clear( sizeof *pk );
1293     rc = get_pubkey( pk, keyid );
1294     if( rc == G10ERR_NO_PUBKEY )
1295       {
1296         log_error(_("key %s: no public key -"
1297                     " can't apply revocation certificate\n"), keystr(keyid));
1298         rc = 0;
1299         goto leave;
1300       }
1301     else if( rc )
1302       {
1303         log_error(_("key %s: public key not found: %s\n"),
1304                   keystr(keyid), g10_errstr(rc));
1305         goto leave;
1306       }
1307
1308     /* read the original keyblock */
1309     hd = keydb_new (0);
1310     {
1311         byte afp[MAX_FINGERPRINT_LEN];
1312         size_t an;
1313         
1314         fingerprint_from_pk (pk, afp, &an);
1315         while (an < MAX_FINGERPRINT_LEN) 
1316             afp[an++] = 0;
1317         rc = keydb_search_fpr (hd, afp);
1318     }
1319     if (rc)
1320       {
1321         log_error (_("key %s: can't locate original keyblock: %s\n"),
1322                    keystr(keyid), g10_errstr(rc));
1323         goto leave;
1324       }
1325     rc = keydb_get_keyblock (hd, &keyblock );
1326     if (rc)
1327       {
1328         log_error (_("key %s: can't read original keyblock: %s\n"),
1329                    keystr(keyid), g10_errstr(rc));
1330         goto leave;
1331       }
1332
1333     /* it is okay, that node is not in keyblock because
1334      * check_key_signature works fine for sig_class 0x20 in this
1335      * special case. */
1336     rc = check_key_signature( keyblock, node, NULL);
1337     if( rc )
1338       {
1339         log_error( _("key %s: invalid revocation certificate"
1340                      ": %s - rejected\n"), keystr(keyid), g10_errstr(rc));
1341         goto leave;
1342       }
1343
1344     /* check whether we already have this */
1345     for(onode=keyblock->next; onode; onode=onode->next ) {
1346         if( onode->pkt->pkttype == PKT_USER_ID )
1347             break;
1348         else if( onode->pkt->pkttype == PKT_SIGNATURE
1349                  && !cmp_signatures(node->pkt->pkt.signature,
1350                                     onode->pkt->pkt.signature))
1351           {
1352             rc = 0;
1353             goto leave; /* yes, we already know about it */
1354           }
1355     }
1356
1357
1358     /* insert it */
1359     insert_kbnode( keyblock, clone_kbnode(node), 0 );
1360
1361     /* and write the keyblock back */
1362     rc = keydb_update_keyblock (hd, keyblock );
1363     if (rc)
1364         log_error (_("error writing keyring `%s': %s\n"),
1365                    keydb_get_resource_name (hd), g10_errstr(rc) );
1366     keydb_release (hd); hd = NULL;
1367     /* we are ready */
1368     if( !opt.quiet )
1369       {
1370         char *p=get_user_id_native (keyid);
1371         log_info( _("key %s: \"%s\" revocation certificate imported\n"),
1372                   keystr(keyid),p);
1373         xfree(p);
1374       }
1375     stats->n_revoc++;
1376
1377     /* If the key we just revoked was ultimately trusted, remove its
1378        ultimate trust.  This doesn't stop the user from putting the
1379        ultimate trust back, but is a reasonable solution for now. */
1380     if(get_ownertrust(pk)==TRUST_ULTIMATE)
1381       clear_ownertrusts(pk);
1382
1383     revalidation_mark ();
1384
1385   leave:
1386     keydb_release (hd);
1387     release_kbnode( keyblock );
1388     free_public_key( pk );
1389     return rc;
1390 }
1391
1392
1393 /*
1394  * Loop over the keyblock and check all self signatures.
1395  * Mark all user-ids with a self-signature by setting flag bit 0.
1396  * Mark all user-ids with an invalid self-signature by setting bit 1.
1397  * This works also for subkeys, here the subkey is marked.  Invalid or
1398  * extra subkey sigs (binding or revocation) are marked for deletion.
1399  * non_self is set to true if there are any sigs other than self-sigs
1400  * in this keyblock.
1401  */
1402 static int
1403 chk_self_sigs( const char *fname, KBNODE keyblock,
1404                PKT_public_key *pk, u32 *keyid, int *non_self )
1405 {
1406   KBNODE n, knode = NULL;
1407   PKT_signature *sig;
1408   int rc;
1409   u32 bsdate=0,rsdate=0;
1410   KBNODE bsnode = NULL, rsnode = NULL;
1411   
1412   (void)fname;
1413   (void)pk;
1414
1415   for (n=keyblock; (n = find_next_kbnode (n, 0)); ) 
1416     {
1417       if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1418         {
1419           knode = n;
1420           bsdate = 0;
1421           rsdate = 0;
1422           bsnode = NULL;
1423           rsnode = NULL;
1424           continue;
1425         }
1426
1427       if ( n->pkt->pkttype != PKT_SIGNATURE )
1428         continue;
1429       
1430       sig = n->pkt->pkt.signature;
1431       if ( keyid[0] != sig->keyid[0] || keyid[1] != sig->keyid[1] )
1432         {
1433           *non_self = 1;
1434           continue;
1435         }
1436
1437       /* This just caches the sigs for later use.  That way we
1438          import a fully-cached key which speeds things up. */
1439       if (!opt.no_sig_cache)
1440         check_key_signature (keyblock, n, NULL);
1441       
1442       if ( IS_UID_SIG(sig) || IS_UID_REV(sig) )
1443         {
1444           KBNODE unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
1445           if ( !unode )
1446             {
1447               log_error( _("key %s: no user ID for signature\n"),
1448                          keystr(keyid));
1449               return -1;  /* The complete keyblock is invalid.  */
1450             }
1451           
1452           /* If it hasn't been marked valid yet, keep trying.  */
1453           if (!(unode->flag&1)) 
1454             {
1455               rc = check_key_signature (keyblock, n, NULL);
1456               if ( rc )
1457                 {
1458                   if ( opt.verbose )
1459                     {
1460                       char *p = utf8_to_native 
1461                         (unode->pkt->pkt.user_id->name,
1462                          strlen (unode->pkt->pkt.user_id->name),0);
1463                       log_info (gpg_err_code(rc) == G10ERR_PUBKEY_ALGO ?
1464                                 _("key %s: unsupported public key "
1465                                   "algorithm on user ID \"%s\"\n"):
1466                                 _("key %s: invalid self-signature "
1467                                   "on user ID \"%s\"\n"),
1468                                 keystr (keyid),p);
1469                       xfree (p);
1470                     }
1471                 }
1472               else
1473                 unode->flag |= 1; /* Mark that signature checked. */
1474             }
1475         }
1476       else if (IS_KEY_SIG (sig))
1477         {
1478           rc = check_key_signature (keyblock, n, NULL);
1479           if ( rc )
1480             {
1481               if (opt.verbose)
1482                 log_info (gpg_err_code (rc) == G10ERR_PUBKEY_ALGO ?
1483                           _("key %s: unsupported public key algorithm\n"):
1484                           _("key %s: invalid direct key signature\n"),
1485                           keystr (keyid));
1486               n->flag |= 4;
1487             }
1488         }
1489       else if ( IS_SUBKEY_SIG (sig) ) 
1490         {
1491           /* Note that this works based solely on the timestamps like
1492              the rest of gpg.  If the standard gets revocation
1493              targets, this may need to be revised.  */
1494
1495           if ( !knode )
1496             {
1497               if (opt.verbose)
1498                 log_info (_("key %s: no subkey for key binding\n"),
1499                           keystr (keyid));
1500               n->flag |= 4; /* delete this */
1501             }
1502           else
1503             {
1504               rc = check_key_signature (keyblock, n, NULL);
1505               if ( rc )
1506                 {
1507                   if (opt.verbose)
1508                     log_info (gpg_err_code (rc) == G10ERR_PUBKEY_ALGO ?
1509                               _("key %s: unsupported public key"
1510                                 " algorithm\n"):
1511                               _("key %s: invalid subkey binding\n"),
1512                               keystr (keyid));
1513                   n->flag |= 4;
1514                 }
1515               else
1516                 {
1517                   /* It's valid, so is it newer? */
1518                   if (sig->timestamp >= bsdate) 
1519                     {
1520                       knode->flag |= 1;  /* The subkey is valid.  */
1521                       if (bsnode)
1522                         {
1523                           /* Delete the last binding sig since this
1524                              one is newer */
1525                           bsnode->flag |= 4; 
1526                           if (opt.verbose)
1527                             log_info (_("key %s: removed multiple subkey"
1528                                         " binding\n"),keystr(keyid));
1529                         }
1530                       
1531                       bsnode = n;
1532                       bsdate = sig->timestamp;
1533                     }
1534                   else
1535                     n->flag |= 4; /* older */
1536                 }
1537             }
1538         }
1539       else if ( IS_SUBKEY_REV (sig) )
1540         {
1541           /* We don't actually mark the subkey as revoked right now,
1542              so just check that the revocation sig is the most recent
1543              valid one.  Note that we don't care if the binding sig is
1544              newer than the revocation sig.  See the comment in
1545              getkey.c:merge_selfsigs_subkey for more.  */
1546           if ( !knode )
1547             {
1548               if (opt.verbose)
1549                 log_info (_("key %s: no subkey for key revocation\n"),
1550                           keystr(keyid));
1551               n->flag |= 4; /* delete this */
1552             }
1553           else
1554             {
1555               rc = check_key_signature (keyblock, n, NULL);
1556               if ( rc )
1557                 {
1558                   if(opt.verbose)
1559                     log_info (gpg_err_code (rc) == G10ERR_PUBKEY_ALGO ?
1560                               _("key %s: unsupported public"
1561                                 " key algorithm\n"):
1562                               _("key %s: invalid subkey revocation\n"),
1563                               keystr(keyid));
1564                   n->flag |= 4;
1565                 }
1566               else
1567                 {
1568                   /* It's valid, so is it newer? */
1569                   if (sig->timestamp >= rsdate)
1570                     {
1571                       if (rsnode)
1572                         {
1573                           /* Delete the last revocation sig since
1574                              this one is newer.  */
1575                           rsnode->flag |= 4; 
1576                           if (opt.verbose)
1577                             log_info (_("key %s: removed multiple subkey"
1578                                         " revocation\n"),keystr(keyid));
1579                         }
1580                       
1581                       rsnode = n;
1582                       rsdate = sig->timestamp;
1583                     }
1584                   else
1585                     n->flag |= 4; /* older */
1586                 }
1587             }
1588         }
1589     }
1590
1591   return 0;
1592 }
1593
1594 /****************
1595  * delete all parts which are invalid and those signatures whose
1596  * public key algorithm is not available in this implemenation;
1597  * but consider RSA as valid, because parse/build_packets knows
1598  * about it.
1599  * returns: true if at least one valid user-id is left over.
1600  */
1601 static int
1602 delete_inv_parts( const char *fname, KBNODE keyblock,
1603                   u32 *keyid, unsigned int options)
1604 {
1605     KBNODE node;
1606     int nvalid=0, uid_seen=0, subkey_seen=0;
1607
1608     (void)fname;
1609
1610     for(node=keyblock->next; node; node = node->next ) {
1611         if( node->pkt->pkttype == PKT_USER_ID ) {
1612             uid_seen = 1;
1613             if( (node->flag & 2) || !(node->flag & 1) ) {
1614                 if( opt.verbose )
1615                   {
1616                     char *p=utf8_to_native(node->pkt->pkt.user_id->name,
1617                                            node->pkt->pkt.user_id->len,0);
1618                     log_info( _("key %s: skipped user ID \"%s\"\n"),
1619                               keystr(keyid),p);
1620                     xfree(p);
1621                   }
1622                 delete_kbnode( node ); /* the user-id */
1623                 /* and all following packets up to the next user-id */
1624                 while( node->next
1625                        && node->next->pkt->pkttype != PKT_USER_ID
1626                        && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1627                        && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
1628                     delete_kbnode( node->next );
1629                     node = node->next;
1630                 }
1631             }
1632             else
1633                 nvalid++;
1634         }
1635         else if(    node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1636                  || node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1637             if( (node->flag & 2) || !(node->flag & 1) ) {
1638                 if( opt.verbose )
1639                   log_info( _("key %s: skipped subkey\n"),keystr(keyid));
1640
1641                 delete_kbnode( node ); /* the subkey */
1642                 /* and all following signature packets */
1643                 while( node->next
1644                        && node->next->pkt->pkttype == PKT_SIGNATURE ) {
1645                     delete_kbnode( node->next );
1646                     node = node->next;
1647                 }
1648             }
1649             else
1650               subkey_seen = 1;
1651         }
1652         else if (node->pkt->pkttype == PKT_SIGNATURE
1653                 && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
1654                 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
1655             delete_kbnode( node ); /* build_packet() can't handle this */
1656         else if( node->pkt->pkttype == PKT_SIGNATURE &&
1657                  !node->pkt->pkt.signature->flags.exportable &&
1658                  !(options&IMPORT_LOCAL_SIGS) &&
1659                  seckey_available( node->pkt->pkt.signature->keyid ) )
1660           {
1661             /* here we violate the rfc a bit by still allowing
1662              * to import non-exportable signature when we have the
1663              * the secret key used to create this signature - it
1664              * seems that this makes sense */
1665             if(opt.verbose)
1666               log_info( _("key %s: non exportable signature"
1667                           " (class 0x%02X) - skipped\n"),
1668                         keystr(keyid), node->pkt->pkt.signature->sig_class );
1669             delete_kbnode( node );
1670           }
1671         else if( node->pkt->pkttype == PKT_SIGNATURE
1672                  && node->pkt->pkt.signature->sig_class == 0x20 )  {
1673             if( uid_seen )
1674               {
1675                 if(opt.verbose)
1676                   log_info( _("key %s: revocation certificate"
1677                               " at wrong place - skipped\n"),keystr(keyid));
1678                 delete_kbnode( node );
1679               }
1680             else {
1681               /* If the revocation cert is from a different key than
1682                  the one we're working on don't check it - it's
1683                  probably from a revocation key and won't be
1684                  verifiable with this key anyway. */
1685
1686               if(node->pkt->pkt.signature->keyid[0]==keyid[0] &&
1687                  node->pkt->pkt.signature->keyid[1]==keyid[1])
1688                 {
1689                   int rc = check_key_signature( keyblock, node, NULL);
1690                   if( rc )
1691                     {
1692                       if(opt.verbose)
1693                         log_info( _("key %s: invalid revocation"
1694                                     " certificate: %s - skipped\n"),
1695                                   keystr(keyid), g10_errstr(rc));
1696                       delete_kbnode( node );
1697                     }
1698                 }
1699             }
1700         }
1701         else if( node->pkt->pkttype == PKT_SIGNATURE &&
1702                  (node->pkt->pkt.signature->sig_class == 0x18 ||
1703                   node->pkt->pkt.signature->sig_class == 0x28) &&
1704                  !subkey_seen )
1705           {
1706             if(opt.verbose)
1707               log_info( _("key %s: subkey signature"
1708                           " in wrong place - skipped\n"), keystr(keyid));
1709             delete_kbnode( node );
1710           }
1711         else if( node->pkt->pkttype == PKT_SIGNATURE
1712                  && !IS_CERT(node->pkt->pkt.signature))
1713           {
1714             if(opt.verbose)
1715               log_info(_("key %s: unexpected signature class (0x%02X) -"
1716                          " skipped\n"),keystr(keyid),
1717                        node->pkt->pkt.signature->sig_class);
1718             delete_kbnode(node);
1719           }
1720         else if( (node->flag & 4) ) /* marked for deletion */
1721           delete_kbnode( node );
1722     }
1723
1724     /* note: because keyblock is the public key, it is never marked
1725      * for deletion and so keyblock cannot change */
1726     commit_kbnode( &keyblock );
1727     return nvalid;
1728 }
1729
1730
1731 /****************
1732  * It may happen that the imported keyblock has duplicated user IDs.
1733  * We check this here and collapse those user IDs together with their
1734  * sigs into one.
1735  * Returns: True if the keyblock has changed.
1736  */
1737 int
1738 collapse_uids( KBNODE *keyblock )
1739 {
1740   KBNODE uid1;
1741   int any=0;
1742
1743   for(uid1=*keyblock;uid1;uid1=uid1->next)
1744     {
1745       KBNODE uid2;
1746
1747       if(is_deleted_kbnode(uid1))
1748         continue;
1749
1750       if(uid1->pkt->pkttype!=PKT_USER_ID)
1751         continue;
1752
1753       for(uid2=uid1->next;uid2;uid2=uid2->next)
1754         {
1755           if(is_deleted_kbnode(uid2))
1756             continue;
1757
1758           if(uid2->pkt->pkttype!=PKT_USER_ID)
1759             continue;
1760
1761           if(cmp_user_ids(uid1->pkt->pkt.user_id,
1762                           uid2->pkt->pkt.user_id)==0)
1763             {
1764               /* We have a duplicated uid */
1765               KBNODE sig1,last;
1766
1767               any=1;
1768
1769               /* Now take uid2's signatures, and attach them to
1770                  uid1 */
1771               for(last=uid2;last->next;last=last->next)
1772                 {
1773                   if(is_deleted_kbnode(last))
1774                     continue;
1775
1776                   if(last->next->pkt->pkttype==PKT_USER_ID
1777                      || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
1778                      || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
1779                     break;
1780                 }
1781
1782               /* Snip out uid2 */
1783               (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
1784
1785               /* Now put uid2 in place as part of uid1 */
1786               last->next=uid1->next;
1787               uid1->next=uid2;
1788               delete_kbnode(uid2);
1789
1790               /* Now dedupe uid1 */
1791               for(sig1=uid1->next;sig1;sig1=sig1->next)
1792                 {
1793                   KBNODE sig2;
1794
1795                   if(is_deleted_kbnode(sig1))
1796                     continue;
1797
1798                   if(sig1->pkt->pkttype==PKT_USER_ID
1799                      || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
1800                      || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
1801                     break;
1802
1803                   if(sig1->pkt->pkttype!=PKT_SIGNATURE)
1804                     continue;
1805
1806                   for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
1807                     {
1808                       if(is_deleted_kbnode(sig2))
1809                         continue;
1810
1811                       if(sig2->pkt->pkttype==PKT_USER_ID
1812                          || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
1813                          || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
1814                         break;
1815
1816                       if(sig2->pkt->pkttype!=PKT_SIGNATURE)
1817                         continue;
1818
1819                       if(cmp_signatures(sig1->pkt->pkt.signature,
1820                                         sig2->pkt->pkt.signature)==0)
1821                         {
1822                           /* We have a match, so delete the second
1823                              signature */
1824                           delete_kbnode(sig2);
1825                           sig2=last;
1826                         }
1827                     }
1828                 }
1829             }
1830         }
1831     }
1832
1833   commit_kbnode(keyblock);
1834
1835   if(any && !opt.quiet)
1836     {
1837       const char *key="???";
1838
1839       if( (uid1=find_kbnode( *keyblock, PKT_PUBLIC_KEY )) )
1840         key=keystr_from_pk(uid1->pkt->pkt.public_key);
1841       else if( (uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY )) )
1842         key=keystr_from_sk(uid1->pkt->pkt.secret_key);
1843
1844       log_info(_("key %s: duplicated user ID detected - merged\n"),key);
1845     }
1846
1847   return any;
1848 }
1849
1850 /* Check for a 0x20 revocation from a revocation key that is not
1851    present.  This may be called without the benefit of merge_xxxx so
1852    you can't rely on pk->revkey and friends. */
1853 static void
1854 revocation_present(KBNODE keyblock)
1855 {
1856   KBNODE onode,inode;
1857   PKT_public_key *pk=keyblock->pkt->pkt.public_key;
1858
1859   for(onode=keyblock->next;onode;onode=onode->next)
1860     {
1861       /* If we reach user IDs, we're done. */
1862       if(onode->pkt->pkttype==PKT_USER_ID)
1863         break;
1864
1865       if(onode->pkt->pkttype==PKT_SIGNATURE &&
1866          onode->pkt->pkt.signature->sig_class==0x1F &&
1867          onode->pkt->pkt.signature->revkey)
1868         {
1869           int idx;
1870           PKT_signature *sig=onode->pkt->pkt.signature;
1871
1872           for(idx=0;idx<sig->numrevkeys;idx++)
1873             {
1874               u32 keyid[2];
1875
1876               keyid_from_fingerprint(sig->revkey[idx]->fpr,
1877                                      MAX_FINGERPRINT_LEN,keyid);
1878
1879               for(inode=keyblock->next;inode;inode=inode->next)
1880                 {
1881                   /* If we reach user IDs, we're done. */
1882                   if(inode->pkt->pkttype==PKT_USER_ID)
1883                     break;
1884
1885                   if(inode->pkt->pkttype==PKT_SIGNATURE &&
1886                      inode->pkt->pkt.signature->sig_class==0x20 &&
1887                      inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
1888                      inode->pkt->pkt.signature->keyid[1]==keyid[1])
1889                     {
1890                       /* Okay, we have a revocation key, and a
1891                          revocation issued by it.  Do we have the key
1892                          itself? */
1893                       int rc;
1894
1895                       rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx]->fpr,
1896                                                    MAX_FINGERPRINT_LEN);
1897                       if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1898                         {
1899                           char *tempkeystr=xstrdup(keystr_from_pk(pk));
1900
1901                           /* No, so try and get it */
1902                           if(opt.keyserver
1903                              && (opt.keyserver_options.options
1904                                  & KEYSERVER_AUTO_KEY_RETRIEVE))
1905                             {
1906                               log_info(_("WARNING: key %s may be revoked:"
1907                                          " fetching revocation key %s\n"),
1908                                        tempkeystr,keystr(keyid));
1909                               keyserver_import_fprint(sig->revkey[idx]->fpr,
1910                                                       MAX_FINGERPRINT_LEN,
1911                                                       opt.keyserver);
1912
1913                               /* Do we have it now? */
1914                               rc=get_pubkey_byfprint_fast (NULL,
1915                                                      sig->revkey[idx]->fpr,
1916                                                      MAX_FINGERPRINT_LEN);
1917                             }
1918
1919                           if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY)
1920                             log_info(_("WARNING: key %s may be revoked:"
1921                                        " revocation key %s not present.\n"),
1922                                      tempkeystr,keystr(keyid));
1923
1924                           xfree(tempkeystr);
1925                         }
1926                     }
1927                 }
1928             }
1929         }
1930     }
1931 }
1932
1933 /****************
1934  * compare and merge the blocks
1935  *
1936  * o compare the signatures: If we already have this signature, check
1937  *   that they compare okay; if not, issue a warning and ask the user.
1938  * o Simply add the signature.  Can't verify here because we may not have
1939  *   the signature's public key yet; verification is done when putting it
1940  *   into the trustdb, which is done automagically as soon as this pubkey
1941  *   is used.
1942  * Note: We indicate newly inserted packets with flag bit 0
1943  */
1944 static int
1945 merge_blocks( const char *fname, KBNODE keyblock_orig, KBNODE keyblock,
1946               u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
1947 {
1948     KBNODE onode, node;
1949     int rc, found;
1950
1951     /* 1st: handle revocation certificates */
1952     for(node=keyblock->next; node; node=node->next ) {
1953         if( node->pkt->pkttype == PKT_USER_ID )
1954             break;
1955         else if( node->pkt->pkttype == PKT_SIGNATURE
1956                  && node->pkt->pkt.signature->sig_class == 0x20 )  {
1957             /* check whether we already have this */
1958             found = 0;
1959             for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1960                 if( onode->pkt->pkttype == PKT_USER_ID )
1961                     break;
1962                 else if( onode->pkt->pkttype == PKT_SIGNATURE
1963                          && onode->pkt->pkt.signature->sig_class == 0x20
1964                          && !cmp_signatures(onode->pkt->pkt.signature,
1965                                             node->pkt->pkt.signature))
1966                   {
1967                     found = 1;
1968                     break;
1969                   }
1970             }
1971             if( !found ) {
1972                 KBNODE n2 = clone_kbnode(node);
1973                 insert_kbnode( keyblock_orig, n2, 0 );
1974                 n2->flag |= 1;
1975                 ++*n_sigs;
1976                 if(!opt.quiet)
1977                   {
1978                     char *p=get_user_id_native (keyid);
1979                     log_info(_("key %s: \"%s\" revocation"
1980                                " certificate added\n"), keystr(keyid),p);
1981                     xfree(p);
1982                   }
1983             }
1984         }
1985     }
1986
1987     /* 2nd: merge in any direct key (0x1F) sigs */
1988     for(node=keyblock->next; node; node=node->next ) {
1989         if( node->pkt->pkttype == PKT_USER_ID )
1990             break;
1991         else if( node->pkt->pkttype == PKT_SIGNATURE
1992                  && node->pkt->pkt.signature->sig_class == 0x1F )  {
1993             /* check whether we already have this */
1994             found = 0;
1995             for(onode=keyblock_orig->next; onode; onode=onode->next ) {
1996                 if( onode->pkt->pkttype == PKT_USER_ID )
1997                     break;
1998                 else if( onode->pkt->pkttype == PKT_SIGNATURE
1999                          && onode->pkt->pkt.signature->sig_class == 0x1F
2000                          && !cmp_signatures(onode->pkt->pkt.signature,
2001                                             node->pkt->pkt.signature)) {
2002                     found = 1;
2003                     break;
2004                 }
2005             }
2006             if( !found )
2007               {
2008                 KBNODE n2 = clone_kbnode(node);
2009                 insert_kbnode( keyblock_orig, n2, 0 );
2010                 n2->flag |= 1;
2011                 ++*n_sigs;
2012                 if(!opt.quiet)
2013                   log_info( _("key %s: direct key signature added\n"),
2014                             keystr(keyid));
2015               }
2016         }
2017     }
2018
2019     /* 3rd: try to merge new certificates in */
2020     for(onode=keyblock_orig->next; onode; onode=onode->next ) {
2021         if( !(onode->flag & 1) && onode->pkt->pkttype == PKT_USER_ID) {
2022             /* find the user id in the imported keyblock */
2023             for(node=keyblock->next; node; node=node->next )
2024                 if( node->pkt->pkttype == PKT_USER_ID
2025                     && !cmp_user_ids( onode->pkt->pkt.user_id,
2026                                           node->pkt->pkt.user_id ) )
2027                     break;
2028             if( node ) { /* found: merge */
2029                 rc = merge_sigs( onode, node, n_sigs, fname, keyid );
2030                 if( rc )
2031                     return rc;
2032             }
2033         }
2034     }
2035
2036     /* 4th: add new user-ids */
2037     for(node=keyblock->next; node; node=node->next ) {
2038         if( node->pkt->pkttype == PKT_USER_ID) {
2039             /* do we have this in the original keyblock */
2040             for(onode=keyblock_orig->next; onode; onode=onode->next )
2041                 if( onode->pkt->pkttype == PKT_USER_ID
2042                     && !cmp_user_ids( onode->pkt->pkt.user_id,
2043                                       node->pkt->pkt.user_id ) )
2044                     break;
2045             if( !onode ) { /* this is a new user id: append */
2046                 rc = append_uid( keyblock_orig, node, n_sigs, fname, keyid);
2047                 if( rc )
2048                     return rc;
2049                 ++*n_uids;
2050             }
2051         }
2052     }
2053
2054     /* 5th: add new subkeys */
2055     for(node=keyblock->next; node; node=node->next ) {
2056         onode = NULL;
2057         if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2058             /* do we have this in the original keyblock? */
2059             for(onode=keyblock_orig->next; onode; onode=onode->next )
2060                 if( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
2061                     && !cmp_public_keys( onode->pkt->pkt.public_key,
2062                                          node->pkt->pkt.public_key ) )
2063                     break;
2064             if( !onode ) { /* this is a new subkey: append */
2065                 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
2066                 if( rc )
2067                     return rc;
2068                 ++*n_subk;
2069             }
2070         }
2071         else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2072             /* do we have this in the original keyblock? */
2073             for(onode=keyblock_orig->next; onode; onode=onode->next )
2074                 if( onode->pkt->pkttype == PKT_SECRET_SUBKEY
2075                     && !cmp_secret_keys( onode->pkt->pkt.secret_key,
2076                                          node->pkt->pkt.secret_key ) )
2077                     break;
2078             if( !onode ) { /* this is a new subkey: append */
2079                 rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
2080                 if( rc )
2081                     return rc;
2082                 ++*n_subk;
2083             }
2084         }
2085     }
2086
2087     /* 6th: merge subkey certificates */
2088     for(onode=keyblock_orig->next; onode; onode=onode->next ) {
2089         if( !(onode->flag & 1)
2090             &&  (   onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
2091                  || onode->pkt->pkttype == PKT_SECRET_SUBKEY) ) {
2092             /* find the subkey in the imported keyblock */
2093             for(node=keyblock->next; node; node=node->next ) {
2094                 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2095                     && !cmp_public_keys( onode->pkt->pkt.public_key,
2096                                           node->pkt->pkt.public_key ) )
2097                     break;
2098                 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY
2099                     && !cmp_secret_keys( onode->pkt->pkt.secret_key,
2100                                           node->pkt->pkt.secret_key ) )
2101                     break;
2102             }
2103             if( node ) { /* found: merge */
2104                 rc = merge_keysigs( onode, node, n_sigs, fname, keyid );
2105                 if( rc )
2106                     return rc;
2107             }
2108         }
2109     }
2110
2111
2112     return 0;
2113 }
2114
2115
2116 /****************
2117  * append the userid starting with NODE and all signatures to KEYBLOCK.
2118  */
2119 static int
2120 append_uid (KBNODE keyblock, KBNODE node, int *n_sigs,
2121             const char *fname, u32 *keyid )
2122 {
2123     KBNODE n, n_where=NULL;
2124
2125     (void)fname;
2126     (void)keyid;
2127
2128     assert(node->pkt->pkttype == PKT_USER_ID );
2129
2130     /* find the position */
2131     for( n = keyblock; n; n_where = n, n = n->next ) {
2132         if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2133             || n->pkt->pkttype == PKT_SECRET_SUBKEY )
2134             break;
2135     }
2136     if( !n )
2137         n_where = NULL;
2138
2139     /* and append/insert */
2140     while( node ) {
2141         /* we add a clone to the original keyblock, because this
2142          * one is released first */
2143         n = clone_kbnode(node);
2144         if( n_where ) {
2145             insert_kbnode( n_where, n, 0 );
2146             n_where = n;
2147         }
2148         else
2149             add_kbnode( keyblock, n );
2150         n->flag |= 1;
2151         node->flag |= 1;
2152         if( n->pkt->pkttype == PKT_SIGNATURE )
2153             ++*n_sigs;
2154
2155         node = node->next;
2156         if( node && node->pkt->pkttype != PKT_SIGNATURE )
2157             break;
2158     }
2159
2160     return 0;
2161 }
2162
2163
2164 /****************
2165  * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
2166  * (how should we handle comment packets here?)
2167  */
2168 static int
2169 merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
2170                                     const char *fname, u32 *keyid )
2171 {
2172     KBNODE n, n2;
2173     int found=0;
2174
2175     (void)fname;
2176     (void)keyid;
2177
2178     assert(dst->pkt->pkttype == PKT_USER_ID );
2179     assert(src->pkt->pkttype == PKT_USER_ID );
2180
2181     for(n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next ) {
2182         if( n->pkt->pkttype != PKT_SIGNATURE )
2183             continue;
2184         if( n->pkt->pkt.signature->sig_class == 0x18
2185             || n->pkt->pkt.signature->sig_class == 0x28 )
2186             continue; /* skip signatures which are only valid on subkeys */
2187         found = 0;
2188         for(n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
2189           if(!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
2190             {
2191               found++;
2192               break;
2193             }
2194         if( !found ) {
2195             /* This signature is new or newer, append N to DST.
2196              * We add a clone to the original keyblock, because this
2197              * one is released first */
2198             n2 = clone_kbnode(n);
2199             insert_kbnode( dst, n2, PKT_SIGNATURE );
2200             n2->flag |= 1;
2201             n->flag |= 1;
2202             ++*n_sigs;
2203         }
2204     }
2205
2206     return 0;
2207 }
2208
2209 /****************
2210  * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
2211  */
2212 static int
2213 merge_keysigs (KBNODE dst, KBNODE src, int *n_sigs,
2214                const char *fname, u32 *keyid)
2215 {
2216     KBNODE n, n2;
2217     int found=0;
2218
2219     (void)fname;
2220     (void)keyid;
2221
2222     assert(   dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
2223            || dst->pkt->pkttype == PKT_SECRET_SUBKEY );
2224
2225     for(n=src->next; n ; n = n->next ) {
2226         if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
2227             || n->pkt->pkttype == PKT_PUBLIC_KEY )
2228             break;
2229         if( n->pkt->pkttype != PKT_SIGNATURE )
2230             continue;
2231         found = 0;
2232         for(n2=dst->next; n2; n2 = n2->next){
2233             if( n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
2234                 || n2->pkt->pkttype == PKT_PUBLIC_KEY )
2235                 break;
2236             if( n2->pkt->pkttype == PKT_SIGNATURE
2237                 && n->pkt->pkt.signature->keyid[0]
2238                    == n2->pkt->pkt.signature->keyid[0]
2239                 && n->pkt->pkt.signature->keyid[1]
2240                    == n2->pkt->pkt.signature->keyid[1]
2241                 && n->pkt->pkt.signature->timestamp
2242                    <= n2->pkt->pkt.signature->timestamp
2243                 && n->pkt->pkt.signature->sig_class
2244                    == n2->pkt->pkt.signature->sig_class ) {
2245                 found++;
2246                 break;
2247             }
2248         }
2249         if( !found ) {
2250             /* This signature is new or newer, append N to DST.
2251              * We add a clone to the original keyblock, because this
2252              * one is released first */
2253             n2 = clone_kbnode(n);
2254             insert_kbnode( dst, n2, PKT_SIGNATURE );
2255             n2->flag |= 1;
2256             n->flag |= 1;
2257             ++*n_sigs;
2258         }
2259     }
2260
2261     return 0;
2262 }
2263
2264 /****************
2265  * append the subkey starting with NODE and all signatures to KEYBLOCK.
2266  * Mark all new and copied packets by setting flag bit 0.
2267  */
2268 static int
2269 append_key (KBNODE keyblock, KBNODE node, int *n_sigs,
2270             const char *fname, u32 *keyid)
2271 {
2272     KBNODE n;
2273
2274     (void)fname;
2275     (void)keyid;
2276
2277     assert( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2278            || node->pkt->pkttype == PKT_SECRET_SUBKEY );
2279
2280     while(  node ) {
2281         /* we add a clone to the original keyblock, because this
2282          * one is released first */
2283         n = clone_kbnode(node);
2284         add_kbnode( keyblock, n );
2285         n->flag |= 1;
2286         node->flag |= 1;
2287         if( n->pkt->pkttype == PKT_SIGNATURE )
2288             ++*n_sigs;
2289
2290         node = node->next;
2291         if( node && node->pkt->pkttype != PKT_SIGNATURE )
2292             break;
2293     }
2294
2295     return 0;
2296 }
2297
2298
2299
2300 /* Walk a public keyblock and produce a secret keyblock out of it.
2301    Instead of inserting the secret key parameters (which we don't
2302    have), we insert a stub.  */
2303 static KBNODE
2304 pub_to_sec_keyblock (KBNODE pub_keyblock)
2305 {
2306   KBNODE pubnode, secnode;
2307   KBNODE sec_keyblock = NULL;
2308   KBNODE walkctx = NULL;
2309
2310   while((pubnode = walk_kbnode (pub_keyblock,&walkctx,0)))
2311     {
2312       if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY
2313           || pubnode->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2314         {
2315           /* Make a secret key.  We only need to convert enough to
2316              write the keyblock out. */
2317           PKT_public_key *pk = pubnode->pkt->pkt.public_key;
2318           PACKET *pkt = xmalloc_clear (sizeof *pkt);
2319           PKT_secret_key *sk = xmalloc_clear (sizeof *sk);
2320           int i, n;
2321           
2322           if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY)
2323             pkt->pkttype = PKT_SECRET_KEY;
2324           else
2325             pkt->pkttype = PKT_SECRET_SUBKEY;
2326           
2327           pkt->pkt.secret_key = sk;
2328
2329           copy_public_parts_to_secret_key ( pk, sk );
2330           sk->version     = pk->version;
2331           sk->timestamp   = pk->timestamp;
2332         
2333           n = pubkey_get_npkey (pk->pubkey_algo);
2334           if (!n)
2335             n = 1; /* Unknown number of parameters, however the data
2336                       is stored in the first mpi. */
2337           for (i=0; i < n; i++ )
2338             sk->skey[i] = mpi_copy (pk->pkey[i]);
2339   
2340           sk->is_protected = 1;
2341           sk->protect.s2k.mode = 1001;
2342   
2343           secnode = new_kbnode (pkt);
2344         }
2345       else
2346         {
2347           secnode = clone_kbnode (pubnode);
2348         }
2349       
2350       if(!sec_keyblock)
2351         sec_keyblock = secnode;
2352       else
2353         add_kbnode (sec_keyblock, secnode);
2354     }
2355
2356   return sec_keyblock;
2357 }
2358
2359
2360 /* Walk over the secret keyring SEC_KEYBLOCK and update any simple
2361    stub keys with the serial number SNNUM of the card if one of the
2362    fingerprints FPR1, FPR2 or FPR3 match.  Print a note if the key is
2363    a duplicate (may happen in case of backed uped keys). 
2364    
2365    Returns: True if anything changed.
2366 */
2367 static int
2368 update_sec_keyblock_with_cardinfo (KBNODE sec_keyblock, 
2369                                    const unsigned char *fpr1,
2370                                    const unsigned char *fpr2,
2371                                    const unsigned char *fpr3,
2372                                    const char *serialnostr)
2373 {
2374   KBNODE node;
2375   KBNODE walkctx = NULL;
2376   PKT_secret_key *sk;
2377   byte array[MAX_FINGERPRINT_LEN];
2378   size_t n;
2379   int result = 0;
2380   const char *s;
2381
2382   while((node = walk_kbnode (sec_keyblock, &walkctx, 0)))
2383     {
2384       if (node->pkt->pkttype != PKT_SECRET_KEY
2385           && node->pkt->pkttype != PKT_SECRET_SUBKEY)
2386         continue;
2387       sk = node->pkt->pkt.secret_key;
2388       
2389       fingerprint_from_sk (sk, array, &n);
2390       if (n != 20)
2391         continue; /* Can't be a card key.  */
2392       if ( !((fpr1 && !memcmp (array, fpr1, 20))
2393              || (fpr2 && !memcmp (array, fpr2, 20))
2394              || (fpr3 && !memcmp (array, fpr3, 20))) )
2395         continue;  /* No match.  */
2396
2397       if (sk->is_protected == 1 && sk->protect.s2k.mode == 1001)
2398         {
2399           /* Standard case: migrate that stub to a key stub.  */
2400           sk->protect.s2k.mode = 1002;
2401           s = serialnostr;
2402           for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2403                sk->protect.ivlen++, s += 2)
2404             sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
2405           result = 1;
2406         }
2407       else if (sk->is_protected == 1 && sk->protect.s2k.mode == 1002)
2408         {
2409           s = serialnostr;
2410           for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2411                sk->protect.ivlen++, s += 2)
2412             if (sk->protect.iv[sk->protect.ivlen] != xtoi_2 (s))
2413               {
2414                 log_info (_("NOTE: a key's S/N does not "
2415                             "match the card's one\n"));
2416                 break;
2417               }
2418         }
2419       else
2420         {
2421           if (node->pkt->pkttype != PKT_SECRET_KEY)
2422             log_info (_("NOTE: primary key is online and stored on card\n"));
2423           else
2424             log_info (_("NOTE: secondary key is online and stored on card\n"));
2425         }
2426     }
2427
2428   return result;
2429 }
2430
2431
2432
2433 /* Check whether a secret key stub exists for the public key PK.  If
2434    not create such a stub key and store it into the secring.  If it
2435    exists, add appropriate subkey stubs and update the secring.
2436    Return 0 if the key could be created. */
2437 int
2438 auto_create_card_key_stub ( const char *serialnostr, 
2439                             const unsigned char *fpr1,
2440                             const unsigned char *fpr2,
2441                             const unsigned char *fpr3)
2442 {
2443   KBNODE pub_keyblock;
2444   KBNODE sec_keyblock;
2445   KEYDB_HANDLE hd;
2446   int rc;
2447
2448   /* We only want to do this for an OpenPGP card.  */
2449   if (!serialnostr || strncmp (serialnostr, "D27600012401", 12) 
2450       || strlen (serialnostr) != 32 )
2451     return G10ERR_GENERAL;
2452
2453   /* First get the public keyring from any of the provided fingerprints. */
2454   if ( (fpr1 && !get_keyblock_byfprint (&pub_keyblock, fpr1, 20))
2455        || (fpr2 && !get_keyblock_byfprint (&pub_keyblock, fpr2, 20))
2456        || (fpr3 && !get_keyblock_byfprint (&pub_keyblock, fpr3, 20)))
2457     ;
2458   else
2459     return G10ERR_GENERAL;
2460  
2461   hd = keydb_new (1);
2462
2463   /* Now check whether there is a secret keyring.  */
2464   {
2465     PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key;
2466     byte afp[MAX_FINGERPRINT_LEN];
2467     size_t an;
2468
2469     fingerprint_from_pk (pk, afp, &an);
2470     if (an < MAX_FINGERPRINT_LEN)
2471       memset (afp+an, 0, MAX_FINGERPRINT_LEN-an);
2472     rc = keydb_search_fpr (hd, afp);
2473   }
2474
2475   if (!rc)
2476     {
2477       rc = keydb_get_keyblock (hd, &sec_keyblock);
2478       if (rc)
2479         {
2480           log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
2481           rc = G10ERR_GENERAL;
2482         }
2483       else
2484         {
2485           merge_keys_and_selfsig (sec_keyblock);
2486           
2487           /* FIXME: We need to add new subkeys first.  */
2488           if (update_sec_keyblock_with_cardinfo (sec_keyblock,
2489                                                  fpr1, fpr2, fpr3,
2490                                                  serialnostr))
2491             {
2492               rc = keydb_update_keyblock (hd, sec_keyblock );
2493               if (rc)
2494                 log_error (_("error writing keyring `%s': %s\n"),
2495                            keydb_get_resource_name (hd), g10_errstr(rc) );
2496             }
2497         }
2498     }
2499   else  /* A secret key does not exists - create it.  */
2500     {
2501       sec_keyblock = pub_to_sec_keyblock (pub_keyblock);
2502       update_sec_keyblock_with_cardinfo (sec_keyblock,
2503                                          fpr1, fpr2, fpr3,
2504                                          serialnostr);
2505
2506       rc = keydb_locate_writable (hd, NULL);
2507       if (rc)
2508         {
2509           log_error (_("no default secret keyring: %s\n"), g10_errstr (rc));
2510           rc = G10ERR_GENERAL;
2511         }
2512       else
2513         {
2514           rc = keydb_insert_keyblock (hd, sec_keyblock );
2515           if (rc)
2516             log_error (_("error writing keyring `%s': %s\n"),
2517                        keydb_get_resource_name (hd), g10_errstr(rc) );
2518         }
2519     }
2520     
2521   release_kbnode (sec_keyblock);
2522   release_kbnode (pub_keyblock);
2523   keydb_release (hd);
2524   return rc;
2525 }