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