Imported Upstream version 2.2.39
[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       compliance_failure ();
948     }
949 }
950
951
952 static int
953 have_seen_pkt_encrypted_aead_or_mdc( CTX c )
954 {
955   CTX cc;
956
957   for (cc = c; cc; cc = cc->anchor)
958     {
959       if (cc->seen_pkt_encrypted_aead)
960         return 1;
961       if (cc->seen_pkt_encrypted_mdc)
962         return 1;
963     }
964
965   return 0;
966 }
967
968
969 static void
970 proc_plaintext( CTX c, PACKET *pkt )
971 {
972   PKT_plaintext *pt = pkt->pkt.plaintext;
973   int any, clearsig, rc;
974   kbnode_t n;
975
976   /* This is a literal data packet.  Bumb a counter for later checks.  */
977   literals_seen++;
978
979   if (pt->namelen == 8 && !memcmp( pt->name, "_CONSOLE", 8))
980     log_info (_("Note: sender requested \"for-your-eyes-only\"\n"));
981   else if (opt.verbose)
982     {
983       /* We don't use print_utf8_buffer because that would require a
984        * string change which we don't want in 2.2.  It is also not
985        * clear whether the filename is always utf-8 encoded.  */
986       char *tmp = make_printable_string (pt->name, pt->namelen, 0);
987       log_info (_("original file name='%.*s'\n"), (int)strlen (tmp), tmp);
988       xfree (tmp);
989     }
990
991   free_md_filter_context (&c->mfx);
992   if (gcry_md_open (&c->mfx.md, 0, 0))
993     BUG ();
994   /* fixme: we may need to push the textfilter if we have sigclass 1
995    * and no armoring - Not yet tested
996    * Hmmm, why don't we need it at all if we have sigclass 1
997    * Should we assume that plaintext in mode 't' has always sigclass 1??
998    * See: Russ Allbery's mail 1999-02-09
999    */
1000   any = clearsig = 0;
1001   for (n=c->list; n; n = n->next )
1002     {
1003       if (n->pkt->pkttype == PKT_ONEPASS_SIG)
1004         {
1005           /* The onepass signature case. */
1006           if (n->pkt->pkt.onepass_sig->digest_algo)
1007             {
1008               if (!opt.skip_verify)
1009                 gcry_md_enable (c->mfx.md,
1010                                 n->pkt->pkt.onepass_sig->digest_algo);
1011
1012               any = 1;
1013             }
1014         }
1015       else if (n->pkt->pkttype == PKT_GPG_CONTROL
1016                && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START)
1017         {
1018           /* The clearsigned message case. */
1019           size_t datalen = n->pkt->pkt.gpg_control->datalen;
1020           const byte *data = n->pkt->pkt.gpg_control->data;
1021
1022           /* Check that we have at least the sigclass and one hash.  */
1023           if  (datalen < 2)
1024             log_fatal ("invalid control packet CTRLPKT_CLEARSIGN_START\n");
1025           /* Note that we don't set the clearsig flag for not-dash-escaped
1026            * documents.  */
1027           clearsig = (*data == 0x01);
1028           for (data++, datalen--; datalen; datalen--, data++)
1029             if (!opt.skip_verify)
1030               gcry_md_enable (c->mfx.md, *data);
1031           any = 1;
1032           break;  /* Stop here as one-pass signature packets are not
1033                      expected.  */
1034         }
1035       else if (n->pkt->pkttype == PKT_SIGNATURE)
1036         {
1037           /* The SIG+LITERAL case that PGP used to use.  */
1038           if (!opt.skip_verify)
1039             gcry_md_enable (c->mfx.md, n->pkt->pkt.signature->digest_algo);
1040           any = 1;
1041         }
1042     }
1043
1044   if (!any && !opt.skip_verify && !have_seen_pkt_encrypted_aead_or_mdc(c))
1045     {
1046       /* This is for the old GPG LITERAL+SIG case.  It's not legal
1047          according to 2440, so hopefully it won't come up that often.
1048          There is no good way to specify what algorithms to use in
1049          that case, so these there are the historical answer. */
1050         gcry_md_enable (c->mfx.md, DIGEST_ALGO_RMD160);
1051         gcry_md_enable (c->mfx.md, DIGEST_ALGO_SHA1);
1052     }
1053   if (DBG_HASHING)
1054     {
1055       gcry_md_debug (c->mfx.md, "verify");
1056       if (c->mfx.md2)
1057         gcry_md_debug (c->mfx.md2, "verify2");
1058     }
1059
1060   rc=0;
1061
1062   if (literals_seen > 1)
1063     {
1064       log_info (_("WARNING: multiple plaintexts seen\n"));
1065
1066       if (!opt.flags.allow_multiple_messages)
1067         {
1068           write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA");
1069           log_inc_errorcount ();
1070           rc = gpg_error (GPG_ERR_UNEXPECTED);
1071         }
1072     }
1073
1074   if (!rc)
1075     {
1076       /* It we are in --verify mode, we do not want to output the
1077        * signed text.  However, if --output is also used we do what
1078        * has been requested and write out the signed data.  */
1079       rc = handle_plaintext (pt, &c->mfx,
1080                              (opt.outfp || opt.outfile)? 0 :  c->sigs_only,
1081                              clearsig);
1082       if (gpg_err_code (rc) == GPG_ERR_EACCES && !c->sigs_only)
1083         {
1084           /* Can't write output but we hash it anyway to check the
1085              signature. */
1086           rc = handle_plaintext( pt, &c->mfx, 1, clearsig );
1087         }
1088     }
1089
1090   if (rc)
1091     log_error ("handle plaintext failed: %s\n", gpg_strerror (rc));
1092
1093   free_packet (pkt, NULL);
1094   c->last_was_session_key = 0;
1095
1096   /* We add a marker control packet instead of the plaintext packet.
1097    * This is so that we can later detect invalid packet sequences.  */
1098   n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK, NULL, 0));
1099   if (c->list)
1100     add_kbnode (c->list, n);
1101   else
1102     c->list = n;
1103 }
1104
1105
1106 static int
1107 proc_compressed_cb (iobuf_t a, void *info)
1108 {
1109   if ( ((CTX)info)->signed_data.used
1110        && ((CTX)info)->signed_data.data_fd != -1)
1111     return proc_signature_packets_by_fd (((CTX)info)->ctrl, info, a,
1112                                          ((CTX)info)->signed_data.data_fd);
1113   else
1114     return proc_signature_packets (((CTX)info)->ctrl, info, a,
1115                                    ((CTX)info)->signed_data.data_names,
1116                                    ((CTX)info)->sigfilename );
1117 }
1118
1119
1120 static int
1121 proc_encrypt_cb (iobuf_t a, void *info )
1122 {
1123   CTX c = info;
1124   return proc_encryption_packets (c->ctrl, info, a );
1125 }
1126
1127
1128 static int
1129 proc_compressed (CTX c, PACKET *pkt)
1130 {
1131   PKT_compressed *zd = pkt->pkt.compressed;
1132   int rc;
1133
1134   /*printf("zip: compressed data packet\n");*/
1135   if (c->sigs_only)
1136     rc = handle_compressed (c->ctrl, c, zd, proc_compressed_cb, c);
1137   else if( c->encrypt_only )
1138     rc = handle_compressed (c->ctrl, c, zd, proc_encrypt_cb, c);
1139   else
1140     rc = handle_compressed (c->ctrl, c, zd, NULL, NULL);
1141
1142   if (gpg_err_code (rc) == GPG_ERR_BAD_DATA)
1143     {
1144       if  (!c->any.uncompress_failed)
1145         {
1146           CTX cc;
1147
1148           for (cc=c; cc; cc = cc->anchor)
1149             cc->any.uncompress_failed = 1;
1150           log_error ("uncompressing failed: %s\n", gpg_strerror (rc));
1151         }
1152     }
1153   else if (rc)
1154     log_error ("uncompressing failed: %s\n", gpg_strerror (rc));
1155
1156   free_packet (pkt, NULL);
1157   c->last_was_session_key = 0;
1158   return rc;
1159 }
1160
1161
1162 /*
1163  * Check the signature.  If R_PK is not NULL a copy of the public key
1164  * used to verify the signature will be stored there, or NULL if not
1165  * found.  If FORCED_PK is not NULL, this public key is used to verify
1166  * _data signatures_ and no key lookup is done.  Returns: 0 = valid
1167  * signature or an error code
1168  */
1169 static int
1170 do_check_sig (CTX c, kbnode_t node,
1171               PKT_public_key *forced_pk, int *is_selfsig,
1172               int *is_expkey, int *is_revkey, PKT_public_key **r_pk)
1173 {
1174   PKT_signature *sig;
1175   gcry_md_hd_t md = NULL;
1176   gcry_md_hd_t md2 = NULL;
1177   gcry_md_hd_t md_good = NULL;
1178   int algo, rc;
1179
1180   if (r_pk)
1181     *r_pk = NULL;
1182
1183   log_assert (node->pkt->pkttype == PKT_SIGNATURE);
1184   if (is_selfsig)
1185     *is_selfsig = 0;
1186   sig = node->pkt->pkt.signature;
1187
1188   algo = sig->digest_algo;
1189   rc = openpgp_md_test_algo (algo);
1190   if (rc)
1191     return rc;
1192
1193   if (sig->sig_class == 0x00)
1194     {
1195       if (c->mfx.md)
1196         {
1197           if (gcry_md_copy (&md, c->mfx.md ))
1198             BUG ();
1199         }
1200       else /* detached signature */
1201         {
1202           /* check_signature() will enable the md. */
1203           if (gcry_md_open (&md, 0, 0 ))
1204             BUG ();
1205         }
1206     }
1207   else if (sig->sig_class == 0x01)
1208     {
1209       /* How do we know that we have to hash the (already hashed) text
1210          in canonical mode ??? (calculating both modes???) */
1211       if (c->mfx.md)
1212         {
1213           if (gcry_md_copy (&md, c->mfx.md ))
1214             BUG ();
1215           if (c->mfx.md2 && gcry_md_copy (&md2, c->mfx.md2))
1216             BUG ();
1217         }
1218       else /* detached signature */
1219         {
1220           log_debug ("Do we really need this here?");
1221           /* check_signature() will enable the md*/
1222           if (gcry_md_open (&md, 0, 0 ))
1223             BUG ();
1224           if (gcry_md_open (&md2, 0, 0 ))
1225             BUG ();
1226         }
1227     }
1228   else if ((sig->sig_class&~3) == 0x10
1229            ||   sig->sig_class == 0x18
1230            ||   sig->sig_class == 0x1f
1231            ||   sig->sig_class == 0x20
1232            ||   sig->sig_class == 0x28
1233            ||   sig->sig_class == 0x30)
1234     {
1235       if (c->list->pkt->pkttype == PKT_PUBLIC_KEY
1236           || c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1237         {
1238           return check_key_signature (c->ctrl, c->list, node, is_selfsig);
1239         }
1240       else if (sig->sig_class == 0x20)
1241         {
1242           log_error (_("standalone revocation - "
1243                        "use \"gpg --import\" to apply\n"));
1244           return GPG_ERR_NOT_PROCESSED;
1245         }
1246       else
1247         {
1248           log_error ("invalid root packet for sigclass %02x\n", sig->sig_class);
1249           return GPG_ERR_SIG_CLASS;
1250         }
1251     }
1252   else
1253     return GPG_ERR_SIG_CLASS;
1254
1255   /* We only get here if we are checking the signature of a binary
1256      (0x00) or text document (0x01).  */
1257   rc = check_signature2 (c->ctrl, sig, md,
1258                          forced_pk,
1259                          NULL, is_expkey, is_revkey, r_pk);
1260   if (! rc)
1261     md_good = md;
1262   else if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE && md2)
1263     {
1264       PKT_public_key *pk2;
1265
1266       rc = check_signature2 (c->ctrl, sig, md2,
1267                              forced_pk,
1268                              NULL, is_expkey, is_revkey,
1269                              r_pk? &pk2 : NULL);
1270       if (!rc)
1271         {
1272           md_good = md2;
1273           if (r_pk)
1274             {
1275               free_public_key (*r_pk);
1276               *r_pk = pk2;
1277             }
1278         }
1279     }
1280
1281   if (md_good)
1282     {
1283       unsigned char *buffer = gcry_md_read (md_good, sig->digest_algo);
1284       sig->digest_len = gcry_md_get_algo_dlen (map_md_openpgp_to_gcry (algo));
1285       memcpy (sig->digest, buffer, sig->digest_len);
1286     }
1287
1288   gcry_md_close (md);
1289   gcry_md_close (md2);
1290
1291   return rc;
1292 }
1293
1294
1295 static void
1296 print_userid (PACKET *pkt)
1297 {
1298   if (!pkt)
1299     BUG();
1300
1301   if (pkt->pkttype != PKT_USER_ID)
1302     {
1303       es_printf ("ERROR: unexpected packet type %d", pkt->pkttype );
1304       return;
1305     }
1306   if (opt.with_colons)
1307     {
1308       if (pkt->pkt.user_id->attrib_data)
1309         es_printf("%u %lu",
1310                   pkt->pkt.user_id->numattribs,
1311                   pkt->pkt.user_id->attrib_len);
1312       else
1313         es_write_sanitized (es_stdout, pkt->pkt.user_id->name,
1314                             pkt->pkt.user_id->len, ":", NULL);
1315     }
1316   else
1317     print_utf8_buffer (es_stdout, pkt->pkt.user_id->name,
1318                        pkt->pkt.user_id->len );
1319 }
1320
1321
1322 /*
1323  * List the keyblock in a user friendly way
1324  */
1325 static void
1326 list_node (CTX c, kbnode_t node)
1327 {
1328   if (!node)
1329     ;
1330   else if (node->pkt->pkttype == PKT_PUBLIC_KEY
1331            || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1332     {
1333       PKT_public_key *pk = node->pkt->pkt.public_key;
1334
1335       if (opt.with_colons)
1336         {
1337           u32 keyid[2];
1338
1339           keyid_from_pk( pk, keyid );
1340           if (pk->flags.primary)
1341             c->trustletter = (opt.fast_list_mode
1342                               ? 0
1343                               : get_validity_info
1344                                   (c->ctrl,
1345                                    node->pkt->pkttype == PKT_PUBLIC_KEY
1346                                    ? node : NULL,
1347                                    pk, NULL));
1348           es_printf ("%s:", pk->flags.primary? "pub":"sub" );
1349           if (c->trustletter)
1350             es_putc (c->trustletter, es_stdout);
1351           es_printf (":%u:%d:%08lX%08lX:%s:%s::",
1352                      nbits_from_pk( pk ),
1353                      pk->pubkey_algo,
1354                      (ulong)keyid[0],(ulong)keyid[1],
1355                      colon_datestr_from_pk( pk ),
1356                      colon_strtime (pk->expiredate) );
1357           if (pk->flags.primary && !opt.fast_list_mode)
1358             es_putc (get_ownertrust_info (c->ctrl, pk, 1), es_stdout);
1359           es_putc (':', es_stdout);
1360           es_putc ('\n', es_stdout);
1361         }
1362       else
1363         {
1364           print_key_line (c->ctrl, es_stdout, pk, 0);
1365         }
1366
1367       if (opt.keyid_format == KF_NONE && !opt.with_colons)
1368         ; /* Already printed.  */
1369       else if ((pk->flags.primary && opt.fingerprint) || opt.fingerprint > 1)
1370         print_fingerprint (c->ctrl, NULL, pk, 0);
1371
1372       if (pk->flags.primary)
1373         {
1374           int kl = opt.keyid_format == KF_NONE? 0 : keystrlen ();
1375
1376           /* Now list all userids with their signatures. */
1377           for (node = node->next; node; node = node->next)
1378             {
1379               if (node->pkt->pkttype == PKT_SIGNATURE)
1380                 {
1381                   list_node (c,  node );
1382                 }
1383               else if (node->pkt->pkttype == PKT_USER_ID)
1384                 {
1385                   if (opt.with_colons)
1386                     es_printf ("%s:::::::::",
1387                                node->pkt->pkt.user_id->attrib_data?"uat":"uid");
1388                   else
1389                     es_printf ("uid%*s",
1390                                kl + (opt.legacy_list_mode? 9:11),
1391                                "" );
1392                   print_userid (node->pkt);
1393                   if (opt.with_colons)
1394                     es_putc (':', es_stdout);
1395                   es_putc ('\n', es_stdout);
1396                 }
1397               else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1398                 {
1399                   list_node(c,  node );
1400                 }
1401             }
1402         }
1403     }
1404   else if (node->pkt->pkttype == PKT_SECRET_KEY
1405            || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1406     {
1407
1408       log_debug ("FIXME: No way to print secret key packets here\n");
1409       /* fixme: We may use a function to turn a secret key packet into
1410          a public key one and use that here.  */
1411     }
1412   else if (node->pkt->pkttype == PKT_SIGNATURE)
1413     {
1414       PKT_signature *sig = node->pkt->pkt.signature;
1415       int is_selfsig = 0;
1416       int rc2 = 0;
1417       size_t n;
1418       char *p;
1419       int sigrc = ' ';
1420
1421       if (!opt.verbose)
1422         return;
1423
1424       if (sig->sig_class == 0x20 || sig->sig_class == 0x30)
1425         es_fputs ("rev", es_stdout);
1426       else
1427         es_fputs ("sig", es_stdout);
1428       if (opt.check_sigs)
1429         {
1430           fflush (stdout);
1431           rc2 = do_check_sig (c, node, NULL, &is_selfsig, NULL, NULL, NULL);
1432           switch (gpg_err_code (rc2))
1433             {
1434             case 0:                       sigrc = '!'; break;
1435             case GPG_ERR_BAD_SIGNATURE:   sigrc = '-'; break;
1436             case GPG_ERR_NO_PUBKEY:
1437             case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break;
1438             default:                      sigrc = '%'; break;
1439             }
1440         }
1441       else /* Check whether this is a self signature.  */
1442         {
1443           u32 keyid[2];
1444
1445           if (c->list->pkt->pkttype == PKT_PUBLIC_KEY
1446               || c->list->pkt->pkttype == PKT_SECRET_KEY )
1447             {
1448               keyid_from_pk (c->list->pkt->pkt.public_key, keyid);
1449
1450               if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1])
1451                 is_selfsig = 1;
1452             }
1453         }
1454
1455       if (opt.with_colons)
1456         {
1457           es_putc (':', es_stdout);
1458           if (sigrc != ' ')
1459             es_putc (sigrc, es_stdout);
1460           es_printf ("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo,
1461                      (ulong)sig->keyid[0], (ulong)sig->keyid[1],
1462                      colon_datestr_from_sig (sig),
1463                      colon_expirestr_from_sig (sig));
1464
1465           if (sig->trust_depth || sig->trust_value)
1466             es_printf ("%d %d",sig->trust_depth,sig->trust_value);
1467           es_putc (':', es_stdout);
1468
1469           if (sig->trust_regexp)
1470             es_write_sanitized (es_stdout, sig->trust_regexp,
1471                                 strlen (sig->trust_regexp), ":", NULL);
1472           es_putc (':', es_stdout);
1473         }
1474       else
1475         es_printf ("%c       %s %s   ",
1476                    sigrc, keystr (sig->keyid), datestr_from_sig(sig));
1477       if (sigrc == '%')
1478         es_printf ("[%s] ", gpg_strerror (rc2) );
1479       else if (sigrc == '?')
1480         ;
1481       else if (is_selfsig)
1482         {
1483           if (opt.with_colons)
1484             es_putc (':', es_stdout);
1485           es_fputs (sig->sig_class == 0x18? "[keybind]":"[selfsig]", es_stdout);
1486           if (opt.with_colons)
1487             es_putc (':', es_stdout);
1488         }
1489       else if (!opt.fast_list_mode)
1490         {
1491           p = get_user_id (c->ctrl, sig->keyid, &n, NULL);
1492           es_write_sanitized (es_stdout, p, n,
1493                               opt.with_colons?":":NULL, NULL );
1494           xfree (p);
1495         }
1496       if (opt.with_colons)
1497         es_printf (":%02x%c:", sig->sig_class, sig->flags.exportable?'x':'l');
1498       es_putc ('\n', es_stdout);
1499     }
1500   else
1501     log_error ("invalid node with packet of type %d\n", node->pkt->pkttype);
1502 }
1503
1504
1505 int
1506 proc_packets (ctrl_t ctrl, void *anchor, iobuf_t a )
1507 {
1508   int rc;
1509   CTX c = xmalloc_clear (sizeof *c);
1510
1511   c->ctrl = ctrl;
1512   c->anchor = anchor;
1513   rc = do_proc_packets (ctrl, c, a);
1514   xfree (c);
1515
1516   return rc;
1517 }
1518
1519
1520 int
1521 proc_signature_packets (ctrl_t ctrl, void *anchor, iobuf_t a,
1522                         strlist_t signedfiles, const char *sigfilename )
1523 {
1524   CTX c = xmalloc_clear (sizeof *c);
1525   int rc;
1526
1527   c->ctrl = ctrl;
1528   c->anchor = anchor;
1529   c->sigs_only = 1;
1530
1531   c->signed_data.data_fd = -1;
1532   c->signed_data.data_names = signedfiles;
1533   c->signed_data.used = !!signedfiles;
1534
1535   c->sigfilename = sigfilename;
1536   rc = do_proc_packets (ctrl, c, a);
1537
1538   /* If we have not encountered any signature we print an error
1539      messages, send a NODATA status back and return an error code.
1540      Using log_error is required because verify_files does not check
1541      error codes for each file but we want to terminate the process
1542      with an error. */
1543   if (!rc && !c->any.sig_seen)
1544     {
1545       write_status_text (STATUS_NODATA, "4");
1546       log_error (_("no signature found\n"));
1547       rc = GPG_ERR_NO_DATA;
1548     }
1549
1550   /* Propagate the signature seen flag upward. Do this only on success
1551      so that we won't issue the nodata status several times.  */
1552   if (!rc && c->anchor && c->any.sig_seen)
1553     c->anchor->any.sig_seen = 1;
1554
1555   xfree (c);
1556   return rc;
1557 }
1558
1559
1560 int
1561 proc_signature_packets_by_fd (ctrl_t ctrl,
1562                               void *anchor, iobuf_t a, int signed_data_fd )
1563 {
1564   int rc;
1565   CTX c;
1566
1567   c = xtrycalloc (1, sizeof *c);
1568   if (!c)
1569     return gpg_error_from_syserror ();
1570
1571   c->ctrl = ctrl;
1572   c->anchor = anchor;
1573   c->sigs_only = 1;
1574
1575   c->signed_data.data_fd = signed_data_fd;
1576   c->signed_data.data_names = NULL;
1577   c->signed_data.used = (signed_data_fd != -1);
1578
1579   rc = do_proc_packets (ctrl, c, a);
1580
1581   /* If we have not encountered any signature we print an error
1582      messages, send a NODATA status back and return an error code.
1583      Using log_error is required because verify_files does not check
1584      error codes for each file but we want to terminate the process
1585      with an error. */
1586   if (!rc && !c->any.sig_seen)
1587     {
1588       write_status_text (STATUS_NODATA, "4");
1589       log_error (_("no signature found\n"));
1590       rc = gpg_error (GPG_ERR_NO_DATA);
1591     }
1592
1593   /* Propagate the signature seen flag upward. Do this only on success
1594      so that we won't issue the nodata status several times. */
1595   if (!rc && c->anchor && c->any.sig_seen)
1596     c->anchor->any.sig_seen = 1;
1597
1598   xfree ( c );
1599   return rc;
1600 }
1601
1602
1603 int
1604 proc_encryption_packets (ctrl_t ctrl, void *anchor, iobuf_t a )
1605 {
1606   CTX c = xmalloc_clear (sizeof *c);
1607   int rc;
1608
1609   c->ctrl = ctrl;
1610   c->anchor = anchor;
1611   c->encrypt_only = 1;
1612   rc = do_proc_packets (ctrl, c, a);
1613   xfree (c);
1614   return rc;
1615 }
1616
1617
1618 static int
1619 check_nesting (CTX c)
1620 {
1621   int level;
1622
1623   for (level=0; c; c = c->anchor)
1624     level++;
1625
1626   if (level > MAX_NESTING_DEPTH)
1627     {
1628       log_error ("input data with too deeply nested packets\n");
1629       write_status_text (STATUS_UNEXPECTED, "1");
1630       return GPG_ERR_BAD_DATA;
1631     }
1632
1633   return 0;
1634 }
1635
1636
1637 static int
1638 do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
1639 {
1640   PACKET *pkt;
1641   struct parse_packet_ctx_s parsectx;
1642   int rc = 0;
1643   int any_data = 0;
1644   int newpkt;
1645
1646   rc = check_nesting (c);
1647   if (rc)
1648     return rc;
1649
1650   pkt = xmalloc( sizeof *pkt );
1651   c->iobuf = a;
1652   init_packet(pkt);
1653   init_parse_packet (&parsectx, a);
1654   while ((rc=parse_packet (&parsectx, pkt)) != -1)
1655     {
1656       any_data = 1;
1657       if (rc)
1658         {
1659           free_packet (pkt, &parsectx);
1660           /* Stop processing when an invalid packet has been encountered
1661            * but don't do so when we are doing a --list-packets.  */
1662           if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
1663               && opt.list_packets == 0)
1664             break;
1665           continue;
1666         }
1667       newpkt = -1;
1668       if (opt.list_packets)
1669         {
1670           switch (pkt->pkttype)
1671             {
1672             case PKT_PUBKEY_ENC:    proc_pubkey_enc (ctrl, c, pkt); break;
1673             case PKT_SYMKEY_ENC:    proc_symkey_enc (c, pkt); break;
1674             case PKT_ENCRYPTED:
1675             case PKT_ENCRYPTED_MDC:
1676             case PKT_ENCRYPTED_AEAD:proc_encrypted (c, pkt); break;
1677             case PKT_COMPRESSED:    rc = proc_compressed (c, pkt); break;
1678             default: newpkt = 0; break;
1679             }
1680         }
1681       else if (c->sigs_only)
1682         {
1683           switch (pkt->pkttype)
1684             {
1685             case PKT_PUBLIC_KEY:
1686             case PKT_SECRET_KEY:
1687             case PKT_USER_ID:
1688             case PKT_SYMKEY_ENC:
1689             case PKT_PUBKEY_ENC:
1690             case PKT_ENCRYPTED:
1691             case PKT_ENCRYPTED_MDC:
1692             case PKT_ENCRYPTED_AEAD:
1693               write_status_text( STATUS_UNEXPECTED, "0" );
1694               rc = GPG_ERR_UNEXPECTED;
1695               goto leave;
1696
1697             case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1698             case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1699             case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1700             case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1701             case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break;
1702             default: newpkt = 0; break;
1703             }
1704         }
1705       else if (c->encrypt_only)
1706         {
1707           switch (pkt->pkttype)
1708             {
1709             case PKT_PUBLIC_KEY:
1710             case PKT_SECRET_KEY:
1711             case PKT_USER_ID:
1712               write_status_text (STATUS_UNEXPECTED, "0");
1713               rc = GPG_ERR_UNEXPECTED;
1714               goto leave;
1715
1716             case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1717             case PKT_SYMKEY_ENC:  proc_symkey_enc (c, pkt); break;
1718             case PKT_PUBKEY_ENC:  proc_pubkey_enc (ctrl, c, pkt); break;
1719             case PKT_ENCRYPTED:
1720             case PKT_ENCRYPTED_MDC:
1721             case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break;
1722             case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1723             case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1724             case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1725             case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break;
1726             default: newpkt = 0; break;
1727             }
1728         }
1729       else
1730         {
1731           switch (pkt->pkttype)
1732             {
1733             case PKT_PUBLIC_KEY:
1734             case PKT_SECRET_KEY:
1735               release_list (c);
1736               c->list = new_kbnode (pkt);
1737               newpkt = 1;
1738               break;
1739             case PKT_PUBLIC_SUBKEY:
1740             case PKT_SECRET_SUBKEY:
1741               newpkt = add_subkey (c, pkt);
1742               break;
1743             case PKT_USER_ID:     newpkt = add_user_id (c, pkt); break;
1744             case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1745             case PKT_PUBKEY_ENC:  proc_pubkey_enc (ctrl, c, pkt); break;
1746             case PKT_SYMKEY_ENC:  proc_symkey_enc (c, pkt); break;
1747             case PKT_ENCRYPTED:
1748             case PKT_ENCRYPTED_MDC:
1749             case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break;
1750             case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1751             case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1752             case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1753             case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
1754             case PKT_RING_TRUST:  newpkt = add_ring_trust (c, pkt); break;
1755             default: newpkt = 0; break;
1756             }
1757         }
1758
1759       if (rc)
1760         goto leave;
1761
1762       /* This is a very ugly construct and frankly, I don't remember why
1763        * I used it.  Adding the MDC check here is a hack.
1764        * The right solution is to initiate another context for encrypted
1765        * packet and not to reuse the current one ...  It works right
1766        * when there is a compression packet between which adds just
1767        * an extra layer.
1768        * Hmmm: Rewrite this whole module here??
1769        */
1770       if (pkt->pkttype != PKT_SIGNATURE && pkt->pkttype != PKT_MDC)
1771         c->any.data = (pkt->pkttype == PKT_PLAINTEXT);
1772
1773       if (newpkt == -1)
1774         ;
1775       else if (newpkt)
1776         {
1777           pkt = xmalloc (sizeof *pkt);
1778           init_packet (pkt);
1779         }
1780       else
1781         free_packet (pkt, &parsectx);
1782     }
1783
1784   if (rc == GPG_ERR_INV_PACKET)
1785     write_status_text (STATUS_NODATA, "3");
1786
1787   if (any_data)
1788     rc = 0;
1789   else if (rc == -1)
1790     write_status_text (STATUS_NODATA, "2");
1791
1792
1793  leave:
1794   release_list (c);
1795   xfree(c->dek);
1796   free_packet (pkt, &parsectx);
1797   deinit_parse_packet (&parsectx);
1798   xfree (pkt);
1799   free_md_filter_context (&c->mfx);
1800   return rc;
1801 }
1802
1803
1804 /* Helper for pka_uri_from_sig to parse the to-be-verified address out
1805    of the notation data. */
1806 static pka_info_t *
1807 get_pka_address (PKT_signature *sig)
1808 {
1809   pka_info_t *pka = NULL;
1810   struct notation *nd,*notation;
1811
1812   notation=sig_to_notation(sig);
1813
1814   for(nd=notation;nd;nd=nd->next)
1815     {
1816       if(strcmp(nd->name,"pka-address@gnupg.org")!=0)
1817         continue; /* Not the notation we want. */
1818
1819       /* For now we only use the first valid PKA notation. In future
1820          we might want to keep additional PKA notations in a linked
1821          list. */
1822       if (is_valid_mailbox (nd->value))
1823         {
1824           pka = xmalloc (sizeof *pka + strlen(nd->value));
1825           pka->valid = 0;
1826           pka->checked = 0;
1827           pka->uri = NULL;
1828           strcpy (pka->email, nd->value);
1829           break;
1830         }
1831     }
1832
1833   free_notation(notation);
1834
1835   return pka;
1836 }
1837
1838
1839 /* Return the URI from a DNS PKA record.  If this record has already
1840    be retrieved for the signature we merely return it; if not we go
1841    out and try to get that DNS record. */
1842 static const char *
1843 pka_uri_from_sig (CTX c, PKT_signature *sig)
1844 {
1845   if (!sig->flags.pka_tried)
1846     {
1847       log_assert (!sig->pka_info);
1848       sig->flags.pka_tried = 1;
1849       sig->pka_info = get_pka_address (sig);
1850       if (sig->pka_info)
1851         {
1852           char *url;
1853           unsigned char *fpr;
1854           size_t fprlen;
1855
1856           if (!gpg_dirmngr_get_pka (c->ctrl, sig->pka_info->email,
1857                                     &fpr, &fprlen, &url))
1858             {
1859               if (fpr && fprlen == sizeof sig->pka_info->fpr)
1860                 {
1861                   memcpy (sig->pka_info->fpr, fpr, fprlen);
1862                   if (url)
1863                     {
1864                       sig->pka_info->valid = 1;
1865                       if (!*url)
1866                         xfree (url);
1867                       else
1868                         sig->pka_info->uri = url;
1869                       url = NULL;
1870                     }
1871                 }
1872               xfree (fpr);
1873               xfree (url);
1874             }
1875         }
1876     }
1877   return sig->pka_info? sig->pka_info->uri : NULL;
1878 }
1879
1880
1881 /* Return true if the AKL has the WKD method specified.  */
1882 static int
1883 akl_has_wkd_method (void)
1884 {
1885   struct akl *akl;
1886
1887   for (akl = opt.auto_key_locate; akl; akl = akl->next)
1888     if (akl->type == AKL_WKD)
1889       return 1;
1890   return 0;
1891 }
1892
1893
1894 /* Return the ISSUER fingerprint buffer and its lenbgth at R_LEN.
1895  * Returns NULL if not available.  The returned buffer is valid as
1896  * long as SIG is not modified.  */
1897 const byte *
1898 issuer_fpr_raw (PKT_signature *sig, size_t *r_len)
1899 {
1900   const byte *p;
1901   size_t n;
1902
1903   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_ISSUER_FPR, &n);
1904   if (p && n == 21 && p[0] == 4)
1905     {
1906       *r_len = n - 1;
1907       return p+1;
1908     }
1909   *r_len = 0;
1910   return NULL;
1911 }
1912
1913
1914 /* Return the ISSUER fingerprint string in human readable format if
1915  * available.  Caller must release the string.  */
1916 /* FIXME: Move to another file.  */
1917 char *
1918 issuer_fpr_string (PKT_signature *sig)
1919 {
1920   const byte *p;
1921   size_t n;
1922
1923   p = issuer_fpr_raw (sig, &n);
1924   return p? bin2hex (p, n, NULL) : NULL;
1925 }
1926
1927
1928 static void
1929 print_good_bad_signature (int statno, const char *keyid_str, kbnode_t un,
1930                           PKT_signature *sig, int rc)
1931 {
1932   char *p;
1933
1934   write_status_text_and_buffer (statno, keyid_str,
1935                                 un? un->pkt->pkt.user_id->name:"[?]",
1936                                 un? un->pkt->pkt.user_id->len:3,
1937                                 -1);
1938
1939   if (un)
1940     p = utf8_to_native (un->pkt->pkt.user_id->name,
1941                         un->pkt->pkt.user_id->len, 0);
1942   else
1943     p = xstrdup ("[?]");
1944
1945   if (rc)
1946     log_info (_("BAD signature from \"%s\""), p);
1947   else if (sig->flags.expired)
1948     log_info (_("Expired signature from \"%s\""), p);
1949   else
1950     log_info (_("Good signature from \"%s\""), p);
1951
1952   xfree (p);
1953 }
1954
1955
1956 static int
1957 check_sig_and_print (CTX c, kbnode_t node)
1958 {
1959   PKT_signature *sig = node->pkt->pkt.signature;
1960   const char *astr;
1961   int rc;
1962   int is_expkey = 0;
1963   int is_revkey = 0;
1964   char *issuer_fpr = NULL;
1965   PKT_public_key *pk = NULL;  /* The public key for the signature or NULL. */
1966   kbnode_t included_keyblock = NULL;
1967
1968   if (opt.skip_verify)
1969     {
1970       log_info(_("signature verification suppressed\n"));
1971       return 0;
1972     }
1973
1974   /* Check that the message composition is valid.
1975    *
1976    * Per RFC-2440bis (-15) allowed:
1977    *
1978    * S{1,n}           -- detached signature.
1979    * S{1,n} P         -- old style PGP2 signature
1980    * O{1,n} P S{1,n}  -- standard OpenPGP signature.
1981    * C P S{1,n}       -- cleartext signature.
1982    *
1983    *
1984    *      O = One-Pass Signature packet.
1985    *      S = Signature packet.
1986    *      P = OpenPGP Message packet (Encrypted | Compressed | Literal)
1987    *             (Note that the current rfc2440bis draft also allows
1988    *              for a signed message but that does not work as it
1989    *              introduces ambiguities.)
1990    *          We keep track of these packages using the marker packet
1991    *          CTRLPKT_PLAINTEXT_MARK.
1992    *      C = Marker packet for cleartext signatures.
1993    *
1994    * We reject all other messages.
1995    *
1996    * Actually we are calling this too often, i.e. for verification of
1997    * each message but better have some duplicate work than to silently
1998    * introduce a bug here.
1999    */
2000   {
2001     kbnode_t n;
2002     int n_onepass, n_sig;
2003
2004 /*     log_debug ("checking signature packet composition\n"); */
2005 /*     dump_kbnode (c->list); */
2006
2007     n = c->list;
2008     log_assert (n);
2009     if ( n->pkt->pkttype == PKT_SIGNATURE )
2010       {
2011         /* This is either "S{1,n}" case (detached signature) or
2012            "S{1,n} P" (old style PGP2 signature). */
2013         for (n = n->next; n; n = n->next)
2014           if (n->pkt->pkttype != PKT_SIGNATURE)
2015             break;
2016         if (!n)
2017           ; /* Okay, this is a detached signature.  */
2018         else if (n->pkt->pkttype == PKT_GPG_CONTROL
2019                  && (n->pkt->pkt.gpg_control->control
2020                      == CTRLPKT_PLAINTEXT_MARK) )
2021           {
2022             if (n->next)
2023               goto ambiguous;  /* We only allow one P packet. */
2024           }
2025         else
2026           goto ambiguous;
2027       }
2028     else if (n->pkt->pkttype == PKT_ONEPASS_SIG)
2029       {
2030         /* This is the "O{1,n} P S{1,n}" case (standard signature). */
2031         for (n_onepass=1, n = n->next;
2032              n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next)
2033           n_onepass++;
2034         if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
2035                     && (n->pkt->pkt.gpg_control->control
2036                         == CTRLPKT_PLAINTEXT_MARK)))
2037           goto ambiguous;
2038         for (n_sig=0, n = n->next;
2039              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
2040           n_sig++;
2041         if (!n_sig)
2042           goto ambiguous;
2043
2044         /* If we wanted to disallow multiple sig verification, we'd do
2045            something like this:
2046
2047            if (n && !opt.allow_multisig_verification)
2048              goto ambiguous;
2049
2050            However, now that we have --allow-multiple-messages, this
2051            can stay allowable as we can't get here unless multiple
2052            messages (i.e. multiple literals) are allowed. */
2053
2054         if (n_onepass != n_sig)
2055           {
2056             log_info ("number of one-pass packets does not match "
2057                       "number of signature packets\n");
2058             goto ambiguous;
2059           }
2060       }
2061     else if (n->pkt->pkttype == PKT_GPG_CONTROL
2062              && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
2063       {
2064         /* This is the "C P S{1,n}" case (clear text signature). */
2065         n = n->next;
2066         if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
2067                     && (n->pkt->pkt.gpg_control->control
2068                         == CTRLPKT_PLAINTEXT_MARK)))
2069           goto ambiguous;
2070         for (n_sig=0, n = n->next;
2071              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
2072           n_sig++;
2073         if (n || !n_sig)
2074           goto ambiguous;
2075       }
2076     else
2077       {
2078       ambiguous:
2079         log_error(_("can't handle this ambiguous signature data\n"));
2080         return 0;
2081       }
2082   }
2083
2084   if (sig->signers_uid)
2085     write_status_buffer (STATUS_NEWSIG,
2086                          sig->signers_uid, strlen (sig->signers_uid), 0);
2087   else
2088     write_status_text (STATUS_NEWSIG, NULL);
2089
2090   astr = openpgp_pk_algo_name ( sig->pubkey_algo );
2091   issuer_fpr = issuer_fpr_string (sig);
2092
2093   if (issuer_fpr)
2094     {
2095       log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
2096       log_info (_("               using %s key %s\n"),
2097                 astr? astr: "?", issuer_fpr);
2098
2099     }
2100   else if (!keystrlen () || keystrlen () > 8)
2101     {
2102       log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
2103       log_info (_("               using %s key %s\n"),
2104                 astr? astr: "?", keystr(sig->keyid));
2105     }
2106   else /* Legacy format.  */
2107     log_info (_("Signature made %s using %s key ID %s\n"),
2108               asctimestamp(sig->timestamp), astr? astr: "?",
2109               keystr(sig->keyid));
2110
2111   /* In verbose mode print the signers UID.  */
2112   if (sig->signers_uid)
2113     log_info (_("               issuer \"%s\"\n"), sig->signers_uid);
2114
2115   rc = do_check_sig (c, node, NULL, NULL, &is_expkey, &is_revkey, &pk);
2116
2117   /* If the key is not found but the signature includes a key block we
2118    * use that key block for verification and on success import it.  */
2119   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2120       && sig->flags.key_block
2121       && opt.flags.auto_key_import)
2122     {
2123       PKT_public_key *included_pk;
2124       const byte *kblock;
2125       size_t kblock_len;
2126
2127       included_pk = xcalloc (1, sizeof *included_pk);
2128       kblock = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_BLOCK, &kblock_len);
2129       if (kblock && kblock_len > 1
2130           && !get_pubkey_from_buffer (c->ctrl, included_pk,
2131                                       kblock+1, kblock_len-1,
2132                                       sig->keyid, &included_keyblock))
2133         {
2134           rc = do_check_sig (c, node, included_pk,
2135                              NULL, &is_expkey, &is_revkey, &pk);
2136           if (!rc)
2137             {
2138               /* The keyblock has been verified, we now import it.  */
2139               rc = import_included_key_block (c->ctrl, included_keyblock);
2140             }
2141
2142         }
2143       free_public_key (included_pk);
2144     }
2145
2146   /* If the key isn't found, check for a preferred keyserver.  Note
2147    * that this is only done if honor-keyserver-url has been set.  We
2148    * test for this in the loop so that we can show info about the
2149    * preferred keyservers.  */
2150   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2151       && sig->flags.pref_ks)
2152     {
2153       const byte *p;
2154       int seq = 0;
2155       size_t n;
2156       int any_pref_ks = 0;
2157
2158       while ((p=enum_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS,&n,&seq,NULL)))
2159         {
2160           /* According to my favorite copy editor, in English grammar,
2161              you say "at" if the key is located on a web page, but
2162              "from" if it is located on a keyserver.  I'm not going to
2163              even try to make two strings here :) */
2164           log_info(_("Key available at: ") );
2165           print_utf8_buffer (log_get_stream(), p, n);
2166           log_printf ("\n");
2167           any_pref_ks = 1;
2168
2169           if ((opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
2170               && (opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL))
2171             {
2172               struct keyserver_spec *spec;
2173
2174               spec = parse_preferred_keyserver (sig);
2175               if (spec)
2176                 {
2177                   int res;
2178
2179                   if (DBG_LOOKUP)
2180                     log_debug ("trying auto-key-retrieve method %s\n",
2181                                "Pref-KS");
2182
2183                   free_public_key (pk);
2184                   pk = NULL;
2185                   glo_ctrl.in_auto_key_retrieve++;
2186                   res = keyserver_import_keyid (c->ctrl, sig->keyid,spec,
2187                                                 KEYSERVER_IMPORT_FLAG_QUICK);
2188                   glo_ctrl.in_auto_key_retrieve--;
2189                   if (!res)
2190                     rc = do_check_sig (c, node, NULL,
2191                                        NULL, &is_expkey, &is_revkey, &pk);
2192                   else if (DBG_LOOKUP)
2193                     log_debug ("lookup via %s failed: %s\n", "Pref-KS",
2194                                gpg_strerror (res));
2195                   free_keyserver_spec (spec);
2196
2197                   if (!rc)
2198                     break;
2199                 }
2200             }
2201         }
2202
2203       if (any_pref_ks
2204           && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
2205           && !(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL))
2206         log_info (_("Note: Use '%s' to make use of this info\n"),
2207                   "--keyserver-option honor-keyserver-url");
2208     }
2209
2210   /* If the above methods didn't work, our next try is to retrieve the
2211    * key from the WKD.  This requires that WKD is in the AKL and the
2212    * Signer's UID is in the signature.  */
2213   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2214       && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
2215       && !opt.flags.disable_signer_uid
2216       && akl_has_wkd_method ()
2217       && sig->signers_uid)
2218     {
2219       int res;
2220
2221       if (DBG_LOOKUP)
2222         log_debug ("trying auto-key-retrieve method %s\n", "WKD");
2223       free_public_key (pk);
2224       pk = NULL;
2225       glo_ctrl.in_auto_key_retrieve++;
2226       res = keyserver_import_wkd (c->ctrl, sig->signers_uid,
2227                                   KEYSERVER_IMPORT_FLAG_QUICK, NULL, NULL);
2228       glo_ctrl.in_auto_key_retrieve--;
2229       /* Fixme: If the fingerprint is embedded in the signature,
2230        * compare it to the fingerprint of the returned key.  */
2231       if (!res)
2232         rc = do_check_sig (c, node, NULL, NULL, &is_expkey, &is_revkey, &pk);
2233       else if (DBG_LOOKUP)
2234         log_debug ("lookup via %s failed: %s\n", "WKD", gpg_strerror (res));
2235     }
2236
2237   /* If the avove methods didn't work, our next try is to use the URI
2238    * from a DNS PKA record.  This is a legacy method which will
2239    * eventually be removed.  */
2240   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2241       && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
2242       && (opt.keyserver_options.options & KEYSERVER_HONOR_PKA_RECORD))
2243     {
2244       const char *uri = pka_uri_from_sig (c, sig);
2245
2246       if (uri)
2247         {
2248           /* FIXME: We might want to locate the key using the
2249              fingerprint instead of the keyid. */
2250           int res;
2251           struct keyserver_spec *spec;
2252
2253           spec = parse_keyserver_uri (uri, 1);
2254           if (spec)
2255             {
2256               if (DBG_LOOKUP)
2257                 log_debug ("trying auto-key-retrieve method %s\n", "PKA");
2258
2259               free_public_key (pk);
2260               pk = NULL;
2261               glo_ctrl.in_auto_key_retrieve++;
2262               res = keyserver_import_keyid (c->ctrl, sig->keyid, spec, 1);
2263               glo_ctrl.in_auto_key_retrieve--;
2264               free_keyserver_spec (spec);
2265               if (!res)
2266                 rc = do_check_sig (c, node, NULL,
2267                                    NULL, &is_expkey, &is_revkey, &pk);
2268               else if (DBG_LOOKUP)
2269                 log_debug ("lookup via %s failed: %s\n", "PKA",
2270                            gpg_strerror (res));
2271             }
2272         }
2273     }
2274
2275   /* If the above methods didn't work, our next try is to locate
2276    * the key via its fingerprint from a keyserver.  This requires
2277    * that the signers fingerprint is encoded in the signature.  */
2278   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2279       && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
2280       && keyserver_any_configured (c->ctrl))
2281     {
2282       int res;
2283       const byte *p;
2284       size_t n;
2285
2286       p = issuer_fpr_raw (sig, &n);
2287       if (p)
2288         {
2289           /* v4 packet with a SHA-1 fingerprint.  */
2290           if (DBG_LOOKUP)
2291             log_debug ("trying auto-key-retrieve method %s\n", "KS");
2292
2293           free_public_key (pk);
2294           pk = NULL;
2295           glo_ctrl.in_auto_key_retrieve++;
2296           res = keyserver_import_fprint (c->ctrl, p, n, opt.keyserver,
2297                                          KEYSERVER_IMPORT_FLAG_QUICK);
2298           glo_ctrl.in_auto_key_retrieve--;
2299           if (!res)
2300             rc = do_check_sig (c, node, NULL,
2301                                NULL, &is_expkey, &is_revkey, &pk);
2302           else if (DBG_LOOKUP)
2303             log_debug ("lookup via %s failed: %s\n", "KS", gpg_strerror (res));
2304         }
2305     }
2306
2307   if (!rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
2308     {
2309       kbnode_t un, keyblock;
2310       int count = 0;
2311       int statno;
2312       char keyid_str[50];
2313       PKT_public_key *mainpk = NULL;
2314
2315       if (rc)
2316         statno = STATUS_BADSIG;
2317       else if (sig->flags.expired)
2318         statno = STATUS_EXPSIG;
2319       else if (is_expkey)
2320         statno = STATUS_EXPKEYSIG;
2321       else if(is_revkey)
2322         statno = STATUS_REVKEYSIG;
2323       else
2324         statno = STATUS_GOODSIG;
2325
2326       /* FIXME: We should have the public key in PK and thus the
2327        * keyblock has already been fetched.  Thus we could use the
2328        * fingerprint or PK itself to lookup the entire keyblock.  That
2329        * would best be done with a cache.  */
2330       if (included_keyblock)
2331         {
2332           keyblock = included_keyblock;
2333           included_keyblock = NULL;
2334         }
2335       else
2336         keyblock = get_pubkeyblock_for_sig (c->ctrl, sig);
2337
2338       snprintf (keyid_str, sizeof keyid_str, "%08lX%08lX [uncertain] ",
2339                 (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
2340
2341       /* Find and print the primary user ID along with the
2342          "Good|Expired|Bad signature" line.  */
2343       for (un=keyblock; un; un = un->next)
2344         {
2345           int valid;
2346
2347           if (un->pkt->pkttype==PKT_PUBLIC_KEY)
2348             {
2349               mainpk = un->pkt->pkt.public_key;
2350               continue;
2351             }
2352           if (un->pkt->pkttype != PKT_USER_ID)
2353             continue;
2354           if (!un->pkt->pkt.user_id->created)
2355             continue;
2356           if (un->pkt->pkt.user_id->flags.revoked)
2357             continue;
2358           if (un->pkt->pkt.user_id->flags.expired)
2359             continue;
2360           if (!un->pkt->pkt.user_id->flags.primary)
2361             continue;
2362           /* We want the textual primary user ID here */
2363           if (un->pkt->pkt.user_id->attrib_data)
2364             continue;
2365
2366           log_assert (mainpk);
2367
2368           /* Since this is just informational, don't actually ask the
2369              user to update any trust information.  (Note: we register
2370              the signature later.)  Because print_good_bad_signature
2371              does not print a LF we need to compute the validity
2372              before calling that function.  */
2373           if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2374             valid = get_validity (c->ctrl, keyblock, mainpk,
2375                                   un->pkt->pkt.user_id, NULL, 0);
2376           else
2377             valid = 0; /* Not used.  */
2378
2379           keyid_str[17] = 0; /* cut off the "[uncertain]" part */
2380
2381           print_good_bad_signature (statno, keyid_str, un, sig, rc);
2382
2383           if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2384             log_printf (" [%s]\n",trust_value_to_string(valid));
2385           else
2386             log_printf ("\n");
2387
2388           count++;
2389         }
2390
2391       log_assert (mainpk);
2392
2393       /* In case we did not found a valid textual userid above
2394          we print the first user id packet or a "[?]" instead along
2395          with the "Good|Expired|Bad signature" line.  */
2396       if (!count)
2397         {
2398           /* Try for an invalid textual userid */
2399           for (un=keyblock; un; un = un->next)
2400             {
2401               if (un->pkt->pkttype == PKT_USER_ID
2402                   && !un->pkt->pkt.user_id->attrib_data)
2403                 break;
2404             }
2405
2406           /* Try for any userid at all */
2407           if (!un)
2408             {
2409               for (un=keyblock; un; un = un->next)
2410                 {
2411                   if (un->pkt->pkttype == PKT_USER_ID)
2412                     break;
2413                 }
2414             }
2415
2416           if (opt.trust_model==TM_ALWAYS || !un)
2417             keyid_str[17] = 0; /* cut off the "[uncertain]" part */
2418
2419           print_good_bad_signature (statno, keyid_str, un, sig, rc);
2420
2421           if (opt.trust_model != TM_ALWAYS && un)
2422             log_printf (" %s",_("[uncertain]") );
2423           log_printf ("\n");
2424         }
2425
2426       /* If we have a good signature and already printed
2427        * the primary user ID, print all the other user IDs */
2428       if (count
2429           && !rc
2430           && !(opt.verify_options & VERIFY_SHOW_PRIMARY_UID_ONLY))
2431         {
2432           char *p;
2433           for( un=keyblock; un; un = un->next)
2434             {
2435               if (un->pkt->pkttype != PKT_USER_ID)
2436                 continue;
2437               if ((un->pkt->pkt.user_id->flags.revoked
2438                    || un->pkt->pkt.user_id->flags.expired)
2439                   && !(opt.verify_options & VERIFY_SHOW_UNUSABLE_UIDS))
2440                 continue;
2441               /* Skip textual primary user ids which we printed above. */
2442               if (un->pkt->pkt.user_id->flags.primary
2443                   && !un->pkt->pkt.user_id->attrib_data )
2444                 continue;
2445
2446               /* If this user id has attribute data, print that.  */
2447               if (un->pkt->pkt.user_id->attrib_data)
2448                 {
2449                   dump_attribs (un->pkt->pkt.user_id, mainpk);
2450
2451                   if (opt.verify_options&VERIFY_SHOW_PHOTOS)
2452                     show_photos (c->ctrl,
2453                                  un->pkt->pkt.user_id->attribs,
2454                                  un->pkt->pkt.user_id->numattribs,
2455                                  mainpk ,un->pkt->pkt.user_id);
2456                 }
2457
2458               p = utf8_to_native (un->pkt->pkt.user_id->name,
2459                                   un->pkt->pkt.user_id->len, 0);
2460               log_info (_("                aka \"%s\""), p);
2461               xfree (p);
2462
2463               if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2464                 {
2465                   const char *valid;
2466
2467                   if (un->pkt->pkt.user_id->flags.revoked)
2468                     valid = _("revoked");
2469                   else if (un->pkt->pkt.user_id->flags.expired)
2470                     valid = _("expired");
2471                   else
2472                     /* Since this is just informational, don't
2473                        actually ask the user to update any trust
2474                        information.  */
2475                     valid = (trust_value_to_string
2476                              (get_validity (c->ctrl, keyblock, mainpk,
2477                                             un->pkt->pkt.user_id, NULL, 0)));
2478                   log_printf (" [%s]\n",valid);
2479                 }
2480               else
2481                 log_printf ("\n");
2482             }
2483         }
2484
2485       /* For good signatures print notation data.  */
2486       if (!rc)
2487         {
2488           if ((opt.verify_options & VERIFY_SHOW_POLICY_URLS))
2489             show_policy_url (sig, 0, 1);
2490           else
2491             show_policy_url (sig, 0, 2);
2492
2493           if ((opt.verify_options & VERIFY_SHOW_KEYSERVER_URLS))
2494             show_keyserver_url (sig, 0, 1);
2495           else
2496             show_keyserver_url (sig, 0, 2);
2497
2498           if ((opt.verify_options & VERIFY_SHOW_NOTATIONS))
2499             show_notation
2500               (sig, 0, 1,
2501                (((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0)
2502                 + ((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0)));
2503           else
2504             show_notation (sig, 0, 2, 0);
2505         }
2506
2507       /* For good signatures print the VALIDSIG status line.  */
2508       if (!rc && is_status_enabled () && pk)
2509         {
2510           char pkhex[MAX_FINGERPRINT_LEN*2+1];
2511           char mainpkhex[MAX_FINGERPRINT_LEN*2+1];
2512
2513           hexfingerprint (pk, pkhex, sizeof pkhex);
2514           hexfingerprint (mainpk, mainpkhex, sizeof mainpkhex);
2515
2516           /* TODO: Replace the reserved '0' in the field below with
2517              bits for status flags (policy url, notation, etc.).  */
2518           write_status_printf (STATUS_VALIDSIG,
2519                                "%s %s %lu %lu %d 0 %d %d %02X %s",
2520                                pkhex,
2521                                strtimestamp (sig->timestamp),
2522                                (ulong)sig->timestamp,
2523                                (ulong)sig->expiredate,
2524                                sig->version, sig->pubkey_algo,
2525                                sig->digest_algo,
2526                                sig->sig_class,
2527                                mainpkhex);
2528         }
2529
2530       /* Print compliance warning for Good signatures.  */
2531       if (!rc && pk && !opt.quiet
2532           && !gnupg_pk_is_compliant (opt.compliance, pk->pubkey_algo, 0,
2533                                      pk->pkey, nbits_from_pk (pk), NULL))
2534         {
2535           log_info (_("WARNING: This key is not suitable for signing"
2536                       " in %s mode\n"),
2537                     gnupg_compliance_option_string (opt.compliance));
2538         }
2539
2540       /* For good signatures compute and print the trust information.
2541          Note that in the Tofu trust model this may ask the user on
2542          how to resolve a conflict.  */
2543       if (!rc)
2544         {
2545           if ((opt.verify_options & VERIFY_PKA_LOOKUPS))
2546             pka_uri_from_sig (c, sig); /* Make sure PKA info is available. */
2547           rc = check_signatures_trust (c->ctrl, sig);
2548         }
2549
2550       /* Print extra information about the signature.  */
2551       if (sig->flags.expired)
2552         {
2553           log_info (_("Signature expired %s\n"), asctimestamp(sig->expiredate));
2554           rc = GPG_ERR_GENERAL; /* Need a better error here?  */
2555         }
2556       else if (sig->expiredate)
2557         log_info (_("Signature expires %s\n"), asctimestamp(sig->expiredate));
2558
2559       if (opt.verbose)
2560         {
2561           char pkstrbuf[PUBKEY_STRING_SIZE];
2562
2563           if (pk)
2564             pubkey_string (pk, pkstrbuf, sizeof pkstrbuf);
2565           else
2566             *pkstrbuf = 0;
2567
2568           log_info (_("%s signature, digest algorithm %s%s%s\n"),
2569                     sig->sig_class==0x00?_("binary"):
2570                     sig->sig_class==0x01?_("textmode"):_("unknown"),
2571                     gcry_md_algo_name (sig->digest_algo),
2572                     *pkstrbuf?_(", key algorithm "):"", pkstrbuf);
2573         }
2574
2575       /* Print final warnings.  */
2576       if (!rc && !c->signed_data.used)
2577         {
2578           /* Signature is basically good but we test whether the
2579              deprecated command
2580                gpg --verify FILE.sig
2581              was used instead of
2582                gpg --verify FILE.sig FILE
2583              to verify a detached signature.  If we figure out that a
2584              data file with a matching name exists, we print a warning.
2585
2586              The problem is that the first form would also verify a
2587              standard signature.  This behavior could be used to
2588              create a made up .sig file for a tarball by creating a
2589              standard signature from a valid detached signature packet
2590              (for example from a signed git tag).  Then replace the
2591              sig file on the FTP server along with a changed tarball.
2592              Using the first form the verify command would correctly
2593              verify the signature but don't even consider the tarball.  */
2594           kbnode_t n;
2595           char *dfile;
2596
2597           dfile = get_matching_datafile (c->sigfilename);
2598           if (dfile)
2599             {
2600               for (n = c->list; n; n = n->next)
2601                 if (n->pkt->pkttype != PKT_SIGNATURE)
2602                   break;
2603               if (n)
2604                 {
2605                   /* Not only signature packets in the tree thus this
2606                      is not a detached signature.  */
2607                   log_info (_("WARNING: not a detached signature; "
2608                               "file '%s' was NOT verified!\n"), dfile);
2609                 }
2610               xfree (dfile);
2611             }
2612         }
2613
2614       /* Compute compliance with CO_DE_VS.  */
2615       if (pk && is_status_enabled ()
2616           && gnupg_gcrypt_is_compliant (CO_DE_VS)
2617           && gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0, pk->pkey,
2618                                     nbits_from_pk (pk), NULL)
2619           && gnupg_digest_is_compliant (CO_DE_VS, sig->digest_algo))
2620         write_status_strings (STATUS_VERIFICATION_COMPLIANCE_MODE,
2621                               gnupg_status_compliance_flag (CO_DE_VS),
2622                               NULL);
2623       else if (opt.flags.require_compliance
2624                && opt.compliance == CO_DE_VS)
2625         {
2626           compliance_failure ();
2627           if (!rc)
2628             rc = gpg_error (GPG_ERR_FORBIDDEN);
2629         }
2630
2631
2632       free_public_key (pk);
2633       pk = NULL;
2634       release_kbnode( keyblock );
2635       if (rc)
2636         g10_errors_seen = 1;
2637       if (opt.batch && rc)
2638         g10_exit (1);
2639     }
2640   else
2641     {
2642       write_status_printf (STATUS_ERRSIG, "%08lX%08lX %d %d %02x %lu %d %s",
2643                            (ulong)sig->keyid[0], (ulong)sig->keyid[1],
2644                            sig->pubkey_algo, sig->digest_algo,
2645                            sig->sig_class, (ulong)sig->timestamp,
2646                            gpg_err_code (rc),
2647                            issuer_fpr? issuer_fpr:"-");
2648       if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2649         {
2650           write_status_printf (STATUS_NO_PUBKEY, "%08lX%08lX",
2651                                (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
2652         }
2653       if (gpg_err_code (rc) != GPG_ERR_NOT_PROCESSED)
2654         log_error (_("Can't check signature: %s\n"), gpg_strerror (rc));
2655     }
2656
2657   free_public_key (pk);
2658   release_kbnode (included_keyblock);
2659   xfree (issuer_fpr);
2660   return rc;
2661 }
2662
2663
2664 /*
2665  * Process the tree which starts at node
2666  */
2667 static void
2668 proc_tree (CTX c, kbnode_t node)
2669 {
2670   kbnode_t n1;
2671   int rc;
2672
2673   if (opt.list_packets || opt.list_only)
2674     return;
2675
2676   /* We must skip our special plaintext marker packets here because
2677      they may be the root packet.  These packets are only used in
2678      additional checks and skipping them here doesn't matter.  */
2679   while (node
2680          && node->pkt->pkttype == PKT_GPG_CONTROL
2681           && node->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK)
2682     {
2683       node = node->next;
2684     }
2685   if (!node)
2686     return;
2687
2688   c->trustletter = ' ';
2689   if (node->pkt->pkttype == PKT_PUBLIC_KEY
2690       || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2691     {
2692       merge_keys_and_selfsig (c->ctrl, node);
2693       list_node (c, node);
2694     }
2695   else if (node->pkt->pkttype == PKT_SECRET_KEY)
2696     {
2697       merge_keys_and_selfsig (c->ctrl, node);
2698       list_node (c, node);
2699     }
2700   else if (node->pkt->pkttype == PKT_ONEPASS_SIG)
2701     {
2702       /* Check all signatures.  */
2703       if (!c->any.data)
2704         {
2705           int use_textmode = 0;
2706
2707           free_md_filter_context (&c->mfx);
2708           /* Prepare to create all requested message digests.  */
2709           rc = gcry_md_open (&c->mfx.md, 0, 0);
2710           if (rc)
2711             goto hash_err;
2712
2713           /* Fixme: why looking for the signature packet and not the
2714              one-pass packet?  */
2715           for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2716             gcry_md_enable (c->mfx.md, n1->pkt->pkt.signature->digest_algo);
2717
2718           if (n1 && n1->pkt->pkt.onepass_sig->sig_class == 0x01)
2719             use_textmode = 1;
2720
2721           /* Ask for file and hash it. */
2722           if (c->sigs_only)
2723             {
2724               if (c->signed_data.used && c->signed_data.data_fd != -1)
2725                 rc = hash_datafile_by_fd (c->mfx.md, NULL,
2726                                           c->signed_data.data_fd,
2727                                           use_textmode);
2728               else
2729                 rc = hash_datafiles (c->mfx.md, NULL,
2730                                      c->signed_data.data_names,
2731                                      c->sigfilename,
2732                                      use_textmode);
2733             }
2734           else
2735             {
2736               rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
2737                                               iobuf_get_real_fname (c->iobuf),
2738                                               use_textmode);
2739             }
2740
2741         hash_err:
2742           if (rc)
2743             {
2744               log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
2745               return;
2746             }
2747         }
2748       else if (c->signed_data.used)
2749         {
2750           log_error (_("not a detached signature\n"));
2751           return;
2752         }
2753
2754       for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2755         check_sig_and_print (c, n1);
2756
2757     }
2758   else if (node->pkt->pkttype == PKT_GPG_CONTROL
2759            && node->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START)
2760     {
2761       /* Clear text signed message.  */
2762       if (!c->any.data)
2763         {
2764           log_error ("cleartext signature without data\n");
2765           return;
2766         }
2767       else if (c->signed_data.used)
2768         {
2769           log_error (_("not a detached signature\n"));
2770           return;
2771         }
2772
2773       for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2774         check_sig_and_print (c, n1);
2775
2776     }
2777   else if (node->pkt->pkttype == PKT_SIGNATURE)
2778     {
2779       PKT_signature *sig = node->pkt->pkt.signature;
2780       int multiple_ok = 1;
2781
2782       n1 = find_next_kbnode (node, PKT_SIGNATURE);
2783       if (n1)
2784         {
2785           byte class = sig->sig_class;
2786           byte hash  = sig->digest_algo;
2787
2788           for (; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
2789             {
2790               /* We can't currently handle multiple signatures of
2791                * different classes (we'd pretty much have to run a
2792                * different hash context for each), but if they are all
2793                * the same and it is detached signature, we make an
2794                * exception.  Note that the old code also disallowed
2795                * multiple signatures if the digest algorithms are
2796                * different.  We softened this restriction only for
2797                * detached signatures, to be on the safe side. */
2798               if (n1->pkt->pkt.signature->sig_class != class
2799                   || (c->any.data
2800                       && n1->pkt->pkt.signature->digest_algo != hash))
2801                 {
2802                   multiple_ok = 0;
2803                   log_info (_("WARNING: multiple signatures detected.  "
2804                               "Only the first will be checked.\n"));
2805                   break;
2806                 }
2807             }
2808         }
2809
2810       if (sig->sig_class != 0x00 && sig->sig_class != 0x01)
2811         {
2812           log_info(_("standalone signature of class 0x%02x\n"), sig->sig_class);
2813         }
2814       else if (!c->any.data)
2815         {
2816           /* Detached signature */
2817           free_md_filter_context (&c->mfx);
2818           rc = gcry_md_open (&c->mfx.md, sig->digest_algo, 0);
2819           if (rc)
2820             goto detached_hash_err;
2821
2822           if (multiple_ok)
2823             {
2824               /* If we have and want to handle multiple signatures we
2825                * need to enable all hash algorithms for the context.  */
2826               for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE)); )
2827                 if (!openpgp_md_test_algo (n1->pkt->pkt.signature->digest_algo))
2828                   gcry_md_enable (c->mfx.md,
2829                                   map_md_openpgp_to_gcry
2830                                   (n1->pkt->pkt.signature->digest_algo));
2831             }
2832
2833           if (RFC2440 || RFC4880)
2834             ; /* Strict RFC mode.  */
2835           else if (sig->digest_algo == DIGEST_ALGO_SHA1
2836                    && sig->pubkey_algo == PUBKEY_ALGO_DSA
2837                    && sig->sig_class == 0x01)
2838             {
2839               /* Enable a workaround for a pgp5 bug when the detached
2840                * signature has been created in textmode.  Note that we
2841                * do not implement this for multiple signatures with
2842                * different hash algorithms. */
2843               rc = gcry_md_open (&c->mfx.md2, sig->digest_algo, 0);
2844               if (rc)
2845                 goto detached_hash_err;
2846             }
2847
2848           /* Here we used to have another hack to work around a pgp
2849            * 2 bug: It worked by not using the textmode for detached
2850            * signatures; this would let the first signature check
2851            * (on md) fail but the second one (on md2), which adds an
2852            * extra CR would then have produced the "correct" hash.
2853            * This is very, very ugly hack but it may haved help in
2854            * some cases (and break others).
2855            *     c->mfx.md2? 0 :(sig->sig_class == 0x01)
2856            */
2857
2858           if (DBG_HASHING)
2859             {
2860               gcry_md_debug (c->mfx.md, "verify");
2861               if (c->mfx.md2)
2862                 gcry_md_debug (c->mfx.md2, "verify2");
2863             }
2864
2865           if (c->sigs_only)
2866             {
2867               if (c->signed_data.used && c->signed_data.data_fd != -1)
2868                 rc = hash_datafile_by_fd (c->mfx.md, c->mfx.md2,
2869                                           c->signed_data.data_fd,
2870                                           (sig->sig_class == 0x01));
2871               else
2872                 rc = hash_datafiles (c->mfx.md, c->mfx.md2,
2873                                      c->signed_data.data_names,
2874                                      c->sigfilename,
2875                                      (sig->sig_class == 0x01));
2876             }
2877           else
2878             {
2879               rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
2880                                               iobuf_get_real_fname(c->iobuf),
2881                                               (sig->sig_class == 0x01));
2882             }
2883
2884         detached_hash_err:
2885           if (rc)
2886             {
2887               log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
2888               return;
2889             }
2890         }
2891       else if (c->signed_data.used)
2892         {
2893           log_error (_("not a detached signature\n"));
2894           return;
2895         }
2896       else if (!opt.quiet)
2897         log_info (_("old style (PGP 2.x) signature\n"));
2898
2899       if (multiple_ok)
2900         {
2901           for (n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
2902             check_sig_and_print (c, n1);
2903         }
2904       else
2905         check_sig_and_print (c, node);
2906
2907     }
2908   else
2909     {
2910       dump_kbnode (c->list);
2911       log_error ("invalid root packet detected in proc_tree()\n");
2912       dump_kbnode (node);
2913     }
2914 }