Imported Upstream version 2.0.28
[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( enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL_E
391              || enc->pubkey_algo == PUBKEY_ALGO_RSA
392              || enc->pubkey_algo == PUBKEY_ALGO_RSA_E
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;
524         STRING2KEY *s2k = NULL;
525         int canceled;
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                 idea_cipher_warn(1);
550                 log_info (_("IDEA cipher unavailable, "
551                             "optimistically attempting to use %s instead\n"),
552                           openpgp_cipher_algo_name (algo));
553               }
554             else
555               {
556                 algo = CIPHER_ALGO_IDEA;
557                 if (!opt.s2k_digest_algo)
558                   {
559                     /* If no digest is given we assume MD5 */
560                     s2kbuf.mode = 0;
561                     s2kbuf.hash_algo = DIGEST_ALGO_MD5;
562                     s2k = &s2kbuf;
563                   }
564                 log_info (_("assuming %s encrypted data\n"), "IDEA");
565               }
566
567             c->dek = passphrase_to_dek ( NULL, 0, algo, s2k, 3, NULL,&canceled);
568             if (c->dek)
569               c->dek->algo_info_printed = 1;
570             else if (canceled)
571               result = gpg_error (GPG_ERR_CANCELED);
572             else
573               result = gpg_error (GPG_ERR_INV_PASSPHRASE);
574           }
575     }
576     else if( !c->dek )
577         result = G10ERR_NO_SECKEY;
578
579     if( !result )
580         result = decrypt_data( c, pkt->pkt.encrypted, c->dek );
581
582     if( result == -1 )
583         ;
584     else if( !result || (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE
585                          && opt.ignore_mdc_error)) {
586         write_status( STATUS_DECRYPTION_OKAY );
587         if( opt.verbose > 1 )
588             log_info(_("decryption okay\n"));
589         if( pkt->pkt.encrypted->mdc_method && !result )
590             write_status( STATUS_GOODMDC );
591         else if(!opt.no_mdc_warn)
592             log_info (_("WARNING: message was not integrity protected\n"));
593     }
594     else if( gpg_err_code (result) == G10ERR_BAD_SIGN ) {
595         log_error(_("WARNING: encrypted message has been manipulated!\n"));
596         write_status( STATUS_BADMDC );
597         write_status( STATUS_DECRYPTION_FAILED );
598     }
599     else {
600         if (gpg_err_code (result) == GPG_ERR_BAD_KEY
601             && *c->dek->s2k_cacheid != '\0')
602           {
603             log_debug(_("cleared passphrase cached with ID: %s\n"),
604                       c->dek->s2k_cacheid);
605             passphrase_clear_cache (NULL, c->dek->s2k_cacheid, 0);
606           }
607         write_status( STATUS_DECRYPTION_FAILED );
608         log_error(_("decryption failed: %s\n"), g10_errstr(result));
609         /* Hmmm: does this work when we have encrypted using multiple
610          * ways to specify the session key (symmmetric and PK)*/
611     }
612     xfree(c->dek); c->dek = NULL;
613     free_packet(pkt);
614     c->last_was_session_key = 0;
615     write_status( STATUS_END_DECRYPTION );
616 }
617
618
619 static void
620 proc_plaintext( CTX c, PACKET *pkt )
621 {
622     PKT_plaintext *pt = pkt->pkt.plaintext;
623     int any, clearsig, only_md5, rc;
624     KBNODE n;
625
626     literals_seen++;
627
628     if( pt->namelen == 8 && !memcmp( pt->name, "_CONSOLE", 8 ) )
629         log_info(_("NOTE: sender requested \"for-your-eyes-only\"\n"));
630     else if( opt.verbose )
631         log_info(_("original file name='%.*s'\n"), pt->namelen, pt->name);
632     free_md_filter_context( &c->mfx );
633     if (gcry_md_open (&c->mfx.md, 0, 0))
634       BUG ();
635     /* fixme: we may need to push the textfilter if we have sigclass 1
636      * and no armoring - Not yet tested
637      * Hmmm, why don't we need it at all if we have sigclass 1
638      * Should we assume that plaintext in mode 't' has always sigclass 1??
639      * See: Russ Allbery's mail 1999-02-09
640      */
641     any = clearsig = only_md5 = 0;
642     for(n=c->list; n; n = n->next )
643       {
644         if( n->pkt->pkttype == PKT_ONEPASS_SIG )
645           {
646             /* For the onepass signature case */
647             if( n->pkt->pkt.onepass_sig->digest_algo )
648               {
649                 gcry_md_enable (c->mfx.md,
650                                 n->pkt->pkt.onepass_sig->digest_algo);
651                 if( !any && n->pkt->pkt.onepass_sig->digest_algo
652                     == DIGEST_ALGO_MD5 )
653                   only_md5 = 1;
654                 else
655                   only_md5 = 0;
656                 any = 1;
657               }
658             if( n->pkt->pkt.onepass_sig->sig_class != 0x01 )
659               only_md5 = 0;
660           }
661         else if( n->pkt->pkttype == PKT_GPG_CONTROL
662                  && n->pkt->pkt.gpg_control->control
663                  == CTRLPKT_CLEARSIGN_START )
664           {
665             /* For the clearsigned message case */
666             size_t datalen = n->pkt->pkt.gpg_control->datalen;
667             const byte *data = n->pkt->pkt.gpg_control->data;
668
669             /* check that we have at least the sigclass and one hash */
670             if ( datalen < 2 )
671               log_fatal("invalid control packet CTRLPKT_CLEARSIGN_START\n");
672             /* Note that we don't set the clearsig flag for not-dash-escaped
673              * documents */
674             clearsig = (*data == 0x01);
675             for( data++, datalen--; datalen; datalen--, data++ )
676                 gcry_md_enable (c->mfx.md, *data);
677             any = 1;
678             break;  /* Stop here as one-pass signature packets are not
679                        expected.  */
680           }
681         else if(n->pkt->pkttype==PKT_SIGNATURE)
682           {
683             /* For the SIG+LITERAL case that PGP used to use. */
684             gcry_md_enable ( c->mfx.md, n->pkt->pkt.signature->digest_algo );
685             any=1;
686           }
687       }
688
689     if( !any && !opt.skip_verify )
690       {
691         /* This is for the old GPG LITERAL+SIG case.  It's not legal
692            according to 2440, so hopefully it won't come up that
693            often.  There is no good way to specify what algorithms to
694            use in that case, so these three are the historical
695            answer. */
696         gcry_md_enable( c->mfx.md, DIGEST_ALGO_RMD160 );
697         gcry_md_enable( c->mfx.md, DIGEST_ALGO_SHA1 );
698         gcry_md_enable( c->mfx.md, DIGEST_ALGO_MD5 );
699       }
700     if( opt.pgp2_workarounds && only_md5 && !opt.skip_verify ) {
701         /* This is a kludge to work around a bug in pgp2.  It does only
702          * catch those mails which are armored.  To catch the non-armored
703          * pgp mails we could see whether there is the signature packet
704          * in front of the plaintext.  If someone needs this, send me a patch.
705          */
706       if ( gcry_md_open (&c->mfx.md2, DIGEST_ALGO_MD5, 0) )
707         BUG ();
708     }
709     if ( DBG_HASHING ) {
710         gcry_md_debug ( c->mfx.md, "verify" );
711         if ( c->mfx.md2  )
712             gcry_md_debug ( c->mfx.md2, "verify2" );
713     }
714
715     rc=0;
716
717     if (literals_seen>1)
718       {
719         log_info (_("WARNING: multiple plaintexts seen\n"));
720
721         if (!opt.flags.allow_multiple_messages)
722           {
723             write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA");
724             log_inc_errorcount ();
725             rc = gpg_error (GPG_ERR_UNEXPECTED);
726           }
727       }
728
729     if(!rc)
730       {
731         rc = handle_plaintext( pt, &c->mfx, c->sigs_only, clearsig );
732         if ( gpg_err_code (rc) == GPG_ERR_EACCES && !c->sigs_only )
733           {
734             /* Can't write output but we hash it anyway to check the
735                signature. */
736             rc = handle_plaintext( pt, &c->mfx, 1, clearsig );
737           }
738       }
739
740     if( rc )
741         log_error( "handle plaintext failed: %s\n", g10_errstr(rc));
742     free_packet(pkt);
743     c->last_was_session_key = 0;
744
745     /* We add a marker control packet instead of the plaintext packet.
746      * This is so that we can later detect invalid packet sequences.
747      */
748     n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK, NULL, 0));
749     if (c->list)
750         add_kbnode (c->list, n);
751     else
752         c->list = n;
753 }
754
755
756 static int
757 proc_compressed_cb( IOBUF a, void *info )
758 {
759   if ( ((CTX)info)->signed_data.used
760        && ((CTX)info)->signed_data.data_fd != -1)
761     return proc_signature_packets_by_fd (info, a,
762                                          ((CTX)info)->signed_data.data_fd);
763   else
764     return proc_signature_packets (info, a,
765                                    ((CTX)info)->signed_data.data_names,
766                                    ((CTX)info)->sigfilename );
767 }
768
769 static int
770 proc_encrypt_cb( IOBUF a, void *info )
771 {
772     return proc_encryption_packets( info, a );
773 }
774
775 static int
776 proc_compressed( CTX c, PACKET *pkt )
777 {
778   PKT_compressed *zd = pkt->pkt.compressed;
779   int rc;
780
781   /*printf("zip: compressed data packet\n");*/
782   if (c->sigs_only)
783     rc = handle_compressed (c, zd, proc_compressed_cb, c);
784   else if (c->encrypt_only)
785     rc = handle_compressed (c, zd, proc_encrypt_cb, c);
786   else
787     rc = handle_compressed (c, zd, NULL, NULL);
788
789   if (gpg_err_code (rc) == GPG_ERR_BAD_DATA)
790     {
791       if  (!c->any.uncompress_failed)
792         {
793           CTX cc;
794
795           for (cc=c; cc; cc = cc->anchor)
796             cc->any.uncompress_failed = 1;
797           log_error ("uncompressing failed: %s\n", g10_errstr(rc));
798         }
799       }
800   else if (rc)
801     log_error("uncompressing failed: %s\n", g10_errstr(rc));
802
803   free_packet (pkt);
804   c->last_was_session_key = 0;
805   return rc;
806 }
807
808 /****************
809  * check the signature
810  * Returns: 0 = valid signature or an error code
811  */
812 static int
813 do_check_sig( CTX c, KBNODE node, int *is_selfsig,
814               int *is_expkey, int *is_revkey )
815 {
816     PKT_signature *sig;
817     gcry_md_hd_t md = NULL, md2 = NULL;
818     int algo, rc;
819
820     assert( node->pkt->pkttype == PKT_SIGNATURE );
821     if( is_selfsig )
822         *is_selfsig = 0;
823     sig = node->pkt->pkt.signature;
824
825     algo = sig->digest_algo;
826     rc = openpgp_md_test_algo(algo);
827     if (rc)
828       return rc;
829
830     if( sig->sig_class == 0x00 ) {
831         if( c->mfx.md )
832           {
833             if (gcry_md_copy (&md, c->mfx.md ))
834               BUG ();
835           }
836         else /* detached signature */
837           {
838             /* signature_check() will enable the md*/
839             if (gcry_md_open (&md, 0, 0 ))
840               BUG ();
841           }
842     }
843     else if( sig->sig_class == 0x01 ) {
844         /* how do we know that we have to hash the (already hashed) text
845          * in canonical mode ??? (calculating both modes???) */
846         if( c->mfx.md ) {
847             if (gcry_md_copy (&md, c->mfx.md ))
848               BUG ();
849             if( c->mfx.md2 && gcry_md_copy (&md2, c->mfx.md2 ))
850               BUG ();
851         }
852         else { /* detached signature */
853             log_debug("Do we really need this here?");
854             /* signature_check() will enable the md*/
855             if (gcry_md_open (&md, 0, 0 ))
856               BUG ();
857             if (gcry_md_open (&md2, 0, 0 ))
858               BUG ();
859         }
860     }
861     else if( (sig->sig_class&~3) == 0x10
862              || sig->sig_class == 0x18
863              || sig->sig_class == 0x1f
864              || sig->sig_class == 0x20
865              || sig->sig_class == 0x28
866              || sig->sig_class == 0x30  ) {
867         if( c->list->pkt->pkttype == PKT_PUBLIC_KEY
868             || c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
869             return check_key_signature( c->list, node, is_selfsig );
870         }
871         else if( sig->sig_class == 0x20 ) {
872             log_error (_("standalone revocation - "
873                          "use \"gpg --import\" to apply\n"));
874             return G10ERR_NOT_PROCESSED;
875         }
876         else {
877             log_error("invalid root packet for sigclass %02x\n",
878                                                         sig->sig_class);
879             return G10ERR_SIG_CLASS;
880         }
881     }
882     else
883         return G10ERR_SIG_CLASS;
884     rc = signature_check2( sig, md, NULL, is_expkey, is_revkey, NULL );
885     if( gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE && md2 )
886         rc = signature_check2( sig, md2, NULL, is_expkey, is_revkey, NULL );
887     gcry_md_close(md);
888     gcry_md_close(md2);
889
890     return rc;
891 }
892
893
894 static void
895 print_userid( PACKET *pkt )
896 {
897     if( !pkt )
898         BUG();
899     if( pkt->pkttype != PKT_USER_ID ) {
900         printf("ERROR: unexpected packet type %d", pkt->pkttype );
901         return;
902     }
903     if( opt.with_colons )
904       {
905         if(pkt->pkt.user_id->attrib_data)
906           printf("%u %lu",
907                  pkt->pkt.user_id->numattribs,
908                  pkt->pkt.user_id->attrib_len);
909         else
910           print_string( stdout,  pkt->pkt.user_id->name,
911                         pkt->pkt.user_id->len, ':');
912       }
913     else
914         print_utf8_string( stdout,  pkt->pkt.user_id->name,
915                                      pkt->pkt.user_id->len );
916 }
917
918
919 /****************
920  * List the certificate in a user friendly way
921  */
922
923 static void
924 list_node( CTX c, KBNODE node )
925 {
926     int mainkey;
927
928     if( !node )
929         ;
930     else if( (mainkey = (node->pkt->pkttype == PKT_PUBLIC_KEY) )
931              || node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
932         PKT_public_key *pk = node->pkt->pkt.public_key;
933
934         if( opt.with_colons )
935           {
936             u32 keyid[2];
937             keyid_from_pk( pk, keyid );
938             if( mainkey )
939               c->trustletter = opt.fast_list_mode?
940                 0 : get_validity_info( pk, NULL );
941             printf("%s:", mainkey? "pub":"sub" );
942             if( c->trustletter )
943               putchar( c->trustletter );
944             printf(":%u:%d:%08lX%08lX:%s:%s::",
945                    nbits_from_pk( pk ),
946                    pk->pubkey_algo,
947                    (ulong)keyid[0],(ulong)keyid[1],
948                    colon_datestr_from_pk( pk ),
949                    colon_strtime (pk->expiredate) );
950             if( mainkey && !opt.fast_list_mode )
951               putchar( get_ownertrust_info (pk) );
952             putchar(':');
953           }
954         else
955           {
956             printf("%s  %4u%c/%s %s",
957                    mainkey? "pub":"sub", nbits_from_pk( pk ),
958                    pubkey_letter( pk->pubkey_algo ), keystr_from_pk( pk ),
959                    datestr_from_pk (pk));
960           }
961
962         if (pk->is_revoked)
963           {
964             printf(" [");
965             printf(_("revoked: %s"),revokestr_from_pk(pk));
966             printf("]\n");
967           }
968         else if (pk->expiredate && !opt.with_colons)
969           {
970             printf(" [");
971             printf(_("expires: %s"),expirestr_from_pk(pk));
972             printf("]\n");
973           }
974         else
975           putchar ('\n');
976
977         if ((mainkey && opt.fingerprint) || opt.fingerprint > 1)
978           print_fingerprint (pk, NULL, 0);
979
980         if (opt.with_colons)
981           {
982             if (node->next && node->next->pkt->pkttype == PKT_RING_TRUST)
983               printf("rtv:1:%u:\n", node->next->pkt->pkt.ring_trust->trustval);
984           }
985
986         if( mainkey ) {
987             /* and now list all userids with their signatures */
988             for( node = node->next; node; node = node->next ) {
989                 if( node->pkt->pkttype == PKT_SIGNATURE ) {
990                     list_node(c,  node );
991                 }
992                 else if( node->pkt->pkttype == PKT_USER_ID ) {
993                     if( opt.with_colons )
994                       printf("%s:::::::::",
995                              node->pkt->pkt.user_id->attrib_data?"uat":"uid");
996                     else
997                       printf( "uid%*s", 28, "" );
998                     print_userid( node->pkt );
999                     if( opt.with_colons )
1000                         putchar(':');
1001                     putchar('\n');
1002                     if( opt.with_colons
1003                         && node->next
1004                         && node->next->pkt->pkttype == PKT_RING_TRUST ) {
1005                         printf("rtv:2:%u:\n",
1006                                node->next->pkt->pkt.ring_trust?
1007                                node->next->pkt->pkt.ring_trust->trustval : 0);
1008                     }
1009                 }
1010                 else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1011                   list_node(c,  node );
1012                 }
1013             }
1014         }
1015     }
1016     else if( (mainkey = (node->pkt->pkttype == PKT_SECRET_KEY) )
1017              || node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1018         PKT_secret_key *sk = node->pkt->pkt.secret_key;
1019
1020         if( opt.with_colons )
1021           {
1022             u32 keyid[2];
1023             keyid_from_sk( sk, keyid );
1024             printf("%s::%u:%d:%08lX%08lX:%s:%s:::",
1025                    mainkey? "sec":"ssb",
1026                    nbits_from_sk( sk ),
1027                    sk->pubkey_algo,
1028                    (ulong)keyid[0],(ulong)keyid[1],
1029                    colon_datestr_from_sk( sk ),
1030                    colon_strtime (sk->expiredate));
1031           }
1032         else
1033           printf("%s  %4u%c/%s %s ", mainkey? "sec":"ssb",
1034                  nbits_from_sk( sk ), pubkey_letter( sk->pubkey_algo ),
1035                  keystr_from_sk( sk ), datestr_from_sk( sk ));
1036
1037         putchar ('\n');
1038         if ((mainkey && opt.fingerprint) || opt.fingerprint > 1)
1039           print_fingerprint (NULL, sk,0);
1040
1041         if( mainkey ) {
1042             /* and now list all userids with their signatures */
1043             for( node = node->next; node; node = node->next ) {
1044                 if( node->pkt->pkttype == PKT_SIGNATURE ) {
1045                     list_node(c,  node );
1046                 }
1047                 else if( node->pkt->pkttype == PKT_USER_ID ) {
1048                     if( opt.with_colons )
1049                         printf("%s:::::::::",
1050                                node->pkt->pkt.user_id->attrib_data?"uat":"uid");
1051                     else
1052                         printf( "uid%*s", 28, "" );
1053                     print_userid( node->pkt );
1054                     if( opt.with_colons )
1055                         putchar(':');
1056                     putchar('\n');
1057                 }
1058                 else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1059                   list_node(c,  node );
1060                 }
1061             }
1062         }
1063     }
1064     else if( node->pkt->pkttype == PKT_SIGNATURE  ) {
1065         PKT_signature *sig = node->pkt->pkt.signature;
1066         int is_selfsig = 0;
1067         int rc2=0;
1068         size_t n;
1069         char *p;
1070         int sigrc = ' ';
1071
1072         if( !opt.verbose )
1073             return;
1074
1075         if( sig->sig_class == 0x20 || sig->sig_class == 0x30 )
1076             fputs("rev", stdout);
1077         else
1078             fputs("sig", stdout);
1079         if( opt.check_sigs ) {
1080             fflush(stdout);
1081             rc2=do_check_sig( c, node, &is_selfsig, NULL, NULL );
1082             switch (gpg_err_code (rc2)) {
1083               case 0:                        sigrc = '!'; break;
1084               case GPG_ERR_BAD_SIGNATURE:    sigrc = '-'; break;
1085               case GPG_ERR_NO_PUBKEY:
1086               case GPG_ERR_UNUSABLE_PUBKEY:  sigrc = '?'; break;
1087               default:                       sigrc = '%'; break;
1088             }
1089         }
1090         else {  /* check whether this is a self signature */
1091             u32 keyid[2];
1092
1093             if( c->list->pkt->pkttype == PKT_PUBLIC_KEY
1094                 || c->list->pkt->pkttype == PKT_SECRET_KEY ) {
1095                 if( c->list->pkt->pkttype == PKT_PUBLIC_KEY )
1096                     keyid_from_pk( c->list->pkt->pkt.public_key, keyid );
1097                 else
1098                     keyid_from_sk( c->list->pkt->pkt.secret_key, keyid );
1099
1100                 if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] )
1101                     is_selfsig = 1;
1102             }
1103         }
1104         if( opt.with_colons ) {
1105             putchar(':');
1106             if( sigrc != ' ' )
1107                 putchar(sigrc);
1108             printf("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo,
1109                    (ulong)sig->keyid[0], (ulong)sig->keyid[1],
1110                    colon_datestr_from_sig(sig),
1111                    colon_expirestr_from_sig(sig));
1112
1113             if(sig->trust_depth || sig->trust_value)
1114               printf("%d %d",sig->trust_depth,sig->trust_value);
1115             printf(":");
1116
1117             if(sig->trust_regexp)
1118               print_string(stdout,sig->trust_regexp,
1119                            strlen(sig->trust_regexp),':');
1120             printf(":");
1121         }
1122         else
1123           printf("%c       %s %s   ",
1124                  sigrc, keystr(sig->keyid), datestr_from_sig(sig));
1125         if( sigrc == '%' )
1126             printf("[%s] ", g10_errstr(rc2) );
1127         else if( sigrc == '?' )
1128             ;
1129         else if( is_selfsig ) {
1130             if( opt.with_colons )
1131                 putchar(':');
1132             fputs( sig->sig_class == 0x18? "[keybind]":"[selfsig]", stdout);
1133             if( opt.with_colons )
1134                 putchar(':');
1135         }
1136         else if( !opt.fast_list_mode ) {
1137             p = get_user_id( sig->keyid, &n );
1138             print_string( stdout, p, n, opt.with_colons );
1139             xfree(p);
1140         }
1141         if( opt.with_colons )
1142             printf(":%02x%c:", sig->sig_class, sig->flags.exportable?'x':'l');
1143         putchar('\n');
1144     }
1145     else
1146         log_error("invalid node with packet of type %d\n", node->pkt->pkttype);
1147 }
1148
1149
1150
1151 int
1152 proc_packets( void *anchor, IOBUF a )
1153 {
1154     int rc;
1155     CTX c = xmalloc_clear( sizeof *c );
1156
1157     c->anchor = anchor;
1158     rc = do_proc_packets( c, a );
1159     xfree( c );
1160     return rc;
1161 }
1162
1163
1164
1165 int
1166 proc_signature_packets( void *anchor, IOBUF a,
1167                         strlist_t signedfiles, const char *sigfilename )
1168 {
1169     CTX c = xmalloc_clear( sizeof *c );
1170     int rc;
1171
1172     c->anchor = anchor;
1173     c->sigs_only = 1;
1174
1175     c->signed_data.data_fd = -1;
1176     c->signed_data.data_names = signedfiles;
1177     c->signed_data.used = !!signedfiles;
1178
1179     c->sigfilename = sigfilename;
1180     rc = do_proc_packets( c, a );
1181
1182     /* If we have not encountered any signature we print an error
1183        messages, send a NODATA status back and return an error code.
1184        Using log_error is required because verify_files does not check
1185        error codes for each file but we want to terminate the process
1186        with an error. */
1187     if (!rc && !c->any.sig_seen)
1188       {
1189         write_status_text (STATUS_NODATA, "4");
1190         log_error (_("no signature found\n"));
1191         rc = G10ERR_NO_DATA;
1192       }
1193
1194     /* Propagate the signature seen flag upward. Do this only on
1195        success so that we won't issue the nodata status several
1196        times. */
1197     if (!rc && c->anchor && c->any.sig_seen)
1198       c->anchor->any.sig_seen = 1;
1199
1200     xfree( c );
1201     return rc;
1202 }
1203
1204 int
1205 proc_signature_packets_by_fd (void *anchor, IOBUF a, int signed_data_fd )
1206 {
1207   int rc;
1208   CTX c = xcalloc (1, sizeof *c);
1209
1210   c->anchor = anchor;
1211   c->sigs_only = 1;
1212
1213   c->signed_data.data_fd = signed_data_fd;
1214   c->signed_data.data_names = NULL;
1215   c->signed_data.used = (signed_data_fd != -1);
1216
1217   rc = do_proc_packets ( c, a );
1218
1219   /* If we have not encountered any signature we print an error
1220      messages, send a NODATA status back and return an error code.
1221      Using log_error is required because verify_files does not check
1222      error codes for each file but we want to terminate the process
1223      with an error. */
1224   if (!rc && !c->any.sig_seen)
1225     {
1226       write_status_text (STATUS_NODATA, "4");
1227       log_error (_("no signature found\n"));
1228       rc = gpg_error (GPG_ERR_NO_DATA);
1229     }
1230
1231   /* Propagate the signature seen flag upward. Do this only on success
1232      so that we won't issue the nodata status several times. */
1233   if (!rc && c->anchor && c->any.sig_seen)
1234     c->anchor->any.sig_seen = 1;
1235
1236   xfree ( c );
1237   return rc;
1238 }
1239
1240
1241 int
1242 proc_encryption_packets( void *anchor, IOBUF a )
1243 {
1244     CTX c = xmalloc_clear( sizeof *c );
1245     int rc;
1246
1247     c->anchor = anchor;
1248     c->encrypt_only = 1;
1249     rc = do_proc_packets( c, a );
1250     xfree( c );
1251     return rc;
1252 }
1253
1254
1255 static int
1256 check_nesting (CTX c)
1257 {
1258   int level;
1259
1260   for (level=0; c; c = c->anchor)
1261     level++;
1262
1263   if (level > MAX_NESTING_DEPTH)
1264     {
1265       log_error ("input data with too deeply nested packets\n");
1266       write_status_text (STATUS_UNEXPECTED, "1");
1267       return GPG_ERR_BAD_DATA;
1268     }
1269   return 0;
1270 }
1271
1272
1273 static int
1274 do_proc_packets( CTX c, IOBUF a )
1275 {
1276     PACKET *pkt;
1277     int rc = 0;
1278     int any_data = 0;
1279     int newpkt;
1280
1281     rc = check_nesting (c);
1282     if (rc)
1283       return rc;
1284
1285     pkt = xmalloc( sizeof *pkt );
1286     c->iobuf = a;
1287     init_packet(pkt);
1288     while( (rc=parse_packet(a, pkt)) != -1 ) {
1289         any_data = 1;
1290         if( rc ) {
1291             free_packet(pkt);
1292             /* stop processing when an invalid packet has been encountered
1293              * but don't do so when we are doing a --list-packets. */
1294             if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
1295                 && opt.list_packets != 2 )
1296                 break;
1297             continue;
1298         }
1299         newpkt = -1;
1300         if( opt.list_packets ) {
1301             switch( pkt->pkttype ) {
1302               case PKT_PUBKEY_ENC:  proc_pubkey_enc( c, pkt ); break;
1303               case PKT_SYMKEY_ENC:  proc_symkey_enc( c, pkt ); break;
1304               case PKT_ENCRYPTED:
1305               case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break;
1306               case PKT_COMPRESSED:  rc = proc_compressed( c, pkt ); break;
1307               default: newpkt = 0; break;
1308             }
1309         }
1310         else if( c->sigs_only ) {
1311             switch( pkt->pkttype ) {
1312               case PKT_PUBLIC_KEY:
1313               case PKT_SECRET_KEY:
1314               case PKT_USER_ID:
1315               case PKT_SYMKEY_ENC:
1316               case PKT_PUBKEY_ENC:
1317               case PKT_ENCRYPTED:
1318               case PKT_ENCRYPTED_MDC:
1319                 write_status_text( STATUS_UNEXPECTED, "0" );
1320                 rc = G10ERR_UNEXPECTED;
1321                 goto leave;
1322               case PKT_SIGNATURE:   newpkt = add_signature( c, pkt ); break;
1323               case PKT_PLAINTEXT:   proc_plaintext( c, pkt ); break;
1324               case PKT_COMPRESSED:  rc = proc_compressed( c, pkt ); break;
1325               case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break;
1326               case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
1327               default: newpkt = 0; break;
1328             }
1329         }
1330         else if( c->encrypt_only ) {
1331             switch( pkt->pkttype ) {
1332               case PKT_PUBLIC_KEY:
1333               case PKT_SECRET_KEY:
1334               case PKT_USER_ID:
1335                 write_status_text( STATUS_UNEXPECTED, "0" );
1336                 rc = G10ERR_UNEXPECTED;
1337                 goto leave;
1338               case PKT_SIGNATURE:   newpkt = add_signature( c, pkt ); break;
1339               case PKT_SYMKEY_ENC:  proc_symkey_enc( c, pkt ); break;
1340               case PKT_PUBKEY_ENC:  proc_pubkey_enc( c, pkt ); break;
1341               case PKT_ENCRYPTED:
1342               case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break;
1343               case PKT_PLAINTEXT:   proc_plaintext( c, pkt ); break;
1344               case PKT_COMPRESSED:  rc = proc_compressed( c, pkt ); break;
1345               case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break;
1346               case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
1347               default: newpkt = 0; break;
1348             }
1349         }
1350         else {
1351             switch( pkt->pkttype ) {
1352               case PKT_PUBLIC_KEY:
1353               case PKT_SECRET_KEY:
1354                 release_list( c );
1355                 c->list = new_kbnode( pkt );
1356                 newpkt = 1;
1357                 break;
1358               case PKT_PUBLIC_SUBKEY:
1359               case PKT_SECRET_SUBKEY:
1360                 newpkt = add_subkey( c, pkt );
1361                 break;
1362               case PKT_USER_ID:     newpkt = add_user_id( c, pkt ); break;
1363               case PKT_SIGNATURE:   newpkt = add_signature( c, pkt ); break;
1364               case PKT_PUBKEY_ENC:  proc_pubkey_enc( c, pkt ); break;
1365               case PKT_SYMKEY_ENC:  proc_symkey_enc( c, pkt ); break;
1366               case PKT_ENCRYPTED:
1367               case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break;
1368               case PKT_PLAINTEXT:   proc_plaintext( c, pkt ); break;
1369               case PKT_COMPRESSED:  rc = proc_compressed( c, pkt ); break;
1370               case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break;
1371               case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
1372               case PKT_RING_TRUST:  newpkt = add_ring_trust( c, pkt ); break;
1373               default: newpkt = 0; break;
1374             }
1375         }
1376
1377         if (rc)
1378           goto leave;
1379
1380         /* This is a very ugly construct and frankly, I don't remember why
1381          * I used it.  Adding the MDC check here is a hack.
1382          * The right solution is to initiate another context for encrypted
1383          * packet and not to reuse the current one ...  It works right
1384          * when there is a compression packet inbetween which adds just
1385          * an extra layer.
1386          * Hmmm: Rewrite this whole module here??
1387          */
1388         if( pkt->pkttype != PKT_SIGNATURE && pkt->pkttype != PKT_MDC )
1389             c->any.data = (pkt->pkttype == PKT_PLAINTEXT);
1390
1391         if( newpkt == -1 )
1392             ;
1393         else if( newpkt ) {
1394             pkt = xmalloc( sizeof *pkt );
1395             init_packet(pkt);
1396         }
1397         else
1398             free_packet(pkt);
1399     }
1400     if( rc == G10ERR_INVALID_PACKET )
1401         write_status_text( STATUS_NODATA, "3" );
1402     if( any_data )
1403         rc = 0;
1404     else if( rc == -1 )
1405         write_status_text( STATUS_NODATA, "2" );
1406
1407
1408   leave:
1409     release_list( c );
1410     xfree(c->dek);
1411     free_packet( pkt );
1412     xfree( pkt );
1413     free_md_filter_context( &c->mfx );
1414     return rc;
1415 }
1416
1417
1418 /* Helper for pka_uri_from_sig to parse the to-be-verified address out
1419    of the notation data. */
1420 static pka_info_t *
1421 get_pka_address (PKT_signature *sig)
1422 {
1423   pka_info_t *pka = NULL;
1424   struct notation *nd,*notation;
1425
1426   notation=sig_to_notation(sig);
1427
1428   for(nd=notation;nd;nd=nd->next)
1429     {
1430       if(strcmp(nd->name,"pka-address@gnupg.org")!=0)
1431         continue; /* Not the notation we want. */
1432
1433       /* For now we only use the first valid PKA notation. In future
1434          we might want to keep additional PKA notations in a linked
1435          list. */
1436       if (is_valid_mailbox (nd->value))
1437         {
1438           pka = xmalloc (sizeof *pka + strlen(nd->value));
1439           pka->valid = 0;
1440           pka->checked = 0;
1441           pka->uri = NULL;
1442           strcpy (pka->email, nd->value);
1443           break;
1444         }
1445     }
1446
1447   free_notation(notation);
1448
1449   return pka;
1450 }
1451
1452
1453 /* Return the URI from a DNS PKA record.  If this record has already
1454    be retrieved for the signature we merely return it; if not we go
1455    out and try to get that DNS record. */
1456 static const char *
1457 pka_uri_from_sig (PKT_signature *sig)
1458 {
1459   if (!sig->flags.pka_tried)
1460     {
1461       assert (!sig->pka_info);
1462       sig->flags.pka_tried = 1;
1463       sig->pka_info = get_pka_address (sig);
1464       if (sig->pka_info)
1465         {
1466           char *uri;
1467
1468           uri = get_pka_info (sig->pka_info->email, sig->pka_info->fpr);
1469           if (uri)
1470             {
1471               sig->pka_info->valid = 1;
1472               if (!*uri)
1473                 xfree (uri);
1474               else
1475                 sig->pka_info->uri = uri;
1476             }
1477         }
1478     }
1479   return sig->pka_info? sig->pka_info->uri : NULL;
1480 }
1481
1482
1483 static int
1484 check_sig_and_print( CTX c, KBNODE node )
1485 {
1486   PKT_signature *sig = node->pkt->pkt.signature;
1487   const char *astr;
1488   int rc, is_expkey=0, is_revkey=0;
1489
1490   if (opt.skip_verify)
1491     {
1492       log_info(_("signature verification suppressed\n"));
1493       return 0;
1494     }
1495
1496   /* Check that the message composition is valid.
1497
1498      Per RFC-2440bis (-15) allowed:
1499
1500      S{1,n}           -- detached signature.
1501      S{1,n} P         -- old style PGP2 signature
1502      O{1,n} P S{1,n}  -- standard OpenPGP signature.
1503      C P S{1,n}       -- cleartext signature.
1504
1505
1506           O = One-Pass Signature packet.
1507           S = Signature packet.
1508           P = OpenPGP Message packet (Encrypted | Compressed | Literal)
1509                  (Note that the current rfc2440bis draft also allows
1510                   for a signed message but that does not work as it
1511                   introduces ambiguities.)
1512               We keep track of these packages using the marker packet
1513               CTRLPKT_PLAINTEXT_MARK.
1514           C = Marker packet for cleartext signatures.
1515
1516      We reject all other messages.
1517
1518      Actually we are calling this too often, i.e. for verification of
1519      each message but better have some duplicate work than to silently
1520      introduce a bug here.
1521   */
1522   {
1523     KBNODE n;
1524     int n_onepass, n_sig;
1525
1526 /*     log_debug ("checking signature packet composition\n"); */
1527 /*     dump_kbnode (c->list); */
1528
1529     n = c->list;
1530     assert (n);
1531     if ( n->pkt->pkttype == PKT_SIGNATURE )
1532       {
1533         /* This is either "S{1,n}" case (detached signature) or
1534            "S{1,n} P" (old style PGP2 signature). */
1535         for (n = n->next; n; n = n->next)
1536           if (n->pkt->pkttype != PKT_SIGNATURE)
1537             break;
1538         if (!n)
1539           ; /* Okay, this is a detached signature.  */
1540         else if (n->pkt->pkttype == PKT_GPG_CONTROL
1541                  && (n->pkt->pkt.gpg_control->control
1542                      == CTRLPKT_PLAINTEXT_MARK) )
1543           {
1544             if (n->next)
1545               goto ambiguous;  /* We only allow one P packet. */
1546           }
1547         else
1548           goto ambiguous;
1549       }
1550     else if (n->pkt->pkttype == PKT_ONEPASS_SIG)
1551       {
1552         /* This is the "O{1,n} P S{1,n}" case (standard signature). */
1553         for (n_onepass=1, n = n->next;
1554              n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next)
1555           n_onepass++;
1556         if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
1557                     && (n->pkt->pkt.gpg_control->control
1558                         == CTRLPKT_PLAINTEXT_MARK)))
1559           goto ambiguous;
1560         for (n_sig=0, n = n->next;
1561              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
1562           n_sig++;
1563         if (!n_sig)
1564           goto ambiguous;
1565
1566         /* If we wanted to disallow multiple sig verification, we'd do
1567            something like this:
1568
1569            if (n && !opt.allow_multisig_verification)
1570              goto ambiguous;
1571
1572            However, now that we have --allow-multiple-messages, this
1573            can stay allowable as we can't get here unless multiple
1574            messages (i.e. multiple literals) are allowed. */
1575
1576         if (n_onepass != n_sig)
1577           {
1578             log_info ("number of one-pass packets does not match "
1579                       "number of signature packets\n");
1580             goto ambiguous;
1581           }
1582       }
1583     else if (n->pkt->pkttype == PKT_GPG_CONTROL
1584              && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
1585       {
1586         /* This is the "C P S{1,n}" case (clear text signature). */
1587         n = n->next;
1588         if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
1589                     && (n->pkt->pkt.gpg_control->control
1590                         == CTRLPKT_PLAINTEXT_MARK)))
1591           goto ambiguous;
1592         for (n_sig=0, n = n->next;
1593              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
1594           n_sig++;
1595         if (n || !n_sig)
1596           goto ambiguous;
1597       }
1598     else
1599       {
1600       ambiguous:
1601         log_error(_("can't handle this ambiguous signature data\n"));
1602         return 0;
1603       }
1604
1605   }
1606
1607   write_status_text (STATUS_NEWSIG, NULL);
1608
1609   /* (Indendation below not yet changed to GNU style.) */
1610
1611     astr = openpgp_pk_algo_name ( sig->pubkey_algo );
1612     if(keystrlen()>8)
1613       {
1614         log_info(_("Signature made %s\n"),asctimestamp(sig->timestamp));
1615         log_info(_("               using %s key %s\n"),
1616                  astr? astr: "?",keystr(sig->keyid));
1617       }
1618     else
1619       log_info(_("Signature made %s using %s key ID %s\n"),
1620                asctimestamp(sig->timestamp), astr? astr: "?",
1621                keystr(sig->keyid));
1622
1623     rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
1624
1625     /* If the key isn't found, check for a preferred keyserver */
1626
1627     if(rc==G10ERR_NO_PUBKEY && sig->flags.pref_ks)
1628       {
1629         const byte *p;
1630         int seq=0;
1631         size_t n;
1632
1633         while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&n,&seq,NULL)))
1634           {
1635             /* According to my favorite copy editor, in English
1636                grammar, you say "at" if the key is located on a web
1637                page, but "from" if it is located on a keyserver.  I'm
1638                not going to even try to make two strings here :) */
1639             log_info(_("Key available at: ") );
1640             print_utf8_string( log_get_stream(), p, n );
1641             log_printf ("\n");
1642
1643             if(opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE
1644                && opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1645               {
1646                 struct keyserver_spec *spec;
1647
1648                 spec=parse_preferred_keyserver(sig);
1649                 if(spec)
1650                   {
1651                     int res;
1652
1653                     glo_ctrl.in_auto_key_retrieve++;
1654                     res=keyserver_import_keyid(sig->keyid,spec);
1655                     glo_ctrl.in_auto_key_retrieve--;
1656                     if(!res)
1657                       rc=do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
1658                     free_keyserver_spec(spec);
1659
1660                     if(!rc)
1661                       break;
1662                   }
1663               }
1664           }
1665       }
1666
1667     /* If the preferred keyserver thing above didn't work, our second
1668        try is to use the URI from a DNS PKA record. */
1669     if ( rc == G10ERR_NO_PUBKEY
1670          && opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE
1671          && opt.keyserver_options.options&KEYSERVER_HONOR_PKA_RECORD)
1672       {
1673         const char *uri = pka_uri_from_sig (sig);
1674
1675         if (uri)
1676           {
1677             /* FIXME: We might want to locate the key using the
1678                fingerprint instead of the keyid. */
1679             int res;
1680             struct keyserver_spec *spec;
1681
1682             spec = parse_keyserver_uri (uri, 1, NULL, 0);
1683             if (spec)
1684               {
1685                 glo_ctrl.in_auto_key_retrieve++;
1686                 res = keyserver_import_keyid (sig->keyid, spec);
1687                 glo_ctrl.in_auto_key_retrieve--;
1688                 free_keyserver_spec (spec);
1689                 if (!res)
1690                   rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
1691               }
1692           }
1693       }
1694
1695     /* If the preferred keyserver thing above didn't work and we got
1696        no information from the DNS PKA, this is a third try. */
1697
1698     if( rc == G10ERR_NO_PUBKEY && opt.keyserver
1699         && opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
1700       {
1701         int res;
1702
1703         glo_ctrl.in_auto_key_retrieve++;
1704         res=keyserver_import_keyid ( sig->keyid, opt.keyserver );
1705         glo_ctrl.in_auto_key_retrieve--;
1706         if(!res)
1707           rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
1708       }
1709
1710     if( !rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE ) {
1711         KBNODE un, keyblock;
1712         int count=0, statno;
1713         char keyid_str[50];
1714         PKT_public_key *pk=NULL;
1715
1716         if(rc)
1717           statno=STATUS_BADSIG;
1718         else if(sig->flags.expired)
1719           statno=STATUS_EXPSIG;
1720         else if(is_expkey)
1721           statno=STATUS_EXPKEYSIG;
1722         else if(is_revkey)
1723           statno=STATUS_REVKEYSIG;
1724         else
1725           statno=STATUS_GOODSIG;
1726
1727         keyblock = get_pubkeyblock( sig->keyid );
1728
1729         sprintf (keyid_str, "%08lX%08lX [uncertain] ",
1730                  (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
1731
1732         /* find and print the primary user ID */
1733         for( un=keyblock; un; un = un->next ) {
1734             char *p;
1735             int valid;
1736             if(un->pkt->pkttype==PKT_PUBLIC_KEY)
1737               {
1738                 pk=un->pkt->pkt.public_key;
1739                 continue;
1740               }
1741             if( un->pkt->pkttype != PKT_USER_ID )
1742                 continue;
1743             if ( !un->pkt->pkt.user_id->created )
1744                 continue;
1745             if ( un->pkt->pkt.user_id->is_revoked )
1746                 continue;
1747             if ( un->pkt->pkt.user_id->is_expired )
1748                 continue;
1749             if ( !un->pkt->pkt.user_id->is_primary )
1750                 continue;
1751             /* We want the textual primary user ID here */
1752             if ( un->pkt->pkt.user_id->attrib_data )
1753                 continue;
1754
1755             assert(pk);
1756
1757             /* Get it before we print anything to avoid interrupting
1758                the output with the "please do a --check-trustdb"
1759                line. */
1760             valid=get_validity(pk,un->pkt->pkt.user_id);
1761
1762             keyid_str[17] = 0; /* cut off the "[uncertain]" part */
1763             write_status_text_and_buffer (statno, keyid_str,
1764                                           un->pkt->pkt.user_id->name,
1765                                           un->pkt->pkt.user_id->len,
1766                                           -1 );
1767
1768             p=utf8_to_native(un->pkt->pkt.user_id->name,
1769                              un->pkt->pkt.user_id->len,0);
1770
1771             if(rc)
1772               log_info(_("BAD signature from \"%s\""),p);
1773             else if(sig->flags.expired)
1774               log_info(_("Expired signature from \"%s\""),p);
1775             else
1776               log_info(_("Good signature from \"%s\""),p);
1777
1778             xfree(p);
1779
1780             if(opt.verify_options&VERIFY_SHOW_UID_VALIDITY)
1781               log_printf (" [%s]\n",trust_value_to_string(valid));
1782             else
1783               log_printf ("\n");
1784             count++;
1785         }
1786         if( !count ) {  /* just in case that we have no valid textual
1787                            userid */
1788             char *p;
1789
1790             /* Try for an invalid textual userid */
1791             for( un=keyblock; un; un = un->next ) {
1792                 if( un->pkt->pkttype == PKT_USER_ID &&
1793                     !un->pkt->pkt.user_id->attrib_data )
1794                     break;
1795             }
1796
1797             /* Try for any userid at all */
1798             if(!un) {
1799                 for( un=keyblock; un; un = un->next ) {
1800                     if( un->pkt->pkttype == PKT_USER_ID )
1801                         break;
1802                 }
1803             }
1804
1805             if (opt.trust_model==TM_ALWAYS || !un)
1806                 keyid_str[17] = 0; /* cut off the "[uncertain]" part */
1807
1808             write_status_text_and_buffer (statno, keyid_str,
1809                                           un? un->pkt->pkt.user_id->name:"[?]",
1810                                           un? un->pkt->pkt.user_id->len:3,
1811                                           -1 );
1812
1813             if(un)
1814               p=utf8_to_native(un->pkt->pkt.user_id->name,
1815                                un->pkt->pkt.user_id->len,0);
1816             else
1817               p=xstrdup("[?]");
1818
1819             if(rc)
1820               log_info(_("BAD signature from \"%s\""),p);
1821             else if(sig->flags.expired)
1822               log_info(_("Expired signature from \"%s\""),p);
1823             else
1824               log_info(_("Good signature from \"%s\""),p);
1825             if (opt.trust_model!=TM_ALWAYS && un)
1826               log_printf (" %s",_("[uncertain]") );
1827             log_printf ("\n");
1828         }
1829
1830         /* If we have a good signature and already printed
1831          * the primary user ID, print all the other user IDs */
1832         if ( count && !rc
1833              && !(opt.verify_options&VERIFY_SHOW_PRIMARY_UID_ONLY)) {
1834             char *p;
1835             for( un=keyblock; un; un = un->next ) {
1836                 if( un->pkt->pkttype != PKT_USER_ID )
1837                     continue;
1838                 if((un->pkt->pkt.user_id->is_revoked
1839                     || un->pkt->pkt.user_id->is_expired)
1840                    && !(opt.verify_options&VERIFY_SHOW_UNUSABLE_UIDS))
1841                   continue;
1842                 /* Only skip textual primaries */
1843                 if ( un->pkt->pkt.user_id->is_primary &&
1844                      !un->pkt->pkt.user_id->attrib_data )
1845                     continue;
1846
1847                 if(un->pkt->pkt.user_id->attrib_data)
1848                   {
1849                     dump_attribs(un->pkt->pkt.user_id,pk,NULL);
1850
1851                     if(opt.verify_options&VERIFY_SHOW_PHOTOS)
1852                       show_photos(un->pkt->pkt.user_id->attribs,
1853                                   un->pkt->pkt.user_id->numattribs,
1854                                   pk,NULL,un->pkt->pkt.user_id);
1855                   }
1856
1857                 p=utf8_to_native(un->pkt->pkt.user_id->name,
1858                                  un->pkt->pkt.user_id->len,0);
1859                 log_info(_("                aka \"%s\""),p);
1860                 xfree(p);
1861
1862                 if(opt.verify_options&VERIFY_SHOW_UID_VALIDITY)
1863                   {
1864                     const char *valid;
1865                     if(un->pkt->pkt.user_id->is_revoked)
1866                       valid=_("revoked");
1867                     else if(un->pkt->pkt.user_id->is_expired)
1868                       valid=_("expired");
1869                     else
1870                       valid=trust_value_to_string(get_validity(pk,
1871                                                                un->pkt->
1872                                                                pkt.user_id));
1873                     log_printf (" [%s]\n",valid);
1874                   }
1875                 else
1876                   log_printf ("\n");
1877             }
1878         }
1879         release_kbnode( keyblock );
1880
1881         if( !rc )
1882           {
1883             if(opt.verify_options&VERIFY_SHOW_POLICY_URLS)
1884               show_policy_url(sig,0,1);
1885             else
1886               show_policy_url(sig,0,2);
1887
1888             if(opt.verify_options&VERIFY_SHOW_KEYSERVER_URLS)
1889               show_keyserver_url(sig,0,1);
1890             else
1891               show_keyserver_url(sig,0,2);
1892
1893             if(opt.verify_options&VERIFY_SHOW_NOTATIONS)
1894               show_notation(sig,0,1,
1895                         ((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0)+
1896                         ((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0));
1897             else
1898               show_notation(sig,0,2,0);
1899           }
1900
1901         if( !rc && is_status_enabled() ) {
1902             /* print a status response with the fingerprint */
1903             PKT_public_key *vpk = xmalloc_clear( sizeof *vpk );
1904
1905             if( !get_pubkey( vpk, sig->keyid ) ) {
1906                 byte array[MAX_FINGERPRINT_LEN], *p;
1907                 char buf[MAX_FINGERPRINT_LEN*4+90], *bufp;
1908                 size_t i, n;
1909
1910                 bufp = buf;
1911                 fingerprint_from_pk( vpk, array, &n );
1912                 p = array;
1913                 for(i=0; i < n ; i++, p++, bufp += 2)
1914                     sprintf(bufp, "%02X", *p );
1915                 /* TODO: Replace the reserved '0' in the field below
1916                    with bits for status flags (policy url, notation,
1917                    etc.).  Remember to make the buffer larger to
1918                    match! */
1919                 sprintf(bufp, " %s %lu %lu %d 0 %d %d %02X ",
1920                         strtimestamp( sig->timestamp ),
1921                         (ulong)sig->timestamp,(ulong)sig->expiredate,
1922                         sig->version,sig->pubkey_algo,sig->digest_algo,
1923                         sig->sig_class);
1924                 bufp = bufp + strlen (bufp);
1925                 if (!vpk->is_primary) {
1926                    u32 akid[2];
1927
1928                    akid[0] = vpk->main_keyid[0];
1929                    akid[1] = vpk->main_keyid[1];
1930                    free_public_key (vpk);
1931                    vpk = xmalloc_clear( sizeof *vpk );
1932                    if (get_pubkey (vpk, akid)) {
1933                      /* impossible error, we simply return a zeroed out fpr */
1934                      n = MAX_FINGERPRINT_LEN < 20? MAX_FINGERPRINT_LEN : 20;
1935                      memset (array, 0, n);
1936                    }
1937                    else
1938                      fingerprint_from_pk( vpk, array, &n );
1939                 }
1940                 p = array;
1941                 for(i=0; i < n ; i++, p++, bufp += 2)
1942                     sprintf(bufp, "%02X", *p );
1943                 write_status_text( STATUS_VALIDSIG, buf );
1944             }
1945             free_public_key( vpk );
1946         }
1947
1948         if (!rc)
1949           {
1950             if(opt.verify_options&VERIFY_PKA_LOOKUPS)
1951               pka_uri_from_sig (sig); /* Make sure PKA info is available. */
1952             rc = check_signatures_trust( sig );
1953           }
1954
1955         if(sig->flags.expired)
1956           {
1957             log_info(_("Signature expired %s\n"),
1958                      asctimestamp(sig->expiredate));
1959             rc=G10ERR_GENERAL; /* need a better error here? */
1960           }
1961         else if(sig->expiredate)
1962           log_info(_("Signature expires %s\n"),asctimestamp(sig->expiredate));
1963
1964         if(opt.verbose)
1965           log_info(_("%s signature, digest algorithm %s\n"),
1966                    sig->sig_class==0x00?_("binary"):
1967                    sig->sig_class==0x01?_("textmode"):_("unknown"),
1968                    gcry_md_algo_name (sig->digest_algo));
1969
1970         if (!rc && !c->signed_data.used)
1971           {
1972             /* Signature is basically good but we test whether the
1973                deprecated command
1974                  gpg --verify FILE.sig
1975                was used instead of
1976                  gpg --verify FILE.sig FILE
1977                to verify a detached signature.  If we figure out that a
1978                data file with a matching name exists, we print a warning.
1979
1980                The problem is that the first form would also verify a
1981                standard signature.  This behavior could be used to
1982                create a made up .sig file for a tarball by creating a
1983                standard signature from a valid detached signature packet
1984                (for example from a signed git tag).  Then replace the
1985                sig file on the FTP server along with a changed tarball.
1986                Using the first form the verify command would correctly
1987                verify the signature but don't even consider the tarball.  */
1988             kbnode_t n;
1989             char *dfile;
1990
1991             dfile = get_matching_datafile (c->sigfilename);
1992             if (dfile)
1993               {
1994                 for (n = c->list; n; n = n->next)
1995                   if (n->pkt->pkttype != PKT_SIGNATURE)
1996                     break;
1997                 if (n)
1998                   {
1999                     /* Not only signature packets in the tree thus this
2000                        is not a detached signature.  */
2001                     log_info (_("WARNING: not a detached signature; "
2002                                 "file '%s' was NOT verified!\n"), dfile);
2003                   }
2004                 xfree (dfile);
2005               }
2006           }
2007
2008         if( rc )
2009             g10_errors_seen = 1;
2010         if( opt.batch && rc )
2011             g10_exit(1);
2012     }
2013     else {
2014         char buf[50];
2015         sprintf(buf, "%08lX%08lX %d %d %02x %lu %d",
2016                      (ulong)sig->keyid[0], (ulong)sig->keyid[1],
2017                      sig->pubkey_algo, sig->digest_algo,
2018                      sig->sig_class, (ulong)sig->timestamp, rc );
2019         write_status_text( STATUS_ERRSIG, buf );
2020         if( rc == G10ERR_NO_PUBKEY ) {
2021             buf[16] = 0;
2022             write_status_text( STATUS_NO_PUBKEY, buf );
2023         }
2024         if( rc != G10ERR_NOT_PROCESSED )
2025             log_error(_("Can't check signature: %s\n"), g10_errstr(rc) );
2026     }
2027     return rc;
2028 }
2029
2030
2031 /****************
2032  * Process the tree which starts at node
2033  */
2034 static void
2035 proc_tree( CTX c, KBNODE node )
2036 {
2037     KBNODE n1;
2038     int rc;
2039
2040     if( opt.list_packets || opt.list_only )
2041         return;
2042
2043     /* we must skip our special plaintext marker packets here becuase
2044        they may be the root packet.  These packets are only used in
2045        addionla checks and skipping them here doesn't matter */
2046     while ( node
2047             && node->pkt->pkttype == PKT_GPG_CONTROL
2048             && node->pkt->pkt.gpg_control->control
2049                          == CTRLPKT_PLAINTEXT_MARK ) {
2050         node = node->next;
2051     }
2052     if (!node)
2053         return;
2054
2055     c->trustletter = ' ';
2056     if( node->pkt->pkttype == PKT_PUBLIC_KEY
2057         || node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2058         merge_keys_and_selfsig( node );
2059         list_node( c, node );
2060     }
2061     else if( node->pkt->pkttype == PKT_SECRET_KEY ) {
2062         merge_keys_and_selfsig( node );
2063         list_node( c, node );
2064     }
2065     else if( node->pkt->pkttype == PKT_ONEPASS_SIG ) {
2066         /* check all signatures */
2067         if( !c->any.data ) {
2068             int use_textmode = 0;
2069
2070             free_md_filter_context( &c->mfx );
2071             /* prepare to create all requested message digests */
2072             if (gcry_md_open (&c->mfx.md, 0, 0))
2073               BUG ();
2074
2075             /* fixme: why looking for the signature packet and not the
2076                one-pass packet? */
2077             for ( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); )
2078               {
2079                 gcry_md_enable (c->mfx.md,
2080                                 n1->pkt->pkt.signature->digest_algo);
2081               }
2082
2083             if (n1 && n1->pkt->pkt.onepass_sig->sig_class == 0x01)
2084                 use_textmode = 1;
2085
2086             /* Ask for file and hash it. */
2087             if( c->sigs_only ) {
2088                 if (c->signed_data.used && c->signed_data.data_fd != -1)
2089                     rc = hash_datafile_by_fd (c->mfx.md, NULL,
2090                                               c->signed_data.data_fd,
2091                                               use_textmode);
2092                 else
2093                     rc = hash_datafiles (c->mfx.md, NULL,
2094                                          c->signed_data.data_names,
2095                                          c->sigfilename,
2096                                          use_textmode );
2097             }
2098             else {
2099                 rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
2100                                                 iobuf_get_real_fname(c->iobuf),
2101                                                 use_textmode );
2102             }
2103             if( rc ) {
2104                 log_error("can't hash datafile: %s\n", g10_errstr(rc));
2105                 return;
2106             }
2107         }
2108         else if ( c->signed_data.used ) {
2109             log_error (_("not a detached signature\n") );
2110             return;
2111         }
2112
2113         for( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); )
2114             check_sig_and_print( c, n1 );
2115     }
2116     else if( node->pkt->pkttype == PKT_GPG_CONTROL
2117              && node->pkt->pkt.gpg_control->control
2118                 == CTRLPKT_CLEARSIGN_START ) {
2119         /* clear text signed message */
2120         if( !c->any.data ) {
2121             log_error("cleartext signature without data\n" );
2122             return;
2123         }
2124         else if ( c->signed_data.used ) {
2125             log_error (_("not a detached signature\n") );
2126             return;
2127         }
2128
2129         for( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); )
2130             check_sig_and_print( c, n1 );
2131     }
2132     else if( node->pkt->pkttype == PKT_SIGNATURE ) {
2133         PKT_signature *sig = node->pkt->pkt.signature;
2134         int multiple_ok=1;
2135
2136         n1=find_next_kbnode(node, PKT_SIGNATURE);
2137         if(n1)
2138           {
2139             byte class=sig->sig_class;
2140             byte hash=sig->digest_algo;
2141
2142             for(; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
2143               {
2144                 /* We can't currently handle multiple signatures of
2145                    different classes or digests (we'd pretty much have
2146                    to run a different hash context for each), but if
2147                    they are all the same, make an exception. */
2148                 if(n1->pkt->pkt.signature->sig_class!=class
2149                    || n1->pkt->pkt.signature->digest_algo!=hash)
2150                   {
2151                     multiple_ok=0;
2152                     log_info(_("WARNING: multiple signatures detected.  "
2153                                "Only the first will be checked.\n"));
2154                     break;
2155                   }
2156               }
2157           }
2158
2159         if( sig->sig_class != 0x00 && sig->sig_class != 0x01 )
2160             log_info(_("standalone signature of class 0x%02x\n"),
2161                                                     sig->sig_class);
2162         else if( !c->any.data ) {
2163             /* detached signature */
2164             free_md_filter_context( &c->mfx );
2165             if (gcry_md_open (&c->mfx.md, sig->digest_algo, 0))
2166               BUG ();
2167
2168             if( !opt.pgp2_workarounds )
2169                 ;
2170             else if( sig->digest_algo == DIGEST_ALGO_MD5
2171                      && is_RSA( sig->pubkey_algo ) ) {
2172                 /* enable a workaround for a pgp2 bug */
2173                 if (gcry_md_open (&c->mfx.md2, DIGEST_ALGO_MD5, 0))
2174                   BUG ();
2175             }
2176             else if( sig->digest_algo == DIGEST_ALGO_SHA1
2177                      && sig->pubkey_algo == PUBKEY_ALGO_DSA
2178                      && sig->sig_class == 0x01 ) {
2179                 /* enable the workaround also for pgp5 when the detached
2180                  * signature has been created in textmode */
2181               if (gcry_md_open (&c->mfx.md2, sig->digest_algo, 0 ))
2182                 BUG ();
2183             }
2184 #if 0 /* workaround disabled */
2185             /* Here we have another hack to work around a pgp 2 bug
2186              * It works by not using the textmode for detached signatures;
2187              * this will let the first signature check (on md) fail
2188              * but the second one (on md2) which adds an extra CR should
2189              * then produce the "correct" hash.  This is very, very ugly
2190              * hack but it may help in some cases (and break others)
2191              */
2192                     /*  c->mfx.md2? 0 :(sig->sig_class == 0x01) */
2193 #endif
2194             if ( DBG_HASHING ) {
2195                 gcry_md_debug( c->mfx.md, "verify" );
2196                 if ( c->mfx.md2  )
2197                     gcry_md_debug( c->mfx.md2, "verify2" );
2198             }
2199             if( c->sigs_only ) {
2200                 if (c->signed_data.used && c->signed_data.data_fd != -1)
2201                     rc = hash_datafile_by_fd (c->mfx.md, c->mfx.md2,
2202                                               c->signed_data.data_fd,
2203                                               (sig->sig_class == 0x01));
2204                 else
2205                     rc = hash_datafiles (c->mfx.md, c->mfx.md2,
2206                                          c->signed_data.data_names,
2207                                          c->sigfilename,
2208                                          (sig->sig_class == 0x01));
2209             }
2210             else {
2211                 rc = ask_for_detached_datafile( c->mfx.md, c->mfx.md2,
2212                                                 iobuf_get_real_fname(c->iobuf),
2213                                                 (sig->sig_class == 0x01) );
2214             }
2215             if( rc ) {
2216                 log_error("can't hash datafile: %s\n", g10_errstr(rc));
2217                 return;
2218             }
2219         }
2220         else if ( c->signed_data.used ) {
2221             log_error (_("not a detached signature\n") );
2222             return;
2223         }
2224         else if (!opt.quiet)
2225             log_info(_("old style (PGP 2.x) signature\n"));
2226
2227         if(multiple_ok)
2228           for( n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )) )
2229             check_sig_and_print( c, n1 );
2230         else
2231           check_sig_and_print( c, node );
2232     }
2233     else {
2234         dump_kbnode (c->list);
2235         log_error(_("invalid root packet detected in proc_tree()\n"));
2236         dump_kbnode (node);
2237     }
2238 }