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