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