Coverage Report

Created: 2026-09-01 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/g10/mainproc.c
Line
Count
Source
1
/* mainproc.c - handle packets
2
 * Copyright (C) 1998-2009 Free Software Foundation, Inc.
3
 * Copyright (C) 2013-2014 Werner Koch
4
 * Copyright (C) 2020, 2024 g10 Code GmbH
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 <https://www.gnu.org/licenses/>.
20
 */
21
22
#include <config.h>
23
#include <stdio.h>
24
#include <stdlib.h>
25
#include <string.h>
26
#include <time.h>
27
28
#include "gpg.h"
29
#include "../common/util.h"
30
#include "packet.h"
31
#include "../common/iobuf.h"
32
#include "options.h"
33
#include "keydb.h"
34
#include "filter.h"
35
#include "main.h"
36
#include "../common/status.h"
37
#include "../common/i18n.h"
38
#include "trustdb.h"
39
#include "keyserver-internal.h"
40
#include "photoid.h"
41
#include "../common/mbox-util.h"
42
#include "call-dirmngr.h"
43
#include "../common/compliance.h"
44
45
/* Put an upper limit on nested packets.  The 32 is an arbitrary
46
   value, a much lower should actually be sufficient.  */
47
57.6k
#define MAX_NESTING_DEPTH 32
48
49
50
/* An object to build a list of symkey packet info.  */
51
struct symlist_item
52
{
53
  struct symlist_item *next;
54
  int cipher_algo;
55
  enum gcry_cipher_modes cipher_mode;
56
  int other_error;
57
};
58
59
60
/*
61
 * Object to hold the processing context.
62
 */
63
typedef struct mainproc_context *CTX;
64
struct mainproc_context
65
{
66
  ctrl_t ctrl;
67
  struct mainproc_context *anchor;  /* May be useful in the future. */
68
  PKT_public_key *last_pubkey;
69
  PKT_user_id     *last_user_id;
70
  md_filter_context_t mfx;
71
  int sigs_only;    /* Process only signatures and reject all other stuff. */
72
  int encrypt_only; /* Process only encryption messages. */
73
74
  /* Name of the file with the complete signature or the file with the
75
     detached signature.  This is currently only used to deduce the
76
     file name of the data file if that has not been given. */
77
  const char *sigfilename;
78
79
  /* A structure to describe the signed data in case of a detached
80
     signature. */
81
  struct
82
  {
83
    /* A file descriptor of the signed data.  Only used if not -1. */
84
    gnupg_fd_t data_fd;
85
    /* A list of filenames with the data files or NULL. This is only
86
       used if DATA_FD is -1. */
87
    strlist_t data_names;
88
    /* Flag to indicated that either one of the next previous fields
89
       is used.  This is only needed for better readability. */
90
    int used;
91
  } signed_data;
92
93
  DEK *dek;
94
  int last_was_session_key;
95
  kbnode_t list;    /* The current list of packets. */
96
  iobuf_t iobuf;    /* Used to get the filename etc. */
97
  int trustletter;  /* Temporary usage in list_node. */
98
  ulong symkeys;    /* Number of symmetrically encrypted session keys.  */
99
  struct seskey_enc_list *sesenc_list; /* List of encryption packets. */
100
  struct symlist_item *symenc_list;   /* List of sym. encryption packets. */
101
  int seen_pkt_encrypted_aead; /* PKT_ENCRYPTED_AEAD packet seen. */
102
  int seen_pkt_encrypted_mdc;  /* PKT_ENCRYPTED_MDC packet seen. */
103
  struct {
104
    unsigned int sig_seen:1;      /* Set to true if a signature packet
105
                                     has been seen. */
106
    unsigned int data:1;          /* Any data packet seen */
107
    unsigned int uncompress_failed:1;
108
  } any;
109
};
110
111
112
/* Counter with the number of literal data packets seen.  Note that
113
 * this is also bumped at the end of an encryption.  This counter is
114
 * used for a basic consistency check of a received PGP message.  */
115
static int literals_seen;
116
117
118
/*** Local prototypes.  ***/
119
static int do_proc_packets (CTX c, iobuf_t a, int keep_dek_and_list);
120
static void list_node (CTX c, kbnode_t node);
121
static void proc_tree (CTX c, kbnode_t node);
122
123
124
/*** Functions.  ***/
125
126
/* Reset the literal data counter.  This is required to setup a new
127
 * decryption or verification context.  */
128
void
129
reset_literals_seen(void)
130
0
{
131
0
  literals_seen = 0;
132
0
}
133
134
135
static void
136
release_list( CTX c )
137
85.2k
{
138
85.2k
  proc_tree (c, c->list);
139
85.2k
  release_kbnode (c->list);
140
85.2k
  free_seskey_enc_list (c->sesenc_list);
141
85.2k
  c->sesenc_list = NULL;
142
106k
  while (c->symenc_list)
143
21.6k
    {
144
21.6k
      struct symlist_item *tmp = c->symenc_list->next;
145
21.6k
      xfree (c->symenc_list);
146
21.6k
      c->symenc_list = tmp;
147
21.6k
    }
148
85.2k
  c->symenc_list = NULL;
149
85.2k
  c->list = NULL;
150
85.2k
  c->any.data = 0;
151
85.2k
  c->any.uncompress_failed = 0;
152
85.2k
  c->last_was_session_key = 0;
153
85.2k
  c->seen_pkt_encrypted_aead = 0;
154
85.2k
  c->seen_pkt_encrypted_mdc = 0;
155
85.2k
  xfree (c->dek);
156
85.2k
  c->dek = NULL;
157
85.2k
}
158
159
160
static int
161
add_onepass_sig (CTX c, PACKET *pkt)
162
1.87k
{
163
1.87k
  kbnode_t node;
164
165
1.87k
  if (c->list) /* Add another packet. */
166
1.78k
    add_kbnode (c->list, new_kbnode (pkt));
167
91
  else /* Insert the first one.  */
168
91
    c->list = node = new_kbnode (pkt);
169
170
1.87k
  return 1;
171
1.87k
}
172
173
174
static int
175
add_gpg_control (CTX c, PACKET *pkt)
176
3.37k
{
177
3.37k
  if ( pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
178
3.37k
    {
179
      /* New clear text signature.
180
       * Process the last one and reset everything */
181
3.37k
      release_list(c);
182
3.37k
    }
183
184
3.37k
  if (c->list)  /* Add another packet.  */
185
0
    add_kbnode (c->list, new_kbnode (pkt));
186
3.37k
  else /* Insert the first one. */
187
3.37k
    c->list = new_kbnode (pkt);
188
189
3.37k
  return 1;
190
3.37k
}
191
192
193
static int
194
add_user_id (CTX c, PACKET *pkt)
195
35.4k
{
196
35.4k
  if (!c->list)
197
12.7k
    {
198
12.7k
      log_error ("orphaned user ID\n");
199
12.7k
      return 0;
200
12.7k
    }
201
22.7k
  add_kbnode (c->list, new_kbnode (pkt));
202
22.7k
  return 1;
203
35.4k
}
204
205
206
static int
207
add_subkey (CTX c, PACKET *pkt)
208
9.31k
{
209
9.31k
  if (!c->list)
210
3.04k
    {
211
3.04k
      log_error ("subkey w/o mainkey\n");
212
3.04k
      return 0;
213
3.04k
    }
214
6.27k
  add_kbnode (c->list, new_kbnode (pkt));
215
6.27k
  return 1;
216
9.31k
}
217
218
219
static int
220
add_ring_trust (CTX c, PACKET *pkt)
221
0
{
222
0
  if (!c->list)
223
0
    {
224
0
      log_error ("ring trust w/o key\n");
225
0
      return 0;
226
0
    }
227
0
  add_kbnode (c->list, new_kbnode (pkt));
228
0
  return 1;
229
0
}
230
231
232
static int
233
add_signature (CTX c, PACKET *pkt)
234
52.4k
{
235
52.4k
  kbnode_t node;
236
237
52.4k
  c->any.sig_seen = 1;
238
52.4k
  if (pkt->pkttype == PKT_SIGNATURE && !c->list)
239
24.0k
    {
240
      /* This is the first signature for the following datafile.
241
       * GPG does not write such packets; instead it always uses
242
       * onepass-sig packets.  The drawback of PGP's method
243
       * of prepending the signature to the data is
244
       * that it is not possible to make a signature from data read
245
       * from stdin.  (GPG is able to read PGP stuff anyway.) */
246
24.0k
      node = new_kbnode (pkt);
247
24.0k
      c->list = node;
248
24.0k
      return 1;
249
24.0k
    }
250
28.4k
  else if (!c->list)
251
0
    return 0; /* oops (invalid packet sequence)*/
252
28.4k
  else if (!c->list->pkt)
253
0
    BUG();    /* so nicht */
254
255
  /* Add a new signature node item at the end. */
256
28.4k
  node = new_kbnode (pkt);
257
28.4k
  add_kbnode (c->list, node);
258
259
28.4k
  return 1;
260
52.4k
}
261
262
static gpg_error_t
263
symkey_decrypt_seskey (DEK *dek, byte *seskey, size_t slen)
264
0
{
265
0
  gpg_error_t err;
266
0
  gcry_cipher_hd_t hd;
267
0
  unsigned int noncelen, keylen;
268
0
  enum gcry_cipher_modes ciphermode;
269
270
0
  if (dek->use_aead)
271
0
    {
272
0
      err = openpgp_aead_algo_info (dek->use_aead, &ciphermode, &noncelen);
273
0
      if (err)
274
0
        return err;
275
0
    }
276
0
  else
277
0
    {
278
0
      ciphermode = GCRY_CIPHER_MODE_CFB;
279
0
      noncelen = 0;
280
0
    }
281
282
  /* Check that the session key has a size of 16 to 32 bytes.  */
283
0
  if ((dek->use_aead && (slen < (noncelen + 16 + 16)
284
0
                         || slen > (noncelen + 32 + 16)))
285
0
      || (!dek->use_aead && (slen < 17 || slen > 33)))
286
0
    {
287
0
      log_error ( _("weird size for an encrypted session key (%d)\n"),
288
0
      (int)slen);
289
0
      return gpg_error (GPG_ERR_BAD_KEY);
290
0
    }
291
292
0
  err = openpgp_cipher_open (&hd, dek->algo, ciphermode, GCRY_CIPHER_SECURE);
293
0
  if (!err)
294
0
    err = gcry_cipher_setkey (hd, dek->key, dek->keylen);
295
0
  if (!err)
296
0
    err = gcry_cipher_setiv (hd, noncelen? seskey : NULL, noncelen);
297
0
  if (err)
298
0
    goto leave;
299
300
0
  if (dek->use_aead)
301
0
    {
302
0
      byte ad[4];
303
304
0
      ad[0] = (0xc0 | PKT_SYMKEY_ENC);
305
0
      ad[1] = 5;
306
0
      ad[2] = dek->algo;
307
0
      ad[3] = dek->use_aead;
308
0
      err = gcry_cipher_authenticate (hd, ad, 4);
309
0
      if (err)
310
0
        goto leave;
311
0
      gcry_cipher_final (hd);
312
0
      keylen = slen - noncelen - 16;
313
0
      err = gcry_cipher_decrypt (hd, seskey+noncelen, keylen, NULL, 0);
314
0
      if (err)
315
0
        goto leave;
316
0
      err = gcry_cipher_checktag (hd, seskey+noncelen+keylen, 16);
317
0
      if (err)
318
0
        goto leave;
319
      /* Now we replace the dek components with the real session key to
320
       * decrypt the contents of the sequencing packet. */
321
0
      if (keylen > DIM(dek->key))
322
0
        {
323
0
          err = gpg_error (GPG_ERR_TOO_LARGE);
324
0
          goto leave;
325
0
        }
326
0
      dek->keylen = keylen;
327
0
      memcpy (dek->key, seskey + noncelen, dek->keylen);
328
0
    }
329
0
  else
330
0
    {
331
0
      gcry_cipher_decrypt (hd, seskey, slen, NULL, 0 );
332
      /* Here we can only test whether the algo given in decrypted
333
       * session key is a valid OpenPGP algo.  With 11 defined
334
       * symmetric algorithms we will miss 4.3% of wrong passphrases
335
       * here.  The actual checking is done later during bulk
336
       * decryption; we can't bring this check forward easily.  We
337
       * need to use the GPG_ERR_CHECKSUM so that we won't run into
338
       * the gnupg < 2.2 bug compatible case which would terminate the
339
       * process on GPG_ERR_CIPHER_ALGO.  Note that with AEAD (above)
340
       * we will have a reliable test here.  */
341
0
      if (openpgp_cipher_test_algo (seskey[0])
342
0
          || openpgp_cipher_get_algo_keylen (seskey[0]) != slen - 1)
343
0
        {
344
0
          err = gpg_error (GPG_ERR_CHECKSUM);
345
0
          goto leave;
346
0
        }
347
348
      /* Now we replace the dek components with the real session key to
349
       * decrypt the contents of the sequencing packet. */
350
0
      keylen = slen-1;
351
0
      if (keylen > DIM(dek->key))
352
0
        {
353
0
          err = gpg_error (GPG_ERR_TOO_LARGE);
354
0
          goto leave;
355
0
        }
356
0
      dek->algo = seskey[0];
357
0
      dek->keylen = keylen;
358
0
      memcpy (dek->key, seskey + 1, dek->keylen);
359
0
    }
360
361
  /*log_hexdump( "thekey", dek->key, dek->keylen );*/
362
363
0
 leave:
364
0
  gcry_cipher_close (hd);
365
0
  return err;
366
0
}
367
368
369
static void
370
proc_symkey_enc (CTX c, PACKET *pkt)
371
21.6k
{
372
21.6k
  gpg_error_t err;
373
21.6k
  PKT_symkey_enc *enc;
374
375
21.6k
  enc = pkt->pkt.symkey_enc;
376
21.6k
  if (!enc)
377
21.6k
    log_error ("invalid symkey encrypted packet\n");
378
20.5k
  else if(!c->dek)
379
20.5k
    {
380
20.5k
      int algo = enc->cipher_algo;
381
20.5k
      const char *s = openpgp_cipher_algo_name (algo);
382
20.5k
      const char *a = (enc->aead_algo ? openpgp_aead_algo_name (enc->aead_algo)
383
20.5k
                       /**/           : "CFB");
384
385
20.5k
      if (!openpgp_cipher_test_algo (algo))
386
4.83k
        {
387
4.83k
          if (!opt.quiet)
388
4.83k
            {
389
4.83k
              if (enc->seskeylen)
390
4.83k
                log_info (_("%s.%s encrypted session key\n"), s, a );
391
4.10k
              else
392
4.83k
                log_info (_("%s.%s encrypted data\n"), s, a );
393
4.83k
            }
394
4.83k
        }
395
15.6k
      else
396
15.6k
        {
397
15.6k
          log_error (_("encrypted with unknown algorithm %d.%s\n"), algo, a);
398
15.6k
          s = NULL; /* Force a goto leave.  */
399
15.6k
        }
400
401
20.5k
      if (openpgp_md_test_algo (enc->s2k.hash_algo))
402
17.4k
        {
403
17.4k
          log_error(_("passphrase generated with unknown digest"
404
17.4k
                      " algorithm %d\n"),enc->s2k.hash_algo);
405
17.4k
          s = NULL;
406
17.4k
        }
407
408
20.5k
      c->last_was_session_key = 2;
409
20.5k
      if (!s || opt.list_only)
410
19.4k
        goto leave;
411
412
1.07k
      if (opt.override_session_key)
413
0
        {
414
0
          c->dek = xmalloc_clear (sizeof *c->dek);
415
0
          if (get_override_session_key (c->dek, opt.override_session_key))
416
0
            {
417
0
              xfree (c->dek);
418
0
              c->dek = NULL;
419
0
            }
420
0
        }
421
1.07k
      else
422
1.07k
        {
423
1.07k
          c->dek = passphrase_to_dek (algo, &enc->s2k, 0, 0, NULL,
424
1.07k
                                      GETPASSWORD_FLAG_SYMDECRYPT, NULL);
425
1.07k
          if (c->dek)
426
0
            {
427
0
              c->dek->symmetric = 1;
428
0
              c->dek->use_aead = enc->aead_algo;
429
430
              /* FIXME: This doesn't work perfectly if a symmetric key
431
                 comes before a public key in the message - if the
432
                 user doesn't know the passphrase, then there is a
433
                 chance that the "decrypted" algorithm will happen to
434
                 be a valid one, which will make the returned dek
435
                 appear valid, so we won't try any public keys that
436
                 come later. */
437
0
              if (enc->seskeylen)
438
0
                {
439
0
                  err = symkey_decrypt_seskey (c->dek,
440
0
                                               enc->seskey, enc->seskeylen);
441
0
                  if (err)
442
0
                    {
443
0
                      log_info ("decryption of the symmetrically encrypted"
444
0
                                 " session key failed: %s\n",
445
0
                                 gpg_strerror (err));
446
0
                      if (gpg_err_code (err) != GPG_ERR_BAD_KEY
447
0
                          && gpg_err_code (err) != GPG_ERR_CHECKSUM)
448
0
                        log_fatal ("process terminated to be bug compatible"
449
0
                                   " with GnuPG <= 2.2\n");
450
0
                      else
451
0
                        write_status_text (STATUS_ERROR,
452
0
                                           "symkey_decrypt.maybe_error"
453
0
                                           " 11_BAD_PASSPHRASE");
454
455
0
                      if (c->dek->s2k_cacheid[0])
456
0
                        {
457
0
                          if (opt.debug)
458
0
                            log_debug ("cleared passphrase cached with ID:"
459
0
                                       " %s\n", c->dek->s2k_cacheid);
460
0
                          passphrase_clear_cache (c->dek->s2k_cacheid);
461
0
                        }
462
0
                      xfree (c->dek);
463
0
                      c->dek = NULL;
464
0
                    }
465
0
                }
466
0
              else
467
0
                c->dek->algo_info_printed = 1;
468
0
            }
469
1.07k
        }
470
1.07k
    }
471
472
21.6k
 leave:
473
  /* Record infos from the packet.  */
474
21.6k
  {
475
21.6k
    struct symlist_item  *symitem;
476
21.6k
    symitem = xcalloc (1, sizeof *symitem);
477
21.6k
    if (enc)
478
20.5k
      {
479
20.5k
        symitem->cipher_algo = enc->cipher_algo;
480
20.5k
        symitem->cipher_mode = !enc->aead_algo;
481
20.5k
        symitem->cipher_mode
482
20.5k
          = (enc->aead_algo == AEAD_ALGO_NONE? GCRY_CIPHER_MODE_CFB :
483
20.5k
             enc->aead_algo == AEAD_ALGO_OCB?  GCRY_CIPHER_MODE_OCB :
484
1.70k
             GCRY_CIPHER_MODE_NONE);
485
20.5k
      }
486
1.13k
    else
487
1.13k
      symitem->other_error = 1;
488
21.6k
    symitem->next = c->symenc_list;
489
21.6k
    c->symenc_list = symitem;
490
21.6k
  }
491
21.6k
  c->symkeys++;
492
21.6k
  free_packet (pkt, NULL);
493
21.6k
}
494
495
496
static void
497
proc_pubkey_enc (CTX c, PACKET *pkt)
498
10.7k
{
499
10.7k
  PKT_pubkey_enc *enc;
500
501
  /* Check whether the secret key is available and store in this case.  */
502
10.7k
  c->last_was_session_key = 1;
503
10.7k
  enc = pkt->pkt.pubkey_enc;
504
  /*printf("enc: encrypted by a pubkey with keyid %08lX\n", enc->keyid[1] );*/
505
  /* Hmmm: why do I have this algo check here - anyway there is
506
   * function to check it. */
507
10.7k
  if (opt.verbose)
508
10.7k
    log_info (_("public key is %s\n"), keystr (enc->keyid));
509
510
10.7k
  if (is_status_enabled ())
511
0
    {
512
0
      char buf[50];
513
0
      snprintf (buf, sizeof buf, "%08lX%08lX %d 0",
514
0
                (ulong)enc->keyid[0], (ulong)enc->keyid[1], enc->pubkey_algo);
515
0
      write_status_text (STATUS_ENC_TO, buf);
516
0
    }
517
518
10.7k
  if (!opt.list_only && !opt.override_session_key)
519
10.7k
    {
520
10.7k
      struct seskey_enc_list *x = xcalloc (1, sizeof *x);
521
522
10.7k
      copy_pubkey_enc_parts (&x->u.pub, enc);
523
10.7k
      x->result = -1;
524
10.7k
      x->next = c->sesenc_list;
525
10.7k
      c->sesenc_list = x;
526
10.7k
    }
527
528
10.7k
  free_packet(pkt, NULL);
529
10.7k
}
530
531
532
/*
533
 * Print the list of public key encrypted packets which we could
534
 * not decrypt.
535
 */
536
static void
537
print_sesenc_list (ctrl_t ctrl, struct seskey_enc_list *list)
538
33.6k
{
539
936k
  for (; list; list = list->next)
540
902k
    {
541
902k
      PKT_public_key *pk;
542
902k
      char pkstrbuf[PUBKEY_STRING_SIZE];
543
902k
      char *p;
544
545
902k
      if (list->u_sym)
546
0
        continue;
547
548
902k
      pk = xmalloc_clear (sizeof *pk);
549
550
902k
      pk->pubkey_algo = list->u.pub.pubkey_algo;
551
902k
      if (!get_pubkey (ctrl, pk, list->u.pub.keyid))
552
0
        {
553
0
          pubkey_string (pk, pkstrbuf, sizeof pkstrbuf);
554
555
0
          log_info (_("encrypted with %s key, ID %s, created %s\n"),
556
0
                    pkstrbuf, keystr_from_pk (pk),
557
0
                    strtimestamp (pk->timestamp));
558
0
          p = get_user_id_native (ctrl, list->u.pub.keyid);
559
0
          log_printf (_("      \"%s\"\n"), p);
560
0
          xfree (p);
561
0
        }
562
902k
      else
563
902k
        log_info (_("encrypted with %s key, ID %s\n"),
564
902k
                  openpgp_pk_algo_name (list->u.pub.pubkey_algo),
565
902k
                  keystr (list->u.pub.keyid));
566
567
902k
      if (opt.flags.require_pqc_encryption
568
0
          && pk->pubkey_algo != PUBKEY_ALGO_KYBER)
569
902k
        log_info (_("WARNING: key is not quantum-resistant\n"));
570
571
902k
      free_public_key (pk);
572
902k
    }
573
33.6k
}
574
575
576
static void
577
proc_encrypted (CTX c, PACKET *pkt)
578
33.6k
{
579
33.6k
  int result = 0;
580
33.6k
  int early_plaintext = literals_seen;
581
33.6k
  unsigned int compliance_de_vs = 0;
582
33.6k
  enum gcry_cipher_modes ciphermode;
583
33.6k
  int unknown_ciphermode;
584
585
33.6k
  if (pkt)
586
33.6k
    {
587
33.6k
      if (pkt->pkttype == PKT_ENCRYPTED_AEAD)
588
23.1k
        c->seen_pkt_encrypted_aead = 1;
589
33.6k
      if (pkt->pkttype == PKT_ENCRYPTED_MDC)
590
1.30k
        c->seen_pkt_encrypted_mdc = 1;
591
33.6k
    }
592
0
  else /* No PKT indicates the add-recipients mode.  */
593
33.6k
    log_assert (c->ctrl->modify_recipients);
594
595
33.6k
  if (early_plaintext)
596
33.6k
    {
597
33.6k
      log_info (_("WARNING: multiple plaintexts seen\n"));
598
33.6k
      write_status_errcode ("decryption.early_plaintext", GPG_ERR_BAD_DATA);
599
      /* We fail only later so that we can print some more info first.  */
600
33.6k
    }
601
602
33.6k
  if (!opt.quiet)
603
33.6k
    {
604
33.6k
      if (c->symkeys>1)
605
33.6k
        log_info (_("encrypted with %lu passphrases\n"), c->symkeys);
606
30.0k
      else if (c->symkeys == 1)
607
30.0k
        log_info (_("encrypted with 1 passphrase\n"));
608
33.6k
      print_sesenc_list (c->ctrl, c->sesenc_list);
609
33.6k
    }
610
611
  /* Figure out the session key by looking at all pkenc packets. */
612
33.6k
  if (opt.list_only || c->dek)
613
0
    ;
614
33.6k
  else if (opt.override_session_key)
615
0
    {
616
0
      c->dek = xmalloc_clear (sizeof *c->dek);
617
0
      result = get_override_session_key (c->dek, opt.override_session_key);
618
0
      if (result)
619
0
        {
620
0
          xfree (c->dek);
621
0
          c->dek = NULL;
622
0
          log_info (_("public key decryption failed: %s\n"),
623
0
                    gpg_strerror (result));
624
0
          write_status_error ("pkdecrypt_failed", result);
625
0
        }
626
0
    }
627
33.6k
  else if (c->sesenc_list)
628
3.91k
    {
629
3.91k
      c->dek = xmalloc_secure_clear (sizeof *c->dek);
630
3.91k
      result = get_session_key (c->ctrl, c->sesenc_list, c->dek);
631
3.91k
      if (is_status_enabled ())
632
0
        {
633
0
          struct seskey_enc_list *list;
634
635
0
          for (list = c->sesenc_list; list; list = list->next)
636
0
            if (list->result && !list->u_sym)
637
0
              { /* Key was not tried or it caused an error.  */
638
0
                char buf[20];
639
0
                snprintf (buf, sizeof buf, "%08lX%08lX",
640
0
                          (ulong)list->u.pub.keyid[0],
641
0
                          (ulong)list->u.pub.keyid[1]);
642
0
                write_status_text (STATUS_NO_SECKEY, buf);
643
0
              }
644
0
        }
645
646
3.91k
      if (result)
647
3.91k
        {
648
3.91k
          log_info (_("public key decryption failed: %s\n"),
649
3.91k
                    gpg_strerror (result));
650
3.91k
          write_status_error ("pkdecrypt_failed", result);
651
652
          /* Error: Delete the DEK. */
653
3.91k
          xfree (c->dek);
654
3.91k
          c->dek = NULL;
655
3.91k
        }
656
3.91k
    }
657
658
33.6k
  if (c->dek && opt.verbose > 1)
659
33.6k
    log_info (_("public key encrypted data: good DEK\n"));
660
661
33.6k
  if (c->ctrl->modify_recipients)
662
0
    {
663
0
      if (c->anchor)
664
0
        {
665
0
          log_error ("command not possible with nested data\n");
666
0
          write_status_errcode ("decryption.mod_recp", GPG_ERR_BAD_DATA);
667
0
          xfree (c->dek);
668
0
          c->dek = NULL;
669
0
          return;
670
0
        }
671
0
      literals_seen++;
672
      /* Simply return here.  Our caller will then test for DEK and
673
       * the PK_list to decide whether decryption worked.  */
674
0
      return;
675
0
    }
676
677
33.6k
  if (!opt.show_only_session_key)
678
33.6k
    write_status (STATUS_BEGIN_DECRYPTION);
679
680
  /*log_debug("dat: %sencrypted data\n", c->dek?"":"conventional ");*/
681
33.6k
  if (opt.list_only)
682
0
    result = -1;
683
33.6k
  else if (!c->dek && !c->last_was_session_key)
684
27.0k
    {
685
27.0k
      int algo;
686
27.0k
      STRING2KEY s2kbuf;
687
27.0k
      STRING2KEY *s2k = NULL;
688
27.0k
      int canceled;
689
690
27.0k
      if (opt.override_session_key)
691
0
        {
692
0
          c->dek = xmalloc_clear (sizeof *c->dek);
693
0
          result = get_override_session_key (c->dek, opt.override_session_key);
694
0
          if (result)
695
0
            {
696
0
              xfree (c->dek);
697
0
              c->dek = NULL;
698
0
            }
699
0
        }
700
27.0k
      else
701
27.0k
        {
702
          /* Assume this is old style conventional encrypted data. */
703
27.0k
          algo = opt.def_cipher_algo;
704
27.0k
          if (algo)
705
27.0k
            log_info (_("assuming %s encrypted data\n"),
706
0
                      openpgp_cipher_algo_name (algo));
707
27.0k
          else if (openpgp_cipher_test_algo (CIPHER_ALGO_IDEA))
708
0
            {
709
0
              algo = opt.def_cipher_algo;
710
0
              if (!algo)
711
0
                algo = opt.s2k_cipher_algo;
712
0
              log_info (_("IDEA cipher unavailable, "
713
0
                          "optimistically attempting to use %s instead\n"),
714
0
                        openpgp_cipher_algo_name (algo));
715
0
            }
716
27.0k
          else
717
27.0k
            {
718
27.0k
              algo = CIPHER_ALGO_IDEA;
719
27.0k
              if (!opt.s2k_digest_algo)
720
27.0k
                {
721
                  /* If no digest is given we assume SHA-1. */
722
27.0k
                  s2kbuf.mode = 0;
723
27.0k
                  s2kbuf.hash_algo = DIGEST_ALGO_SHA1;
724
27.0k
                  s2k = &s2kbuf;
725
27.0k
                }
726
27.0k
              log_info (_("assuming %s encrypted data\n"), "IDEA");
727
27.0k
            }
728
729
27.0k
          c->dek = passphrase_to_dek (algo, s2k, 0, 0, NULL,
730
27.0k
                                      GETPASSWORD_FLAG_SYMDECRYPT, &canceled);
731
27.0k
          if (c->dek)
732
0
            c->dek->algo_info_printed = 1;
733
27.0k
          else if (canceled)
734
27.0k
            result = gpg_error (GPG_ERR_CANCELED);
735
0
          else
736
0
            result = gpg_error (GPG_ERR_INV_PASSPHRASE);
737
27.0k
        }
738
27.0k
    }
739
6.61k
  else if (!c->dek)
740
6.61k
    {
741
6.61k
      if (c->symkeys && !c->sesenc_list)
742
3.60k
        result = gpg_error (GPG_ERR_BAD_KEY);
743
744
6.61k
      if (!result)
745
0
        result = gpg_error (GPG_ERR_NO_SECKEY);
746
6.61k
    }
747
748
  /* We need to know the ciphermode for gnupg_cipher_is_compliant.  */
749
33.6k
  unknown_ciphermode = 0;
750
33.6k
  if (pkt->pkt.encrypted->aead_algo)
751
4.71k
    {
752
4.71k
      unsigned int dummy;
753
4.71k
      if (openpgp_aead_algo_info (pkt->pkt.encrypted->aead_algo,
754
4.71k
                                  &ciphermode, &dummy))
755
1.60k
        unknown_ciphermode = 1;  /* error -> unknown mode */
756
4.71k
    }
757
28.9k
  else
758
28.9k
    ciphermode = GCRY_CIPHER_MODE_CFB;
759
760
  /* Compute compliance with CO_DE_VS.  */
761
33.6k
  if (!result && (is_status_enabled () || opt.flags.require_compliance)
762
      /* Overriding session key voids compliance.  */
763
0
      && !opt.override_session_key
764
      /* Check symmetric cipher.  */
765
0
      && gnupg_gcrypt_is_compliant (CO_DE_VS)
766
0
      && !unknown_ciphermode
767
0
      && gnupg_cipher_is_compliant (CO_DE_VS, c->dek->algo, ciphermode))
768
0
    {
769
0
      struct seskey_enc_list *i;
770
0
      struct symlist_item *si;
771
0
      int compliant = 1;
772
0
      PKT_public_key *pk = xmalloc (sizeof *pk);
773
774
0
      if ( !(c->sesenc_list || c->symkeys) )
775
0
        log_debug ("%s: where else did the session key come from?\n", __func__);
776
777
      /* Check that all seen symmetric key packets use compliant
778
       * algos.  This is so that no non-compliant encrypted session
779
       * key can be sneaked in.  */
780
0
      for (si = c->symenc_list; si && compliant; si = si->next)
781
0
        {
782
0
          if (si->cipher_mode == GCRY_CIPHER_MODE_NONE
783
0
              || !gnupg_cipher_is_compliant (CO_DE_VS, si->cipher_algo,
784
0
                                             si->cipher_mode))
785
0
            compliant = 0;
786
0
        }
787
788
      /* Check that every known public key used to encrypt the session key
789
       * is compliant.  */
790
0
      for (i = c->sesenc_list; i && compliant; i = i->next)
791
0
        {
792
0
          if (i->u_sym)
793
0
            continue;
794
0
          memset (pk, 0, sizeof *pk);
795
0
          pk->pubkey_algo = i->u.pub.pubkey_algo;
796
0
          if (!get_pubkey (c->ctrl, pk, i->u.pub.keyid)
797
0
              && !gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0,
798
0
                                         pk->pkey, nbits_from_pk (pk), NULL))
799
0
            compliant = 0;
800
0
          release_public_key_parts (pk);
801
0
        }
802
803
0
      xfree (pk);
804
805
0
      if (compliant)
806
0
        compliance_de_vs |= 1;
807
0
    }
808
809
33.6k
  if (!result)
810
0
    {
811
0
      int compl_error;
812
0
      result = decrypt_data (c->ctrl, c, pkt->pkt.encrypted, c->dek,
813
0
                             &compl_error);
814
0
      if (!result && !compl_error)
815
0
        compliance_de_vs |= 2;
816
0
    }
817
818
  /* Trigger the deferred error.  */
819
33.6k
  if (!result && early_plaintext)
820
0
    result = gpg_error (GPG_ERR_BAD_DATA);
821
33.6k
  else if (!result && opt.show_only_session_key)
822
0
    result = -1;
823
824
825
33.6k
  if (result == -1)
826
0
    ;
827
33.6k
  else if (!result
828
0
           && !opt.ignore_mdc_error
829
0
           && !pkt->pkt.encrypted->mdc_method
830
0
           && !pkt->pkt.encrypted->aead_algo)
831
0
    {
832
      /* The message has been decrypted but does not carry an MDC or
833
       * uses AEAD encryption.  --ignore-mdc-error has also not been
834
       * used.  To avoid attacks changing an MDC message to a non-MDC
835
       * message, we fail here.  */
836
0
      log_error (_("WARNING: message was not integrity protected\n"));
837
0
      if (!pkt->pkt.encrypted->mdc_method
838
0
          && (openpgp_cipher_get_algo_blklen (c->dek->algo) == 8
839
0
              || c->dek->algo == CIPHER_ALGO_TWOFISH))
840
0
        {
841
          /* Before 2.2.8 we did not fail hard for a missing MDC if
842
           * one of the old ciphers where used.  Although these cases
843
           * are rare in practice we print a hint on how to decrypt
844
           * such messages.  */
845
0
          log_string
846
0
            (GPGRT_LOGLVL_INFO,
847
0
             _("Hint: If this message was created before the year 2003 it is\n"
848
0
               "likely that this message is legitimate.  This is because back\n"
849
0
               "then integrity protection was not widely used.\n"));
850
0
          log_info (_("Use the option '%s' to decrypt anyway.\n"),
851
0
                     "--ignore-mdc-error");
852
0
          write_status_errcode ("nomdc_with_legacy_cipher",
853
0
                                GPG_ERR_DECRYPT_FAILED);
854
0
        }
855
0
      log_info (_("decryption forced to fail!\n"));
856
0
      write_status (STATUS_DECRYPTION_FAILED);
857
0
    }
858
33.6k
  else if (!result || (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE
859
0
                       && !pkt->pkt.encrypted->aead_algo
860
0
                       && opt.ignore_mdc_error))
861
0
    {
862
      /* All is fine or for an MDC message the MDC failed but the
863
       * --ignore-mdc-error option is active.  For compatibility
864
       * reasons we issue GOODMDC also for AEAD messages.  */
865
0
      int partfailed;
866
867
0
      if (gnupg_commit_partial_file ())
868
0
        {
869
0
          partfailed = 1;
870
0
          log_error ("renaming partial file failed\n");
871
0
          write_status (STATUS_DECRYPTION_FAILED);
872
0
        }
873
0
      else
874
0
        {
875
0
          partfailed = 0;
876
0
          write_status (STATUS_DECRYPTION_OKAY);
877
0
          if (opt.verbose > 1)
878
0
            log_info(_("decryption okay\n"));
879
0
        }
880
881
0
      if (partfailed)
882
0
        ;
883
0
      else if (pkt->pkt.encrypted->aead_algo)
884
0
        {
885
0
          write_status (STATUS_GOODMDC);
886
0
          compliance_de_vs |= 4;
887
0
        }
888
0
      else if (pkt->pkt.encrypted->mdc_method && !result)
889
0
        {
890
0
          write_status (STATUS_GOODMDC);
891
0
          compliance_de_vs |= 4;
892
0
        }
893
0
      else
894
0
        log_info (_("WARNING: message was not integrity protected\n"));
895
0
    }
896
33.6k
  else if (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE
897
33.6k
           || gpg_err_code (result) == GPG_ERR_TRUNCATED)
898
0
    {
899
0
      glo_ctrl.lasterr = result;
900
0
      log_error (_("WARNING: encrypted message has been manipulated!\n"));
901
0
      write_status (STATUS_BADMDC);
902
0
      write_status (STATUS_DECRYPTION_FAILED);
903
0
    }
904
33.6k
  else
905
33.6k
    {
906
33.6k
      if (gpg_err_code (result) == GPG_ERR_BAD_KEY
907
30.0k
          || gpg_err_code (result) == GPG_ERR_CHECKSUM
908
30.0k
          || gpg_err_code (result) == GPG_ERR_CIPHER_ALGO)
909
3.60k
        {
910
3.60k
          if (c->symkeys)
911
3.60k
            write_status_text (STATUS_ERROR,
912
3.60k
                               "symkey_decrypt.maybe_error"
913
3.60k
                               " 11_BAD_PASSPHRASE");
914
915
3.60k
          if (c->dek && *c->dek->s2k_cacheid != '\0')
916
0
            {
917
0
              if (opt.debug)
918
0
                log_debug ("cleared passphrase cached with ID: %s\n",
919
0
                           c->dek->s2k_cacheid);
920
0
              passphrase_clear_cache (c->dek->s2k_cacheid);
921
0
            }
922
3.60k
        }
923
33.6k
      glo_ctrl.lasterr = result;
924
33.6k
      write_status (STATUS_DECRYPTION_FAILED);
925
33.6k
      log_error (_("decryption failed: %s\n"), gpg_strerror (result));
926
      /* Hmmm: does this work when we have encrypted using multiple
927
       * ways to specify the session key (symmmetric and PK). */
928
33.6k
    }
929
930
931
  /* If we concluded that the decryption was compliant, issue a
932
   * compliance status before the end of the decryption status.  */
933
33.6k
  if (compliance_de_vs == (4|2|1))
934
0
    {
935
0
      write_status_strings (STATUS_DECRYPTION_COMPLIANCE_MODE,
936
0
                            gnupg_status_compliance_flag (CO_DE_VS),
937
0
                            NULL);
938
0
    }
939
940
33.6k
  xfree (c->dek);
941
33.6k
  c->dek = NULL;
942
33.6k
  free_packet (pkt, NULL);
943
33.6k
  c->last_was_session_key = 0;
944
945
33.6k
  if (!opt.show_only_session_key)
946
33.6k
    write_status (STATUS_END_DECRYPTION);
947
948
  /* Bump the counter even if we have not seen a literal data packet
949
   * inside an encryption container.  This acts as a sentinel in case
950
   * a misplace extra literal data packets follows after this
951
   * encrypted packet.  */
952
33.6k
  literals_seen++;
953
954
  /* The --require-compliance option allows one to simplify decryption in
955
   * de-vs compliance mode by just looking at the exit status.  */
956
33.6k
  if (opt.flags.require_compliance
957
0
      && opt.compliance == CO_DE_VS
958
0
      && compliance_de_vs != (4|2|1)
959
0
      && !opt.show_only_session_key)
960
0
    {
961
0
      log_error (_("operation forced to fail due to"
962
0
                   " unfulfilled compliance rules\n"));
963
0
      g10_errors_seen = 1;
964
0
    }
965
33.6k
}
966
967
968
static int
969
have_seen_pkt_encrypted_aead_or_mdc( CTX c )
970
3.07k
{
971
3.07k
  CTX cc;
972
973
9.38k
  for (cc = c; cc; cc = cc->anchor)
974
7.02k
    {
975
7.02k
      if (cc->seen_pkt_encrypted_aead)
976
525
  return 1;
977
6.50k
      if (cc->seen_pkt_encrypted_mdc)
978
194
  return 1;
979
6.50k
    }
980
981
2.35k
  return 0;
982
3.07k
}
983
984
985
static void
986
proc_plaintext( CTX c, PACKET *pkt )
987
13.6k
{
988
13.6k
  PKT_plaintext *pt = pkt->pkt.plaintext;
989
13.6k
  int any, clearsig, rc;
990
13.6k
  kbnode_t n;
991
13.6k
  unsigned char *extrahash;
992
13.6k
  size_t extrahashlen;
993
994
  /* This is a literal data packet.  Bump a counter for later checks.  */
995
13.6k
  literals_seen++;
996
997
13.6k
  if (pt->namelen == 8 && !memcmp( pt->name, "_CONSOLE", 8))
998
13.6k
    log_info (_("Note: sender requested \"for-your-eyes-only\"\n"));
999
13.6k
  else if (opt.verbose)
1000
0
    {
1001
      /* We don't use print_utf8_buffer because that would require a
1002
       * string change which we don't want in 2.2.  It is also not
1003
       * clear whether the filename is always utf-8 encoded.  */
1004
0
      char *tmp = make_printable_string (pt->name, pt->namelen, 0);
1005
0
      log_info (_("original file name='%.*s'\n"), (int)strlen (tmp), tmp);
1006
0
      xfree (tmp);
1007
0
    }
1008
1009
13.6k
  free_md_filter_context (&c->mfx);
1010
13.6k
  if (gcry_md_open (&c->mfx.md, 0, 0))
1011
0
    BUG ();
1012
  /* fixme: we may need to push the textfilter if we have sigclass 1
1013
   * and no armoring - Not yet tested
1014
   * Hmmm, why don't we need it at all if we have sigclass 1
1015
   * Should we assume that plaintext in mode 't' has always sigclass 1??
1016
   * See: Russ Allbery's mail 1999-02-09
1017
   */
1018
13.6k
  any = clearsig = 0;
1019
11.7M
  for (n=c->list; n; n = n->next )
1020
11.7M
    {
1021
11.7M
      if (n->pkt->pkttype == PKT_ONEPASS_SIG)
1022
13.2k
        {
1023
          /* The onepass signature case. */
1024
13.2k
          if (n->pkt->pkt.onepass_sig->digest_algo)
1025
12.0k
            {
1026
12.0k
              if (!opt.skip_verify)
1027
12.0k
                gcry_md_enable (c->mfx.md,
1028
12.0k
                                n->pkt->pkt.onepass_sig->digest_algo);
1029
1030
12.0k
              any = 1;
1031
12.0k
            }
1032
13.2k
        }
1033
11.6M
      else if (n->pkt->pkttype == PKT_GPG_CONTROL
1034
11.6M
               && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START)
1035
3.10k
        {
1036
          /* The clearsigned message case. */
1037
3.10k
          size_t datalen = n->pkt->pkt.gpg_control->datalen;
1038
3.10k
          const byte *data = n->pkt->pkt.gpg_control->data;
1039
1040
          /* Check that we have at least the sigclass and one hash.  */
1041
3.10k
          if  (datalen < 2)
1042
3.10k
            log_fatal ("invalid control packet CTRLPKT_CLEARSIGN_START\n");
1043
          /* Note that we don't set the clearsig flag for not-dash-escaped
1044
           * documents.  */
1045
3.10k
          clearsig = (*data == 0x01);
1046
7.82k
          for (data++, datalen--; datalen; datalen--, data++)
1047
4.72k
            if (!opt.skip_verify)
1048
4.72k
              gcry_md_enable (c->mfx.md, *data);
1049
3.10k
          any = 1;
1050
3.10k
          break;  /* Stop here as one-pass signature packets are not
1051
                     expected.  */
1052
3.10k
        }
1053
11.6M
      else if (n->pkt->pkttype == PKT_SIGNATURE)
1054
19.1k
        {
1055
          /* The SIG+LITERAL case that PGP used to use.  */
1056
19.1k
          if (!opt.skip_verify)
1057
19.1k
            gcry_md_enable (c->mfx.md, n->pkt->pkt.signature->digest_algo);
1058
19.1k
          any = 1;
1059
19.1k
        }
1060
11.7M
    }
1061
1062
13.6k
  if (!any && !opt.skip_verify && !have_seen_pkt_encrypted_aead_or_mdc(c))
1063
2.35k
    {
1064
      /* This is for the old GPG LITERAL+SIG case.  It's not legal
1065
         according to 2440, so hopefully it won't come up that often.
1066
         There is no good way to specify what algorithms to use in
1067
         that case, so these there are the historical answer. */
1068
2.35k
  gcry_md_enable (c->mfx.md, DIGEST_ALGO_RMD160);
1069
2.35k
  gcry_md_enable (c->mfx.md, DIGEST_ALGO_SHA1);
1070
2.35k
    }
1071
13.6k
  if (DBG_HASHING)
1072
0
    {
1073
0
      gcry_md_debug (c->mfx.md, "verify");
1074
0
      if (c->mfx.md2)
1075
0
        gcry_md_debug (c->mfx.md2, "verify2");
1076
0
    }
1077
1078
13.6k
  rc=0;
1079
1080
13.6k
  if (literals_seen > 1)
1081
13.6k
    {
1082
13.6k
      log_info (_("WARNING: multiple plaintexts seen\n"));
1083
1084
13.6k
      write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA");
1085
13.6k
      log_inc_errorcount ();
1086
13.6k
      rc = gpg_error (GPG_ERR_UNEXPECTED);
1087
13.6k
    }
1088
1089
13.6k
  if (!rc)
1090
1
    {
1091
      /* It we are in --verify mode, we do not want to output the
1092
       * signed text.  However, if --output is also used we do what
1093
       * has been requested and write out the signed data.  */
1094
1
      rc = handle_plaintext (pt, &c->mfx,
1095
1
                             (opt.outfp || opt.outfile)? 0 :  c->sigs_only,
1096
1
                             clearsig);
1097
1
      if (gpg_err_code (rc) == GPG_ERR_EACCES && !c->sigs_only)
1098
0
        {
1099
          /* Can't write output but we hash it anyway to check the
1100
             signature. */
1101
0
          rc = handle_plaintext( pt, &c->mfx, 1, clearsig );
1102
0
        }
1103
1
    }
1104
1105
13.6k
  if (rc)
1106
13.6k
    log_error ("handle plaintext failed: %s\n", gpg_strerror (rc));
1107
1108
  /* We add a marker control packet instead of the plaintext packet.
1109
   * This is so that we can later detect invalid packet sequences.
1110
   * The packet is further used to convey extra data from the
1111
   * plaintext packet to the signature verification. */
1112
13.6k
  extrahash = xtrymalloc (6 + pt->namelen);
1113
13.6k
  if (!extrahash)
1114
0
    {
1115
      /* No way to return an error.  */
1116
0
      rc = gpg_error_from_syserror ();
1117
0
      log_error ("malloc failed in %s: %s\n", __func__, gpg_strerror (rc));
1118
0
      extrahashlen = 0;
1119
0
    }
1120
13.6k
  else
1121
13.6k
    {
1122
13.6k
      extrahash[0] = pt->mode;
1123
13.6k
      extrahash[1] = pt->namelen;
1124
13.6k
      if (pt->namelen)
1125
9.68k
        memcpy (extrahash+2, pt->name, pt->namelen);
1126
13.6k
      extrahashlen = 2 + pt->namelen;
1127
13.6k
      extrahash[extrahashlen++] = pt->timestamp >> 24;
1128
13.6k
      extrahash[extrahashlen++] = pt->timestamp >> 16;
1129
13.6k
      extrahash[extrahashlen++] = pt->timestamp >>  8;
1130
13.6k
      extrahash[extrahashlen++] = pt->timestamp      ;
1131
13.6k
    }
1132
1133
13.6k
  free_packet (pkt, NULL);
1134
13.6k
  c->last_was_session_key = 0;
1135
1136
13.6k
  n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK,
1137
13.6k
                                      extrahash, extrahashlen));
1138
13.6k
  xfree (extrahash);
1139
13.6k
  if (c->list)
1140
13.0k
    add_kbnode (c->list, n);
1141
651
  else
1142
651
    c->list = n;
1143
13.6k
}
1144
1145
1146
static int
1147
proc_compressed_cb (iobuf_t a, void *info)
1148
0
{
1149
0
  if ( ((CTX)info)->signed_data.used
1150
0
       && ((CTX)info)->signed_data.data_fd != GNUPG_INVALID_FD)
1151
0
    return proc_signature_packets_by_fd (((CTX)info)->ctrl, info, a,
1152
0
                                         ((CTX)info)->signed_data.data_fd);
1153
0
  else
1154
0
    return proc_signature_packets (((CTX)info)->ctrl, info, a,
1155
0
                                   ((CTX)info)->signed_data.data_names,
1156
0
                                   ((CTX)info)->sigfilename );
1157
0
}
1158
1159
1160
static int
1161
proc_encrypt_cb (iobuf_t a, void *info )
1162
0
{
1163
0
  CTX c = info;
1164
0
  return proc_encryption_packets (c->ctrl, info, a, NULL, NULL);
1165
0
}
1166
1167
1168
static int
1169
proc_compressed (CTX c, PACKET *pkt)
1170
49.8k
{
1171
49.8k
  PKT_compressed *zd = pkt->pkt.compressed;
1172
49.8k
  int rc;
1173
1174
  /*printf("zip: compressed data packet\n");*/
1175
49.8k
  if (c->sigs_only)
1176
0
    rc = handle_compressed (c->ctrl, c, zd, proc_compressed_cb, c);
1177
49.8k
  else if( c->encrypt_only )
1178
0
    rc = handle_compressed (c->ctrl, c, zd, proc_encrypt_cb, c);
1179
49.8k
  else
1180
49.8k
    rc = handle_compressed (c->ctrl, c, zd, NULL, NULL);
1181
1182
49.8k
  if (gpg_err_code (rc) == GPG_ERR_BAD_DATA)
1183
192
    {
1184
192
      if  (!c->any.uncompress_failed)
1185
6
        {
1186
6
          CTX cc;
1187
1188
198
          for (cc=c; cc; cc = cc->anchor)
1189
192
            cc->any.uncompress_failed = 1;
1190
6
          log_error ("uncompressing failed: %s\n", gpg_strerror (rc));
1191
6
        }
1192
192
    }
1193
49.6k
  else if (rc)
1194
49.6k
    log_error ("uncompressing failed: %s\n", gpg_strerror (rc));
1195
1196
49.8k
  free_packet (pkt, NULL);
1197
49.8k
  c->last_was_session_key = 0;
1198
49.8k
  return rc;
1199
49.8k
}
1200
1201
1202
/*
1203
 * Check the signature.  If R_PK is not NULL a copy of the public key
1204
 * used to verify the signature will be stored there, or NULL if not
1205
 * found.  If FORCED_PK is not NULL, this public key is used to verify
1206
 * _data signatures_ and no key lookup is done.  Returns: 0 = valid
1207
 * signature or an error code.  If R_KEYBLOCK is not NULL the keyblock
1208
 * carries the used PK is stored there.  The caller should always free
1209
 * the return value using release_kbnode.
1210
 */
1211
static int
1212
do_check_sig (CTX c, kbnode_t node, const void *extrahash, size_t extrahashlen,
1213
              PKT_public_key *forced_pk, int *is_selfsig,
1214
        int *is_expkey, int *is_revkey,
1215
              PKT_public_key **r_pk, kbnode_t *r_keyblock)
1216
17.6k
{
1217
17.6k
  PKT_signature *sig;
1218
17.6k
  gcry_md_hd_t md = NULL;
1219
17.6k
  gcry_md_hd_t md2 = NULL;
1220
17.6k
  gcry_md_hd_t md_good = NULL;
1221
17.6k
  int algo, rc;
1222
1223
17.6k
  if (r_pk)
1224
17.6k
    *r_pk = NULL;
1225
17.6k
  if (r_keyblock)
1226
17.6k
    *r_keyblock = NULL;
1227
1228
17.6k
  log_assert (node->pkt->pkttype == PKT_SIGNATURE);
1229
17.6k
  if (is_selfsig)
1230
0
    *is_selfsig = 0;
1231
17.6k
  sig = node->pkt->pkt.signature;
1232
1233
17.6k
  algo = sig->digest_algo;
1234
17.6k
  rc = openpgp_md_test_algo (algo);
1235
17.6k
  if (rc)
1236
16.6k
    return rc;
1237
1238
1.00k
  if (sig->sig_class == 0x00)
1239
474
    {
1240
474
      if (c->mfx.md)
1241
474
        {
1242
474
          if (gcry_md_copy (&md, c->mfx.md ))
1243
0
            BUG ();
1244
474
        }
1245
0
      else /* detached signature */
1246
0
        {
1247
          /* check_signature() will enable the md. */
1248
0
          if (gcry_md_open (&md, 0, 0 ))
1249
0
            BUG ();
1250
0
        }
1251
474
    }
1252
531
  else if (sig->sig_class == 0x01)
1253
0
    {
1254
      /* How do we know that we have to hash the (already hashed) text
1255
         in canonical mode ??? (calculating both modes???) */
1256
0
      if (c->mfx.md)
1257
0
        {
1258
0
          if (gcry_md_copy (&md, c->mfx.md ))
1259
0
            BUG ();
1260
0
          if (c->mfx.md2 && gcry_md_copy (&md2, c->mfx.md2))
1261
0
            BUG ();
1262
0
  }
1263
0
      else /* detached signature */
1264
0
        {
1265
0
          log_debug ("Do we really need this here?");
1266
          /* check_signature() will enable the md*/
1267
0
          if (gcry_md_open (&md, 0, 0 ))
1268
0
            BUG ();
1269
0
          if (gcry_md_open (&md2, 0, 0 ))
1270
0
            BUG ();
1271
0
  }
1272
0
    }
1273
531
  else if ((sig->sig_class&~3) == 0x10
1274
530
           ||   sig->sig_class == 0x18
1275
530
           ||   sig->sig_class == 0x1f
1276
505
     ||   sig->sig_class == 0x20
1277
364
     ||   sig->sig_class == 0x28
1278
364
           ||   sig->sig_class == 0x30)
1279
191
    {
1280
191
      if (c->list->pkt->pkttype == PKT_PUBLIC_KEY
1281
191
          || c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1282
0
        {
1283
0
          return check_key_signature (c->ctrl, c->list, node, is_selfsig);
1284
0
  }
1285
191
      else if (sig->sig_class == 0x20)
1286
141
        {
1287
141
          log_error (_("standalone revocation - "
1288
141
                       "use \"gpg --import\" to apply\n"));
1289
141
          return GPG_ERR_NOT_PROCESSED;
1290
141
  }
1291
50
      else
1292
50
        {
1293
50
          log_error ("invalid root packet for sigclass %02x\n", sig->sig_class);
1294
50
          return GPG_ERR_SIG_CLASS;
1295
50
  }
1296
191
    }
1297
340
  else
1298
340
    return GPG_ERR_SIG_CLASS;
1299
1300
  /* We only get here if we are checking the signature of a binary
1301
     (0x00) or text document (0x01).  */
1302
474
  rc = check_signature (c->ctrl, sig, md, extrahash, extrahashlen,
1303
474
                        forced_pk, NULL, is_expkey, is_revkey,
1304
474
                        r_pk, r_keyblock);
1305
474
  if (! rc)
1306
0
    md_good = md;
1307
474
  else if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE && md2)
1308
0
    {
1309
0
      PKT_public_key *pk2;
1310
1311
0
      if (r_keyblock)
1312
0
        release_kbnode (*r_keyblock);
1313
0
      rc = check_signature (c->ctrl, sig, md2, extrahash, extrahashlen,
1314
0
                            forced_pk, NULL, is_expkey, is_revkey,
1315
0
                            r_pk? &pk2 : NULL, r_keyblock);
1316
0
      if (!rc)
1317
0
        {
1318
0
          md_good = md2;
1319
0
          if (r_pk)
1320
0
            {
1321
0
              free_public_key (*r_pk);
1322
0
              *r_pk = pk2;
1323
0
            }
1324
0
        }
1325
0
    }
1326
1327
474
  if (md_good)
1328
0
    {
1329
0
      unsigned char *buffer = gcry_md_read (md_good, sig->digest_algo);
1330
0
      sig->digest_len = gcry_md_get_algo_dlen (map_md_openpgp_to_gcry (algo));
1331
0
      memcpy (sig->digest, buffer, sig->digest_len);
1332
0
    }
1333
1334
474
  gcry_md_close (md);
1335
474
  gcry_md_close (md2);
1336
1337
474
  return rc;
1338
1.00k
}
1339
1340
1341
static void
1342
print_userid (PACKET *pkt)
1343
18.8k
{
1344
18.8k
  if (!pkt)
1345
0
    BUG();
1346
1347
18.8k
  if (pkt->pkttype != PKT_USER_ID)
1348
0
    {
1349
0
      es_printf ("ERROR: unexpected packet type %d", pkt->pkttype );
1350
0
      return;
1351
0
    }
1352
18.8k
  if (opt.with_colons)
1353
0
    {
1354
0
      if (pkt->pkt.user_id->attrib_data)
1355
0
        es_printf("%u %lu",
1356
0
                  pkt->pkt.user_id->numattribs,
1357
0
                  pkt->pkt.user_id->attrib_len);
1358
0
      else
1359
0
        es_write_sanitized (es_stdout, pkt->pkt.user_id->name,
1360
0
                            pkt->pkt.user_id->len, ":", NULL);
1361
0
    }
1362
18.8k
  else
1363
18.8k
    print_utf8_buffer (es_stdout, pkt->pkt.user_id->name,
1364
18.8k
                       pkt->pkt.user_id->len );
1365
18.8k
}
1366
1367
1368
/*
1369
 * List the keyblock in a user friendly way
1370
 */
1371
static void
1372
list_node (CTX c, kbnode_t node)
1373
45.3k
{
1374
45.3k
  if (!node)
1375
0
    ;
1376
45.3k
  else if (node->pkt->pkttype == PKT_PUBLIC_KEY
1377
21.9k
           || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1378
28.3k
    {
1379
28.3k
      PKT_public_key *pk = node->pkt->pkt.public_key;
1380
1381
28.3k
      if (opt.with_colons)
1382
0
        {
1383
0
          u32 keyid[2];
1384
1385
0
          keyid_from_pk( pk, keyid );
1386
0
          if (pk->flags.primary)
1387
0
            c->trustletter = (opt.fast_list_mode
1388
0
                              ? 0
1389
0
                              : get_validity_info
1390
0
                                  (c->ctrl,
1391
0
                                   node->pkt->pkttype == PKT_PUBLIC_KEY
1392
0
                                   ? node : NULL,
1393
0
                                   pk, NULL));
1394
0
          es_printf ("%s:", pk->flags.primary? "pub":"sub" );
1395
0
          if (c->trustletter)
1396
0
            es_putc (c->trustletter, es_stdout);
1397
0
          es_printf (":%u:%d:%08lX%08lX:%s:%s::",
1398
0
                     nbits_from_pk( pk ),
1399
0
                     pk->pubkey_algo,
1400
0
                     (ulong)keyid[0],(ulong)keyid[1],
1401
0
                     colon_datestr_from_pk( pk ),
1402
0
                     colon_strtime (pk->expiredate) );
1403
0
          if (pk->flags.primary && !opt.fast_list_mode)
1404
0
            es_putc (get_ownertrust_info (c->ctrl, pk, 1), es_stdout);
1405
0
          es_putc (':', es_stdout);
1406
0
          es_putc ('\n', es_stdout);
1407
0
        }
1408
28.3k
      else
1409
28.3k
        {
1410
28.3k
          print_key_line (c->ctrl, es_stdout, pk, 0);
1411
28.3k
        }
1412
1413
28.3k
      if (opt.keyid_format == KF_NONE && !opt.with_colons)
1414
0
        ; /* Already printed.  */
1415
28.3k
      else if ((pk->flags.primary && opt.fingerprint) || opt.fingerprint > 1)
1416
0
        print_fingerprint (c->ctrl, NULL, pk, 0);
1417
1418
28.3k
      if (pk->flags.primary)
1419
23.3k
        {
1420
23.3k
          int kl = opt.keyid_format == KF_NONE? 0 : keystrlen ();
1421
1422
          /* Now list all userids with their signatures. */
1423
63.5k
          for (node = node->next; node; node = node->next)
1424
40.1k
            {
1425
40.1k
              if (node->pkt->pkttype == PKT_SIGNATURE)
1426
16.0k
                {
1427
16.0k
                  list_node (c,  node );
1428
16.0k
                }
1429
24.1k
              else if (node->pkt->pkttype == PKT_USER_ID)
1430
18.8k
                {
1431
18.8k
                  if (opt.with_colons)
1432
18.8k
                    es_printf ("%s:::::::::",
1433
0
                               node->pkt->pkt.user_id->attrib_data?"uat":"uid");
1434
18.8k
                  else
1435
18.8k
                    es_printf ("uid%*s",
1436
18.8k
                               kl + (opt.legacy_list_mode? 9:11),
1437
18.8k
                               "" );
1438
18.8k
                  print_userid (node->pkt);
1439
18.8k
                  if (opt.with_colons)
1440
18.8k
                    es_putc (':', es_stdout);
1441
18.8k
                  es_putc ('\n', es_stdout);
1442
18.8k
    }
1443
5.33k
              else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1444
5.02k
                {
1445
5.02k
                  list_node(c,  node );
1446
5.02k
                }
1447
40.1k
            }
1448
23.3k
        }
1449
28.3k
    }
1450
16.9k
  else if (node->pkt->pkttype == PKT_SECRET_KEY
1451
16.0k
           || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1452
918
    {
1453
1454
918
      log_debug ("FIXME: No way to print secret key packets here\n");
1455
      /* fixme: We may use a function to turn a secret key packet into
1456
         a public key one and use that here.  */
1457
918
    }
1458
16.0k
  else if (node->pkt->pkttype == PKT_SIGNATURE)
1459
16.0k
    {
1460
16.0k
      PKT_signature *sig = node->pkt->pkt.signature;
1461
16.0k
      int is_selfsig = 0;
1462
16.0k
      int rc2 = 0;
1463
16.0k
      size_t n;
1464
16.0k
      char *p;
1465
16.0k
      int sigrc = ' ';
1466
1467
16.0k
      if (!opt.verbose)
1468
16.0k
        return;
1469
1470
0
      if (sig->sig_class == 0x20 || sig->sig_class == 0x30)
1471
0
        es_fputs ("rev", es_stdout);
1472
0
      else
1473
0
        es_fputs ("sig", es_stdout);
1474
0
      if (opt.check_sigs)
1475
0
        {
1476
0
          fflush (stdout);
1477
0
          rc2 = do_check_sig (c, node, NULL, 0, NULL,
1478
0
                              &is_selfsig, NULL, NULL, NULL, NULL);
1479
0
          switch (gpg_err_code (rc2))
1480
0
            {
1481
0
            case 0:             sigrc = '!'; break;
1482
0
            case GPG_ERR_BAD_SIGNATURE:   sigrc = '-'; break;
1483
0
            case GPG_ERR_NO_PUBKEY:
1484
0
            case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break;
1485
0
            default:              sigrc = '%'; break;
1486
0
      }
1487
0
  }
1488
0
      else /* Check whether this is a self signature.  */
1489
0
        {
1490
0
          u32 keyid[2];
1491
1492
0
          if (c->list->pkt->pkttype == PKT_PUBLIC_KEY
1493
0
              || c->list->pkt->pkttype == PKT_SECRET_KEY )
1494
0
            {
1495
0
              keyid_from_pk (c->list->pkt->pkt.public_key, keyid);
1496
1497
0
              if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1])
1498
0
                is_selfsig = 1;
1499
0
            }
1500
0
  }
1501
1502
0
      if (opt.with_colons)
1503
0
        {
1504
0
          es_putc (':', es_stdout);
1505
0
          if (sigrc != ' ')
1506
0
            es_putc (sigrc, es_stdout);
1507
0
          es_printf ("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo,
1508
0
                     (ulong)sig->keyid[0], (ulong)sig->keyid[1],
1509
0
                     colon_datestr_from_sig (sig),
1510
0
                     colon_expirestr_from_sig (sig));
1511
1512
0
          if (sig->trust_depth || sig->trust_value)
1513
0
            es_printf ("%d %d",sig->trust_depth,sig->trust_value);
1514
0
          es_putc (':', es_stdout);
1515
1516
0
          if (sig->trust_regexp)
1517
0
            es_write_sanitized (es_stdout, sig->trust_regexp,
1518
0
                                strlen (sig->trust_regexp), ":", NULL);
1519
0
          es_putc (':', es_stdout);
1520
0
  }
1521
0
      else
1522
0
        es_printf ("%c       %s %s   ",
1523
0
                   sigrc, keystr (sig->keyid), datestr_from_sig(sig));
1524
0
      if (sigrc == '%')
1525
0
        es_printf ("[%s] ", gpg_strerror (rc2) );
1526
0
      else if (sigrc == '?')
1527
0
        ;
1528
0
      else if (is_selfsig)
1529
0
        {
1530
0
          if (opt.with_colons)
1531
0
            es_putc (':', es_stdout);
1532
0
          es_fputs (sig->sig_class == 0x18? "[keybind]":"[selfsig]", es_stdout);
1533
0
          if (opt.with_colons)
1534
0
            es_putc (':', es_stdout);
1535
0
  }
1536
0
      else if (!opt.fast_list_mode)
1537
0
        {
1538
0
          p = get_user_id (c->ctrl, sig->keyid, &n, NULL);
1539
0
          es_write_sanitized (es_stdout, p, n,
1540
0
                              opt.with_colons?":":NULL, NULL );
1541
0
          xfree (p);
1542
0
  }
1543
0
      if (opt.with_colons)
1544
0
        es_printf (":%02x%c:", sig->sig_class, sig->flags.exportable?'x':'l');
1545
0
      es_putc ('\n', es_stdout);
1546
0
    }
1547
0
  else
1548
16.0k
    log_error ("invalid node with packet of type %d\n", node->pkt->pkttype);
1549
45.3k
}
1550
1551
1552
int
1553
proc_packets (ctrl_t ctrl, void *anchor, iobuf_t a )
1554
57.6k
{
1555
57.6k
  int rc;
1556
57.6k
  CTX c = xmalloc_clear (sizeof *c);
1557
1558
57.6k
  c->ctrl = ctrl;
1559
57.6k
  c->anchor = anchor;
1560
57.6k
  rc = do_proc_packets (c, a, 0);
1561
57.6k
  xfree (c);
1562
1563
57.6k
  return rc;
1564
57.6k
}
1565
1566
1567
int
1568
proc_signature_packets (ctrl_t ctrl, void *anchor, iobuf_t a,
1569
      strlist_t signedfiles, const char *sigfilename )
1570
0
{
1571
0
  CTX c = xmalloc_clear (sizeof *c);
1572
0
  int rc;
1573
1574
0
  c->ctrl = ctrl;
1575
0
  c->anchor = anchor;
1576
0
  c->sigs_only = 1;
1577
1578
0
  c->signed_data.data_fd = GNUPG_INVALID_FD;
1579
0
  c->signed_data.data_names = signedfiles;
1580
0
  c->signed_data.used = !!signedfiles;
1581
1582
0
  c->sigfilename = sigfilename;
1583
0
  rc = do_proc_packets (c, a, 0);
1584
1585
  /* If we have not encountered any signature we print an error
1586
     messages, send a NODATA status back and return an error code.
1587
     Using log_error is required because verify_files does not check
1588
     error codes for each file but we want to terminate the process
1589
     with an error. */
1590
0
  if (!rc && !c->any.sig_seen)
1591
0
    {
1592
0
      write_status_text (STATUS_NODATA, "4");
1593
0
      log_error (_("no signature found\n"));
1594
0
      rc = GPG_ERR_NO_DATA;
1595
0
    }
1596
1597
  /* Propagate the signature seen flag upward. Do this only on success
1598
     so that we won't issue the nodata status several times.  */
1599
0
  if (!rc && c->anchor && c->any.sig_seen)
1600
0
    c->anchor->any.sig_seen = 1;
1601
1602
0
  xfree (c);
1603
0
  return rc;
1604
0
}
1605
1606
1607
int
1608
proc_signature_packets_by_fd (ctrl_t ctrl, void *anchor, iobuf_t a,
1609
                              gnupg_fd_t signed_data_fd)
1610
0
{
1611
0
  int rc;
1612
0
  CTX c;
1613
1614
0
  c = xtrycalloc (1, sizeof *c);
1615
0
  if (!c)
1616
0
    return gpg_error_from_syserror ();
1617
1618
0
  c->ctrl = ctrl;
1619
0
  c->anchor = anchor;
1620
0
  c->sigs_only = 1;
1621
1622
0
  c->signed_data.data_fd = signed_data_fd;
1623
0
  c->signed_data.data_names = NULL;
1624
0
  c->signed_data.used = (signed_data_fd != GNUPG_INVALID_FD);
1625
1626
0
  rc = do_proc_packets (c, a, 0);
1627
1628
  /* If we have not encountered any signature we print an error
1629
     messages, send a NODATA status back and return an error code.
1630
     Using log_error is required because verify_files does not check
1631
     error codes for each file but we want to terminate the process
1632
     with an error. */
1633
0
  if (!rc && !c->any.sig_seen)
1634
0
    {
1635
0
      write_status_text (STATUS_NODATA, "4");
1636
0
      log_error (_("no signature found\n"));
1637
0
      rc = gpg_error (GPG_ERR_NO_DATA);
1638
0
    }
1639
1640
  /* Propagate the signature seen flag upward. Do this only on success
1641
     so that we won't issue the nodata status several times. */
1642
0
  if (!rc && c->anchor && c->any.sig_seen)
1643
0
    c->anchor->any.sig_seen = 1;
1644
1645
0
  xfree ( c );
1646
0
  return rc;
1647
0
}
1648
1649
1650
/* Handle encryption packets.  If called recursively the caller's CTX
1651
 * should be given for ANCHOR.  If R_DEK and R_LIST are not NULL the
1652
 * DEK (or NULL) is returned there and the list at R_LIST; the caller
1653
 * needs to release them; even if the function returns an error. */
1654
gpg_error_t
1655
proc_encryption_packets (ctrl_t ctrl, void *anchor, iobuf_t a,
1656
                         DEK **r_dek, struct seskey_enc_list **r_list)
1657
0
{
1658
0
  CTX c = xmalloc_clear (sizeof *c);
1659
0
  int rc;
1660
1661
0
  c->ctrl = ctrl;
1662
0
  c->anchor = anchor;
1663
0
  c->encrypt_only = 1;
1664
0
  if (r_dek && r_list)
1665
0
    {
1666
0
      rc = do_proc_packets (c, a, 1);
1667
0
      *r_dek = c->dek;
1668
0
      c->dek = NULL;
1669
0
      *r_list = c->sesenc_list;
1670
0
      c->sesenc_list = NULL;
1671
0
    }
1672
0
  else
1673
0
    rc = do_proc_packets (c, a, 0);
1674
0
  xfree (c);
1675
0
  return rc;
1676
0
}
1677
1678
1679
static int
1680
check_nesting (CTX c)
1681
57.6k
{
1682
57.6k
  int level;
1683
1684
626k
  for (level=0; c; c = c->anchor)
1685
569k
    level++;
1686
1687
57.6k
  if (level > MAX_NESTING_DEPTH)
1688
6
    {
1689
6
      log_error ("input data with too deeply nested packets\n");
1690
6
      write_status_text (STATUS_UNEXPECTED, "1");
1691
6
      return GPG_ERR_BAD_DATA;
1692
6
    }
1693
1694
57.6k
  return 0;
1695
57.6k
}
1696
1697
1698
/* Main processing loop.  If KEEP_DEK_AND_LIST is set the DEK and
1699
 * SESENC_LIST of the context C are not released at the end of the
1700
 * function.  The caller is then required to do this.  */
1701
static int
1702
do_proc_packets (CTX c, iobuf_t a, int keep_dek_and_list)
1703
57.6k
{
1704
57.6k
  PACKET *pkt;
1705
57.6k
  struct parse_packet_ctx_s parsectx;
1706
57.6k
  int rc = 0;
1707
57.6k
  int any_data = 0;
1708
57.6k
  int newpkt;
1709
1710
57.6k
  rc = check_nesting (c);
1711
57.6k
  if (rc)
1712
6
    return rc;
1713
1714
57.6k
  pkt = xmalloc( sizeof *pkt );
1715
57.6k
  c->iobuf = a;
1716
57.6k
  init_packet(pkt);
1717
57.6k
  init_parse_packet (&parsectx, a);
1718
326k
  while ((rc=parse_packet (&parsectx, pkt)) != -1)
1719
319k
    {
1720
319k
      any_data = 1;
1721
319k
      if (rc)
1722
56.9k
        {
1723
56.9k
          if (c->ctrl->modify_recipients && gpg_err_code (rc) == GPG_ERR_TRUE)
1724
0
            {
1725
              /* Save the last read CTB (which was the last byte
1726
               * actually read from the input) and get out of the
1727
               * loop.  */
1728
0
              c->ctrl->last_read_ctb = parsectx.last_ctb;
1729
              /* We need to call the first part of the encrypted data
1730
               * handler to get the DEK.  */
1731
0
              proc_encrypted (c, NULL);
1732
0
              rc = -1;
1733
0
              break;
1734
0
            }
1735
56.9k
          free_packet (pkt, &parsectx);
1736
          /* Stop processing when an invalid packet has been encountered
1737
           * but don't do so when we are doing a --list-packets.  */
1738
56.9k
          if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
1739
49.1k
              && opt.list_packets == 0)
1740
49.1k
            break;
1741
7.77k
          continue;
1742
56.9k
  }
1743
262k
      newpkt = -1;
1744
262k
      if (opt.list_packets)
1745
0
        {
1746
0
          switch (pkt->pkttype)
1747
0
            {
1748
0
            case PKT_PUBKEY_ENC:    proc_pubkey_enc (c, pkt); break;
1749
0
            case PKT_SYMKEY_ENC:    proc_symkey_enc (c, pkt); break;
1750
0
            case PKT_ENCRYPTED:
1751
0
            case PKT_ENCRYPTED_MDC:
1752
0
            case PKT_ENCRYPTED_AEAD:proc_encrypted (c, pkt); break;
1753
0
            case PKT_COMPRESSED:    rc = proc_compressed (c, pkt); break;
1754
0
            default: newpkt = 0; break;
1755
0
      }
1756
0
  }
1757
262k
      else if (c->sigs_only)
1758
0
        {
1759
0
          switch (pkt->pkttype)
1760
0
            {
1761
0
            case PKT_PUBLIC_KEY:
1762
0
            case PKT_SECRET_KEY:
1763
0
            case PKT_USER_ID:
1764
0
            case PKT_SYMKEY_ENC:
1765
0
            case PKT_PUBKEY_ENC:
1766
0
            case PKT_ENCRYPTED:
1767
0
            case PKT_ENCRYPTED_MDC:
1768
0
            case PKT_ENCRYPTED_AEAD:
1769
0
              write_status_text( STATUS_UNEXPECTED, "0" );
1770
0
              rc = GPG_ERR_UNEXPECTED;
1771
0
              goto leave;
1772
1773
0
            case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1774
0
            case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1775
0
            case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1776
0
            case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1777
0
            case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break;
1778
0
            default: newpkt = 0; break;
1779
0
      }
1780
0
  }
1781
262k
      else if (c->encrypt_only)
1782
0
        {
1783
0
          switch (pkt->pkttype)
1784
0
            {
1785
0
            case PKT_PUBLIC_KEY:
1786
0
            case PKT_SECRET_KEY:
1787
0
            case PKT_USER_ID:
1788
0
              write_status_text (STATUS_UNEXPECTED, "0");
1789
0
              rc = GPG_ERR_UNEXPECTED;
1790
0
              goto leave;
1791
1792
0
            case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1793
1794
0
            case PKT_SYMKEY_ENC:
1795
0
            case PKT_PUBKEY_ENC:
1796
              /* In --add-recipients mode set the stop flag as soon as
1797
               * we see the first of these packets.  */
1798
0
              if (c->ctrl->modify_recipients)
1799
0
                parsectx.only_fookey_enc = 1;
1800
0
              if (pkt->pkttype == PKT_SYMKEY_ENC)
1801
0
                proc_symkey_enc (c, pkt);
1802
0
              else
1803
0
                proc_pubkey_enc (c, pkt);
1804
0
              break;
1805
1806
0
            case PKT_ENCRYPTED:
1807
0
            case PKT_ENCRYPTED_MDC:
1808
0
            case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break;
1809
0
            case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1810
0
            case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1811
0
            case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1812
0
            case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break;
1813
0
            default: newpkt = 0; break;
1814
0
      }
1815
0
  }
1816
262k
      else
1817
262k
        {
1818
262k
          switch (pkt->pkttype)
1819
262k
            {
1820
23.3k
            case PKT_PUBLIC_KEY:
1821
24.2k
            case PKT_SECRET_KEY:
1822
24.2k
              release_list (c);
1823
24.2k
              c->list = new_kbnode (pkt);
1824
24.2k
              newpkt = 1;
1825
24.2k
              break;
1826
5.29k
            case PKT_PUBLIC_SUBKEY:
1827
9.31k
            case PKT_SECRET_SUBKEY:
1828
9.31k
              newpkt = add_subkey (c, pkt);
1829
9.31k
              break;
1830
35.4k
            case PKT_USER_ID:     newpkt = add_user_id (c, pkt); break;
1831
52.4k
            case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
1832
10.7k
            case PKT_PUBKEY_ENC:  proc_pubkey_enc (c, pkt); break;
1833
21.6k
            case PKT_SYMKEY_ENC:  proc_symkey_enc (c, pkt); break;
1834
9.20k
            case PKT_ENCRYPTED:
1835
10.5k
            case PKT_ENCRYPTED_MDC:
1836
33.6k
            case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break;
1837
13.6k
            case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
1838
49.8k
            case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
1839
1.87k
            case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
1840
3.37k
            case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
1841
0
            case PKT_RING_TRUST:  newpkt = add_ring_trust (c, pkt); break;
1842
5.95k
            default: newpkt = 0; break;
1843
262k
      }
1844
262k
  }
1845
1846
262k
      if (rc)
1847
1.00k
        goto leave;
1848
1849
      /* This is a very ugly construct and frankly, I don't remember why
1850
       * I used it.  Adding the MDC check here is a hack.
1851
       * The right solution is to initiate another context for encrypted
1852
       * packet and not to reuse the current one ...  It works right
1853
       * when there is a compression packet between which adds just
1854
       * an extra layer.
1855
       *
1856
       * Note that we should not reset the any.data due to another
1857
       * packets.  Just set it once on seeing a plaintext.
1858
       *
1859
       * Hmmm: Rewrite this whole module here??
1860
       */
1861
261k
      if (pkt->pkttype != PKT_SIGNATURE && pkt->pkttype != PKT_MDC)
1862
208k
        c->any.data |= (pkt->pkttype == PKT_PLAINTEXT);
1863
1864
261k
      if (newpkt == -1)
1865
128k
        ;
1866
132k
      else if (newpkt)
1867
110k
        {
1868
110k
          pkt = xmalloc (sizeof *pkt);
1869
110k
          init_packet (pkt);
1870
110k
  }
1871
21.7k
      else
1872
21.7k
        free_packet (pkt, &parsectx);
1873
261k
    }
1874
1875
56.6k
  if (rc == GPG_ERR_INV_PACKET)
1876
49.1k
    write_status_text (STATUS_NODATA, "3");
1877
1878
56.6k
  if (any_data)
1879
55.7k
    rc = 0;
1880
925
  else if (rc == -1)
1881
925
    write_status_text (STATUS_NODATA, "2");
1882
1883
1884
57.6k
 leave:
1885
57.6k
  if (!keep_dek_and_list)
1886
57.6k
    release_list (c);
1887
57.6k
  free_packet (pkt, &parsectx);
1888
57.6k
  deinit_parse_packet (&parsectx);
1889
57.6k
  xfree (pkt);
1890
57.6k
  free_md_filter_context (&c->mfx);
1891
57.6k
  return rc;
1892
56.6k
}
1893
1894
1895
/* Return true if the AKL has the WKD method specified.  */
1896
static int
1897
akl_has_wkd_method (void)
1898
0
{
1899
0
  struct akl *akl;
1900
1901
0
  for (akl = opt.auto_key_locate; akl; akl = akl->next)
1902
0
    if (akl->type == AKL_WKD)
1903
0
      return 1;
1904
0
  return 0;
1905
0
}
1906
1907
1908
/* Return the ISSUER fingerprint buffer and its length at R_LEN.
1909
 * Returns NULL if not available.  The returned buffer is valid as
1910
 * long as SIG is not modified.  */
1911
const byte *
1912
issuer_fpr_raw (PKT_signature *sig, size_t *r_len)
1913
18.0k
{
1914
18.0k
  const byte *p;
1915
18.0k
  size_t n;
1916
1917
18.0k
  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_ISSUER_FPR, &n);
1918
18.0k
  if (p && ((n == 21 && p[0] == 4) || (n == 33 && p[0] == 5)))
1919
154
    {
1920
154
      *r_len = n - 1;
1921
154
      return p+1;
1922
154
    }
1923
17.9k
  *r_len = 0;
1924
17.9k
  return NULL;
1925
18.0k
}
1926
1927
1928
/* Return the ISSUER fingerprint string in human readable format if
1929
 * available.  Caller must release the string.  */
1930
/* FIXME: Move to another file.  */
1931
char *
1932
issuer_fpr_string (PKT_signature *sig)
1933
17.6k
{
1934
17.6k
  const byte *p;
1935
17.6k
  size_t n;
1936
1937
17.6k
  p = issuer_fpr_raw (sig, &n);
1938
17.6k
  return p? bin2hex (p, n, NULL) : NULL;
1939
17.6k
}
1940
1941
static void
1942
print_good_bad_signature (int statno, const char *keyid_str, kbnode_t un,
1943
                          PKT_signature *sig, int rc)
1944
0
{
1945
0
  char *p;
1946
1947
0
  write_status_text_and_buffer (statno, keyid_str,
1948
0
                                un? un->pkt->pkt.user_id->name:"[?]",
1949
0
                                un? un->pkt->pkt.user_id->len:3,
1950
0
                                -1);
1951
0
  if (statno == STATUS_BADSIG)
1952
0
    {
1953
0
      gnupg_isotime_t timestr;
1954
1955
0
      epoch2isotime (timestr, sig->timestamp);
1956
0
      write_status_text_and_buffer (STATUS_SIGINFO, timestr,
1957
0
                                    NULL, 0, -1);
1958
0
    }
1959
1960
0
  if (un)
1961
0
    p = utf8_to_native (un->pkt->pkt.user_id->name,
1962
0
                        un->pkt->pkt.user_id->len, 0);
1963
0
  else
1964
0
    p = xstrdup ("[?]");
1965
1966
0
  if (rc)
1967
0
    log_info (_("BAD signature from \"%s\""), p);
1968
0
  else if (sig->flags.expired)
1969
0
    log_info (_("Expired signature from \"%s\""), p);
1970
0
  else
1971
0
    log_info (_("Good signature from \"%s\""), p);
1972
1973
0
  xfree (p);
1974
0
}
1975
1976
1977
static int
1978
check_sig_and_print (CTX c, kbnode_t node)
1979
18.7k
{
1980
18.7k
  PKT_signature *sig = node->pkt->pkt.signature;
1981
18.7k
  const char *astr;
1982
18.7k
  gpg_error_t rc;
1983
18.7k
  int is_expkey = 0;
1984
18.7k
  int is_revkey = 0;
1985
18.7k
  char *issuer_fpr = NULL;
1986
18.7k
  PKT_public_key *pk = NULL;  /* The public key for the signature or NULL. */
1987
18.7k
  const void *extrahash = NULL;
1988
18.7k
  size_t extrahashlen = 0;
1989
18.7k
  kbnode_t keyblock = NULL;
1990
18.7k
  char pkstrbuf[PUBKEY_STRING_SIZE] = { 0 };
1991
1992
1993
18.7k
  if (opt.skip_verify)
1994
0
    {
1995
0
      log_info(_("signature verification suppressed\n"));
1996
0
      return 0;
1997
0
    }
1998
1999
  /* Check that the message composition is valid.
2000
   *
2001
   * Per RFC-2440bis (-15) allowed:
2002
   *
2003
   * S{1,n}           -- detached signature.
2004
   * S{1,n} P         -- old style PGP2 signature
2005
   * O{1,n} P S{1,n}  -- standard OpenPGP signature.
2006
   * C P S{1,n}       -- cleartext signature.
2007
   *
2008
   *
2009
   *      O = One-Pass Signature packet.
2010
   *      S = Signature packet.
2011
   *      P = OpenPGP Message packet (Encrypted | Compressed | Literal)
2012
   *             (Note that the current rfc2440bis draft also allows
2013
   *              for a signed message but that does not work as it
2014
   *              introduces ambiguities.)
2015
   *          We keep track of these packages using the marker packet
2016
   *          CTRLPKT_PLAINTEXT_MARK.
2017
   *      C = Marker packet for cleartext signatures.
2018
   *
2019
   * We reject all other messages.
2020
   *
2021
   * Actually we are calling this too often, i.e. for verification of
2022
   * each message but better have some duplicate work than to silently
2023
   * introduce a bug here.
2024
   */
2025
18.7k
  {
2026
18.7k
    kbnode_t n;
2027
18.7k
    int n_onepass, n_sig;
2028
2029
/*     log_debug ("checking signature packet composition\n"); */
2030
/*     dump_kbnode (c->list); */
2031
2032
18.7k
    n = c->list;
2033
18.7k
    log_assert (n);
2034
18.7k
    if ( n->pkt->pkttype == PKT_SIGNATURE )
2035
17.9k
      {
2036
        /* This is either "S{1,n}" case (detached signature) or
2037
           "S{1,n} P" (old style PGP2 signature). */
2038
420k
        for (n = n->next; n; n = n->next)
2039
403k
          if (n->pkt->pkttype != PKT_SIGNATURE)
2040
995
            break;
2041
17.9k
        if (!n)
2042
16.9k
          ; /* Okay, this is a detached signature.  */
2043
995
        else if (n->pkt->pkttype == PKT_GPG_CONTROL
2044
245
                 && (n->pkt->pkt.gpg_control->control
2045
245
                     == CTRLPKT_PLAINTEXT_MARK) )
2046
245
          {
2047
245
            if (n->next)
2048
101
              goto ambiguous;  /* We only allow one P packet. */
2049
144
            extrahash = n->pkt->pkt.gpg_control->data;
2050
144
            extrahashlen = n->pkt->pkt.gpg_control->datalen;
2051
144
          }
2052
750
        else
2053
750
          goto ambiguous;
2054
17.9k
      }
2055
739
    else if (n->pkt->pkttype == PKT_ONEPASS_SIG)
2056
688
      {
2057
        /* This is the "O{1,n} P S{1,n}" case (standard signature). */
2058
688
        for (n_onepass=1, n = n->next;
2059
1.31k
             n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next)
2060
626
          n_onepass++;
2061
688
        if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
2062
606
                    && (n->pkt->pkt.gpg_control->control
2063
606
                        == CTRLPKT_PLAINTEXT_MARK)))
2064
82
          goto ambiguous;
2065
606
        extrahash = n->pkt->pkt.gpg_control->data;
2066
606
        extrahashlen = n->pkt->pkt.gpg_control->datalen;
2067
2068
606
        for (n_sig=0, n = n->next;
2069
1.92k
             n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
2070
1.31k
          n_sig++;
2071
606
        if (!n_sig)
2072
0
          goto ambiguous;
2073
2074
  /* If we wanted to disallow multiple sig verification, we'd do
2075
   * something like this:
2076
         *
2077
   * if (n)
2078
         *   goto ambiguous;
2079
         *
2080
         * However, this can stay allowable as we can't get here.  */
2081
2082
606
        if (n_onepass != n_sig)
2083
129
          {
2084
129
            log_info ("number of one-pass packets does not match "
2085
129
                      "number of signature packets\n");
2086
129
            goto ambiguous;
2087
129
          }
2088
606
      }
2089
51
    else if (n->pkt->pkttype == PKT_GPG_CONTROL
2090
51
             && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
2091
38
      {
2092
        /* This is the "C P S{1,n}" case (clear text signature). */
2093
38
        n = n->next;
2094
38
        if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
2095
38
                    && (n->pkt->pkt.gpg_control->control
2096
38
                        == CTRLPKT_PLAINTEXT_MARK)))
2097
0
          goto ambiguous;
2098
38
        extrahash = n->pkt->pkt.gpg_control->data;
2099
38
        extrahashlen = n->pkt->pkt.gpg_control->datalen;
2100
38
        for (n_sig=0, n = n->next;
2101
44
             n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
2102
6
          n_sig++;
2103
38
        if (n || !n_sig)
2104
34
          goto ambiguous;
2105
38
      }
2106
13
    else
2107
13
      {
2108
1.10k
      ambiguous:
2109
1.10k
        log_error(_("can't handle this ambiguous signature data\n"));
2110
1.10k
        rc = 0;
2111
1.10k
        goto leave;
2112
13
      }
2113
18.7k
  } /* End checking signature packet composition.  */
2114
2115
17.6k
  if (sig->signers_uid)
2116
5.80k
    write_status_buffer (STATUS_NEWSIG,
2117
5.80k
                         sig->signers_uid, strlen (sig->signers_uid), 0);
2118
11.8k
  else
2119
11.8k
    write_status_text (STATUS_NEWSIG, NULL);
2120
2121
17.6k
  astr = openpgp_pk_algo_name ( sig->pubkey_algo );
2122
17.6k
  issuer_fpr = issuer_fpr_string (sig);
2123
2124
17.6k
  if (issuer_fpr)
2125
154
    {
2126
154
      log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
2127
154
      log_info (_("               using %s key %s\n"),
2128
154
                astr? astr: "?", issuer_fpr);
2129
2130
154
    }
2131
17.4k
  else if (!keystrlen () || keystrlen () > 8)
2132
17.4k
    {
2133
17.4k
      log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
2134
17.4k
      log_info (_("               using %s key %s\n"),
2135
17.4k
                astr? astr: "?", keystr(sig->keyid));
2136
17.4k
    }
2137
0
  else /* Legacy format.  */
2138
17.4k
    log_info (_("Signature made %s using %s key ID %s\n"),
2139
0
              asctimestamp(sig->timestamp), astr? astr: "?",
2140
0
              keystr(sig->keyid));
2141
2142
  /* In verbose mode print the signers UID.  */
2143
17.6k
  if (sig->signers_uid)
2144
17.6k
    log_info (_("               issuer \"%s\"\n"), sig->signers_uid);
2145
2146
17.6k
  rc = do_check_sig (c, node, extrahash, extrahashlen, NULL,
2147
17.6k
                     NULL, &is_expkey, &is_revkey, &pk, &keyblock);
2148
2149
  /* If the key is not found but the signature includes a key block we
2150
   * use that key block for verification and on success import it.  */
2151
17.6k
  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2152
474
      && sig->flags.key_block
2153
0
      && opt.flags.auto_key_import)
2154
0
    {
2155
0
      kbnode_t included_keyblock = NULL;
2156
0
      PKT_public_key *included_pk;
2157
0
      const byte *kblock;
2158
0
      size_t kblock_len;
2159
2160
0
      included_pk = xcalloc (1, sizeof *included_pk);
2161
0
      kblock = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_BLOCK, &kblock_len);
2162
0
      if (kblock && kblock_len > 1
2163
0
          && !get_pubkey_from_buffer (c->ctrl, included_pk,
2164
0
                                      kblock+1, kblock_len-1,
2165
0
                                      sig->keyid, &included_keyblock))
2166
0
        {
2167
          /* Note: This is the only place where we use the forced_pk
2168
           *       arg (ie. included_pk) with do_check_sig.  */
2169
0
          rc = do_check_sig (c, node, extrahash, extrahashlen, included_pk,
2170
0
                             NULL, &is_expkey, &is_revkey, &pk, NULL);
2171
0
          if (opt.verbose)
2172
0
            log_info ("checked signature using included key block: %s\n",
2173
0
                       gpg_strerror (rc));
2174
0
          if (!rc)
2175
0
            {
2176
              /* The keyblock has been verified, we now import it.  */
2177
0
              rc = import_included_key_block (c->ctrl, included_keyblock);
2178
0
            }
2179
2180
0
        }
2181
0
      free_public_key (included_pk);
2182
0
      release_kbnode (included_keyblock);
2183
2184
      /* To make sure that nothing strange happened we check the
2185
       * signature again now using our own key store. This also
2186
       * returns the keyblock which we use later on.  */
2187
0
      if (!rc)
2188
0
        {
2189
0
          release_kbnode (keyblock);
2190
0
          keyblock = NULL;
2191
0
          rc = do_check_sig (c, node, extrahash, extrahashlen, NULL,
2192
0
                             NULL, &is_expkey, &is_revkey, &pk, &keyblock);
2193
0
        }
2194
0
    }
2195
2196
  /* If the key isn't found, check for a preferred keyserver.  Note
2197
   * that this is only done if honor-keyserver-url has been set.  We
2198
   * test for this in the loop so that we can show info about the
2199
   * preferred keyservers.  */
2200
17.6k
  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2201
474
      && sig->flags.pref_ks)
2202
0
    {
2203
0
      const byte *p;
2204
0
      int seq = 0;
2205
0
      size_t n;
2206
0
      int any_pref_ks = 0;
2207
2208
0
      while ((p=enum_sig_subpkt (sig, 1, SIGSUBPKT_PREF_KS, &n, &seq, NULL)))
2209
0
        {
2210
          /* According to my favorite copy editor, in English grammar,
2211
             you say "at" if the key is located on a web page, but
2212
             "from" if it is located on a keyserver.  I'm not going to
2213
             even try to make two strings here :) */
2214
0
          log_info(_("Key available at: ") );
2215
0
          print_utf8_buffer (log_get_stream(), p, n);
2216
0
          log_printf ("\n");
2217
0
          any_pref_ks = 1;
2218
2219
0
          if ((opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
2220
0
              && (opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL))
2221
0
            {
2222
0
              struct keyserver_spec *spec;
2223
2224
0
              spec = parse_preferred_keyserver (sig);
2225
0
              if (spec)
2226
0
                {
2227
0
                  int res;
2228
2229
0
                  if (DBG_LOOKUP)
2230
0
                    log_debug ("trying auto-key-retrieve method %s\n",
2231
0
                               "Pref-KS");
2232
2233
0
                  free_public_key (pk);
2234
0
                  pk = NULL;
2235
0
                  glo_ctrl.in_auto_key_retrieve++;
2236
0
                  res = keyserver_import_keyid (c->ctrl, sig->keyid,spec,
2237
0
                                                KEYSERVER_IMPORT_FLAG_QUICK);
2238
0
                  glo_ctrl.in_auto_key_retrieve--;
2239
0
                  if (!res)
2240
0
                    {
2241
0
                      release_kbnode (keyblock);
2242
0
                      keyblock = NULL;
2243
0
                      rc = do_check_sig (c, node, extrahash, extrahashlen, NULL,
2244
0
                                         NULL, &is_expkey, &is_revkey, &pk,
2245
0
                                         &keyblock);
2246
0
                    }
2247
0
                  else if (DBG_LOOKUP)
2248
0
                    log_debug ("lookup via %s failed: %s\n", "Pref-KS",
2249
0
                               gpg_strerror (res));
2250
0
                  free_keyserver_spec (spec);
2251
2252
0
                  if (!rc)
2253
0
                    break;
2254
0
                }
2255
0
            }
2256
0
        }
2257
2258
0
      if (any_pref_ks
2259
0
          && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
2260
0
          && !(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL))
2261
0
        log_info (_("Note: Use '%s' to make use of this info\n"),
2262
0
                  "--keyserver-option honor-keyserver-url");
2263
0
    }
2264
2265
  /* If the above methods didn't work, our next try is to retrieve the
2266
   * key from the WKD.  This requires that WKD is in the AKL and the
2267
   * Signer's UID is in the signature.  */
2268
17.6k
  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2269
474
      && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
2270
0
      && !opt.flags.disable_signer_uid
2271
0
      && akl_has_wkd_method ()
2272
0
      && sig->signers_uid)
2273
0
    {
2274
0
      int res;
2275
2276
0
      if (DBG_LOOKUP)
2277
0
        log_debug ("trying auto-key-retrieve method %s\n", "WKD");
2278
0
      free_public_key (pk);
2279
0
      pk = NULL;
2280
0
      glo_ctrl.in_auto_key_retrieve++;
2281
0
      res = keyserver_import_wkd (c->ctrl, sig->signers_uid,
2282
0
                                  KEYSERVER_IMPORT_FLAG_QUICK, NULL, NULL);
2283
0
      glo_ctrl.in_auto_key_retrieve--;
2284
      /* Fixme: If the fingerprint is embedded in the signature,
2285
       * compare it to the fingerprint of the returned key.  */
2286
0
      if (!res)
2287
0
        {
2288
0
          release_kbnode (keyblock);
2289
0
          keyblock = NULL;
2290
0
          rc = do_check_sig (c, node, extrahash, extrahashlen, NULL,
2291
0
                             NULL, &is_expkey, &is_revkey, &pk, &keyblock);
2292
0
        }
2293
0
      else if (DBG_LOOKUP)
2294
0
        log_debug ("lookup via %s failed: %s\n", "WKD", gpg_strerror (res));
2295
0
    }
2296
2297
  /* If the above methods didn't work, our next try is to locate
2298
   * the key via its fingerprint from a keyserver.  This requires
2299
   * that the signers fingerprint is encoded in the signature.  */
2300
17.6k
  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
2301
474
      && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
2302
0
      && keyserver_any_configured (c->ctrl))
2303
0
    {
2304
0
      int res;
2305
0
      const byte *p;
2306
0
      size_t n;
2307
2308
0
      p = issuer_fpr_raw (sig, &n);
2309
0
      if (p)
2310
0
        {
2311
0
          if (DBG_LOOKUP)
2312
0
            log_debug ("trying auto-key-retrieve method %s\n", "KS");
2313
2314
          /* v4 or v5 packet with a SHA-1/256 fingerprint.  */
2315
0
          free_public_key (pk);
2316
0
          pk = NULL;
2317
0
          glo_ctrl.in_auto_key_retrieve++;
2318
0
          res = keyserver_import_fpr (c->ctrl, p, n, opt.keyserver,
2319
0
                                      KEYSERVER_IMPORT_FLAG_QUICK);
2320
0
          glo_ctrl.in_auto_key_retrieve--;
2321
0
          if (!res)
2322
0
            {
2323
0
              release_kbnode (keyblock);
2324
0
              keyblock = NULL;
2325
0
              rc = do_check_sig (c, node, extrahash, extrahashlen, NULL,
2326
0
                                 NULL, &is_expkey, &is_revkey, &pk,
2327
0
                                 &keyblock);
2328
0
            }
2329
0
          else if (DBG_LOOKUP)
2330
0
            log_debug ("lookup via %s failed: %s\n", "KS", gpg_strerror (res));
2331
0
        }
2332
0
    }
2333
2334
  /* Do something with the result of the signature checking.  */
2335
17.6k
  if (!rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
2336
0
    {
2337
      /* We have checked the signature and the result is either a good
2338
       * signature or a bad signature.  Further examination follows.  */
2339
0
      kbnode_t un;
2340
0
      int count = 0;
2341
0
      int keyblock_has_pk = 0;  /* For failsafe check.  */
2342
0
      int statno;
2343
0
      char keyid_str[50];
2344
0
      PKT_public_key *mainpk = NULL;
2345
2346
0
      if (rc)
2347
0
        statno = STATUS_BADSIG;
2348
0
      else if (sig->flags.expired)
2349
0
        statno = STATUS_EXPSIG;
2350
0
      else if (is_expkey)
2351
0
        statno = STATUS_EXPKEYSIG;
2352
0
      else if(is_revkey)
2353
0
        statno = STATUS_REVKEYSIG;
2354
0
      else
2355
0
        statno = STATUS_GOODSIG;
2356
2357
0
      snprintf (keyid_str, sizeof keyid_str, "%08lX%08lX [uncertain] ",
2358
0
                (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
2359
2360
      /* Find and print the primary user ID along with the
2361
         "Good|Expired|Bad signature" line.  */
2362
0
      for (un=keyblock; un; un = un->next)
2363
0
        {
2364
0
          int valid;
2365
2366
0
          if (!keyblock_has_pk
2367
0
              && (un->pkt->pkttype == PKT_PUBLIC_KEY
2368
0
                  || un->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2369
0
              && !cmp_public_keys (un->pkt->pkt.public_key, pk))
2370
0
            {
2371
0
              keyblock_has_pk = 1;
2372
0
            }
2373
0
          if (un->pkt->pkttype == PKT_PUBLIC_KEY)
2374
0
            {
2375
0
              mainpk = un->pkt->pkt.public_key;
2376
0
              continue;
2377
0
            }
2378
0
          if (un->pkt->pkttype != PKT_USER_ID)
2379
0
            continue;
2380
0
          if (!un->pkt->pkt.user_id->created)
2381
0
            continue;
2382
0
          if (un->pkt->pkt.user_id->flags.revoked)
2383
0
            continue;
2384
0
          if (un->pkt->pkt.user_id->flags.expired)
2385
0
            continue;
2386
0
          if (!un->pkt->pkt.user_id->flags.primary)
2387
0
            continue;
2388
          /* We want the textual primary user ID here */
2389
0
          if (un->pkt->pkt.user_id->attrib_data)
2390
0
            continue;
2391
2392
0
          log_assert (mainpk);
2393
2394
    /* Since this is just informational, don't actually ask the
2395
       user to update any trust information.  (Note: we register
2396
       the signature later.)  Because print_good_bad_signature
2397
       does not print a LF we need to compute the validity
2398
       before calling that function.  */
2399
0
          if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2400
0
            valid = get_validity (c->ctrl, keyblock, mainpk,
2401
0
                                  un->pkt->pkt.user_id, NULL, 0);
2402
0
          else
2403
0
            valid = 0; /* Not used.  */
2404
2405
0
          keyid_str[17] = 0; /* cut off the "[uncertain]" part */
2406
2407
0
          print_good_bad_signature (statno, keyid_str, un, sig, rc);
2408
2409
0
          if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2410
0
            log_printf (" [%s]\n",trust_value_to_string(valid));
2411
0
          else
2412
0
            log_printf ("\n");
2413
2414
0
          count++;
2415
          /* At this point we could in theory stop because the primary
2416
           * UID flag is never set for more than one User ID per
2417
           * keyblock.  However, we use this loop also for a failsafe
2418
           * check that the public key used to create the signature is
2419
           * contained in the keyring.*/
2420
0
  }
2421
2422
0
      if (!mainpk || !keyblock_has_pk)
2423
0
        {
2424
0
          log_error ("signature key lost from keyblock (%p,%p,%d)\n",
2425
0
                     keyblock, mainpk, keyblock_has_pk);
2426
0
          rc = gpg_error (GPG_ERR_INTERNAL);
2427
0
        }
2428
2429
      /* In case we did not found a valid textual userid above
2430
         we print the first user id packet or a "[?]" instead along
2431
         with the "Good|Expired|Bad signature" line.  */
2432
0
      if (!count)
2433
0
        {
2434
          /* Try for an invalid textual userid */
2435
0
          for (un=keyblock; un; un = un->next)
2436
0
            {
2437
0
              if (un->pkt->pkttype == PKT_USER_ID
2438
0
                  && !un->pkt->pkt.user_id->attrib_data)
2439
0
                break;
2440
0
            }
2441
2442
          /* Try for any userid at all */
2443
0
          if (!un)
2444
0
            {
2445
0
              for (un=keyblock; un; un = un->next)
2446
0
                {
2447
0
                  if (un->pkt->pkttype == PKT_USER_ID)
2448
0
                    break;
2449
0
    }
2450
0
      }
2451
2452
0
          if (opt.trust_model==TM_ALWAYS || !un)
2453
0
            keyid_str[17] = 0; /* cut off the "[uncertain]" part */
2454
2455
0
          print_good_bad_signature (statno, keyid_str, un, sig, rc);
2456
2457
0
          if (opt.trust_model != TM_ALWAYS && un)
2458
0
            log_printf (" %s",_("[uncertain]") );
2459
0
          log_printf ("\n");
2460
0
  }
2461
2462
      /* If we have a good signature and already printed
2463
       * the primary user ID, print all the other user IDs */
2464
0
      if (count
2465
0
          && !rc
2466
0
          && !(opt.verify_options & VERIFY_SHOW_PRIMARY_UID_ONLY))
2467
0
        {
2468
0
          char *p;
2469
0
          for( un=keyblock; un; un = un->next)
2470
0
            {
2471
0
              if (un->pkt->pkttype != PKT_USER_ID)
2472
0
                continue;
2473
0
              if ((un->pkt->pkt.user_id->flags.revoked
2474
0
                   || un->pkt->pkt.user_id->flags.expired)
2475
0
                  && !(opt.verify_options & VERIFY_SHOW_UNUSABLE_UIDS))
2476
0
                continue;
2477
              /* Skip textual primary user ids which we printed above. */
2478
0
              if (un->pkt->pkt.user_id->flags.primary
2479
0
                  && !un->pkt->pkt.user_id->attrib_data )
2480
0
                continue;
2481
2482
              /* If this user id has attribute data, print that.  */
2483
0
              if (un->pkt->pkt.user_id->attrib_data)
2484
0
                {
2485
0
                  dump_attribs (un->pkt->pkt.user_id, mainpk);
2486
2487
0
                  if (opt.verify_options&VERIFY_SHOW_PHOTOS)
2488
0
                    show_photos (c->ctrl,
2489
0
                                 un->pkt->pkt.user_id->attribs,
2490
0
                                 un->pkt->pkt.user_id->numattribs,
2491
0
                                 mainpk ,un->pkt->pkt.user_id);
2492
0
                }
2493
2494
0
              p = utf8_to_native (un->pkt->pkt.user_id->name,
2495
0
          un->pkt->pkt.user_id->len, 0);
2496
0
              log_info (_("                aka \"%s\""), p);
2497
0
              xfree (p);
2498
2499
0
              if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
2500
0
                {
2501
0
                  const char *valid;
2502
2503
0
                  if (un->pkt->pkt.user_id->flags.revoked)
2504
0
                    valid = _("revoked");
2505
0
                  else if (un->pkt->pkt.user_id->flags.expired)
2506
0
                    valid = _("expired");
2507
0
                  else
2508
        /* Since this is just informational, don't
2509
           actually ask the user to update any trust
2510
           information.  */
2511
0
                    valid = (trust_value_to_string
2512
0
                             (get_validity (c->ctrl, keyblock, mainpk,
2513
0
                                            un->pkt->pkt.user_id, NULL, 0)));
2514
0
                  log_printf (" [%s]\n",valid);
2515
0
                }
2516
0
              else
2517
0
                log_printf ("\n");
2518
0
            }
2519
0
  }
2520
2521
      /* For good signatures print notation data.  */
2522
0
      if (!rc)
2523
0
        {
2524
0
          if ((opt.verify_options & VERIFY_SHOW_POLICY_URLS))
2525
0
            show_policy_url (sig, 0, 1);
2526
0
          else
2527
0
            show_policy_url (sig, 0, 2);
2528
2529
0
          if ((opt.verify_options & VERIFY_SHOW_KEYSERVER_URLS))
2530
0
            show_keyserver_url (sig, 0, 1);
2531
0
          else
2532
0
            show_keyserver_url (sig, 0, 2);
2533
2534
0
          if ((opt.verify_options & VERIFY_SHOW_NOTATIONS))
2535
0
            show_notation
2536
0
              (sig, 0, 1,
2537
0
               (((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0)
2538
0
                + ((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0)
2539
0
                + ((opt.verify_options &VERIFY_SHOW_HIDDEN_NOTATIONS)? 4:0)
2540
0
                ));
2541
0
          else
2542
0
            show_notation (sig, 0, 2, 0);
2543
0
          print_matching_notations (sig);
2544
0
        }
2545
2546
      /* Fill PKSTRBUF with the algostring in case we later need it.  */
2547
0
      if (pk)
2548
0
        pubkey_string (pk, pkstrbuf, sizeof pkstrbuf);
2549
2550
      /* For good signatures print the VALIDSIG status line.  */
2551
0
      if (!rc && (is_status_enabled ()
2552
0
                  || opt.assert_signer_list
2553
0
                  || opt.assert_pubkey_algos) && pk)
2554
0
        {
2555
0
          char pkhex[MAX_FINGERPRINT_LEN*2+1];
2556
0
          char mainpkhex[MAX_FINGERPRINT_LEN*2+1];
2557
2558
0
          hexfingerprint (pk, pkhex, sizeof pkhex);
2559
0
          hexfingerprint (mainpk, mainpkhex, sizeof mainpkhex);
2560
2561
          /* TODO: Replace the reserved '0' in the field below with
2562
             bits for status flags (policy url, notation, etc.).  */
2563
0
          write_status_printf (STATUS_VALIDSIG,
2564
0
                               "%s %s %lu %lu %d 0 %d %d %02X %s",
2565
0
                               pkhex,
2566
0
                               strtimestamp (sig->timestamp),
2567
0
                               (ulong)sig->timestamp,
2568
0
                               (ulong)sig->expiredate,
2569
0
                               sig->version, sig->pubkey_algo,
2570
0
                               sig->digest_algo,
2571
0
                               sig->sig_class,
2572
0
                               mainpkhex);
2573
          /* Handle the --assert-signer option.  */
2574
0
          check_assert_signer_list (mainpkhex, pkhex);
2575
          /* Handle the --assert-pubkey-algo option.  */
2576
0
          check_assert_pubkey_algo (pkstrbuf, pkhex);
2577
0
  }
2578
2579
      /* Print compliance warning for Good signatures.  */
2580
0
      if (!rc && pk && !opt.quiet
2581
0
          && !gnupg_pk_is_compliant (opt.compliance, pk->pubkey_algo, 0,
2582
0
                                     pk->pkey, nbits_from_pk (pk), NULL))
2583
0
        {
2584
0
          log_info (_("WARNING: This key is not suitable for signing"
2585
0
                      " in %s mode\n"),
2586
0
                    gnupg_compliance_option_string (opt.compliance));
2587
0
        }
2588
2589
      /* For good signatures compute and print the trust information.
2590
         Note that in the Tofu trust model this may ask the user on
2591
         how to resolve a conflict.  */
2592
0
      if (!rc)
2593
0
        {
2594
0
          rc = check_signatures_trust (c->ctrl, keyblock, pk, sig);
2595
0
        }
2596
2597
      /* Print extra information about the signature.  */
2598
0
      if (sig->flags.expired)
2599
0
        {
2600
0
          log_info (_("Signature expired %s\n"), asctimestamp(sig->expiredate));
2601
0
          if (!rc)
2602
0
            rc = gpg_error (GPG_ERR_GENERAL); /* Need a better error here?  */
2603
0
        }
2604
0
      else if (sig->expiredate)
2605
0
        log_info (_("Signature expires %s\n"), asctimestamp(sig->expiredate));
2606
2607
0
      if (opt.verbose)
2608
0
        {
2609
0
          log_info (_("%s signature, digest algorithm %s%s%s\n"),
2610
0
                    sig->sig_class==0x00?_("binary"):
2611
0
                    sig->sig_class==0x01?_("textmode"):_("unknown"),
2612
0
                    gcry_md_algo_name (sig->digest_algo),
2613
0
                    *pkstrbuf?_(", key algorithm "):"", pkstrbuf);
2614
0
        }
2615
2616
      /* Print final warnings.  */
2617
0
      if (!rc && !c->signed_data.used)
2618
0
        {
2619
          /* Signature is basically good but we test whether the
2620
             deprecated command
2621
               gpg --verify FILE.sig
2622
             was used instead of
2623
               gpg --verify FILE.sig FILE
2624
             to verify a detached signature.  If we figure out that a
2625
             data file with a matching name exists, we print a warning.
2626
2627
             The problem is that the first form would also verify a
2628
             standard signature.  This behavior could be used to
2629
             create a made up .sig file for a tarball by creating a
2630
             standard signature from a valid detached signature packet
2631
             (for example from a signed git tag).  Then replace the
2632
             sig file on the FTP server along with a changed tarball.
2633
             Using the first form the verify command would correctly
2634
             verify the signature but don't even consider the tarball.  */
2635
0
          kbnode_t n;
2636
0
          char *dfile;
2637
2638
0
          dfile = get_matching_datafile (c->sigfilename);
2639
0
          if (dfile)
2640
0
            {
2641
0
              for (n = c->list; n; n = n->next)
2642
0
                if (n->pkt->pkttype != PKT_SIGNATURE)
2643
0
                  break;
2644
0
              if (n)
2645
0
                {
2646
                  /* Not only signature packets in the tree thus this
2647
                     is not a detached signature.  */
2648
0
                  log_info (_("WARNING: not a detached signature; "
2649
0
                              "file '%s' was NOT verified!\n"), dfile);
2650
0
                  assert_signer_true = 0;
2651
0
                }
2652
0
              xfree (dfile);
2653
0
            }
2654
0
        }
2655
2656
      /* Compute compliance with CO_DE_VS.  */
2657
0
      if (pk
2658
0
          && gnupg_gcrypt_is_compliant (CO_DE_VS)
2659
0
          && gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0, pk->pkey,
2660
0
                                    nbits_from_pk (pk), NULL)
2661
0
          && gnupg_digest_is_compliant (CO_DE_VS, sig->digest_algo))
2662
0
        write_status_strings (STATUS_VERIFICATION_COMPLIANCE_MODE,
2663
0
                              gnupg_status_compliance_flag (CO_DE_VS),
2664
0
                              NULL);
2665
0
      else if (opt.flags.require_compliance
2666
0
               && opt.compliance == CO_DE_VS)
2667
0
        {
2668
0
          log_error (_("operation forced to fail due to"
2669
0
                       " unfulfilled compliance rules\n"));
2670
0
          if (!rc)
2671
0
            rc = gpg_error (GPG_ERR_FORBIDDEN);
2672
0
        }
2673
2674
2675
0
      free_public_key (pk);
2676
0
      pk = NULL;
2677
0
      release_kbnode( keyblock );
2678
0
      if (rc)
2679
0
        g10_errors_seen = 1;
2680
0
    }
2681
17.6k
  else  /* Error checking the signature. (neither Good nor Bad).  */
2682
17.6k
    {
2683
17.6k
      write_status_printf (STATUS_ERRSIG, "%08lX%08lX %d %d %02x %lu %d %s",
2684
17.6k
                           (ulong)sig->keyid[0], (ulong)sig->keyid[1],
2685
17.6k
                           sig->pubkey_algo, sig->digest_algo,
2686
17.6k
                           sig->sig_class, (ulong)sig->timestamp,
2687
17.6k
                           gpg_err_code (rc),
2688
17.6k
                           issuer_fpr? issuer_fpr:"-");
2689
17.6k
      if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2690
474
        {
2691
474
          write_status_printf (STATUS_NO_PUBKEY, "%08lX%08lX",
2692
474
                               (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
2693
474
  }
2694
17.6k
      if (gpg_err_code (rc) != GPG_ERR_NOT_PROCESSED)
2695
17.6k
        log_error (_("Can't check signature: %s\n"), gpg_strerror (rc));
2696
17.6k
    }
2697
2698
18.7k
 leave:
2699
18.7k
  free_public_key (pk);
2700
18.7k
  xfree (issuer_fpr);
2701
18.7k
  return rc;
2702
17.6k
}
2703
2704
2705
/*
2706
 * Process the tree which starts at node
2707
 */
2708
static void
2709
proc_tree (CTX c, kbnode_t node)
2710
85.2k
{
2711
85.2k
  kbnode_t n1;
2712
85.2k
  int rc;
2713
2714
85.2k
  if (opt.list_packets || opt.list_only)
2715
0
    return;
2716
2717
  /* We must skip our special plaintext marker packets here because
2718
     they may be the root packet.  These packets are only used in
2719
     additional checks and skipping them here doesn't matter.  */
2720
87.7k
  while (node
2721
54.2k
         && node->pkt->pkttype == PKT_GPG_CONTROL
2722
5.83k
          && node->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK)
2723
2.46k
    {
2724
2.46k
      node = node->next;
2725
2.46k
    }
2726
85.2k
  if (!node)
2727
33.4k
    return;
2728
2729
51.8k
  c->trustletter = ' ';
2730
51.8k
  if (node->pkt->pkttype == PKT_PUBLIC_KEY
2731
28.4k
      || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2732
23.3k
    {
2733
23.3k
      merge_keys_and_selfsig (c->ctrl, node);
2734
23.3k
      list_node (c, node);
2735
23.3k
    }
2736
28.4k
  else if (node->pkt->pkttype == PKT_SECRET_KEY)
2737
918
    {
2738
918
      merge_keys_and_selfsig (c->ctrl, node);
2739
918
      list_node (c, node);
2740
918
    }
2741
27.5k
  else if (node->pkt->pkttype == PKT_ONEPASS_SIG)
2742
91
    {
2743
      /* Check all signatures.  */
2744
91
      if (!c->any.data)
2745
0
        {
2746
0
          int use_textmode = 0;
2747
2748
0
          free_md_filter_context (&c->mfx);
2749
          /* Prepare to create all requested message digests.  */
2750
0
          rc = gcry_md_open (&c->mfx.md, 0, 0);
2751
0
          if (rc)
2752
0
            goto hash_err;
2753
2754
          /* Fixme: why looking for the signature packet and not the
2755
             one-pass packet?  */
2756
0
          for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2757
0
            gcry_md_enable (c->mfx.md, n1->pkt->pkt.signature->digest_algo);
2758
2759
0
          if (n1 && n1->pkt->pkt.onepass_sig->sig_class == 0x01)
2760
0
            use_textmode = 1;
2761
2762
          /* Ask for file and hash it. */
2763
0
          if (c->sigs_only)
2764
0
            {
2765
0
              if (c->signed_data.used
2766
0
                  && c->signed_data.data_fd != GNUPG_INVALID_FD)
2767
0
                rc = hash_datafile_by_fd (c->mfx.md, NULL,
2768
0
                                          c->signed_data.data_fd,
2769
0
                                          use_textmode);
2770
0
              else
2771
0
                rc = hash_datafiles (c->mfx.md, NULL,
2772
0
                                     c->signed_data.data_names,
2773
0
                                     c->sigfilename,
2774
0
                                     use_textmode);
2775
0
      }
2776
0
          else
2777
0
            {
2778
0
              rc = ask_for_detached_datafile (c->mfx.md, NULL,
2779
0
                                              iobuf_get_real_fname (c->iobuf),
2780
0
                                              use_textmode);
2781
0
      }
2782
2783
0
        hash_err:
2784
0
          if (rc)
2785
0
            {
2786
0
              log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
2787
0
              return;
2788
0
      }
2789
0
  }
2790
91
      else if (c->signed_data.used)
2791
0
        {
2792
0
          log_error (_("not a detached signature\n"));
2793
0
          return;
2794
0
        }
2795
2796
779
      for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2797
688
        if (check_sig_and_print (c, n1) && opt.batch
2798
0
            && !opt.flags.proc_all_sigs)
2799
0
          break;
2800
2801
91
    }
2802
27.4k
  else if (node->pkt->pkttype == PKT_GPG_CONTROL
2803
3.37k
           && node->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START)
2804
3.37k
    {
2805
      /* Clear text signed message.  */
2806
3.37k
      if (!c->any.data)
2807
304
        {
2808
304
          log_error ("cleartext signature without data\n");
2809
304
          return;
2810
304
        }
2811
3.06k
      else if (c->signed_data.used)
2812
0
        {
2813
0
          log_error (_("not a detached signature\n"));
2814
0
          return;
2815
0
        }
2816
2817
3.10k
      for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
2818
38
        if (check_sig_and_print (c, n1) && opt.batch
2819
0
            && !opt.flags.proc_all_sigs)
2820
0
          break;
2821
3.06k
    }
2822
24.0k
  else if (node->pkt->pkttype == PKT_SIGNATURE)
2823
24.0k
    {
2824
24.0k
      PKT_signature *sig = node->pkt->pkt.signature;
2825
24.0k
      int multiple_ok = 1;
2826
2827
24.0k
      n1 = find_next_kbnode (node, PKT_SIGNATURE);
2828
24.0k
      if (n1)
2829
2.35k
        {
2830
2.35k
          byte class = sig->sig_class;
2831
2.35k
          byte hash  = sig->digest_algo;
2832
2833
9.28k
          for (; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
2834
8.09k
            {
2835
              /* We can't currently handle multiple signatures of
2836
               * different classes (we'd pretty much have to run a
2837
               * different hash context for each), but if they are all
2838
               * the same and it is detached signature, we make an
2839
               * exception.  Note that the old code also disallowed
2840
               * multiple signatures if the digest algorithms are
2841
               * different.  We softened this restriction only for
2842
               * detached signatures, to be on the safe side. */
2843
8.09k
              if (n1->pkt->pkt.signature->sig_class != class
2844
6.93k
                  || (c->any.data
2845
209
                      && n1->pkt->pkt.signature->digest_algo != hash))
2846
1.15k
                {
2847
1.15k
                  multiple_ok = 0;
2848
1.15k
                  log_info (_("WARNING: multiple signatures detected.  "
2849
1.15k
                              "Only the first will be checked.\n"));
2850
1.15k
                  break;
2851
1.15k
                }
2852
8.09k
            }
2853
2.35k
        }
2854
2855
24.0k
      if (sig->sig_class != 0x00 && sig->sig_class != 0x01)
2856
11.6k
        {
2857
11.6k
          log_info(_("standalone signature of class 0x%02x\n"), sig->sig_class);
2858
11.6k
        }
2859
12.4k
      else if (!c->any.data)
2860
12.3k
        {
2861
          /* Detached signature */
2862
12.3k
          free_md_filter_context (&c->mfx);
2863
12.3k
          rc = gcry_md_open (&c->mfx.md, sig->digest_algo, 0);
2864
12.3k
          if (rc)
2865
12.3k
            goto detached_hash_err;
2866
2867
0
          if (multiple_ok)
2868
0
            {
2869
              /* If we have and want to handle multiple signatures we
2870
               * need to enable all hash algorithms for the context.  */
2871
0
              for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE)); )
2872
0
                if (!openpgp_md_test_algo (n1->pkt->pkt.signature->digest_algo))
2873
0
                  gcry_md_enable (c->mfx.md,
2874
0
                                  map_md_openpgp_to_gcry
2875
0
                                  (n1->pkt->pkt.signature->digest_algo));
2876
0
            }
2877
2878
0
          if (RFC2440 || RFC4880)
2879
0
            ; /* Strict RFC mode.  */
2880
0
          else if (sig->digest_algo == DIGEST_ALGO_SHA1
2881
0
                   && sig->pubkey_algo == PUBKEY_ALGO_DSA
2882
0
                   && sig->sig_class == 0x01)
2883
0
            {
2884
              /* Enable a workaround for a pgp5 bug when the detached
2885
               * signature has been created in textmode.  Note that we
2886
               * do not implement this for multiple signatures with
2887
               * different hash algorithms. */
2888
0
              rc = gcry_md_open (&c->mfx.md2, sig->digest_algo, 0);
2889
0
              if (rc)
2890
0
                goto detached_hash_err;
2891
0
      }
2892
2893
          /* Here we used to have another hack to work around a pgp
2894
           * 2 bug: It worked by not using the textmode for detached
2895
           * signatures; this would let the first signature check
2896
           * (on md) fail but the second one (on md2), which adds an
2897
           * extra CR would then have produced the "correct" hash.
2898
           * This is very, very ugly hack but it may haved help in
2899
           * some cases (and break others).
2900
           *   c->mfx.md2? 0 :(sig->sig_class == 0x01)
2901
           */
2902
2903
0
          if (DBG_HASHING)
2904
0
            {
2905
0
              gcry_md_debug (c->mfx.md, "verify");
2906
0
              if (c->mfx.md2)
2907
0
                gcry_md_debug (c->mfx.md2, "verify2");
2908
0
            }
2909
2910
0
          if (c->sigs_only)
2911
0
            {
2912
0
              if (c->signed_data.used
2913
0
                  && c->signed_data.data_fd != GNUPG_INVALID_FD)
2914
0
                rc = hash_datafile_by_fd (c->mfx.md, c->mfx.md2,
2915
0
                                          c->signed_data.data_fd,
2916
0
                                          (sig->sig_class == 0x01));
2917
0
              else
2918
0
                rc = hash_datafiles (c->mfx.md, c->mfx.md2,
2919
0
                                     c->signed_data.data_names,
2920
0
                                     c->sigfilename,
2921
0
                                     (sig->sig_class == 0x01));
2922
0
      }
2923
0
          else
2924
0
            {
2925
0
              rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
2926
0
                                              iobuf_get_real_fname(c->iobuf),
2927
0
                                              (sig->sig_class == 0x01));
2928
0
      }
2929
2930
12.3k
        detached_hash_err:
2931
12.3k
          if (rc)
2932
12.3k
            {
2933
12.3k
              log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
2934
12.3k
              return;
2935
12.3k
      }
2936
12.3k
  }
2937
37
      else if (c->signed_data.used)
2938
0
        {
2939
0
          log_error (_("not a detached signature\n"));
2940
0
          return;
2941
0
        }
2942
37
      else if (!opt.quiet)
2943
37
        log_info (_("old style (PGP 2.x) signature\n"));
2944
2945
11.6k
      if (multiple_ok)
2946
10.8k
        {
2947
28.0k
          for (n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
2948
17.1k
      if (check_sig_and_print (c, n1) && opt.batch
2949
0
                && !opt.flags.proc_all_sigs)
2950
0
              break;
2951
10.8k
        }
2952
802
      else
2953
802
        check_sig_and_print (c, node);
2954
2955
11.6k
    }
2956
55
  else
2957
55
    {
2958
55
      dump_kbnode (c->list);
2959
      log_error ("invalid root packet detected in proc_tree()\n");
2960
55
      dump_kbnode (node);
2961
55
    }
2962
51.8k
}