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