Coverage Report

Created: 2024-11-21 07:03

/src/libgcrypt/cipher/rsa-common.c
Line
Count
Source (jump to first uncovered line)
1
/* rsa-common.c - Supporting functions for RSA
2
 * Copyright (C) 2011 Free Software Foundation, Inc.
3
 * Copyright (C) 2013  g10 Code GmbH
4
 *
5
 * This file is part of Libgcrypt.
6
 *
7
 * Libgcrypt is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU Lesser General Public License as
9
 * published by the Free Software Foundation; either version 2.1 of
10
 * the License, or (at your option) any later version.
11
 *
12
 * Libgcrypt 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 Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
19
 */
20
21
#include <config.h>
22
#include <stdio.h>
23
#include <stdlib.h>
24
#include <string.h>
25
26
#include "g10lib.h"
27
#include "mpi.h"
28
#include "cipher.h"
29
#include "pubkey-internal.h"
30
#include "const-time.h"
31
32
33
/* Turn VALUE into an octet string and store it in an allocated buffer
34
   at R_FRAME or - if R_RAME is NULL - copy it into the caller
35
   provided buffer SPACE; either SPACE or R_FRAME may be used.  If
36
   SPACE if not NULL, the caller must provide a buffer of at least
37
   NBYTES.  If the resulting octet string is shorter than NBYTES pad
38
   it to the left with zeroes.  If VALUE does not fit into NBYTES
39
   return an error code.  */
40
static gpg_err_code_t
41
octet_string_from_mpi (unsigned char **r_frame, void *space,
42
                       gcry_mpi_t value, size_t nbytes)
43
0
{
44
0
  return _gcry_mpi_to_octet_string (r_frame, space, value, nbytes);
45
0
}
46
47
48
49
/* Encode {VALUE,VALUELEN} for an NBITS keys using the pkcs#1 block
50
   type 2 padding.  On success the result is stored as a new MPI at
51
   R_RESULT.  On error the value at R_RESULT is undefined.
52
53
   If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as
54
   the seed instead of using a random string for it.  This feature is
55
   only useful for regression tests.  Note that this value may not
56
   contain zero bytes.
57
58
   We encode the value in this way:
59
60
     0  2  RND(n bytes)  0  VALUE
61
62
   0   is a marker we unfortunately can't encode because we return an
63
       MPI which strips all leading zeroes.
64
   2   is the block type.
65
   RND are non-zero random bytes.
66
67
   (Note that OpenPGP includes the cipher algorithm and a checksum in
68
   VALUE; the caller needs to prepare the value accordingly.)
69
  */
70
gpg_err_code_t
71
_gcry_rsa_pkcs1_encode_for_enc (gcry_mpi_t *r_result, unsigned int nbits,
72
                                const unsigned char *value, size_t valuelen,
73
                                const unsigned char *random_override,
74
                                size_t random_override_len)
75
0
{
76
0
  gcry_err_code_t rc = 0;
77
0
  unsigned char *frame = NULL;
78
0
  size_t nframe = (nbits+7) / 8;
79
0
  int i;
80
0
  size_t n;
81
0
  unsigned char *p;
82
83
0
  if (valuelen + 7 > nframe || !nframe)
84
0
    {
85
      /* Can't encode a VALUELEN value in a NFRAME bytes frame.  */
86
0
      return GPG_ERR_TOO_SHORT; /* The key is too short.  */
87
0
    }
88
89
0
  if ( !(frame = xtrymalloc_secure (nframe)))
90
0
    return gpg_err_code_from_syserror ();
91
92
0
  n = 0;
93
0
  frame[n++] = 0;
94
0
  frame[n++] = 2; /* block type */
95
0
  i = nframe - 3 - valuelen;
96
0
  gcry_assert (i > 0);
97
98
0
  if (random_override)
99
0
    {
100
0
      int j;
101
102
0
      if (random_override_len != i)
103
0
        {
104
0
          xfree (frame);
105
0
          return GPG_ERR_INV_ARG;
106
0
        }
107
      /* Check that random does not include a zero byte.  */
108
0
      for (j=0; j < random_override_len; j++)
109
0
        if (!random_override[j])
110
0
          {
111
0
            xfree (frame);
112
0
            return GPG_ERR_INV_ARG;
113
0
          }
114
0
      memcpy (frame + n, random_override, random_override_len);
115
0
      n += random_override_len;
116
0
    }
117
0
  else
118
0
    {
119
0
      p = _gcry_random_bytes_secure (i, GCRY_STRONG_RANDOM);
120
      /* Replace zero bytes by new values. */
121
0
      for (;;)
122
0
        {
123
0
          int j, k;
124
0
          unsigned char *pp;
125
126
          /* Count the zero bytes. */
127
0
          for (j=k=0; j < i; j++)
128
0
            {
129
0
              if (!p[j])
130
0
                k++;
131
0
            }
132
0
          if (!k)
133
0
            break; /* Okay: no (more) zero bytes. */
134
135
0
          k += k/128 + 3; /* Better get some more. */
136
0
          pp = _gcry_random_bytes_secure (k, GCRY_STRONG_RANDOM);
137
0
          for (j=0; j < i && k; )
138
0
            {
139
0
              if (!p[j])
140
0
                p[j] = pp[--k];
141
0
              if (p[j])
142
0
                j++;
143
0
            }
144
0
          xfree (pp);
145
0
        }
146
0
      memcpy (frame+n, p, i);
147
0
      n += i;
148
0
      xfree (p);
149
0
    }
150
151
0
  frame[n++] = 0;
152
0
  memcpy (frame+n, value, valuelen);
153
0
  n += valuelen;
154
0
  gcry_assert (n == nframe);
155
156
0
  rc = _gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe);
157
0
  if (!rc &&DBG_CIPHER)
158
0
    log_mpidump ("PKCS#1 block type 2 encoded data", *r_result);
159
0
  xfree (frame);
160
161
0
  return rc;
162
0
}
163
164
165
/*
166
 *                    <--len-->
167
 * DST-------v       v-------------SRC
168
 *           [.................]
169
 *            <---- buflen --->
170
 *
171
 * Copy the memory area SRC with LEN into another memory area DST.
172
 * Conditions met:
173
 *         the address SRC > DST
174
 *         DST + BUFLEN == SRC + LEN.
175
 *
176
 * Memory access doesn't depends on LEN, but always done independently,
177
 * sliding memory area by 1, 2, 4 ... until done.
178
 */
179
static void
180
memmov_independently (void *dst, const void *src, size_t len, size_t buflen)
181
0
{
182
0
  size_t offset = (size_t)((char *)src - (char *)dst);
183
0
  size_t shift;
184
185
0
  (void)len; /* No dependency.  */
186
0
  for (shift = 1; shift < buflen; shift <<= 1)
187
0
    {
188
0
      ct_memmov_cond (dst, (char *)dst + shift, buflen - shift, (offset&1));
189
0
      offset >>= 1;
190
0
    }
191
0
}
192
193
194
/* Decode a plaintext in VALUE assuming pkcs#1 block type 2 padding.
195
   NBITS is the size of the secret key.  On success the result is
196
   stored as a newly allocated buffer at R_RESULT and its valid length at
197
   R_RESULTLEN.  On error NULL is stored at R_RESULT.  */
198
gpg_err_code_t
199
_gcry_rsa_pkcs1_decode_for_enc (unsigned char **r_result, size_t *r_resultlen,
200
                                unsigned int nbits, gcry_mpi_t value)
201
0
{
202
0
  gcry_error_t err;
203
0
  unsigned char *frame = NULL;
204
0
  size_t nframe = (nbits+7) / 8;
205
0
  size_t n, n0;
206
0
  unsigned int failed = 0;
207
0
  unsigned int not_found = 1;
208
209
0
  *r_result = NULL;
210
211
0
  if ( !(frame = xtrymalloc_secure (nframe)))
212
0
    return gpg_err_code_from_syserror ();
213
214
0
  err = _gcry_mpi_print (GCRYMPI_FMT_USG, frame, nframe, &n, value);
215
0
  if (err)
216
0
    {
217
0
      xfree (frame);
218
0
      return gcry_err_code (err);
219
0
    }
220
221
0
  nframe = n; /* Set NFRAME to the actual length.  */
222
223
  /* FRAME = 0x00 || 0x02 || PS || 0x00 || M
224
225
     pkcs#1 requires that the first byte is zero.  Our MPIs usually
226
     strip leading zero bytes; thus we are not able to detect them.
227
     However due to the way gcry_mpi_print is implemented we may see
228
     leading zero bytes nevertheless.  We handle this by making the
229
     first zero byte optional.  */
230
0
  if (nframe < 4)
231
0
    {
232
0
      xfree (frame);
233
0
      return GPG_ERR_ENCODING_PROBLEM;  /* Too short.  */
234
0
    }
235
0
  n = 0;
236
0
  if (!frame[0])
237
0
    n++;
238
0
  failed |= ct_not_equal_byte (frame[n++], 0x02);
239
240
  /* Find the terminating zero byte.  */
241
0
  n0 = n;
242
0
  for (; n < nframe; n++)
243
0
    {
244
0
      not_found &= ct_not_equal_byte (frame[n], 0x00);
245
0
      n0 += not_found;
246
0
    }
247
248
0
  failed |= not_found;
249
0
  n0 += ct_is_zero (not_found); /* Skip the zero byte.  */
250
251
  /* To avoid an extra allocation we reuse the frame buffer.  The only
252
     caller of this function will anyway free the result soon.  */
253
0
  memmov_independently (frame, frame + n0, nframe - n0, nframe);
254
255
0
  *r_result = frame;
256
0
  *r_resultlen = nframe - n0;
257
258
0
  if (DBG_CIPHER)
259
0
    log_printhex ("value extracted from PKCS#1 block type 2 encoded data",
260
0
                  *r_result, *r_resultlen);
261
262
0
  return (0U - failed) & GPG_ERR_ENCODING_PROBLEM;
263
0
}
264
265
266
/* Encode {VALUE,VALUELEN} for an NBITS keys and hash algorithm ALGO
267
   using the pkcs#1 block type 1 padding.  On success the result is
268
   stored as a new MPI at R_RESULT.  On error the value at R_RESULT is
269
   undefined.
270
271
   We encode the value in this way:
272
273
     0  1  PAD(n bytes)  0  ASN(asnlen bytes) VALUE(valuelen bytes)
274
275
   0   is a marker we unfortunately can't encode because we return an
276
       MPI which strips all leading zeroes.
277
   1   is the block type.
278
   PAD consists of 0xff bytes.
279
   0   marks the end of the padding.
280
   ASN is the DER encoding of the hash algorithm; along with the VALUE
281
       it yields a valid DER encoding.
282
283
   (Note that PGP prior to version 2.3 encoded the message digest as:
284
      0   1   MD(16 bytes)   0   PAD(n bytes)   1
285
    The MD is always 16 bytes here because it's always MD5.  GnuPG
286
    does not not support pre-v2.3 signatures, but I'm including this
287
    comment so the information is easily found if needed.)
288
*/
289
gpg_err_code_t
290
_gcry_rsa_pkcs1_encode_for_sig (gcry_mpi_t *r_result, unsigned int nbits,
291
                                const unsigned char *value, size_t valuelen,
292
                                int algo)
293
0
{
294
0
  gcry_err_code_t rc = 0;
295
0
  byte asn[100];
296
0
  byte *frame = NULL;
297
0
  size_t nframe = (nbits+7) / 8;
298
0
  int i;
299
0
  size_t n;
300
0
  size_t asnlen, dlen;
301
302
0
  asnlen = DIM(asn);
303
0
  dlen = _gcry_md_get_algo_dlen (algo);
304
305
0
  if (_gcry_md_algo_info (algo, GCRYCTL_GET_ASNOID, asn, &asnlen))
306
0
    {
307
      /* We don't have yet all of the above algorithms.  */
308
0
      return GPG_ERR_NOT_IMPLEMENTED;
309
0
    }
310
311
0
  if ( valuelen != dlen )
312
0
    {
313
      /* Hash value does not match the length of digest for
314
         the given algorithm.  */
315
0
      return GPG_ERR_CONFLICT;
316
0
    }
317
318
0
  if ( !dlen || dlen + asnlen + 4 > nframe)
319
0
    {
320
      /* Can't encode an DLEN byte digest MD into an NFRAME byte
321
         frame.  */
322
0
      return GPG_ERR_TOO_SHORT;
323
0
    }
324
325
0
  if ( !(frame = xtrymalloc (nframe)) )
326
0
    return gpg_err_code_from_syserror ();
327
328
  /* Assemble the pkcs#1 block type 1. */
329
0
  n = 0;
330
0
  frame[n++] = 0;
331
0
  frame[n++] = 1; /* block type */
332
0
  i = nframe - valuelen - asnlen - 3 ;
333
0
  gcry_assert (i > 1);
334
0
  memset (frame+n, 0xff, i );
335
0
  n += i;
336
0
  frame[n++] = 0;
337
0
  memcpy (frame+n, asn, asnlen);
338
0
  n += asnlen;
339
0
  memcpy (frame+n, value, valuelen );
340
0
  n += valuelen;
341
0
  gcry_assert (n == nframe);
342
343
  /* Convert it into an MPI. */
344
0
  rc = _gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe);
345
0
  if (!rc && DBG_CIPHER)
346
0
    log_mpidump ("PKCS#1 block type 1 encoded data", *r_result);
347
0
  xfree (frame);
348
349
0
  return rc;
350
0
}
351
352
/* Encode {VALUE,VALUELEN} for an NBITS keys using the pkcs#1 block
353
   type 1 padding.  On success the result is stored as a new MPI at
354
   R_RESULT.  On error the value at R_RESULT is undefined.
355
356
   We encode the value in this way:
357
358
     0  1  PAD(n bytes)  0  VALUE(valuelen bytes)
359
360
   0   is a marker we unfortunately can't encode because we return an
361
       MPI which strips all leading zeroes.
362
   1   is the block type.
363
   PAD consists of 0xff bytes.
364
   0   marks the end of the padding.
365
366
   (Note that PGP prior to version 2.3 encoded the message digest as:
367
      0   1   MD(16 bytes)   0   PAD(n bytes)   1
368
    The MD is always 16 bytes here because it's always MD5.  GnuPG
369
    does not not support pre-v2.3 signatures, but I'm including this
370
    comment so the information is easily found if needed.)
371
*/
372
gpg_err_code_t
373
_gcry_rsa_pkcs1_encode_raw_for_sig (gcry_mpi_t *r_result, unsigned int nbits,
374
                                const unsigned char *value, size_t valuelen)
375
0
{
376
0
  gcry_err_code_t rc = 0;
377
0
  gcry_error_t err;
378
0
  byte *frame = NULL;
379
0
  size_t nframe = (nbits+7) / 8;
380
0
  int i;
381
0
  size_t n;
382
383
0
  if ( !valuelen || valuelen + 4 > nframe)
384
0
    {
385
      /* Can't encode an DLEN byte digest MD into an NFRAME byte
386
         frame.  */
387
0
      return GPG_ERR_TOO_SHORT;
388
0
    }
389
390
0
  if ( !(frame = xtrymalloc (nframe)) )
391
0
    return gpg_err_code_from_syserror ();
392
393
  /* Assemble the pkcs#1 block type 1. */
394
0
  n = 0;
395
0
  frame[n++] = 0;
396
0
  frame[n++] = 1; /* block type */
397
0
  i = nframe - valuelen - 3 ;
398
0
  gcry_assert (i > 1);
399
0
  memset (frame+n, 0xff, i );
400
0
  n += i;
401
0
  frame[n++] = 0;
402
0
  memcpy (frame+n, value, valuelen );
403
0
  n += valuelen;
404
0
  gcry_assert (n == nframe);
405
406
  /* Convert it into an MPI. */
407
0
  err = _gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe);
408
0
  if (err)
409
0
    rc = gcry_err_code (err);
410
0
  else if (DBG_CIPHER)
411
0
    log_mpidump ("PKCS#1 block type 1 encoded data", *r_result);
412
0
  xfree (frame);
413
414
0
  return rc;
415
0
}
416
417
418
/* Mask generation function for OAEP.  See RFC-3447 B.2.1.  */
419
static gcry_err_code_t
420
mgf1 (unsigned char *output, size_t outlen, unsigned char *seed, size_t seedlen,
421
      int algo)
422
0
{
423
0
  size_t dlen, nbytes, n;
424
0
  int idx;
425
0
  gcry_md_hd_t hd;
426
0
  gcry_err_code_t err;
427
428
0
  err = _gcry_md_open (&hd, algo, 0);
429
0
  if (err)
430
0
    return err;
431
432
0
  dlen = _gcry_md_get_algo_dlen (algo);
433
434
  /* We skip step 1 which would be assert(OUTLEN <= 2^32).  The loop
435
     in step 3 is merged with step 4 by concatenating no more octets
436
     than what would fit into OUTPUT.  The ceiling for the counter IDX
437
     is implemented indirectly.  */
438
0
  nbytes = 0;  /* Step 2.  */
439
0
  idx = 0;
440
0
  while ( nbytes < outlen )
441
0
    {
442
0
      unsigned char c[4], *digest;
443
444
0
      if (idx)
445
0
        _gcry_md_reset (hd);
446
447
0
      c[0] = (idx >> 24) & 0xFF;
448
0
      c[1] = (idx >> 16) & 0xFF;
449
0
      c[2] = (idx >> 8) & 0xFF;
450
0
      c[3] = idx & 0xFF;
451
0
      idx++;
452
453
0
      _gcry_md_write (hd, seed, seedlen);
454
0
      _gcry_md_write (hd, c, 4);
455
0
      digest = _gcry_md_read (hd, 0);
456
457
0
      n = (outlen - nbytes < dlen)? (outlen - nbytes) : dlen;
458
0
      memcpy (output+nbytes, digest, n);
459
0
      nbytes += n;
460
0
    }
461
462
0
  _gcry_md_close (hd);
463
0
  return GPG_ERR_NO_ERROR;
464
0
}
465
466
467
/* RFC-3447 (pkcs#1 v2.1) OAEP encoding.  NBITS is the length of the
468
   key measured in bits.  ALGO is the hash function; it must be a
469
   valid and usable algorithm.  {VALUE,VALUELEN} is the message to
470
   encrypt.  {LABEL,LABELLEN} is the optional label to be associated
471
   with the message, if LABEL is NULL the default is to use the empty
472
   string as label.  On success the encoded ciphertext is returned at
473
   R_RESULT.
474
475
   If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as
476
   the seed instead of using a random string for it.  This feature is
477
   only useful for regression tests.
478
479
   Here is figure 1 from the RFC depicting the process:
480
481
                             +----------+---------+-------+
482
                        DB = |  lHash   |    PS   |   M   |
483
                             +----------+---------+-------+
484
                                            |
485
                  +----------+              V
486
                  |   seed   |--> MGF ---> xor
487
                  +----------+              |
488
                        |                   |
489
               +--+     V                   |
490
               |00|    xor <----- MGF <-----|
491
               +--+     |                   |
492
                 |      |                   |
493
                 V      V                   V
494
               +--+----------+----------------------------+
495
         EM =  |00|maskedSeed|          maskedDB          |
496
               +--+----------+----------------------------+
497
  */
498
gpg_err_code_t
499
_gcry_rsa_oaep_encode (gcry_mpi_t *r_result, unsigned int nbits, int algo,
500
                       const unsigned char *value, size_t valuelen,
501
                       const unsigned char *label, size_t labellen,
502
                       const void *random_override, size_t random_override_len)
503
0
{
504
0
  gcry_err_code_t rc = 0;
505
0
  unsigned char *frame = NULL;
506
0
  size_t nframe = (nbits+7) / 8;
507
0
  unsigned char *p;
508
0
  size_t hlen;
509
0
  size_t n;
510
511
0
  *r_result = NULL;
512
513
  /* Set defaults for LABEL.  */
514
0
  if (!label || !labellen)
515
0
    {
516
0
      label = (const unsigned char*)"";
517
0
      labellen = 0;
518
0
    }
519
520
0
  hlen = _gcry_md_get_algo_dlen (algo);
521
522
  /* We skip step 1a which would be to check that LABELLEN is not
523
     greater than 2^61-1.  See rfc-3447 7.1.1. */
524
525
  /* Step 1b.  Note that the obsolete rfc-2437 uses the check:
526
     valuelen > nframe - 2 * hlen - 1 .  */
527
0
  if (valuelen > nframe - 2 * hlen - 2 || !nframe)
528
0
    {
529
      /* Can't encode a VALUELEN value in a NFRAME bytes frame. */
530
0
      return GPG_ERR_TOO_SHORT; /* The key is too short.  */
531
0
    }
532
533
  /* Allocate the frame.  */
534
0
  frame = xtrycalloc_secure (1, nframe);
535
0
  if (!frame)
536
0
    return gpg_err_code_from_syserror ();
537
538
  /* Step 2a: Compute the hash of the label.  We store it in the frame
539
     where later the maskedDB will commence.  */
540
0
  _gcry_md_hash_buffer (algo, frame + 1 + hlen, label, labellen);
541
542
  /* Step 2b: Set octet string to zero.  */
543
  /* This has already been done while allocating FRAME.  */
544
545
  /* Step 2c: Create DB by concatenating lHash, PS, 0x01 and M.  */
546
0
  n = nframe - valuelen - 1;
547
0
  frame[n] = 0x01;
548
0
  memcpy (frame + n + 1, value, valuelen);
549
550
  /* Step 3d: Generate seed.  We store it where the maskedSeed will go
551
     later. */
552
0
  if (random_override)
553
0
    {
554
0
      if (random_override_len != hlen)
555
0
        {
556
0
          xfree (frame);
557
0
          return GPG_ERR_INV_ARG;
558
0
        }
559
0
      memcpy (frame + 1, random_override, hlen);
560
0
    }
561
0
  else
562
0
    _gcry_randomize (frame + 1, hlen, GCRY_STRONG_RANDOM);
563
564
  /* Step 2e and 2f: Create maskedDB.  */
565
0
  {
566
0
    unsigned char *dmask;
567
568
0
    dmask = xtrymalloc_secure (nframe - hlen - 1);
569
0
    if (!dmask)
570
0
      {
571
0
        rc = gpg_err_code_from_syserror ();
572
0
        xfree (frame);
573
0
        return rc;
574
0
      }
575
0
    rc = mgf1 (dmask, nframe - hlen - 1, frame+1, hlen, algo);
576
0
    if (rc)
577
0
      {
578
0
        xfree (dmask);
579
0
        xfree (frame);
580
0
        return rc;
581
0
      }
582
0
    for (n = 1 + hlen, p = dmask; n < nframe; n++)
583
0
      frame[n] ^= *p++;
584
0
    xfree (dmask);
585
0
  }
586
587
  /* Step 2g and 2h: Create maskedSeed.  */
588
0
  {
589
0
    unsigned char *smask;
590
591
0
    smask = xtrymalloc_secure (hlen);
592
0
    if (!smask)
593
0
      {
594
0
        rc = gpg_err_code_from_syserror ();
595
0
        xfree (frame);
596
0
        return rc;
597
0
      }
598
0
    rc = mgf1 (smask, hlen, frame + 1 + hlen, nframe - hlen - 1, algo);
599
0
    if (rc)
600
0
      {
601
0
        xfree (smask);
602
0
        xfree (frame);
603
0
        return rc;
604
0
      }
605
0
    for (n = 1, p = smask; n < 1 + hlen; n++)
606
0
      frame[n] ^= *p++;
607
0
    xfree (smask);
608
0
  }
609
610
  /* Step 2i: Concatenate 0x00, maskedSeed and maskedDB.  */
611
  /* This has already been done by using in-place operations.  */
612
613
  /* Convert the stuff into an MPI as expected by the caller.  */
614
0
  rc = _gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, nframe, NULL);
615
0
  if (!rc && DBG_CIPHER)
616
0
    log_mpidump ("OAEP encoded data", *r_result);
617
0
  xfree (frame);
618
619
0
  return rc;
620
0
}
621
622
623
/* RFC-3447 (pkcs#1 v2.1) OAEP decoding.  NBITS is the length of the
624
   key measured in bits.  ALGO is the hash function; it must be a
625
   valid and usable algorithm.  VALUE is the raw decrypted message
626
   {LABEL,LABELLEN} is the optional label to be associated with the
627
   message, if LABEL is NULL the default is to use the empty string as
628
   label.  On success the plaintext is returned as a newly allocated
629
   buffer at R_RESULT; its valid length is stored at R_RESULTLEN.  On
630
   error NULL is stored at R_RESULT.  */
631
gpg_err_code_t
632
_gcry_rsa_oaep_decode (unsigned char **r_result, size_t *r_resultlen,
633
                       unsigned int nbits, int algo,
634
                       gcry_mpi_t value,
635
                       const unsigned char *label, size_t labellen)
636
0
{
637
0
  gcry_err_code_t rc;
638
0
  unsigned char *frame = NULL; /* Encoded messages (EM).  */
639
0
  unsigned char *masked_seed;  /* Points into FRAME.  */
640
0
  unsigned char *masked_db;    /* Points into FRAME.  */
641
0
  unsigned char *seed = NULL;  /* Allocated space for the seed and DB.  */
642
0
  unsigned char *db;           /* Points into SEED.  */
643
0
  unsigned char *lhash = NULL; /* Hash of the label.  */
644
0
  size_t nframe;               /* Length of the ciphertext (EM).  */
645
0
  size_t hlen;                 /* Length of the hash digest.  */
646
0
  size_t db_len;               /* Length of DB and masked_db.  */
647
0
  size_t nkey = (nbits+7)/8;   /* Length of the key in bytes.  */
648
0
  int failed = 0;              /* Error indicator.  */
649
0
  size_t n, n1;
650
0
  unsigned int not_found = 1;
651
652
0
  *r_result = NULL;
653
654
  /* This code is implemented as described by rfc-3447 7.1.2.  */
655
656
  /* Set defaults for LABEL.  */
657
0
  if (!label || !labellen)
658
0
    {
659
0
      label = (const unsigned char*)"";
660
0
      labellen = 0;
661
0
    }
662
663
  /* Get the length of the digest.  */
664
0
  hlen = _gcry_md_get_algo_dlen (algo);
665
666
  /* Hash the label right away.  */
667
0
  lhash = xtrymalloc (hlen);
668
0
  if (!lhash)
669
0
    return gpg_err_code_from_syserror ();
670
0
  _gcry_md_hash_buffer (algo, lhash, label, labellen);
671
672
  /* Turn the MPI into an octet string.  If the octet string is
673
     shorter than the key we pad it to the left with zeroes.  This may
674
     happen due to the leading zero in OAEP frames and due to the
675
     following random octets (seed^mask) which may have leading zero
676
     bytes.  This all is needed to cope with our leading zeroes
677
     suppressing MPI implementation.  The code implictly implements
678
     Step 1b (bail out if NFRAME != N).  */
679
0
  rc = octet_string_from_mpi (&frame, NULL, value, nkey);
680
0
  if (rc)
681
0
    {
682
0
      xfree (lhash);
683
0
      return GPG_ERR_ENCODING_PROBLEM;
684
0
    }
685
0
  nframe = nkey;
686
687
  /* Step 1c: Check that the key is long enough.  */
688
0
  if ( nframe < 2 * hlen + 2 )
689
0
    {
690
0
      xfree (frame);
691
0
      xfree (lhash);
692
0
      return GPG_ERR_ENCODING_PROBLEM;
693
0
    }
694
695
  /* Step 2 has already been done by the caller and the
696
     gcry_mpi_aprint above.  */
697
698
  /* Allocate space for SEED and DB.  */
699
0
  seed = xtrymalloc_secure (nframe - 1);
700
0
  if (!seed)
701
0
    {
702
0
      rc = gpg_err_code_from_syserror ();
703
0
      xfree (frame);
704
0
      xfree (lhash);
705
0
      return rc;
706
0
    }
707
0
  db = seed + hlen;
708
709
  /* To avoid chosen ciphertext attacks from now on we make sure to
710
     run all code even in the error case; this avoids possible timing
711
     attacks as described by Manger.  */
712
713
  /* Step 3a: Hash the label.  */
714
  /* This has already been done.  */
715
716
  /* Step 3b: Separate the encoded message.  */
717
0
  masked_seed = frame + 1;
718
0
  masked_db   = frame + 1 + hlen;
719
0
  db_len      = nframe - 1 - hlen;
720
721
  /* Step 3c and 3d: seed = maskedSeed ^ mgf(maskedDB, hlen).  */
722
0
  failed |= (mgf1 (seed, hlen, masked_db, db_len, algo) != 0);
723
0
  for (n = 0; n < hlen; n++)
724
0
    seed[n] ^= masked_seed[n];
725
726
  /* Step 3e and 3f: db = maskedDB ^ mgf(seed, db_len).  */
727
0
  failed |= (mgf1 (db, db_len, seed, hlen, algo) != 0);
728
0
  for (n = 0; n < db_len; n++)
729
0
    db[n] ^= masked_db[n];
730
731
  /* Step 3g: Check lhash, an possible empty padding string terminated
732
     by 0x01 and the first byte of EM being 0.  */
733
0
  failed |= ct_not_memequal (lhash, db, hlen);
734
0
  for (n = n1 = hlen; n < db_len; n++)
735
0
    {
736
0
      not_found &= ct_not_equal_byte (db[n], 0x01);
737
0
      n1 += not_found;
738
0
    }
739
0
  failed |= not_found;
740
0
  failed |= ct_not_equal_byte (frame[0], 0x00);
741
742
0
  xfree (lhash);
743
0
  xfree (frame);
744
745
  /* Step 4: Output M.  */
746
  /* To avoid an extra allocation we reuse the seed buffer.  The only
747
     caller of this function will anyway free the result soon.  */
748
0
  n1 += !not_found;
749
0
  memmov_independently (seed, db + n1, db_len - n1, nframe - 1);
750
0
  *r_result = seed;
751
0
  *r_resultlen = db_len - n1;
752
0
  seed = NULL;
753
754
0
  if (DBG_CIPHER)
755
0
    log_printhex ("value extracted from OAEP encoded data",
756
0
                  *r_result, *r_resultlen);
757
758
0
  return (0U - failed) & GPG_ERR_ENCODING_PROBLEM;
759
0
}
760
761
762
/* RFC-3447 (pkcs#1 v2.1) PSS encoding.  Encode {VALUE,VALUELEN} for
763
   an NBITS key.  ALGO is a valid hash algorithm and SALTLEN is the
764
   length of salt to be used.  When HASHED_ALREADY is set, VALUE is
765
   already the mHash from the picture below.  Otherwise, VALUE is M.
766
767
   On success the result is stored as a new MPI at R_RESULT.  On error
768
   the value at R_RESULT is undefined.
769
770
   If RANDOM_OVERRIDE is given it is used as the salt instead of using
771
   a random string for the salt.  This feature is only useful for
772
   regression tests.
773
774
   Here is figure 2 from the RFC (errata 595 applied) depicting the
775
   process:
776
777
                                  +-----------+
778
                                  |     M     |
779
                                  +-----------+
780
                                        |
781
                                        V
782
                                      Hash
783
                                        |
784
                                        V
785
                          +--------+----------+----------+
786
                     M' = |Padding1|  mHash   |   salt   |
787
                          +--------+----------+----------+
788
                                         |
789
               +--------+----------+     V
790
         DB =  |Padding2| salt     |   Hash
791
               +--------+----------+     |
792
                         |               |
793
                         V               |    +----+
794
                        xor <--- MGF <---|    |0xbc|
795
                         |               |    +----+
796
                         |               |      |
797
                         V               V      V
798
               +-------------------+----------+----+
799
         EM =  |    maskedDB       |     H    |0xbc|
800
               +-------------------+----------+----+
801
802
  */
803
gpg_err_code_t
804
_gcry_rsa_pss_encode (gcry_mpi_t *r_result, unsigned int nbits, int algo,
805
                      int saltlen, int hashed_already,
806
                      const unsigned char *value, size_t valuelen,
807
                      const void *random_override)
808
0
{
809
0
  gcry_err_code_t rc = 0;
810
0
  gcry_md_hd_t hd = NULL;
811
0
  unsigned char *digest;
812
0
  size_t hlen;                 /* Length of the hash digest.  */
813
0
  unsigned char *em = NULL;    /* Encoded message.  */
814
0
  size_t emlen = (nbits+7)/8;  /* Length in bytes of EM.  */
815
0
  unsigned char *h;            /* Points into EM.  */
816
0
  unsigned char *buf = NULL;   /* Help buffer.  */
817
0
  size_t buflen;               /* Length of BUF.  */
818
0
  unsigned char *mhash;        /* Points into BUF.  */
819
0
  unsigned char *salt;         /* Points into BUF.  */
820
0
  unsigned char *dbmask;       /* Points into BUF.  */
821
0
  unsigned char *p;
822
0
  size_t n;
823
824
825
  /* This code is implemented as described by rfc-3447 9.1.1.  */
826
827
0
  rc = _gcry_md_open (&hd, algo, 0);
828
0
  if (rc)
829
0
    return rc;
830
831
  /* Get the length of the digest.  */
832
0
  if (algo == GCRY_MD_SHAKE128)
833
0
    hlen = 32;
834
0
  else if (algo == GCRY_MD_SHAKE256)
835
0
    hlen = 64;
836
0
  else
837
0
    hlen = _gcry_md_get_algo_dlen (algo);
838
0
  gcry_assert (hlen);  /* We expect a valid ALGO here.  */
839
840
  /* The FIPS 186-4 Section 5.5 allows only 0 <= sLen <= hLen */
841
0
  if (fips_mode () && saltlen > hlen)
842
0
    {
843
0
      rc = GPG_ERR_INV_ARG;
844
0
      goto leave;
845
0
    }
846
847
  /* Allocate a help buffer and setup some pointers.  */
848
0
  buflen = 8 + hlen + saltlen + (emlen - hlen - 1);
849
0
  buf = xtrymalloc (buflen);
850
0
  if (!buf)
851
0
    {
852
0
      rc = gpg_err_code_from_syserror ();
853
0
      goto leave;
854
0
    }
855
0
  mhash = buf + 8;
856
0
  salt  = mhash + hlen;
857
0
  dbmask= salt + saltlen;
858
859
  /* Step 2: mHash = Hash(M) (or copy input to mHash, if already hashed).   */
860
0
  if (!hashed_already)
861
0
    {
862
0
      _gcry_md_write (hd, value, valuelen);
863
0
      digest = _gcry_md_read (hd, 0);
864
0
      memcpy (mhash, digest, hlen);
865
0
      _gcry_md_reset (hd);
866
0
    }
867
0
  else
868
0
    {
869
0
      if (valuelen != hlen)
870
0
        {
871
0
          rc = GPG_ERR_INV_LENGTH;
872
0
          goto leave;
873
0
        }
874
0
      memcpy (mhash, value, hlen);
875
0
    }
876
877
  /* Step 3: Check length constraints.  */
878
0
  if (emlen < hlen + saltlen + 2)
879
0
    {
880
0
      rc = GPG_ERR_TOO_SHORT;
881
0
      goto leave;
882
0
    }
883
884
  /* Allocate space for EM.  */
885
0
  em = xtrymalloc (emlen);
886
0
  if (!em)
887
0
    {
888
0
      rc = gpg_err_code_from_syserror ();
889
0
      goto leave;
890
0
    }
891
0
  h = em + emlen - 1 - hlen;
892
893
  /* Step 4: Create a salt.  */
894
0
  if (saltlen)
895
0
    {
896
0
      if (random_override)
897
0
        memcpy (salt, random_override, saltlen);
898
0
      else
899
0
        _gcry_randomize (salt, saltlen, GCRY_STRONG_RANDOM);
900
0
    }
901
902
  /* Step 5 and 6: M' = Hash(Padding1 || mHash || salt).  */
903
0
  memset (buf, 0, 8);  /* Padding.  */
904
905
0
  _gcry_md_write (hd, buf, 8 + hlen + saltlen);
906
0
  digest = _gcry_md_read (hd, 0);
907
0
  memcpy (h, digest, hlen);
908
909
  /* Step 7 and 8: DB = PS || 0x01 || salt.  */
910
  /* Note that we use EM to store DB and later Xor in-place.  */
911
0
  p = em + emlen - 1 - hlen - saltlen - 1;
912
0
  memset (em, 0, p - em);
913
0
  *p++ = 0x01;
914
0
  memcpy (p, salt, saltlen);
915
916
  /* Step 9: dbmask = MGF(H, emlen - hlen - 1).  */
917
0
  if (algo == GCRY_MD_SHAKE128 || algo == GCRY_MD_SHAKE256)
918
0
    {
919
0
      gcry_buffer_t iov;
920
921
0
      iov.size = 0;
922
0
      iov.data = (void *)h;
923
0
      iov.off = 0;
924
0
      iov.len = hlen;
925
926
0
      _gcry_md_hash_buffers_extract (algo, 0, dbmask, emlen - hlen - 1,
927
0
                                     &iov, 1);
928
0
    }
929
0
  else
930
0
    mgf1 (dbmask, emlen - hlen - 1, h, hlen, algo);
931
932
  /* Step 10: maskedDB = DB ^ dbMask */
933
0
  for (n = 0, p = dbmask; n < emlen - hlen - 1; n++, p++)
934
0
    em[n] ^= *p;
935
936
  /* Step 11: Set the leftmost bits to zero.  */
937
0
  em[0] &= 0xFF >> (8 * emlen - nbits);
938
939
  /* Step 12: EM = maskedDB || H || 0xbc.  */
940
0
  em[emlen-1] = 0xbc;
941
942
  /* Convert EM into an MPI.  */
943
0
  rc = _gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, em, emlen, NULL);
944
0
  if (!rc && DBG_CIPHER)
945
0
    log_mpidump ("PSS encoded data", *r_result);
946
947
0
 leave:
948
0
  _gcry_md_close (hd);
949
0
  if (em)
950
0
    {
951
0
      wipememory (em, emlen);
952
0
      xfree (em);
953
0
    }
954
0
  if (buf)
955
0
    {
956
0
      wipememory (buf, buflen);
957
0
      xfree (buf);
958
0
    }
959
0
  return rc;
960
0
}
961
962
963
/* Verify a signature assuming PSS padding.  When HASHED_ALREADY is
964
   set, VALUE is the hash of the message (mHash); its length must
965
   match the digest length of ALGO.  Otherwise, its M (before mHash).
966
   VALUE is an opaque MPI.  ENCODED is the output of the RSA public
967
   key function (EM).  NBITS is the size of the public key.  ALGO is
968
   the hash algorithm and SALTLEN is the length of the used salt.  The
969
   function returns 0 on success or on error code.  */
970
gpg_err_code_t
971
_gcry_rsa_pss_verify (gcry_mpi_t value, int hashed_already,
972
                      gcry_mpi_t encoded,
973
                      unsigned int nbits, int algo, size_t saltlen)
974
0
{
975
0
  gcry_err_code_t rc = 0;
976
0
  gcry_md_hd_t hd = NULL;
977
0
  unsigned char *digest;
978
0
  size_t hlen;                 /* Length of the hash digest.  */
979
0
  unsigned char *em = NULL;    /* Encoded message.  */
980
0
  size_t emlen = (nbits+7)/8;  /* Length in bytes of EM.  */
981
0
  unsigned char *salt;         /* Points into EM.  */
982
0
  unsigned char *h;            /* Points into EM.  */
983
0
  unsigned char *buf = NULL;   /* Help buffer.  */
984
0
  size_t buflen;               /* Length of BUF.  */
985
0
  unsigned char *dbmask;       /* Points into BUF.  */
986
0
  unsigned char *mhash;        /* Points into BUF.  */
987
0
  unsigned char *p;
988
0
  size_t n;
989
0
  unsigned int input_nbits;
990
991
  /* This code is implemented as described by rfc-3447 9.1.2.  */
992
993
0
  rc = _gcry_md_open (&hd, algo, 0);
994
0
  if (rc)
995
0
    return rc;
996
997
  /* Get the length of the digest.  */
998
0
  if (algo == GCRY_MD_SHAKE128)
999
0
    hlen = 32;
1000
0
  else if (algo == GCRY_MD_SHAKE256)
1001
0
    hlen = 64;
1002
0
  else
1003
0
    hlen = _gcry_md_get_algo_dlen (algo);
1004
0
  gcry_assert (hlen);  /* We expect a valid ALGO here.  */
1005
1006
  /* The FIPS 186-4 Section 5.5 allows only 0 <= sLen <= hLen */
1007
0
  if (fips_mode () && saltlen > hlen)
1008
0
    {
1009
0
      rc = GPG_ERR_INV_ARG;
1010
0
      goto leave;
1011
0
    }
1012
1013
  /* Allocate a help buffer and setup some pointers.
1014
     This buffer is used for two purposes:
1015
        +------------------------------+-------+
1016
     1. | dbmask                       | mHash |
1017
        +------------------------------+-------+
1018
           emlen - hlen - 1              hlen
1019
1020
        +----------+-------+---------+-+-------+
1021
     2. | padding1 | mHash | salt    | | mHash |
1022
        +----------+-------+---------+-+-------+
1023
             8       hlen    saltlen     hlen
1024
  */
1025
0
  buflen = 8 + hlen + saltlen;
1026
0
  if (buflen < emlen - hlen - 1)
1027
0
    buflen = emlen - hlen - 1;
1028
0
  buflen += hlen;
1029
0
  buf = xtrymalloc (buflen);
1030
0
  if (!buf)
1031
0
    {
1032
0
      rc = gpg_err_code_from_syserror ();
1033
0
      goto leave;
1034
0
    }
1035
0
  dbmask = buf;
1036
0
  mhash = buf + buflen - hlen;
1037
1038
  /* Step 2: mHash = Hash(M) (or copy input to mHash, if already hashed).   */
1039
0
  p = mpi_get_opaque (value, &input_nbits);
1040
0
  if (!p)
1041
0
    {
1042
0
      rc = GPG_ERR_INV_ARG;
1043
0
      goto leave;
1044
0
    }
1045
1046
0
  if (!hashed_already)
1047
0
    {
1048
0
      _gcry_md_write (hd, p, (input_nbits+7)/8);
1049
0
      digest = _gcry_md_read (hd, 0);
1050
0
      memcpy (mhash, digest, hlen);
1051
0
      _gcry_md_reset (hd);
1052
0
    }
1053
0
  else
1054
0
    memcpy (mhash, p, hlen);
1055
1056
  /* Convert the signature into an octet string.  */
1057
0
  rc = octet_string_from_mpi (&em, NULL, encoded, emlen);
1058
0
  if (rc)
1059
0
    goto leave;
1060
1061
  /* Step 3: Check length of EM.  Because we internally use MPI
1062
     functions we can't do this properly; EMLEN is always the length
1063
     of the key because octet_string_from_mpi needs to left pad the
1064
     result with zero to cope with the fact that our MPIs suppress all
1065
     leading zeroes.  Thus what we test here are merely the digest and
1066
     salt lengths to the key.  */
1067
0
  if (emlen < hlen + saltlen + 2)
1068
0
    {
1069
0
      rc = GPG_ERR_TOO_SHORT; /* For the hash and saltlen.  */
1070
0
      goto leave;
1071
0
    }
1072
1073
  /* Step 4: Check last octet.  */
1074
0
  if (em[emlen - 1] != 0xbc)
1075
0
    {
1076
0
      rc = GPG_ERR_BAD_SIGNATURE;
1077
0
      goto leave;
1078
0
    }
1079
1080
  /* Step 5: Split EM.  */
1081
0
  h = em + emlen - 1 - hlen;
1082
1083
  /* Step 6: Check the leftmost bits.  */
1084
0
  if ((em[0] & ~(0xFF >> (8 * emlen - nbits))))
1085
0
    {
1086
0
      rc = GPG_ERR_BAD_SIGNATURE;
1087
0
      goto leave;
1088
0
    }
1089
1090
  /* Step 7: dbmask = MGF(H, emlen - hlen - 1).  */
1091
0
  if (algo == GCRY_MD_SHAKE128 || algo == GCRY_MD_SHAKE256)
1092
0
    {
1093
0
      gcry_buffer_t iov;
1094
1095
0
      iov.size = 0;
1096
0
      iov.data = (void *)h;
1097
0
      iov.off = 0;
1098
0
      iov.len = hlen;
1099
1100
0
      _gcry_md_hash_buffers_extract (algo, 0, dbmask, emlen - hlen - 1,
1101
0
                                     &iov, 1);
1102
0
    }
1103
0
  else
1104
0
    mgf1 (dbmask, emlen - hlen - 1, h, hlen, algo);
1105
1106
  /* Step 8: maskedDB = DB ^ dbMask.  */
1107
0
  for (n = 0, p = dbmask; n < emlen - hlen - 1; n++, p++)
1108
0
    em[n] ^= *p;
1109
1110
  /* Step 9: Set leftmost bits in DB to zero.  */
1111
0
  em[0] &= 0xFF >> (8 * emlen - nbits);
1112
1113
  /* Step 10: Check the padding of DB.  */
1114
0
  for (n = 0; n < emlen - hlen - saltlen - 2 && !em[n]; n++)
1115
0
    ;
1116
0
  if (n != emlen - hlen - saltlen - 2 || em[n++] != 1)
1117
0
    {
1118
0
      rc = GPG_ERR_BAD_SIGNATURE;
1119
0
      goto leave;
1120
0
    }
1121
1122
  /* Step 11: Extract salt from DB.  */
1123
0
  salt = em + n;
1124
1125
  /* Step 12:  M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */
1126
0
  memset (buf, 0, 8);
1127
0
  memcpy (buf+8, mhash, hlen);
1128
0
  memcpy (buf+8+hlen, salt, saltlen);
1129
1130
  /* Step 13:  H' = Hash(M').  */
1131
0
  _gcry_md_write (hd, buf, 8 + hlen + saltlen);
1132
0
  digest = _gcry_md_read (hd, 0);
1133
0
  memcpy (buf, digest, hlen);
1134
1135
  /* Step 14:  Check H == H'.   */
1136
0
  rc = memcmp (h, buf, hlen) ? GPG_ERR_BAD_SIGNATURE : GPG_ERR_NO_ERROR;
1137
1138
0
 leave:
1139
0
  _gcry_md_close (hd);
1140
0
  if (em)
1141
0
    {
1142
0
      wipememory (em, emlen);
1143
0
      xfree (em);
1144
0
    }
1145
0
  if (buf)
1146
0
    {
1147
0
      wipememory (buf, buflen);
1148
0
      xfree (buf);
1149
0
    }
1150
0
  return rc;
1151
0
}