512d33c59d7da1848bfc8951b9862f99c85fe10b
[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);
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 string in human readbale format if
1612  * available.  Caller must release the string.  */
1613 static char *
1614 issuer_fpr_string (PKT_signature *sig)
1615 {
1616   const byte *p;
1617   size_t n;
1618
1619   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_ISSUER_FPR, &n);
1620   if (p && n == 21 && p[0] == 4)
1621     return bin2hex (p+1, n-1, NULL);
1622   return NULL;
1623 }
1624
1625
1626 static void
1627 print_good_bad_signature (int statno, const char *keyid_str, kbnode_t un,
1628                           PKT_signature *sig, int rc)
1629 {
1630   char *p;
1631
1632   write_status_text_and_buffer (statno, keyid_str,
1633                                 un? un->pkt->pkt.user_id->name:"[?]",
1634                                 un? un->pkt->pkt.user_id->len:3,
1635                                 -1);
1636
1637   if (un)
1638     p = utf8_to_native (un->pkt->pkt.user_id->name,
1639                         un->pkt->pkt.user_id->len, 0);
1640   else
1641     p = xstrdup ("[?]");
1642
1643   if (rc)
1644     log_info (_("BAD signature from \"%s\""), p);
1645   else if (sig->flags.expired)
1646     log_info (_("Expired signature from \"%s\""), p);
1647   else
1648     log_info (_("Good signature from \"%s\""), p);
1649
1650   xfree (p);
1651 }
1652
1653
1654 static int
1655 check_sig_and_print (CTX c, kbnode_t node)
1656 {
1657   PKT_signature *sig = node->pkt->pkt.signature;
1658   const char *astr;
1659   int rc;
1660   int is_expkey = 0;
1661   int is_revkey = 0;
1662   char *issuer_fpr;
1663   PKT_public_key *pk = NULL;  /* The public key for the signature or NULL. */
1664   int tried_ks_by_fpr;
1665
1666   if (opt.skip_verify)
1667     {
1668       log_info(_("signature verification suppressed\n"));
1669       return 0;
1670     }
1671
1672   /* Check that the message composition is valid.
1673    *
1674    * Per RFC-2440bis (-15) allowed:
1675    *
1676    * S{1,n}           -- detached signature.
1677    * S{1,n} P         -- old style PGP2 signature
1678    * O{1,n} P S{1,n}  -- standard OpenPGP signature.
1679    * C P S{1,n}       -- cleartext signature.
1680    *
1681    *
1682    *      O = One-Pass Signature packet.
1683    *      S = Signature packet.
1684    *      P = OpenPGP Message packet (Encrypted | Compressed | Literal)
1685    *             (Note that the current rfc2440bis draft also allows
1686    *              for a signed message but that does not work as it
1687    *              introduces ambiguities.)
1688    *          We keep track of these packages using the marker packet
1689    *          CTRLPKT_PLAINTEXT_MARK.
1690    *      C = Marker packet for cleartext signatures.
1691    *
1692    * We reject all other messages.
1693    *
1694    * Actually we are calling this too often, i.e. for verification of
1695    * each message but better have some duplicate work than to silently
1696    * introduce a bug here.
1697    */
1698   {
1699     kbnode_t n;
1700     int n_onepass, n_sig;
1701
1702 /*     log_debug ("checking signature packet composition\n"); */
1703 /*     dump_kbnode (c->list); */
1704
1705     n = c->list;
1706     log_assert (n);
1707     if ( n->pkt->pkttype == PKT_SIGNATURE )
1708       {
1709         /* This is either "S{1,n}" case (detached signature) or
1710            "S{1,n} P" (old style PGP2 signature). */
1711         for (n = n->next; n; n = n->next)
1712           if (n->pkt->pkttype != PKT_SIGNATURE)
1713             break;
1714         if (!n)
1715           ; /* Okay, this is a detached signature.  */
1716         else if (n->pkt->pkttype == PKT_GPG_CONTROL
1717                  && (n->pkt->pkt.gpg_control->control
1718                      == CTRLPKT_PLAINTEXT_MARK) )
1719           {
1720             if (n->next)
1721               goto ambiguous;  /* We only allow one P packet. */
1722           }
1723         else
1724           goto ambiguous;
1725       }
1726     else if (n->pkt->pkttype == PKT_ONEPASS_SIG)
1727       {
1728         /* This is the "O{1,n} P S{1,n}" case (standard signature). */
1729         for (n_onepass=1, n = n->next;
1730              n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next)
1731           n_onepass++;
1732         if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
1733                     && (n->pkt->pkt.gpg_control->control
1734                         == CTRLPKT_PLAINTEXT_MARK)))
1735           goto ambiguous;
1736         for (n_sig=0, n = n->next;
1737              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
1738           n_sig++;
1739         if (!n_sig)
1740           goto ambiguous;
1741
1742         /* If we wanted to disallow multiple sig verification, we'd do
1743            something like this:
1744
1745            if (n && !opt.allow_multisig_verification)
1746              goto ambiguous;
1747
1748            However, now that we have --allow-multiple-messages, this
1749            can stay allowable as we can't get here unless multiple
1750            messages (i.e. multiple literals) are allowed. */
1751
1752         if (n_onepass != n_sig)
1753           {
1754             log_info ("number of one-pass packets does not match "
1755                       "number of signature packets\n");
1756             goto ambiguous;
1757           }
1758       }
1759     else if (n->pkt->pkttype == PKT_GPG_CONTROL
1760              && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
1761       {
1762         /* This is the "C P S{1,n}" case (clear text signature). */
1763         n = n->next;
1764         if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
1765                     && (n->pkt->pkt.gpg_control->control
1766                         == CTRLPKT_PLAINTEXT_MARK)))
1767           goto ambiguous;
1768         for (n_sig=0, n = n->next;
1769              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
1770           n_sig++;
1771         if (n || !n_sig)
1772           goto ambiguous;
1773       }
1774     else
1775       {
1776       ambiguous:
1777         log_error(_("can't handle this ambiguous signature data\n"));
1778         return 0;
1779       }
1780   }
1781
1782   if (sig->signers_uid)
1783     write_status_buffer (STATUS_NEWSIG,
1784                          sig->signers_uid, strlen (sig->signers_uid), 0);
1785   else
1786     write_status_text (STATUS_NEWSIG, NULL);
1787
1788   astr = openpgp_pk_algo_name ( sig->pubkey_algo );
1789   if ((issuer_fpr = issuer_fpr_string (sig)))
1790     {
1791       log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
1792       log_info (_("               using %s key %s\n"),
1793                 astr? astr: "?", issuer_fpr);
1794
1795       xfree (issuer_fpr);
1796     }
1797   else if (!keystrlen () || keystrlen () > 8)
1798     {
1799       log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
1800       log_info (_("               using %s key %s\n"),
1801                 astr? astr: "?", keystr(sig->keyid));
1802     }
1803   else /* Legacy format.  */
1804     log_info (_("Signature made %s using %s key ID %s\n"),
1805               asctimestamp(sig->timestamp), astr? astr: "?",
1806               keystr(sig->keyid));
1807
1808   /* In verbose mode print the signers UID.  */
1809   if (sig->signers_uid)
1810     log_info (_("               issuer \"%s\"\n"), sig->signers_uid);
1811
1812   rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey, &pk);
1813
1814   /* If the key isn't found, check for a preferred keyserver.  */
1815   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && sig->flags.pref_ks)
1816     {
1817       const byte *p;
1818       int seq = 0;
1819       size_t n;
1820
1821       while ((p=enum_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS,&n,&seq,NULL)))
1822         {
1823           /* According to my favorite copy editor, in English grammar,
1824              you say "at" if the key is located on a web page, but
1825              "from" if it is located on a keyserver.  I'm not going to
1826              even try to make two strings here :) */
1827           log_info(_("Key available at: ") );
1828           print_utf8_buffer (log_get_stream(), p, n);
1829           log_printf ("\n");
1830
1831           if (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE
1832               && opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1833             {
1834               struct keyserver_spec *spec;
1835
1836               spec = parse_preferred_keyserver (sig);
1837               if (spec)
1838                 {
1839                   int res;
1840
1841                   free_public_key (pk);
1842                   pk = NULL;
1843                   glo_ctrl.in_auto_key_retrieve++;
1844                   res = keyserver_import_keyid (c->ctrl, sig->keyid,spec, 1);
1845                   glo_ctrl.in_auto_key_retrieve--;
1846                   if (!res)
1847                     rc = do_check_sig (c, node, NULL,
1848                                        &is_expkey, &is_revkey, &pk);
1849                   free_keyserver_spec (spec);
1850
1851                   if (!rc)
1852                     break;
1853                 }
1854             }
1855         }
1856     }
1857
1858   /* If the avove methods didn't work, our next try is to use the URI
1859    * from a DNS PKA record.  */
1860   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1861       && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
1862       && (opt.keyserver_options.options & KEYSERVER_HONOR_PKA_RECORD))
1863     {
1864       const char *uri = pka_uri_from_sig (c, sig);
1865
1866       if (uri)
1867         {
1868           /* FIXME: We might want to locate the key using the
1869              fingerprint instead of the keyid. */
1870           int res;
1871           struct keyserver_spec *spec;
1872
1873           spec = parse_keyserver_uri (uri, 1);
1874           if (spec)
1875             {
1876               free_public_key (pk);
1877               pk = NULL;
1878               glo_ctrl.in_auto_key_retrieve++;
1879               res = keyserver_import_keyid (c->ctrl, sig->keyid, spec, 1);
1880               glo_ctrl.in_auto_key_retrieve--;
1881               free_keyserver_spec (spec);
1882               if (!res)
1883                 rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey, &pk);
1884             }
1885         }
1886     }
1887
1888   /* If the above methods didn't work, our next try is to locate
1889    * the key via its fingerprint from a keyserver.  This requires
1890    * that the signers fingerprint is encoded in the signature.  We
1891    * favor this over the WKD method (to be tried next), because an
1892    * arbitrary keyserver is less subject to web bug like monitoring.  */
1893   tried_ks_by_fpr = 0;
1894   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1895       && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
1896       && keyserver_any_configured (c->ctrl))
1897     {
1898       int res;
1899       const byte *p;
1900       size_t n;
1901
1902       p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_ISSUER_FPR, &n);
1903       if (p && n == 21 && p[0] == 4)
1904         {
1905           /* v4 packet with a SHA-1 fingerprint.  */
1906           free_public_key (pk);
1907           pk = NULL;
1908           glo_ctrl.in_auto_key_retrieve++;
1909           res = keyserver_import_fprint (c->ctrl, p+1, n-1, opt.keyserver, 1);
1910           tried_ks_by_fpr = 1;
1911           glo_ctrl.in_auto_key_retrieve--;
1912           if (!res)
1913             rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey, &pk);
1914         }
1915     }
1916
1917   /* If the above methods didn't work, our next try is to retrieve the
1918    * key from the WKD. */
1919   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1920       && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
1921       && !opt.flags.disable_signer_uid
1922       && akl_has_wkd_method ()
1923       && sig->signers_uid)
1924     {
1925       int res;
1926
1927       free_public_key (pk);
1928       pk = NULL;
1929       glo_ctrl.in_auto_key_retrieve++;
1930       res = keyserver_import_wkd (c->ctrl, sig->signers_uid, 1, NULL, NULL);
1931       glo_ctrl.in_auto_key_retrieve--;
1932       /* Fixme: If the fingerprint is embedded in the signature,
1933        * compare it to the fingerprint of the returned key.  */
1934       if (!res)
1935         rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey, &pk);
1936     }
1937
1938   /* If the above methods did't work, our next try is to use a
1939    * keyserver.  */
1940   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
1941       && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
1942       && !tried_ks_by_fpr
1943       && keyserver_any_configured (c->ctrl))
1944     {
1945       int res;
1946
1947       free_public_key (pk);
1948       pk = NULL;
1949       glo_ctrl.in_auto_key_retrieve++;
1950       res = keyserver_import_keyid (c->ctrl, sig->keyid, opt.keyserver, 1);
1951       glo_ctrl.in_auto_key_retrieve--;
1952       if (!res)
1953         rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey, &pk);
1954     }
1955
1956   if (!rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
1957     {
1958       kbnode_t un, keyblock;
1959       int count = 0;
1960       int statno;
1961       char keyid_str[50];
1962       PKT_public_key *mainpk = NULL;
1963
1964       if (rc)
1965         statno = STATUS_BADSIG;
1966       else if (sig->flags.expired)
1967         statno = STATUS_EXPSIG;
1968       else if (is_expkey)
1969         statno = STATUS_EXPKEYSIG;
1970       else if(is_revkey)
1971         statno = STATUS_REVKEYSIG;
1972       else
1973         statno = STATUS_GOODSIG;
1974
1975       /* FIXME: We should have the public key in PK and thus the
1976        * keyblock has already been fetched.  Thus we could use the
1977        * fingerprint or PK itself to lookup the entire keyblock.  That
1978        * would best be done with a cache.  */
1979       keyblock = get_pubkeyblock (c->ctrl, sig->keyid);
1980
1981       snprintf (keyid_str, sizeof keyid_str, "%08lX%08lX [uncertain] ",
1982                 (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
1983
1984       /* Find and print the primary user ID along with the
1985          "Good|Expired|Bad signature" line.  */
1986       for (un=keyblock; un; un = un->next)
1987         {
1988           int valid;
1989
1990           if (un->pkt->pkttype==PKT_PUBLIC_KEY)
1991             {
1992               mainpk = un->pkt->pkt.public_key;
1993               continue;
1994             }
1995           if (un->pkt->pkttype != PKT_USER_ID)
1996             continue;
1997           if (!un->pkt->pkt.user_id->created)
1998             continue;
1999           if (un->pkt->pkt.user_id->flags.revoked)
2000             continue;
2001           if (un->pkt->pkt.user_id->flags.expired)
2002             continue;
2003           if (!un->pkt->pkt.user_id->flags.primary)
2004             continue;
2005           /* We want the textual primary user ID here */
2006           if (un->pkt->pkt.user_id->attrib_data)
2007             continue;
2008
2009           log_assert (mainpk);
2010
2011           /* Since this is just informational, don't actually ask the
2012              user to update any trust information.  (Note: we register
2013              the signature later.)  Because print_good_bad_signature
2014              does not print a LF we need to compute the validity
2015              before calling that function.  */
2016           if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2017             valid = get_validity (c->ctrl, keyblock, mainpk,
2018                                   un->pkt->pkt.user_id, NULL, 0);
2019           else
2020             valid = 0; /* Not used.  */
2021
2022           keyid_str[17] = 0; /* cut off the "[uncertain]" part */
2023
2024           print_good_bad_signature (statno, keyid_str, un, sig, rc);
2025
2026           if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2027             log_printf (" [%s]\n",trust_value_to_string(valid));
2028           else
2029             log_printf ("\n");
2030
2031           count++;
2032         }
2033
2034       log_assert (mainpk);
2035
2036       /* In case we did not found a valid textual userid above
2037          we print the first user id packet or a "[?]" instead along
2038          with the "Good|Expired|Bad signature" line.  */
2039       if (!count)
2040         {
2041           /* Try for an invalid textual userid */
2042           for (un=keyblock; un; un = un->next)
2043             {
2044               if (un->pkt->pkttype == PKT_USER_ID
2045                   && !un->pkt->pkt.user_id->attrib_data)
2046                 break;
2047             }
2048
2049           /* Try for any userid at all */
2050           if (!un)
2051             {
2052               for (un=keyblock; un; un = un->next)
2053                 {
2054                   if (un->pkt->pkttype == PKT_USER_ID)
2055                     break;
2056                 }
2057             }
2058
2059           if (opt.trust_model==TM_ALWAYS || !un)
2060             keyid_str[17] = 0; /* cut off the "[uncertain]" part */
2061
2062           print_good_bad_signature (statno, keyid_str, un, sig, rc);
2063
2064           if (opt.trust_model != TM_ALWAYS && un)
2065             log_printf (" %s",_("[uncertain]") );
2066           log_printf ("\n");
2067         }
2068
2069       /* If we have a good signature and already printed
2070        * the primary user ID, print all the other user IDs */
2071       if (count
2072           && !rc
2073           && !(opt.verify_options & VERIFY_SHOW_PRIMARY_UID_ONLY))
2074         {
2075           char *p;
2076           for( un=keyblock; un; un = un->next)
2077             {
2078               if (un->pkt->pkttype != PKT_USER_ID)
2079                 continue;
2080               if ((un->pkt->pkt.user_id->flags.revoked
2081                    || un->pkt->pkt.user_id->flags.expired)
2082                   && !(opt.verify_options & VERIFY_SHOW_UNUSABLE_UIDS))
2083                 continue;
2084               /* Skip textual primary user ids which we printed above. */
2085               if (un->pkt->pkt.user_id->flags.primary
2086                   && !un->pkt->pkt.user_id->attrib_data )
2087                 continue;
2088
2089               /* If this user id has attribute data, print that.  */
2090               if (un->pkt->pkt.user_id->attrib_data)
2091                 {
2092                   dump_attribs (un->pkt->pkt.user_id, mainpk);
2093
2094                   if (opt.verify_options&VERIFY_SHOW_PHOTOS)
2095                     show_photos (c->ctrl,
2096                                  un->pkt->pkt.user_id->attribs,
2097                                  un->pkt->pkt.user_id->numattribs,
2098                                  mainpk ,un->pkt->pkt.user_id);
2099                 }
2100
2101               p = utf8_to_native (un->pkt->pkt.user_id->name,
2102                                   un->pkt->pkt.user_id->len, 0);
2103               log_info (_("                aka \"%s\""), p);
2104               xfree (p);
2105
2106               if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2107                 {
2108                   const char *valid;
2109
2110                   if (un->pkt->pkt.user_id->flags.revoked)
2111                     valid = _("revoked");
2112                   else if (un->pkt->pkt.user_id->flags.expired)
2113                     valid = _("expired");
2114                   else
2115                     /* Since this is just informational, don't
2116                        actually ask the user to update any trust
2117                        information.  */
2118                     valid = (trust_value_to_string
2119                              (get_validity (c->ctrl, keyblock, mainpk,
2120                                             un->pkt->pkt.user_id, NULL, 0)));
2121                   log_printf (" [%s]\n",valid);
2122                 }
2123               else
2124                 log_printf ("\n");
2125             }
2126         }
2127
2128       /* For good signatures print notation data.  */
2129       if (!rc)
2130         {
2131           if ((opt.verify_options & VERIFY_SHOW_POLICY_URLS))
2132             show_policy_url (sig, 0, 1);
2133           else
2134             show_policy_url (sig, 0, 2);
2135
2136           if ((opt.verify_options & VERIFY_SHOW_KEYSERVER_URLS))
2137             show_keyserver_url (sig, 0, 1);
2138           else
2139             show_keyserver_url (sig, 0, 2);
2140
2141           if ((opt.verify_options & VERIFY_SHOW_NOTATIONS))
2142             show_notation
2143               (sig, 0, 1,
2144                (((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0)
2145                 + ((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0)));
2146           else
2147             show_notation (sig, 0, 2, 0);
2148         }
2149
2150       /* For good signatures print the VALIDSIG status line.  */
2151       if (!rc && is_status_enabled () && pk)
2152         {
2153           char pkhex[MAX_FINGERPRINT_LEN*2+1];
2154           char mainpkhex[MAX_FINGERPRINT_LEN*2+1];
2155
2156           hexfingerprint (pk, pkhex, sizeof pkhex);
2157           hexfingerprint (mainpk, mainpkhex, sizeof mainpkhex);
2158
2159           /* TODO: Replace the reserved '0' in the field below with
2160              bits for status flags (policy url, notation, etc.).  */
2161           write_status_printf (STATUS_VALIDSIG,
2162                                "%s %s %lu %lu %d 0 %d %d %02X %s",
2163                                pkhex,
2164                                strtimestamp (sig->timestamp),
2165                                (ulong)sig->timestamp,
2166                                (ulong)sig->expiredate,
2167                                sig->version, sig->pubkey_algo,
2168                                sig->digest_algo,
2169                                sig->sig_class,
2170                                mainpkhex);
2171         }
2172
2173       /* Print compliance warning for Good signatures.  */
2174       if (!rc && pk && !opt.quiet
2175           && !gnupg_pk_is_compliant (opt.compliance, pk->pubkey_algo,
2176                                      pk->pkey, nbits_from_pk (pk), NULL))
2177         {
2178           log_info (_("WARNING: This key is not suitable for signing"
2179                       " in %s mode\n"),
2180                     gnupg_compliance_option_string (opt.compliance));
2181         }
2182
2183       /* For good signatures compute and print the trust information.
2184          Note that in the Tofu trust model this may ask the user on
2185          how to resolve a conflict.  */
2186       if (!rc)
2187         {
2188           if ((opt.verify_options & VERIFY_PKA_LOOKUPS))
2189             pka_uri_from_sig (c, sig); /* Make sure PKA info is available. */
2190           rc = check_signatures_trust (c->ctrl, sig);
2191         }
2192
2193       /* Print extra information about the signature.  */
2194       if (sig->flags.expired)
2195         {
2196           log_info (_("Signature expired %s\n"), asctimestamp(sig->expiredate));
2197           rc = GPG_ERR_GENERAL; /* Need a better error here?  */
2198         }
2199       else if (sig->expiredate)
2200         log_info (_("Signature expires %s\n"), asctimestamp(sig->expiredate));
2201
2202       if (opt.verbose)
2203         {
2204           char pkstrbuf[PUBKEY_STRING_SIZE];
2205
2206           if (pk)
2207             pubkey_string (pk, pkstrbuf, sizeof pkstrbuf);
2208           else
2209             *pkstrbuf = 0;
2210
2211           log_info (_("%s signature, digest algorithm %s%s%s\n"),
2212                     sig->sig_class==0x00?_("binary"):
2213                     sig->sig_class==0x01?_("textmode"):_("unknown"),
2214                     gcry_md_algo_name (sig->digest_algo),
2215                     *pkstrbuf?_(", key algorithm "):"", pkstrbuf);
2216         }
2217
2218       /* Print final warnings.  */
2219       if (!rc && !c->signed_data.used)
2220         {
2221           /* Signature is basically good but we test whether the
2222              deprecated command
2223                gpg --verify FILE.sig
2224              was used instead of
2225                gpg --verify FILE.sig FILE
2226              to verify a detached signature.  If we figure out that a
2227              data file with a matching name exists, we print a warning.
2228
2229              The problem is that the first form would also verify a
2230              standard signature.  This behavior could be used to
2231              create a made up .sig file for a tarball by creating a
2232              standard signature from a valid detached signature packet
2233              (for example from a signed git tag).  Then replace the
2234              sig file on the FTP server along with a changed tarball.
2235              Using the first form the verify command would correctly
2236              verify the signature but don't even consider the tarball.  */
2237           kbnode_t n;
2238           char *dfile;
2239
2240           dfile = get_matching_datafile (c->sigfilename);
2241           if (dfile)
2242             {
2243               for (n = c->list; n; n = n->next)
2244                 if (n->pkt->pkttype != PKT_SIGNATURE)
2245                   break;
2246               if (n)
2247                 {
2248                   /* Not only signature packets in the tree thus this
2249                      is not a detached signature.  */
2250                   log_info (_("WARNING: not a detached signature; "
2251                               "file '%s' was NOT verified!\n"), dfile);
2252                 }
2253               xfree (dfile);
2254             }
2255         }
2256
2257       /* Compute compliance with CO_DE_VS.  */
2258       if (pk && is_status_enabled ()
2259           && gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, pk->pkey,
2260                                     nbits_from_pk (pk), NULL)
2261           && gnupg_digest_is_compliant (CO_DE_VS, sig->digest_algo))
2262         write_status_strings (STATUS_VERIFICATION_COMPLIANCE_MODE,
2263                               gnupg_status_compliance_flag (CO_DE_VS),
2264                               NULL);
2265
2266       free_public_key (pk);
2267       pk = NULL;
2268       release_kbnode( keyblock );
2269       if (rc)
2270         g10_errors_seen = 1;
2271       if (opt.batch && rc)
2272         g10_exit (1);
2273     }
2274   else
2275     {
2276       char buf[50];
2277
2278       snprintf (buf, sizeof buf, "%08lX%08lX %d %d %02x %lu %d",
2279                 (ulong)sig->keyid[0], (ulong)sig->keyid[1],
2280                 sig->pubkey_algo, sig->digest_algo,
2281                 sig->sig_class, (ulong)sig->timestamp, gpg_err_code (rc));
2282       write_status_text (STATUS_ERRSIG, buf);
2283       if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2284         {
2285           buf[16] = 0;
2286           write_status_text (STATUS_NO_PUBKEY, buf);
2287         }
2288       if (gpg_err_code (rc) != GPG_ERR_NOT_PROCESSED)
2289         log_error (_("Can't check signature: %s\n"), gpg_strerror (rc));
2290     }
2291
2292   return rc;
2293 }
2294
2295
2296 /*
2297  * Process the tree which starts at node
2298  */
2299 static void
2300 proc_tree (CTX c, kbnode_t node)
2301 {
2302   kbnode_t n1;
2303   int rc;
2304
2305   if (opt.list_packets || opt.list_only)
2306     return;
2307
2308   /* We must skip our special plaintext marker packets here because
2309      they may be the root packet.  These packets are only used in
2310      additional checks and skipping them here doesn't matter.  */
2311   while (node
2312          && node->pkt->pkttype == PKT_GPG_CONTROL
2313           && node->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK)
2314     {
2315       node = node->next;
2316     }
2317   if (!node)
2318     return;
2319
2320   c->trustletter = ' ';
2321   if (node->pkt->pkttype == PKT_PUBLIC_KEY
2322       || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2323     {
2324       merge_keys_and_selfsig (c->ctrl, node);
2325       list_node (c, node);
2326     }
2327   else if (node->pkt->pkttype == PKT_SECRET_KEY)
2328     {
2329       merge_keys_and_selfsig (c->ctrl, node);
2330       list_node (c, node);
2331     }
2332   else if (node->pkt->pkttype == PKT_ONEPASS_SIG)
2333     {
2334       /* Check all signatures.  */
2335       if (!c->any.data)
2336         {
2337           int use_textmode = 0;
2338
2339           free_md_filter_context (&c->mfx);
2340           /* Prepare to create all requested message digests.  */
2341           rc = gcry_md_open (&c->mfx.md, 0, 0);
2342           if (rc)
2343             goto hash_err;
2344
2345           /* Fixme: why looking for the signature packet and not the
2346              one-pass packet?  */
2347           for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2348             gcry_md_enable (c->mfx.md, n1->pkt->pkt.signature->digest_algo);
2349
2350           if (n1 && n1->pkt->pkt.onepass_sig->sig_class == 0x01)
2351             use_textmode = 1;
2352
2353           /* Ask for file and hash it. */
2354           if (c->sigs_only)
2355             {
2356               if (c->signed_data.used && c->signed_data.data_fd != -1)
2357                 rc = hash_datafile_by_fd (c->mfx.md, NULL,
2358                                           c->signed_data.data_fd,
2359                                           use_textmode);
2360               else
2361                 rc = hash_datafiles (c->mfx.md, NULL,
2362                                      c->signed_data.data_names,
2363                                      c->sigfilename,
2364                                      use_textmode);
2365             }
2366           else
2367             {
2368               rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
2369                                               iobuf_get_real_fname (c->iobuf),
2370                                               use_textmode);
2371             }
2372
2373         hash_err:
2374           if (rc)
2375             {
2376               log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
2377               return;
2378             }
2379         }
2380       else if (c->signed_data.used)
2381         {
2382           log_error (_("not a detached signature\n"));
2383           return;
2384         }
2385
2386       for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2387         check_sig_and_print (c, n1);
2388
2389     }
2390   else if (node->pkt->pkttype == PKT_GPG_CONTROL
2391            && node->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START)
2392     {
2393       /* Clear text signed message.  */
2394       if (!c->any.data)
2395         {
2396           log_error ("cleartext signature without data\n");
2397           return;
2398         }
2399       else if (c->signed_data.used)
2400         {
2401           log_error (_("not a detached signature\n"));
2402           return;
2403         }
2404
2405       for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2406         check_sig_and_print (c, n1);
2407
2408     }
2409   else if (node->pkt->pkttype == PKT_SIGNATURE)
2410     {
2411       PKT_signature *sig = node->pkt->pkt.signature;
2412       int multiple_ok = 1;
2413
2414       n1 = find_next_kbnode (node, PKT_SIGNATURE);
2415       if (n1)
2416         {
2417           byte class = sig->sig_class;
2418           byte hash  = sig->digest_algo;
2419
2420           for (; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
2421             {
2422               /* We can't currently handle multiple signatures of
2423                * different classes (we'd pretty much have to run a
2424                * different hash context for each), but if they are all
2425                * the same and it is detached signature, we make an
2426                * exception.  Note that the old code also disallowed
2427                * multiple signatures if the digest algorithms are
2428                * different.  We softened this restriction only for
2429                * detached signatures, to be on the safe side. */
2430               if (n1->pkt->pkt.signature->sig_class != class
2431                   || (c->any.data
2432                       && n1->pkt->pkt.signature->digest_algo != hash))
2433                 {
2434                   multiple_ok = 0;
2435                   log_info (_("WARNING: multiple signatures detected.  "
2436                               "Only the first will be checked.\n"));
2437                   break;
2438                 }
2439             }
2440         }
2441
2442       if (sig->sig_class != 0x00 && sig->sig_class != 0x01)
2443         {
2444           log_info(_("standalone signature of class 0x%02x\n"), sig->sig_class);
2445         }
2446       else if (!c->any.data)
2447         {
2448           /* Detached signature */
2449           free_md_filter_context (&c->mfx);
2450           rc = gcry_md_open (&c->mfx.md, sig->digest_algo, 0);
2451           if (rc)
2452             goto detached_hash_err;
2453
2454           if (multiple_ok)
2455             {
2456               /* If we have and want to handle multiple signatures we
2457                * need to enable all hash algorithms for the context.  */
2458               for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE)); )
2459                 if (!openpgp_md_test_algo (n1->pkt->pkt.signature->digest_algo))
2460                   gcry_md_enable (c->mfx.md,
2461                                   map_md_openpgp_to_gcry
2462                                   (n1->pkt->pkt.signature->digest_algo));
2463             }
2464
2465           if (RFC2440 || RFC4880)
2466             ; /* Strict RFC mode.  */
2467           else if (sig->digest_algo == DIGEST_ALGO_SHA1
2468                    && sig->pubkey_algo == PUBKEY_ALGO_DSA
2469                    && sig->sig_class == 0x01)
2470             {
2471               /* Enable a workaround for a pgp5 bug when the detached
2472                * signature has been created in textmode.  Note that we
2473                * do not implement this for multiple signatures with
2474                * different hash algorithms. */
2475               rc = gcry_md_open (&c->mfx.md2, sig->digest_algo, 0);
2476               if (rc)
2477                 goto detached_hash_err;
2478             }
2479
2480           /* Here we used to have another hack to work around a pgp
2481            * 2 bug: It worked by not using the textmode for detached
2482            * signatures; this would let the first signature check
2483            * (on md) fail but the second one (on md2), which adds an
2484            * extra CR would then have produced the "correct" hash.
2485            * This is very, very ugly hack but it may haved help in
2486            * some cases (and break others).
2487            *     c->mfx.md2? 0 :(sig->sig_class == 0x01)
2488            */
2489
2490           if (DBG_HASHING)
2491             {
2492               gcry_md_debug (c->mfx.md, "verify");
2493               if (c->mfx.md2)
2494                 gcry_md_debug (c->mfx.md2, "verify2");
2495             }
2496
2497           if (c->sigs_only)
2498             {
2499               if (c->signed_data.used && c->signed_data.data_fd != -1)
2500                 rc = hash_datafile_by_fd (c->mfx.md, c->mfx.md2,
2501                                           c->signed_data.data_fd,
2502                                           (sig->sig_class == 0x01));
2503               else
2504                 rc = hash_datafiles (c->mfx.md, c->mfx.md2,
2505                                      c->signed_data.data_names,
2506                                      c->sigfilename,
2507                                      (sig->sig_class == 0x01));
2508             }
2509           else
2510             {
2511               rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
2512                                               iobuf_get_real_fname(c->iobuf),
2513                                               (sig->sig_class == 0x01));
2514             }
2515
2516         detached_hash_err:
2517           if (rc)
2518             {
2519               log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
2520               return;
2521             }
2522         }
2523       else if (c->signed_data.used)
2524         {
2525           log_error (_("not a detached signature\n"));
2526           return;
2527         }
2528       else if (!opt.quiet)
2529         log_info (_("old style (PGP 2.x) signature\n"));
2530
2531       if (multiple_ok)
2532         {
2533           for (n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
2534             check_sig_and_print (c, n1);
2535         }
2536       else
2537         check_sig_and_print (c, node);
2538
2539     }
2540   else
2541     {
2542       dump_kbnode (c->list);
2543       log_error ("invalid root packet detected in proc_tree()\n");
2544       dump_kbnode (node);
2545     }
2546 }