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