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