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