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