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