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