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