LCOV - code coverage report
Current view: top level - os_stub/mbedtlslib/mbedtls/library - rsa.c (source / functions) Coverage Total Hit
Test: coverage.info Lines: 46.2 % 1047 484
Test Date: 2025-11-23 08:10:21 Functions: 55.8 % 52 29

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

Generated by: LCOV version 2.0-1