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