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