Coverage Report

Created: 2026-01-10 07:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/g10/decrypt-data.c
Line
Count
Source
1
/* decrypt-data.c - Decrypt an encrypted data packet
2
 * Copyright (C) 1998-2001, 2005-2006, 2009 Free Software Foundation, Inc.
3
 * Copyright (C) 1998-2001, 2005-2006, 2009, 2018 Werner Koch
4
 *
5
 * This file is part of GnuPG.
6
 *
7
 * GnuPG is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * GnuPG is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, see <https://www.gnu.org/licenses/>.
19
 * SPDX-License-Identifier: GPL-3.0-or-later
20
 */
21
22
#include <config.h>
23
#include <stdio.h>
24
#include <stdlib.h>
25
#include <string.h>
26
27
#include "gpg.h"
28
#include "../common/util.h"
29
#include "packet.h"
30
#include "options.h"
31
#include "../common/i18n.h"
32
#include "../common/status.h"
33
#include "../common/compliance.h"
34
35
36
static int aead_decode_filter (void *opaque, int control, iobuf_t a,
37
                               byte *buf, size_t *ret_len);
38
static int mdc_decode_filter ( void *opaque, int control, IOBUF a,
39
                               byte *buf, size_t *ret_len);
40
static int decode_filter ( void *opaque, int control, IOBUF a,
41
          byte *buf, size_t *ret_len);
42
43
/* Our context object.  */
44
struct decode_filter_context_s
45
{
46
  /* Redcounter (max value is 2).  We need it because we do not know
47
   * whether the iobuf or the outer control code frees this object
48
   * first.  */
49
  int  refcount;
50
51
  /* The cipher handle.  */
52
  gcry_cipher_hd_t cipher_hd;
53
54
  /* The hash handle for use in MDC mode.  */
55
  gcry_md_hd_t mdc_hash;
56
57
  /* The start IV for AEAD encryption.   */
58
  byte startiv[16];
59
60
  /* The holdback buffer and its used length.  For AEAD we need 32+1
61
   * bytes but we use 48 byte.  For MDC we need 22 bytes; here
62
   * holdbacklen will either 0 or 22.  */
63
  char holdback[48];
64
  unsigned int holdbacklen;
65
66
  /* Working on a partial length packet.  */
67
  unsigned int partial : 1;
68
69
  /* EOF indicator with these true values:
70
   *   1 = normal EOF
71
   *   2 = premature EOF (tag or hash incomplete)
72
   *   3 = premature EOF (general)       */
73
  unsigned int eof_seen : 2;
74
75
  /* Flag to convey an error from aead_checktag.  */
76
  unsigned int checktag_failed : 1;
77
78
  /* The actually used cipher algo for AEAD.  */
79
  byte cipher_algo;
80
81
  /* The AEAD algo.  */
82
  byte aead_algo;
83
84
  /* The encoded chunk byte for AEAD.  */
85
  byte chunkbyte;
86
87
  /* The decoded CHUNKBYTE.  */
88
  uint64_t chunksize;
89
90
  /* The chunk index for AEAD.  */
91
  uint64_t chunkindex;
92
93
  /* The number of bytes in the current chunk.  */
94
  uint64_t chunklen;
95
96
  /* The total count of decrypted plaintext octets.  */
97
  uint64_t total;
98
99
  /* Remaining bytes in the packet according to the packet header.
100
   * Not used if PARTIAL is true.  */
101
  size_t length;
102
};
103
typedef struct decode_filter_context_s *decode_filter_ctx_t;
104
105
106
/* Helper to release the decode context.  */
107
static void
108
release_dfx_context (decode_filter_ctx_t dfx)
109
0
{
110
0
  if (!dfx)
111
0
    return;
112
113
0
  log_assert (dfx->refcount);
114
0
  if ( !--dfx->refcount )
115
0
    {
116
0
      gcry_cipher_close (dfx->cipher_hd);
117
0
      dfx->cipher_hd = NULL;
118
0
      gcry_md_close (dfx->mdc_hash);
119
0
      dfx->mdc_hash = NULL;
120
0
      xfree (dfx);
121
0
    }
122
0
}
123
124
125
/* Set the nonce and the additional data for the current chunk.  This
126
 * also reset the decryption machinery so that the handle can be
127
 * used for a new chunk.  If FINAL is set the final AEAD chunk is
128
 * processed.  */
129
static gpg_error_t
130
aead_set_nonce_and_ad (decode_filter_ctx_t dfx, int final)
131
0
{
132
0
  gpg_error_t err;
133
0
  unsigned char ad[21];
134
0
  unsigned char nonce[16];
135
0
  int i;
136
137
0
  switch (dfx->aead_algo)
138
0
    {
139
0
    case AEAD_ALGO_OCB:
140
0
      memcpy (nonce, dfx->startiv, 15);
141
0
      i = 7;
142
0
      break;
143
144
0
    case AEAD_ALGO_EAX:
145
0
      memcpy (nonce, dfx->startiv, 16);
146
0
      i = 8;
147
0
      break;
148
149
0
    default:
150
0
      BUG ();
151
0
    }
152
0
  nonce[i++] ^= dfx->chunkindex >> 56;
153
0
  nonce[i++] ^= dfx->chunkindex >> 48;
154
0
  nonce[i++] ^= dfx->chunkindex >> 40;
155
0
  nonce[i++] ^= dfx->chunkindex >> 32;
156
0
  nonce[i++] ^= dfx->chunkindex >> 24;
157
0
  nonce[i++] ^= dfx->chunkindex >> 16;
158
0
  nonce[i++] ^= dfx->chunkindex >>  8;
159
0
  nonce[i++] ^= dfx->chunkindex;
160
161
0
  if (DBG_CRYPTO)
162
0
    log_printhex (nonce, i, "nonce:");
163
0
  err = gcry_cipher_setiv (dfx->cipher_hd, nonce, i);
164
0
  if (err)
165
0
    return err;
166
167
0
  ad[0] = (0xc0 | PKT_ENCRYPTED_AEAD);
168
0
  ad[1] = 1;
169
0
  ad[2] = dfx->cipher_algo;
170
0
  ad[3] = dfx->aead_algo;
171
0
  ad[4] = dfx->chunkbyte;
172
0
  ad[5] = dfx->chunkindex >> 56;
173
0
  ad[6] = dfx->chunkindex >> 48;
174
0
  ad[7] = dfx->chunkindex >> 40;
175
0
  ad[8] = dfx->chunkindex >> 32;
176
0
  ad[9] = dfx->chunkindex >> 24;
177
0
  ad[10]= dfx->chunkindex >> 16;
178
0
  ad[11]= dfx->chunkindex >>  8;
179
0
  ad[12]= dfx->chunkindex;
180
0
  if (final)
181
0
    {
182
0
      ad[13] = dfx->total >> 56;
183
0
      ad[14] = dfx->total >> 48;
184
0
      ad[15] = dfx->total >> 40;
185
0
      ad[16] = dfx->total >> 32;
186
0
      ad[17] = dfx->total >> 24;
187
0
      ad[18] = dfx->total >> 16;
188
0
      ad[19] = dfx->total >>  8;
189
0
      ad[20] = dfx->total;
190
0
    }
191
0
  if (DBG_CRYPTO)
192
0
    log_printhex (ad, final? 21 : 13, "authdata:");
193
0
  return gcry_cipher_authenticate (dfx->cipher_hd, ad, final? 21 : 13);
194
0
}
195
196
197
/* Helper to check the 16 byte tag in TAGBUF.  The FINAL flag is only
198
 * for debug messages.  */
199
static gpg_error_t
200
aead_checktag (decode_filter_ctx_t dfx, int final, const void *tagbuf)
201
0
{
202
0
  gpg_error_t err;
203
204
0
  if (DBG_FILTER)
205
0
    log_printhex (tagbuf, 16, "tag:");
206
0
  err = gcry_cipher_checktag (dfx->cipher_hd, tagbuf, 16);
207
0
  if (err)
208
0
    {
209
0
      log_error ("gcry_cipher_checktag%s failed: %s\n",
210
0
                 final? " (final)":"", gpg_strerror (err));
211
0
      write_status_error ("aead_checktag", err);
212
0
      dfx->checktag_failed = 1;
213
0
      return err;
214
0
    }
215
0
  if (DBG_FILTER)
216
0
    log_debug ("%stag is valid\n", final?"final ":"");
217
0
  return 0;
218
0
}
219
220
221
/****************
222
 * Decrypt the data, specified by ED with the key DEK.  On return
223
 * COMPLIANCE_ERROR is set to true iff the decryption can claim that
224
 * it was compliant in the current mode; otherwise this flag is set to
225
 * false.
226
 */
227
int
228
decrypt_data (ctrl_t ctrl, void *procctx, PKT_encrypted *ed, DEK *dek,
229
              int *compliance_error)
230
0
{
231
0
  decode_filter_ctx_t dfx;
232
0
  enum gcry_cipher_modes ciphermode;
233
0
  unsigned int startivlen;
234
0
  byte *p;
235
0
  int rc=0, c, i;
236
0
  byte temp[32];
237
0
  unsigned int blocksize;
238
0
  unsigned int nprefix;
239
240
0
  *compliance_error = 0;
241
242
0
  dfx = xtrycalloc (1, sizeof *dfx);
243
0
  if (!dfx)
244
0
    return gpg_error_from_syserror ();
245
0
  dfx->refcount = 1;
246
247
0
  if ( opt.verbose && !dek->algo_info_printed )
248
0
    {
249
0
      if (!openpgp_cipher_test_algo (dek->algo))
250
0
        log_info (_("%s encrypted data\n"),
251
0
                  openpgp_cipher_algo_mode_name (dek->algo, ed->aead_algo));
252
0
      else
253
0
        log_info (_("encrypted with unknown algorithm %d\n"), dek->algo );
254
0
      dek->algo_info_printed = 1;
255
0
    }
256
257
0
  if (ed->aead_algo)
258
0
    {
259
0
      rc = openpgp_aead_algo_info (ed->aead_algo, &ciphermode, &startivlen);
260
0
      if (rc)
261
0
        goto leave;
262
0
      log_assert (startivlen <= sizeof dfx->startiv);
263
0
    }
264
0
  else
265
0
    ciphermode = GCRY_CIPHER_MODE_CFB;
266
267
  /* Check compliance.  */
268
0
  if (!gnupg_cipher_is_allowed (opt.compliance, 0, dek->algo, ciphermode))
269
0
    {
270
0
      gpgrt_log (opt.show_only_session_key? GPGRT_LOGLVL_INFO
271
0
                 /*                     */: GPGRT_LOGLVL_ERROR,
272
0
                 _("cipher algorithm '%s' may not be used in %s mode\n"),
273
0
     openpgp_cipher_algo_mode_name (dek->algo,ed->aead_algo),
274
0
     gnupg_compliance_option_string (opt.compliance));
275
0
      *compliance_error = 1;
276
0
      if (opt.flags.require_compliance && !opt.show_only_session_key)
277
0
        {
278
          /* We fail early in this case because it does not make sense
279
           * to first decrypt everything.  */
280
0
          rc = gpg_error (GPG_ERR_CIPHER_ALGO);
281
0
          goto leave;
282
0
        }
283
0
    }
284
285
0
  write_status_printf (STATUS_DECRYPTION_INFO, "%d %d %d %d",
286
0
                       ed->mdc_method, dek->algo, ed->aead_algo,
287
0
                       *compliance_error);
288
289
0
  if (opt.show_session_key)
290
0
    {
291
0
      char numbuf[30];
292
0
      char *hexbuf;
293
294
0
      if (ed->aead_algo)
295
0
        snprintf (numbuf, sizeof numbuf, "%d.%u:", dek->algo, ed->aead_algo);
296
0
      else
297
0
        snprintf (numbuf, sizeof numbuf, "%d:", dek->algo);
298
0
      hexbuf = bin2hex (dek->key, dek->keylen, NULL);
299
0
      if (!hexbuf)
300
0
        {
301
0
          rc = gpg_error_from_syserror ();
302
0
          goto leave;
303
0
        }
304
0
      log_info ("session key: '%s%s'\n", numbuf, hexbuf);
305
0
      write_status_strings (STATUS_SESSION_KEY, numbuf, hexbuf, NULL);
306
0
      xfree (hexbuf);
307
0
      if (opt.show_only_session_key)
308
0
        {
309
0
          rc = 0;
310
0
          goto leave;
311
0
        }
312
0
    }
313
314
0
  rc = openpgp_cipher_test_algo (dek->algo);
315
0
  if (rc)
316
0
    goto leave;
317
0
  blocksize = openpgp_cipher_get_algo_blklen (dek->algo);
318
0
  if ( !blocksize || blocksize > 16 )
319
0
    log_fatal ("unsupported blocksize %u\n", blocksize );
320
321
0
  if (ed->aead_algo)
322
0
    {
323
0
      if (blocksize != 16)
324
0
        {
325
0
          rc = gpg_error (GPG_ERR_CIPHER_ALGO);
326
0
          goto leave;
327
0
        }
328
329
0
      if (ed->chunkbyte > 56)
330
0
        {
331
0
          log_error ("invalid AEAD chunkbyte %u\n", ed->chunkbyte);
332
0
          rc = gpg_error (GPG_ERR_INV_PACKET);
333
0
          goto leave;
334
0
        }
335
336
      /* Read the Start-IV. */
337
0
      if (ed->len)
338
0
        {
339
0
          for (i=0; i < startivlen && ed->len; i++, ed->len--)
340
0
            {
341
0
              if ((c=iobuf_get (ed->buf)) == -1)
342
0
                break;
343
0
              dfx->startiv[i] = c;
344
0
            }
345
0
        }
346
0
      else
347
0
        {
348
0
          for (i=0; i < startivlen; i++ )
349
0
            if ( (c=iobuf_get (ed->buf)) == -1 )
350
0
              break;
351
0
            else
352
0
              dfx->startiv[i] = c;
353
0
        }
354
0
      if (i != startivlen)
355
0
        {
356
0
          log_error ("Start-IV in AEAD packet too short (%d/%u)\n",
357
0
                     i, startivlen);
358
0
          rc = gpg_error (GPG_ERR_TOO_SHORT);
359
0
          goto leave;
360
0
        }
361
362
0
      dfx->cipher_algo = ed->cipher_algo;
363
0
      dfx->aead_algo = ed->aead_algo;
364
0
      dfx->chunkbyte = ed->chunkbyte;
365
0
      dfx->chunksize = (uint64_t)1 << (dfx->chunkbyte + 6);
366
367
0
      if (dek->algo != dfx->cipher_algo)
368
0
        log_info ("Note: different cipher algorithms used (%s/%s)\n",
369
0
                  openpgp_cipher_algo_name (dek->algo),
370
0
                  openpgp_cipher_algo_name (dfx->cipher_algo));
371
372
0
      rc = openpgp_cipher_open (&dfx->cipher_hd,
373
0
                                dfx->cipher_algo,
374
0
                                ciphermode,
375
0
                                GCRY_CIPHER_SECURE);
376
0
      if (rc)
377
0
        goto leave; /* Should never happen.  */
378
379
0
      if (DBG_CRYPTO)
380
0
        log_printhex (dek->key, dek->keylen, "thekey:");
381
0
      rc = gcry_cipher_setkey (dfx->cipher_hd, dek->key, dek->keylen);
382
0
      if (gpg_err_code (rc) == GPG_ERR_WEAK_KEY)
383
0
        {
384
0
          log_info (_("WARNING: message was encrypted with"
385
0
                      " a weak key in the symmetric cipher.\n"));
386
0
          rc = 0;
387
0
        }
388
0
      else if (rc)
389
0
        {
390
0
          log_error("key setup failed: %s\n", gpg_strerror (rc));
391
0
          goto leave;
392
0
        }
393
394
0
      if (!ed->buf)
395
0
        {
396
0
          log_error(_("problem handling encrypted packet\n"));
397
0
          goto leave;
398
0
        }
399
400
0
    }
401
0
  else /* CFB encryption.  */
402
0
    {
403
0
      nprefix = blocksize;
404
0
      if ( ed->len && ed->len < (nprefix+2) )
405
0
        {
406
          /* An invalid message.  We can't check that during parsing
407
           * because we may not know the used cipher then.  */
408
0
          rc = gpg_error (GPG_ERR_INV_PACKET);
409
0
          goto leave;
410
0
        }
411
412
0
      if ( ed->mdc_method )
413
0
        {
414
0
          if (gcry_md_open (&dfx->mdc_hash, ed->mdc_method, 0 ))
415
0
            BUG ();
416
0
          if ( DBG_HASHING )
417
0
            gcry_md_debug (dfx->mdc_hash, "checkmdc");
418
0
        }
419
420
0
      rc = openpgp_cipher_open (&dfx->cipher_hd, dek->algo,
421
0
                                GCRY_CIPHER_MODE_CFB,
422
0
                                (GCRY_CIPHER_SECURE
423
0
                                 | ((ed->mdc_method || dek->algo >= 100)?
424
0
                                    0 : GCRY_CIPHER_ENABLE_SYNC)));
425
0
      if (rc)
426
0
        {
427
          /* We should never get an error here cause we already checked
428
           * that the algorithm is available.  */
429
0
          BUG();
430
0
        }
431
432
433
      /* log_hexdump( "thekey", dek->key, dek->keylen );*/
434
0
      rc = gcry_cipher_setkey (dfx->cipher_hd, dek->key, dek->keylen);
435
0
      if ( gpg_err_code (rc) == GPG_ERR_WEAK_KEY )
436
0
        {
437
0
          log_info (_("WARNING: message was encrypted with"
438
0
                      " a weak key in the symmetric cipher.\n"));
439
0
          rc=0;
440
0
        }
441
0
      else if (rc)
442
0
        {
443
0
          log_error ("key setup failed: %s\n", gpg_strerror (rc) );
444
0
          goto leave;
445
0
        }
446
447
0
      if (!ed->buf)
448
0
        {
449
0
          log_error (_("problem handling encrypted packet\n"));
450
0
          rc = gpg_error (GPG_ERR_INV_PACKET);
451
0
          goto leave;
452
0
        }
453
454
0
      gcry_cipher_setiv (dfx->cipher_hd, NULL, 0);
455
456
0
      if ( ed->len )
457
0
        {
458
0
          for (i=0; i < (nprefix+2) && ed->len; i++, ed->len-- )
459
0
            {
460
0
              if ( (c=iobuf_get(ed->buf)) == -1 )
461
0
                break;
462
0
              else
463
0
                temp[i] = c;
464
0
            }
465
0
        }
466
0
      else
467
0
        {
468
0
          for (i=0; i < (nprefix+2); i++ )
469
0
            if ( (c=iobuf_get(ed->buf)) == -1 )
470
0
              break;
471
0
            else
472
0
              temp[i] = c;
473
0
        }
474
475
0
      gcry_cipher_decrypt (dfx->cipher_hd, temp, nprefix+2, NULL, 0);
476
0
      gcry_cipher_sync (dfx->cipher_hd);
477
0
      p = temp;
478
      /* log_hexdump( "prefix", temp, nprefix+2 ); */
479
0
      if (dek->symmetric
480
0
          && (p[nprefix-2] != p[nprefix] || p[nprefix-1] != p[nprefix+1]) )
481
0
        {
482
0
          rc = gpg_error (GPG_ERR_BAD_KEY);
483
0
          goto leave;
484
0
        }
485
486
0
      if ( dfx->mdc_hash )
487
0
        gcry_md_write (dfx->mdc_hash, temp, nprefix+2);
488
0
    }
489
490
0
  dfx->refcount++;
491
0
  dfx->partial = !!ed->is_partial;
492
0
  dfx->length = ed->len;
493
0
  dfx->checktag_failed = 0;
494
0
  if (ed->aead_algo)
495
0
    iobuf_push_filter ( ed->buf, aead_decode_filter, dfx );
496
0
  else if (ed->mdc_method)
497
0
    iobuf_push_filter ( ed->buf, mdc_decode_filter, dfx );
498
0
  else
499
0
    iobuf_push_filter ( ed->buf, decode_filter, dfx );
500
501
0
  if (opt.unwrap_encryption)
502
0
    {
503
0
      char *filename = NULL;
504
0
      estream_t fp;
505
506
0
      rc = get_output_file ("", 0, ed->buf, &filename, &fp);
507
0
      if (! rc)
508
0
        {
509
0
          iobuf_t output = iobuf_esopen (fp, "w", 0, 0);
510
0
          armor_filter_context_t *afx = NULL;
511
512
0
    es_setbuf (fp, NULL);
513
514
0
          if (opt.armor)
515
0
            {
516
0
              afx = new_armor_context ();
517
0
              push_armor_filter (afx, output);
518
0
            }
519
520
0
          iobuf_copy (output, ed->buf);
521
0
          if ((rc = iobuf_error (ed->buf)))
522
0
            log_error (_("error reading '%s': %s\n"),
523
0
                       filename, gpg_strerror (rc));
524
0
          else if ((rc = iobuf_error (output)))
525
0
            log_error (_("error writing '%s': %s\n"),
526
0
                       filename, gpg_strerror (rc));
527
528
0
          iobuf_close (output);
529
0
          release_armor_context (afx);
530
0
        }
531
0
      xfree (filename);
532
0
    }
533
0
  else
534
0
    proc_packets (ctrl, procctx, ed->buf );
535
536
0
  ed->buf = NULL;
537
0
  if (dfx->eof_seen > 1 )
538
0
    rc = gpg_error (GPG_ERR_INV_PACKET);
539
0
  else if (dfx->checktag_failed)
540
0
    {
541
0
      rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
542
0
    }
543
0
  else if ( ed->mdc_method )
544
0
    {
545
      /* We used to let parse-packet.c handle the MDC packet but this
546
         turned out to be a problem with compressed packets: With old
547
         style packets there is no length information available and
548
         the decompressor uses an implicit end.  However we can't know
549
         this implicit end beforehand (:-) and thus may feed the
550
         decompressor with more bytes than actually needed.  It would
551
         be possible to unread the extra bytes but due to our weird
552
         iobuf system any unread is non reliable due to filters
553
         already popped off.  The easy and sane solution is to care
554
         about the MDC packet only here and never pass it to the
555
         packet parser.  Fortunatley the OpenPGP spec requires a
556
         strict format for the MDC packet so that we know that 22
557
         bytes are appended.  */
558
0
      int datalen = gcry_md_get_algo_dlen (ed->mdc_method);
559
560
0
      log_assert (dfx->cipher_hd);
561
0
      log_assert (dfx->mdc_hash);
562
0
      gcry_cipher_decrypt (dfx->cipher_hd, dfx->holdback, 22, NULL, 0);
563
0
      gcry_md_write (dfx->mdc_hash, dfx->holdback, 2);
564
0
      gcry_md_final (dfx->mdc_hash);
565
566
0
      if (   dfx->holdback[0] != '\xd3'
567
0
          || dfx->holdback[1] != '\x14'
568
0
          || datalen != 20
569
0
          || memcmp (gcry_md_read (dfx->mdc_hash, 0), dfx->holdback+2, datalen))
570
0
        rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
571
      /* log_printhex("MDC message:", dfx->holdback, 22); */
572
      /* log_printhex("MDC calc:", gcry_md_read (dfx->mdc_hash,0), datalen); */
573
0
    }
574
575
0
 leave:
576
0
  release_dfx_context (dfx);
577
0
  return rc;
578
0
}
579
580
581
/* Fill BUFFER with up to NBYTES-OFFSET from STREAM utilizing
582
 * information from the context DFX.  Returns the new offset which is
583
 * the number of bytes read plus the original offset.  On EOF the
584
 * respective flag in DFX is set. */
585
static size_t
586
fill_buffer (decode_filter_ctx_t dfx, iobuf_t stream,
587
             byte *buffer, size_t nbytes, size_t offset)
588
0
{
589
0
  size_t nread = offset;
590
0
  size_t curr;
591
0
  int ret;
592
593
0
  if (dfx->partial)
594
0
    {
595
0
      while (nread < nbytes)
596
0
        {
597
0
          curr = nbytes - nread;
598
599
0
          ret = iobuf_read (stream, &buffer[nread], curr);
600
0
          if (ret == -1)
601
0
            {
602
0
              dfx->eof_seen = 1; /* Normal EOF. */
603
0
              break;
604
0
            }
605
606
0
          nread += ret;
607
0
        }
608
0
    }
609
0
  else
610
0
    {
611
0
      while (nread < nbytes && dfx->length)
612
0
        {
613
0
          curr = nbytes - nread;
614
0
          if (curr > dfx->length)
615
0
            curr = dfx->length;
616
617
0
          ret = iobuf_read (stream, &buffer[nread], curr);
618
0
          if (ret == -1)
619
0
            {
620
0
              dfx->eof_seen = 3; /* Premature EOF. */
621
0
              break;
622
0
            }
623
624
0
          nread += ret;
625
0
          dfx->length -= ret;
626
0
        }
627
0
      if (!dfx->length)
628
0
        dfx->eof_seen = 1; /* Normal EOF.  */
629
0
    }
630
631
0
  return nread;
632
0
}
633
634
635
/* The core of the AEAD decryption.  This is the underflow function of
636
 * the aead_decode_filter.  */
637
static gpg_error_t
638
aead_underflow (decode_filter_ctx_t dfx, iobuf_t a, byte *buf, size_t *ret_len)
639
0
{
640
0
  const size_t size = *ret_len; /* The allocated size of BUF.  */
641
0
  gpg_error_t err;
642
0
  size_t totallen = 0; /* The number of bytes to return on success or EOF.  */
643
0
  size_t off = 0;      /* The offset into the buffer.  */
644
0
  size_t len;          /* The current number of bytes in BUF+OFF.  */
645
646
0
  log_assert (size > 48); /* Our code requires at least this size.  */
647
648
  /* Copy the rest from the last call of this function into BUF.  */
649
0
  len = dfx->holdbacklen;
650
0
  dfx->holdbacklen = 0;
651
0
  memcpy (buf, dfx->holdback, len);
652
653
0
  if (DBG_FILTER)
654
0
    log_debug ("aead_underflow: size=%zu len=%zu%s%s\n", size, len,
655
0
               dfx->partial? " partial":"", dfx->eof_seen? " eof":"");
656
657
  /* Read and fill up BUF.  We need to watch out for an EOF so that we
658
   * can detect the last chunk which is commonly shorter than the
659
   * chunksize.  After the last data byte from the last chunk 32 more
660
   * bytes are expected for the last chunk's tag and the following
661
   * final chunk's tag.  To detect the EOF we need to try reading at least
662
   * one further byte; however we try to read 16 extra bytes to avoid
663
   * single byte reads in some lower layers.  The outcome is that we
664
   * have up to 48 extra extra octets which we will later put into the
665
   * holdback buffer for the next invocation (which handles the EOF
666
   * case).  */
667
0
  len = fill_buffer (dfx, a, buf, size, len);
668
0
  if (len < 32)
669
0
    {
670
      /* Not enough data for the last two tags.  */
671
0
      err = gpg_error (GPG_ERR_TRUNCATED);
672
0
      goto leave;
673
0
    }
674
0
  if (dfx->eof_seen)
675
0
    {
676
      /* If have seen an EOF we copy only the last two auth tags into
677
       * the holdback buffer.  */
678
0
      dfx->holdbacklen = 32;
679
0
      memcpy (dfx->holdback, buf+len-32, 32);
680
0
      len -= 32;
681
0
    }
682
0
  else
683
0
    {
684
      /* If have not seen an EOF we copy the entire extra 48 bytes
685
       * into the holdback buffer for processing at the next call of
686
       * this function.  */
687
0
      dfx->holdbacklen = len > 48? 48 : len;
688
0
      memcpy (dfx->holdback, buf+len-dfx->holdbacklen, dfx->holdbacklen);
689
0
      len -= dfx->holdbacklen;
690
0
    }
691
  /* log_printhex (dfx->holdback, dfx->holdbacklen, "holdback:"); */
692
693
  /* Decrypt the buffer.  This first requires a loop to handle the
694
   * case when a chunk ends within the buffer.  */
695
0
  if (DBG_FILTER)
696
0
    log_debug ("decrypt: chunklen=%llu total=%llu size=%zu len=%zu%s\n",
697
0
               (unsigned long long)dfx->chunklen,
698
0
               (unsigned long long)dfx->total,
699
0
               size, len,
700
0
               dfx->eof_seen? " eof":"");
701
702
0
  while (len && dfx->chunklen + len >= dfx->chunksize)
703
0
    {
704
0
      size_t n = dfx->chunksize - dfx->chunklen;
705
0
      byte tagbuf[16];
706
707
0
      if (DBG_FILTER)
708
0
        log_debug ("chunksize will be reached: n=%zu\n", n);
709
710
0
      if (!dfx->chunklen)
711
0
        {
712
          /* First data for this chunk - prepare.  */
713
0
          err = aead_set_nonce_and_ad (dfx, 0);
714
0
          if (err)
715
0
            goto leave;
716
0
        }
717
718
      /* log_printhex (buf, n, "ciph:"); */
719
0
      gcry_cipher_final (dfx->cipher_hd);
720
0
      err = gcry_cipher_decrypt (dfx->cipher_hd, buf+off, n, NULL, 0);
721
0
      if (err)
722
0
        {
723
0
          log_error ("gcry_cipher_decrypt failed (1): %s\n",
724
0
                     gpg_strerror (err));
725
0
          goto leave;
726
0
        }
727
      /* log_printhex (buf, n, "plai:"); */
728
0
      totallen += n;
729
0
      dfx->chunklen += n;
730
0
      dfx->total += n;
731
0
      off += n;
732
0
      len -= n;
733
734
0
      if (DBG_FILTER)
735
0
        log_debug ("ndecrypted: %zu (nchunk=%llu) bytes left: %zu at off=%zu\n",
736
0
                   totallen, (unsigned long long)dfx->chunklen, len, off);
737
738
      /* Check the tag.  */
739
0
      if (len < 16)
740
0
        {
741
          /* The tag is not entirely in the buffer.  Read the rest of
742
           * the tag from the holdback buffer.  Then shift the holdback
743
           * buffer and fill it up again.  */
744
0
          memcpy (tagbuf, buf+off, len);
745
0
          memcpy (tagbuf + len, dfx->holdback, 16 - len);
746
0
          dfx->holdbacklen -= 16-len;
747
0
          memmove (dfx->holdback, dfx->holdback + (16-len), dfx->holdbacklen);
748
749
0
          if (dfx->eof_seen)
750
0
            {
751
              /* We should have the last chunk's tag in TAGBUF and the
752
               * final tag in HOLDBACKBUF.  */
753
0
              if (len || dfx->holdbacklen != 16)
754
0
                {
755
                  /* Not enough data for the last two tags.  */
756
0
                  err = gpg_error (GPG_ERR_TRUNCATED);
757
0
                  goto leave;
758
0
                }
759
0
            }
760
0
          else
761
0
            {
762
0
              len = 0;
763
0
              dfx->holdbacklen = fill_buffer (dfx, a, dfx->holdback, 48,
764
0
                                              dfx->holdbacklen);
765
0
              if (dfx->holdbacklen < 32)
766
0
                {
767
                  /* Not enough data for the last two tags.  */
768
0
                  err = gpg_error (GPG_ERR_TRUNCATED);
769
0
                  goto leave;
770
0
                }
771
0
            }
772
0
        }
773
0
      else /* We already have the full tag.  */
774
0
        {
775
0
          memcpy (tagbuf, buf+off, 16);
776
          /* Remove that tag from the output.  */
777
0
          memmove (buf + off, buf + off + 16, len - 16);
778
0
          len -= 16;
779
0
        }
780
0
      err = aead_checktag (dfx, 0, tagbuf);
781
0
      if (err)
782
0
        goto leave;
783
0
      dfx->chunklen = 0;
784
0
      dfx->chunkindex++;
785
786
0
      continue;
787
0
    }
788
789
  /* The bulk decryption of our buffer.  */
790
0
  if (len)
791
0
    {
792
0
      if (!dfx->chunklen)
793
0
        {
794
          /* First data for this chunk - prepare.  */
795
0
          err = aead_set_nonce_and_ad (dfx, 0);
796
0
          if (err)
797
0
            goto leave;
798
0
        }
799
800
0
      if (dfx->eof_seen)
801
0
        {
802
          /* This is the last block of the last chunk.  Its length may
803
           * not be a multiple of the block length.  */
804
0
          gcry_cipher_final (dfx->cipher_hd);
805
0
        }
806
0
      err = gcry_cipher_decrypt (dfx->cipher_hd, buf + off, len, NULL, 0);
807
0
      if (err)
808
0
        {
809
0
          log_error ("gcry_cipher_decrypt failed (2): %s\n",
810
0
                     gpg_strerror (err));
811
0
          goto leave;
812
0
        }
813
0
      totallen += len;
814
0
      dfx->chunklen += len;
815
0
      dfx->total += len;
816
0
      if (DBG_FILTER)
817
0
        log_debug ("ndecrypted: %zu (nchunk=%llu)\n",
818
0
                   totallen, (unsigned long long)dfx->chunklen);
819
0
    }
820
821
0
  if (dfx->eof_seen)
822
0
    {
823
824
0
      if (dfx->chunklen)
825
0
        {
826
0
          if (DBG_FILTER)
827
0
            log_debug ("eof seen: holdback has the last and final tag\n");
828
0
          log_assert (dfx->holdbacklen >= 32);
829
0
          err = aead_checktag (dfx, 0, dfx->holdback);
830
0
          if (err)
831
0
            goto leave;
832
0
          dfx->chunklen = 0;
833
0
          dfx->chunkindex++;
834
0
          off = 16;
835
0
        }
836
0
      else
837
0
        {
838
0
          if (DBG_FILTER)
839
0
            log_debug ("eof seen: holdback has the final tag\n");
840
0
          log_assert (dfx->holdbacklen >= 16);
841
0
          off = 0;
842
0
        }
843
844
      /* Check the final chunk.  */
845
0
      err = aead_set_nonce_and_ad (dfx, 1);
846
0
      if (err)
847
0
        goto leave;
848
0
      gcry_cipher_final (dfx->cipher_hd);
849
      /* Decrypt an empty string (using HOLDBACK as a dummy).  */
850
0
      err = gcry_cipher_decrypt (dfx->cipher_hd, dfx->holdback, 0, NULL, 0);
851
0
      if (err)
852
0
        {
853
0
          log_error ("gcry_cipher_decrypt failed (final): %s\n",
854
0
                     gpg_strerror (err));
855
0
          goto leave;
856
0
        }
857
0
      err = aead_checktag (dfx, 1, dfx->holdback+off);
858
0
      if (err)
859
0
        goto leave;
860
0
      err = gpg_error (GPG_ERR_EOF);
861
0
    }
862
863
0
 leave:
864
0
  if (DBG_FILTER)
865
0
    log_debug ("aead_underflow: returning %zu (%s)\n",
866
0
               totallen, gpg_strerror (err));
867
868
  /* In case of an auth error we map the error code to the same as
869
   * used by the MDC decryption.  */
870
0
  if (gpg_err_code (err) == GPG_ERR_CHECKSUM)
871
0
    err = gpg_error (GPG_ERR_BAD_SIGNATURE);
872
873
  /* In case of an error we better wipe out the buffer than to convey
874
   * partly decrypted data.  */
875
0
  if (err && gpg_err_code (err) != GPG_ERR_EOF)
876
0
    memset (buf, 0, size);
877
878
0
  *ret_len = totallen;
879
880
0
  return err;
881
0
}
882
883
884
/* The IOBUF filter used to decrypt AEAD encrypted data.  */
885
static int
886
aead_decode_filter (void *opaque, int control, IOBUF a,
887
                    byte *buf, size_t *ret_len)
888
0
{
889
0
  decode_filter_ctx_t dfx = opaque;
890
0
  int rc = 0;
891
892
0
  if ( control == IOBUFCTRL_UNDERFLOW && dfx->eof_seen )
893
0
    {
894
0
      *ret_len = 0;
895
0
      rc = -1;
896
0
    }
897
0
  else if ( control == IOBUFCTRL_UNDERFLOW )
898
0
    {
899
0
      log_assert (a);
900
901
0
      rc = aead_underflow (dfx, a, buf, ret_len);
902
0
      if (gpg_err_code (rc) == GPG_ERR_EOF)
903
0
        rc = -1; /* We need to use the old convention in the filter.  */
904
905
0
    }
906
0
  else if ( control == IOBUFCTRL_FREE )
907
0
    {
908
0
      release_dfx_context (dfx);
909
0
    }
910
0
  else if ( control == IOBUFCTRL_DESC )
911
0
    {
912
0
      mem2str (buf, "aead_decode_filter", *ret_len);
913
0
    }
914
915
0
  return rc;
916
0
}
917
918
919
static int
920
mdc_decode_filter (void *opaque, int control, IOBUF a,
921
                   byte *buf, size_t *ret_len)
922
0
{
923
0
  decode_filter_ctx_t dfx = opaque;
924
0
  size_t n, size = *ret_len;
925
0
  int rc = 0;
926
927
  /* Note: We need to distinguish between a partial and a fixed length
928
     packet.  The first is the usual case as created by GPG.  However
929
     for short messages the format degrades to a fixed length packet
930
     and other implementations might use fixed length as well.  Only
931
     looking for the EOF on fixed data works only if the encrypted
932
     packet is not followed by other data.  This used to be a long
933
     standing bug which was fixed on 2009-10-02.  */
934
935
0
  if ( control == IOBUFCTRL_UNDERFLOW && dfx->eof_seen )
936
0
    {
937
0
      *ret_len = 0;
938
0
      rc = -1;
939
0
    }
940
0
  else if( control == IOBUFCTRL_UNDERFLOW )
941
0
    {
942
0
      log_assert (a);
943
0
      log_assert (size > 44); /* Our code requires at least this size.  */
944
945
      /* Get at least 22 bytes and put it ahead in the buffer.  */
946
0
      n = fill_buffer (dfx, a, buf, 44, 22);
947
0
      if (n == 44)
948
0
        {
949
          /* We have enough stuff - flush the holdback buffer.  */
950
0
          if ( !dfx->holdbacklen )  /* First time. */
951
0
            {
952
0
              memcpy (buf, buf+22, 22);
953
0
              n = 22;
954
0
      }
955
0
          else
956
0
            {
957
0
              memcpy (buf, dfx->holdback, 22);
958
0
      }
959
960
          /* Fill up the buffer. */
961
0
          n = fill_buffer (dfx, a, buf, size, n);
962
963
          /* Move the trailing 22 bytes back to the holdback buffer.  We
964
             have at least 44 bytes thus a memmove is not needed.  */
965
0
          n -= 22;
966
0
          memcpy (dfx->holdback, buf+n, 22 );
967
0
          dfx->holdbacklen = 22;
968
0
  }
969
0
      else if ( !dfx->holdbacklen ) /* EOF seen but empty holdback. */
970
0
        {
971
          /* This is bad because it means an incomplete hash. */
972
0
          n -= 22;
973
0
          memcpy (buf, buf+22, n );
974
0
          dfx->eof_seen = 2; /* EOF with incomplete hash.  */
975
0
  }
976
0
      else  /* EOF seen (i.e. read less than 22 bytes). */
977
0
        {
978
0
          memcpy (buf, dfx->holdback, 22 );
979
0
          n -= 22;
980
0
          memcpy (dfx->holdback, buf+n, 22 );
981
0
          dfx->eof_seen = 1; /* Normal EOF. */
982
0
  }
983
984
0
      if ( n )
985
0
        {
986
0
          if ( dfx->cipher_hd )
987
0
            gcry_cipher_decrypt (dfx->cipher_hd, buf, n, NULL, 0);
988
0
          if ( dfx->mdc_hash )
989
0
            gcry_md_write (dfx->mdc_hash, buf, n);
990
0
  }
991
0
      else
992
0
        {
993
0
          log_assert ( dfx->eof_seen );
994
0
          rc = -1; /* Return EOF.  */
995
0
  }
996
0
      *ret_len = n;
997
0
    }
998
0
  else if ( control == IOBUFCTRL_FREE )
999
0
    {
1000
0
      release_dfx_context (dfx);
1001
0
    }
1002
0
  else if ( control == IOBUFCTRL_DESC )
1003
0
    {
1004
0
      mem2str (buf, "mdc_decode_filter", *ret_len);
1005
0
    }
1006
0
  return rc;
1007
0
}
1008
1009
1010
static int
1011
decode_filter( void *opaque, int control, IOBUF a, byte *buf, size_t *ret_len)
1012
0
{
1013
0
  decode_filter_ctx_t fc = opaque;
1014
0
  size_t size = *ret_len;
1015
0
  size_t n;
1016
0
  int rc = 0;
1017
1018
1019
0
  if ( control == IOBUFCTRL_UNDERFLOW && fc->eof_seen )
1020
0
    {
1021
0
      *ret_len = 0;
1022
0
      rc = -1;
1023
0
    }
1024
0
  else if ( control == IOBUFCTRL_UNDERFLOW )
1025
0
    {
1026
0
      log_assert (a);
1027
1028
0
      n = fill_buffer (fc, a, buf, size, 0);
1029
0
      if (n)
1030
0
        {
1031
0
          if (fc->cipher_hd)
1032
0
            gcry_cipher_decrypt (fc->cipher_hd, buf, n, NULL, 0);
1033
0
        }
1034
0
      else
1035
0
        {
1036
0
          if (!fc->eof_seen)
1037
0
            fc->eof_seen = 1;
1038
0
          rc = -1; /* Return EOF. */
1039
0
        }
1040
0
      *ret_len = n;
1041
0
    }
1042
0
  else if ( control == IOBUFCTRL_FREE )
1043
0
    {
1044
0
      release_dfx_context (fc);
1045
0
    }
1046
0
  else if ( control == IOBUFCTRL_DESC )
1047
0
    {
1048
0
      mem2str (buf, "decode_filter", *ret_len);
1049
0
    }
1050
0
  return rc;
1051
0
}