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