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