Imported Upstream version 2.2.9
[platform/upstream/gpg2.git] / g10 / mainproc.c
1 /* mainproc.c - handle packets
2  * Copyright (C) 1998-2009 Free Software Foundation, Inc.
3  * Copyright (C) 2013-2014 Werner Koch
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 <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <time.h>
26
27 #include "gpg.h"
28 #include "../common/util.h"
29 #include "packet.h"
30 #include "../common/iobuf.h"
31 #include "options.h"
32 #include "keydb.h"
33 #include "filter.h"
34 #include "main.h"
35 #include "../common/status.h"
36 #include "../common/i18n.h"
37 #include "trustdb.h"
38 #include "keyserver-internal.h"
39 #include "photoid.h"
40 #include "../common/mbox-util.h"
41 #include "call-dirmngr.h"
42 #include "../common/compliance.h"
43
44 /* Put an upper limit on nested packets.  The 32 is an arbitrary
45    value, a much lower should actually be sufficient.  */
46 #define MAX_NESTING_DEPTH 32
47
48
49 /* An object to build a list of keyid related info.  */
50 struct kidlist_item
51 {
52   struct kidlist_item *next;
53   u32 kid[2];
54   int pubkey_algo;
55   int reason;
56 };
57
58
59 /*
60  * Object to hold the processing context.
61  */
62 typedef struct mainproc_context *CTX;
63 struct mainproc_context
64 {
65   ctrl_t ctrl;
66   struct mainproc_context *anchor;  /* May be useful in the future. */
67   PKT_public_key *last_pubkey;
68   PKT_user_id     *last_user_id;
69   md_filter_context_t mfx;
70   int sigs_only;    /* Process only signatures and reject all other stuff. */
71   int encrypt_only; /* Process only encryption messages. */
72
73   /* Name of the file with the complete signature or the file with the
74      detached signature.  This is currently only used to deduce the
75      file name of the data file if that has not been given. */
76   const char *sigfilename;
77
78   /* A structure to describe the signed data in case of a detached
79      signature. */
80   struct
81   {
82     /* A file descriptor of the signed data.  Only used if not -1. */
83     int data_fd;
84     /* A list of filenames with the data files or NULL. This is only
85        used if DATA_FD is -1. */
86     strlist_t data_names;
87     /* Flag to indicated that either one of the next previous fields
88        is used.  This is only needed for better readability. */
89     int used;
90   } signed_data;
91
92   DEK *dek;
93   int last_was_session_key;
94   kbnode_t list;    /* The current list of packets. */
95   iobuf_t iobuf;    /* Used to get the filename etc. */
96   int trustletter;  /* Temporary usage in list_node. */
97   ulong symkeys;    /* Number of symmetrically encrypted session keys.  */
98   struct kidlist_item *pkenc_list; /* List of encryption packets. */
99   struct {
100     unsigned int sig_seen:1;      /* Set to true if a signature packet
101                                      has been seen. */
102     unsigned int data:1;          /* Any data packet seen */
103     unsigned int uncompress_failed:1;
104   } any;
105 };
106
107
108 /* Counter with the number of literal data packets seen.  Note that
109  * this is also bumped at the end of an encryption.  This counter is
110  * used for a basic consistency check of a received PGP message.  */
111 static int literals_seen;
112
113
114 /*** Local prototypes.  ***/
115 static int do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a);
116 static void list_node (CTX c, kbnode_t node);
117 static void proc_tree (CTX c, kbnode_t node);
118
119
120 /*** Functions.  ***/
121
122 /* Reset the literal data counter.  This is required to setup a new
123  * decryption or verification context.  */
124 void
125 reset_literals_seen(void)
126 {
127   literals_seen = 0;
128 }
129
130
131 static void
132 release_list( CTX c )
133 {
134   proc_tree (c, c->list);
135   release_kbnode (c->list);
136   while (c->pkenc_list)
137     {
138       struct kidlist_item *tmp = c->pkenc_list->next;
139       xfree (c->pkenc_list);
140       c->pkenc_list = tmp;
141     }
142   c->pkenc_list = NULL;
143   c->list = NULL;
144   c->any.data = 0;
145   c->any.uncompress_failed = 0;
146   c->last_was_session_key = 0;
147   xfree (c->dek);
148   c->dek = NULL;
149 }
150
151
152 static int
153 add_onepass_sig (CTX c, PACKET *pkt)
154 {
155   kbnode_t node;
156
157   if (c->list) /* Add another packet. */
158     add_kbnode (c->list, new_kbnode (pkt));
159   else /* Insert the first one.  */
160     c->list = node = new_kbnode (pkt);
161
162   return 1;
163 }
164
165
166 static int
167 add_gpg_control (CTX c, PACKET *pkt)
168 {
169   if ( pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
170     {
171       /* New clear text signature.
172        * Process the last one and reset everything */
173       release_list(c);
174     }
175
176   if (c->list)  /* Add another packet.  */
177     add_kbnode (c->list, new_kbnode (pkt));
178   else /* Insert the first one. */
179     c->list = new_kbnode (pkt);
180
181   return 1;
182 }
183
184
185 static int
186 add_user_id (CTX c, PACKET *pkt)
187 {
188   if (!c->list)
189     {
190       log_error ("orphaned user ID\n");
191       return 0;
192     }
193   add_kbnode (c->list, new_kbnode (pkt));
194   return 1;
195 }
196
197
198 static int
199 add_subkey (CTX c, PACKET *pkt)
200 {
201   if (!c->list)
202     {
203       log_error ("subkey w/o mainkey\n");
204       return 0;
205     }
206   add_kbnode (c->list, new_kbnode (pkt));
207   return 1;
208 }
209
210
211 static int
212 add_ring_trust (CTX c, PACKET *pkt)
213 {
214   if (!c->list)
215     {
216       log_error ("ring trust w/o key\n");
217       return 0;
218     }
219   add_kbnode (c->list, new_kbnode (pkt));
220   return 1;
221 }
222
223
224 static int
225 add_signature (CTX c, PACKET *pkt)
226 {
227   kbnode_t node;
228
229   c->any.sig_seen = 1;
230   if (pkt->pkttype == PKT_SIGNATURE && !c->list)
231     {
232       /* This is the first signature for the following datafile.
233        * GPG does not write such packets; instead it always uses
234        * onepass-sig packets.  The drawback of PGP's method
235        * of prepending the signature to the data is
236        * that it is not possible to make a signature from data read
237        * from stdin.    (GPG is able to read PGP stuff anyway.) */
238       node = new_kbnode (pkt);
239       c->list = node;
240       return 1;
241     }
242   else if (!c->list)
243     return 0; /* oops (invalid packet sequence)*/
244   else if (!c->list->pkt)
245     BUG();    /* so nicht */
246
247   /* Add a new signature node item at the end. */
248   node = new_kbnode (pkt);
249   add_kbnode (c->list, node);
250
251   return 1;
252 }
253
254 static int
255 symkey_decrypt_seskey (DEK *dek, byte *seskey, size_t slen)
256 {
257   gcry_cipher_hd_t hd;
258
259   if(slen < 17 || slen > 33)
260     {
261       log_error ( _("weird size for an encrypted session key (%d)\n"),
262                   (int)slen);
263       return GPG_ERR_BAD_KEY;
264     }
265
266   if (openpgp_cipher_open (&hd, dek->algo, GCRY_CIPHER_MODE_CFB, 1))
267       BUG ();
268   if (gcry_cipher_setkey ( hd, dek->key, dek->keylen ))
269     BUG ();
270   gcry_cipher_setiv ( hd, NULL, 0 );
271   gcry_cipher_decrypt ( hd, seskey, slen, NULL, 0 );
272   gcry_cipher_close ( hd );
273
274   /* Here we can only test whether the algo given in decrypted
275    * session key is a valid OpenPGP algo.  With 11 defined
276    * symmetric algorithms we will miss 4.3% of wrong passphrases
277    * here.  The actual checking is done later during bulk
278    * decryption; we can't bring this check forward easily.  */
279   if (openpgp_cipher_test_algo (seskey[0]))
280     return gpg_error (GPG_ERR_BAD_KEY);
281
282   /* Now we replace the dek components with the real session key to
283      decrypt the contents of the sequencing packet. */
284
285   dek->keylen=slen-1;
286   dek->algo=seskey[0];
287
288   if(dek->keylen > DIM(dek->key))
289     BUG ();
290
291   memcpy(dek->key, seskey + 1, dek->keylen);
292
293   /*log_hexdump( "thekey", dek->key, dek->keylen );*/
294
295   return 0;
296 }
297
298
299 static void
300 proc_symkey_enc (CTX c, PACKET *pkt)
301 {
302   PKT_symkey_enc *enc;
303
304   enc = pkt->pkt.symkey_enc;
305   if (!enc)
306     log_error ("invalid symkey encrypted packet\n");
307   else if(!c->dek)
308     {
309       int algo = enc->cipher_algo;
310       const char *s = openpgp_cipher_algo_name (algo);
311
312       if (!openpgp_cipher_test_algo (algo))
313         {
314           if (!opt.quiet)
315             {
316               if (enc->seskeylen)
317                 log_info (_("%s encrypted session key\n"), s );
318               else
319                 log_info (_("%s encrypted data\n"), s );
320             }
321         }
322       else
323         log_error (_("encrypted with unknown algorithm %d\n"), algo);
324
325       if (openpgp_md_test_algo (enc->s2k.hash_algo))
326         {
327           log_error(_("passphrase generated with unknown digest"
328                       " algorithm %d\n"),enc->s2k.hash_algo);
329           s = NULL;
330         }
331
332       c->last_was_session_key = 2;
333       if (!s || opt.list_only)
334         goto leave;
335
336       if (opt.override_session_key)
337         {
338           c->dek = xmalloc_clear (sizeof *c->dek);
339           if (get_override_session_key (c->dek, opt.override_session_key))
340             {
341               xfree (c->dek);
342               c->dek = NULL;
343             }
344         }
345       else
346         {
347           c->dek = passphrase_to_dek (algo, &enc->s2k, 0, 0, NULL, NULL);
348           if (c->dek)
349             {
350               c->dek->symmetric = 1;
351
352               /* FIXME: This doesn't work perfectly if a symmetric key
353                  comes before a public key in the message - if the
354                  user doesn't know the passphrase, then there is a
355                  chance that the "decrypted" algorithm will happen to
356                  be a valid one, which will make the returned dek
357                  appear valid, so we won't try any public keys that
358                  come later. */
359               if (enc->seskeylen)
360                 {
361                   if (symkey_decrypt_seskey (c->dek,
362                                              enc->seskey, enc->seskeylen))
363                     {
364                       if (c->dek->s2k_cacheid[0])
365                         {
366                           if (opt.debug)
367                             log_debug ("cleared passphrase cached with ID:"
368                                        " %s\n", c->dek->s2k_cacheid);
369                           passphrase_clear_cache (c->dek->s2k_cacheid);
370                         }
371                       xfree (c->dek);
372                       c->dek = NULL;
373                     }
374                 }
375               else
376                 c->dek->algo_info_printed = 1;
377             }
378         }
379     }
380
381  leave:
382   c->symkeys++;
383   free_packet (pkt, NULL);
384 }
385
386
387 static void
388 proc_pubkey_enc (ctrl_t ctrl, CTX c, PACKET *pkt)
389 {
390   PKT_pubkey_enc *enc;
391   int result = 0;
392
393   /* Check whether the secret key is available and store in this case.  */
394   c->last_was_session_key = 1;
395   enc = pkt->pkt.pubkey_enc;
396   /*printf("enc: encrypted by a pubkey with keyid %08lX\n", enc->keyid[1] );*/
397   /* Hmmm: why do I have this algo check here - anyway there is
398    * function to check it. */
399   if (opt.verbose)
400     log_info (_("public key is %s\n"), keystr (enc->keyid));
401
402   if (is_status_enabled())
403     {
404       char buf[50];
405       /* FIXME: For ECC support we need to map the OpenPGP algo number
406          to the Libgcrypt defined one.  This is due a chicken-egg
407          problem: We need to have code in Libgcrypt for a new
408          algorithm so to implement a proposed new algorithm before the
409          IANA will finally assign an OpenPGP identifier.  */
410       snprintf (buf, sizeof buf, "%08lX%08lX %d 0",
411                 (ulong)enc->keyid[0], (ulong)enc->keyid[1], enc->pubkey_algo);
412       write_status_text (STATUS_ENC_TO, buf);
413     }
414
415   if (!opt.list_only && opt.override_session_key)
416     {
417       /* It does not make much sense to store the session key in
418        * secure memory because it has already been passed on the
419        * command line and the GCHQ knows about it.  */
420       c->dek = xmalloc_clear (sizeof *c->dek);
421       result = get_override_session_key (c->dek, opt.override_session_key);
422       if (result)
423         {
424           xfree (c->dek);
425           c->dek = NULL;
426         }
427     }
428   else if (enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL_E
429            || enc->pubkey_algo == PUBKEY_ALGO_ECDH
430            || enc->pubkey_algo == PUBKEY_ALGO_RSA
431            || enc->pubkey_algo == PUBKEY_ALGO_RSA_E
432            || enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL)
433     {
434       /* Note that we also allow type 20 Elgamal keys for decryption.
435          There are still a couple of those keys in active use as a
436          subkey.  */
437
438       /* FIXME: Store this all in a list and process it later so that
439          we can prioritize what key to use.  This gives a better user
440          experience if wildcard keyids are used.  */
441       if  (!c->dek && ((!enc->keyid[0] && !enc->keyid[1])
442                        || opt.try_all_secrets
443                        || have_secret_key_with_kid (enc->keyid)))
444         {
445           if(opt.list_only)
446             result = GPG_ERR_MISSING_ACTION; /* fixme: Use better error code. */
447           else
448             {
449               c->dek = xmalloc_secure_clear (sizeof *c->dek);
450               if ((result = get_session_key (ctrl, enc, c->dek)))
451                 {
452                   /* Error: Delete the DEK. */
453                   xfree (c->dek);
454                   c->dek = NULL;
455                 }
456             }
457         }
458       else
459         result = GPG_ERR_NO_SECKEY;
460     }
461   else
462     result = GPG_ERR_PUBKEY_ALGO;
463
464   if (1)
465     {
466       /* Store it for later display.  */
467       struct kidlist_item *x = xmalloc (sizeof *x);
468       x->kid[0] = enc->keyid[0];
469       x->kid[1] = enc->keyid[1];
470       x->pubkey_algo = enc->pubkey_algo;
471       x->reason = result;
472       x->next = c->pkenc_list;
473       c->pkenc_list = x;
474
475       if (!result && opt.verbose > 1)
476         log_info (_("public key encrypted data: good DEK\n"));
477     }
478
479   free_packet(pkt, NULL);
480 }
481
482
483 /*
484  * Print the list of public key encrypted packets which we could
485  * not decrypt.
486  */
487 static void
488 print_pkenc_list (ctrl_t ctrl, struct kidlist_item *list, int failed)
489 {
490   for (; list; list = list->next)
491     {
492       PKT_public_key *pk;
493       const char *algstr;
494
495       if (failed && !list->reason)
496         continue;
497       if (!failed && list->reason)
498         continue;
499
500       algstr = openpgp_pk_algo_name (list->pubkey_algo);
501       pk = xmalloc_clear (sizeof *pk);
502
503       if (!algstr)
504         algstr = "[?]";
505       pk->pubkey_algo = list->pubkey_algo;
506       if (!get_pubkey (ctrl, pk, list->kid))
507         {
508           char *p;
509           log_info (_("encrypted with %u-bit %s key, ID %s, created %s\n"),
510                     nbits_from_pk (pk), algstr, keystr_from_pk(pk),
511                     strtimestamp (pk->timestamp));
512           p = get_user_id_native (ctrl, list->kid);
513           log_printf (_("      \"%s\"\n"), p);
514           xfree (p);
515         }
516       else
517         log_info (_("encrypted with %s key, ID %s\n"),
518                   algstr, keystr(list->kid));
519
520       free_public_key (pk);
521
522       if (gpg_err_code (list->reason) == GPG_ERR_NO_SECKEY)
523         {
524           if (is_status_enabled())
525             {
526               char buf[20];
527               snprintf (buf, sizeof buf, "%08lX%08lX",
528                         (ulong)list->kid[0], (ulong)list->kid[1]);
529               write_status_text (STATUS_NO_SECKEY, buf);
530             }
531         }
532       else if (gpg_err_code (list->reason) == GPG_ERR_MISSING_ACTION)
533         {
534           /* Not tested for secret key due to --list-only mode.  */
535         }
536       else if (list->reason)
537         {
538           log_info (_("public key decryption failed: %s\n"),
539                     gpg_strerror (list->reason));
540           write_status_error ("pkdecrypt_failed", list->reason);
541         }
542     }
543 }
544
545
546 static void
547 proc_encrypted (CTX c, PACKET *pkt)
548 {
549   int result = 0;
550   int early_plaintext = literals_seen;
551
552   if (early_plaintext)
553     {
554       log_info (_("WARNING: multiple plaintexts seen\n"));
555       write_status_errcode ("decryption.early_plaintext", GPG_ERR_BAD_DATA);
556       /* We fail only later so that we can print some more info first.  */
557     }
558
559   if (!opt.quiet)
560     {
561       if (c->symkeys>1)
562         log_info (_("encrypted with %lu passphrases\n"), c->symkeys);
563       else if (c->symkeys == 1)
564         log_info (_("encrypted with 1 passphrase\n"));
565       print_pkenc_list (c->ctrl, c->pkenc_list, 1 );
566       print_pkenc_list (c->ctrl, c->pkenc_list, 0 );
567     }
568
569   /* FIXME: Figure out the session key by looking at all pkenc packets. */
570
571   write_status (STATUS_BEGIN_DECRYPTION);
572
573   /*log_debug("dat: %sencrypted data\n", c->dek?"":"conventional ");*/
574   if (opt.list_only)
575     result = -1;
576   else if (!c->dek && !c->last_was_session_key)
577     {
578       int algo;
579       STRING2KEY s2kbuf;
580       STRING2KEY *s2k = NULL;
581       int canceled;
582
583       if (opt.override_session_key)
584         {
585           c->dek = xmalloc_clear (sizeof *c->dek);
586           result = get_override_session_key (c->dek, opt.override_session_key);
587           if (result)
588             {
589               xfree (c->dek);
590               c->dek = NULL;
591             }
592         }
593       else
594         {
595           /* Assume this is old style conventional encrypted data. */
596           algo = opt.def_cipher_algo;
597           if (algo)
598             log_info (_("assuming %s encrypted data\n"),
599                       openpgp_cipher_algo_name (algo));
600           else if (openpgp_cipher_test_algo (CIPHER_ALGO_IDEA))
601             {
602               algo = opt.def_cipher_algo;
603               if (!algo)
604                 algo = opt.s2k_cipher_algo;
605               log_info (_("IDEA cipher unavailable, "
606                           "optimistically attempting to use %s instead\n"),
607                         openpgp_cipher_algo_name (algo));
608             }
609           else
610             {
611               algo = CIPHER_ALGO_IDEA;
612               if (!opt.s2k_digest_algo)
613                 {
614                   /* If no digest is given we assume SHA-1. */
615                   s2kbuf.mode = 0;
616                   s2kbuf.hash_algo = DIGEST_ALGO_SHA1;
617                   s2k = &s2kbuf;
618                 }
619               log_info (_("assuming %s encrypted data\n"), "IDEA");
620             }
621
622           c->dek = passphrase_to_dek (algo, s2k, 0, 0, NULL, &canceled);
623           if (c->dek)
624             c->dek->algo_info_printed = 1;
625           else if (canceled)
626             result = gpg_error (GPG_ERR_CANCELED);
627           else
628             result = gpg_error (GPG_ERR_INV_PASSPHRASE);
629         }
630     }
631   else if (!c->dek)
632     result = GPG_ERR_NO_SECKEY;
633
634   /* Compute compliance with CO_DE_VS.  */
635   if (!result && is_status_enabled ()
636       /* Symmetric encryption and asymmetric encryption voids compliance.  */
637       && (c->symkeys != !!c->pkenc_list )
638       /* Overriding session key voids compliance.  */
639       && !opt.override_session_key
640       /* Check symmetric cipher.  */
641       && gnupg_cipher_is_compliant (CO_DE_VS, c->dek->algo,
642                                     GCRY_CIPHER_MODE_CFB))
643     {
644       struct kidlist_item *i;
645       int compliant = 1;
646       PKT_public_key *pk = xmalloc (sizeof *pk);
647
648       if ( !(c->pkenc_list || c->symkeys) )
649         log_debug ("%s: where else did the session key come from?\n", __func__);
650
651       /* Now check that every key used to encrypt the session key is
652        * compliant.  */
653       for (i = c->pkenc_list; i && compliant; i = i->next)
654         {
655           memset (pk, 0, sizeof *pk);
656           pk->pubkey_algo = i->pubkey_algo;
657           if (get_pubkey (c->ctrl, pk, i->kid) != 0
658               || ! gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, pk->pkey,
659                                           nbits_from_pk (pk), NULL))
660             compliant = 0;
661           release_public_key_parts (pk);
662         }
663
664       xfree (pk);
665
666       if (compliant)
667         write_status_strings (STATUS_DECRYPTION_COMPLIANCE_MODE,
668                               gnupg_status_compliance_flag (CO_DE_VS),
669                               NULL);
670
671     }
672
673
674   if (!result)
675     result = decrypt_data (c->ctrl, c, pkt->pkt.encrypted, c->dek );
676
677   /* Trigger the deferred error.  */
678   if (!result && early_plaintext)
679     result = gpg_error (GPG_ERR_BAD_DATA);
680
681   if (result == -1)
682     ;
683   else if (!result
684            && !opt.ignore_mdc_error
685            && !pkt->pkt.encrypted->mdc_method)
686     {
687       /* The message has been decrypted but does not carry an MDC.
688        * The option --ignore-mdc-error has also not been used.  To
689        * avoid attacks changing an MDC message to a non-MDC message,
690        * we fail here.  */
691       log_error (_("WARNING: message was not integrity protected\n"));
692       if (!pkt->pkt.encrypted->mdc_method
693           && (openpgp_cipher_get_algo_blklen (c->dek->algo) == 8
694               || c->dek->algo == CIPHER_ALGO_TWOFISH))
695         {
696           /* Before 2.2.8 we did not fail hard for a missing MDC if
697            * one of the old ciphers where used.  Although these cases
698            * are rare in practice we print a hint on how to decrypt
699            * such messages.  */
700           log_string
701             (GPGRT_LOG_INFO,
702              _("Hint: If this message was created before the year 2003 it is\n"
703                "likely that this message is legitimate.  This is because back\n"
704                "then integrity protection was not widely used.\n"));
705           log_info (_("Use the option '%s' to decrypt anyway.\n"),
706                      "--ignore-mdc-error");
707           write_status_errcode ("nomdc_with_legacy_cipher",
708                                 GPG_ERR_DECRYPT_FAILED);
709         }
710       log_info (_("decryption forced to fail!\n"));
711       write_status (STATUS_DECRYPTION_FAILED);
712     }
713   else if (!result || (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE
714                        && opt.ignore_mdc_error))
715     {
716       write_status (STATUS_DECRYPTION_OKAY);
717       if (opt.verbose > 1)
718         log_info(_("decryption okay\n"));
719       if (pkt->pkt.encrypted->mdc_method && !result)
720         write_status (STATUS_GOODMDC);
721       else
722         log_info (_("WARNING: message was not integrity protected\n"));
723     }
724   else if (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE)
725     {
726       glo_ctrl.lasterr = result;
727       log_error (_("WARNING: encrypted message has been manipulated!\n"));
728       write_status (STATUS_BADMDC);
729       write_status (STATUS_DECRYPTION_FAILED);
730     }
731   else
732     {
733       if ((gpg_err_code (result) == GPG_ERR_BAD_KEY
734            || gpg_err_code (result) == GPG_ERR_CIPHER_ALGO)
735           && *c->dek->s2k_cacheid != '\0')
736         {
737           if (opt.debug)
738             log_debug ("cleared passphrase cached with ID: %s\n",
739                        c->dek->s2k_cacheid);
740           passphrase_clear_cache (c->dek->s2k_cacheid);
741         }
742       glo_ctrl.lasterr = result;
743       write_status (STATUS_DECRYPTION_FAILED);
744       log_error (_("decryption failed: %s\n"), gpg_strerror (result));
745       /* Hmmm: does this work when we have encrypted using multiple
746        * ways to specify the session key (symmmetric and PK). */
747     }
748
749   xfree (c->dek);
750   c->dek = NULL;
751   free_packet (pkt, NULL);
752   c->last_was_session_key = 0;
753   write_status (STATUS_END_DECRYPTION);
754
755   /* Bump the counter even if we have not seen a literal data packet
756    * inside an encryption container.  This acts as a sentinel in case
757    * a misplace extra literal data packets follows after this
758    * encrypted packet.  */
759   literals_seen++;
760 }
761
762
763 static void
764 proc_plaintext( CTX c, PACKET *pkt )
765 {
766   PKT_plaintext *pt = pkt->pkt.plaintext;
767   int any, clearsig, rc;
768   kbnode_t n;
769
770   /* This is a literal data packet.  Bumb a counter for later checks.  */
771   literals_seen++;
772
773   if (pt->namelen == 8 && !memcmp( pt->name, "_CONSOLE", 8))
774     log_info (_("Note: sender requested \"for-your-eyes-only\"\n"));
775   else if (opt.verbose)
776     {
777       /* We don't use print_utf8_buffer because that would require a
778        * string change which we don't want in 2.2.  It is also not
779        * clear whether the filename is always utf-8 encoded.  */
780       char *tmp = make_printable_string (pt->name, pt->namelen, 0);
781       log_info (_("original file name='%.*s'\n"), (int)strlen (tmp), tmp);
782       xfree (tmp);
783     }
784
785   free_md_filter_context (&c->mfx);
786   if (gcry_md_open (&c->mfx.md, 0, 0))
787     BUG ();
788   /* fixme: we may need to push the textfilter if we have sigclass 1
789    * and no armoring - Not yet tested
790    * Hmmm, why don't we need it at all if we have sigclass 1
791    * Should we assume that plaintext in mode 't' has always sigclass 1??
792    * See: Russ Allbery's mail 1999-02-09
793    */
794   any = clearsig = 0;
795   for (n=c->list; n; n = n->next )
796     {
797       if (n->pkt->pkttype == PKT_ONEPASS_SIG)
798         {
799           /* The onepass signature case. */
800           if (n->pkt->pkt.onepass_sig->digest_algo)
801             {
802               gcry_md_enable (c->mfx.md, n->pkt->pkt.onepass_sig->digest_algo);
803               any = 1;
804             }
805         }
806       else if (n->pkt->pkttype == PKT_GPG_CONTROL
807                && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START)
808         {
809           /* The clearsigned message case. */
810           size_t datalen = n->pkt->pkt.gpg_control->datalen;
811           const byte *data = n->pkt->pkt.gpg_control->data;
812
813           /* Check that we have at least the sigclass and one hash.  */
814           if  (datalen < 2)
815             log_fatal ("invalid control packet CTRLPKT_CLEARSIGN_START\n");
816           /* Note that we don't set the clearsig flag for not-dash-escaped
817            * documents.  */
818           clearsig = (*data == 0x01);
819           for (data++, datalen--; datalen; datalen--, data++)
820             gcry_md_enable (c->mfx.md, *data);
821           any = 1;
822           break;  /* Stop here as one-pass signature packets are not
823                      expected.  */
824         }
825       else if (n->pkt->pkttype == PKT_SIGNATURE)
826         {
827           /* The SIG+LITERAL case that PGP used to use.  */
828           gcry_md_enable ( c->mfx.md, n->pkt->pkt.signature->digest_algo );
829           any = 1;
830         }
831     }
832
833   if (!any && !opt.skip_verify)
834     {
835       /* This is for the old GPG LITERAL+SIG case.  It's not legal
836          according to 2440, so hopefully it won't come up that often.
837          There is no good way to specify what algorithms to use in
838          that case, so these there are the historical answer. */
839         gcry_md_enable (c->mfx.md, DIGEST_ALGO_RMD160);
840         gcry_md_enable (c->mfx.md, DIGEST_ALGO_SHA1);
841     }
842   if (DBG_HASHING)
843     {
844       gcry_md_debug (c->mfx.md, "verify");
845       if (c->mfx.md2)
846         gcry_md_debug (c->mfx.md2, "verify2");
847     }
848
849   rc=0;
850
851   if (literals_seen > 1)
852     {
853       log_info (_("WARNING: multiple plaintexts seen\n"));
854
855       if (!opt.flags.allow_multiple_messages)
856         {
857           write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA");
858           log_inc_errorcount ();
859           rc = gpg_error (GPG_ERR_UNEXPECTED);
860         }
861     }
862
863   if (!rc)
864     {
865       /* It we are in --verify mode, we do not want to output the
866        * signed text.  However, if --output is also used we do what
867        * has been requested and write out the signed data.  */
868       rc = handle_plaintext (pt, &c->mfx,
869                              (opt.outfp || opt.outfile)? 0 :  c->sigs_only,
870                              clearsig);
871       if (gpg_err_code (rc) == GPG_ERR_EACCES && !c->sigs_only)
872         {
873           /* Can't write output but we hash it anyway to check the
874              signature. */
875           rc = handle_plaintext( pt, &c->mfx, 1, clearsig );
876         }
877     }
878
879   if (rc)
880     log_error ("handle plaintext failed: %s\n", gpg_strerror (rc));
881
882   free_packet (pkt, NULL);
883   c->last_was_session_key = 0;
884
885   /* We add a marker control packet instead of the plaintext packet.
886    * This is so that we can later detect invalid packet sequences.  */
887   n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK, NULL, 0));
888   if (c->list)
889     add_kbnode (c->list, n);
890   else
891     c->list = n;
892 }
893
894
895 static int
896 proc_compressed_cb (iobuf_t a, void *info)
897 {
898   if ( ((CTX)info)->signed_data.used
899        && ((CTX)info)->signed_data.data_fd != -1)
900     return proc_signature_packets_by_fd (((CTX)info)->ctrl, info, a,
901                                          ((CTX)info)->signed_data.data_fd);
902   else
903     return proc_signature_packets (((CTX)info)->ctrl, info, a,
904                                    ((CTX)info)->signed_data.data_names,
905                                    ((CTX)info)->sigfilename );
906 }
907
908
909 static int
910 proc_encrypt_cb (iobuf_t a, void *info )
911 {
912   CTX c = info;
913   return proc_encryption_packets (c->ctrl, info, a );
914 }
915
916
917 static int
918 proc_compressed (CTX c, PACKET *pkt)
919 {
920   PKT_compressed *zd = pkt->pkt.compressed;
921   int rc;
922
923   /*printf("zip: compressed data packet\n");*/
924   if (c->sigs_only)
925     rc = handle_compressed (c->ctrl, c, zd, proc_compressed_cb, c);
926   else if( c->encrypt_only )
927     rc = handle_compressed (c->ctrl, c, zd, proc_encrypt_cb, c);
928   else
929     rc = handle_compressed (c->ctrl, c, zd, NULL, NULL);
930
931   if (gpg_err_code (rc) == GPG_ERR_BAD_DATA)
932     {
933       if  (!c->any.uncompress_failed)
934         {
935           CTX cc;
936
937           for (cc=c; cc; cc = cc->anchor)
938             cc->any.uncompress_failed = 1;
939           log_error ("uncompressing failed: %s\n", gpg_strerror (rc));
940         }
941     }
942   else if (rc)
943     log_error ("uncompressing failed: %s\n", gpg_strerror (rc));
944
945   free_packet (pkt, NULL);
946   c->last_was_session_key = 0;
947   return rc;
948 }
949
950
951 /*
952  * Check the signature.  If R_PK is not NULL a copy of the public key
953  * used to verify the signature will be stored there, or NULL if not
954  * found.  Returns: 0 = valid signature or an error code
955  */
956 static int
957 do_check_sig (CTX c, kbnode_t node, int *is_selfsig,
958               int *is_expkey, int *is_revkey, PKT_public_key **r_pk)
959 {
960   PKT_signature *sig;
961   gcry_md_hd_t md = NULL;
962   gcry_md_hd_t md2 = NULL;
963   gcry_md_hd_t md_good = NULL;
964   int algo, rc;
965
966   if (r_pk)
967     *r_pk = NULL;
968
969   log_assert (node->pkt->pkttype == PKT_SIGNATURE);
970   if (is_selfsig)
971     *is_selfsig = 0;
972   sig = node->pkt->pkt.signature;
973
974   algo = sig->digest_algo;
975   rc = openpgp_md_test_algo (algo);
976   if (rc)
977     return rc;
978
979   if (sig->sig_class == 0x00)
980     {
981       if (c->mfx.md)
982         {
983           if (gcry_md_copy (&md, c->mfx.md ))
984             BUG ();
985         }
986       else /* detached signature */
987         {
988           /* check_signature() will enable the md. */
989           if (gcry_md_open (&md, 0, 0 ))
990             BUG ();
991         }
992     }
993   else if (sig->sig_class == 0x01)
994     {
995       /* How do we know that we have to hash the (already hashed) text
996          in canonical mode ??? (calculating both modes???) */
997       if (c->mfx.md)
998         {
999           if (gcry_md_copy (&md, c->mfx.md ))
1000             BUG ();
1001           if (c->mfx.md2 && gcry_md_copy (&md2, c->mfx.md2))
1002             BUG ();
1003         }
1004       else /* detached signature */
1005         {
1006           log_debug ("Do we really need this here?");
1007           /* check_signature() will enable the md*/
1008           if (gcry_md_open (&md, 0, 0 ))
1009             BUG ();
1010           if (gcry_md_open (&md2, 0, 0 ))
1011             BUG ();
1012         }
1013     }
1014   else if ((sig->sig_class&~3) == 0x10
1015            ||   sig->sig_class == 0x18
1016            ||   sig->sig_class == 0x1f
1017            ||   sig->sig_class == 0x20
1018            ||   sig->sig_class == 0x28
1019            ||   sig->sig_class == 0x30)
1020     {
1021       if (c->list->pkt->pkttype == PKT_PUBLIC_KEY
1022           || c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1023         {
1024           return check_key_signature (c->ctrl, c->list, node, is_selfsig);
1025         }
1026       else if (sig->sig_class == 0x20)
1027         {
1028           log_error (_("standalone revocation - "
1029                        "use \"gpg --import\" to apply\n"));
1030           return GPG_ERR_NOT_PROCESSED;
1031         }
1032       else
1033         {
1034           log_error ("invalid root packet for sigclass %02x\n", sig->sig_class);
1035           return GPG_ERR_SIG_CLASS;
1036         }
1037     }
1038   else
1039     return GPG_ERR_SIG_CLASS;
1040
1041   /* We only get here if we are checking the signature of a binary
1042      (0x00) or text document (0x01).  */
1043   rc = check_signature2 (c->ctrl, sig, md, NULL, is_expkey, is_revkey, r_pk);
1044   if (! rc)
1045     md_good = md;
1046   else if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE && md2)
1047     {
1048       PKT_public_key *pk2;
1049
1050       rc = check_signature2 (c->ctrl, sig, md2, NULL, is_expkey, is_revkey,
1051                              r_pk? &pk2 : NULL);
1052       if (!rc)
1053         {
1054           md_good = md2;
1055           if (r_pk)
1056             {
1057               free_public_key (*r_pk);
1058               *r_pk = pk2;
1059             }
1060         }
1061     }
1062
1063   if (md_good)
1064     {
1065       unsigned char *buffer = gcry_md_read (md_good, sig->digest_algo);
1066       sig->digest_len = gcry_md_get_algo_dlen (map_md_openpgp_to_gcry (algo));
1067       memcpy (sig->digest, buffer, sig->digest_len);
1068     }
1069
1070   gcry_md_close (md);
1071   gcry_md_close (md2);
1072
1073   return rc;
1074 }
1075
1076
1077 static void
1078 print_userid (PACKET *pkt)
1079 {
1080   if (!pkt)
1081     BUG();
1082
1083   if (pkt->pkttype != PKT_USER_ID)
1084     {
1085       es_printf ("ERROR: unexpected packet type %d", pkt->pkttype );
1086       return;
1087     }
1088   if (opt.with_colons)
1089     {
1090       if (pkt->pkt.user_id->attrib_data)
1091         es_printf("%u %lu",
1092                   pkt->pkt.user_id->numattribs,
1093                   pkt->pkt.user_id->attrib_len);
1094       else
1095         es_write_sanitized (es_stdout, pkt->pkt.user_id->name,
1096                             pkt->pkt.user_id->len, ":", NULL);
1097     }
1098   else
1099     print_utf8_buffer (es_stdout, pkt->pkt.user_id->name,
1100                        pkt->pkt.user_id->len );
1101 }
1102
1103
1104 /*
1105  * List the keyblock in a user friendly way
1106  */
1107 static void
1108 list_node (CTX c, kbnode_t node)
1109 {
1110   if (!node)
1111     ;
1112   else if (node->pkt->pkttype == PKT_PUBLIC_KEY
1113            || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1114     {
1115       PKT_public_key *pk = node->pkt->pkt.public_key;
1116
1117       if (opt.with_colons)
1118         {
1119           u32 keyid[2];
1120
1121           keyid_from_pk( pk, keyid );
1122           if (pk->flags.primary)
1123             c->trustletter = (opt.fast_list_mode
1124                               ? 0
1125                               : get_validity_info
1126                                   (c->ctrl,
1127                                    node->pkt->pkttype == PKT_PUBLIC_KEY
1128                                    ? node : NULL,
1129                                    pk, NULL));
1130           es_printf ("%s:", pk->flags.primary? "pub":"sub" );
1131           if (c->trustletter)
1132             es_putc (c->trustletter, es_stdout);
1133           es_printf (":%u:%d:%08lX%08lX:%s:%s::",
1134                      nbits_from_pk( pk ),
1135                      pk->pubkey_algo,
1136                      (ulong)keyid[0],(ulong)keyid[1],
1137                      colon_datestr_from_pk( pk ),
1138                      colon_strtime (pk->expiredate) );
1139           if (pk->flags.primary && !opt.fast_list_mode)
1140             es_putc (get_ownertrust_info (c->ctrl, pk, 1), es_stdout);
1141           es_putc (':', es_stdout);
1142           es_putc ('\n', es_stdout);
1143         }
1144       else
1145         {
1146           print_key_line (c->ctrl, es_stdout, pk, 0);
1147         }
1148
1149       if (opt.keyid_format == KF_NONE && !opt.with_colons)
1150         ; /* Already printed.  */
1151       else if ((pk->flags.primary && opt.fingerprint) || opt.fingerprint > 1)
1152         print_fingerprint (c->ctrl, NULL, pk, 0);
1153
1154       if (pk->flags.primary)
1155         {
1156           int kl = opt.keyid_format == KF_NONE? 0 : keystrlen ();
1157
1158           /* Now list all userids with their signatures. */
1159           for (node = node->next; node; node = node->next)
1160             {
1161               if (node->pkt->pkttype == PKT_SIGNATURE)
1162                 {
1163                   list_node (c,  node );
1164                 }
1165               else if (node->pkt->pkttype == PKT_USER_ID)
1166                 {
1167                   if (opt.with_colons)
1168                     es_printf ("%s:::::::::",
1169                                node->pkt->pkt.user_id->attrib_data?"uat":"uid");
1170                   else
1171                     es_printf ("uid%*s",
1172                                kl + (opt.legacy_list_mode? 9:11),
1173                                "" );
1174                   print_userid (node->pkt);
1175                   if (opt.with_colons)
1176                     es_putc (':', es_stdout);
1177                   es_putc ('\n', es_stdout);
1178                 }
1179               else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1180                 {
1181                   list_node(c,  node );
1182                 }
1183             }
1184         }
1185     }
1186   else if (node->pkt->pkttype == PKT_SECRET_KEY
1187            || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1188     {
1189
1190       log_debug ("FIXME: No way to print secret key packets here\n");
1191       /* fixme: We may use a function to turn a secret key packet into
1192          a public key one and use that here.  */
1193     }
1194   else if (node->pkt->pkttype == PKT_SIGNATURE)
1195     {
1196       PKT_signature *sig = node->pkt->pkt.signature;
1197       int is_selfsig = 0;
1198       int rc2 = 0;
1199       size_t n;
1200       char *p;
1201       int sigrc = ' ';
1202
1203       if (!opt.verbose)
1204         return;
1205
1206       if (sig->sig_class == 0x20 || sig->sig_class == 0x30)
1207         es_fputs ("rev", es_stdout);
1208       else
1209         es_fputs ("sig", es_stdout);
1210       if (opt.check_sigs)
1211         {
1212           fflush (stdout);
1213           rc2 = do_check_sig (c, node, &is_selfsig, NULL, NULL, NULL);
1214           switch (gpg_err_code (rc2))
1215             {
1216             case 0:                       sigrc = '!'; break;
1217             case GPG_ERR_BAD_SIGNATURE:   sigrc = '-'; break;
1218             case GPG_ERR_NO_PUBKEY:
1219             case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break;
1220             default:                      sigrc = '%'; break;
1221             }
1222         }
1223       else /* Check whether this is a self signature.  */
1224         {
1225           u32 keyid[2];
1226
1227           if (c->list->pkt->pkttype == PKT_PUBLIC_KEY
1228               || c->list->pkt->pkttype == PKT_SECRET_KEY )
1229             {
1230               keyid_from_pk (c->list->pkt->pkt.public_key, keyid);
1231
1232               if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1])
1233                 is_selfsig = 1;
1234             }
1235         }
1236
1237       if (opt.with_colons)
1238         {
1239           es_putc (':', es_stdout);
1240           if (sigrc != ' ')
1241             es_putc (sigrc, es_stdout);
1242           es_printf ("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo,
1243                      (ulong)sig->keyid[0], (ulong)sig->keyid[1],
1244                      colon_datestr_from_sig (sig),
1245                      colon_expirestr_from_sig (sig));
1246
1247           if (sig->trust_depth || sig->trust_value)
1248             es_printf ("%d %d",sig->trust_depth,sig->trust_value);
1249           es_putc (':', es_stdout);
1250
1251           if (sig->trust_regexp)
1252             es_write_sanitized (es_stdout, sig->trust_regexp,
1253                                 strlen (sig->trust_regexp), ":", NULL);
1254           es_putc (':', es_stdout);
1255         }
1256       else
1257         es_printf ("%c       %s %s   ",
1258                    sigrc, keystr (sig->keyid), datestr_from_sig(sig));
1259       if (sigrc == '%')
1260         es_printf ("[%s] ", gpg_strerror (rc2) );
1261       else if (sigrc == '?')
1262         ;
1263       else if (is_selfsig)
1264         {
1265           if (opt.with_colons)
1266             es_putc (':', es_stdout);
1267           es_fputs (sig->sig_class == 0x18? "[keybind]":"[selfsig]", es_stdout);
1268           if (opt.with_colons)
1269             es_putc (':', es_stdout);
1270         }
1271       else if (!opt.fast_list_mode)
1272         {
1273           p = get_user_id (c->ctrl, sig->keyid, &n, NULL);
1274           es_write_sanitized (es_stdout, p, n,
1275                               opt.with_colons?":":NULL, NULL );
1276           xfree (p);
1277         }
1278       if (opt.with_colons)
1279         es_printf (":%02x%c:", sig->sig_class, sig->flags.exportable?'x':'l');
1280       es_putc ('\n', es_stdout);
1281     }
1282   else
1283     log_error ("invalid node with packet of type %d\n", node->pkt->pkttype);
1284 }
1285
1286
1287 int
1288 proc_packets (ctrl_t ctrl, void *anchor, iobuf_t a )
1289 {
1290   int rc;
1291   CTX c = xmalloc_clear (sizeof *c);
1292
1293   c->ctrl = ctrl;
1294   c->anchor = anchor;
1295   rc = do_proc_packets (ctrl, c, a);
1296   xfree (c);
1297
1298   return rc;
1299 }
1300
1301
1302 int
1303 proc_signature_packets (ctrl_t ctrl, void *anchor, iobuf_t a,
1304                         strlist_t signedfiles, const char *sigfilename )
1305 {
1306   CTX c = xmalloc_clear (sizeof *c);
1307   int rc;
1308
1309   c->ctrl = ctrl;
1310   c->anchor = anchor;
1311   c->sigs_only = 1;
1312
1313   c->signed_data.data_fd = -1;
1314   c->signed_data.data_names = signedfiles;
1315   c->signed_data.used = !!signedfiles;
1316
1317   c->sigfilename = sigfilename;
1318   rc = do_proc_packets (ctrl, c, a);
1319
1320   /* If we have not encountered any signature we print an error
1321      messages, send a NODATA status back and return an error code.
1322      Using log_error is required because verify_files does not check
1323      error codes for each file but we want to terminate the process
1324      with an error. */
1325   if (!rc && !c->any.sig_seen)
1326     {
1327       write_status_text (STATUS_NODATA, "4");
1328       log_error (_("no signature found\n"));
1329       rc = GPG_ERR_NO_DATA;
1330     }
1331
1332   /* Propagate the signature seen flag upward. Do this only on success
1333      so that we won't issue the nodata status several times.  */
1334   if (!rc && c->anchor && c->any.sig_seen)
1335     c->anchor->any.sig_seen = 1;
1336
1337   xfree (c);
1338   return rc;
1339 }
1340
1341
1342 int
1343 proc_signature_packets_by_fd (ctrl_t ctrl,
1344                               void *anchor, iobuf_t a, int signed_data_fd )
1345 {
1346   int rc;
1347   CTX c;
1348
1349   c = xtrycalloc (1, sizeof *c);
1350   if (!c)
1351     return gpg_error_from_syserror ();
1352
1353   c->ctrl = ctrl;
1354   c->anchor = anchor;
1355   c->sigs_only = 1;
1356
1357   c->signed_data.data_fd = signed_data_fd;
1358   c->signed_data.data_names = NULL;
1359   c->signed_data.used = (signed_data_fd != -1);
1360
1361   rc = do_proc_packets (ctrl, c, a);
1362
1363   /* If we have not encountered any signature we print an error
1364      messages, send a NODATA status back and return an error code.
1365      Using log_error is required because verify_files does not check
1366      error codes for each file but we want to terminate the process
1367      with an error. */
1368   if (!rc && !c->any.sig_seen)
1369     {
1370       write_status_text (STATUS_NODATA, "4");
1371       log_error (_("no signature found\n"));
1372       rc = gpg_error (GPG_ERR_NO_DATA);
1373     }
1374
1375   /* Propagate the signature seen flag upward. Do this only on success
1376      so that we won't issue the nodata status several times. */
1377   if (!rc && c->anchor && c->any.sig_seen)
1378     c->anchor->any.sig_seen = 1;
1379
1380   xfree ( c );
1381   return rc;
1382 }
1383
1384
1385 int
1386 proc_encryption_packets (ctrl_t ctrl, void *anchor, iobuf_t a )
1387 {
1388   CTX c = xmalloc_clear (sizeof *c);
1389   int rc;
1390
1391   c->ctrl = ctrl;
1392   c->anchor = anchor;
1393   c->encrypt_only = 1;
1394   rc = do_proc_packets (ctrl, c, a);
1395   xfree (c);
1396   return rc;
1397 }
1398
1399
1400 static int
1401 check_nesting (CTX c)
1402 {
1403   int level;
1404
1405   for (level=0; c; c = c->anchor)
1406     level++;
1407
1408   if (level > MAX_NESTING_DEPTH)
1409     {
1410       log_error ("input data with too deeply nested packets\n");
1411       write_status_text (STATUS_UNEXPECTED, "1");
1412       return GPG_ERR_BAD_DATA;
1413     }
1414
1415   return 0;
1416 }
1417
1418
1419 static int
1420 do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
1421 {
1422   PACKET *pkt;
1423   struct parse_packet_ctx_s parsectx;
1424   int rc = 0;
1425   int any_data = 0;
1426   int newpkt;
1427
1428   rc = check_nesting (c);
1429   if (rc)
1430     return rc;
1431
1432   pkt = xmalloc( sizeof *pkt );
1433   c->iobuf = a;
1434   init_packet(pkt);
1435   init_parse_packet (&parsectx, a);
1436   while ((rc=parse_packet (&parsectx, pkt)) != -1)
1437     {
1438       any_data = 1;
1439       if (rc)
1440         {
1441           free_packet (pkt, &parsectx);
1442           /* Stop processing when an invalid packet has been encountered
1443            * but don't do so when we are doing a --list-packets.  */
1444           if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
1445               && opt.list_packets == 0)
1446             break;
1447           continue;
1448         }
1449       newpkt = -1;
1450       if (opt.list_packets)
1451         {
1452           switch (pkt->pkttype)
1453             {
1454             case PKT_PUBKEY_ENC:    proc_pubkey_enc (ctrl, c, pkt); break;
1455             case PKT_SYMKEY_ENC:    proc_symkey_enc (c, pkt); break;
1456             case PKT_ENCRYPTED:
1457             case PKT_ENCRYPTED_MDC: proc_encrypted (c, pkt); break;
1458             case PKT_COMPRESSED:    rc = proc_compressed (c, pkt); break;
1459             default: newpkt = 0; break;
1460             }
1461         }
1462       else if (c->sigs_only)
1463         {
1464           switch (pkt->pkttype)
1465             {
1466             case PKT_PUBLIC_KEY:
1467             case PKT_SECRET_KEY:
1468             case PKT_USER_ID:
1469             case PKT_SYMKEY_ENC:
1470             case PKT_PUBKEY_ENC:
1471             case PKT_ENCRYPTED:
1472             case PKT_ENCRYPTED_MDC:
1473               write_status_text( STATUS_UNEXPECTED, "0" );
1474               rc = GPG_ERR_UNEXPECTED;
1475               goto leave;
1476
1477             case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1478             case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1479             case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1480             case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1481             case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break;
1482             default: newpkt = 0; break;
1483             }
1484         }
1485       else if (c->encrypt_only)
1486         {
1487           switch (pkt->pkttype)
1488             {
1489             case PKT_PUBLIC_KEY:
1490             case PKT_SECRET_KEY:
1491             case PKT_USER_ID:
1492               write_status_text (STATUS_UNEXPECTED, "0");
1493               rc = GPG_ERR_UNEXPECTED;
1494               goto leave;
1495
1496             case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1497             case PKT_SYMKEY_ENC:  proc_symkey_enc (c, pkt); break;
1498             case PKT_PUBKEY_ENC:  proc_pubkey_enc (ctrl, c, pkt); break;
1499             case PKT_ENCRYPTED:
1500             case PKT_ENCRYPTED_MDC: proc_encrypted (c, pkt); break;
1501             case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1502             case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1503             case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1504             case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break;
1505             default: newpkt = 0; break;
1506             }
1507         }
1508       else
1509         {
1510           switch (pkt->pkttype)
1511             {
1512             case PKT_PUBLIC_KEY:
1513             case PKT_SECRET_KEY:
1514               release_list (c);
1515               c->list = new_kbnode (pkt);
1516               newpkt = 1;
1517               break;
1518             case PKT_PUBLIC_SUBKEY:
1519             case PKT_SECRET_SUBKEY:
1520               newpkt = add_subkey (c, pkt);
1521               break;
1522             case PKT_USER_ID:     newpkt = add_user_id (c, pkt); break;
1523             case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1524             case PKT_PUBKEY_ENC:  proc_pubkey_enc (ctrl, c, pkt); break;
1525             case PKT_SYMKEY_ENC:  proc_symkey_enc (c, pkt); break;
1526             case PKT_ENCRYPTED:
1527             case PKT_ENCRYPTED_MDC: proc_encrypted (c, pkt); break;
1528             case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1529             case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1530             case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1531             case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
1532             case PKT_RING_TRUST:  newpkt = add_ring_trust (c, pkt); break;
1533             default: newpkt = 0; break;
1534             }
1535         }
1536
1537       if (rc)
1538         goto leave;
1539
1540       /* This is a very ugly construct and frankly, I don't remember why
1541        * I used it.  Adding the MDC check here is a hack.
1542        * The right solution is to initiate another context for encrypted
1543        * packet and not to reuse the current one ...  It works right
1544        * when there is a compression packet between which adds just
1545        * an extra layer.
1546        * Hmmm: Rewrite this whole module here??
1547        */
1548       if (pkt->pkttype != PKT_SIGNATURE && pkt->pkttype != PKT_MDC)
1549         c->any.data = (pkt->pkttype == PKT_PLAINTEXT);
1550
1551       if (newpkt == -1)
1552         ;
1553       else if (newpkt)
1554         {
1555           pkt = xmalloc (sizeof *pkt);
1556           init_packet (pkt);
1557         }
1558       else
1559         free_packet (pkt, &parsectx);
1560     }
1561
1562   if (rc == GPG_ERR_INV_PACKET)
1563     write_status_text (STATUS_NODATA, "3");
1564
1565   if (any_data)
1566     rc = 0;
1567   else if (rc == -1)
1568     write_status_text (STATUS_NODATA, "2");
1569
1570
1571  leave:
1572   release_list (c);
1573   xfree(c->dek);
1574   free_packet (pkt, &parsectx);
1575   deinit_parse_packet (&parsectx);
1576   xfree (pkt);
1577   free_md_filter_context (&c->mfx);
1578   return rc;
1579 }
1580
1581
1582 /* Helper for pka_uri_from_sig to parse the to-be-verified address out
1583    of the notation data. */
1584 static pka_info_t *
1585 get_pka_address (PKT_signature *sig)
1586 {
1587   pka_info_t *pka = NULL;
1588   struct notation *nd,*notation;
1589
1590   notation=sig_to_notation(sig);
1591
1592   for(nd=notation;nd;nd=nd->next)
1593     {
1594       if(strcmp(nd->name,"pka-address@gnupg.org")!=0)
1595         continue; /* Not the notation we want. */
1596
1597       /* For now we only use the first valid PKA notation. In future
1598          we might want to keep additional PKA notations in a linked
1599          list. */
1600       if (is_valid_mailbox (nd->value))
1601         {
1602           pka = xmalloc (sizeof *pka + strlen(nd->value));
1603           pka->valid = 0;
1604           pka->checked = 0;
1605           pka->uri = NULL;
1606           strcpy (pka->email, nd->value);
1607           break;
1608         }
1609     }
1610
1611   free_notation(notation);
1612
1613   return pka;
1614 }
1615
1616
1617 /* Return the URI from a DNS PKA record.  If this record has already
1618    be retrieved for the signature we merely return it; if not we go
1619    out and try to get that DNS record. */
1620 static const char *
1621 pka_uri_from_sig (CTX c, PKT_signature *sig)
1622 {
1623   if (!sig->flags.pka_tried)
1624     {
1625       log_assert (!sig->pka_info);
1626       sig->flags.pka_tried = 1;
1627       sig->pka_info = get_pka_address (sig);
1628       if (sig->pka_info)
1629         {
1630           char *url;
1631           unsigned char *fpr;
1632           size_t fprlen;
1633
1634           if (!gpg_dirmngr_get_pka (c->ctrl, sig->pka_info->email,
1635                                     &fpr, &fprlen, &url))
1636             {
1637               if (fpr && fprlen == sizeof sig->pka_info->fpr)
1638                 {
1639                   memcpy (sig->pka_info->fpr, fpr, fprlen);
1640                   if (url)
1641                     {
1642                       sig->pka_info->valid = 1;
1643                       if (!*url)
1644                         xfree (url);
1645                       else
1646                         sig->pka_info->uri = url;
1647                       url = NULL;
1648                     }
1649                 }
1650               xfree (fpr);
1651               xfree (url);
1652             }
1653         }
1654     }
1655   return sig->pka_info? sig->pka_info->uri : NULL;
1656 }
1657
1658
1659 /* Return true if the AKL has the WKD method specified.  */
1660 static int
1661 akl_has_wkd_method (void)
1662 {
1663   struct akl *akl;
1664
1665   for (akl = opt.auto_key_locate; akl; akl = akl->next)
1666     if (akl->type == AKL_WKD)
1667       return 1;
1668   return 0;
1669 }
1670
1671
1672 /* Return the ISSUER fingerprint buffer and its lenbgth at R_LEN.
1673  * Returns NULL if not available.  The returned buffer is valid as
1674  * long as SIG is not modified.  */
1675 const byte *
1676 issuer_fpr_raw (PKT_signature *sig, size_t *r_len)
1677 {
1678   const byte *p;
1679   size_t n;
1680
1681   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_ISSUER_FPR, &n);
1682   if (p && n == 21 && p[0] == 4)
1683     {
1684       *r_len = n - 1;
1685       return p+1;
1686     }
1687   *r_len = 0;
1688   return NULL;
1689 }
1690
1691
1692 /* Return the ISSUER fingerprint string in human readable format if
1693  * available.  Caller must release the string.  */
1694 /* FIXME: Move to another file.  */
1695 char *
1696 issuer_fpr_string (PKT_signature *sig)
1697 {
1698   const byte *p;
1699   size_t n;
1700
1701   p = issuer_fpr_raw (sig, &n);
1702   return p? bin2hex (p, n, NULL) : NULL;
1703 }
1704
1705
1706 static void
1707 print_good_bad_signature (int statno, const char *keyid_str, kbnode_t un,
1708                           PKT_signature *sig, int rc)
1709 {
1710   char *p;
1711
1712   write_status_text_and_buffer (statno, keyid_str,
1713                                 un? un->pkt->pkt.user_id->name:"[?]",
1714                                 un? un->pkt->pkt.user_id->len:3,
1715                                 -1);
1716
1717   if (un)
1718     p = utf8_to_native (un->pkt->pkt.user_id->name,
1719                         un->pkt->pkt.user_id->len, 0);
1720   else
1721     p = xstrdup ("[?]");
1722
1723   if (rc)
1724     log_info (_("BAD signature from \"%s\""), p);
1725   else if (sig->flags.expired)
1726     log_info (_("Expired signature from \"%s\""), p);
1727   else
1728     log_info (_("Good signature from \"%s\""), p);
1729
1730   xfree (p);
1731 }
1732
1733
1734 static int
1735 check_sig_and_print (CTX c, kbnode_t node)
1736 {
1737   PKT_signature *sig = node->pkt->pkt.signature;
1738   const char *astr;
1739   int rc;
1740   int is_expkey = 0;
1741   int is_revkey = 0;
1742   char *issuer_fpr = NULL;
1743   PKT_public_key *pk = NULL;  /* The public key for the signature or NULL. */
1744   int tried_ks_by_fpr;
1745
1746   if (opt.skip_verify)
1747     {
1748       log_info(_("signature verification suppressed\n"));
1749       return 0;
1750     }
1751
1752   /* Check that the message composition is valid.
1753    *
1754    * Per RFC-2440bis (-15) allowed:
1755    *
1756    * S{1,n}           -- detached signature.
1757    * S{1,n} P         -- old style PGP2 signature
1758    * O{1,n} P S{1,n}  -- standard OpenPGP signature.
1759    * C P S{1,n}       -- cleartext signature.
1760    *
1761    *
1762    *      O = One-Pass Signature packet.
1763    *      S = Signature packet.
1764    *      P = OpenPGP Message packet (Encrypted | Compressed | Literal)
1765    *             (Note that the current rfc2440bis draft also allows
1766    *              for a signed message but that does not work as it
1767    *              introduces ambiguities.)
1768    *          We keep track of these packages using the marker packet
1769    *          CTRLPKT_PLAINTEXT_MARK.
1770    *      C = Marker packet for cleartext signatures.
1771    *
1772    * We reject all other messages.
1773    *
1774    * Actually we are calling this too often, i.e. for verification of
1775    * each message but better have some duplicate work than to silently
1776    * introduce a bug here.
1777    */
1778   {
1779     kbnode_t n;
1780     int n_onepass, n_sig;
1781
1782 /*     log_debug ("checking signature packet composition\n"); */
1783 /*     dump_kbnode (c->list); */
1784
1785     n = c->list;
1786     log_assert (n);
1787     if ( n->pkt->pkttype == PKT_SIGNATURE )
1788       {
1789         /* This is either "S{1,n}" case (detached signature) or
1790            "S{1,n} P" (old style PGP2 signature). */
1791         for (n = n->next; n; n = n->next)
1792           if (n->pkt->pkttype != PKT_SIGNATURE)
1793             break;
1794         if (!n)
1795           ; /* Okay, this is a detached signature.  */
1796         else if (n->pkt->pkttype == PKT_GPG_CONTROL
1797                  && (n->pkt->pkt.gpg_control->control
1798                      == CTRLPKT_PLAINTEXT_MARK) )
1799           {
1800             if (n->next)
1801               goto ambiguous;  /* We only allow one P packet. */
1802           }
1803         else
1804           goto ambiguous;
1805       }
1806     else if (n->pkt->pkttype == PKT_ONEPASS_SIG)
1807       {
1808         /* This is the "O{1,n} P S{1,n}" case (standard signature). */
1809         for (n_onepass=1, n = n->next;
1810              n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next)
1811           n_onepass++;
1812         if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
1813                     && (n->pkt->pkt.gpg_control->control
1814                         == CTRLPKT_PLAINTEXT_MARK)))
1815           goto ambiguous;
1816         for (n_sig=0, n = n->next;
1817              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
1818           n_sig++;
1819         if (!n_sig)
1820           goto ambiguous;
1821
1822         /* If we wanted to disallow multiple sig verification, we'd do
1823            something like this:
1824
1825            if (n && !opt.allow_multisig_verification)
1826              goto ambiguous;
1827
1828            However, now that we have --allow-multiple-messages, this
1829            can stay allowable as we can't get here unless multiple
1830            messages (i.e. multiple literals) are allowed. */
1831
1832         if (n_onepass != n_sig)
1833           {
1834             log_info ("number of one-pass packets does not match "
1835                       "number of signature packets\n");
1836             goto ambiguous;
1837           }
1838       }
1839     else if (n->pkt->pkttype == PKT_GPG_CONTROL
1840              && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
1841       {
1842         /* This is the "C P S{1,n}" case (clear text signature). */
1843         n = n->next;
1844         if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
1845                     && (n->pkt->pkt.gpg_control->control
1846                         == CTRLPKT_PLAINTEXT_MARK)))
1847           goto ambiguous;
1848         for (n_sig=0, n = n->next;
1849              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
1850           n_sig++;
1851         if (n || !n_sig)
1852           goto ambiguous;
1853       }
1854     else
1855       {
1856       ambiguous:
1857         log_error(_("can't handle this ambiguous signature data\n"));
1858         return 0;
1859       }
1860   }
1861
1862   if (sig->signers_uid)
1863     write_status_buffer (STATUS_NEWSIG,
1864                          sig->signers_uid, strlen (sig->signers_uid), 0);
1865   else
1866     write_status_text (STATUS_NEWSIG, NULL);
1867
1868   astr = openpgp_pk_algo_name ( sig->pubkey_algo );
1869   issuer_fpr = issuer_fpr_string (sig);
1870
1871   if (issuer_fpr)
1872     {
1873       log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
1874       log_info (_("               using %s key %s\n"),
1875                 astr? astr: "?", issuer_fpr);
1876
1877     }
1878   else if (!keystrlen () || keystrlen () > 8)
1879     {
1880       log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
1881       log_info (_("               using %s key %s\n"),
1882                 astr? astr: "?", keystr(sig->keyid));
1883     }
1884   else /* Legacy format.  */
1885     log_info (_("Signature made %s using %s key ID %s\n"),
1886               asctimestamp(sig->timestamp), astr? astr: "?",
1887               keystr(sig->keyid));
1888
1889   /* In verbose mode print the signers UID.  */
1890   if (sig->signers_uid)
1891     log_info (_("               issuer \"%s\"\n"), sig->signers_uid);
1892
1893   rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey, &pk);
1894
1895   /* If the key isn't found, check for a preferred keyserver.  */
1896   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && sig->flags.pref_ks)
1897     {
1898       const byte *p;
1899       int seq = 0;
1900       size_t n;
1901
1902       while ((p=enum_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS,&n,&seq,NULL)))
1903         {
1904           /* According to my favorite copy editor, in English grammar,
1905              you say "at" if the key is located on a web page, but
1906              "from" if it is located on a keyserver.  I'm not going to
1907              even try to make two strings here :) */
1908           log_info(_("Key available at: ") );
1909           print_utf8_buffer (log_get_stream(), p, n);
1910           log_printf ("\n");
1911
1912           if (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE
1913               && opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1914             {
1915               struct keyserver_spec *spec;
1916
1917               spec = parse_preferred_keyserver (sig);
1918               if (spec)
1919                 {
1920                   int res;
1921
1922                   free_public_key (pk);
1923                   pk = NULL;
1924                   glo_ctrl.in_auto_key_retrieve++;
1925                   res = keyserver_import_keyid (c->ctrl, sig->keyid,spec, 1);
1926                   glo_ctrl.in_auto_key_retrieve--;
1927                   if (!res)
1928                     rc = do_check_sig (c, node, NULL,
1929                                        &is_expkey, &is_revkey, &pk);
1930                   free_keyserver_spec (spec);
1931
1932                   if (!rc)
1933                     break;
1934                 }
1935             }
1936         }
1937     }
1938
1939   /* If the avove methods didn't work, our next try is to use the URI
1940    * from a DNS PKA record.  */
1941   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1942       && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
1943       && (opt.keyserver_options.options & KEYSERVER_HONOR_PKA_RECORD))
1944     {
1945       const char *uri = pka_uri_from_sig (c, sig);
1946
1947       if (uri)
1948         {
1949           /* FIXME: We might want to locate the key using the
1950              fingerprint instead of the keyid. */
1951           int res;
1952           struct keyserver_spec *spec;
1953
1954           spec = parse_keyserver_uri (uri, 1);
1955           if (spec)
1956             {
1957               free_public_key (pk);
1958               pk = NULL;
1959               glo_ctrl.in_auto_key_retrieve++;
1960               res = keyserver_import_keyid (c->ctrl, sig->keyid, spec, 1);
1961               glo_ctrl.in_auto_key_retrieve--;
1962               free_keyserver_spec (spec);
1963               if (!res)
1964                 rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey, &pk);
1965             }
1966         }
1967     }
1968
1969   /* If the above methods didn't work, our next try is to locate
1970    * the key via its fingerprint from a keyserver.  This requires
1971    * that the signers fingerprint is encoded in the signature.  We
1972    * favor this over the WKD method (to be tried next), because an
1973    * arbitrary keyserver is less subject to web bug like monitoring.  */
1974   tried_ks_by_fpr = 0;
1975   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1976       && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
1977       && keyserver_any_configured (c->ctrl))
1978     {
1979       int res;
1980       const byte *p;
1981       size_t n;
1982
1983       p = issuer_fpr_raw (sig, &n);
1984       if (p)
1985         {
1986           /* v4 packet with a SHA-1 fingerprint.  */
1987           free_public_key (pk);
1988           pk = NULL;
1989           glo_ctrl.in_auto_key_retrieve++;
1990           res = keyserver_import_fprint (c->ctrl, p, n, opt.keyserver, 1);
1991           tried_ks_by_fpr = 1;
1992           glo_ctrl.in_auto_key_retrieve--;
1993           if (!res)
1994             rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey, &pk);
1995         }
1996     }
1997
1998   /* If the above methods didn't work, our next try is to retrieve the
1999    * key from the WKD. */
2000   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2001       && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
2002       && !opt.flags.disable_signer_uid
2003       && akl_has_wkd_method ()
2004       && sig->signers_uid)
2005     {
2006       int res;
2007
2008       free_public_key (pk);
2009       pk = NULL;
2010       glo_ctrl.in_auto_key_retrieve++;
2011       res = keyserver_import_wkd (c->ctrl, sig->signers_uid, 1, NULL, NULL);
2012       glo_ctrl.in_auto_key_retrieve--;
2013       /* Fixme: If the fingerprint is embedded in the signature,
2014        * compare it to the fingerprint of the returned key.  */
2015       if (!res)
2016         rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey, &pk);
2017     }
2018
2019   /* If the above methods did't work, our next try is to use a
2020    * keyserver.  */
2021   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2022       && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
2023       && !tried_ks_by_fpr
2024       && keyserver_any_configured (c->ctrl))
2025     {
2026       int res;
2027
2028       free_public_key (pk);
2029       pk = NULL;
2030       glo_ctrl.in_auto_key_retrieve++;
2031       res = keyserver_import_keyid (c->ctrl, sig->keyid, opt.keyserver, 1);
2032       glo_ctrl.in_auto_key_retrieve--;
2033       if (!res)
2034         rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey, &pk);
2035     }
2036
2037   if (!rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
2038     {
2039       kbnode_t un, keyblock;
2040       int count = 0;
2041       int statno;
2042       char keyid_str[50];
2043       PKT_public_key *mainpk = NULL;
2044
2045       if (rc)
2046         statno = STATUS_BADSIG;
2047       else if (sig->flags.expired)
2048         statno = STATUS_EXPSIG;
2049       else if (is_expkey)
2050         statno = STATUS_EXPKEYSIG;
2051       else if(is_revkey)
2052         statno = STATUS_REVKEYSIG;
2053       else
2054         statno = STATUS_GOODSIG;
2055
2056       /* FIXME: We should have the public key in PK and thus the
2057        * keyblock has already been fetched.  Thus we could use the
2058        * fingerprint or PK itself to lookup the entire keyblock.  That
2059        * would best be done with a cache.  */
2060       keyblock = get_pubkeyblock_for_sig (c->ctrl, sig);
2061
2062       snprintf (keyid_str, sizeof keyid_str, "%08lX%08lX [uncertain] ",
2063                 (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
2064
2065       /* Find and print the primary user ID along with the
2066          "Good|Expired|Bad signature" line.  */
2067       for (un=keyblock; un; un = un->next)
2068         {
2069           int valid;
2070
2071           if (un->pkt->pkttype==PKT_PUBLIC_KEY)
2072             {
2073               mainpk = un->pkt->pkt.public_key;
2074               continue;
2075             }
2076           if (un->pkt->pkttype != PKT_USER_ID)
2077             continue;
2078           if (!un->pkt->pkt.user_id->created)
2079             continue;
2080           if (un->pkt->pkt.user_id->flags.revoked)
2081             continue;
2082           if (un->pkt->pkt.user_id->flags.expired)
2083             continue;
2084           if (!un->pkt->pkt.user_id->flags.primary)
2085             continue;
2086           /* We want the textual primary user ID here */
2087           if (un->pkt->pkt.user_id->attrib_data)
2088             continue;
2089
2090           log_assert (mainpk);
2091
2092           /* Since this is just informational, don't actually ask the
2093              user to update any trust information.  (Note: we register
2094              the signature later.)  Because print_good_bad_signature
2095              does not print a LF we need to compute the validity
2096              before calling that function.  */
2097           if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2098             valid = get_validity (c->ctrl, keyblock, mainpk,
2099                                   un->pkt->pkt.user_id, NULL, 0);
2100           else
2101             valid = 0; /* Not used.  */
2102
2103           keyid_str[17] = 0; /* cut off the "[uncertain]" part */
2104
2105           print_good_bad_signature (statno, keyid_str, un, sig, rc);
2106
2107           if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2108             log_printf (" [%s]\n",trust_value_to_string(valid));
2109           else
2110             log_printf ("\n");
2111
2112           count++;
2113         }
2114
2115       log_assert (mainpk);
2116
2117       /* In case we did not found a valid textual userid above
2118          we print the first user id packet or a "[?]" instead along
2119          with the "Good|Expired|Bad signature" line.  */
2120       if (!count)
2121         {
2122           /* Try for an invalid textual userid */
2123           for (un=keyblock; un; un = un->next)
2124             {
2125               if (un->pkt->pkttype == PKT_USER_ID
2126                   && !un->pkt->pkt.user_id->attrib_data)
2127                 break;
2128             }
2129
2130           /* Try for any userid at all */
2131           if (!un)
2132             {
2133               for (un=keyblock; un; un = un->next)
2134                 {
2135                   if (un->pkt->pkttype == PKT_USER_ID)
2136                     break;
2137                 }
2138             }
2139
2140           if (opt.trust_model==TM_ALWAYS || !un)
2141             keyid_str[17] = 0; /* cut off the "[uncertain]" part */
2142
2143           print_good_bad_signature (statno, keyid_str, un, sig, rc);
2144
2145           if (opt.trust_model != TM_ALWAYS && un)
2146             log_printf (" %s",_("[uncertain]") );
2147           log_printf ("\n");
2148         }
2149
2150       /* If we have a good signature and already printed
2151        * the primary user ID, print all the other user IDs */
2152       if (count
2153           && !rc
2154           && !(opt.verify_options & VERIFY_SHOW_PRIMARY_UID_ONLY))
2155         {
2156           char *p;
2157           for( un=keyblock; un; un = un->next)
2158             {
2159               if (un->pkt->pkttype != PKT_USER_ID)
2160                 continue;
2161               if ((un->pkt->pkt.user_id->flags.revoked
2162                    || un->pkt->pkt.user_id->flags.expired)
2163                   && !(opt.verify_options & VERIFY_SHOW_UNUSABLE_UIDS))
2164                 continue;
2165               /* Skip textual primary user ids which we printed above. */
2166               if (un->pkt->pkt.user_id->flags.primary
2167                   && !un->pkt->pkt.user_id->attrib_data )
2168                 continue;
2169
2170               /* If this user id has attribute data, print that.  */
2171               if (un->pkt->pkt.user_id->attrib_data)
2172                 {
2173                   dump_attribs (un->pkt->pkt.user_id, mainpk);
2174
2175                   if (opt.verify_options&VERIFY_SHOW_PHOTOS)
2176                     show_photos (c->ctrl,
2177                                  un->pkt->pkt.user_id->attribs,
2178                                  un->pkt->pkt.user_id->numattribs,
2179                                  mainpk ,un->pkt->pkt.user_id);
2180                 }
2181
2182               p = utf8_to_native (un->pkt->pkt.user_id->name,
2183                                   un->pkt->pkt.user_id->len, 0);
2184               log_info (_("                aka \"%s\""), p);
2185               xfree (p);
2186
2187               if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2188                 {
2189                   const char *valid;
2190
2191                   if (un->pkt->pkt.user_id->flags.revoked)
2192                     valid = _("revoked");
2193                   else if (un->pkt->pkt.user_id->flags.expired)
2194                     valid = _("expired");
2195                   else
2196                     /* Since this is just informational, don't
2197                        actually ask the user to update any trust
2198                        information.  */
2199                     valid = (trust_value_to_string
2200                              (get_validity (c->ctrl, keyblock, mainpk,
2201                                             un->pkt->pkt.user_id, NULL, 0)));
2202                   log_printf (" [%s]\n",valid);
2203                 }
2204               else
2205                 log_printf ("\n");
2206             }
2207         }
2208
2209       /* For good signatures print notation data.  */
2210       if (!rc)
2211         {
2212           if ((opt.verify_options & VERIFY_SHOW_POLICY_URLS))
2213             show_policy_url (sig, 0, 1);
2214           else
2215             show_policy_url (sig, 0, 2);
2216
2217           if ((opt.verify_options & VERIFY_SHOW_KEYSERVER_URLS))
2218             show_keyserver_url (sig, 0, 1);
2219           else
2220             show_keyserver_url (sig, 0, 2);
2221
2222           if ((opt.verify_options & VERIFY_SHOW_NOTATIONS))
2223             show_notation
2224               (sig, 0, 1,
2225                (((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0)
2226                 + ((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0)));
2227           else
2228             show_notation (sig, 0, 2, 0);
2229         }
2230
2231       /* For good signatures print the VALIDSIG status line.  */
2232       if (!rc && is_status_enabled () && pk)
2233         {
2234           char pkhex[MAX_FINGERPRINT_LEN*2+1];
2235           char mainpkhex[MAX_FINGERPRINT_LEN*2+1];
2236
2237           hexfingerprint (pk, pkhex, sizeof pkhex);
2238           hexfingerprint (mainpk, mainpkhex, sizeof mainpkhex);
2239
2240           /* TODO: Replace the reserved '0' in the field below with
2241              bits for status flags (policy url, notation, etc.).  */
2242           write_status_printf (STATUS_VALIDSIG,
2243                                "%s %s %lu %lu %d 0 %d %d %02X %s",
2244                                pkhex,
2245                                strtimestamp (sig->timestamp),
2246                                (ulong)sig->timestamp,
2247                                (ulong)sig->expiredate,
2248                                sig->version, sig->pubkey_algo,
2249                                sig->digest_algo,
2250                                sig->sig_class,
2251                                mainpkhex);
2252         }
2253
2254       /* Print compliance warning for Good signatures.  */
2255       if (!rc && pk && !opt.quiet
2256           && !gnupg_pk_is_compliant (opt.compliance, pk->pubkey_algo,
2257                                      pk->pkey, nbits_from_pk (pk), NULL))
2258         {
2259           log_info (_("WARNING: This key is not suitable for signing"
2260                       " in %s mode\n"),
2261                     gnupg_compliance_option_string (opt.compliance));
2262         }
2263
2264       /* For good signatures compute and print the trust information.
2265          Note that in the Tofu trust model this may ask the user on
2266          how to resolve a conflict.  */
2267       if (!rc)
2268         {
2269           if ((opt.verify_options & VERIFY_PKA_LOOKUPS))
2270             pka_uri_from_sig (c, sig); /* Make sure PKA info is available. */
2271           rc = check_signatures_trust (c->ctrl, sig);
2272         }
2273
2274       /* Print extra information about the signature.  */
2275       if (sig->flags.expired)
2276         {
2277           log_info (_("Signature expired %s\n"), asctimestamp(sig->expiredate));
2278           rc = GPG_ERR_GENERAL; /* Need a better error here?  */
2279         }
2280       else if (sig->expiredate)
2281         log_info (_("Signature expires %s\n"), asctimestamp(sig->expiredate));
2282
2283       if (opt.verbose)
2284         {
2285           char pkstrbuf[PUBKEY_STRING_SIZE];
2286
2287           if (pk)
2288             pubkey_string (pk, pkstrbuf, sizeof pkstrbuf);
2289           else
2290             *pkstrbuf = 0;
2291
2292           log_info (_("%s signature, digest algorithm %s%s%s\n"),
2293                     sig->sig_class==0x00?_("binary"):
2294                     sig->sig_class==0x01?_("textmode"):_("unknown"),
2295                     gcry_md_algo_name (sig->digest_algo),
2296                     *pkstrbuf?_(", key algorithm "):"", pkstrbuf);
2297         }
2298
2299       /* Print final warnings.  */
2300       if (!rc && !c->signed_data.used)
2301         {
2302           /* Signature is basically good but we test whether the
2303              deprecated command
2304                gpg --verify FILE.sig
2305              was used instead of
2306                gpg --verify FILE.sig FILE
2307              to verify a detached signature.  If we figure out that a
2308              data file with a matching name exists, we print a warning.
2309
2310              The problem is that the first form would also verify a
2311              standard signature.  This behavior could be used to
2312              create a made up .sig file for a tarball by creating a
2313              standard signature from a valid detached signature packet
2314              (for example from a signed git tag).  Then replace the
2315              sig file on the FTP server along with a changed tarball.
2316              Using the first form the verify command would correctly
2317              verify the signature but don't even consider the tarball.  */
2318           kbnode_t n;
2319           char *dfile;
2320
2321           dfile = get_matching_datafile (c->sigfilename);
2322           if (dfile)
2323             {
2324               for (n = c->list; n; n = n->next)
2325                 if (n->pkt->pkttype != PKT_SIGNATURE)
2326                   break;
2327               if (n)
2328                 {
2329                   /* Not only signature packets in the tree thus this
2330                      is not a detached signature.  */
2331                   log_info (_("WARNING: not a detached signature; "
2332                               "file '%s' was NOT verified!\n"), dfile);
2333                 }
2334               xfree (dfile);
2335             }
2336         }
2337
2338       /* Compute compliance with CO_DE_VS.  */
2339       if (pk && is_status_enabled ()
2340           && gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, pk->pkey,
2341                                     nbits_from_pk (pk), NULL)
2342           && gnupg_digest_is_compliant (CO_DE_VS, sig->digest_algo))
2343         write_status_strings (STATUS_VERIFICATION_COMPLIANCE_MODE,
2344                               gnupg_status_compliance_flag (CO_DE_VS),
2345                               NULL);
2346
2347       free_public_key (pk);
2348       pk = NULL;
2349       release_kbnode( keyblock );
2350       if (rc)
2351         g10_errors_seen = 1;
2352       if (opt.batch && rc)
2353         g10_exit (1);
2354     }
2355   else
2356     {
2357       write_status_printf (STATUS_ERRSIG, "%08lX%08lX %d %d %02x %lu %d %s",
2358                            (ulong)sig->keyid[0], (ulong)sig->keyid[1],
2359                            sig->pubkey_algo, sig->digest_algo,
2360                            sig->sig_class, (ulong)sig->timestamp,
2361                            gpg_err_code (rc),
2362                            issuer_fpr? issuer_fpr:"-");
2363       if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2364         {
2365           write_status_printf (STATUS_NO_PUBKEY, "%08lX%08lX",
2366                                (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
2367         }
2368       if (gpg_err_code (rc) != GPG_ERR_NOT_PROCESSED)
2369         log_error (_("Can't check signature: %s\n"), gpg_strerror (rc));
2370     }
2371
2372   free_public_key (pk);
2373   xfree (issuer_fpr);
2374   return rc;
2375 }
2376
2377
2378 /*
2379  * Process the tree which starts at node
2380  */
2381 static void
2382 proc_tree (CTX c, kbnode_t node)
2383 {
2384   kbnode_t n1;
2385   int rc;
2386
2387   if (opt.list_packets || opt.list_only)
2388     return;
2389
2390   /* We must skip our special plaintext marker packets here because
2391      they may be the root packet.  These packets are only used in
2392      additional checks and skipping them here doesn't matter.  */
2393   while (node
2394          && node->pkt->pkttype == PKT_GPG_CONTROL
2395           && node->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK)
2396     {
2397       node = node->next;
2398     }
2399   if (!node)
2400     return;
2401
2402   c->trustletter = ' ';
2403   if (node->pkt->pkttype == PKT_PUBLIC_KEY
2404       || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2405     {
2406       merge_keys_and_selfsig (c->ctrl, node);
2407       list_node (c, node);
2408     }
2409   else if (node->pkt->pkttype == PKT_SECRET_KEY)
2410     {
2411       merge_keys_and_selfsig (c->ctrl, node);
2412       list_node (c, node);
2413     }
2414   else if (node->pkt->pkttype == PKT_ONEPASS_SIG)
2415     {
2416       /* Check all signatures.  */
2417       if (!c->any.data)
2418         {
2419           int use_textmode = 0;
2420
2421           free_md_filter_context (&c->mfx);
2422           /* Prepare to create all requested message digests.  */
2423           rc = gcry_md_open (&c->mfx.md, 0, 0);
2424           if (rc)
2425             goto hash_err;
2426
2427           /* Fixme: why looking for the signature packet and not the
2428              one-pass packet?  */
2429           for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2430             gcry_md_enable (c->mfx.md, n1->pkt->pkt.signature->digest_algo);
2431
2432           if (n1 && n1->pkt->pkt.onepass_sig->sig_class == 0x01)
2433             use_textmode = 1;
2434
2435           /* Ask for file and hash it. */
2436           if (c->sigs_only)
2437             {
2438               if (c->signed_data.used && c->signed_data.data_fd != -1)
2439                 rc = hash_datafile_by_fd (c->mfx.md, NULL,
2440                                           c->signed_data.data_fd,
2441                                           use_textmode);
2442               else
2443                 rc = hash_datafiles (c->mfx.md, NULL,
2444                                      c->signed_data.data_names,
2445                                      c->sigfilename,
2446                                      use_textmode);
2447             }
2448           else
2449             {
2450               rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
2451                                               iobuf_get_real_fname (c->iobuf),
2452                                               use_textmode);
2453             }
2454
2455         hash_err:
2456           if (rc)
2457             {
2458               log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
2459               return;
2460             }
2461         }
2462       else if (c->signed_data.used)
2463         {
2464           log_error (_("not a detached signature\n"));
2465           return;
2466         }
2467
2468       for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2469         check_sig_and_print (c, n1);
2470
2471     }
2472   else if (node->pkt->pkttype == PKT_GPG_CONTROL
2473            && node->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START)
2474     {
2475       /* Clear text signed message.  */
2476       if (!c->any.data)
2477         {
2478           log_error ("cleartext signature without data\n");
2479           return;
2480         }
2481       else if (c->signed_data.used)
2482         {
2483           log_error (_("not a detached signature\n"));
2484           return;
2485         }
2486
2487       for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2488         check_sig_and_print (c, n1);
2489
2490     }
2491   else if (node->pkt->pkttype == PKT_SIGNATURE)
2492     {
2493       PKT_signature *sig = node->pkt->pkt.signature;
2494       int multiple_ok = 1;
2495
2496       n1 = find_next_kbnode (node, PKT_SIGNATURE);
2497       if (n1)
2498         {
2499           byte class = sig->sig_class;
2500           byte hash  = sig->digest_algo;
2501
2502           for (; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
2503             {
2504               /* We can't currently handle multiple signatures of
2505                * different classes (we'd pretty much have to run a
2506                * different hash context for each), but if they are all
2507                * the same and it is detached signature, we make an
2508                * exception.  Note that the old code also disallowed
2509                * multiple signatures if the digest algorithms are
2510                * different.  We softened this restriction only for
2511                * detached signatures, to be on the safe side. */
2512               if (n1->pkt->pkt.signature->sig_class != class
2513                   || (c->any.data
2514                       && n1->pkt->pkt.signature->digest_algo != hash))
2515                 {
2516                   multiple_ok = 0;
2517                   log_info (_("WARNING: multiple signatures detected.  "
2518                               "Only the first will be checked.\n"));
2519                   break;
2520                 }
2521             }
2522         }
2523
2524       if (sig->sig_class != 0x00 && sig->sig_class != 0x01)
2525         {
2526           log_info(_("standalone signature of class 0x%02x\n"), sig->sig_class);
2527         }
2528       else if (!c->any.data)
2529         {
2530           /* Detached signature */
2531           free_md_filter_context (&c->mfx);
2532           rc = gcry_md_open (&c->mfx.md, sig->digest_algo, 0);
2533           if (rc)
2534             goto detached_hash_err;
2535
2536           if (multiple_ok)
2537             {
2538               /* If we have and want to handle multiple signatures we
2539                * need to enable all hash algorithms for the context.  */
2540               for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE)); )
2541                 if (!openpgp_md_test_algo (n1->pkt->pkt.signature->digest_algo))
2542                   gcry_md_enable (c->mfx.md,
2543                                   map_md_openpgp_to_gcry
2544                                   (n1->pkt->pkt.signature->digest_algo));
2545             }
2546
2547           if (RFC2440 || RFC4880)
2548             ; /* Strict RFC mode.  */
2549           else if (sig->digest_algo == DIGEST_ALGO_SHA1
2550                    && sig->pubkey_algo == PUBKEY_ALGO_DSA
2551                    && sig->sig_class == 0x01)
2552             {
2553               /* Enable a workaround for a pgp5 bug when the detached
2554                * signature has been created in textmode.  Note that we
2555                * do not implement this for multiple signatures with
2556                * different hash algorithms. */
2557               rc = gcry_md_open (&c->mfx.md2, sig->digest_algo, 0);
2558               if (rc)
2559                 goto detached_hash_err;
2560             }
2561
2562           /* Here we used to have another hack to work around a pgp
2563            * 2 bug: It worked by not using the textmode for detached
2564            * signatures; this would let the first signature check
2565            * (on md) fail but the second one (on md2), which adds an
2566            * extra CR would then have produced the "correct" hash.
2567            * This is very, very ugly hack but it may haved help in
2568            * some cases (and break others).
2569            *     c->mfx.md2? 0 :(sig->sig_class == 0x01)
2570            */
2571
2572           if (DBG_HASHING)
2573             {
2574               gcry_md_debug (c->mfx.md, "verify");
2575               if (c->mfx.md2)
2576                 gcry_md_debug (c->mfx.md2, "verify2");
2577             }
2578
2579           if (c->sigs_only)
2580             {
2581               if (c->signed_data.used && c->signed_data.data_fd != -1)
2582                 rc = hash_datafile_by_fd (c->mfx.md, c->mfx.md2,
2583                                           c->signed_data.data_fd,
2584                                           (sig->sig_class == 0x01));
2585               else
2586                 rc = hash_datafiles (c->mfx.md, c->mfx.md2,
2587                                      c->signed_data.data_names,
2588                                      c->sigfilename,
2589                                      (sig->sig_class == 0x01));
2590             }
2591           else
2592             {
2593               rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
2594                                               iobuf_get_real_fname(c->iobuf),
2595                                               (sig->sig_class == 0x01));
2596             }
2597
2598         detached_hash_err:
2599           if (rc)
2600             {
2601               log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
2602               return;
2603             }
2604         }
2605       else if (c->signed_data.used)
2606         {
2607           log_error (_("not a detached signature\n"));
2608           return;
2609         }
2610       else if (!opt.quiet)
2611         log_info (_("old style (PGP 2.x) signature\n"));
2612
2613       if (multiple_ok)
2614         {
2615           for (n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
2616             check_sig_and_print (c, n1);
2617         }
2618       else
2619         check_sig_and_print (c, node);
2620
2621     }
2622   else
2623     {
2624       dump_kbnode (c->list);
2625       log_error ("invalid root packet detected in proc_tree()\n");
2626       dump_kbnode (node);
2627     }
2628 }