Debian Codegraph @

cipher/rsa-common.c

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