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