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