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