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