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