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