1 /*
2 * The RSA public-key cryptosystem
3 *
4 * Copyright The Mbed TLS Contributors
5 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6 */
7
8 /*
9 * The following sources were referenced in the design of this implementation
10 * of the RSA algorithm:
11 *
12 * [1] A method for obtaining digital signatures and public-key cryptosystems
13 * R Rivest, A Shamir, and L Adleman
14 * http://people.csail.mit.edu/rivest/pubs.html#RSA78
15 *
16 * [2] Handbook of Applied Cryptography - 1997, Chapter 8
17 * Menezes, van Oorschot and Vanstone
18 *
19 * [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks
20 * Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and
21 * Stefan Mangard
22 * https://arxiv.org/abs/1702.08719v2
23 *
24 */
25
26 #include "common.h"
27
28 #if defined(MBEDTLS_RSA_C)
29
30 #include "mbedtls/rsa.h"
31 #include "bignum_core.h"
32 #include "bignum_internal.h"
33 #include "rsa_alt_helpers.h"
34 #include "rsa_internal.h"
35 #include "mbedtls/oid.h"
36 #include "mbedtls/asn1write.h"
37 #include "mbedtls/platform_util.h"
38 #include "mbedtls/error.h"
39 #include "constant_time_internal.h"
40 #include "mbedtls/constant_time.h"
41 #include "md_psa.h"
42
43 #include <string.h>
44
45 #if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__) && !defined(__NetBSD__)
46 #include <stdlib.h>
47 #endif
48
49 #include "mbedtls/platform.h"
50
51 #include <fault_mitigation.h>
52
53 /*
54 * Wrapper around mbedtls_asn1_get_mpi() that rejects zero.
55 *
56 * The value zero is:
57 * - never a valid value for an RSA parameter
58 * - interpreted as "omitted, please reconstruct" by mbedtls_rsa_complete().
59 *
60 * Since values can't be omitted in PKCS#1, passing a zero value to
61 * rsa_complete() would be incorrect, so reject zero values early.
62 */
asn1_get_nonzero_mpi(unsigned char ** p,const unsigned char * end,mbedtls_mpi * X)63 static int asn1_get_nonzero_mpi(unsigned char **p,
64 const unsigned char *end,
65 mbedtls_mpi *X)
66 {
67 int ret;
68
69 ret = mbedtls_asn1_get_mpi(p, end, X);
70 if (ret != 0) {
71 return ret;
72 }
73
74 if (mbedtls_mpi_cmp_int(X, 0) == 0) {
75 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
76 }
77
78 return 0;
79 }
80
mbedtls_rsa_parse_key(mbedtls_rsa_context * rsa,const unsigned char * key,size_t keylen)81 int mbedtls_rsa_parse_key(mbedtls_rsa_context *rsa, const unsigned char *key, size_t keylen)
82 {
83 int ret, version;
84 size_t len;
85 unsigned char *p, *end;
86
87 mbedtls_mpi T;
88 mbedtls_mpi_init(&T);
89
90 p = (unsigned char *) key;
91 end = p + keylen;
92
93 /*
94 * This function parses the RSAPrivateKey (PKCS#1)
95 *
96 * RSAPrivateKey ::= SEQUENCE {
97 * version Version,
98 * modulus INTEGER, -- n
99 * publicExponent INTEGER, -- e
100 * privateExponent INTEGER, -- d
101 * prime1 INTEGER, -- p
102 * prime2 INTEGER, -- q
103 * exponent1 INTEGER, -- d mod (p-1)
104 * exponent2 INTEGER, -- d mod (q-1)
105 * coefficient INTEGER, -- (inverse of q) mod p
106 * otherPrimeInfos OtherPrimeInfos OPTIONAL
107 * }
108 */
109 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
110 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
111 return ret;
112 }
113
114 if (end != p + len) {
115 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
116 }
117
118 if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
119 return ret;
120 }
121
122 if (version != 0) {
123 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
124 }
125
126 /* Import N */
127 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
128 (ret = mbedtls_rsa_import(rsa, &T, NULL, NULL,
129 NULL, NULL)) != 0) {
130 goto cleanup;
131 }
132
133 /* Import E */
134 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
135 (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
136 NULL, &T)) != 0) {
137 goto cleanup;
138 }
139
140 /* Import D */
141 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
142 (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
143 &T, NULL)) != 0) {
144 goto cleanup;
145 }
146
147 /* Import P */
148 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
149 (ret = mbedtls_rsa_import(rsa, NULL, &T, NULL,
150 NULL, NULL)) != 0) {
151 goto cleanup;
152 }
153
154 /* Import Q */
155 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
156 (ret = mbedtls_rsa_import(rsa, NULL, NULL, &T,
157 NULL, NULL)) != 0) {
158 goto cleanup;
159 }
160
161 #if !defined(MBEDTLS_RSA_NO_CRT) && !defined(MBEDTLS_RSA_ALT)
162 /*
163 * The RSA CRT parameters DP, DQ and QP are nominally redundant, in
164 * that they can be easily recomputed from D, P and Q. However by
165 * parsing them from the PKCS1 structure it is possible to avoid
166 * recalculating them which both reduces the overhead of loading
167 * RSA private keys into memory and also avoids side channels which
168 * can arise when computing those values, since all of D, P, and Q
169 * are secret. See https://eprint.iacr.org/2020/055 for a
170 * description of one such attack.
171 */
172
173 /* Import DP */
174 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
175 (ret = mbedtls_mpi_copy(&rsa->DP, &T)) != 0) {
176 goto cleanup;
177 }
178
179 /* Import DQ */
180 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
181 (ret = mbedtls_mpi_copy(&rsa->DQ, &T)) != 0) {
182 goto cleanup;
183 }
184
185 /* Import QP */
186 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
187 (ret = mbedtls_mpi_copy(&rsa->QP, &T)) != 0) {
188 goto cleanup;
189 }
190
191 #else
192 /* Verify existence of the CRT params */
193 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
194 (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
195 (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0) {
196 goto cleanup;
197 }
198 #endif
199
200 /* rsa_complete() doesn't complete anything with the default
201 * implementation but is still called:
202 * - for the benefit of alternative implementation that may want to
203 * pre-compute stuff beyond what's provided (eg Montgomery factors)
204 * - as is also sanity-checks the key
205 *
206 * Furthermore, we also check the public part for consistency with
207 * mbedtls_pk_parse_pubkey(), as it includes size minima for example.
208 */
209 if ((ret = mbedtls_rsa_complete(rsa)) != 0 ||
210 (ret = mbedtls_rsa_check_pubkey(rsa)) != 0) {
211 goto cleanup;
212 }
213
214 if (p != end) {
215 ret = MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
216 }
217
218 cleanup:
219
220 mbedtls_mpi_free(&T);
221
222 if (ret != 0) {
223 mbedtls_rsa_free(rsa);
224 }
225
226 return ret;
227 }
228
mbedtls_rsa_parse_pubkey(mbedtls_rsa_context * rsa,const unsigned char * key,size_t keylen)229 int mbedtls_rsa_parse_pubkey(mbedtls_rsa_context *rsa, const unsigned char *key, size_t keylen)
230 {
231 unsigned char *p = (unsigned char *) key;
232 unsigned char *end = (unsigned char *) (key + keylen);
233 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
234 size_t len;
235
236 /*
237 * RSAPublicKey ::= SEQUENCE {
238 * modulus INTEGER, -- n
239 * publicExponent INTEGER -- e
240 * }
241 */
242
243 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
244 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
245 return ret;
246 }
247
248 if (end != p + len) {
249 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
250 }
251
252 /* Import N */
253 if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
254 return ret;
255 }
256
257 if ((ret = mbedtls_rsa_import_raw(rsa, p, len, NULL, 0, NULL, 0,
258 NULL, 0, NULL, 0)) != 0) {
259 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
260 }
261
262 p += len;
263
264 /* Import E */
265 if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
266 return ret;
267 }
268
269 if ((ret = mbedtls_rsa_import_raw(rsa, NULL, 0, NULL, 0, NULL, 0,
270 NULL, 0, p, len)) != 0) {
271 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
272 }
273
274 p += len;
275
276 if (mbedtls_rsa_complete(rsa) != 0 ||
277 mbedtls_rsa_check_pubkey(rsa) != 0) {
278 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
279 }
280
281 if (p != end) {
282 return MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
283 }
284
285 return 0;
286 }
287
mbedtls_rsa_write_key(const mbedtls_rsa_context * rsa,unsigned char * start,unsigned char ** p)288 int mbedtls_rsa_write_key(const mbedtls_rsa_context *rsa, unsigned char *start,
289 unsigned char **p)
290 {
291 size_t len = 0;
292 int ret;
293
294 mbedtls_mpi T; /* Temporary holding the exported parameters */
295
296 /*
297 * Export the parameters one after another to avoid simultaneous copies.
298 */
299
300 mbedtls_mpi_init(&T);
301
302 /* Export QP */
303 if ((ret = mbedtls_rsa_export_crt(rsa, NULL, NULL, &T)) != 0 ||
304 (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
305 goto end_of_export;
306 }
307 len += ret;
308
309 /* Export DQ */
310 if ((ret = mbedtls_rsa_export_crt(rsa, NULL, &T, NULL)) != 0 ||
311 (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
312 goto end_of_export;
313 }
314 len += ret;
315
316 /* Export DP */
317 if ((ret = mbedtls_rsa_export_crt(rsa, &T, NULL, NULL)) != 0 ||
318 (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
319 goto end_of_export;
320 }
321 len += ret;
322
323 /* Export Q */
324 if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, &T, NULL, NULL)) != 0 ||
325 (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
326 goto end_of_export;
327 }
328 len += ret;
329
330 /* Export P */
331 if ((ret = mbedtls_rsa_export(rsa, NULL, &T, NULL, NULL, NULL)) != 0 ||
332 (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
333 goto end_of_export;
334 }
335 len += ret;
336
337 /* Export D */
338 if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, &T, NULL)) != 0 ||
339 (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
340 goto end_of_export;
341 }
342 len += ret;
343
344 /* Export E */
345 if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, NULL, &T)) != 0 ||
346 (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
347 goto end_of_export;
348 }
349 len += ret;
350
351 /* Export N */
352 if ((ret = mbedtls_rsa_export(rsa, &T, NULL, NULL, NULL, NULL)) != 0 ||
353 (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
354 goto end_of_export;
355 }
356 len += ret;
357
358 end_of_export:
359
360 mbedtls_mpi_free(&T);
361 if (ret < 0) {
362 return ret;
363 }
364
365 MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_int(p, start, 0));
366 MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
367 MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start,
368 MBEDTLS_ASN1_CONSTRUCTED |
369 MBEDTLS_ASN1_SEQUENCE));
370
371 return (int) len;
372 }
373
374 /*
375 * RSAPublicKey ::= SEQUENCE {
376 * modulus INTEGER, -- n
377 * publicExponent INTEGER -- e
378 * }
379 */
mbedtls_rsa_write_pubkey(const mbedtls_rsa_context * rsa,unsigned char * start,unsigned char ** p)380 int mbedtls_rsa_write_pubkey(const mbedtls_rsa_context *rsa, unsigned char *start,
381 unsigned char **p)
382 {
383 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
384 size_t len = 0;
385 mbedtls_mpi T;
386
387 mbedtls_mpi_init(&T);
388
389 /* Export E */
390 if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, NULL, &T)) != 0 ||
391 (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
392 goto end_of_export;
393 }
394 len += ret;
395
396 /* Export N */
397 if ((ret = mbedtls_rsa_export(rsa, &T, NULL, NULL, NULL, NULL)) != 0 ||
398 (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
399 goto end_of_export;
400 }
401 len += ret;
402
403 end_of_export:
404
405 mbedtls_mpi_free(&T);
406 if (ret < 0) {
407 return ret;
408 }
409
410 MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
411 MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start, MBEDTLS_ASN1_CONSTRUCTED |
412 MBEDTLS_ASN1_SEQUENCE));
413
414 return (int) len;
415 }
416
417 #if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
418
419 /** This function performs the unpadding part of a PKCS#1 v1.5 decryption
420 * operation (EME-PKCS1-v1_5 decoding).
421 *
422 * \note The return value from this function is a sensitive value
423 * (this is unusual). #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE shouldn't happen
424 * in a well-written application, but 0 vs #MBEDTLS_ERR_RSA_INVALID_PADDING
425 * is often a situation that an attacker can provoke and leaking which
426 * one is the result is precisely the information the attacker wants.
427 *
428 * \param input The input buffer which is the payload inside PKCS#1v1.5
429 * encryption padding, called the "encoded message EM"
430 * by the terminology.
431 * \param ilen The length of the payload in the \p input buffer.
432 * \param output The buffer for the payload, called "message M" by the
433 * PKCS#1 terminology. This must be a writable buffer of
434 * length \p output_max_len bytes.
435 * \param olen The address at which to store the length of
436 * the payload. This must not be \c NULL.
437 * \param output_max_len The length in bytes of the output buffer \p output.
438 *
439 * \return \c 0 on success.
440 * \return #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE
441 * The output buffer is too small for the unpadded payload.
442 * \return #MBEDTLS_ERR_RSA_INVALID_PADDING
443 * The input doesn't contain properly formatted padding.
444 */
mbedtls_ct_rsaes_pkcs1_v15_unpadding(unsigned char * input,size_t ilen,unsigned char * output,size_t output_max_len,size_t * olen)445 static int mbedtls_ct_rsaes_pkcs1_v15_unpadding(unsigned char *input,
446 size_t ilen,
447 unsigned char *output,
448 size_t output_max_len,
449 size_t *olen)
450 {
451 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
452 size_t i, plaintext_max_size;
453
454 /* The following variables take sensitive values: their value must
455 * not leak into the observable behavior of the function other than
456 * the designated outputs (output, olen, return value). Otherwise
457 * this would open the execution of the function to
458 * side-channel-based variants of the Bleichenbacher padding oracle
459 * attack. Potential side channels include overall timing, memory
460 * access patterns (especially visible to an adversary who has access
461 * to a shared memory cache), and branches (especially visible to
462 * an adversary who has access to a shared code cache or to a shared
463 * branch predictor). */
464 size_t pad_count = 0;
465 mbedtls_ct_condition_t bad;
466 mbedtls_ct_condition_t pad_done;
467 size_t plaintext_size = 0;
468 mbedtls_ct_condition_t output_too_large;
469
470 plaintext_max_size = (output_max_len > ilen - 11) ? ilen - 11
471 : output_max_len;
472
473 /* Check and get padding length in constant time and constant
474 * memory trace. The first byte must be 0. */
475 bad = mbedtls_ct_bool(input[0]);
476
477
478 /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
479 * where PS must be at least 8 nonzero bytes. */
480 bad = mbedtls_ct_bool_or(bad, mbedtls_ct_uint_ne(input[1], MBEDTLS_RSA_CRYPT));
481
482 /* Read the whole buffer. Set pad_done to nonzero if we find
483 * the 0x00 byte and remember the padding length in pad_count. */
484 pad_done = MBEDTLS_CT_FALSE;
485 for (i = 2; i < ilen; i++) {
486 mbedtls_ct_condition_t found = mbedtls_ct_uint_eq(input[i], 0);
487 pad_done = mbedtls_ct_bool_or(pad_done, found);
488 pad_count += mbedtls_ct_uint_if_else_0(mbedtls_ct_bool_not(pad_done), 1);
489 }
490
491 /* If pad_done is still zero, there's no data, only unfinished padding. */
492 bad = mbedtls_ct_bool_or(bad, mbedtls_ct_bool_not(pad_done));
493
494 /* There must be at least 8 bytes of padding. */
495 bad = mbedtls_ct_bool_or(bad, mbedtls_ct_uint_gt(8, pad_count));
496
497 /* If the padding is valid, set plaintext_size to the number of
498 * remaining bytes after stripping the padding. If the padding
499 * is invalid, avoid leaking this fact through the size of the
500 * output: use the maximum message size that fits in the output
501 * buffer. Do it without branches to avoid leaking the padding
502 * validity through timing. RSA keys are small enough that all the
503 * size_t values involved fit in unsigned int. */
504 plaintext_size = mbedtls_ct_uint_if(
505 bad, (unsigned) plaintext_max_size,
506 (unsigned) (ilen - pad_count - 3));
507
508 /* Set output_too_large to 0 if the plaintext fits in the output
509 * buffer and to 1 otherwise. */
510 output_too_large = mbedtls_ct_uint_gt(plaintext_size,
511 plaintext_max_size);
512
513 /* Set ret without branches to avoid timing attacks. Return:
514 * - INVALID_PADDING if the padding is bad (bad != 0).
515 * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
516 * plaintext does not fit in the output buffer.
517 * - 0 if the padding is correct. */
518 ret = mbedtls_ct_error_if(
519 bad,
520 MBEDTLS_ERR_RSA_INVALID_PADDING,
521 mbedtls_ct_error_if_else_0(output_too_large, MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE)
522 );
523
524 /* If the padding is bad or the plaintext is too large, zero the
525 * data that we're about to copy to the output buffer.
526 * We need to copy the same amount of data
527 * from the same buffer whether the padding is good or not to
528 * avoid leaking the padding validity through overall timing or
529 * through memory or cache access patterns. */
530 mbedtls_ct_zeroize_if(mbedtls_ct_bool_or(bad, output_too_large), input + 11, ilen - 11);
531
532 /* If the plaintext is too large, truncate it to the buffer size.
533 * Copy anyway to avoid revealing the length through timing, because
534 * revealing the length is as bad as revealing the padding validity
535 * for a Bleichenbacher attack. */
536 plaintext_size = mbedtls_ct_uint_if(output_too_large,
537 (unsigned) plaintext_max_size,
538 (unsigned) plaintext_size);
539
540 /* Move the plaintext to the leftmost position where it can start in
541 * the working buffer, i.e. make it start plaintext_max_size from
542 * the end of the buffer. Do this with a memory access trace that
543 * does not depend on the plaintext size. After this move, the
544 * starting location of the plaintext is no longer sensitive
545 * information. */
546 mbedtls_ct_memmove_left(input + ilen - plaintext_max_size,
547 plaintext_max_size,
548 plaintext_max_size - plaintext_size);
549
550 /* Finally copy the decrypted plaintext plus trailing zeros into the output
551 * buffer. If output_max_len is 0, then output may be an invalid pointer
552 * and the result of memcpy() would be undefined; prevent undefined
553 * behavior making sure to depend only on output_max_len (the size of the
554 * user-provided output buffer), which is independent from plaintext
555 * length, validity of padding, success of the decryption, and other
556 * secrets. */
557 if (output_max_len != 0) {
558 memcpy(output, input + ilen - plaintext_max_size, plaintext_max_size);
559 }
560
561 /* Report the amount of data we copied to the output buffer. In case
562 * of errors (bad padding or output too large), the value of *olen
563 * when this function returns is not specified. Making it equivalent
564 * to the good case limits the risks of leaking the padding validity. */
565 *olen = plaintext_size;
566
567 return ret;
568 }
569
570 #endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
571
572 #if !defined(MBEDTLS_RSA_ALT)
573
mbedtls_rsa_import(mbedtls_rsa_context * ctx,const mbedtls_mpi * N,const mbedtls_mpi * P,const mbedtls_mpi * Q,const mbedtls_mpi * D,const mbedtls_mpi * E)574 int mbedtls_rsa_import(mbedtls_rsa_context *ctx,
575 const mbedtls_mpi *N,
576 const mbedtls_mpi *P, const mbedtls_mpi *Q,
577 const mbedtls_mpi *D, const mbedtls_mpi *E)
578 {
579 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
580
581 if ((N != NULL && (ret = mbedtls_mpi_copy(&ctx->N, N)) != 0) ||
582 (P != NULL && (ret = mbedtls_mpi_copy(&ctx->P, P)) != 0) ||
583 (Q != NULL && (ret = mbedtls_mpi_copy(&ctx->Q, Q)) != 0) ||
584 (D != NULL && (ret = mbedtls_mpi_copy(&ctx->D, D)) != 0) ||
585 (E != NULL && (ret = mbedtls_mpi_copy(&ctx->E, E)) != 0)) {
586 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
587 }
588
589 if (N != NULL) {
590 ctx->len = mbedtls_mpi_size(&ctx->N);
591 }
592
593 return 0;
594 }
595
mbedtls_rsa_import_raw(mbedtls_rsa_context * ctx,unsigned char const * N,size_t N_len,unsigned char const * P,size_t P_len,unsigned char const * Q,size_t Q_len,unsigned char const * D,size_t D_len,unsigned char const * E,size_t E_len)596 int mbedtls_rsa_import_raw(mbedtls_rsa_context *ctx,
597 unsigned char const *N, size_t N_len,
598 unsigned char const *P, size_t P_len,
599 unsigned char const *Q, size_t Q_len,
600 unsigned char const *D, size_t D_len,
601 unsigned char const *E, size_t E_len)
602 {
603 int ret = 0;
604
605 if (N != NULL) {
606 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->N, N, N_len));
607 ctx->len = mbedtls_mpi_size(&ctx->N);
608 }
609
610 if (P != NULL) {
611 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->P, P, P_len));
612 }
613
614 if (Q != NULL) {
615 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->Q, Q, Q_len));
616 }
617
618 if (D != NULL) {
619 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->D, D, D_len));
620 }
621
622 if (E != NULL) {
623 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->E, E, E_len));
624 }
625
626 cleanup:
627
628 if (ret != 0) {
629 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
630 }
631
632 return 0;
633 }
634
635 /*
636 * Checks whether the context fields are set in such a way
637 * that the RSA primitives will be able to execute without error.
638 * It does *not* make guarantees for consistency of the parameters.
639 */
rsa_check_context(mbedtls_rsa_context const * ctx,int is_priv,int blinding_needed)640 static int rsa_check_context(mbedtls_rsa_context const *ctx, int is_priv,
641 int blinding_needed)
642 {
643 #if !defined(MBEDTLS_RSA_NO_CRT)
644 /* blinding_needed is only used for NO_CRT to decide whether
645 * P,Q need to be present or not. */
646 ((void) blinding_needed);
647 #endif
648
649 if (ctx->len != mbedtls_mpi_size(&ctx->N) ||
650 ctx->len > MBEDTLS_MPI_MAX_SIZE) {
651 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
652 }
653
654 /*
655 * 1. Modular exponentiation needs positive, odd moduli.
656 */
657
658 /* Modular exponentiation wrt. N is always used for
659 * RSA public key operations. */
660 if (mbedtls_mpi_cmp_int(&ctx->N, 0) <= 0 ||
661 mbedtls_mpi_get_bit(&ctx->N, 0) == 0) {
662 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
663 }
664
665 #if !defined(MBEDTLS_RSA_NO_CRT)
666 /* Modular exponentiation for P and Q is only
667 * used for private key operations and if CRT
668 * is used. */
669 if (is_priv &&
670 (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
671 mbedtls_mpi_get_bit(&ctx->P, 0) == 0 ||
672 mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0 ||
673 mbedtls_mpi_get_bit(&ctx->Q, 0) == 0)) {
674 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
675 }
676 #endif /* !MBEDTLS_RSA_NO_CRT */
677
678 /*
679 * 2. Exponents must be positive
680 */
681
682 /* Always need E for public key operations */
683 if (mbedtls_mpi_cmp_int(&ctx->E, 0) <= 0) {
684 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
685 }
686
687 #if defined(MBEDTLS_RSA_NO_CRT)
688 /* For private key operations, use D or DP & DQ
689 * as (unblinded) exponents. */
690 if (is_priv && mbedtls_mpi_cmp_int(&ctx->D, 0) <= 0) {
691 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
692 }
693 #else
694 if (is_priv &&
695 (mbedtls_mpi_cmp_int(&ctx->DP, 0) <= 0 ||
696 mbedtls_mpi_cmp_int(&ctx->DQ, 0) <= 0)) {
697 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
698 }
699 #endif /* MBEDTLS_RSA_NO_CRT */
700
701 /* Blinding shouldn't make exponents negative either,
702 * so check that P, Q >= 1 if that hasn't yet been
703 * done as part of 1. */
704 #if defined(MBEDTLS_RSA_NO_CRT)
705 if (is_priv && blinding_needed &&
706 (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
707 mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0)) {
708 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
709 }
710 #endif
711
712 /* It wouldn't lead to an error if it wasn't satisfied,
713 * but check for QP >= 1 nonetheless. */
714 #if !defined(MBEDTLS_RSA_NO_CRT)
715 if (is_priv &&
716 mbedtls_mpi_cmp_int(&ctx->QP, 0) <= 0) {
717 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
718 }
719 #endif
720
721 return 0;
722 }
723
mbedtls_rsa_complete(mbedtls_rsa_context * ctx)724 int mbedtls_rsa_complete(mbedtls_rsa_context *ctx)
725 {
726 int ret = 0;
727 int have_N, have_P, have_Q, have_D, have_E;
728 #if !defined(MBEDTLS_RSA_NO_CRT)
729 int have_DP, have_DQ, have_QP;
730 #endif
731 int n_missing, pq_missing, d_missing, is_pub, is_priv;
732
733 have_N = (mbedtls_mpi_cmp_int(&ctx->N, 0) != 0);
734 have_P = (mbedtls_mpi_cmp_int(&ctx->P, 0) != 0);
735 have_Q = (mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0);
736 have_D = (mbedtls_mpi_cmp_int(&ctx->D, 0) != 0);
737 have_E = (mbedtls_mpi_cmp_int(&ctx->E, 0) != 0);
738
739 #if !defined(MBEDTLS_RSA_NO_CRT)
740 have_DP = (mbedtls_mpi_cmp_int(&ctx->DP, 0) != 0);
741 have_DQ = (mbedtls_mpi_cmp_int(&ctx->DQ, 0) != 0);
742 have_QP = (mbedtls_mpi_cmp_int(&ctx->QP, 0) != 0);
743 #endif
744
745 /*
746 * Check whether provided parameters are enough
747 * to deduce all others. The following incomplete
748 * parameter sets for private keys are supported:
749 *
750 * (1) P, Q missing.
751 * (2) D and potentially N missing.
752 *
753 */
754
755 n_missing = have_P && have_Q && have_D && have_E;
756 pq_missing = have_N && !have_P && !have_Q && have_D && have_E;
757 d_missing = have_P && have_Q && !have_D && have_E;
758 is_pub = have_N && !have_P && !have_Q && !have_D && have_E;
759
760 /* These three alternatives are mutually exclusive */
761 is_priv = n_missing || pq_missing || d_missing;
762
763 if (!is_priv && !is_pub) {
764 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
765 }
766
767 /*
768 * Step 1: Deduce N if P, Q are provided.
769 */
770
771 if (!have_N && have_P && have_Q) {
772 if ((ret = mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P,
773 &ctx->Q)) != 0) {
774 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
775 }
776
777 ctx->len = mbedtls_mpi_size(&ctx->N);
778 }
779
780 /*
781 * Step 2: Deduce and verify all remaining core parameters.
782 */
783
784 if (pq_missing) {
785 ret = mbedtls_rsa_deduce_primes(&ctx->N, &ctx->E, &ctx->D,
786 &ctx->P, &ctx->Q);
787 if (ret != 0) {
788 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
789 }
790
791 } else if (d_missing) {
792 if ((ret = mbedtls_rsa_deduce_private_exponent(&ctx->P,
793 &ctx->Q,
794 &ctx->E,
795 &ctx->D)) != 0) {
796 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
797 }
798 }
799
800 /*
801 * Step 3: Deduce all additional parameters specific
802 * to our current RSA implementation.
803 */
804
805 #if !defined(MBEDTLS_RSA_NO_CRT)
806 if (is_priv && !(have_DP && have_DQ && have_QP)) {
807 ret = mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
808 &ctx->DP, &ctx->DQ, &ctx->QP);
809 if (ret != 0) {
810 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
811 }
812 }
813 #endif /* MBEDTLS_RSA_NO_CRT */
814
815 /*
816 * Step 3: Basic sanity checks
817 */
818
819 return rsa_check_context(ctx, is_priv, 1);
820 }
821
mbedtls_rsa_export_raw(const mbedtls_rsa_context * ctx,unsigned char * N,size_t N_len,unsigned char * P,size_t P_len,unsigned char * Q,size_t Q_len,unsigned char * D,size_t D_len,unsigned char * E,size_t E_len)822 int mbedtls_rsa_export_raw(const mbedtls_rsa_context *ctx,
823 unsigned char *N, size_t N_len,
824 unsigned char *P, size_t P_len,
825 unsigned char *Q, size_t Q_len,
826 unsigned char *D, size_t D_len,
827 unsigned char *E, size_t E_len)
828 {
829 int ret = 0;
830 int is_priv;
831
832 /* Check if key is private or public */
833 is_priv =
834 mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
835 mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
836 mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
837 mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
838 mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
839
840 if (!is_priv) {
841 /* If we're trying to export private parameters for a public key,
842 * something must be wrong. */
843 if (P != NULL || Q != NULL || D != NULL) {
844 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
845 }
846
847 }
848
849 if (N != NULL) {
850 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->N, N, N_len));
851 }
852
853 if (P != NULL) {
854 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->P, P, P_len));
855 }
856
857 if (Q != NULL) {
858 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->Q, Q, Q_len));
859 }
860
861 if (D != NULL) {
862 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->D, D, D_len));
863 }
864
865 if (E != NULL) {
866 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->E, E, E_len));
867 }
868
869 cleanup:
870
871 return ret;
872 }
873
mbedtls_rsa_export(const mbedtls_rsa_context * ctx,mbedtls_mpi * N,mbedtls_mpi * P,mbedtls_mpi * Q,mbedtls_mpi * D,mbedtls_mpi * E)874 int mbedtls_rsa_export(const mbedtls_rsa_context *ctx,
875 mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
876 mbedtls_mpi *D, mbedtls_mpi *E)
877 {
878 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
879 int is_priv;
880
881 /* Check if key is private or public */
882 is_priv =
883 mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
884 mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
885 mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
886 mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
887 mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
888
889 if (!is_priv) {
890 /* If we're trying to export private parameters for a public key,
891 * something must be wrong. */
892 if (P != NULL || Q != NULL || D != NULL) {
893 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
894 }
895
896 }
897
898 /* Export all requested core parameters. */
899
900 if ((N != NULL && (ret = mbedtls_mpi_copy(N, &ctx->N)) != 0) ||
901 (P != NULL && (ret = mbedtls_mpi_copy(P, &ctx->P)) != 0) ||
902 (Q != NULL && (ret = mbedtls_mpi_copy(Q, &ctx->Q)) != 0) ||
903 (D != NULL && (ret = mbedtls_mpi_copy(D, &ctx->D)) != 0) ||
904 (E != NULL && (ret = mbedtls_mpi_copy(E, &ctx->E)) != 0)) {
905 return ret;
906 }
907
908 return 0;
909 }
910
911 /*
912 * Export CRT parameters
913 * This must also be implemented if CRT is not used, for being able to
914 * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt
915 * can be used in this case.
916 */
mbedtls_rsa_export_crt(const mbedtls_rsa_context * ctx,mbedtls_mpi * DP,mbedtls_mpi * DQ,mbedtls_mpi * QP)917 int mbedtls_rsa_export_crt(const mbedtls_rsa_context *ctx,
918 mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP)
919 {
920 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
921 int is_priv;
922
923 /* Check if key is private or public */
924 is_priv =
925 mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
926 mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
927 mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
928 mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
929 mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
930
931 if (!is_priv) {
932 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
933 }
934
935 #if !defined(MBEDTLS_RSA_NO_CRT)
936 /* Export all requested blinding parameters. */
937 if ((DP != NULL && (ret = mbedtls_mpi_copy(DP, &ctx->DP)) != 0) ||
938 (DQ != NULL && (ret = mbedtls_mpi_copy(DQ, &ctx->DQ)) != 0) ||
939 (QP != NULL && (ret = mbedtls_mpi_copy(QP, &ctx->QP)) != 0)) {
940 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
941 }
942 #else
943 if ((ret = mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
944 DP, DQ, QP)) != 0) {
945 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
946 }
947 #endif
948
949 return 0;
950 }
951
952 /*
953 * Initialize an RSA context
954 */
mbedtls_rsa_init(mbedtls_rsa_context * ctx)955 void mbedtls_rsa_init(mbedtls_rsa_context *ctx)
956 {
957 memset(ctx, 0, sizeof(mbedtls_rsa_context));
958
959 ctx->padding = MBEDTLS_RSA_PKCS_V15;
960 ctx->hash_id = MBEDTLS_MD_NONE;
961
962 #if defined(MBEDTLS_THREADING_C)
963 /* Set ctx->ver to nonzero to indicate that the mutex has been
964 * initialized and will need to be freed. */
965 ctx->ver = 1;
966 mbedtls_mutex_init(&ctx->mutex);
967 #endif
968 }
969
970 /*
971 * Set padding for an existing RSA context
972 */
mbedtls_rsa_set_padding(mbedtls_rsa_context * ctx,int padding,mbedtls_md_type_t hash_id)973 int mbedtls_rsa_set_padding(mbedtls_rsa_context *ctx, int padding,
974 mbedtls_md_type_t hash_id)
975 {
976 switch (padding) {
977 #if defined(MBEDTLS_PKCS1_V15)
978 case MBEDTLS_RSA_PKCS_V15:
979 break;
980 #endif
981
982 #if defined(MBEDTLS_PKCS1_V21)
983 case MBEDTLS_RSA_PKCS_V21:
984 break;
985 #endif
986 default:
987 return MBEDTLS_ERR_RSA_INVALID_PADDING;
988 }
989
990 #if defined(MBEDTLS_PKCS1_V21)
991 if ((padding == MBEDTLS_RSA_PKCS_V21) &&
992 (hash_id != MBEDTLS_MD_NONE)) {
993 /* Just make sure this hash is supported in this build. */
994 if (mbedtls_md_info_from_type(hash_id) == NULL) {
995 return MBEDTLS_ERR_RSA_INVALID_PADDING;
996 }
997 }
998 #endif /* MBEDTLS_PKCS1_V21 */
999
1000 ctx->padding = padding;
1001 ctx->hash_id = hash_id;
1002
1003 return 0;
1004 }
1005
1006 /*
1007 * Get padding mode of initialized RSA context
1008 */
mbedtls_rsa_get_padding_mode(const mbedtls_rsa_context * ctx)1009 int mbedtls_rsa_get_padding_mode(const mbedtls_rsa_context *ctx)
1010 {
1011 return ctx->padding;
1012 }
1013
1014 /*
1015 * Get hash identifier of mbedtls_md_type_t type
1016 */
mbedtls_rsa_get_md_alg(const mbedtls_rsa_context * ctx)1017 int mbedtls_rsa_get_md_alg(const mbedtls_rsa_context *ctx)
1018 {
1019 return ctx->hash_id;
1020 }
1021
1022 /*
1023 * Get length in bits of RSA modulus
1024 */
mbedtls_rsa_get_bitlen(const mbedtls_rsa_context * ctx)1025 size_t mbedtls_rsa_get_bitlen(const mbedtls_rsa_context *ctx)
1026 {
1027 return mbedtls_mpi_bitlen(&ctx->N);
1028 }
1029
1030 /*
1031 * Get length in bytes of RSA modulus
1032 */
mbedtls_rsa_get_len(const mbedtls_rsa_context * ctx)1033 size_t mbedtls_rsa_get_len(const mbedtls_rsa_context *ctx)
1034 {
1035 return ctx->len;
1036 }
1037
1038 #if defined(MBEDTLS_GENPRIME)
1039
1040 /*
1041 * Generate an RSA keypair
1042 *
1043 * This generation method follows the RSA key pair generation procedure of
1044 * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072.
1045 */
mbedtls_rsa_gen_key(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,unsigned int nbits,int exponent)1046 int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx,
1047 int (*f_rng)(void *, unsigned char *, size_t),
1048 void *p_rng,
1049 unsigned int nbits, int exponent)
1050 {
1051 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1052 mbedtls_mpi H, G, L;
1053 int prime_quality = 0;
1054
1055 /*
1056 * If the modulus is 1024 bit long or shorter, then the security strength of
1057 * the RSA algorithm is less than or equal to 80 bits and therefore an error
1058 * rate of 2^-80 is sufficient.
1059 */
1060 if (nbits > 1024) {
1061 prime_quality = MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR;
1062 }
1063
1064 mbedtls_mpi_init(&H);
1065 mbedtls_mpi_init(&G);
1066 mbedtls_mpi_init(&L);
1067
1068 if (exponent < 3 || nbits % 2 != 0) {
1069 ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1070 goto cleanup;
1071 }
1072
1073 if (nbits < MBEDTLS_RSA_GEN_KEY_MIN_BITS) {
1074 ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1075 goto cleanup;
1076 }
1077
1078 /*
1079 * find primes P and Q with Q < P so that:
1080 * 1. |P-Q| > 2^( nbits / 2 - 100 )
1081 * 2. GCD( E, (P-1)*(Q-1) ) == 1
1082 * 3. E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )
1083 */
1084 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&ctx->E, exponent));
1085
1086 do {
1087 MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->P, nbits >> 1,
1088 prime_quality, f_rng, p_rng));
1089
1090 MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->Q, nbits >> 1,
1091 prime_quality, f_rng, p_rng));
1092
1093 /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */
1094 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&H, &ctx->P, &ctx->Q));
1095 if (mbedtls_mpi_bitlen(&H) <= ((nbits >= 200) ? ((nbits >> 1) - 99) : 0)) {
1096 continue;
1097 }
1098
1099 /* not required by any standards, but some users rely on the fact that P > Q */
1100 if (H.s < 0) {
1101 mbedtls_mpi_swap(&ctx->P, &ctx->Q);
1102 }
1103
1104 /* Temporarily replace P,Q by P-1, Q-1 */
1105 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->P, &ctx->P, 1));
1106 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->Q, &ctx->Q, 1));
1107 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&H, &ctx->P, &ctx->Q));
1108
1109 /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */
1110 MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->E, &H));
1111 if (mbedtls_mpi_cmp_int(&G, 1) != 0) {
1112 continue;
1113 }
1114
1115 /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */
1116 MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->P, &ctx->Q));
1117 MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&L, NULL, &H, &G));
1118 MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&ctx->D, &ctx->E, &L));
1119
1120 if (mbedtls_mpi_bitlen(&ctx->D) <= ((nbits + 1) / 2)) { // (FIPS 186-4 §B.3.1 criterion 3(a))
1121 continue;
1122 }
1123
1124 break;
1125 } while (1);
1126
1127 /* Restore P,Q */
1128 MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->P, &ctx->P, 1));
1129 MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->Q, &ctx->Q, 1));
1130
1131 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q));
1132
1133 ctx->len = mbedtls_mpi_size(&ctx->N);
1134
1135 #if !defined(MBEDTLS_RSA_NO_CRT)
1136 /*
1137 * DP = D mod (P - 1)
1138 * DQ = D mod (Q - 1)
1139 * QP = Q^-1 mod P
1140 */
1141 MBEDTLS_MPI_CHK(mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
1142 &ctx->DP, &ctx->DQ, &ctx->QP));
1143 #endif /* MBEDTLS_RSA_NO_CRT */
1144
1145 /* Double-check */
1146 MBEDTLS_MPI_CHK(mbedtls_rsa_check_privkey(ctx));
1147
1148 cleanup:
1149
1150 mbedtls_mpi_free(&H);
1151 mbedtls_mpi_free(&G);
1152 mbedtls_mpi_free(&L);
1153
1154 if (ret != 0) {
1155 mbedtls_rsa_free(ctx);
1156
1157 if ((-ret & ~0x7f) == 0) {
1158 ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_KEY_GEN_FAILED, ret);
1159 }
1160 return ret;
1161 }
1162
1163 return 0;
1164 }
1165
1166 #endif /* MBEDTLS_GENPRIME */
1167
1168 /*
1169 * Check a public RSA key
1170 */
mbedtls_rsa_check_pubkey(const mbedtls_rsa_context * ctx)1171 int mbedtls_rsa_check_pubkey(const mbedtls_rsa_context *ctx)
1172 {
1173 if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */) != 0) {
1174 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1175 }
1176
1177 if (mbedtls_mpi_bitlen(&ctx->N) < 128) {
1178 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1179 }
1180
1181 if (mbedtls_mpi_get_bit(&ctx->E, 0) == 0 ||
1182 mbedtls_mpi_bitlen(&ctx->E) < 2 ||
1183 mbedtls_mpi_cmp_mpi(&ctx->E, &ctx->N) >= 0) {
1184 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1185 }
1186
1187 return 0;
1188 }
1189
1190 /*
1191 * Check for the consistency of all fields in an RSA private key context
1192 */
mbedtls_rsa_check_privkey(const mbedtls_rsa_context * ctx)1193 int mbedtls_rsa_check_privkey(const mbedtls_rsa_context *ctx)
1194 {
1195 if (mbedtls_rsa_check_pubkey(ctx) != 0 ||
1196 rsa_check_context(ctx, 1 /* private */, 1 /* blinding */) != 0) {
1197 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1198 }
1199
1200 if (mbedtls_rsa_validate_params(&ctx->N, &ctx->P, &ctx->Q,
1201 &ctx->D, &ctx->E, NULL, NULL) != 0) {
1202 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1203 }
1204
1205 #if !defined(MBEDTLS_RSA_NO_CRT)
1206 else if (mbedtls_rsa_validate_crt(&ctx->P, &ctx->Q, &ctx->D,
1207 &ctx->DP, &ctx->DQ, &ctx->QP) != 0) {
1208 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1209 }
1210 #endif
1211
1212 return 0;
1213 }
1214
1215 /*
1216 * Check if contexts holding a public and private key match
1217 */
mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context * pub,const mbedtls_rsa_context * prv)1218 int mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context *pub,
1219 const mbedtls_rsa_context *prv)
1220 {
1221 if (mbedtls_rsa_check_pubkey(pub) != 0 ||
1222 mbedtls_rsa_check_privkey(prv) != 0) {
1223 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1224 }
1225
1226 if (mbedtls_mpi_cmp_mpi(&pub->N, &prv->N) != 0 ||
1227 mbedtls_mpi_cmp_mpi(&pub->E, &prv->E) != 0) {
1228 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1229 }
1230
1231 return 0;
1232 }
1233
1234 /*
1235 * Do an RSA public key operation
1236 */
mbedtls_rsa_public(mbedtls_rsa_context * ctx,const unsigned char * input,unsigned char * output)1237 int mbedtls_rsa_public(mbedtls_rsa_context *ctx,
1238 const unsigned char *input,
1239 unsigned char *output)
1240 {
1241 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1242 size_t olen;
1243 mbedtls_mpi T;
1244
1245 if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */)) {
1246 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1247 }
1248
1249 mbedtls_mpi_init(&T);
1250
1251 #if defined(MBEDTLS_THREADING_C)
1252 if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
1253 return ret;
1254 }
1255 #endif
1256
1257 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
1258
1259 if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
1260 ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
1261 goto cleanup;
1262 }
1263
1264 olen = ctx->len;
1265 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod_unsafe(&T, &T, &ctx->E, &ctx->N, &ctx->RN));
1266 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
1267
1268 cleanup:
1269 #if defined(MBEDTLS_THREADING_C)
1270 if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
1271 return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
1272 }
1273 #endif
1274
1275 mbedtls_mpi_free(&T);
1276
1277 if (ret != 0) {
1278 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PUBLIC_FAILED, ret);
1279 }
1280
1281 return 0;
1282 }
1283
1284 /*
1285 * Generate or update blinding values, see section 10 of:
1286 * KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
1287 * DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
1288 * Berlin Heidelberg, 1996. p. 104-113.
1289 */
rsa_prepare_blinding(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1290 static int rsa_prepare_blinding(mbedtls_rsa_context *ctx,
1291 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1292 {
1293 int ret, count = 0;
1294 mbedtls_mpi R;
1295
1296 mbedtls_mpi_init(&R);
1297
1298 if (ctx->Vf.p != NULL) {
1299 /* We already have blinding values, just update them by squaring */
1300 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &ctx->Vi));
1301 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
1302 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vf, &ctx->Vf));
1303 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->N));
1304
1305 goto cleanup;
1306 }
1307
1308 /* Unblinding value: Vf = random number, invertible mod N */
1309 do {
1310 if (count++ > 10) {
1311 ret = MBEDTLS_ERR_RSA_RNG_FAILED;
1312 goto cleanup;
1313 }
1314
1315 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&ctx->Vf, ctx->len - 1, f_rng, p_rng));
1316
1317 /* Compute Vf^-1 as R * (R Vf)^-1 to avoid leaks from inv_mod. */
1318 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, ctx->len - 1, f_rng, p_rng));
1319 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vf, &R));
1320 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
1321
1322 /* At this point, Vi is invertible mod N if and only if both Vf and R
1323 * are invertible mod N. If one of them isn't, we don't need to know
1324 * which one, we just loop and choose new values for both of them.
1325 * (Each iteration succeeds with overwhelming probability.) */
1326 ret = mbedtls_mpi_inv_mod(&ctx->Vi, &ctx->Vi, &ctx->N);
1327 if (ret != 0 && ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
1328 goto cleanup;
1329 }
1330
1331 } while (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE);
1332
1333 /* Finish the computation of Vf^-1 = R * (R Vf)^-1 */
1334 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &R));
1335 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
1336
1337 /* Blinding value: Vi = Vf^(-e) mod N
1338 * (Vi already contains Vf^-1 at this point) */
1339 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN));
1340
1341
1342 cleanup:
1343 mbedtls_mpi_free(&R);
1344
1345 return ret;
1346 }
1347
1348 /*
1349 * Unblind
1350 * T = T * Vf mod N
1351 */
rsa_unblind(mbedtls_mpi * T,mbedtls_mpi * Vf,const mbedtls_mpi * N)1352 static int rsa_unblind(mbedtls_mpi *T, mbedtls_mpi *Vf, const mbedtls_mpi *N)
1353 {
1354 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1355 const mbedtls_mpi_uint mm = mbedtls_mpi_core_montmul_init(N->p);
1356 const size_t nlimbs = N->n;
1357 const size_t tlimbs = mbedtls_mpi_core_montmul_working_limbs(nlimbs);
1358 mbedtls_mpi RR, M_T;
1359
1360 mbedtls_mpi_init(&RR);
1361 mbedtls_mpi_init(&M_T);
1362
1363 MBEDTLS_MPI_CHK(mbedtls_mpi_core_get_mont_r2_unsafe(&RR, N));
1364 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&M_T, tlimbs));
1365
1366 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(T, nlimbs));
1367 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Vf, nlimbs));
1368
1369 /* T = T * Vf mod N
1370 * Reminder: montmul(A, B, N) = A * B * R^-1 mod N
1371 * Usually both operands are multiplied by R mod N beforehand (by calling
1372 * `to_mont_rep()` on them), yielding a result that's also * R mod N (aka
1373 * "in the Montgomery domain"). Here we only multiply one operand by R mod
1374 * N, so the result is directly what we want - no need to call
1375 * `from_mont_rep()` on it. */
1376 mbedtls_mpi_core_to_mont_rep(T->p, T->p, N->p, nlimbs, mm, RR.p, M_T.p);
1377 mbedtls_mpi_core_montmul(T->p, T->p, Vf->p, nlimbs, N->p, nlimbs, mm, M_T.p);
1378
1379 cleanup:
1380
1381 mbedtls_mpi_free(&RR);
1382 mbedtls_mpi_free(&M_T);
1383
1384 return ret;
1385 }
1386
1387 /*
1388 * Exponent blinding supposed to prevent side-channel attacks using multiple
1389 * traces of measurements to recover the RSA key. The more collisions are there,
1390 * the more bits of the key can be recovered. See [3].
1391 *
1392 * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
1393 * observations on average.
1394 *
1395 * For example with 28 byte blinding to achieve 2 collisions the adversary has
1396 * to make 2^112 observations on average.
1397 *
1398 * (With the currently (as of 2017 April) known best algorithms breaking 2048
1399 * bit RSA requires approximately as much time as trying out 2^112 random keys.
1400 * Thus in this sense with 28 byte blinding the security is not reduced by
1401 * side-channel attacks like the one in [3])
1402 *
1403 * This countermeasure does not help if the key recovery is possible with a
1404 * single trace.
1405 */
1406 #define RSA_EXPONENT_BLINDING 28
1407
1408 /*
1409 * Do an RSA private key operation
1410 */
mbedtls_rsa_private(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,const unsigned char * input,unsigned char * output)1411 int mbedtls_rsa_private(mbedtls_rsa_context *ctx,
1412 int (*f_rng)(void *, unsigned char *, size_t),
1413 void *p_rng,
1414 const unsigned char *input,
1415 unsigned char *output)
1416 {
1417 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1418 size_t olen;
1419
1420 /* Temporary holding the result */
1421 mbedtls_mpi T;
1422
1423 /* Temporaries holding P-1, Q-1 and the
1424 * exponent blinding factor, respectively. */
1425 mbedtls_mpi P1, Q1, R;
1426
1427 #if !defined(MBEDTLS_RSA_NO_CRT)
1428 /* Temporaries holding the results mod p resp. mod q. */
1429 mbedtls_mpi TP, TQ;
1430
1431 /* Temporaries holding the blinded exponents for
1432 * the mod p resp. mod q computation (if used). */
1433 mbedtls_mpi DP_blind, DQ_blind;
1434 #else
1435 /* Temporary holding the blinded exponent (if used). */
1436 mbedtls_mpi D_blind;
1437 #endif /* MBEDTLS_RSA_NO_CRT */
1438
1439 /* Temporaries holding the initial input and the double
1440 * checked result; should be the same in the end. */
1441 mbedtls_mpi input_blinded, check_result_blinded;
1442
1443 if (f_rng == NULL) {
1444 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1445 }
1446
1447 if (rsa_check_context(ctx, 1 /* private key checks */,
1448 1 /* blinding on */) != 0) {
1449 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1450 }
1451
1452 #if defined(MBEDTLS_THREADING_C)
1453 if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
1454 return ret;
1455 }
1456 #endif
1457
1458 /* MPI Initialization */
1459 mbedtls_mpi_init(&T);
1460
1461 mbedtls_mpi_init(&P1);
1462 mbedtls_mpi_init(&Q1);
1463 mbedtls_mpi_init(&R);
1464
1465 #if defined(MBEDTLS_RSA_NO_CRT)
1466 mbedtls_mpi_init(&D_blind);
1467 #else
1468 mbedtls_mpi_init(&DP_blind);
1469 mbedtls_mpi_init(&DQ_blind);
1470 #endif
1471
1472 #if !defined(MBEDTLS_RSA_NO_CRT)
1473 mbedtls_mpi_init(&TP); mbedtls_mpi_init(&TQ);
1474 #endif
1475
1476 mbedtls_mpi_init(&input_blinded);
1477 mbedtls_mpi_init(&check_result_blinded);
1478
1479 /* End of MPI initialization */
1480
1481 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
1482 if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
1483 ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
1484 goto cleanup;
1485 }
1486
1487 /*
1488 * Blinding
1489 * T = T * Vi mod N
1490 */
1491 MBEDTLS_MPI_CHK(rsa_prepare_blinding(ctx, f_rng, p_rng));
1492 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vi));
1493 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N));
1494
1495 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&input_blinded, &T));
1496
1497 /*
1498 * Exponent blinding
1499 */
1500 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&P1, &ctx->P, 1));
1501 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&Q1, &ctx->Q, 1));
1502
1503 #if defined(MBEDTLS_RSA_NO_CRT)
1504 /*
1505 * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
1506 */
1507 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
1508 f_rng, p_rng));
1509 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &P1, &Q1));
1510 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &D_blind, &R));
1511 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&D_blind, &D_blind, &ctx->D));
1512 #else
1513 /*
1514 * DP_blind = ( P - 1 ) * R + DP
1515 */
1516 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
1517 f_rng, p_rng));
1518 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DP_blind, &P1, &R));
1519 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DP_blind, &DP_blind,
1520 &ctx->DP));
1521
1522 /*
1523 * DQ_blind = ( Q - 1 ) * R + DQ
1524 */
1525 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
1526 f_rng, p_rng));
1527 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DQ_blind, &Q1, &R));
1528 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DQ_blind, &DQ_blind,
1529 &ctx->DQ));
1530 #endif /* MBEDTLS_RSA_NO_CRT */
1531
1532 #if defined(MBEDTLS_RSA_NO_CRT)
1533 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, &D_blind, &ctx->N, &ctx->RN));
1534 #else
1535 /*
1536 * Faster decryption using the CRT
1537 *
1538 * TP = input ^ dP mod P
1539 * TQ = input ^ dQ mod Q
1540 */
1541
1542 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TP, &T, &DP_blind, &ctx->P, &ctx->RP));
1543 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TQ, &T, &DQ_blind, &ctx->Q, &ctx->RQ));
1544
1545 /*
1546 * T = (TP - TQ) * (Q^-1 mod P) mod P
1547 */
1548 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&T, &TP, &TQ));
1549 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->QP));
1550 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &TP, &ctx->P));
1551
1552 /*
1553 * T = TQ + T * Q
1554 */
1555 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->Q));
1556 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&T, &TQ, &TP));
1557 #endif /* MBEDTLS_RSA_NO_CRT */
1558
1559 /* Verify the result to prevent glitching attacks. */
1560 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&check_result_blinded, &T, &ctx->E,
1561 &ctx->N, &ctx->RN));
1562 if (mbedtls_mpi_cmp_mpi(&check_result_blinded, &input_blinded) != 0) {
1563 ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
1564 goto cleanup;
1565 }
1566
1567 /*
1568 * Unblind
1569 * T = T * Vf mod N
1570 */
1571 MBEDTLS_MPI_CHK(rsa_unblind(&T, &ctx->Vf, &ctx->N));
1572
1573 olen = ctx->len;
1574 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
1575
1576 cleanup:
1577 #if defined(MBEDTLS_THREADING_C)
1578 if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
1579 return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
1580 }
1581 #endif
1582
1583 mbedtls_mpi_free(&P1);
1584 mbedtls_mpi_free(&Q1);
1585 mbedtls_mpi_free(&R);
1586
1587 #if defined(MBEDTLS_RSA_NO_CRT)
1588 mbedtls_mpi_free(&D_blind);
1589 #else
1590 mbedtls_mpi_free(&DP_blind);
1591 mbedtls_mpi_free(&DQ_blind);
1592 #endif
1593
1594 mbedtls_mpi_free(&T);
1595
1596 #if !defined(MBEDTLS_RSA_NO_CRT)
1597 mbedtls_mpi_free(&TP); mbedtls_mpi_free(&TQ);
1598 #endif
1599
1600 mbedtls_mpi_free(&check_result_blinded);
1601 mbedtls_mpi_free(&input_blinded);
1602
1603 if (ret != 0 && ret >= -0x007f) {
1604 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PRIVATE_FAILED, ret);
1605 }
1606
1607 return ret;
1608 }
1609
1610 #if defined(MBEDTLS_PKCS1_V21)
1611 /**
1612 * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
1613 *
1614 * \param dst buffer to mask
1615 * \param dlen length of destination buffer
1616 * \param src source of the mask generation
1617 * \param slen length of the source buffer
1618 * \param md_alg message digest to use
1619 */
mgf_mask(unsigned char * dst,size_t dlen,unsigned char * src,size_t slen,mbedtls_md_type_t md_alg)1620 static int mgf_mask(unsigned char *dst, size_t dlen, unsigned char *src,
1621 size_t slen, mbedtls_md_type_t md_alg)
1622 {
1623 unsigned char counter[4];
1624 unsigned char *p;
1625 unsigned int hlen;
1626 size_t i, use_len;
1627 unsigned char mask[MBEDTLS_MD_MAX_SIZE];
1628 int ret = 0;
1629 const mbedtls_md_info_t *md_info;
1630 mbedtls_md_context_t md_ctx;
1631
1632 mbedtls_md_init(&md_ctx);
1633 md_info = mbedtls_md_info_from_type(md_alg);
1634 if (md_info == NULL) {
1635 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1636 }
1637
1638 mbedtls_md_init(&md_ctx);
1639 if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1640 goto exit;
1641 }
1642
1643 hlen = mbedtls_md_get_size(md_info);
1644
1645 memset(mask, 0, sizeof(mask));
1646 memset(counter, 0, 4);
1647
1648 /* Generate and apply dbMask */
1649 p = dst;
1650
1651 while (dlen > 0) {
1652 use_len = hlen;
1653 if (dlen < hlen) {
1654 use_len = dlen;
1655 }
1656
1657 if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
1658 goto exit;
1659 }
1660 if ((ret = mbedtls_md_update(&md_ctx, src, slen)) != 0) {
1661 goto exit;
1662 }
1663 if ((ret = mbedtls_md_update(&md_ctx, counter, 4)) != 0) {
1664 goto exit;
1665 }
1666 if ((ret = mbedtls_md_finish(&md_ctx, mask)) != 0) {
1667 goto exit;
1668 }
1669
1670 for (i = 0; i < use_len; ++i) {
1671 *p++ ^= mask[i];
1672 }
1673
1674 counter[3]++;
1675
1676 dlen -= use_len;
1677 }
1678
1679 exit:
1680 mbedtls_platform_zeroize(mask, sizeof(mask));
1681 mbedtls_md_free(&md_ctx);
1682
1683 return ret;
1684 }
1685
1686 /**
1687 * Generate Hash(M') as in RFC 8017 page 43 points 5 and 6.
1688 *
1689 * \param hash the input hash
1690 * \param hlen length of the input hash
1691 * \param salt the input salt
1692 * \param slen length of the input salt
1693 * \param out the output buffer - must be large enough for \p md_alg
1694 * \param md_alg message digest to use
1695 */
hash_mprime(const unsigned char * hash,size_t hlen,const unsigned char * salt,size_t slen,unsigned char * out,mbedtls_md_type_t md_alg)1696 static int hash_mprime(const unsigned char *hash, size_t hlen,
1697 const unsigned char *salt, size_t slen,
1698 unsigned char *out, mbedtls_md_type_t md_alg)
1699 {
1700 const unsigned char zeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1701
1702 mbedtls_md_context_t md_ctx;
1703 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1704
1705 const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
1706 if (md_info == NULL) {
1707 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1708 }
1709
1710 mbedtls_md_init(&md_ctx);
1711 if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1712 goto exit;
1713 }
1714 if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
1715 goto exit;
1716 }
1717 if ((ret = mbedtls_md_update(&md_ctx, zeros, sizeof(zeros))) != 0) {
1718 goto exit;
1719 }
1720 if ((ret = mbedtls_md_update(&md_ctx, hash, hlen)) != 0) {
1721 goto exit;
1722 }
1723 if ((ret = mbedtls_md_update(&md_ctx, salt, slen)) != 0) {
1724 goto exit;
1725 }
1726 if ((ret = mbedtls_md_finish(&md_ctx, out)) != 0) {
1727 goto exit;
1728 }
1729
1730 exit:
1731 mbedtls_md_free(&md_ctx);
1732
1733 return ret;
1734 }
1735
1736 /**
1737 * Compute a hash.
1738 *
1739 * \param md_alg algorithm to use
1740 * \param input input message to hash
1741 * \param ilen input length
1742 * \param output the output buffer - must be large enough for \p md_alg
1743 */
compute_hash(mbedtls_md_type_t md_alg,const unsigned char * input,size_t ilen,unsigned char * output)1744 static int compute_hash(mbedtls_md_type_t md_alg,
1745 const unsigned char *input, size_t ilen,
1746 unsigned char *output)
1747 {
1748 const mbedtls_md_info_t *md_info;
1749
1750 md_info = mbedtls_md_info_from_type(md_alg);
1751 if (md_info == NULL) {
1752 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1753 }
1754
1755 return mbedtls_md(md_info, input, ilen, output);
1756 }
1757 #endif /* MBEDTLS_PKCS1_V21 */
1758
1759 #if defined(MBEDTLS_PKCS1_V21)
1760 /*
1761 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
1762 */
mbedtls_rsa_rsaes_oaep_encrypt(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,const unsigned char * label,size_t label_len,size_t ilen,const unsigned char * input,unsigned char * output)1763 int mbedtls_rsa_rsaes_oaep_encrypt(mbedtls_rsa_context *ctx,
1764 int (*f_rng)(void *, unsigned char *, size_t),
1765 void *p_rng,
1766 const unsigned char *label, size_t label_len,
1767 size_t ilen,
1768 const unsigned char *input,
1769 unsigned char *output)
1770 {
1771 size_t olen;
1772 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1773 unsigned char *p = output;
1774 unsigned int hlen;
1775
1776 if (f_rng == NULL) {
1777 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1778 }
1779
1780 hlen = mbedtls_md_get_size_from_type((mbedtls_md_type_t) ctx->hash_id);
1781 if (hlen == 0) {
1782 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1783 }
1784
1785 olen = ctx->len;
1786
1787 /* first comparison checks for overflow */
1788 if (ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2) {
1789 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1790 }
1791
1792 memset(output, 0, olen);
1793
1794 *p++ = 0;
1795
1796 /* Generate a random octet string seed */
1797 if ((ret = f_rng(p_rng, p, hlen)) != 0) {
1798 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1799 }
1800
1801 p += hlen;
1802
1803 /* Construct DB */
1804 ret = compute_hash((mbedtls_md_type_t) ctx->hash_id, label, label_len, p);
1805 if (ret != 0) {
1806 return ret;
1807 }
1808 p += hlen;
1809 p += olen - 2 * hlen - 2 - ilen;
1810 *p++ = 1;
1811 if (ilen != 0) {
1812 memcpy(p, input, ilen);
1813 }
1814
1815 /* maskedDB: Apply dbMask to DB */
1816 if ((ret = mgf_mask(output + hlen + 1, olen - hlen - 1, output + 1, hlen,
1817 (mbedtls_md_type_t) ctx->hash_id)) != 0) {
1818 return ret;
1819 }
1820
1821 /* maskedSeed: Apply seedMask to seed */
1822 if ((ret = mgf_mask(output + 1, hlen, output + hlen + 1, olen - hlen - 1,
1823 (mbedtls_md_type_t) ctx->hash_id)) != 0) {
1824 return ret;
1825 }
1826
1827 return mbedtls_rsa_public(ctx, output, output);
1828 }
1829 #endif /* MBEDTLS_PKCS1_V21 */
1830
1831 #if defined(MBEDTLS_PKCS1_V15)
1832 /*
1833 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
1834 */
mbedtls_rsa_rsaes_pkcs1_v15_encrypt(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,size_t ilen,const unsigned char * input,unsigned char * output)1835 int mbedtls_rsa_rsaes_pkcs1_v15_encrypt(mbedtls_rsa_context *ctx,
1836 int (*f_rng)(void *, unsigned char *, size_t),
1837 void *p_rng, size_t ilen,
1838 const unsigned char *input,
1839 unsigned char *output)
1840 {
1841 size_t nb_pad, olen;
1842 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1843 unsigned char *p = output;
1844
1845 olen = ctx->len;
1846
1847 /* first comparison checks for overflow */
1848 if (ilen + 11 < ilen || olen < ilen + 11) {
1849 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1850 }
1851
1852 nb_pad = olen - 3 - ilen;
1853
1854 *p++ = 0;
1855
1856 if (f_rng == NULL) {
1857 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1858 }
1859
1860 *p++ = MBEDTLS_RSA_CRYPT;
1861
1862 while (nb_pad-- > 0) {
1863 int rng_dl = 100;
1864
1865 do {
1866 ret = f_rng(p_rng, p, 1);
1867 } while (*p == 0 && --rng_dl && ret == 0);
1868
1869 /* Check if RNG failed to generate data */
1870 if (rng_dl == 0 || ret != 0) {
1871 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1872 }
1873
1874 p++;
1875 }
1876
1877 *p++ = 0;
1878 if (ilen != 0) {
1879 memcpy(p, input, ilen);
1880 }
1881
1882 return mbedtls_rsa_public(ctx, output, output);
1883 }
1884 #endif /* MBEDTLS_PKCS1_V15 */
1885
1886 /*
1887 * Add the message padding, then do an RSA operation
1888 */
mbedtls_rsa_pkcs1_encrypt(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,size_t ilen,const unsigned char * input,unsigned char * output)1889 int mbedtls_rsa_pkcs1_encrypt(mbedtls_rsa_context *ctx,
1890 int (*f_rng)(void *, unsigned char *, size_t),
1891 void *p_rng,
1892 size_t ilen,
1893 const unsigned char *input,
1894 unsigned char *output)
1895 {
1896 switch (ctx->padding) {
1897 #if defined(MBEDTLS_PKCS1_V15)
1898 case MBEDTLS_RSA_PKCS_V15:
1899 return mbedtls_rsa_rsaes_pkcs1_v15_encrypt(ctx, f_rng, p_rng,
1900 ilen, input, output);
1901 #endif
1902
1903 #if defined(MBEDTLS_PKCS1_V21)
1904 case MBEDTLS_RSA_PKCS_V21:
1905 return mbedtls_rsa_rsaes_oaep_encrypt(ctx, f_rng, p_rng, NULL, 0,
1906 ilen, input, output);
1907 #endif
1908
1909 default:
1910 return MBEDTLS_ERR_RSA_INVALID_PADDING;
1911 }
1912 }
1913
1914 #if defined(MBEDTLS_PKCS1_V21)
1915 /*
1916 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
1917 */
mbedtls_rsa_rsaes_oaep_decrypt(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,const unsigned char * label,size_t label_len,size_t * olen,const unsigned char * input,unsigned char * output,size_t output_max_len)1918 int mbedtls_rsa_rsaes_oaep_decrypt(mbedtls_rsa_context *ctx,
1919 int (*f_rng)(void *, unsigned char *, size_t),
1920 void *p_rng,
1921 const unsigned char *label, size_t label_len,
1922 size_t *olen,
1923 const unsigned char *input,
1924 unsigned char *output,
1925 size_t output_max_len)
1926 {
1927 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1928 size_t ilen, i, pad_len;
1929 unsigned char *p;
1930 mbedtls_ct_condition_t bad, in_padding;
1931 unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
1932 unsigned char lhash[MBEDTLS_MD_MAX_SIZE];
1933 unsigned int hlen;
1934
1935 /*
1936 * Parameters sanity checks
1937 */
1938 if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
1939 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1940 }
1941
1942 ilen = ctx->len;
1943
1944 if (ilen < 16 || ilen > sizeof(buf)) {
1945 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1946 }
1947
1948 hlen = mbedtls_md_get_size_from_type((mbedtls_md_type_t) ctx->hash_id);
1949 if (hlen == 0) {
1950 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1951 }
1952
1953 // checking for integer underflow
1954 if (2 * hlen + 2 > ilen) {
1955 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1956 }
1957
1958 /*
1959 * RSA operation
1960 */
1961 if( ctx->P.n == 0 )
1962 ret = mbedtls_rsa_private( ctx, NULL, NULL, input, buf );
1963 else
1964 ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
1965
1966 if (ret != 0) {
1967 goto cleanup;
1968 }
1969
1970 /*
1971 * Unmask data and generate lHash
1972 */
1973 /* seed: Apply seedMask to maskedSeed */
1974 if ((ret = mgf_mask(buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
1975 (mbedtls_md_type_t) ctx->hash_id)) != 0 ||
1976 /* DB: Apply dbMask to maskedDB */
1977 (ret = mgf_mask(buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
1978 (mbedtls_md_type_t) ctx->hash_id)) != 0) {
1979 goto cleanup;
1980 }
1981
1982 /* Generate lHash */
1983 ret = compute_hash((mbedtls_md_type_t) ctx->hash_id,
1984 label, label_len, lhash);
1985 if (ret != 0) {
1986 goto cleanup;
1987 }
1988
1989 /*
1990 * Check contents, in "constant-time"
1991 */
1992 p = buf;
1993
1994 bad = mbedtls_ct_bool(*p++); /* First byte must be 0 */
1995
1996 p += hlen; /* Skip seed */
1997
1998 /* Check lHash */
1999 bad = mbedtls_ct_bool_or(bad, mbedtls_ct_bool(mbedtls_ct_memcmp(lhash, p, hlen)));
2000 p += hlen;
2001
2002 /* Get zero-padding len, but always read till end of buffer
2003 * (minus one, for the 01 byte) */
2004 pad_len = 0;
2005 in_padding = MBEDTLS_CT_TRUE;
2006 for (i = 0; i < ilen - 2 * hlen - 2; i++) {
2007 in_padding = mbedtls_ct_bool_and(in_padding, mbedtls_ct_uint_eq(p[i], 0));
2008 pad_len += mbedtls_ct_uint_if_else_0(in_padding, 1);
2009 }
2010
2011 p += pad_len;
2012 bad = mbedtls_ct_bool_or(bad, mbedtls_ct_uint_ne(*p++, 0x01));
2013
2014 /*
2015 * The only information "leaked" is whether the padding was correct or not
2016 * (eg, no data is copied if it was not correct). This meets the
2017 * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
2018 * the different error conditions.
2019 */
2020 if (bad != MBEDTLS_CT_FALSE) {
2021 ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
2022 goto cleanup;
2023 }
2024
2025 if (ilen - ((size_t) (p - buf)) > output_max_len) {
2026 ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
2027 goto cleanup;
2028 }
2029
2030 *olen = ilen - ((size_t) (p - buf));
2031 if (*olen != 0) {
2032 memcpy(output, p, *olen);
2033 }
2034 ret = 0;
2035
2036 cleanup:
2037 mbedtls_platform_zeroize(buf, sizeof(buf));
2038 mbedtls_platform_zeroize(lhash, sizeof(lhash));
2039
2040 return ret;
2041 }
2042 #endif /* MBEDTLS_PKCS1_V21 */
2043
2044 #if defined(MBEDTLS_PKCS1_V15)
2045 /*
2046 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
2047 */
mbedtls_rsa_rsaes_pkcs1_v15_decrypt(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,size_t * olen,const unsigned char * input,unsigned char * output,size_t output_max_len)2048 int mbedtls_rsa_rsaes_pkcs1_v15_decrypt(mbedtls_rsa_context *ctx,
2049 int (*f_rng)(void *, unsigned char *, size_t),
2050 void *p_rng,
2051 size_t *olen,
2052 const unsigned char *input,
2053 unsigned char *output,
2054 size_t output_max_len)
2055 {
2056 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2057 size_t ilen;
2058 unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
2059
2060 ilen = ctx->len;
2061
2062 if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
2063 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2064 }
2065
2066 if (ilen < 16 || ilen > sizeof(buf)) {
2067 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2068 }
2069
2070 ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
2071
2072 if (ret != 0) {
2073 goto cleanup;
2074 }
2075
2076 ret = mbedtls_ct_rsaes_pkcs1_v15_unpadding(buf, ilen,
2077 output, output_max_len, olen);
2078
2079 cleanup:
2080 mbedtls_platform_zeroize(buf, sizeof(buf));
2081
2082 return ret;
2083 }
2084 #endif /* MBEDTLS_PKCS1_V15 */
2085
2086 /*
2087 * Do an RSA operation, then remove the message padding
2088 */
mbedtls_rsa_pkcs1_decrypt(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,size_t * olen,const unsigned char * input,unsigned char * output,size_t output_max_len)2089 int mbedtls_rsa_pkcs1_decrypt(mbedtls_rsa_context *ctx,
2090 int (*f_rng)(void *, unsigned char *, size_t),
2091 void *p_rng,
2092 size_t *olen,
2093 const unsigned char *input,
2094 unsigned char *output,
2095 size_t output_max_len)
2096 {
2097 switch (ctx->padding) {
2098 #if defined(MBEDTLS_PKCS1_V15)
2099 case MBEDTLS_RSA_PKCS_V15:
2100 return mbedtls_rsa_rsaes_pkcs1_v15_decrypt(ctx, f_rng, p_rng, olen,
2101 input, output, output_max_len);
2102 #endif
2103
2104 #if defined(MBEDTLS_PKCS1_V21)
2105 case MBEDTLS_RSA_PKCS_V21:
2106 return mbedtls_rsa_rsaes_oaep_decrypt(ctx, f_rng, p_rng, NULL, 0,
2107 olen, input, output,
2108 output_max_len);
2109 #endif
2110
2111 default:
2112 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2113 }
2114 }
2115
2116 #if defined(MBEDTLS_PKCS1_V21)
rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,int saltlen,unsigned char * sig)2117 static int rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context *ctx,
2118 int (*f_rng)(void *, unsigned char *, size_t),
2119 void *p_rng,
2120 mbedtls_md_type_t md_alg,
2121 unsigned int hashlen,
2122 const unsigned char *hash,
2123 int saltlen,
2124 unsigned char *sig)
2125 {
2126 size_t olen;
2127 unsigned char *p = sig;
2128 unsigned char *salt = NULL;
2129 size_t slen, min_slen, hlen, offset = 0;
2130 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2131 size_t msb;
2132 mbedtls_md_type_t hash_id;
2133
2134 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2135 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2136 }
2137
2138 if (f_rng == NULL) {
2139 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2140 }
2141
2142 olen = ctx->len;
2143
2144 if (md_alg != MBEDTLS_MD_NONE) {
2145 /* Gather length of hash to sign */
2146 size_t exp_hashlen = mbedtls_md_get_size_from_type(md_alg);
2147 if (exp_hashlen == 0) {
2148 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2149 }
2150
2151 if (hashlen != exp_hashlen) {
2152 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2153 }
2154 }
2155
2156 hash_id = (mbedtls_md_type_t) ctx->hash_id;
2157 if (hash_id == MBEDTLS_MD_NONE) {
2158 hash_id = md_alg;
2159 }
2160 hlen = mbedtls_md_get_size_from_type(hash_id);
2161 if (hlen == 0) {
2162 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2163 }
2164
2165 if (saltlen == MBEDTLS_RSA_SALT_LEN_ANY) {
2166 /* Calculate the largest possible salt length, up to the hash size.
2167 * Normally this is the hash length, which is the maximum salt length
2168 * according to FIPS 185-4 §5.5 (e) and common practice. If there is not
2169 * enough room, use the maximum salt length that fits. The constraint is
2170 * that the hash length plus the salt length plus 2 bytes must be at most
2171 * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017
2172 * (PKCS#1 v2.2) §9.1.1 step 3. */
2173 min_slen = hlen - 2;
2174 if (olen < hlen + min_slen + 2) {
2175 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2176 } else if (olen >= hlen + hlen + 2) {
2177 slen = hlen;
2178 } else {
2179 slen = olen - hlen - 2;
2180 }
2181 } else if ((saltlen < 0) || (saltlen + hlen + 2 > olen)) {
2182 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2183 } else {
2184 slen = (size_t) saltlen;
2185 }
2186
2187 memset(sig, 0, olen);
2188
2189 /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
2190 msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2191 p += olen - hlen - slen - 2;
2192 *p++ = 0x01;
2193
2194 /* Generate salt of length slen in place in the encoded message */
2195 salt = p;
2196 if ((ret = f_rng(p_rng, salt, slen)) != 0) {
2197 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
2198 }
2199
2200 p += slen;
2201
2202 /* Generate H = Hash( M' ) */
2203 ret = hash_mprime(hash, hashlen, salt, slen, p, hash_id);
2204 if (ret != 0) {
2205 return ret;
2206 }
2207
2208 /* Compensate for boundary condition when applying mask */
2209 if (msb % 8 == 0) {
2210 offset = 1;
2211 }
2212
2213 /* maskedDB: Apply dbMask to DB */
2214 ret = mgf_mask(sig + offset, olen - hlen - 1 - offset, p, hlen, hash_id);
2215 if (ret != 0) {
2216 return ret;
2217 }
2218
2219 msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2220 sig[0] &= 0xFF >> (olen * 8 - msb);
2221
2222 p += hlen;
2223 *p++ = 0xBC;
2224
2225 if (ctx->P.n == 0)
2226 return mbedtls_rsa_private(ctx, NULL, NULL, sig, sig);
2227
2228 return mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig);
2229 }
2230
rsa_rsassa_pss_sign(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,int saltlen,unsigned char * sig)2231 static int rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
2232 int (*f_rng)(void *, unsigned char *, size_t),
2233 void *p_rng,
2234 mbedtls_md_type_t md_alg,
2235 unsigned int hashlen,
2236 const unsigned char *hash,
2237 int saltlen,
2238 unsigned char *sig)
2239 {
2240 if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
2241 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2242 }
2243 if ((ctx->hash_id == MBEDTLS_MD_NONE) && (md_alg == MBEDTLS_MD_NONE)) {
2244 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2245 }
2246 return rsa_rsassa_pss_sign_no_mode_check(ctx, f_rng, p_rng, md_alg, hashlen, hash, saltlen,
2247 sig);
2248 }
2249
mbedtls_rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,unsigned char * sig)2250 int mbedtls_rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context *ctx,
2251 int (*f_rng)(void *, unsigned char *, size_t),
2252 void *p_rng,
2253 mbedtls_md_type_t md_alg,
2254 unsigned int hashlen,
2255 const unsigned char *hash,
2256 unsigned char *sig)
2257 {
2258 return rsa_rsassa_pss_sign_no_mode_check(ctx, f_rng, p_rng, md_alg,
2259 hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
2260 }
2261
2262 /*
2263 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function with
2264 * the option to pass in the salt length.
2265 */
mbedtls_rsa_rsassa_pss_sign_ext(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,int saltlen,unsigned char * sig)2266 int mbedtls_rsa_rsassa_pss_sign_ext(mbedtls_rsa_context *ctx,
2267 int (*f_rng)(void *, unsigned char *, size_t),
2268 void *p_rng,
2269 mbedtls_md_type_t md_alg,
2270 unsigned int hashlen,
2271 const unsigned char *hash,
2272 int saltlen,
2273 unsigned char *sig)
2274 {
2275 return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
2276 hashlen, hash, saltlen, sig);
2277 }
2278
2279 /*
2280 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
2281 */
mbedtls_rsa_rsassa_pss_sign(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,unsigned char * sig)2282 int mbedtls_rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
2283 int (*f_rng)(void *, unsigned char *, size_t),
2284 void *p_rng,
2285 mbedtls_md_type_t md_alg,
2286 unsigned int hashlen,
2287 const unsigned char *hash,
2288 unsigned char *sig)
2289 {
2290 return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
2291 hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
2292 }
2293 #endif /* MBEDTLS_PKCS1_V21 */
2294
2295 #if defined(MBEDTLS_PKCS1_V15)
2296 /*
2297 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
2298 */
2299
2300 /* Construct a PKCS v1.5 encoding of a hashed message
2301 *
2302 * This is used both for signature generation and verification.
2303 *
2304 * Parameters:
2305 * - md_alg: Identifies the hash algorithm used to generate the given hash;
2306 * MBEDTLS_MD_NONE if raw data is signed.
2307 * - hashlen: Length of hash. Must match md_alg if that's not NONE.
2308 * - hash: Buffer containing the hashed message or the raw data.
2309 * - dst_len: Length of the encoded message.
2310 * - dst: Buffer to hold the encoded message.
2311 *
2312 * Assumptions:
2313 * - hash has size hashlen.
2314 * - dst points to a buffer of size at least dst_len.
2315 *
2316 */
rsa_rsassa_pkcs1_v15_encode(mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,size_t dst_len,unsigned char * dst)2317 static int rsa_rsassa_pkcs1_v15_encode(mbedtls_md_type_t md_alg,
2318 unsigned int hashlen,
2319 const unsigned char *hash,
2320 size_t dst_len,
2321 unsigned char *dst)
2322 {
2323 size_t oid_size = 0;
2324 size_t nb_pad = dst_len;
2325 unsigned char *p = dst;
2326 const char *oid = NULL;
2327
2328 /* Are we signing hashed or raw data? */
2329 if (md_alg != MBEDTLS_MD_NONE) {
2330 unsigned char md_size = mbedtls_md_get_size_from_type(md_alg);
2331 if (md_size == 0) {
2332 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2333 }
2334
2335 if (mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size) != 0) {
2336 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2337 }
2338
2339 if (hashlen != md_size) {
2340 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2341 }
2342
2343 /* Double-check that 8 + hashlen + oid_size can be used as a
2344 * 1-byte ASN.1 length encoding and that there's no overflow. */
2345 if (8 + hashlen + oid_size >= 0x80 ||
2346 10 + hashlen < hashlen ||
2347 10 + hashlen + oid_size < 10 + hashlen) {
2348 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2349 }
2350
2351 /*
2352 * Static bounds check:
2353 * - Need 10 bytes for five tag-length pairs.
2354 * (Insist on 1-byte length encodings to protect against variants of
2355 * Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)
2356 * - Need hashlen bytes for hash
2357 * - Need oid_size bytes for hash alg OID.
2358 */
2359 if (nb_pad < 10 + hashlen + oid_size) {
2360 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2361 }
2362 nb_pad -= 10 + hashlen + oid_size;
2363 } else {
2364 if (nb_pad < hashlen) {
2365 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2366 }
2367
2368 nb_pad -= hashlen;
2369 }
2370
2371 /* Need space for signature header and padding delimiter (3 bytes),
2372 * and 8 bytes for the minimal padding */
2373 if (nb_pad < 3 + 8) {
2374 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2375 }
2376 nb_pad -= 3;
2377
2378 /* Now nb_pad is the amount of memory to be filled
2379 * with padding, and at least 8 bytes long. */
2380
2381 /* Write signature header and padding */
2382 *p++ = 0;
2383 *p++ = MBEDTLS_RSA_SIGN;
2384 memset(p, 0xFF, nb_pad);
2385 p += nb_pad;
2386 *p++ = 0;
2387
2388 /* Are we signing raw data? */
2389 if (md_alg == MBEDTLS_MD_NONE) {
2390 memcpy(p, hash, hashlen);
2391 return 0;
2392 }
2393
2394 /* Signing hashed data, add corresponding ASN.1 structure
2395 *
2396 * DigestInfo ::= SEQUENCE {
2397 * digestAlgorithm DigestAlgorithmIdentifier,
2398 * digest Digest }
2399 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
2400 * Digest ::= OCTET STRING
2401 *
2402 * Schematic:
2403 * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID + LEN [ OID ]
2404 * TAG-NULL + LEN [ NULL ] ]
2405 * TAG-OCTET + LEN [ HASH ] ]
2406 */
2407 *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
2408 *p++ = (unsigned char) (0x08 + oid_size + hashlen);
2409 *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
2410 *p++ = (unsigned char) (0x04 + oid_size);
2411 *p++ = MBEDTLS_ASN1_OID;
2412 *p++ = (unsigned char) oid_size;
2413 memcpy(p, oid, oid_size);
2414 p += oid_size;
2415 *p++ = MBEDTLS_ASN1_NULL;
2416 *p++ = 0x00;
2417 *p++ = MBEDTLS_ASN1_OCTET_STRING;
2418 *p++ = (unsigned char) hashlen;
2419 memcpy(p, hash, hashlen);
2420 p += hashlen;
2421
2422 /* Just a sanity-check, should be automatic
2423 * after the initial bounds check. */
2424 if (p != dst + dst_len) {
2425 mbedtls_platform_zeroize(dst, dst_len);
2426 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2427 }
2428
2429 return 0;
2430 }
2431
2432 /*
2433 * Do an RSA operation to sign the message digest
2434 */
mbedtls_rsa_rsassa_pkcs1_v15_sign(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,unsigned char * sig)2435 int mbedtls_rsa_rsassa_pkcs1_v15_sign(mbedtls_rsa_context *ctx,
2436 int (*f_rng)(void *, unsigned char *, size_t),
2437 void *p_rng,
2438 mbedtls_md_type_t md_alg,
2439 unsigned int hashlen,
2440 const unsigned char *hash,
2441 unsigned char *sig)
2442 {
2443 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2444 unsigned char *sig_try = NULL, *verif = NULL;
2445
2446 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2447 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2448 }
2449
2450 if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
2451 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2452 }
2453
2454 /*
2455 * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
2456 */
2457
2458 if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash,
2459 ctx->len, sig)) != 0) {
2460 return ret;
2461 }
2462
2463 /* Private key operation
2464 *
2465 * In order to prevent Lenstra's attack, make the signature in a
2466 * temporary buffer and check it before returning it.
2467 */
2468
2469 sig_try = mbedtls_calloc(1, ctx->len);
2470 if (sig_try == NULL) {
2471 return MBEDTLS_ERR_MPI_ALLOC_FAILED;
2472 }
2473
2474 verif = mbedtls_calloc(1, ctx->len);
2475 if (verif == NULL) {
2476 mbedtls_free(sig_try);
2477 return MBEDTLS_ERR_MPI_ALLOC_FAILED;
2478 }
2479
2480 MBEDTLS_MPI_CHK(mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig_try));
2481 MBEDTLS_MPI_CHK(mbedtls_rsa_public(ctx, sig_try, verif));
2482
2483 if (mbedtls_ct_memcmp(verif, sig, ctx->len) != 0) {
2484 ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
2485 goto cleanup;
2486 }
2487
2488 memcpy(sig, sig_try, ctx->len);
2489
2490 cleanup:
2491 mbedtls_zeroize_and_free(sig_try, ctx->len);
2492 mbedtls_zeroize_and_free(verif, ctx->len);
2493
2494 if (ret != 0) {
2495 memset(sig, '!', ctx->len);
2496 }
2497 return ret;
2498 }
2499 #endif /* MBEDTLS_PKCS1_V15 */
2500
2501 /*
2502 * Do an RSA operation to sign the message digest
2503 */
mbedtls_rsa_pkcs1_sign(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,unsigned char * sig)2504 int mbedtls_rsa_pkcs1_sign(mbedtls_rsa_context *ctx,
2505 int (*f_rng)(void *, unsigned char *, size_t),
2506 void *p_rng,
2507 mbedtls_md_type_t md_alg,
2508 unsigned int hashlen,
2509 const unsigned char *hash,
2510 unsigned char *sig)
2511 {
2512 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2513 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2514 }
2515
2516 switch (ctx->padding) {
2517 #if defined(MBEDTLS_PKCS1_V15)
2518 case MBEDTLS_RSA_PKCS_V15:
2519 return mbedtls_rsa_rsassa_pkcs1_v15_sign(ctx, f_rng, p_rng,
2520 md_alg, hashlen, hash, sig);
2521 #endif
2522
2523 #if defined(MBEDTLS_PKCS1_V21)
2524 case MBEDTLS_RSA_PKCS_V21:
2525 return mbedtls_rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
2526 hashlen, hash, sig);
2527 #endif
2528
2529 default:
2530 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2531 }
2532 }
2533
2534 #if defined(MBEDTLS_PKCS1_V21)
2535 /*
2536 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2537 */
mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_rsa_context * ctx,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,mbedtls_md_type_t mgf1_hash_id,int expected_salt_len,const unsigned char * sig)2538 int mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_rsa_context *ctx,
2539 mbedtls_md_type_t md_alg,
2540 unsigned int hashlen,
2541 const unsigned char *hash,
2542 mbedtls_md_type_t mgf1_hash_id,
2543 int expected_salt_len,
2544 const unsigned char *sig)
2545 {
2546 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2547 size_t siglen;
2548 unsigned char *p;
2549 unsigned char *hash_start;
2550 unsigned char result[MBEDTLS_MD_MAX_SIZE];
2551 unsigned int hlen;
2552 size_t observed_salt_len, msb;
2553 unsigned char buf[MBEDTLS_MPI_MAX_SIZE] = { 0 };
2554
2555 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2556 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2557 }
2558
2559 siglen = ctx->len;
2560
2561 if (siglen < 16 || siglen > sizeof(buf)) {
2562 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2563 }
2564
2565 ret = mbedtls_rsa_public(ctx, sig, buf);
2566
2567 if (ret != 0) {
2568 return ret;
2569 }
2570
2571 p = buf;
2572
2573 if (buf[siglen - 1] != 0xBC) {
2574 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2575 }
2576
2577 if (md_alg != MBEDTLS_MD_NONE) {
2578 /* Gather length of hash to sign */
2579 size_t exp_hashlen = mbedtls_md_get_size_from_type(md_alg);
2580 if (exp_hashlen == 0) {
2581 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2582 }
2583
2584 if (hashlen != exp_hashlen) {
2585 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2586 }
2587 }
2588
2589 hlen = mbedtls_md_get_size_from_type(mgf1_hash_id);
2590 if (hlen == 0) {
2591 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2592 }
2593
2594 /*
2595 * Note: EMSA-PSS verification is over the length of N - 1 bits
2596 */
2597 msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2598
2599 if (buf[0] >> (8 - siglen * 8 + msb)) {
2600 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2601 }
2602
2603 /* Compensate for boundary condition when applying mask */
2604 if (msb % 8 == 0) {
2605 p++;
2606 siglen -= 1;
2607 }
2608
2609 if (siglen < hlen + 2) {
2610 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2611 }
2612 hash_start = p + siglen - hlen - 1;
2613
2614 ret = mgf_mask(p, siglen - hlen - 1, hash_start, hlen, mgf1_hash_id);
2615 if (ret != 0) {
2616 return ret;
2617 }
2618
2619 buf[0] &= 0xFF >> (siglen * 8 - msb);
2620
2621 while (p < hash_start - 1 && *p == 0) {
2622 p++;
2623 }
2624
2625 if (*p++ != 0x01) {
2626 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2627 }
2628
2629 observed_salt_len = (size_t) (hash_start - p);
2630
2631 if (expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
2632 observed_salt_len != (size_t) expected_salt_len) {
2633 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2634 }
2635
2636 /*
2637 * Generate H = Hash( M' )
2638 */
2639 ret = hash_mprime(hash, hashlen, p, observed_salt_len,
2640 result, mgf1_hash_id);
2641 if (ret != 0) {
2642 return ret;
2643 }
2644
2645 if (FTMN_CALLEE_DONE_MEMCMP(memcmp, hash_start, result, hlen) != 0) {
2646 return MBEDTLS_ERR_RSA_VERIFY_FAILED;
2647 }
2648
2649 return 0;
2650 }
2651
2652 /*
2653 * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2654 */
mbedtls_rsa_rsassa_pss_verify(mbedtls_rsa_context * ctx,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,const unsigned char * sig)2655 int mbedtls_rsa_rsassa_pss_verify(mbedtls_rsa_context *ctx,
2656 mbedtls_md_type_t md_alg,
2657 unsigned int hashlen,
2658 const unsigned char *hash,
2659 const unsigned char *sig)
2660 {
2661 mbedtls_md_type_t mgf1_hash_id;
2662 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2663 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2664 }
2665
2666 mgf1_hash_id = (ctx->hash_id != MBEDTLS_MD_NONE)
2667 ? (mbedtls_md_type_t) ctx->hash_id
2668 : md_alg;
2669
2670 return mbedtls_rsa_rsassa_pss_verify_ext(ctx,
2671 md_alg, hashlen, hash,
2672 mgf1_hash_id,
2673 MBEDTLS_RSA_SALT_LEN_ANY,
2674 sig);
2675
2676 }
2677 #endif /* MBEDTLS_PKCS1_V21 */
2678
2679 #if defined(MBEDTLS_PKCS1_V15)
2680 /*
2681 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
2682 */
mbedtls_rsa_rsassa_pkcs1_v15_verify(mbedtls_rsa_context * ctx,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,const unsigned char * sig)2683 int mbedtls_rsa_rsassa_pkcs1_v15_verify(mbedtls_rsa_context *ctx,
2684 mbedtls_md_type_t md_alg,
2685 unsigned int hashlen,
2686 const unsigned char *hash,
2687 const unsigned char *sig)
2688 {
2689 int ret = 0;
2690 size_t sig_len;
2691 unsigned char *encoded = NULL, *encoded_expected = NULL;
2692
2693 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2694 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2695 }
2696
2697 sig_len = ctx->len;
2698
2699 /*
2700 * Prepare expected PKCS1 v1.5 encoding of hash.
2701 */
2702
2703 if ((encoded = mbedtls_calloc(1, sig_len)) == NULL ||
2704 (encoded_expected = mbedtls_calloc(1, sig_len)) == NULL) {
2705 ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
2706 goto cleanup;
2707 }
2708
2709 if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash, sig_len,
2710 encoded_expected)) != 0) {
2711 goto cleanup;
2712 }
2713
2714 /*
2715 * Apply RSA primitive to get what should be PKCS1 encoded hash.
2716 */
2717
2718 ret = mbedtls_rsa_public(ctx, sig, encoded);
2719 if (ret != 0) {
2720 goto cleanup;
2721 }
2722
2723 /*
2724 * Compare
2725 */
2726
2727 if ((ret = FTMN_CALLEE_DONE_MEMCMP(mbedtls_ct_memcmp, encoded,
2728 encoded_expected, sig_len )) != 0) {
2729 ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
2730 goto cleanup;
2731 }
2732
2733 cleanup:
2734
2735 if (encoded != NULL) {
2736 mbedtls_zeroize_and_free(encoded, sig_len);
2737 }
2738
2739 if (encoded_expected != NULL) {
2740 mbedtls_zeroize_and_free(encoded_expected, sig_len);
2741 }
2742
2743 return ret;
2744 }
2745 #endif /* MBEDTLS_PKCS1_V15 */
2746
2747 /*
2748 * Do an RSA operation and check the message digest
2749 */
mbedtls_rsa_pkcs1_verify(mbedtls_rsa_context * ctx,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,const unsigned char * sig)2750 int mbedtls_rsa_pkcs1_verify(mbedtls_rsa_context *ctx,
2751 mbedtls_md_type_t md_alg,
2752 unsigned int hashlen,
2753 const unsigned char *hash,
2754 const unsigned char *sig)
2755 {
2756 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2757 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2758 }
2759
2760 switch (ctx->padding) {
2761 #if defined(MBEDTLS_PKCS1_V15)
2762 case MBEDTLS_RSA_PKCS_V15:
2763 return mbedtls_rsa_rsassa_pkcs1_v15_verify(ctx, md_alg,
2764 hashlen, hash, sig);
2765 #endif
2766
2767 #if defined(MBEDTLS_PKCS1_V21)
2768 case MBEDTLS_RSA_PKCS_V21:
2769 return mbedtls_rsa_rsassa_pss_verify(ctx, md_alg,
2770 hashlen, hash, sig);
2771 #endif
2772
2773 default:
2774 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2775 }
2776 }
2777
2778 /*
2779 * Copy the components of an RSA key
2780 */
mbedtls_rsa_copy(mbedtls_rsa_context * dst,const mbedtls_rsa_context * src)2781 int mbedtls_rsa_copy(mbedtls_rsa_context *dst, const mbedtls_rsa_context *src)
2782 {
2783 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2784
2785 dst->len = src->len;
2786
2787 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->N, &src->N));
2788 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->E, &src->E));
2789
2790 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->D, &src->D));
2791 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->P, &src->P));
2792 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Q, &src->Q));
2793
2794 #if !defined(MBEDTLS_RSA_NO_CRT)
2795 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DP, &src->DP));
2796 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DQ, &src->DQ));
2797 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->QP, &src->QP));
2798 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RP, &src->RP));
2799 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RQ, &src->RQ));
2800 #endif
2801
2802 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RN, &src->RN));
2803
2804 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vi, &src->Vi));
2805 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vf, &src->Vf));
2806
2807 dst->padding = src->padding;
2808 dst->hash_id = src->hash_id;
2809
2810 cleanup:
2811 if (ret != 0) {
2812 mbedtls_rsa_free(dst);
2813 }
2814
2815 return ret;
2816 }
2817
2818 /*
2819 * Free the components of an RSA key
2820 */
mbedtls_rsa_free(mbedtls_rsa_context * ctx)2821 void mbedtls_rsa_free(mbedtls_rsa_context *ctx)
2822 {
2823 if (ctx == NULL) {
2824 return;
2825 }
2826
2827 mbedtls_mpi_free(&ctx->Vi);
2828 mbedtls_mpi_free(&ctx->Vf);
2829 mbedtls_mpi_free(&ctx->RN);
2830 mbedtls_mpi_free(&ctx->D);
2831 mbedtls_mpi_free(&ctx->Q);
2832 mbedtls_mpi_free(&ctx->P);
2833 mbedtls_mpi_free(&ctx->E);
2834 mbedtls_mpi_free(&ctx->N);
2835
2836 #if !defined(MBEDTLS_RSA_NO_CRT)
2837 mbedtls_mpi_free(&ctx->RQ);
2838 mbedtls_mpi_free(&ctx->RP);
2839 mbedtls_mpi_free(&ctx->QP);
2840 mbedtls_mpi_free(&ctx->DQ);
2841 mbedtls_mpi_free(&ctx->DP);
2842 #endif /* MBEDTLS_RSA_NO_CRT */
2843
2844 #if defined(MBEDTLS_THREADING_C)
2845 /* Free the mutex, but only if it hasn't been freed already. */
2846 if (ctx->ver != 0) {
2847 mbedtls_mutex_free(&ctx->mutex);
2848 ctx->ver = 0;
2849 }
2850 #endif
2851 }
2852
2853 #endif /* !MBEDTLS_RSA_ALT */
2854
2855 #if defined(MBEDTLS_SELF_TEST)
2856
2857
2858 /*
2859 * Example RSA-1024 keypair, for test purposes
2860 */
2861 #define KEY_LEN 128
2862
2863 #define RSA_N "9292758453063D803DD603D5E777D788" \
2864 "8ED1D5BF35786190FA2F23EBC0848AEA" \
2865 "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
2866 "7130B9CED7ACDF54CFC7555AC14EEBAB" \
2867 "93A89813FBF3C4F8066D2D800F7C38A8" \
2868 "1AE31942917403FF4946B0A83D3D3E05" \
2869 "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
2870 "5E94BB77B07507233A0BC7BAC8F90F79"
2871
2872 #define RSA_E "10001"
2873
2874 #define RSA_D "24BF6185468786FDD303083D25E64EFC" \
2875 "66CA472BC44D253102F8B4A9D3BFA750" \
2876 "91386C0077937FE33FA3252D28855837" \
2877 "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
2878 "DF79C5CE07EE72C7F123142198164234" \
2879 "CABB724CF78B8173B9F880FC86322407" \
2880 "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
2881 "071513A1E85B5DFA031F21ECAE91A34D"
2882
2883 #define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
2884 "2C01CAD19EA484A87EA4377637E75500" \
2885 "FCB2005C5C7DD6EC4AC023CDA285D796" \
2886 "C3D9E75E1EFC42488BB4F1D13AC30A57"
2887
2888 #define RSA_Q "C000DF51A7C77AE8D7C7370C1FF55B69" \
2889 "E211C2B9E5DB1ED0BF61D0D9899620F4" \
2890 "910E4168387E3C30AA1E00C339A79508" \
2891 "8452DD96A9A5EA5D9DCA68DA636032AF"
2892
2893 #define PT_LEN 24
2894 #define RSA_PT "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
2895 "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
2896
2897 #if defined(MBEDTLS_PKCS1_V15)
myrand(void * rng_state,unsigned char * output,size_t len)2898 static int myrand(void *rng_state, unsigned char *output, size_t len)
2899 {
2900 #if !defined(__OpenBSD__) && !defined(__NetBSD__)
2901 size_t i;
2902
2903 if (rng_state != NULL) {
2904 rng_state = NULL;
2905 }
2906
2907 for (i = 0; i < len; ++i) {
2908 output[i] = rand();
2909 }
2910 #else
2911 if (rng_state != NULL) {
2912 rng_state = NULL;
2913 }
2914
2915 arc4random_buf(output, len);
2916 #endif /* !OpenBSD && !NetBSD */
2917
2918 return 0;
2919 }
2920 #endif /* MBEDTLS_PKCS1_V15 */
2921
2922 /*
2923 * Checkup routine
2924 */
mbedtls_rsa_self_test(int verbose)2925 int mbedtls_rsa_self_test(int verbose)
2926 {
2927 int ret = 0;
2928 #if defined(MBEDTLS_PKCS1_V15)
2929 size_t len;
2930 mbedtls_rsa_context rsa;
2931 unsigned char rsa_plaintext[PT_LEN];
2932 unsigned char rsa_decrypted[PT_LEN];
2933 unsigned char rsa_ciphertext[KEY_LEN];
2934 #if defined(MBEDTLS_MD_CAN_SHA1)
2935 unsigned char sha1sum[20];
2936 #endif
2937
2938 mbedtls_mpi K;
2939
2940 mbedtls_mpi_init(&K);
2941 mbedtls_rsa_init(&rsa);
2942
2943 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_N));
2944 MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, &K, NULL, NULL, NULL, NULL));
2945 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_P));
2946 MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, &K, NULL, NULL, NULL));
2947 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_Q));
2948 MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, &K, NULL, NULL));
2949 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_D));
2950 MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, &K, NULL));
2951 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_E));
2952 MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, NULL, &K));
2953
2954 MBEDTLS_MPI_CHK(mbedtls_rsa_complete(&rsa));
2955
2956 if (verbose != 0) {
2957 mbedtls_printf(" RSA key validation: ");
2958 }
2959
2960 if (mbedtls_rsa_check_pubkey(&rsa) != 0 ||
2961 mbedtls_rsa_check_privkey(&rsa) != 0) {
2962 if (verbose != 0) {
2963 mbedtls_printf("failed\n");
2964 }
2965
2966 ret = 1;
2967 goto cleanup;
2968 }
2969
2970 if (verbose != 0) {
2971 mbedtls_printf("passed\n PKCS#1 encryption : ");
2972 }
2973
2974 memcpy(rsa_plaintext, RSA_PT, PT_LEN);
2975
2976 if (mbedtls_rsa_pkcs1_encrypt(&rsa, myrand, NULL,
2977 PT_LEN, rsa_plaintext,
2978 rsa_ciphertext) != 0) {
2979 if (verbose != 0) {
2980 mbedtls_printf("failed\n");
2981 }
2982
2983 ret = 1;
2984 goto cleanup;
2985 }
2986
2987 if (verbose != 0) {
2988 mbedtls_printf("passed\n PKCS#1 decryption : ");
2989 }
2990
2991 if (mbedtls_rsa_pkcs1_decrypt(&rsa, myrand, NULL,
2992 &len, rsa_ciphertext, rsa_decrypted,
2993 sizeof(rsa_decrypted)) != 0) {
2994 if (verbose != 0) {
2995 mbedtls_printf("failed\n");
2996 }
2997
2998 ret = 1;
2999 goto cleanup;
3000 }
3001
3002 if (memcmp(rsa_decrypted, rsa_plaintext, len) != 0) {
3003 if (verbose != 0) {
3004 mbedtls_printf("failed\n");
3005 }
3006
3007 ret = 1;
3008 goto cleanup;
3009 }
3010
3011 if (verbose != 0) {
3012 mbedtls_printf("passed\n");
3013 }
3014
3015 #if defined(MBEDTLS_MD_CAN_SHA1)
3016 if (verbose != 0) {
3017 mbedtls_printf(" PKCS#1 data sign : ");
3018 }
3019
3020 if (mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1),
3021 rsa_plaintext, PT_LEN, sha1sum) != 0) {
3022 if (verbose != 0) {
3023 mbedtls_printf("failed\n");
3024 }
3025
3026 return 1;
3027 }
3028
3029 if (mbedtls_rsa_pkcs1_sign(&rsa, myrand, NULL,
3030 MBEDTLS_MD_SHA1, 20,
3031 sha1sum, rsa_ciphertext) != 0) {
3032 if (verbose != 0) {
3033 mbedtls_printf("failed\n");
3034 }
3035
3036 ret = 1;
3037 goto cleanup;
3038 }
3039
3040 if (verbose != 0) {
3041 mbedtls_printf("passed\n PKCS#1 sig. verify: ");
3042 }
3043
3044 if (mbedtls_rsa_pkcs1_verify(&rsa, MBEDTLS_MD_SHA1, 20,
3045 sha1sum, rsa_ciphertext) != 0) {
3046 if (verbose != 0) {
3047 mbedtls_printf("failed\n");
3048 }
3049
3050 ret = 1;
3051 goto cleanup;
3052 }
3053
3054 if (verbose != 0) {
3055 mbedtls_printf("passed\n");
3056 }
3057 #endif /* MBEDTLS_MD_CAN_SHA1 */
3058
3059 if (verbose != 0) {
3060 mbedtls_printf("\n");
3061 }
3062
3063 cleanup:
3064 mbedtls_mpi_free(&K);
3065 mbedtls_rsa_free(&rsa);
3066 #else /* MBEDTLS_PKCS1_V15 */
3067 ((void) verbose);
3068 #endif /* MBEDTLS_PKCS1_V15 */
3069 return ret;
3070 }
3071
3072 #endif /* MBEDTLS_SELF_TEST */
3073
3074 #endif /* MBEDTLS_RSA_C */
3075