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