Imported Upstream version 2.1.15
[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 <http://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 "util.h"
29 #include "packet.h"
30 #include "iobuf.h"
31 #include "options.h"
32 #include "keydb.h"
33 #include "filter.h"
34 #include "main.h"
35 #include "status.h"
36 #include "i18n.h"
37 #include "trustdb.h"
38 #include "keyserver-internal.h"
39 #include "photoid.h"
40 #include "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 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);
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);
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 (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 (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 (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->pkenc_list, 1 );
534       print_pkenc_list ( 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);
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       rc = handle_plaintext (pt, &c->mfx, c->sigs_only, clearsig);
761       if (gpg_err_code (rc) == GPG_ERR_EACCES && !c->sigs_only)
762         {
763           /* Can't write output but we hash it anyway to check the
764              signature. */
765           rc = handle_plaintext( pt, &c->mfx, 1, clearsig );
766         }
767     }
768
769   if (rc)
770     log_error ("handle plaintext failed: %s\n", gpg_strerror (rc));
771
772   free_packet(pkt);
773   c->last_was_session_key = 0;
774
775   /* We add a marker control packet instead of the plaintext packet.
776    * This is so that we can later detect invalid packet sequences.  */
777   n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK, NULL, 0));
778   if (c->list)
779     add_kbnode (c->list, n);
780   else
781     c->list = n;
782 }
783
784
785 static int
786 proc_compressed_cb (iobuf_t a, void *info)
787 {
788   if ( ((CTX)info)->signed_data.used
789        && ((CTX)info)->signed_data.data_fd != -1)
790     return proc_signature_packets_by_fd (((CTX)info)->ctrl, info, a,
791                                          ((CTX)info)->signed_data.data_fd);
792   else
793     return proc_signature_packets (((CTX)info)->ctrl, info, a,
794                                    ((CTX)info)->signed_data.data_names,
795                                    ((CTX)info)->sigfilename );
796 }
797
798
799 static int
800 proc_encrypt_cb (iobuf_t a, void *info )
801 {
802   CTX c = info;
803   return proc_encryption_packets (c->ctrl, info, a );
804 }
805
806
807 static int
808 proc_compressed (CTX c, PACKET *pkt)
809 {
810   PKT_compressed *zd = pkt->pkt.compressed;
811   int rc;
812
813   /*printf("zip: compressed data packet\n");*/
814   if (c->sigs_only)
815     rc = handle_compressed (c->ctrl, c, zd, proc_compressed_cb, c);
816   else if( c->encrypt_only )
817     rc = handle_compressed (c->ctrl, c, zd, proc_encrypt_cb, c);
818   else
819     rc = handle_compressed (c->ctrl, c, zd, NULL, NULL);
820
821   if (gpg_err_code (rc) == GPG_ERR_BAD_DATA)
822     {
823       if  (!c->any.uncompress_failed)
824         {
825           CTX cc;
826
827           for (cc=c; cc; cc = cc->anchor)
828             cc->any.uncompress_failed = 1;
829           log_error ("uncompressing failed: %s\n", gpg_strerror (rc));
830         }
831     }
832   else if (rc)
833     log_error ("uncompressing failed: %s\n", gpg_strerror (rc));
834
835   free_packet(pkt);
836   c->last_was_session_key = 0;
837   return rc;
838 }
839
840
841 /*
842  * check the signature
843  * Returns: 0 = valid signature or an error code
844  */
845 static int
846 do_check_sig (CTX c, kbnode_t node, int *is_selfsig,
847               int *is_expkey, int *is_revkey)
848 {
849   PKT_signature *sig;
850   gcry_md_hd_t md = NULL;
851   gcry_md_hd_t md2 = NULL;
852   gcry_md_hd_t md_good = NULL;
853   int algo, rc;
854
855   log_assert (node->pkt->pkttype == PKT_SIGNATURE);
856   if (is_selfsig)
857     *is_selfsig = 0;
858   sig = node->pkt->pkt.signature;
859
860   algo = sig->digest_algo;
861   rc = openpgp_md_test_algo (algo);
862   if (rc)
863     return rc;
864
865   if (sig->sig_class == 0x00)
866     {
867       if (c->mfx.md)
868         {
869           if (gcry_md_copy (&md, c->mfx.md ))
870             BUG ();
871         }
872       else /* detached signature */
873         {
874           /* check_signature() will enable the md. */
875           if (gcry_md_open (&md, 0, 0 ))
876             BUG ();
877         }
878     }
879   else if (sig->sig_class == 0x01)
880     {
881       /* How do we know that we have to hash the (already hashed) text
882          in canonical mode ??? (calculating both modes???) */
883       if (c->mfx.md)
884         {
885           if (gcry_md_copy (&md, c->mfx.md ))
886             BUG ();
887           if (c->mfx.md2 && gcry_md_copy (&md2, c->mfx.md2))
888             BUG ();
889         }
890       else /* detached signature */
891         {
892           log_debug ("Do we really need this here?");
893           /* check_signature() will enable the md*/
894           if (gcry_md_open (&md, 0, 0 ))
895             BUG ();
896           if (gcry_md_open (&md2, 0, 0 ))
897             BUG ();
898         }
899     }
900   else if ((sig->sig_class&~3) == 0x10
901            ||   sig->sig_class == 0x18
902            ||   sig->sig_class == 0x1f
903            ||   sig->sig_class == 0x20
904            ||   sig->sig_class == 0x28
905            ||   sig->sig_class == 0x30)
906     {
907       if (c->list->pkt->pkttype == PKT_PUBLIC_KEY
908           || c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY)
909         {
910           return check_key_signature( c->list, node, is_selfsig );
911         }
912       else if (sig->sig_class == 0x20)
913         {
914           log_error (_("standalone revocation - "
915                        "use \"gpg --import\" to apply\n"));
916           return GPG_ERR_NOT_PROCESSED;
917         }
918       else
919         {
920           log_error ("invalid root packet for sigclass %02x\n", sig->sig_class);
921           return GPG_ERR_SIG_CLASS;
922         }
923     }
924   else
925     return GPG_ERR_SIG_CLASS;
926
927   /* We only get here if we are checking the signature of a binary
928      (0x00) or text document (0x01).  */
929   rc = check_signature2 (sig, md, NULL, is_expkey, is_revkey, NULL);
930   if (! rc)
931     md_good = md;
932   else if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE && md2)
933     {
934       rc = check_signature2 (sig, md2, NULL, is_expkey, is_revkey, NULL);
935       if (! rc)
936         md_good = md2;
937     }
938
939   if (md_good)
940     {
941       unsigned char *buffer = gcry_md_read (md_good, 0);
942       sig->digest_len = gcry_md_get_algo_dlen (map_md_openpgp_to_gcry (algo));
943       memcpy (sig->digest, buffer, sig->digest_len);
944     }
945
946   gcry_md_close (md);
947   gcry_md_close (md2);
948
949   return rc;
950 }
951
952
953 static void
954 print_userid (PACKET *pkt)
955 {
956   if (!pkt)
957     BUG();
958
959   if (pkt->pkttype != PKT_USER_ID)
960     {
961       es_printf ("ERROR: unexpected packet type %d", pkt->pkttype );
962       return;
963     }
964   if (opt.with_colons)
965     {
966       if (pkt->pkt.user_id->attrib_data)
967         es_printf("%u %lu",
968                   pkt->pkt.user_id->numattribs,
969                   pkt->pkt.user_id->attrib_len);
970       else
971         es_write_sanitized (es_stdout, pkt->pkt.user_id->name,
972                             pkt->pkt.user_id->len, ":", NULL);
973     }
974   else
975     print_utf8_buffer (es_stdout, pkt->pkt.user_id->name,
976                        pkt->pkt.user_id->len );
977 }
978
979
980 /*
981  * List the keyblock in a user friendly way
982  */
983 static void
984 list_node (CTX c, kbnode_t node)
985 {
986   if (!node)
987     ;
988   else if (node->pkt->pkttype == PKT_PUBLIC_KEY
989            || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
990     {
991       PKT_public_key *pk = node->pkt->pkt.public_key;
992
993       if (opt.with_colons)
994         {
995           u32 keyid[2];
996
997           keyid_from_pk( pk, keyid );
998           if (pk->flags.primary)
999             c->trustletter = (opt.fast_list_mode?
1000                               0 : get_validity_info (c->ctrl, pk, NULL));
1001           es_printf ("%s:", pk->flags.primary? "pub":"sub" );
1002           if (c->trustletter)
1003             es_putc (c->trustletter, es_stdout);
1004           es_printf (":%u:%d:%08lX%08lX:%s:%s::",
1005                      nbits_from_pk( pk ),
1006                      pk->pubkey_algo,
1007                      (ulong)keyid[0],(ulong)keyid[1],
1008                      colon_datestr_from_pk( pk ),
1009                      colon_strtime (pk->expiredate) );
1010           if (pk->flags.primary && !opt.fast_list_mode)
1011             es_putc (get_ownertrust_info (pk), es_stdout);
1012           es_putc (':', es_stdout);
1013           es_putc ('\n', es_stdout);
1014         }
1015       else
1016         {
1017           print_key_line (es_stdout, pk, 0);
1018         }
1019
1020       if (opt.keyid_format == KF_NONE && !opt.with_colons)
1021         ; /* Already printed.  */
1022       else if ((pk->flags.primary && opt.fingerprint) || opt.fingerprint > 1)
1023         print_fingerprint (NULL, pk, 0);
1024
1025       if (opt.with_colons)
1026         {
1027           if (node->next && node->next->pkt->pkttype == PKT_RING_TRUST)
1028             es_printf ("rtv:1:%u:\n",
1029                        node->next->pkt->pkt.ring_trust->trustval);
1030         }
1031
1032       if (pk->flags.primary)
1033         {
1034           int kl = opt.keyid_format == KF_NONE? 0 : keystrlen ();
1035
1036           /* Now list all userids with their signatures. */
1037           for (node = node->next; node; node = node->next)
1038             {
1039               if (node->pkt->pkttype == PKT_SIGNATURE)
1040                 {
1041                   list_node (c,  node );
1042                 }
1043               else if (node->pkt->pkttype == PKT_USER_ID)
1044                 {
1045                   if (opt.with_colons)
1046                     es_printf ("%s:::::::::",
1047                                node->pkt->pkt.user_id->attrib_data?"uat":"uid");
1048                   else
1049                     es_printf ("uid%*s",
1050                                kl + (opt.legacy_list_mode? 9:11),
1051                                "" );
1052                   print_userid (node->pkt);
1053                   if (opt.with_colons)
1054                     es_putc (':', es_stdout);
1055                   es_putc ('\n', es_stdout);
1056                   if (opt.with_colons
1057                       && node->next
1058                       && node->next->pkt->pkttype == PKT_RING_TRUST)
1059                     {
1060                       es_printf ("rtv:2:%u:\n",
1061                                  node->next->pkt->pkt.ring_trust?
1062                                  node->next->pkt->pkt.ring_trust->trustval : 0);
1063                     }
1064                 }
1065               else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1066                 {
1067                   list_node(c,  node );
1068                 }
1069             }
1070         }
1071     }
1072   else if (node->pkt->pkttype == PKT_SECRET_KEY
1073            || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1074     {
1075
1076       log_debug ("FIXME: No way to print secret key packets here\n");
1077       /* fixme: We may use a function to turn a secret key packet into
1078          a public key one and use that here.  */
1079     }
1080   else if (node->pkt->pkttype == PKT_SIGNATURE)
1081     {
1082       PKT_signature *sig = node->pkt->pkt.signature;
1083       int is_selfsig = 0;
1084       int rc2 = 0;
1085       size_t n;
1086       char *p;
1087       int sigrc = ' ';
1088
1089       if (!opt.verbose)
1090         return;
1091
1092       if (sig->sig_class == 0x20 || sig->sig_class == 0x30)
1093         es_fputs ("rev", es_stdout);
1094       else
1095         es_fputs ("sig", es_stdout);
1096       if (opt.check_sigs)
1097         {
1098           fflush (stdout);
1099           rc2 = do_check_sig (c, node, &is_selfsig, NULL, NULL);
1100           switch (gpg_err_code (rc2))
1101             {
1102             case 0:                       sigrc = '!'; break;
1103             case GPG_ERR_BAD_SIGNATURE:   sigrc = '-'; break;
1104             case GPG_ERR_NO_PUBKEY:
1105             case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break;
1106             default:                      sigrc = '%'; break;
1107             }
1108         }
1109       else /* Check whether this is a self signature.  */
1110         {
1111           u32 keyid[2];
1112
1113           if (c->list->pkt->pkttype == PKT_PUBLIC_KEY
1114               || c->list->pkt->pkttype == PKT_SECRET_KEY )
1115             {
1116               keyid_from_pk (c->list->pkt->pkt.public_key, keyid);
1117
1118               if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1])
1119                 is_selfsig = 1;
1120             }
1121         }
1122
1123       if (opt.with_colons)
1124         {
1125           es_putc (':', es_stdout);
1126           if (sigrc != ' ')
1127             es_putc (sigrc, es_stdout);
1128           es_printf ("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo,
1129                      (ulong)sig->keyid[0], (ulong)sig->keyid[1],
1130                      colon_datestr_from_sig (sig),
1131                      colon_expirestr_from_sig (sig));
1132
1133           if (sig->trust_depth || sig->trust_value)
1134             es_printf ("%d %d",sig->trust_depth,sig->trust_value);
1135           es_putc (':', es_stdout);
1136
1137           if (sig->trust_regexp)
1138             es_write_sanitized (es_stdout, sig->trust_regexp,
1139                                 strlen (sig->trust_regexp), ":", NULL);
1140           es_putc (':', es_stdout);
1141         }
1142       else
1143         es_printf ("%c       %s %s   ",
1144                    sigrc, keystr (sig->keyid), datestr_from_sig(sig));
1145       if (sigrc == '%')
1146         es_printf ("[%s] ", gpg_strerror (rc2) );
1147       else if (sigrc == '?')
1148         ;
1149       else if (is_selfsig)
1150         {
1151           if (opt.with_colons)
1152             es_putc (':', es_stdout);
1153           es_fputs (sig->sig_class == 0x18? "[keybind]":"[selfsig]", es_stdout);
1154           if (opt.with_colons)
1155             es_putc (':', es_stdout);
1156         }
1157       else if (!opt.fast_list_mode)
1158         {
1159           p = get_user_id (sig->keyid, &n);
1160           es_write_sanitized (es_stdout, p, n,
1161                               opt.with_colons?":":NULL, NULL );
1162           xfree (p);
1163         }
1164       if (opt.with_colons)
1165         es_printf (":%02x%c:", sig->sig_class, sig->flags.exportable?'x':'l');
1166       es_putc ('\n', es_stdout);
1167     }
1168   else
1169     log_error ("invalid node with packet of type %d\n", node->pkt->pkttype);
1170 }
1171
1172
1173 int
1174 proc_packets (ctrl_t ctrl, void *anchor, iobuf_t a )
1175 {
1176   int rc;
1177   CTX c = xmalloc_clear (sizeof *c);
1178
1179   c->ctrl = ctrl;
1180   c->anchor = anchor;
1181   rc = do_proc_packets (ctrl, c, a);
1182   xfree (c);
1183
1184   return rc;
1185 }
1186
1187
1188 int
1189 proc_signature_packets (ctrl_t ctrl, void *anchor, iobuf_t a,
1190                         strlist_t signedfiles, const char *sigfilename )
1191 {
1192   CTX c = xmalloc_clear (sizeof *c);
1193   int rc;
1194
1195   c->ctrl = ctrl;
1196   c->anchor = anchor;
1197   c->sigs_only = 1;
1198
1199   c->signed_data.data_fd = -1;
1200   c->signed_data.data_names = signedfiles;
1201   c->signed_data.used = !!signedfiles;
1202
1203   c->sigfilename = sigfilename;
1204   rc = do_proc_packets (ctrl, c, a);
1205
1206   /* If we have not encountered any signature we print an error
1207      messages, send a NODATA status back and return an error code.
1208      Using log_error is required because verify_files does not check
1209      error codes for each file but we want to terminate the process
1210      with an error. */
1211   if (!rc && !c->any.sig_seen)
1212     {
1213       write_status_text (STATUS_NODATA, "4");
1214       log_error (_("no signature found\n"));
1215       rc = GPG_ERR_NO_DATA;
1216     }
1217
1218   /* Propagate the signature seen flag upward. Do this only on success
1219      so that we won't issue the nodata status several times.  */
1220   if (!rc && c->anchor && c->any.sig_seen)
1221     c->anchor->any.sig_seen = 1;
1222
1223   xfree (c);
1224   return rc;
1225 }
1226
1227
1228 int
1229 proc_signature_packets_by_fd (ctrl_t ctrl,
1230                               void *anchor, iobuf_t a, int signed_data_fd )
1231 {
1232   int rc;
1233   CTX c;
1234
1235   c = xtrycalloc (1, sizeof *c);
1236   if (!c)
1237     return gpg_error_from_syserror ();
1238
1239   c->ctrl = ctrl;
1240   c->anchor = anchor;
1241   c->sigs_only = 1;
1242
1243   c->signed_data.data_fd = signed_data_fd;
1244   c->signed_data.data_names = NULL;
1245   c->signed_data.used = (signed_data_fd != -1);
1246
1247   rc = do_proc_packets (ctrl, c, a);
1248
1249   /* If we have not encountered any signature we print an error
1250      messages, send a NODATA status back and return an error code.
1251      Using log_error is required because verify_files does not check
1252      error codes for each file but we want to terminate the process
1253      with an error. */
1254   if (!rc && !c->any.sig_seen)
1255     {
1256       write_status_text (STATUS_NODATA, "4");
1257       log_error (_("no signature found\n"));
1258       rc = gpg_error (GPG_ERR_NO_DATA);
1259     }
1260
1261   /* Propagate the signature seen flag upward. Do this only on success
1262      so that we won't issue the nodata status several times. */
1263   if (!rc && c->anchor && c->any.sig_seen)
1264     c->anchor->any.sig_seen = 1;
1265
1266   xfree ( c );
1267   return rc;
1268 }
1269
1270
1271 int
1272 proc_encryption_packets (ctrl_t ctrl, void *anchor, iobuf_t a )
1273 {
1274   CTX c = xmalloc_clear (sizeof *c);
1275   int rc;
1276
1277   c->ctrl = ctrl;
1278   c->anchor = anchor;
1279   c->encrypt_only = 1;
1280   rc = do_proc_packets (ctrl, c, a);
1281   xfree (c);
1282   return rc;
1283 }
1284
1285
1286 static int
1287 check_nesting (CTX c)
1288 {
1289   int level;
1290
1291   for (level=0; c; c = c->anchor)
1292     level++;
1293
1294   if (level > MAX_NESTING_DEPTH)
1295     {
1296       log_error ("input data with too deeply nested packets\n");
1297       write_status_text (STATUS_UNEXPECTED, "1");
1298       return GPG_ERR_BAD_DATA;
1299     }
1300
1301   return 0;
1302 }
1303
1304
1305 static int
1306 do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
1307 {
1308   PACKET *pkt;
1309   int rc = 0;
1310   int any_data = 0;
1311   int newpkt;
1312
1313   rc = check_nesting (c);
1314   if (rc)
1315     return rc;
1316
1317   pkt = xmalloc( sizeof *pkt );
1318   c->iobuf = a;
1319   init_packet(pkt);
1320   while ((rc=parse_packet(a, pkt)) != -1)
1321     {
1322       any_data = 1;
1323       if (rc)
1324         {
1325           free_packet (pkt);
1326           /* Stop processing when an invalid packet has been encountered
1327            * but don't do so when we are doing a --list-packets.  */
1328           if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
1329               && opt.list_packets == 0)
1330             break;
1331           continue;
1332         }
1333       newpkt = -1;
1334       if (opt.list_packets)
1335         {
1336           switch (pkt->pkttype)
1337             {
1338             case PKT_PUBKEY_ENC:    proc_pubkey_enc (ctrl, c, pkt); break;
1339             case PKT_SYMKEY_ENC:    proc_symkey_enc (c, pkt); break;
1340             case PKT_ENCRYPTED:
1341             case PKT_ENCRYPTED_MDC: proc_encrypted (c, pkt); break;
1342             case PKT_COMPRESSED:    rc = proc_compressed (c, pkt); break;
1343             default: newpkt = 0; break;
1344             }
1345         }
1346       else if (c->sigs_only)
1347         {
1348           switch (pkt->pkttype)
1349             {
1350             case PKT_PUBLIC_KEY:
1351             case PKT_SECRET_KEY:
1352             case PKT_USER_ID:
1353             case PKT_SYMKEY_ENC:
1354             case PKT_PUBKEY_ENC:
1355             case PKT_ENCRYPTED:
1356             case PKT_ENCRYPTED_MDC:
1357               write_status_text( STATUS_UNEXPECTED, "0" );
1358               rc = GPG_ERR_UNEXPECTED;
1359               goto leave;
1360
1361             case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1362             case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1363             case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1364             case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1365             case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break;
1366             default: newpkt = 0; break;
1367             }
1368         }
1369       else if (c->encrypt_only)
1370         {
1371           switch (pkt->pkttype)
1372             {
1373             case PKT_PUBLIC_KEY:
1374             case PKT_SECRET_KEY:
1375             case PKT_USER_ID:
1376               write_status_text (STATUS_UNEXPECTED, "0");
1377               rc = GPG_ERR_UNEXPECTED;
1378               goto leave;
1379
1380             case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1381             case PKT_SYMKEY_ENC:  proc_symkey_enc (c, pkt); break;
1382             case PKT_PUBKEY_ENC:  proc_pubkey_enc (ctrl, c, pkt); break;
1383             case PKT_ENCRYPTED:
1384             case PKT_ENCRYPTED_MDC: proc_encrypted (c, pkt); break;
1385             case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1386             case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1387             case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1388             case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break;
1389             default: newpkt = 0; break;
1390             }
1391         }
1392       else
1393         {
1394           switch (pkt->pkttype)
1395             {
1396             case PKT_PUBLIC_KEY:
1397             case PKT_SECRET_KEY:
1398               release_list (c);
1399               c->list = new_kbnode (pkt);
1400               newpkt = 1;
1401               break;
1402             case PKT_PUBLIC_SUBKEY:
1403             case PKT_SECRET_SUBKEY:
1404               newpkt = add_subkey (c, pkt);
1405               break;
1406             case PKT_USER_ID:     newpkt = add_user_id (c, pkt); break;
1407             case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1408             case PKT_PUBKEY_ENC:  proc_pubkey_enc (ctrl, c, pkt); break;
1409             case PKT_SYMKEY_ENC:  proc_symkey_enc (c, pkt); break;
1410             case PKT_ENCRYPTED:
1411             case PKT_ENCRYPTED_MDC: proc_encrypted (c, pkt); break;
1412             case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1413             case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1414             case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1415             case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
1416             case PKT_RING_TRUST:  newpkt = add_ring_trust (c, pkt); break;
1417             default: newpkt = 0; break;
1418             }
1419         }
1420
1421       if (rc)
1422         goto leave;
1423
1424       /* This is a very ugly construct and frankly, I don't remember why
1425        * I used it.  Adding the MDC check here is a hack.
1426        * The right solution is to initiate another context for encrypted
1427        * packet and not to reuse the current one ...  It works right
1428        * when there is a compression packet between which adds just
1429        * an extra layer.
1430        * Hmmm: Rewrite this whole module here??
1431        */
1432       if (pkt->pkttype != PKT_SIGNATURE && pkt->pkttype != PKT_MDC)
1433         c->any.data = (pkt->pkttype == PKT_PLAINTEXT);
1434
1435       if (newpkt == -1)
1436         ;
1437       else if (newpkt)
1438         {
1439           pkt = xmalloc (sizeof *pkt);
1440           init_packet (pkt);
1441         }
1442       else
1443         free_packet(pkt);
1444     }
1445
1446   if (rc == GPG_ERR_INV_PACKET)
1447     write_status_text (STATUS_NODATA, "3");
1448
1449   if (any_data)
1450     rc = 0;
1451   else if (rc == -1)
1452     write_status_text (STATUS_NODATA, "2");
1453
1454
1455  leave:
1456   release_list (c);
1457   xfree(c->dek);
1458   free_packet (pkt);
1459   xfree (pkt);
1460   free_md_filter_context (&c->mfx);
1461   return rc;
1462 }
1463
1464
1465 /* Helper for pka_uri_from_sig to parse the to-be-verified address out
1466    of the notation data. */
1467 static pka_info_t *
1468 get_pka_address (PKT_signature *sig)
1469 {
1470   pka_info_t *pka = NULL;
1471   struct notation *nd,*notation;
1472
1473   notation=sig_to_notation(sig);
1474
1475   for(nd=notation;nd;nd=nd->next)
1476     {
1477       if(strcmp(nd->name,"pka-address@gnupg.org")!=0)
1478         continue; /* Not the notation we want. */
1479
1480       /* For now we only use the first valid PKA notation. In future
1481          we might want to keep additional PKA notations in a linked
1482          list. */
1483       if (is_valid_mailbox (nd->value))
1484         {
1485           pka = xmalloc (sizeof *pka + strlen(nd->value));
1486           pka->valid = 0;
1487           pka->checked = 0;
1488           pka->uri = NULL;
1489           strcpy (pka->email, nd->value);
1490           break;
1491         }
1492     }
1493
1494   free_notation(notation);
1495
1496   return pka;
1497 }
1498
1499
1500 /* Return the URI from a DNS PKA record.  If this record has already
1501    be retrieved for the signature we merely return it; if not we go
1502    out and try to get that DNS record. */
1503 static const char *
1504 pka_uri_from_sig (CTX c, PKT_signature *sig)
1505 {
1506   if (!sig->flags.pka_tried)
1507     {
1508       log_assert (!sig->pka_info);
1509       sig->flags.pka_tried = 1;
1510       sig->pka_info = get_pka_address (sig);
1511       if (sig->pka_info)
1512         {
1513           char *url;
1514           unsigned char *fpr;
1515           size_t fprlen;
1516
1517           if (!gpg_dirmngr_get_pka (c->ctrl, sig->pka_info->email,
1518                                     &fpr, &fprlen, &url))
1519             {
1520               if (fpr && fprlen == sizeof sig->pka_info->fpr)
1521                 {
1522                   memcpy (sig->pka_info->fpr, fpr, fprlen);
1523                   if (url)
1524                     {
1525                       sig->pka_info->valid = 1;
1526                       if (!*url)
1527                         xfree (url);
1528                       else
1529                         sig->pka_info->uri = url;
1530                       url = NULL;
1531                     }
1532                 }
1533               xfree (fpr);
1534               xfree (url);
1535             }
1536         }
1537     }
1538   return sig->pka_info? sig->pka_info->uri : NULL;
1539 }
1540
1541
1542 /* Return true if the AKL has the WKD method specified.  */
1543 static int
1544 akl_has_wkd_method (void)
1545 {
1546   struct akl *akl;
1547
1548   for (akl = opt.auto_key_locate; akl; akl = akl->next)
1549     if (akl->type == AKL_WKD)
1550       return 1;
1551   return 0;
1552 }
1553
1554
1555 /* Return the ISSUER fingerprint string in human readbale format if
1556  * available.  Caller must release the string.  */
1557 static char *
1558 issuer_fpr_string (PKT_signature *sig)
1559 {
1560   const byte *p;
1561   size_t n;
1562
1563   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_ISSUER_FPR, &n);
1564   if (p && n == 21 && p[0] == 4)
1565     return bin2hex (p+1, n-1, NULL);
1566   return NULL;
1567 }
1568
1569
1570 static void
1571 print_good_bad_signature (int statno, const char *keyid_str, kbnode_t un,
1572                           PKT_signature *sig, int rc)
1573 {
1574   char *p;
1575
1576   write_status_text_and_buffer (statno, keyid_str,
1577                                 un? un->pkt->pkt.user_id->name:"[?]",
1578                                 un? un->pkt->pkt.user_id->len:3,
1579                                 -1);
1580
1581   if (un)
1582     p = utf8_to_native (un->pkt->pkt.user_id->name,
1583                         un->pkt->pkt.user_id->len, 0);
1584   else
1585     p = xstrdup ("[?]");
1586
1587   if (rc)
1588     log_info (_("BAD signature from \"%s\""), p);
1589   else if (sig->flags.expired)
1590     log_info (_("Expired signature from \"%s\""), p);
1591   else
1592     log_info (_("Good signature from \"%s\""), p);
1593
1594   xfree (p);
1595 }
1596
1597
1598 static int
1599 check_sig_and_print (CTX c, kbnode_t node)
1600 {
1601   PKT_signature *sig = node->pkt->pkt.signature;
1602   const char *astr;
1603   int rc;
1604   int is_expkey = 0;
1605   int is_revkey = 0;
1606   char pkstrbuf[PUBKEY_STRING_SIZE];
1607   char *issuer_fpr;
1608
1609   *pkstrbuf = 0;
1610
1611   if (opt.skip_verify)
1612     {
1613       log_info(_("signature verification suppressed\n"));
1614       return 0;
1615     }
1616
1617   /* Check that the message composition is valid.
1618    *
1619    * Per RFC-2440bis (-15) allowed:
1620    *
1621    * S{1,n}           -- detached signature.
1622    * S{1,n} P         -- old style PGP2 signature
1623    * O{1,n} P S{1,n}  -- standard OpenPGP signature.
1624    * C P S{1,n}       -- cleartext signature.
1625    *
1626    *
1627    *      O = One-Pass Signature packet.
1628    *      S = Signature packet.
1629    *      P = OpenPGP Message packet (Encrypted | Compressed | Literal)
1630    *             (Note that the current rfc2440bis draft also allows
1631    *              for a signed message but that does not work as it
1632    *              introduces ambiguities.)
1633    *          We keep track of these packages using the marker packet
1634    *          CTRLPKT_PLAINTEXT_MARK.
1635    *      C = Marker packet for cleartext signatures.
1636    *
1637    * We reject all other messages.
1638    *
1639    * Actually we are calling this too often, i.e. for verification of
1640    * each message but better have some duplicate work than to silently
1641    * introduce a bug here.
1642    */
1643   {
1644     kbnode_t n;
1645     int n_onepass, n_sig;
1646
1647 /*     log_debug ("checking signature packet composition\n"); */
1648 /*     dump_kbnode (c->list); */
1649
1650     n = c->list;
1651     log_assert (n);
1652     if ( n->pkt->pkttype == PKT_SIGNATURE )
1653       {
1654         /* This is either "S{1,n}" case (detached signature) or
1655            "S{1,n} P" (old style PGP2 signature). */
1656         for (n = n->next; n; n = n->next)
1657           if (n->pkt->pkttype != PKT_SIGNATURE)
1658             break;
1659         if (!n)
1660           ; /* Okay, this is a detached signature.  */
1661         else if (n->pkt->pkttype == PKT_GPG_CONTROL
1662                  && (n->pkt->pkt.gpg_control->control
1663                      == CTRLPKT_PLAINTEXT_MARK) )
1664           {
1665             if (n->next)
1666               goto ambiguous;  /* We only allow one P packet. */
1667           }
1668         else
1669           goto ambiguous;
1670       }
1671     else if (n->pkt->pkttype == PKT_ONEPASS_SIG)
1672       {
1673         /* This is the "O{1,n} P S{1,n}" case (standard signature). */
1674         for (n_onepass=1, n = n->next;
1675              n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next)
1676           n_onepass++;
1677         if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
1678                     && (n->pkt->pkt.gpg_control->control
1679                         == CTRLPKT_PLAINTEXT_MARK)))
1680           goto ambiguous;
1681         for (n_sig=0, n = n->next;
1682              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
1683           n_sig++;
1684         if (!n_sig)
1685           goto ambiguous;
1686
1687         /* If we wanted to disallow multiple sig verification, we'd do
1688            something like this:
1689
1690            if (n && !opt.allow_multisig_verification)
1691              goto ambiguous;
1692
1693            However, now that we have --allow-multiple-messages, this
1694            can stay allowable as we can't get here unless multiple
1695            messages (i.e. multiple literals) are allowed. */
1696
1697         if (n_onepass != n_sig)
1698           {
1699             log_info ("number of one-pass packets does not match "
1700                       "number of signature packets\n");
1701             goto ambiguous;
1702           }
1703       }
1704     else if (n->pkt->pkttype == PKT_GPG_CONTROL
1705              && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
1706       {
1707         /* This is the "C P S{1,n}" case (clear text signature). */
1708         n = n->next;
1709         if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
1710                     && (n->pkt->pkt.gpg_control->control
1711                         == CTRLPKT_PLAINTEXT_MARK)))
1712           goto ambiguous;
1713         for (n_sig=0, n = n->next;
1714              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
1715           n_sig++;
1716         if (n || !n_sig)
1717           goto ambiguous;
1718       }
1719     else
1720       {
1721       ambiguous:
1722         log_error(_("can't handle this ambiguous signature data\n"));
1723         return 0;
1724       }
1725   }
1726
1727   if (sig->signers_uid)
1728     write_status_buffer (STATUS_NEWSIG,
1729                          sig->signers_uid, strlen (sig->signers_uid), 0);
1730   else
1731     write_status_text (STATUS_NEWSIG, NULL);
1732
1733   astr = openpgp_pk_algo_name ( sig->pubkey_algo );
1734   if (opt.flags.rfc4880bis && (issuer_fpr = issuer_fpr_string (sig)))
1735     {
1736       log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
1737       log_info (_("               using %s key %s\n"),
1738                 astr? astr: "?", issuer_fpr);
1739
1740       xfree (issuer_fpr);
1741     }
1742   else if (!keystrlen () || keystrlen () > 8)
1743     {
1744       log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
1745       log_info (_("               using %s key %s\n"),
1746                 astr? astr: "?", keystr(sig->keyid));
1747     }
1748   else /* Legacy format.  */
1749     log_info (_("Signature made %s using %s key ID %s\n"),
1750               asctimestamp(sig->timestamp), astr? astr: "?",
1751               keystr(sig->keyid));
1752
1753   /* In verbose mode print the signers UID.  */
1754   if (sig->signers_uid)
1755     log_info (_("               issuer \"%s\"\n"), sig->signers_uid);
1756
1757   rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey );
1758
1759   /* If the key isn't found, check for a preferred keyserver.  */
1760   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && sig->flags.pref_ks)
1761     {
1762       const byte *p;
1763       int seq = 0;
1764       size_t n;
1765
1766       while ((p=enum_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS,&n,&seq,NULL)))
1767         {
1768           /* According to my favorite copy editor, in English grammar,
1769              you say "at" if the key is located on a web page, but
1770              "from" if it is located on a keyserver.  I'm not going to
1771              even try to make two strings here :) */
1772           log_info(_("Key available at: ") );
1773           print_utf8_buffer (log_get_stream(), p, n);
1774           log_printf ("\n");
1775
1776           if (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE
1777               && opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1778             {
1779               struct keyserver_spec *spec;
1780
1781               spec = parse_preferred_keyserver (sig);
1782               if (spec)
1783                 {
1784                   int res;
1785
1786                   glo_ctrl.in_auto_key_retrieve++;
1787                   res = keyserver_import_keyid (c->ctrl, sig->keyid,spec);
1788                   glo_ctrl.in_auto_key_retrieve--;
1789                   if (!res)
1790                     rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
1791                   free_keyserver_spec (spec);
1792
1793                   if (!rc)
1794                     break;
1795                 }
1796             }
1797         }
1798     }
1799
1800   /* If the avove methods didn't work, our next try is to use the URI
1801    * from a DNS PKA record.  */
1802   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1803       && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
1804       && (opt.keyserver_options.options & KEYSERVER_HONOR_PKA_RECORD))
1805     {
1806       const char *uri = pka_uri_from_sig (c, sig);
1807
1808       if (uri)
1809         {
1810           /* FIXME: We might want to locate the key using the
1811              fingerprint instead of the keyid. */
1812           int res;
1813           struct keyserver_spec *spec;
1814
1815           spec = parse_keyserver_uri (uri, 1);
1816           if (spec)
1817             {
1818               glo_ctrl.in_auto_key_retrieve++;
1819               res = keyserver_import_keyid (c->ctrl, sig->keyid, spec);
1820               glo_ctrl.in_auto_key_retrieve--;
1821               free_keyserver_spec (spec);
1822               if (!res)
1823                 rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey );
1824             }
1825         }
1826     }
1827
1828   /* If the above methods didn't work, our next try is to use locate
1829    * the key via its fingerprint from a keyserver.  This requires
1830    * that the signers fingerprint is encoded in the signature.  We
1831    * favor this over the WKD method (to be tried next), because an
1832    * arbitrary keyserver is less subject to web bug like
1833    * monitoring.  */
1834   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1835       && opt.flags.rfc4880bis
1836       && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
1837       && keyserver_any_configured (c->ctrl))
1838     {
1839       int res;
1840       const byte *p;
1841       size_t n;
1842
1843       p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_ISSUER_FPR, &n);
1844       if (p && n == 21 && p[0] == 4)
1845         {
1846           /* v4 packet with a SHA-1 fingerprint.  */
1847           glo_ctrl.in_auto_key_retrieve++;
1848           res = keyserver_import_fprint (c->ctrl, p+1, n-1, opt.keyserver);
1849           glo_ctrl.in_auto_key_retrieve--;
1850           if (!res)
1851             rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey );
1852         }
1853     }
1854
1855   /* If the above methods didn't work, our next try is to retrieve the
1856    * key from the WKD. */
1857   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1858       && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
1859       && !opt.flags.disable_signer_uid
1860       && akl_has_wkd_method ()
1861       && sig->signers_uid)
1862     {
1863       int res;
1864
1865       glo_ctrl.in_auto_key_retrieve++;
1866       res = keyserver_import_wkd (c->ctrl, sig->signers_uid, NULL, NULL);
1867       glo_ctrl.in_auto_key_retrieve--;
1868       /* Fixme: If the fingerprint is embedded in the signature,
1869        * compare it to the fingerprint of the returned key.  */
1870       if (!res)
1871         rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey );
1872     }
1873
1874   /* If the above methods did't work, our next try is to use a
1875    * keyserver.  */
1876   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1877       && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
1878       && keyserver_any_configured (c->ctrl))
1879     {
1880       int res;
1881
1882       glo_ctrl.in_auto_key_retrieve++;
1883       res = keyserver_import_keyid (c->ctrl, sig->keyid, opt.keyserver );
1884       glo_ctrl.in_auto_key_retrieve--;
1885       if (!res)
1886         rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey );
1887     }
1888
1889   if (!rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
1890     {
1891       kbnode_t un, keyblock;
1892       int count = 0;
1893       int statno;
1894       char keyid_str[50];
1895       PKT_public_key *pk = NULL;
1896
1897       if (rc)
1898         statno = STATUS_BADSIG;
1899       else if (sig->flags.expired)
1900         statno = STATUS_EXPSIG;
1901       else if (is_expkey)
1902         statno = STATUS_EXPKEYSIG;
1903       else if(is_revkey)
1904         statno = STATUS_REVKEYSIG;
1905       else
1906         statno = STATUS_GOODSIG;
1907
1908       keyblock = get_pubkeyblock (sig->keyid);
1909
1910       snprintf (keyid_str, sizeof keyid_str, "%08lX%08lX [uncertain] ",
1911                 (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
1912
1913       /* Find and print the primary user ID along with the
1914          "Good|Expired|Bad signature" line.  */
1915       for (un=keyblock; un; un = un->next)
1916         {
1917           int valid;
1918
1919           if (un->pkt->pkttype==PKT_PUBLIC_KEY)
1920             {
1921               pk=un->pkt->pkt.public_key;
1922               continue;
1923             }
1924           if (un->pkt->pkttype != PKT_USER_ID)
1925             continue;
1926           if (!un->pkt->pkt.user_id->created)
1927             continue;
1928           if (un->pkt->pkt.user_id->is_revoked)
1929             continue;
1930           if (un->pkt->pkt.user_id->is_expired)
1931             continue;
1932           if (!un->pkt->pkt.user_id->is_primary)
1933             continue;
1934           /* We want the textual primary user ID here */
1935           if (un->pkt->pkt.user_id->attrib_data)
1936             continue;
1937
1938           log_assert (pk);
1939
1940           /* Since this is just informational, don't actually ask the
1941              user to update any trust information.  (Note: we register
1942              the signature later.)  Because print_good_bad_signature
1943              does not print a LF we need to compute the validity
1944              before calling that function.  */
1945           if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
1946             valid = get_validity (c->ctrl, pk, un->pkt->pkt.user_id, NULL, 0);
1947           else
1948             valid = 0; /* Not used.  */
1949
1950           keyid_str[17] = 0; /* cut off the "[uncertain]" part */
1951
1952           print_good_bad_signature (statno, keyid_str, un, sig, rc);
1953
1954           if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
1955             log_printf (" [%s]\n",trust_value_to_string(valid));
1956           else
1957             log_printf ("\n");
1958
1959           /* Get a string description of the algo for informational
1960              output we want to print later.  It is convenient to do it
1961              here because we already have the right public key. */
1962           pubkey_string (pk, pkstrbuf, sizeof pkstrbuf);
1963           count++;
1964         }
1965
1966       /* In case we did not found a valid valid textual userid above
1967          we print the first user id packet or a "[?]" instead along
1968          with the "Good|Expired|Bad signature" line.  */
1969       if (!count)
1970         {
1971           /* Try for an invalid textual userid */
1972           for (un=keyblock; un; un = un->next)
1973             {
1974               if (un->pkt->pkttype == PKT_USER_ID
1975                   && !un->pkt->pkt.user_id->attrib_data)
1976                 break;
1977             }
1978
1979           /* Try for any userid at all */
1980           if (!un)
1981             {
1982               for (un=keyblock; un; un = un->next)
1983                 {
1984                   if (un->pkt->pkttype == PKT_USER_ID)
1985                     break;
1986                 }
1987             }
1988
1989           if (opt.trust_model==TM_ALWAYS || !un)
1990             keyid_str[17] = 0; /* cut off the "[uncertain]" part */
1991
1992           print_good_bad_signature (statno, keyid_str, un, sig, rc);
1993
1994           if (opt.trust_model != TM_ALWAYS && un)
1995             log_printf (" %s",_("[uncertain]") );
1996           log_printf ("\n");
1997         }
1998
1999       /* If we have a good signature and already printed
2000        * the primary user ID, print all the other user IDs */
2001       if (count
2002           && !rc
2003           && !(opt.verify_options & VERIFY_SHOW_PRIMARY_UID_ONLY))
2004         {
2005           char *p;
2006           for( un=keyblock; un; un = un->next)
2007             {
2008               if (un->pkt->pkttype != PKT_USER_ID)
2009                 continue;
2010               if ((un->pkt->pkt.user_id->is_revoked
2011                    || un->pkt->pkt.user_id->is_expired)
2012                   && !(opt.verify_options & VERIFY_SHOW_UNUSABLE_UIDS))
2013                 continue;
2014               /* Skip textual primary user ids which we printed above. */
2015               if (un->pkt->pkt.user_id->is_primary
2016                   && !un->pkt->pkt.user_id->attrib_data )
2017                 continue;
2018
2019               /* If this user id has attribute data, print that.  */
2020               if (un->pkt->pkt.user_id->attrib_data)
2021                 {
2022                   dump_attribs (un->pkt->pkt.user_id, pk);
2023
2024                   if (opt.verify_options&VERIFY_SHOW_PHOTOS)
2025                     show_photos (c->ctrl,
2026                                  un->pkt->pkt.user_id->attribs,
2027                                  un->pkt->pkt.user_id->numattribs,
2028                                  pk ,un->pkt->pkt.user_id);
2029                 }
2030
2031               p = utf8_to_native (un->pkt->pkt.user_id->name,
2032                                   un->pkt->pkt.user_id->len, 0);
2033               log_info (_("                aka \"%s\""), p);
2034               xfree (p);
2035
2036               if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2037                 {
2038                   const char *valid;
2039
2040                   if (un->pkt->pkt.user_id->is_revoked)
2041                     valid = _("revoked");
2042                   else if (un->pkt->pkt.user_id->is_expired)
2043                     valid = _("expired");
2044                   else
2045                     /* Since this is just informational, don't
2046                        actually ask the user to update any trust
2047                        information.  */
2048                     valid = (trust_value_to_string
2049                              (get_validity (c->ctrl, pk,
2050                                             un->pkt->pkt.user_id, sig, 0)));
2051                   log_printf (" [%s]\n",valid);
2052                 }
2053               else
2054                 log_printf ("\n");
2055             }
2056         }
2057       release_kbnode( keyblock );
2058
2059       /* For good signatures print notation data.  */
2060       if (!rc)
2061         {
2062           if ((opt.verify_options & VERIFY_SHOW_POLICY_URLS))
2063             show_policy_url (sig, 0, 1);
2064           else
2065             show_policy_url (sig, 0, 2);
2066
2067           if ((opt.verify_options & VERIFY_SHOW_KEYSERVER_URLS))
2068             show_keyserver_url (sig, 0, 1);
2069           else
2070             show_keyserver_url (sig, 0, 2);
2071
2072           if ((opt.verify_options & VERIFY_SHOW_NOTATIONS))
2073             show_notation
2074               (sig, 0, 1,
2075                (((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0)
2076                 + ((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0)));
2077           else
2078             show_notation (sig, 0, 2, 0);
2079         }
2080
2081       /* For good signatures print the VALIDSIG status line.  */
2082       if (!rc && is_status_enabled ())
2083         {
2084           PKT_public_key *vpk = xmalloc_clear (sizeof *vpk);
2085
2086           if (!get_pubkey (vpk, sig->keyid))
2087             {
2088               byte array[MAX_FINGERPRINT_LEN], *p;
2089               char buf[MAX_FINGERPRINT_LEN*4+90], *bufp;
2090               size_t i, n;
2091
2092               bufp = buf;
2093               fingerprint_from_pk (vpk, array, &n);
2094               p = array;
2095               for(i=0; i < n ; i++, p++, bufp += 2)
2096                 sprintf (bufp, "%02X", *p );
2097               /* TODO: Replace the reserved '0' in the field below
2098                  with bits for status flags (policy url, notation,
2099                  etc.).  Remember to make the buffer larger to match! */
2100               sprintf (bufp, " %s %lu %lu %d 0 %d %d %02X ",
2101                        strtimestamp( sig->timestamp ),
2102                        (ulong)sig->timestamp,(ulong)sig->expiredate,
2103                        sig->version,sig->pubkey_algo,sig->digest_algo,
2104                        sig->sig_class);
2105               bufp = bufp + strlen (bufp);
2106               if (!vpk->flags.primary)
2107                 {
2108                   u32 akid[2];
2109
2110                   akid[0] = vpk->main_keyid[0];
2111                   akid[1] = vpk->main_keyid[1];
2112                   free_public_key (vpk);
2113                   vpk = xmalloc_clear (sizeof *vpk);
2114                   if (get_pubkey (vpk, akid))
2115                     {
2116                       /* Impossible error, we simply return a zeroed out fpr */
2117                       n = MAX_FINGERPRINT_LEN < 20? MAX_FINGERPRINT_LEN : 20;
2118                       memset (array, 0, n);
2119                     }
2120                   else
2121                     fingerprint_from_pk( vpk, array, &n );
2122                 }
2123               p = array;
2124               for (i=0; i < n ; i++, p++, bufp += 2)
2125                 sprintf(bufp, "%02X", *p );
2126               write_status_text (STATUS_VALIDSIG, buf);
2127             }
2128           free_public_key (vpk);
2129         }
2130
2131       /* For good signatures compute and print the trust information.
2132          Note that in the Tofu trust model this may ask the user on
2133          how to resolve a conflict.  */
2134       if (!rc)
2135         {
2136           if ((opt.verify_options & VERIFY_PKA_LOOKUPS))
2137             pka_uri_from_sig (c, sig); /* Make sure PKA info is available. */
2138           rc = check_signatures_trust (c->ctrl, sig);
2139         }
2140
2141       /* Print extra information about the signature.  */
2142       if (sig->flags.expired)
2143         {
2144           log_info (_("Signature expired %s\n"), asctimestamp(sig->expiredate));
2145           rc = GPG_ERR_GENERAL; /* Need a better error here?  */
2146         }
2147       else if (sig->expiredate)
2148         log_info (_("Signature expires %s\n"), asctimestamp(sig->expiredate));
2149
2150       if (opt.verbose)
2151         log_info (_("%s signature, digest algorithm %s%s%s\n"),
2152                   sig->sig_class==0x00?_("binary"):
2153                   sig->sig_class==0x01?_("textmode"):_("unknown"),
2154                   gcry_md_algo_name (sig->digest_algo),
2155                   *pkstrbuf?_(", key algorithm "):"",
2156                   pkstrbuf);
2157
2158       /* Print final warnings.  */
2159       if (!rc && !c->signed_data.used)
2160         {
2161           /* Signature is basically good but we test whether the
2162              deprecated command
2163                gpg --verify FILE.sig
2164              was used instead of
2165                gpg --verify FILE.sig FILE
2166              to verify a detached signature.  If we figure out that a
2167              data file with a matching name exists, we print a warning.
2168
2169              The problem is that the first form would also verify a
2170              standard signature.  This behavior could be used to
2171              create a made up .sig file for a tarball by creating a
2172              standard signature from a valid detached signature packet
2173              (for example from a signed git tag).  Then replace the
2174              sig file on the FTP server along with a changed tarball.
2175              Using the first form the verify command would correctly
2176              verify the signature but don't even consider the tarball.  */
2177           kbnode_t n;
2178           char *dfile;
2179
2180           dfile = get_matching_datafile (c->sigfilename);
2181           if (dfile)
2182             {
2183               for (n = c->list; n; n = n->next)
2184                 if (n->pkt->pkttype != PKT_SIGNATURE)
2185                   break;
2186               if (n)
2187                 {
2188                   /* Not only signature packets in the tree thus this
2189                      is not a detached signature.  */
2190                   log_info (_("WARNING: not a detached signature; "
2191                               "file '%s' was NOT verified!\n"), dfile);
2192                 }
2193               xfree (dfile);
2194             }
2195         }
2196
2197       if (rc)
2198         g10_errors_seen = 1;
2199       if (opt.batch && rc)
2200         g10_exit (1);
2201     }
2202   else
2203     {
2204       char buf[50];
2205
2206       snprintf (buf, sizeof buf, "%08lX%08lX %d %d %02x %lu %d",
2207                 (ulong)sig->keyid[0], (ulong)sig->keyid[1],
2208                 sig->pubkey_algo, sig->digest_algo,
2209                 sig->sig_class, (ulong)sig->timestamp, rc);
2210       write_status_text (STATUS_ERRSIG, buf);
2211       if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2212         {
2213           buf[16] = 0;
2214           write_status_text (STATUS_NO_PUBKEY, buf);
2215         }
2216       if (gpg_err_code (rc) != GPG_ERR_NOT_PROCESSED)
2217         log_error (_("Can't check signature: %s\n"), gpg_strerror (rc));
2218     }
2219
2220   return rc;
2221 }
2222
2223
2224 /*
2225  * Process the tree which starts at node
2226  */
2227 static void
2228 proc_tree (CTX c, kbnode_t node)
2229 {
2230   kbnode_t n1;
2231   int rc;
2232
2233   if (opt.list_packets || opt.list_only)
2234     return;
2235
2236   /* We must skip our special plaintext marker packets here because
2237      they may be the root packet.  These packets are only used in
2238      addional checks and skipping them here doesn't matter.  */
2239   while (node
2240          && node->pkt->pkttype == PKT_GPG_CONTROL
2241           && node->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK)
2242     {
2243       node = node->next;
2244     }
2245   if (!node)
2246     return;
2247
2248   c->trustletter = ' ';
2249   if (node->pkt->pkttype == PKT_PUBLIC_KEY
2250       || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2251     {
2252       merge_keys_and_selfsig (node);
2253       list_node (c, node);
2254     }
2255   else if (node->pkt->pkttype == PKT_SECRET_KEY)
2256     {
2257       merge_keys_and_selfsig (node);
2258       list_node (c, node);
2259     }
2260   else if (node->pkt->pkttype == PKT_ONEPASS_SIG)
2261     {
2262       /* Check all signatures.  */
2263       if (!c->any.data)
2264         {
2265           int use_textmode = 0;
2266
2267           free_md_filter_context (&c->mfx);
2268           /* Prepare to create all requested message digests.  */
2269           rc = gcry_md_open (&c->mfx.md, 0, 0);
2270           if (rc)
2271             goto hash_err;
2272
2273           /* Fixme: why looking for the signature packet and not the
2274              one-pass packet?  */
2275           for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2276             gcry_md_enable (c->mfx.md, n1->pkt->pkt.signature->digest_algo);
2277
2278           if (n1 && n1->pkt->pkt.onepass_sig->sig_class == 0x01)
2279             use_textmode = 1;
2280
2281           /* Ask for file and hash it. */
2282           if (c->sigs_only)
2283             {
2284               if (c->signed_data.used && c->signed_data.data_fd != -1)
2285                 rc = hash_datafile_by_fd (c->mfx.md, NULL,
2286                                           c->signed_data.data_fd,
2287                                           use_textmode);
2288               else
2289                 rc = hash_datafiles (c->mfx.md, NULL,
2290                                      c->signed_data.data_names,
2291                                      c->sigfilename,
2292                                      use_textmode);
2293             }
2294           else
2295             {
2296               rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
2297                                               iobuf_get_real_fname (c->iobuf),
2298                                               use_textmode);
2299             }
2300
2301         hash_err:
2302           if (rc)
2303             {
2304               log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
2305               return;
2306             }
2307         }
2308       else if (c->signed_data.used)
2309         {
2310           log_error (_("not a detached signature\n"));
2311           return;
2312         }
2313
2314       for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2315         check_sig_and_print (c, n1);
2316
2317     }
2318   else if (node->pkt->pkttype == PKT_GPG_CONTROL
2319            && node->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START)
2320     {
2321       /* Clear text signed message.  */
2322       if (!c->any.data)
2323         {
2324           log_error ("cleartext signature without data\n");
2325           return;
2326         }
2327       else if (c->signed_data.used)
2328         {
2329           log_error (_("not a detached signature\n"));
2330           return;
2331         }
2332
2333       for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2334         check_sig_and_print (c, n1);
2335
2336     }
2337   else if (node->pkt->pkttype == PKT_SIGNATURE)
2338     {
2339       PKT_signature *sig = node->pkt->pkt.signature;
2340       int multiple_ok = 1;
2341
2342       n1 = find_next_kbnode (node, PKT_SIGNATURE);
2343       if (n1)
2344         {
2345           byte class = sig->sig_class;
2346           byte hash  = sig->digest_algo;
2347
2348           for (; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
2349             {
2350               /* We can't currently handle multiple signatures of
2351                  different classes or digests (we'd pretty much have
2352                  to run a different hash context for each), but if
2353                  they are all the same, make an exception. */
2354               if (n1->pkt->pkt.signature->sig_class != class
2355                   || n1->pkt->pkt.signature->digest_algo != hash)
2356                 {
2357                   multiple_ok = 0;
2358                   log_info (_("WARNING: multiple signatures detected.  "
2359                               "Only the first will be checked.\n"));
2360                   break;
2361                 }
2362             }
2363         }
2364
2365       if (sig->sig_class != 0x00 && sig->sig_class != 0x01)
2366         {
2367           log_info(_("standalone signature of class 0x%02x\n"), sig->sig_class);
2368         }
2369       else if (!c->any.data)
2370         {
2371           /* Detached signature */
2372           free_md_filter_context (&c->mfx);
2373           rc = gcry_md_open (&c->mfx.md, sig->digest_algo, 0);
2374           if (rc)
2375             goto detached_hash_err;
2376
2377           if (RFC2440 || RFC4880)
2378             ; /* Strict RFC mode.  */
2379           else if (sig->digest_algo == DIGEST_ALGO_SHA1
2380                    && sig->pubkey_algo == PUBKEY_ALGO_DSA
2381                    && sig->sig_class == 0x01)
2382             {
2383               /* Enable a workaround for a pgp5 bug when the detached
2384                * signature has been created in textmode.  */
2385               rc = gcry_md_open (&c->mfx.md2, sig->digest_algo, 0);
2386               if (rc)
2387                 goto detached_hash_err;
2388             }
2389
2390           /* Here we used to have another hack to work around a pgp
2391            * 2 bug: It worked by not using the textmode for detached
2392            * signatures; this would let the first signature check
2393            * (on md) fail but the second one (on md2), which adds an
2394            * extra CR would then have produced the "correct" hash.
2395            * This is very, very ugly hack but it may haved help in
2396            * some cases (and break others).
2397            *     c->mfx.md2? 0 :(sig->sig_class == 0x01)
2398            */
2399
2400           if (DBG_HASHING)
2401             {
2402               gcry_md_debug (c->mfx.md, "verify");
2403               if (c->mfx.md2)
2404                 gcry_md_debug (c->mfx.md2, "verify2");
2405             }
2406
2407           if (c->sigs_only)
2408             {
2409               if (c->signed_data.used && c->signed_data.data_fd != -1)
2410                 rc = hash_datafile_by_fd (c->mfx.md, c->mfx.md2,
2411                                           c->signed_data.data_fd,
2412                                           (sig->sig_class == 0x01));
2413               else
2414                 rc = hash_datafiles (c->mfx.md, c->mfx.md2,
2415                                      c->signed_data.data_names,
2416                                      c->sigfilename,
2417                                      (sig->sig_class == 0x01));
2418             }
2419           else
2420             {
2421               rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
2422                                               iobuf_get_real_fname(c->iobuf),
2423                                               (sig->sig_class == 0x01));
2424             }
2425
2426         detached_hash_err:
2427           if (rc)
2428             {
2429               log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
2430               return;
2431             }
2432         }
2433       else if (c->signed_data.used)
2434         {
2435           log_error (_("not a detached signature\n"));
2436           return;
2437         }
2438       else if (!opt.quiet)
2439         log_info (_("old style (PGP 2.x) signature\n"));
2440
2441       if (multiple_ok)
2442         {
2443           for (n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
2444             check_sig_and_print (c, n1);
2445         }
2446       else
2447         check_sig_and_print (c, node);
2448
2449     }
2450   else
2451     {
2452       dump_kbnode (c->list);
2453       log_error ("invalid root packet detected in proc_tree()\n");
2454       dump_kbnode (node);
2455     }
2456 }