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