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