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