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;
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
1066 if (exponent < 3 || nbits % 2 != 0) {
1067 ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1068 goto cleanup;
1069 }
1070
1071 if (nbits < MBEDTLS_RSA_GEN_KEY_MIN_BITS) {
1072 ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1073 goto cleanup;
1074 }
1075
1076 /*
1077 * find primes P and Q with Q < P so that:
1078 * 1. |P-Q| > 2^( nbits / 2 - 100 )
1079 * 2. GCD( E, (P-1)*(Q-1) ) == 1
1080 * 3. E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )
1081 */
1082 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&ctx->E, exponent));
1083
1084 do {
1085 MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->P, nbits >> 1,
1086 prime_quality, f_rng, p_rng));
1087
1088 MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->Q, nbits >> 1,
1089 prime_quality, f_rng, p_rng));
1090
1091 /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */
1092 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&H, &ctx->P, &ctx->Q));
1093 if (mbedtls_mpi_bitlen(&H) <= ((nbits >= 200) ? ((nbits >> 1) - 99) : 0)) {
1094 continue;
1095 }
1096
1097 /* not required by any standards, but some users rely on the fact that P > Q */
1098 if (H.s < 0) {
1099 mbedtls_mpi_swap(&ctx->P, &ctx->Q);
1100 }
1101
1102 /* Compute D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b))
1103 * if it exists (FIPS 186-4 §B.3.1 criterion 2(a)) */
1104 ret = mbedtls_rsa_deduce_private_exponent(&ctx->P, &ctx->Q, &ctx->E, &ctx->D);
1105 if (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
1106 mbedtls_mpi_lset(&ctx->D, 0); /* needed for the next call */
1107 continue;
1108 }
1109 if (ret != 0) {
1110 goto cleanup;
1111 }
1112
1113 /* (FIPS 186-4 §B.3.1 criterion 3(a)) */
1114 if (mbedtls_mpi_bitlen(&ctx->D) <= ((nbits + 1) / 2)) {
1115 continue;
1116 }
1117
1118 break;
1119 } while (1);
1120
1121
1122 /* N = P * Q */
1123 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q));
1124 ctx->len = mbedtls_mpi_size(&ctx->N);
1125
1126 #if !defined(MBEDTLS_RSA_NO_CRT)
1127 /*
1128 * DP = D mod (P - 1)
1129 * DQ = D mod (Q - 1)
1130 * QP = Q^-1 mod P
1131 */
1132 MBEDTLS_MPI_CHK(mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
1133 &ctx->DP, &ctx->DQ, &ctx->QP));
1134 #endif /* MBEDTLS_RSA_NO_CRT */
1135
1136 /* Double-check */
1137 MBEDTLS_MPI_CHK(mbedtls_rsa_check_privkey(ctx));
1138
1139 cleanup:
1140
1141 mbedtls_mpi_free(&H);
1142
1143 if (ret != 0) {
1144 mbedtls_rsa_free(ctx);
1145
1146 if ((-ret & ~0x7f) == 0) {
1147 ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_KEY_GEN_FAILED, ret);
1148 }
1149 return ret;
1150 }
1151
1152 return 0;
1153 }
1154
1155 #endif /* MBEDTLS_GENPRIME */
1156
1157 /*
1158 * Check a public RSA key
1159 */
mbedtls_rsa_check_pubkey(const mbedtls_rsa_context * ctx)1160 int mbedtls_rsa_check_pubkey(const mbedtls_rsa_context *ctx)
1161 {
1162 if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */) != 0) {
1163 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1164 }
1165
1166 if (mbedtls_mpi_bitlen(&ctx->N) < 128) {
1167 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1168 }
1169
1170 if (mbedtls_mpi_get_bit(&ctx->E, 0) == 0 ||
1171 mbedtls_mpi_bitlen(&ctx->E) < 2 ||
1172 mbedtls_mpi_cmp_mpi(&ctx->E, &ctx->N) >= 0) {
1173 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1174 }
1175
1176 return 0;
1177 }
1178
1179 /*
1180 * Check for the consistency of all fields in an RSA private key context
1181 */
mbedtls_rsa_check_privkey(const mbedtls_rsa_context * ctx)1182 int mbedtls_rsa_check_privkey(const mbedtls_rsa_context *ctx)
1183 {
1184 if (mbedtls_rsa_check_pubkey(ctx) != 0 ||
1185 rsa_check_context(ctx, 1 /* private */, 1 /* blinding */) != 0) {
1186 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1187 }
1188
1189 if (mbedtls_rsa_validate_params(&ctx->N, &ctx->P, &ctx->Q,
1190 &ctx->D, &ctx->E, NULL, NULL) != 0) {
1191 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1192 }
1193
1194 #if !defined(MBEDTLS_RSA_NO_CRT)
1195 else if (mbedtls_rsa_validate_crt(&ctx->P, &ctx->Q, &ctx->D,
1196 &ctx->DP, &ctx->DQ, &ctx->QP) != 0) {
1197 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1198 }
1199 #endif
1200
1201 return 0;
1202 }
1203
1204 /*
1205 * Check if contexts holding a public and private key match
1206 */
mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context * pub,const mbedtls_rsa_context * prv)1207 int mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context *pub,
1208 const mbedtls_rsa_context *prv)
1209 {
1210 if (mbedtls_rsa_check_pubkey(pub) != 0 ||
1211 mbedtls_rsa_check_privkey(prv) != 0) {
1212 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1213 }
1214
1215 if (mbedtls_mpi_cmp_mpi(&pub->N, &prv->N) != 0 ||
1216 mbedtls_mpi_cmp_mpi(&pub->E, &prv->E) != 0) {
1217 return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1218 }
1219
1220 return 0;
1221 }
1222
1223 /*
1224 * Do an RSA public key operation
1225 */
mbedtls_rsa_public(mbedtls_rsa_context * ctx,const unsigned char * input,unsigned char * output)1226 int mbedtls_rsa_public(mbedtls_rsa_context *ctx,
1227 const unsigned char *input,
1228 unsigned char *output)
1229 {
1230 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1231 size_t olen;
1232 mbedtls_mpi T;
1233
1234 if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */)) {
1235 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1236 }
1237
1238 mbedtls_mpi_init(&T);
1239
1240 #if defined(MBEDTLS_THREADING_C)
1241 if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
1242 return ret;
1243 }
1244 #endif
1245
1246 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
1247
1248 if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
1249 ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
1250 goto cleanup;
1251 }
1252
1253 olen = ctx->len;
1254 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod_unsafe(&T, &T, &ctx->E, &ctx->N, &ctx->RN));
1255 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
1256
1257 cleanup:
1258 #if defined(MBEDTLS_THREADING_C)
1259 if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
1260 return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
1261 }
1262 #endif
1263
1264 mbedtls_mpi_free(&T);
1265
1266 if (ret != 0) {
1267 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PUBLIC_FAILED, ret);
1268 }
1269
1270 return 0;
1271 }
1272
1273 /*
1274 * Generate or update blinding values, see section 10 of:
1275 * KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
1276 * DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
1277 * Berlin Heidelberg, 1996. p. 104-113.
1278 */
rsa_prepare_blinding(mbedtls_rsa_context * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1279 static int rsa_prepare_blinding(mbedtls_rsa_context *ctx,
1280 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1281 {
1282 int ret, count = 0;
1283 mbedtls_mpi R;
1284
1285 mbedtls_mpi_init(&R);
1286
1287 if (ctx->Vf.p != NULL) {
1288 /* We already have blinding values, just update them by squaring */
1289 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &ctx->Vi));
1290 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
1291 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vf, &ctx->Vf));
1292 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->N));
1293
1294 goto cleanup;
1295 }
1296
1297 /* Unblinding value: Vf = random number, invertible mod N */
1298 mbedtls_mpi_lset(&R, 0);
1299 do {
1300 if (count++ > 10) {
1301 ret = MBEDTLS_ERR_RSA_RNG_FAILED;
1302 goto cleanup;
1303 }
1304
1305 MBEDTLS_MPI_CHK(mbedtls_mpi_random(&ctx->Vf, 1, &ctx->N, f_rng, p_rng));
1306 MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(&R, &ctx->Vi, &ctx->Vf, &ctx->N));
1307 } while (mbedtls_mpi_cmp_int(&R, 1) != 0);
1308
1309 /* Blinding value: Vi = Vf^(-e) mod N
1310 * (Vi already contains Vf^-1 at this point) */
1311 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN));
1312
1313
1314 cleanup:
1315 mbedtls_mpi_free(&R);
1316
1317 return ret;
1318 }
1319
1320 /*
1321 * Unblind
1322 * T = T * Vf mod N
1323 */
rsa_unblind(mbedtls_mpi * T,mbedtls_mpi * Vf,const mbedtls_mpi * N)1324 static int rsa_unblind(mbedtls_mpi *T, mbedtls_mpi *Vf, const mbedtls_mpi *N)
1325 {
1326 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1327 const mbedtls_mpi_uint mm = mbedtls_mpi_core_montmul_init(N->p);
1328 const size_t nlimbs = N->n;
1329 const size_t tlimbs = mbedtls_mpi_core_montmul_working_limbs(nlimbs);
1330 mbedtls_mpi RR, M_T;
1331
1332 mbedtls_mpi_init(&RR);
1333 mbedtls_mpi_init(&M_T);
1334
1335 MBEDTLS_MPI_CHK(mbedtls_mpi_core_get_mont_r2_unsafe(&RR, N));
1336 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&M_T, tlimbs));
1337
1338 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(T, nlimbs));
1339 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Vf, nlimbs));
1340
1341 /* T = T * Vf mod N
1342 * Reminder: montmul(A, B, N) = A * B * R^-1 mod N
1343 * Usually both operands are multiplied by R mod N beforehand (by calling
1344 * `to_mont_rep()` on them), yielding a result that's also * R mod N (aka
1345 * "in the Montgomery domain"). Here we only multiply one operand by R mod
1346 * N, so the result is directly what we want - no need to call
1347 * `from_mont_rep()` on it. */
1348 mbedtls_mpi_core_to_mont_rep(T->p, T->p, N->p, nlimbs, mm, RR.p, M_T.p);
1349 mbedtls_mpi_core_montmul(T->p, T->p, Vf->p, nlimbs, N->p, nlimbs, mm, M_T.p);
1350
1351 cleanup:
1352
1353 mbedtls_mpi_free(&RR);
1354 mbedtls_mpi_free(&M_T);
1355
1356 return ret;
1357 }
1358
1359 /*
1360 * Exponent blinding supposed to prevent side-channel attacks using multiple
1361 * traces of measurements to recover the RSA key. The more collisions are there,
1362 * the more bits of the key can be recovered. See [3].
1363 *
1364 * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
1365 * observations on average.
1366 *
1367 * For example with 28 byte blinding to achieve 2 collisions the adversary has
1368 * to make 2^112 observations on average.
1369 *
1370 * (With the currently (as of 2017 April) known best algorithms breaking 2048
1371 * bit RSA requires approximately as much time as trying out 2^112 random keys.
1372 * Thus in this sense with 28 byte blinding the security is not reduced by
1373 * side-channel attacks like the one in [3])
1374 *
1375 * This countermeasure does not help if the key recovery is possible with a
1376 * single trace.
1377 */
1378 #define RSA_EXPONENT_BLINDING 28
1379
1380 /*
1381 * Do an RSA private key operation
1382 */
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)1383 int mbedtls_rsa_private(mbedtls_rsa_context *ctx,
1384 int (*f_rng)(void *, unsigned char *, size_t),
1385 void *p_rng,
1386 const unsigned char *input,
1387 unsigned char *output)
1388 {
1389 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1390 size_t olen;
1391
1392 /* Temporary holding the result */
1393 mbedtls_mpi T;
1394
1395 /* Temporaries holding P-1, Q-1 and the
1396 * exponent blinding factor, respectively. */
1397 mbedtls_mpi P1, Q1, R;
1398
1399 #if !defined(MBEDTLS_RSA_NO_CRT)
1400 /* Temporaries holding the results mod p resp. mod q. */
1401 mbedtls_mpi TP, TQ;
1402
1403 /* Temporaries holding the blinded exponents for
1404 * the mod p resp. mod q computation (if used). */
1405 mbedtls_mpi DP_blind, DQ_blind;
1406 #else
1407 /* Temporary holding the blinded exponent (if used). */
1408 mbedtls_mpi D_blind;
1409 #endif /* MBEDTLS_RSA_NO_CRT */
1410
1411 /* Temporaries holding the initial input and the double
1412 * checked result; should be the same in the end. */
1413 mbedtls_mpi input_blinded, check_result_blinded;
1414
1415 if (f_rng == NULL) {
1416 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1417 }
1418
1419 if (rsa_check_context(ctx, 1 /* private key checks */,
1420 1 /* blinding on */) != 0) {
1421 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1422 }
1423
1424 #if defined(MBEDTLS_THREADING_C)
1425 if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
1426 return ret;
1427 }
1428 #endif
1429
1430 /* MPI Initialization */
1431 mbedtls_mpi_init(&T);
1432
1433 mbedtls_mpi_init(&P1);
1434 mbedtls_mpi_init(&Q1);
1435 mbedtls_mpi_init(&R);
1436
1437 #if defined(MBEDTLS_RSA_NO_CRT)
1438 mbedtls_mpi_init(&D_blind);
1439 #else
1440 mbedtls_mpi_init(&DP_blind);
1441 mbedtls_mpi_init(&DQ_blind);
1442 #endif
1443
1444 #if !defined(MBEDTLS_RSA_NO_CRT)
1445 mbedtls_mpi_init(&TP); mbedtls_mpi_init(&TQ);
1446 #endif
1447
1448 mbedtls_mpi_init(&input_blinded);
1449 mbedtls_mpi_init(&check_result_blinded);
1450
1451 /* End of MPI initialization */
1452
1453 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
1454 if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
1455 ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
1456 goto cleanup;
1457 }
1458
1459 /*
1460 * Blinding
1461 * T = T * Vi mod N
1462 */
1463 MBEDTLS_MPI_CHK(rsa_prepare_blinding(ctx, f_rng, p_rng));
1464 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vi));
1465 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N));
1466
1467 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&input_blinded, &T));
1468
1469 /*
1470 * Exponent blinding
1471 */
1472 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&P1, &ctx->P, 1));
1473 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&Q1, &ctx->Q, 1));
1474
1475 #if defined(MBEDTLS_RSA_NO_CRT)
1476 /*
1477 * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
1478 */
1479 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
1480 f_rng, p_rng));
1481 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &P1, &Q1));
1482 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &D_blind, &R));
1483 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&D_blind, &D_blind, &ctx->D));
1484 #else
1485 /*
1486 * DP_blind = ( P - 1 ) * R + DP
1487 */
1488 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
1489 f_rng, p_rng));
1490 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DP_blind, &P1, &R));
1491 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DP_blind, &DP_blind,
1492 &ctx->DP));
1493
1494 /*
1495 * DQ_blind = ( Q - 1 ) * R + DQ
1496 */
1497 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
1498 f_rng, p_rng));
1499 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DQ_blind, &Q1, &R));
1500 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DQ_blind, &DQ_blind,
1501 &ctx->DQ));
1502 #endif /* MBEDTLS_RSA_NO_CRT */
1503
1504 #if defined(MBEDTLS_RSA_NO_CRT)
1505 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, &D_blind, &ctx->N, &ctx->RN));
1506 #else
1507 /*
1508 * Faster decryption using the CRT
1509 *
1510 * TP = input ^ dP mod P
1511 * TQ = input ^ dQ mod Q
1512 */
1513
1514 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TP, &T, &DP_blind, &ctx->P, &ctx->RP));
1515 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TQ, &T, &DQ_blind, &ctx->Q, &ctx->RQ));
1516
1517 /*
1518 * T = (TP - TQ) * (Q^-1 mod P) mod P
1519 */
1520 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&T, &TP, &TQ));
1521 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->QP));
1522 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &TP, &ctx->P));
1523
1524 /*
1525 * T = TQ + T * Q
1526 */
1527 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->Q));
1528 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&T, &TQ, &TP));
1529 #endif /* MBEDTLS_RSA_NO_CRT */
1530
1531 /* Verify the result to prevent glitching attacks. */
1532 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&check_result_blinded, &T, &ctx->E,
1533 &ctx->N, &ctx->RN));
1534 if (mbedtls_mpi_cmp_mpi(&check_result_blinded, &input_blinded) != 0) {
1535 ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
1536 goto cleanup;
1537 }
1538
1539 /*
1540 * Unblind
1541 * T = T * Vf mod N
1542 */
1543 MBEDTLS_MPI_CHK(rsa_unblind(&T, &ctx->Vf, &ctx->N));
1544
1545 olen = ctx->len;
1546 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
1547
1548 cleanup:
1549 #if defined(MBEDTLS_THREADING_C)
1550 if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
1551 return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
1552 }
1553 #endif
1554
1555 mbedtls_mpi_free(&P1);
1556 mbedtls_mpi_free(&Q1);
1557 mbedtls_mpi_free(&R);
1558
1559 #if defined(MBEDTLS_RSA_NO_CRT)
1560 mbedtls_mpi_free(&D_blind);
1561 #else
1562 mbedtls_mpi_free(&DP_blind);
1563 mbedtls_mpi_free(&DQ_blind);
1564 #endif
1565
1566 mbedtls_mpi_free(&T);
1567
1568 #if !defined(MBEDTLS_RSA_NO_CRT)
1569 mbedtls_mpi_free(&TP); mbedtls_mpi_free(&TQ);
1570 #endif
1571
1572 mbedtls_mpi_free(&check_result_blinded);
1573 mbedtls_mpi_free(&input_blinded);
1574
1575 if (ret != 0 && ret >= -0x007f) {
1576 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PRIVATE_FAILED, ret);
1577 }
1578
1579 return ret;
1580 }
1581
1582 #if defined(MBEDTLS_PKCS1_V21)
1583 /**
1584 * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
1585 *
1586 * \param dst buffer to mask
1587 * \param dlen length of destination buffer
1588 * \param src source of the mask generation
1589 * \param slen length of the source buffer
1590 * \param md_alg message digest to use
1591 */
mgf_mask(unsigned char * dst,size_t dlen,unsigned char * src,size_t slen,mbedtls_md_type_t md_alg)1592 static int mgf_mask(unsigned char *dst, size_t dlen, unsigned char *src,
1593 size_t slen, mbedtls_md_type_t md_alg)
1594 {
1595 unsigned char counter[4];
1596 unsigned char *p;
1597 unsigned int hlen;
1598 size_t i, use_len;
1599 unsigned char mask[MBEDTLS_MD_MAX_SIZE];
1600 int ret = 0;
1601 const mbedtls_md_info_t *md_info;
1602 mbedtls_md_context_t md_ctx;
1603
1604 mbedtls_md_init(&md_ctx);
1605 md_info = mbedtls_md_info_from_type(md_alg);
1606 if (md_info == NULL) {
1607 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1608 }
1609
1610 mbedtls_md_init(&md_ctx);
1611 if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1612 goto exit;
1613 }
1614
1615 hlen = mbedtls_md_get_size(md_info);
1616
1617 memset(mask, 0, sizeof(mask));
1618 memset(counter, 0, 4);
1619
1620 /* Generate and apply dbMask */
1621 p = dst;
1622
1623 while (dlen > 0) {
1624 use_len = hlen;
1625 if (dlen < hlen) {
1626 use_len = dlen;
1627 }
1628
1629 if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
1630 goto exit;
1631 }
1632 if ((ret = mbedtls_md_update(&md_ctx, src, slen)) != 0) {
1633 goto exit;
1634 }
1635 if ((ret = mbedtls_md_update(&md_ctx, counter, 4)) != 0) {
1636 goto exit;
1637 }
1638 if ((ret = mbedtls_md_finish(&md_ctx, mask)) != 0) {
1639 goto exit;
1640 }
1641
1642 for (i = 0; i < use_len; ++i) {
1643 *p++ ^= mask[i];
1644 }
1645
1646 counter[3]++;
1647
1648 dlen -= use_len;
1649 }
1650
1651 exit:
1652 mbedtls_platform_zeroize(mask, sizeof(mask));
1653 mbedtls_md_free(&md_ctx);
1654
1655 return ret;
1656 }
1657
1658 /**
1659 * Generate Hash(M') as in RFC 8017 page 43 points 5 and 6.
1660 *
1661 * \param hash the input hash
1662 * \param hlen length of the input hash
1663 * \param salt the input salt
1664 * \param slen length of the input salt
1665 * \param out the output buffer - must be large enough for \p md_alg
1666 * \param md_alg message digest to use
1667 */
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)1668 static int hash_mprime(const unsigned char *hash, size_t hlen,
1669 const unsigned char *salt, size_t slen,
1670 unsigned char *out, mbedtls_md_type_t md_alg)
1671 {
1672 const unsigned char zeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1673
1674 mbedtls_md_context_t md_ctx;
1675 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1676
1677 const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
1678 if (md_info == NULL) {
1679 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1680 }
1681
1682 mbedtls_md_init(&md_ctx);
1683 if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1684 goto exit;
1685 }
1686 if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
1687 goto exit;
1688 }
1689 if ((ret = mbedtls_md_update(&md_ctx, zeros, sizeof(zeros))) != 0) {
1690 goto exit;
1691 }
1692 if ((ret = mbedtls_md_update(&md_ctx, hash, hlen)) != 0) {
1693 goto exit;
1694 }
1695 if ((ret = mbedtls_md_update(&md_ctx, salt, slen)) != 0) {
1696 goto exit;
1697 }
1698 if ((ret = mbedtls_md_finish(&md_ctx, out)) != 0) {
1699 goto exit;
1700 }
1701
1702 exit:
1703 mbedtls_md_free(&md_ctx);
1704
1705 return ret;
1706 }
1707
1708 /**
1709 * Compute a hash.
1710 *
1711 * \param md_alg algorithm to use
1712 * \param input input message to hash
1713 * \param ilen input length
1714 * \param output the output buffer - must be large enough for \p md_alg
1715 */
compute_hash(mbedtls_md_type_t md_alg,const unsigned char * input,size_t ilen,unsigned char * output)1716 static int compute_hash(mbedtls_md_type_t md_alg,
1717 const unsigned char *input, size_t ilen,
1718 unsigned char *output)
1719 {
1720 const mbedtls_md_info_t *md_info;
1721
1722 md_info = mbedtls_md_info_from_type(md_alg);
1723 if (md_info == NULL) {
1724 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1725 }
1726
1727 return mbedtls_md(md_info, input, ilen, output);
1728 }
1729 #endif /* MBEDTLS_PKCS1_V21 */
1730
1731 #if defined(MBEDTLS_PKCS1_V21)
1732 /*
1733 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
1734 */
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)1735 int mbedtls_rsa_rsaes_oaep_encrypt(mbedtls_rsa_context *ctx,
1736 int (*f_rng)(void *, unsigned char *, size_t),
1737 void *p_rng,
1738 const unsigned char *label, size_t label_len,
1739 size_t ilen,
1740 const unsigned char *input,
1741 unsigned char *output)
1742 {
1743 size_t olen;
1744 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1745 unsigned char *p = output;
1746 unsigned int hlen;
1747
1748 if (f_rng == NULL) {
1749 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1750 }
1751
1752 hlen = mbedtls_md_get_size_from_type((mbedtls_md_type_t) ctx->hash_id);
1753 if (hlen == 0) {
1754 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1755 }
1756
1757 olen = ctx->len;
1758
1759 /* first comparison checks for overflow */
1760 if (ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2) {
1761 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1762 }
1763
1764 memset(output, 0, olen);
1765
1766 *p++ = 0;
1767
1768 /* Generate a random octet string seed */
1769 if ((ret = f_rng(p_rng, p, hlen)) != 0) {
1770 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1771 }
1772
1773 p += hlen;
1774
1775 /* Construct DB */
1776 ret = compute_hash((mbedtls_md_type_t) ctx->hash_id, label, label_len, p);
1777 if (ret != 0) {
1778 return ret;
1779 }
1780 p += hlen;
1781 p += olen - 2 * hlen - 2 - ilen;
1782 *p++ = 1;
1783 if (ilen != 0) {
1784 memcpy(p, input, ilen);
1785 }
1786
1787 /* maskedDB: Apply dbMask to DB */
1788 if ((ret = mgf_mask(output + hlen + 1, olen - hlen - 1, output + 1, hlen,
1789 (mbedtls_md_type_t) ctx->hash_id)) != 0) {
1790 return ret;
1791 }
1792
1793 /* maskedSeed: Apply seedMask to seed */
1794 if ((ret = mgf_mask(output + 1, hlen, output + hlen + 1, olen - hlen - 1,
1795 (mbedtls_md_type_t) ctx->hash_id)) != 0) {
1796 return ret;
1797 }
1798
1799 return mbedtls_rsa_public(ctx, output, output);
1800 }
1801 #endif /* MBEDTLS_PKCS1_V21 */
1802
1803 #if defined(MBEDTLS_PKCS1_V15)
1804 /*
1805 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
1806 */
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)1807 int mbedtls_rsa_rsaes_pkcs1_v15_encrypt(mbedtls_rsa_context *ctx,
1808 int (*f_rng)(void *, unsigned char *, size_t),
1809 void *p_rng, size_t ilen,
1810 const unsigned char *input,
1811 unsigned char *output)
1812 {
1813 size_t nb_pad, olen;
1814 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1815 unsigned char *p = output;
1816
1817 olen = ctx->len;
1818
1819 /* first comparison checks for overflow */
1820 if (ilen + 11 < ilen || olen < ilen + 11) {
1821 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1822 }
1823
1824 nb_pad = olen - 3 - ilen;
1825
1826 *p++ = 0;
1827
1828 if (f_rng == NULL) {
1829 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1830 }
1831
1832 *p++ = MBEDTLS_RSA_CRYPT;
1833
1834 while (nb_pad-- > 0) {
1835 int rng_dl = 100;
1836
1837 do {
1838 ret = f_rng(p_rng, p, 1);
1839 } while (*p == 0 && --rng_dl && ret == 0);
1840
1841 /* Check if RNG failed to generate data */
1842 if (rng_dl == 0 || ret != 0) {
1843 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1844 }
1845
1846 p++;
1847 }
1848
1849 *p++ = 0;
1850 if (ilen != 0) {
1851 memcpy(p, input, ilen);
1852 }
1853
1854 return mbedtls_rsa_public(ctx, output, output);
1855 }
1856 #endif /* MBEDTLS_PKCS1_V15 */
1857
1858 /*
1859 * Add the message padding, then do an RSA operation
1860 */
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)1861 int mbedtls_rsa_pkcs1_encrypt(mbedtls_rsa_context *ctx,
1862 int (*f_rng)(void *, unsigned char *, size_t),
1863 void *p_rng,
1864 size_t ilen,
1865 const unsigned char *input,
1866 unsigned char *output)
1867 {
1868 switch (ctx->padding) {
1869 #if defined(MBEDTLS_PKCS1_V15)
1870 case MBEDTLS_RSA_PKCS_V15:
1871 return mbedtls_rsa_rsaes_pkcs1_v15_encrypt(ctx, f_rng, p_rng,
1872 ilen, input, output);
1873 #endif
1874
1875 #if defined(MBEDTLS_PKCS1_V21)
1876 case MBEDTLS_RSA_PKCS_V21:
1877 return mbedtls_rsa_rsaes_oaep_encrypt(ctx, f_rng, p_rng, NULL, 0,
1878 ilen, input, output);
1879 #endif
1880
1881 default:
1882 return MBEDTLS_ERR_RSA_INVALID_PADDING;
1883 }
1884 }
1885
1886 #if defined(MBEDTLS_PKCS1_V21)
1887 /*
1888 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
1889 */
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)1890 int mbedtls_rsa_rsaes_oaep_decrypt(mbedtls_rsa_context *ctx,
1891 int (*f_rng)(void *, unsigned char *, size_t),
1892 void *p_rng,
1893 const unsigned char *label, size_t label_len,
1894 size_t *olen,
1895 const unsigned char *input,
1896 unsigned char *output,
1897 size_t output_max_len)
1898 {
1899 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1900 size_t ilen, i, pad_len;
1901 unsigned char *p;
1902 mbedtls_ct_condition_t bad, in_padding;
1903 unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
1904 unsigned char lhash[MBEDTLS_MD_MAX_SIZE];
1905 unsigned int hlen;
1906
1907 /*
1908 * Parameters sanity checks
1909 */
1910 if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
1911 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1912 }
1913
1914 ilen = ctx->len;
1915
1916 if (ilen < 16 || ilen > sizeof(buf)) {
1917 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1918 }
1919
1920 hlen = mbedtls_md_get_size_from_type((mbedtls_md_type_t) ctx->hash_id);
1921 if (hlen == 0) {
1922 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1923 }
1924
1925 // checking for integer underflow
1926 if (2 * hlen + 2 > ilen) {
1927 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1928 }
1929
1930 /*
1931 * RSA operation
1932 */
1933 if( ctx->P.n == 0 )
1934 ret = mbedtls_rsa_private( ctx, NULL, NULL, input, buf );
1935 else
1936 ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
1937
1938 if (ret != 0) {
1939 goto cleanup;
1940 }
1941
1942 /*
1943 * Unmask data and generate lHash
1944 */
1945 /* seed: Apply seedMask to maskedSeed */
1946 if ((ret = mgf_mask(buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
1947 (mbedtls_md_type_t) ctx->hash_id)) != 0 ||
1948 /* DB: Apply dbMask to maskedDB */
1949 (ret = mgf_mask(buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
1950 (mbedtls_md_type_t) ctx->hash_id)) != 0) {
1951 goto cleanup;
1952 }
1953
1954 /* Generate lHash */
1955 ret = compute_hash((mbedtls_md_type_t) ctx->hash_id,
1956 label, label_len, lhash);
1957 if (ret != 0) {
1958 goto cleanup;
1959 }
1960
1961 /*
1962 * Check contents, in "constant-time"
1963 */
1964 p = buf;
1965
1966 bad = mbedtls_ct_bool(*p++); /* First byte must be 0 */
1967
1968 p += hlen; /* Skip seed */
1969
1970 /* Check lHash */
1971 bad = mbedtls_ct_bool_or(bad, mbedtls_ct_bool(mbedtls_ct_memcmp(lhash, p, hlen)));
1972 p += hlen;
1973
1974 /* Get zero-padding len, but always read till end of buffer
1975 * (minus one, for the 01 byte) */
1976 pad_len = 0;
1977 in_padding = MBEDTLS_CT_TRUE;
1978 for (i = 0; i < ilen - 2 * hlen - 2; i++) {
1979 in_padding = mbedtls_ct_bool_and(in_padding, mbedtls_ct_uint_eq(p[i], 0));
1980 pad_len += mbedtls_ct_uint_if_else_0(in_padding, 1);
1981 }
1982
1983 p += pad_len;
1984 bad = mbedtls_ct_bool_or(bad, mbedtls_ct_uint_ne(*p++, 0x01));
1985
1986 /*
1987 * The only information "leaked" is whether the padding was correct or not
1988 * (eg, no data is copied if it was not correct). This meets the
1989 * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
1990 * the different error conditions.
1991 */
1992 if (bad != MBEDTLS_CT_FALSE) {
1993 ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
1994 goto cleanup;
1995 }
1996
1997 if (ilen - ((size_t) (p - buf)) > output_max_len) {
1998 ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
1999 goto cleanup;
2000 }
2001
2002 *olen = ilen - ((size_t) (p - buf));
2003 if (*olen != 0) {
2004 memcpy(output, p, *olen);
2005 }
2006 ret = 0;
2007
2008 cleanup:
2009 mbedtls_platform_zeroize(buf, sizeof(buf));
2010 mbedtls_platform_zeroize(lhash, sizeof(lhash));
2011
2012 return ret;
2013 }
2014 #endif /* MBEDTLS_PKCS1_V21 */
2015
2016 #if defined(MBEDTLS_PKCS1_V15)
2017 /*
2018 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
2019 */
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)2020 int mbedtls_rsa_rsaes_pkcs1_v15_decrypt(mbedtls_rsa_context *ctx,
2021 int (*f_rng)(void *, unsigned char *, size_t),
2022 void *p_rng,
2023 size_t *olen,
2024 const unsigned char *input,
2025 unsigned char *output,
2026 size_t output_max_len)
2027 {
2028 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2029 size_t ilen;
2030 unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
2031
2032 ilen = ctx->len;
2033
2034 if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
2035 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2036 }
2037
2038 if (ilen < 16 || ilen > sizeof(buf)) {
2039 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2040 }
2041
2042 ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
2043
2044 if (ret != 0) {
2045 goto cleanup;
2046 }
2047
2048 ret = mbedtls_ct_rsaes_pkcs1_v15_unpadding(buf, ilen,
2049 output, output_max_len, olen);
2050
2051 cleanup:
2052 mbedtls_platform_zeroize(buf, sizeof(buf));
2053
2054 return ret;
2055 }
2056 #endif /* MBEDTLS_PKCS1_V15 */
2057
2058 /*
2059 * Do an RSA operation, then remove the message padding
2060 */
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)2061 int mbedtls_rsa_pkcs1_decrypt(mbedtls_rsa_context *ctx,
2062 int (*f_rng)(void *, unsigned char *, size_t),
2063 void *p_rng,
2064 size_t *olen,
2065 const unsigned char *input,
2066 unsigned char *output,
2067 size_t output_max_len)
2068 {
2069 switch (ctx->padding) {
2070 #if defined(MBEDTLS_PKCS1_V15)
2071 case MBEDTLS_RSA_PKCS_V15:
2072 return mbedtls_rsa_rsaes_pkcs1_v15_decrypt(ctx, f_rng, p_rng, olen,
2073 input, output, output_max_len);
2074 #endif
2075
2076 #if defined(MBEDTLS_PKCS1_V21)
2077 case MBEDTLS_RSA_PKCS_V21:
2078 return mbedtls_rsa_rsaes_oaep_decrypt(ctx, f_rng, p_rng, NULL, 0,
2079 olen, input, output,
2080 output_max_len);
2081 #endif
2082
2083 default:
2084 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2085 }
2086 }
2087
2088 #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)2089 static int rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context *ctx,
2090 int (*f_rng)(void *, unsigned char *, size_t),
2091 void *p_rng,
2092 mbedtls_md_type_t md_alg,
2093 unsigned int hashlen,
2094 const unsigned char *hash,
2095 int saltlen,
2096 unsigned char *sig)
2097 {
2098 size_t olen;
2099 unsigned char *p = sig;
2100 unsigned char *salt = NULL;
2101 size_t slen, min_slen, hlen, offset = 0;
2102 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2103 size_t msb;
2104 mbedtls_md_type_t hash_id;
2105
2106 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2107 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2108 }
2109
2110 if (f_rng == NULL) {
2111 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2112 }
2113
2114 olen = ctx->len;
2115
2116 if (md_alg != MBEDTLS_MD_NONE) {
2117 /* Gather length of hash to sign */
2118 size_t exp_hashlen = mbedtls_md_get_size_from_type(md_alg);
2119 if (exp_hashlen == 0) {
2120 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2121 }
2122
2123 if (hashlen != exp_hashlen) {
2124 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2125 }
2126 }
2127
2128 hash_id = (mbedtls_md_type_t) ctx->hash_id;
2129 if (hash_id == MBEDTLS_MD_NONE) {
2130 hash_id = md_alg;
2131 }
2132 hlen = mbedtls_md_get_size_from_type(hash_id);
2133 if (hlen == 0) {
2134 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2135 }
2136
2137 if (saltlen == MBEDTLS_RSA_SALT_LEN_ANY) {
2138 /* Calculate the largest possible salt length, up to the hash size.
2139 * Normally this is the hash length, which is the maximum salt length
2140 * according to FIPS 185-4 §5.5 (e) and common practice. If there is not
2141 * enough room, use the maximum salt length that fits. The constraint is
2142 * that the hash length plus the salt length plus 2 bytes must be at most
2143 * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017
2144 * (PKCS#1 v2.2) §9.1.1 step 3. */
2145 min_slen = hlen - 2;
2146 if (olen < hlen + min_slen + 2) {
2147 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2148 } else if (olen >= hlen + hlen + 2) {
2149 slen = hlen;
2150 } else {
2151 slen = olen - hlen - 2;
2152 }
2153 } else if ((saltlen < 0) || (saltlen + hlen + 2 > olen)) {
2154 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2155 } else {
2156 slen = (size_t) saltlen;
2157 }
2158
2159 memset(sig, 0, olen);
2160
2161 /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
2162 msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2163 p += olen - hlen - slen - 2;
2164 *p++ = 0x01;
2165
2166 /* Generate salt of length slen in place in the encoded message */
2167 salt = p;
2168 if ((ret = f_rng(p_rng, salt, slen)) != 0) {
2169 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
2170 }
2171
2172 p += slen;
2173
2174 /* Generate H = Hash( M' ) */
2175 ret = hash_mprime(hash, hashlen, salt, slen, p, hash_id);
2176 if (ret != 0) {
2177 return ret;
2178 }
2179
2180 /* Compensate for boundary condition when applying mask */
2181 if (msb % 8 == 0) {
2182 offset = 1;
2183 }
2184
2185 /* maskedDB: Apply dbMask to DB */
2186 ret = mgf_mask(sig + offset, olen - hlen - 1 - offset, p, hlen, hash_id);
2187 if (ret != 0) {
2188 return ret;
2189 }
2190
2191 msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2192 sig[0] &= 0xFF >> (olen * 8 - msb);
2193
2194 p += hlen;
2195 *p++ = 0xBC;
2196
2197 if (ctx->P.n == 0)
2198 return mbedtls_rsa_private(ctx, NULL, NULL, sig, sig);
2199
2200 return mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig);
2201 }
2202
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)2203 static int rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
2204 int (*f_rng)(void *, unsigned char *, size_t),
2205 void *p_rng,
2206 mbedtls_md_type_t md_alg,
2207 unsigned int hashlen,
2208 const unsigned char *hash,
2209 int saltlen,
2210 unsigned char *sig)
2211 {
2212 if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
2213 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2214 }
2215 if ((ctx->hash_id == MBEDTLS_MD_NONE) && (md_alg == MBEDTLS_MD_NONE)) {
2216 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2217 }
2218 return rsa_rsassa_pss_sign_no_mode_check(ctx, f_rng, p_rng, md_alg, hashlen, hash, saltlen,
2219 sig);
2220 }
2221
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)2222 int mbedtls_rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context *ctx,
2223 int (*f_rng)(void *, unsigned char *, size_t),
2224 void *p_rng,
2225 mbedtls_md_type_t md_alg,
2226 unsigned int hashlen,
2227 const unsigned char *hash,
2228 unsigned char *sig)
2229 {
2230 return rsa_rsassa_pss_sign_no_mode_check(ctx, f_rng, p_rng, md_alg,
2231 hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
2232 }
2233
2234 /*
2235 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function with
2236 * the option to pass in the salt length.
2237 */
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)2238 int mbedtls_rsa_rsassa_pss_sign_ext(mbedtls_rsa_context *ctx,
2239 int (*f_rng)(void *, unsigned char *, size_t),
2240 void *p_rng,
2241 mbedtls_md_type_t md_alg,
2242 unsigned int hashlen,
2243 const unsigned char *hash,
2244 int saltlen,
2245 unsigned char *sig)
2246 {
2247 return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
2248 hashlen, hash, saltlen, sig);
2249 }
2250
2251 /*
2252 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
2253 */
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)2254 int mbedtls_rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
2255 int (*f_rng)(void *, unsigned char *, size_t),
2256 void *p_rng,
2257 mbedtls_md_type_t md_alg,
2258 unsigned int hashlen,
2259 const unsigned char *hash,
2260 unsigned char *sig)
2261 {
2262 return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
2263 hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
2264 }
2265 #endif /* MBEDTLS_PKCS1_V21 */
2266
2267 #if defined(MBEDTLS_PKCS1_V15)
2268 /*
2269 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
2270 */
2271
2272 /* Construct a PKCS v1.5 encoding of a hashed message
2273 *
2274 * This is used both for signature generation and verification.
2275 *
2276 * Parameters:
2277 * - md_alg: Identifies the hash algorithm used to generate the given hash;
2278 * MBEDTLS_MD_NONE if raw data is signed.
2279 * - hashlen: Length of hash. Must match md_alg if that's not NONE.
2280 * - hash: Buffer containing the hashed message or the raw data.
2281 * - dst_len: Length of the encoded message.
2282 * - dst: Buffer to hold the encoded message.
2283 *
2284 * Assumptions:
2285 * - hash has size hashlen.
2286 * - dst points to a buffer of size at least dst_len.
2287 *
2288 */
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)2289 static int rsa_rsassa_pkcs1_v15_encode(mbedtls_md_type_t md_alg,
2290 unsigned int hashlen,
2291 const unsigned char *hash,
2292 size_t dst_len,
2293 unsigned char *dst)
2294 {
2295 size_t oid_size = 0;
2296 size_t nb_pad = dst_len;
2297 unsigned char *p = dst;
2298 const char *oid = NULL;
2299
2300 /* Are we signing hashed or raw data? */
2301 if (md_alg != MBEDTLS_MD_NONE) {
2302 unsigned char md_size = mbedtls_md_get_size_from_type(md_alg);
2303 if (md_size == 0) {
2304 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2305 }
2306
2307 if (mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size) != 0) {
2308 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2309 }
2310
2311 if (hashlen != md_size) {
2312 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2313 }
2314
2315 /* Double-check that 8 + hashlen + oid_size can be used as a
2316 * 1-byte ASN.1 length encoding and that there's no overflow. */
2317 if (8 + hashlen + oid_size >= 0x80 ||
2318 10 + hashlen < hashlen ||
2319 10 + hashlen + oid_size < 10 + hashlen) {
2320 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2321 }
2322
2323 /*
2324 * Static bounds check:
2325 * - Need 10 bytes for five tag-length pairs.
2326 * (Insist on 1-byte length encodings to protect against variants of
2327 * Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)
2328 * - Need hashlen bytes for hash
2329 * - Need oid_size bytes for hash alg OID.
2330 */
2331 if (nb_pad < 10 + hashlen + oid_size) {
2332 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2333 }
2334 nb_pad -= 10 + hashlen + oid_size;
2335 } else {
2336 if (nb_pad < hashlen) {
2337 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2338 }
2339
2340 nb_pad -= hashlen;
2341 }
2342
2343 /* Need space for signature header and padding delimiter (3 bytes),
2344 * and 8 bytes for the minimal padding */
2345 if (nb_pad < 3 + 8) {
2346 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2347 }
2348 nb_pad -= 3;
2349
2350 /* Now nb_pad is the amount of memory to be filled
2351 * with padding, and at least 8 bytes long. */
2352
2353 /* Write signature header and padding */
2354 *p++ = 0;
2355 *p++ = MBEDTLS_RSA_SIGN;
2356 memset(p, 0xFF, nb_pad);
2357 p += nb_pad;
2358 *p++ = 0;
2359
2360 /* Are we signing raw data? */
2361 if (md_alg == MBEDTLS_MD_NONE) {
2362 memcpy(p, hash, hashlen);
2363 return 0;
2364 }
2365
2366 /* Signing hashed data, add corresponding ASN.1 structure
2367 *
2368 * DigestInfo ::= SEQUENCE {
2369 * digestAlgorithm DigestAlgorithmIdentifier,
2370 * digest Digest }
2371 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
2372 * Digest ::= OCTET STRING
2373 *
2374 * Schematic:
2375 * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID + LEN [ OID ]
2376 * TAG-NULL + LEN [ NULL ] ]
2377 * TAG-OCTET + LEN [ HASH ] ]
2378 */
2379 *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
2380 *p++ = (unsigned char) (0x08 + oid_size + hashlen);
2381 *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
2382 *p++ = (unsigned char) (0x04 + oid_size);
2383 *p++ = MBEDTLS_ASN1_OID;
2384 *p++ = (unsigned char) oid_size;
2385 memcpy(p, oid, oid_size);
2386 p += oid_size;
2387 *p++ = MBEDTLS_ASN1_NULL;
2388 *p++ = 0x00;
2389 *p++ = MBEDTLS_ASN1_OCTET_STRING;
2390 *p++ = (unsigned char) hashlen;
2391 memcpy(p, hash, hashlen);
2392 p += hashlen;
2393
2394 /* Just a sanity-check, should be automatic
2395 * after the initial bounds check. */
2396 if (p != dst + dst_len) {
2397 mbedtls_platform_zeroize(dst, dst_len);
2398 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2399 }
2400
2401 return 0;
2402 }
2403
2404 /*
2405 * Do an RSA operation to sign the message digest
2406 */
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)2407 int mbedtls_rsa_rsassa_pkcs1_v15_sign(mbedtls_rsa_context *ctx,
2408 int (*f_rng)(void *, unsigned char *, size_t),
2409 void *p_rng,
2410 mbedtls_md_type_t md_alg,
2411 unsigned int hashlen,
2412 const unsigned char *hash,
2413 unsigned char *sig)
2414 {
2415 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2416 unsigned char *sig_try = NULL, *verif = NULL;
2417
2418 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2419 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2420 }
2421
2422 if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
2423 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2424 }
2425
2426 /*
2427 * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
2428 */
2429
2430 if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash,
2431 ctx->len, sig)) != 0) {
2432 return ret;
2433 }
2434
2435 /* Private key operation
2436 *
2437 * In order to prevent Lenstra's attack, make the signature in a
2438 * temporary buffer and check it before returning it.
2439 */
2440
2441 sig_try = mbedtls_calloc(1, ctx->len);
2442 if (sig_try == NULL) {
2443 return MBEDTLS_ERR_MPI_ALLOC_FAILED;
2444 }
2445
2446 verif = mbedtls_calloc(1, ctx->len);
2447 if (verif == NULL) {
2448 mbedtls_free(sig_try);
2449 return MBEDTLS_ERR_MPI_ALLOC_FAILED;
2450 }
2451
2452 MBEDTLS_MPI_CHK(mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig_try));
2453 MBEDTLS_MPI_CHK(mbedtls_rsa_public(ctx, sig_try, verif));
2454
2455 if (mbedtls_ct_memcmp(verif, sig, ctx->len) != 0) {
2456 ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
2457 goto cleanup;
2458 }
2459
2460 memcpy(sig, sig_try, ctx->len);
2461
2462 cleanup:
2463 mbedtls_zeroize_and_free(sig_try, ctx->len);
2464 mbedtls_zeroize_and_free(verif, ctx->len);
2465
2466 if (ret != 0) {
2467 memset(sig, '!', ctx->len);
2468 }
2469 return ret;
2470 }
2471 #endif /* MBEDTLS_PKCS1_V15 */
2472
2473 /*
2474 * Do an RSA operation to sign the message digest
2475 */
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)2476 int mbedtls_rsa_pkcs1_sign(mbedtls_rsa_context *ctx,
2477 int (*f_rng)(void *, unsigned char *, size_t),
2478 void *p_rng,
2479 mbedtls_md_type_t md_alg,
2480 unsigned int hashlen,
2481 const unsigned char *hash,
2482 unsigned char *sig)
2483 {
2484 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2485 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2486 }
2487
2488 switch (ctx->padding) {
2489 #if defined(MBEDTLS_PKCS1_V15)
2490 case MBEDTLS_RSA_PKCS_V15:
2491 return mbedtls_rsa_rsassa_pkcs1_v15_sign(ctx, f_rng, p_rng,
2492 md_alg, hashlen, hash, sig);
2493 #endif
2494
2495 #if defined(MBEDTLS_PKCS1_V21)
2496 case MBEDTLS_RSA_PKCS_V21:
2497 return mbedtls_rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
2498 hashlen, hash, sig);
2499 #endif
2500
2501 default:
2502 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2503 }
2504 }
2505
2506 #if defined(MBEDTLS_PKCS1_V21)
2507 /*
2508 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2509 */
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)2510 int mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_rsa_context *ctx,
2511 mbedtls_md_type_t md_alg,
2512 unsigned int hashlen,
2513 const unsigned char *hash,
2514 mbedtls_md_type_t mgf1_hash_id,
2515 int expected_salt_len,
2516 const unsigned char *sig)
2517 {
2518 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2519 size_t siglen;
2520 unsigned char *p;
2521 unsigned char *hash_start;
2522 unsigned char result[MBEDTLS_MD_MAX_SIZE];
2523 unsigned int hlen;
2524 size_t observed_salt_len, msb;
2525 unsigned char buf[MBEDTLS_MPI_MAX_SIZE] = { 0 };
2526
2527 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2528 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2529 }
2530
2531 siglen = ctx->len;
2532
2533 if (siglen < 16 || siglen > sizeof(buf)) {
2534 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2535 }
2536
2537 ret = mbedtls_rsa_public(ctx, sig, buf);
2538
2539 if (ret != 0) {
2540 return ret;
2541 }
2542
2543 p = buf;
2544
2545 if (buf[siglen - 1] != 0xBC) {
2546 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2547 }
2548
2549 if (md_alg != MBEDTLS_MD_NONE) {
2550 /* Gather length of hash to sign */
2551 size_t exp_hashlen = mbedtls_md_get_size_from_type(md_alg);
2552 if (exp_hashlen == 0) {
2553 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2554 }
2555
2556 if (hashlen != exp_hashlen) {
2557 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2558 }
2559 }
2560
2561 hlen = mbedtls_md_get_size_from_type(mgf1_hash_id);
2562 if (hlen == 0) {
2563 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2564 }
2565
2566 /*
2567 * Note: EMSA-PSS verification is over the length of N - 1 bits
2568 */
2569 msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2570
2571 if (buf[0] >> (8 - siglen * 8 + msb)) {
2572 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2573 }
2574
2575 /* Compensate for boundary condition when applying mask */
2576 if (msb % 8 == 0) {
2577 p++;
2578 siglen -= 1;
2579 }
2580
2581 if (siglen < hlen + 2) {
2582 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2583 }
2584 hash_start = p + siglen - hlen - 1;
2585
2586 ret = mgf_mask(p, siglen - hlen - 1, hash_start, hlen, mgf1_hash_id);
2587 if (ret != 0) {
2588 return ret;
2589 }
2590
2591 buf[0] &= 0xFF >> (siglen * 8 - msb);
2592
2593 while (p < hash_start - 1 && *p == 0) {
2594 p++;
2595 }
2596
2597 if (*p++ != 0x01) {
2598 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2599 }
2600
2601 observed_salt_len = (size_t) (hash_start - p);
2602
2603 if (expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
2604 observed_salt_len != (size_t) expected_salt_len) {
2605 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2606 }
2607
2608 /*
2609 * Generate H = Hash( M' )
2610 */
2611 ret = hash_mprime(hash, hashlen, p, observed_salt_len,
2612 result, mgf1_hash_id);
2613 if (ret != 0) {
2614 return ret;
2615 }
2616
2617 if (FTMN_CALLEE_DONE_MEMCMP(memcmp, hash_start, result, hlen) != 0) {
2618 return MBEDTLS_ERR_RSA_VERIFY_FAILED;
2619 }
2620
2621 return 0;
2622 }
2623
2624 /*
2625 * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2626 */
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)2627 int mbedtls_rsa_rsassa_pss_verify(mbedtls_rsa_context *ctx,
2628 mbedtls_md_type_t md_alg,
2629 unsigned int hashlen,
2630 const unsigned char *hash,
2631 const unsigned char *sig)
2632 {
2633 mbedtls_md_type_t mgf1_hash_id;
2634 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2635 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2636 }
2637
2638 mgf1_hash_id = (ctx->hash_id != MBEDTLS_MD_NONE)
2639 ? (mbedtls_md_type_t) ctx->hash_id
2640 : md_alg;
2641
2642 return mbedtls_rsa_rsassa_pss_verify_ext(ctx,
2643 md_alg, hashlen, hash,
2644 mgf1_hash_id,
2645 MBEDTLS_RSA_SALT_LEN_ANY,
2646 sig);
2647
2648 }
2649 #endif /* MBEDTLS_PKCS1_V21 */
2650
2651 #if defined(MBEDTLS_PKCS1_V15)
2652 /*
2653 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
2654 */
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)2655 int mbedtls_rsa_rsassa_pkcs1_v15_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 int ret = 0;
2662 size_t sig_len;
2663 unsigned char *encoded = NULL, *encoded_expected = NULL;
2664
2665 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2666 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2667 }
2668
2669 sig_len = ctx->len;
2670
2671 /*
2672 * Prepare expected PKCS1 v1.5 encoding of hash.
2673 */
2674
2675 if ((encoded = mbedtls_calloc(1, sig_len)) == NULL ||
2676 (encoded_expected = mbedtls_calloc(1, sig_len)) == NULL) {
2677 ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
2678 goto cleanup;
2679 }
2680
2681 if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash, sig_len,
2682 encoded_expected)) != 0) {
2683 goto cleanup;
2684 }
2685
2686 /*
2687 * Apply RSA primitive to get what should be PKCS1 encoded hash.
2688 */
2689
2690 ret = mbedtls_rsa_public(ctx, sig, encoded);
2691 if (ret != 0) {
2692 goto cleanup;
2693 }
2694
2695 /*
2696 * Compare
2697 */
2698
2699 if ((ret = FTMN_CALLEE_DONE_MEMCMP(mbedtls_ct_memcmp, encoded,
2700 encoded_expected, sig_len )) != 0) {
2701 ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
2702 goto cleanup;
2703 }
2704
2705 cleanup:
2706
2707 if (encoded != NULL) {
2708 mbedtls_zeroize_and_free(encoded, sig_len);
2709 }
2710
2711 if (encoded_expected != NULL) {
2712 mbedtls_zeroize_and_free(encoded_expected, sig_len);
2713 }
2714
2715 return ret;
2716 }
2717 #endif /* MBEDTLS_PKCS1_V15 */
2718
2719 /*
2720 * Do an RSA operation and check the message digest
2721 */
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)2722 int mbedtls_rsa_pkcs1_verify(mbedtls_rsa_context *ctx,
2723 mbedtls_md_type_t md_alg,
2724 unsigned int hashlen,
2725 const unsigned char *hash,
2726 const unsigned char *sig)
2727 {
2728 if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2729 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2730 }
2731
2732 switch (ctx->padding) {
2733 #if defined(MBEDTLS_PKCS1_V15)
2734 case MBEDTLS_RSA_PKCS_V15:
2735 return mbedtls_rsa_rsassa_pkcs1_v15_verify(ctx, md_alg,
2736 hashlen, hash, sig);
2737 #endif
2738
2739 #if defined(MBEDTLS_PKCS1_V21)
2740 case MBEDTLS_RSA_PKCS_V21:
2741 return mbedtls_rsa_rsassa_pss_verify(ctx, md_alg,
2742 hashlen, hash, sig);
2743 #endif
2744
2745 default:
2746 return MBEDTLS_ERR_RSA_INVALID_PADDING;
2747 }
2748 }
2749
2750 /*
2751 * Copy the components of an RSA key
2752 */
mbedtls_rsa_copy(mbedtls_rsa_context * dst,const mbedtls_rsa_context * src)2753 int mbedtls_rsa_copy(mbedtls_rsa_context *dst, const mbedtls_rsa_context *src)
2754 {
2755 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2756
2757 dst->len = src->len;
2758
2759 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->N, &src->N));
2760 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->E, &src->E));
2761
2762 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->D, &src->D));
2763 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->P, &src->P));
2764 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Q, &src->Q));
2765
2766 #if !defined(MBEDTLS_RSA_NO_CRT)
2767 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DP, &src->DP));
2768 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DQ, &src->DQ));
2769 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->QP, &src->QP));
2770 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RP, &src->RP));
2771 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RQ, &src->RQ));
2772 #endif
2773
2774 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RN, &src->RN));
2775
2776 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vi, &src->Vi));
2777 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vf, &src->Vf));
2778
2779 dst->padding = src->padding;
2780 dst->hash_id = src->hash_id;
2781
2782 cleanup:
2783 if (ret != 0) {
2784 mbedtls_rsa_free(dst);
2785 }
2786
2787 return ret;
2788 }
2789
2790 /*
2791 * Free the components of an RSA key
2792 */
mbedtls_rsa_free(mbedtls_rsa_context * ctx)2793 void mbedtls_rsa_free(mbedtls_rsa_context *ctx)
2794 {
2795 if (ctx == NULL) {
2796 return;
2797 }
2798
2799 mbedtls_mpi_free(&ctx->Vi);
2800 mbedtls_mpi_free(&ctx->Vf);
2801 mbedtls_mpi_free(&ctx->RN);
2802 mbedtls_mpi_free(&ctx->D);
2803 mbedtls_mpi_free(&ctx->Q);
2804 mbedtls_mpi_free(&ctx->P);
2805 mbedtls_mpi_free(&ctx->E);
2806 mbedtls_mpi_free(&ctx->N);
2807
2808 #if !defined(MBEDTLS_RSA_NO_CRT)
2809 mbedtls_mpi_free(&ctx->RQ);
2810 mbedtls_mpi_free(&ctx->RP);
2811 mbedtls_mpi_free(&ctx->QP);
2812 mbedtls_mpi_free(&ctx->DQ);
2813 mbedtls_mpi_free(&ctx->DP);
2814 #endif /* MBEDTLS_RSA_NO_CRT */
2815
2816 #if defined(MBEDTLS_THREADING_C)
2817 /* Free the mutex, but only if it hasn't been freed already. */
2818 if (ctx->ver != 0) {
2819 mbedtls_mutex_free(&ctx->mutex);
2820 ctx->ver = 0;
2821 }
2822 #endif
2823 }
2824
2825 #endif /* !MBEDTLS_RSA_ALT */
2826
2827 #if defined(MBEDTLS_SELF_TEST)
2828
2829
2830 /*
2831 * Example RSA-1024 keypair, for test purposes
2832 */
2833 #define KEY_LEN 128
2834
2835 #define RSA_N "9292758453063D803DD603D5E777D788" \
2836 "8ED1D5BF35786190FA2F23EBC0848AEA" \
2837 "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
2838 "7130B9CED7ACDF54CFC7555AC14EEBAB" \
2839 "93A89813FBF3C4F8066D2D800F7C38A8" \
2840 "1AE31942917403FF4946B0A83D3D3E05" \
2841 "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
2842 "5E94BB77B07507233A0BC7BAC8F90F79"
2843
2844 #define RSA_E "10001"
2845
2846 #define RSA_D "24BF6185468786FDD303083D25E64EFC" \
2847 "66CA472BC44D253102F8B4A9D3BFA750" \
2848 "91386C0077937FE33FA3252D28855837" \
2849 "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
2850 "DF79C5CE07EE72C7F123142198164234" \
2851 "CABB724CF78B8173B9F880FC86322407" \
2852 "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
2853 "071513A1E85B5DFA031F21ECAE91A34D"
2854
2855 #define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
2856 "2C01CAD19EA484A87EA4377637E75500" \
2857 "FCB2005C5C7DD6EC4AC023CDA285D796" \
2858 "C3D9E75E1EFC42488BB4F1D13AC30A57"
2859
2860 #define RSA_Q "C000DF51A7C77AE8D7C7370C1FF55B69" \
2861 "E211C2B9E5DB1ED0BF61D0D9899620F4" \
2862 "910E4168387E3C30AA1E00C339A79508" \
2863 "8452DD96A9A5EA5D9DCA68DA636032AF"
2864
2865 #define PT_LEN 24
2866 #define RSA_PT "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
2867 "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
2868
2869 #if defined(MBEDTLS_PKCS1_V15)
myrand(void * rng_state,unsigned char * output,size_t len)2870 static int myrand(void *rng_state, unsigned char *output, size_t len)
2871 {
2872 #if !defined(__OpenBSD__) && !defined(__NetBSD__)
2873 size_t i;
2874
2875 if (rng_state != NULL) {
2876 rng_state = NULL;
2877 }
2878
2879 for (i = 0; i < len; ++i) {
2880 output[i] = rand();
2881 }
2882 #else
2883 if (rng_state != NULL) {
2884 rng_state = NULL;
2885 }
2886
2887 arc4random_buf(output, len);
2888 #endif /* !OpenBSD && !NetBSD */
2889
2890 return 0;
2891 }
2892 #endif /* MBEDTLS_PKCS1_V15 */
2893
2894 /*
2895 * Checkup routine
2896 */
mbedtls_rsa_self_test(int verbose)2897 int mbedtls_rsa_self_test(int verbose)
2898 {
2899 int ret = 0;
2900 #if defined(MBEDTLS_PKCS1_V15)
2901 size_t len;
2902 mbedtls_rsa_context rsa;
2903 unsigned char rsa_plaintext[PT_LEN];
2904 unsigned char rsa_decrypted[PT_LEN];
2905 unsigned char rsa_ciphertext[KEY_LEN];
2906 #if defined(MBEDTLS_MD_CAN_SHA1)
2907 unsigned char sha1sum[20];
2908 #endif
2909
2910 mbedtls_mpi K;
2911
2912 mbedtls_mpi_init(&K);
2913 mbedtls_rsa_init(&rsa);
2914
2915 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_N));
2916 MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, &K, NULL, NULL, NULL, NULL));
2917 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_P));
2918 MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, &K, NULL, NULL, NULL));
2919 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_Q));
2920 MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, &K, NULL, NULL));
2921 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_D));
2922 MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, &K, NULL));
2923 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_E));
2924 MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, NULL, &K));
2925
2926 MBEDTLS_MPI_CHK(mbedtls_rsa_complete(&rsa));
2927
2928 if (verbose != 0) {
2929 mbedtls_printf(" RSA key validation: ");
2930 }
2931
2932 if (mbedtls_rsa_check_pubkey(&rsa) != 0 ||
2933 mbedtls_rsa_check_privkey(&rsa) != 0) {
2934 if (verbose != 0) {
2935 mbedtls_printf("failed\n");
2936 }
2937
2938 ret = 1;
2939 goto cleanup;
2940 }
2941
2942 if (verbose != 0) {
2943 mbedtls_printf("passed\n PKCS#1 encryption : ");
2944 }
2945
2946 memcpy(rsa_plaintext, RSA_PT, PT_LEN);
2947
2948 if (mbedtls_rsa_pkcs1_encrypt(&rsa, myrand, NULL,
2949 PT_LEN, rsa_plaintext,
2950 rsa_ciphertext) != 0) {
2951 if (verbose != 0) {
2952 mbedtls_printf("failed\n");
2953 }
2954
2955 ret = 1;
2956 goto cleanup;
2957 }
2958
2959 if (verbose != 0) {
2960 mbedtls_printf("passed\n PKCS#1 decryption : ");
2961 }
2962
2963 if (mbedtls_rsa_pkcs1_decrypt(&rsa, myrand, NULL,
2964 &len, rsa_ciphertext, rsa_decrypted,
2965 sizeof(rsa_decrypted)) != 0) {
2966 if (verbose != 0) {
2967 mbedtls_printf("failed\n");
2968 }
2969
2970 ret = 1;
2971 goto cleanup;
2972 }
2973
2974 if (memcmp(rsa_decrypted, rsa_plaintext, len) != 0) {
2975 if (verbose != 0) {
2976 mbedtls_printf("failed\n");
2977 }
2978
2979 ret = 1;
2980 goto cleanup;
2981 }
2982
2983 if (verbose != 0) {
2984 mbedtls_printf("passed\n");
2985 }
2986
2987 #if defined(MBEDTLS_MD_CAN_SHA1)
2988 if (verbose != 0) {
2989 mbedtls_printf(" PKCS#1 data sign : ");
2990 }
2991
2992 if (mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1),
2993 rsa_plaintext, PT_LEN, sha1sum) != 0) {
2994 if (verbose != 0) {
2995 mbedtls_printf("failed\n");
2996 }
2997
2998 return 1;
2999 }
3000
3001 if (mbedtls_rsa_pkcs1_sign(&rsa, myrand, NULL,
3002 MBEDTLS_MD_SHA1, 20,
3003 sha1sum, rsa_ciphertext) != 0) {
3004 if (verbose != 0) {
3005 mbedtls_printf("failed\n");
3006 }
3007
3008 ret = 1;
3009 goto cleanup;
3010 }
3011
3012 if (verbose != 0) {
3013 mbedtls_printf("passed\n PKCS#1 sig. verify: ");
3014 }
3015
3016 if (mbedtls_rsa_pkcs1_verify(&rsa, MBEDTLS_MD_SHA1, 20,
3017 sha1sum, rsa_ciphertext) != 0) {
3018 if (verbose != 0) {
3019 mbedtls_printf("failed\n");
3020 }
3021
3022 ret = 1;
3023 goto cleanup;
3024 }
3025
3026 if (verbose != 0) {
3027 mbedtls_printf("passed\n");
3028 }
3029 #endif /* MBEDTLS_MD_CAN_SHA1 */
3030
3031 if (verbose != 0) {
3032 mbedtls_printf("\n");
3033 }
3034
3035 cleanup:
3036 mbedtls_mpi_free(&K);
3037 mbedtls_rsa_free(&rsa);
3038 #else /* MBEDTLS_PKCS1_V15 */
3039 ((void) verbose);
3040 #endif /* MBEDTLS_PKCS1_V15 */
3041 return ret;
3042 }
3043
3044 #endif /* MBEDTLS_SELF_TEST */
3045
3046 #endif /* MBEDTLS_RSA_C */
3047