Path: blob/master/thirdparty/mbedtls/library/bignum_core.c
21731 views
/*1* Core bignum functions2*3* Copyright The Mbed TLS Contributors4* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later5*/67#include "common.h"89#if defined(MBEDTLS_BIGNUM_C)1011#include <string.h>1213#include "mbedtls/error.h"14#include "mbedtls/platform_util.h"15#include "constant_time_internal.h"1617#include "mbedtls/platform.h"1819#include "bignum_core.h"20#include "bignum_core_invasive.h"21#include "bn_mul.h"22#include "constant_time_internal.h"2324size_t mbedtls_mpi_core_clz(mbedtls_mpi_uint a)25{26#if defined(__has_builtin)27#if (MBEDTLS_MPI_UINT_MAX == UINT_MAX) && __has_builtin(__builtin_clz)28#define core_clz __builtin_clz29#elif (MBEDTLS_MPI_UINT_MAX == ULONG_MAX) && __has_builtin(__builtin_clzl)30#define core_clz __builtin_clzl31#elif (MBEDTLS_MPI_UINT_MAX == ULLONG_MAX) && __has_builtin(__builtin_clzll)32#define core_clz __builtin_clzll33#endif34#endif35#if defined(core_clz)36return (size_t) core_clz(a);37#else38size_t j;39mbedtls_mpi_uint mask = (mbedtls_mpi_uint) 1 << (biL - 1);4041for (j = 0; j < biL; j++) {42if (a & mask) {43break;44}4546mask >>= 1;47}4849return j;50#endif51}5253size_t mbedtls_mpi_core_bitlen(const mbedtls_mpi_uint *A, size_t A_limbs)54{55int i;56size_t j;5758for (i = ((int) A_limbs) - 1; i >= 0; i--) {59if (A[i] != 0) {60j = biL - mbedtls_mpi_core_clz(A[i]);61return (i * biL) + j;62}63}6465return 0;66}6768static mbedtls_mpi_uint mpi_bigendian_to_host(mbedtls_mpi_uint a)69{70if (MBEDTLS_IS_BIG_ENDIAN) {71/* Nothing to do on bigendian systems. */72return a;73} else {74#if defined(MBEDTLS_HAVE_INT32)75return (mbedtls_mpi_uint) MBEDTLS_BSWAP32(a);76#elif defined(MBEDTLS_HAVE_INT64)77return (mbedtls_mpi_uint) MBEDTLS_BSWAP64(a);78#endif79}80}8182void mbedtls_mpi_core_bigendian_to_host(mbedtls_mpi_uint *A,83size_t A_limbs)84{85mbedtls_mpi_uint *cur_limb_left;86mbedtls_mpi_uint *cur_limb_right;87if (A_limbs == 0) {88return;89}9091/*92* Traverse limbs and93* - adapt byte-order in each limb94* - swap the limbs themselves.95* For that, simultaneously traverse the limbs from left to right96* and from right to left, as long as the left index is not bigger97* than the right index (it's not a problem if limbs is odd and the98* indices coincide in the last iteration).99*/100for (cur_limb_left = A, cur_limb_right = A + (A_limbs - 1);101cur_limb_left <= cur_limb_right;102cur_limb_left++, cur_limb_right--) {103mbedtls_mpi_uint tmp;104/* Note that if cur_limb_left == cur_limb_right,105* this code effectively swaps the bytes only once. */106tmp = mpi_bigendian_to_host(*cur_limb_left);107*cur_limb_left = mpi_bigendian_to_host(*cur_limb_right);108*cur_limb_right = tmp;109}110}111112/* Whether min <= A, in constant time.113* A_limbs must be at least 1. */114mbedtls_ct_condition_t mbedtls_mpi_core_uint_le_mpi(mbedtls_mpi_uint min,115const mbedtls_mpi_uint *A,116size_t A_limbs)117{118/* min <= least significant limb? */119mbedtls_ct_condition_t min_le_lsl = mbedtls_ct_uint_ge(A[0], min);120121/* limbs other than the least significant one are all zero? */122mbedtls_ct_condition_t msll_mask = MBEDTLS_CT_FALSE;123for (size_t i = 1; i < A_limbs; i++) {124msll_mask = mbedtls_ct_bool_or(msll_mask, mbedtls_ct_bool(A[i]));125}126127/* min <= A iff the lowest limb of A is >= min or the other limbs128* are not all zero. */129return mbedtls_ct_bool_or(msll_mask, min_le_lsl);130}131132mbedtls_ct_condition_t mbedtls_mpi_core_lt_ct(const mbedtls_mpi_uint *A,133const mbedtls_mpi_uint *B,134size_t limbs)135{136mbedtls_ct_condition_t ret = MBEDTLS_CT_FALSE, cond = MBEDTLS_CT_FALSE, done = MBEDTLS_CT_FALSE;137138for (size_t i = limbs; i > 0; i--) {139/*140* If B[i - 1] < A[i - 1] then A < B is false and the result must141* remain 0.142*143* Again even if we can make a decision, we just mark the result and144* the fact that we are done and continue looping.145*/146cond = mbedtls_ct_uint_lt(B[i - 1], A[i - 1]);147done = mbedtls_ct_bool_or(done, cond);148149/*150* If A[i - 1] < B[i - 1] then A < B is true.151*152* Again even if we can make a decision, we just mark the result and153* the fact that we are done and continue looping.154*/155cond = mbedtls_ct_uint_lt(A[i - 1], B[i - 1]);156ret = mbedtls_ct_bool_or(ret, mbedtls_ct_bool_and(cond, mbedtls_ct_bool_not(done)));157done = mbedtls_ct_bool_or(done, cond);158}159160/*161* If all the limbs were equal, then the numbers are equal, A < B is false162* and leaving the result 0 is correct.163*/164165return ret;166}167168void mbedtls_mpi_core_cond_assign(mbedtls_mpi_uint *X,169const mbedtls_mpi_uint *A,170size_t limbs,171mbedtls_ct_condition_t assign)172{173if (X == A) {174return;175}176177/* This function is very performance-sensitive for RSA. For this reason178* we have the loop below, instead of calling mbedtls_ct_memcpy_if179* (this is more optimal since here we don't have to handle the case where180* we copy awkwardly sized data).181*/182for (size_t i = 0; i < limbs; i++) {183X[i] = mbedtls_ct_mpi_uint_if(assign, A[i], X[i]);184}185}186187void mbedtls_mpi_core_cond_swap(mbedtls_mpi_uint *X,188mbedtls_mpi_uint *Y,189size_t limbs,190mbedtls_ct_condition_t swap)191{192if (X == Y) {193return;194}195196for (size_t i = 0; i < limbs; i++) {197mbedtls_mpi_uint tmp = X[i];198X[i] = mbedtls_ct_mpi_uint_if(swap, Y[i], X[i]);199Y[i] = mbedtls_ct_mpi_uint_if(swap, tmp, Y[i]);200}201}202203int mbedtls_mpi_core_read_le(mbedtls_mpi_uint *X,204size_t X_limbs,205const unsigned char *input,206size_t input_length)207{208const size_t limbs = CHARS_TO_LIMBS(input_length);209210if (X_limbs < limbs) {211return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;212}213214if (X != NULL) {215memset(X, 0, X_limbs * ciL);216217for (size_t i = 0; i < input_length; i++) {218size_t offset = ((i % ciL) << 3);219X[i / ciL] |= ((mbedtls_mpi_uint) input[i]) << offset;220}221}222223return 0;224}225226int mbedtls_mpi_core_read_be(mbedtls_mpi_uint *X,227size_t X_limbs,228const unsigned char *input,229size_t input_length)230{231const size_t limbs = CHARS_TO_LIMBS(input_length);232233if (X_limbs < limbs) {234return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;235}236237/* If X_limbs is 0, input_length must also be 0 (from previous test).238* Nothing to do. */239if (X_limbs == 0) {240return 0;241}242243memset(X, 0, X_limbs * ciL);244245/* memcpy() with (NULL, 0) is undefined behaviour */246if (input_length != 0) {247size_t overhead = (X_limbs * ciL) - input_length;248unsigned char *Xp = (unsigned char *) X;249memcpy(Xp + overhead, input, input_length);250}251252mbedtls_mpi_core_bigendian_to_host(X, X_limbs);253254return 0;255}256257int mbedtls_mpi_core_write_le(const mbedtls_mpi_uint *A,258size_t A_limbs,259unsigned char *output,260size_t output_length)261{262size_t stored_bytes = A_limbs * ciL;263size_t bytes_to_copy;264265if (stored_bytes < output_length) {266bytes_to_copy = stored_bytes;267} else {268bytes_to_copy = output_length;269270/* The output buffer is smaller than the allocated size of A.271* However A may fit if its leading bytes are zero. */272for (size_t i = bytes_to_copy; i < stored_bytes; i++) {273if (GET_BYTE(A, i) != 0) {274return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;275}276}277}278279for (size_t i = 0; i < bytes_to_copy; i++) {280output[i] = GET_BYTE(A, i);281}282283if (stored_bytes < output_length) {284/* Write trailing 0 bytes */285memset(output + stored_bytes, 0, output_length - stored_bytes);286}287288return 0;289}290291int mbedtls_mpi_core_write_be(const mbedtls_mpi_uint *X,292size_t X_limbs,293unsigned char *output,294size_t output_length)295{296size_t stored_bytes;297size_t bytes_to_copy;298unsigned char *p;299300stored_bytes = X_limbs * ciL;301302if (stored_bytes < output_length) {303/* There is enough space in the output buffer. Write initial304* null bytes and record the position at which to start305* writing the significant bytes. In this case, the execution306* trace of this function does not depend on the value of the307* number. */308bytes_to_copy = stored_bytes;309p = output + output_length - stored_bytes;310memset(output, 0, output_length - stored_bytes);311} else {312/* The output buffer is smaller than the allocated size of X.313* However X may fit if its leading bytes are zero. */314bytes_to_copy = output_length;315p = output;316for (size_t i = bytes_to_copy; i < stored_bytes; i++) {317if (GET_BYTE(X, i) != 0) {318return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;319}320}321}322323for (size_t i = 0; i < bytes_to_copy; i++) {324p[bytes_to_copy - i - 1] = GET_BYTE(X, i);325}326327return 0;328}329330void mbedtls_mpi_core_shift_r(mbedtls_mpi_uint *X, size_t limbs,331size_t count)332{333size_t i, v0, v1;334mbedtls_mpi_uint r0 = 0, r1;335336v0 = count / biL;337v1 = count & (biL - 1);338339if (v0 > limbs || (v0 == limbs && v1 > 0)) {340memset(X, 0, limbs * ciL);341return;342}343344/*345* shift by count / limb_size346*/347if (v0 > 0) {348for (i = 0; i < limbs - v0; i++) {349X[i] = X[i + v0];350}351352for (; i < limbs; i++) {353X[i] = 0;354}355}356357/*358* shift by count % limb_size359*/360if (v1 > 0) {361for (i = limbs; i > 0; i--) {362r1 = X[i - 1] << (biL - v1);363X[i - 1] >>= v1;364X[i - 1] |= r0;365r0 = r1;366}367}368}369370void mbedtls_mpi_core_shift_l(mbedtls_mpi_uint *X, size_t limbs,371size_t count)372{373size_t i, v0, v1;374mbedtls_mpi_uint r0 = 0, r1;375376v0 = count / (biL);377v1 = count & (biL - 1);378379/*380* shift by count / limb_size381*/382if (v0 > 0) {383for (i = limbs; i > v0; i--) {384X[i - 1] = X[i - v0 - 1];385}386387for (; i > 0; i--) {388X[i - 1] = 0;389}390}391392/*393* shift by count % limb_size394*/395if (v1 > 0) {396for (i = v0; i < limbs; i++) {397r1 = X[i] >> (biL - v1);398X[i] <<= v1;399X[i] |= r0;400r0 = r1;401}402}403}404405mbedtls_mpi_uint mbedtls_mpi_core_add(mbedtls_mpi_uint *X,406const mbedtls_mpi_uint *A,407const mbedtls_mpi_uint *B,408size_t limbs)409{410mbedtls_mpi_uint c = 0;411412for (size_t i = 0; i < limbs; i++) {413mbedtls_mpi_uint t = c + A[i];414c = (t < A[i]);415t += B[i];416c += (t < B[i]);417X[i] = t;418}419420return c;421}422423mbedtls_mpi_uint mbedtls_mpi_core_add_if(mbedtls_mpi_uint *X,424const mbedtls_mpi_uint *A,425size_t limbs,426unsigned cond)427{428mbedtls_mpi_uint c = 0;429430mbedtls_ct_condition_t do_add = mbedtls_ct_bool(cond);431432for (size_t i = 0; i < limbs; i++) {433mbedtls_mpi_uint add = mbedtls_ct_mpi_uint_if_else_0(do_add, A[i]);434mbedtls_mpi_uint t = c + X[i];435c = (t < X[i]);436t += add;437c += (t < add);438X[i] = t;439}440441return c;442}443444mbedtls_mpi_uint mbedtls_mpi_core_sub(mbedtls_mpi_uint *X,445const mbedtls_mpi_uint *A,446const mbedtls_mpi_uint *B,447size_t limbs)448{449mbedtls_mpi_uint c = 0;450451for (size_t i = 0; i < limbs; i++) {452mbedtls_mpi_uint z = (A[i] < c);453mbedtls_mpi_uint t = A[i] - c;454c = (t < B[i]) + z;455X[i] = t - B[i];456}457458return c;459}460461mbedtls_mpi_uint mbedtls_mpi_core_mla(mbedtls_mpi_uint *d, size_t d_len,462const mbedtls_mpi_uint *s, size_t s_len,463mbedtls_mpi_uint b)464{465mbedtls_mpi_uint c = 0; /* carry */466/*467* It is a documented precondition of this function that d_len >= s_len.468* If that's not the case, we swap these round: this turns what would be469* a buffer overflow into an incorrect result.470*/471if (d_len < s_len) {472s_len = d_len;473}474size_t excess_len = d_len - s_len;475size_t steps_x8 = s_len / 8;476size_t steps_x1 = s_len & 7;477478while (steps_x8--) {479MULADDC_X8_INIT480MULADDC_X8_CORE481MULADDC_X8_STOP482}483484while (steps_x1--) {485MULADDC_X1_INIT486MULADDC_X1_CORE487MULADDC_X1_STOP488}489490while (excess_len--) {491*d += c;492c = (*d < c);493d++;494}495496return c;497}498499void mbedtls_mpi_core_mul(mbedtls_mpi_uint *X,500const mbedtls_mpi_uint *A, size_t A_limbs,501const mbedtls_mpi_uint *B, size_t B_limbs)502{503memset(X, 0, (A_limbs + B_limbs) * ciL);504505for (size_t i = 0; i < B_limbs; i++) {506(void) mbedtls_mpi_core_mla(X + i, A_limbs + 1, A, A_limbs, B[i]);507}508}509510/*511* Fast Montgomery initialization (thanks to Tom St Denis).512*/513mbedtls_mpi_uint mbedtls_mpi_core_montmul_init(const mbedtls_mpi_uint *N)514{515mbedtls_mpi_uint x = N[0];516517x += ((N[0] + 2) & 4) << 1;518519for (unsigned int i = biL; i >= 8; i /= 2) {520x *= (2 - (N[0] * x));521}522523return ~x + 1;524}525526void mbedtls_mpi_core_montmul(mbedtls_mpi_uint *X,527const mbedtls_mpi_uint *A,528const mbedtls_mpi_uint *B,529size_t B_limbs,530const mbedtls_mpi_uint *N,531size_t AN_limbs,532mbedtls_mpi_uint mm,533mbedtls_mpi_uint *T)534{535memset(T, 0, (2 * AN_limbs + 1) * ciL);536537for (size_t i = 0; i < AN_limbs; i++) {538/* T = (T + u0*B + u1*N) / 2^biL */539mbedtls_mpi_uint u0 = A[i];540mbedtls_mpi_uint u1 = (T[0] + u0 * B[0]) * mm;541542(void) mbedtls_mpi_core_mla(T, AN_limbs + 2, B, B_limbs, u0);543(void) mbedtls_mpi_core_mla(T, AN_limbs + 2, N, AN_limbs, u1);544545T++;546}547548/*549* The result we want is (T >= N) ? T - N : T.550*551* For better constant-time properties in this function, we always do the552* subtraction, with the result in X.553*554* We also look to see if there was any carry in the final additions in the555* loop above.556*/557558mbedtls_mpi_uint carry = T[AN_limbs];559mbedtls_mpi_uint borrow = mbedtls_mpi_core_sub(X, T, N, AN_limbs);560561/*562* Using R as the Montgomery radix (auxiliary modulus) i.e. 2^(biL*AN_limbs):563*564* T can be in one of 3 ranges:565*566* 1) T < N : (carry, borrow) = (0, 1): we want T567* 2) N <= T < R : (carry, borrow) = (0, 0): we want X568* 3) T >= R : (carry, borrow) = (1, 1): we want X569*570* and (carry, borrow) = (1, 0) can't happen.571*572* So the correct return value is already in X if (carry ^ borrow) = 0,573* but is in (the lower AN_limbs limbs of) T if (carry ^ borrow) = 1.574*/575mbedtls_ct_memcpy_if(mbedtls_ct_bool(carry ^ borrow),576(unsigned char *) X,577(unsigned char *) T,578NULL,579AN_limbs * sizeof(mbedtls_mpi_uint));580}581582int mbedtls_mpi_core_get_mont_r2_unsafe(mbedtls_mpi *X,583const mbedtls_mpi *N)584{585int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;586587MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, 1));588MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(X, N->n * 2 * biL));589MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(X, X, N));590MBEDTLS_MPI_CHK(mbedtls_mpi_shrink(X, N->n));591592cleanup:593return ret;594}595596MBEDTLS_STATIC_TESTABLE597void mbedtls_mpi_core_ct_uint_table_lookup(mbedtls_mpi_uint *dest,598const mbedtls_mpi_uint *table,599size_t limbs,600size_t count,601size_t index)602{603for (size_t i = 0; i < count; i++, table += limbs) {604mbedtls_ct_condition_t assign = mbedtls_ct_uint_eq(i, index);605mbedtls_mpi_core_cond_assign(dest, table, limbs, assign);606}607}608609/* Fill X with n_bytes random bytes.610* X must already have room for those bytes.611* The ordering of the bytes returned from the RNG is suitable for612* deterministic ECDSA (see RFC 6979 §3.3 and the specification of613* mbedtls_mpi_core_random()).614*/615int mbedtls_mpi_core_fill_random(616mbedtls_mpi_uint *X, size_t X_limbs,617size_t n_bytes,618int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)619{620int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;621const size_t limbs = CHARS_TO_LIMBS(n_bytes);622const size_t overhead = (limbs * ciL) - n_bytes;623624if (X_limbs < limbs) {625return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;626}627628memset(X, 0, overhead);629memset((unsigned char *) X + limbs * ciL, 0, (X_limbs - limbs) * ciL);630MBEDTLS_MPI_CHK(f_rng(p_rng, (unsigned char *) X + overhead, n_bytes));631mbedtls_mpi_core_bigendian_to_host(X, limbs);632633cleanup:634return ret;635}636637int mbedtls_mpi_core_random(mbedtls_mpi_uint *X,638mbedtls_mpi_uint min,639const mbedtls_mpi_uint *N,640size_t limbs,641int (*f_rng)(void *, unsigned char *, size_t),642void *p_rng)643{644mbedtls_ct_condition_t ge_lower = MBEDTLS_CT_TRUE, lt_upper = MBEDTLS_CT_FALSE;645size_t n_bits = mbedtls_mpi_core_bitlen(N, limbs);646size_t n_bytes = (n_bits + 7) / 8;647int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;648649/*650* When min == 0, each try has at worst a probability 1/2 of failing651* (the msb has a probability 1/2 of being 0, and then the result will652* be < N), so after 30 tries failure probability is a most 2**(-30).653*654* When N is just below a power of 2, as is the case when generating655* a random scalar on most elliptic curves, 1 try is enough with656* overwhelming probability. When N is just above a power of 2,657* as when generating a random scalar on secp224k1, each try has658* a probability of failing that is almost 1/2.659*660* The probabilities are almost the same if min is nonzero but negligible661* compared to N. This is always the case when N is crypto-sized, but662* it's convenient to support small N for testing purposes. When N663* is small, use a higher repeat count, otherwise the probability of664* failure is macroscopic.665*/666int count = (n_bytes > 4 ? 30 : 250);667668/*669* Match the procedure given in RFC 6979 §3.3 (deterministic ECDSA)670* when f_rng is a suitably parametrized instance of HMAC_DRBG:671* - use the same byte ordering;672* - keep the leftmost n_bits bits of the generated octet string;673* - try until result is in the desired range.674* This also avoids any bias, which is especially important for ECDSA.675*/676do {677MBEDTLS_MPI_CHK(mbedtls_mpi_core_fill_random(X, limbs,678n_bytes,679f_rng, p_rng));680mbedtls_mpi_core_shift_r(X, limbs, 8 * n_bytes - n_bits);681682if (--count == 0) {683ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;684goto cleanup;685}686687ge_lower = mbedtls_mpi_core_uint_le_mpi(min, X, limbs);688lt_upper = mbedtls_mpi_core_lt_ct(X, N, limbs);689} while (mbedtls_ct_bool_and(ge_lower, lt_upper) == MBEDTLS_CT_FALSE);690691cleanup:692return ret;693}694695static size_t exp_mod_get_window_size(size_t Ebits)696{697#if MBEDTLS_MPI_WINDOW_SIZE >= 6698return (Ebits > 671) ? 6 : (Ebits > 239) ? 5 : (Ebits > 79) ? 4 : 1;699#elif MBEDTLS_MPI_WINDOW_SIZE == 5700return (Ebits > 239) ? 5 : (Ebits > 79) ? 4 : 1;701#elif MBEDTLS_MPI_WINDOW_SIZE > 1702return (Ebits > 79) ? MBEDTLS_MPI_WINDOW_SIZE : 1;703#else704(void) Ebits;705return 1;706#endif707}708709size_t mbedtls_mpi_core_exp_mod_working_limbs(size_t AN_limbs, size_t E_limbs)710{711const size_t wsize = exp_mod_get_window_size(E_limbs * biL);712const size_t welem = ((size_t) 1) << wsize;713714/* How big does each part of the working memory pool need to be? */715const size_t table_limbs = welem * AN_limbs;716const size_t select_limbs = AN_limbs;717const size_t temp_limbs = 2 * AN_limbs + 1;718719return table_limbs + select_limbs + temp_limbs;720}721722static void exp_mod_precompute_window(const mbedtls_mpi_uint *A,723const mbedtls_mpi_uint *N,724size_t AN_limbs,725mbedtls_mpi_uint mm,726const mbedtls_mpi_uint *RR,727size_t welem,728mbedtls_mpi_uint *Wtable,729mbedtls_mpi_uint *temp)730{731/* W[0] = 1 (in Montgomery presentation) */732memset(Wtable, 0, AN_limbs * ciL);733Wtable[0] = 1;734mbedtls_mpi_core_montmul(Wtable, Wtable, RR, AN_limbs, N, AN_limbs, mm, temp);735736/* W[1] = A (already in Montgomery presentation) */737mbedtls_mpi_uint *W1 = Wtable + AN_limbs;738memcpy(W1, A, AN_limbs * ciL);739740/* W[i+1] = W[i] * W[1], i >= 2 */741mbedtls_mpi_uint *Wprev = W1;742for (size_t i = 2; i < welem; i++) {743mbedtls_mpi_uint *Wcur = Wprev + AN_limbs;744mbedtls_mpi_core_montmul(Wcur, Wprev, W1, AN_limbs, N, AN_limbs, mm, temp);745Wprev = Wcur;746}747}748749#if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)750void (*mbedtls_safe_codepath_hook)(void) = NULL;751void (*mbedtls_unsafe_codepath_hook)(void) = NULL;752#endif753754/*755* This function calculates the indices of the exponent where the exponentiation algorithm should756* start processing.757*758* Warning! If the parameter E_public has MBEDTLS_MPI_IS_PUBLIC as its value,759* this function is not constant time with respect to the exponent (parameter E).760*/761static inline void exp_mod_calc_first_bit_optionally_safe(const mbedtls_mpi_uint *E,762size_t E_limbs,763int E_public,764size_t *E_limb_index,765size_t *E_bit_index)766{767if (E_public == MBEDTLS_MPI_IS_PUBLIC) {768/*769* Skip leading zero bits.770*/771size_t E_bits = mbedtls_mpi_core_bitlen(E, E_limbs);772if (E_bits == 0) {773/*774* If E is 0 mbedtls_mpi_core_bitlen() returns 0. Even if that is the case, we will want775* to represent it as a single 0 bit and as such the bitlength will be 1.776*/777E_bits = 1;778}779780*E_limb_index = E_bits / biL;781*E_bit_index = E_bits % biL;782783#if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)784if (mbedtls_unsafe_codepath_hook != NULL) {785mbedtls_unsafe_codepath_hook();786}787#endif788} else {789/*790* Here we need to be constant time with respect to E and can't do anything better than791* start at the first allocated bit.792*/793*E_limb_index = E_limbs;794*E_bit_index = 0;795#if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)796if (mbedtls_safe_codepath_hook != NULL) {797mbedtls_safe_codepath_hook();798}799#endif800}801}802803/*804* Warning! If the parameter window_public has MBEDTLS_MPI_IS_PUBLIC as its value, this function is805* not constant time with respect to the window parameter and consequently the exponent of the806* exponentiation (parameter E of mbedtls_mpi_core_exp_mod_optionally_safe).807*/808static inline void exp_mod_table_lookup_optionally_safe(mbedtls_mpi_uint *Wselect,809mbedtls_mpi_uint *Wtable,810size_t AN_limbs, size_t welem,811mbedtls_mpi_uint window,812int window_public)813{814if (window_public == MBEDTLS_MPI_IS_PUBLIC) {815memcpy(Wselect, Wtable + window * AN_limbs, AN_limbs * ciL);816#if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)817if (mbedtls_unsafe_codepath_hook != NULL) {818mbedtls_unsafe_codepath_hook();819}820#endif821} else {822/* Select Wtable[window] without leaking window through823* memory access patterns. */824mbedtls_mpi_core_ct_uint_table_lookup(Wselect, Wtable,825AN_limbs, welem, window);826#if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)827if (mbedtls_safe_codepath_hook != NULL) {828mbedtls_safe_codepath_hook();829}830#endif831}832}833834/* Exponentiation: X := A^E mod N.835*836* Warning! If the parameter E_public has MBEDTLS_MPI_IS_PUBLIC as its value,837* this function is not constant time with respect to the exponent (parameter E).838*839* A must already be in Montgomery form.840*841* As in other bignum functions, assume that AN_limbs and E_limbs are nonzero.842*843* RR must contain 2^{2*biL} mod N.844*845* The algorithm is a variant of Left-to-right k-ary exponentiation: HAC 14.82846* (The difference is that the body in our loop processes a single bit instead847* of a full window.)848*/849static void mbedtls_mpi_core_exp_mod_optionally_safe(mbedtls_mpi_uint *X,850const mbedtls_mpi_uint *A,851const mbedtls_mpi_uint *N,852size_t AN_limbs,853const mbedtls_mpi_uint *E,854size_t E_limbs,855int E_public,856const mbedtls_mpi_uint *RR,857mbedtls_mpi_uint *T)858{859/* We'll process the bits of E from most significant860* (limb_index=E_limbs-1, E_bit_index=biL-1) to least significant861* (limb_index=0, E_bit_index=0). */862size_t E_limb_index = E_limbs;863size_t E_bit_index = 0;864exp_mod_calc_first_bit_optionally_safe(E, E_limbs, E_public,865&E_limb_index, &E_bit_index);866867const size_t wsize = exp_mod_get_window_size(E_limb_index * biL);868const size_t welem = ((size_t) 1) << wsize;869870/* This is how we will use the temporary storage T, which must have space871* for table_limbs, select_limbs and (2 * AN_limbs + 1) for montmul. */872const size_t table_limbs = welem * AN_limbs;873const size_t select_limbs = AN_limbs;874875/* Pointers to specific parts of the temporary working memory pool */876mbedtls_mpi_uint *const Wtable = T;877mbedtls_mpi_uint *const Wselect = Wtable + table_limbs;878mbedtls_mpi_uint *const temp = Wselect + select_limbs;879880/*881* Window precomputation882*/883884const mbedtls_mpi_uint mm = mbedtls_mpi_core_montmul_init(N);885886/* Set Wtable[i] = A^i (in Montgomery representation) */887exp_mod_precompute_window(A, N, AN_limbs,888mm, RR,889welem, Wtable, temp);890891/*892* Fixed window exponentiation893*/894895/* X = 1 (in Montgomery presentation) initially */896memcpy(X, Wtable, AN_limbs * ciL);897898/* At any given time, window contains window_bits bits from E.899* window_bits can go up to wsize. */900size_t window_bits = 0;901mbedtls_mpi_uint window = 0;902903do {904/* Square */905mbedtls_mpi_core_montmul(X, X, X, AN_limbs, N, AN_limbs, mm, temp);906907/* Move to the next bit of the exponent */908if (E_bit_index == 0) {909--E_limb_index;910E_bit_index = biL - 1;911} else {912--E_bit_index;913}914/* Insert next exponent bit into window */915++window_bits;916window <<= 1;917window |= (E[E_limb_index] >> E_bit_index) & 1;918919/* Clear window if it's full. Also clear the window at the end,920* when we've finished processing the exponent. */921if (window_bits == wsize ||922(E_bit_index == 0 && E_limb_index == 0)) {923924exp_mod_table_lookup_optionally_safe(Wselect, Wtable, AN_limbs, welem,925window, E_public);926/* Multiply X by the selected element. */927mbedtls_mpi_core_montmul(X, X, Wselect, AN_limbs, N, AN_limbs, mm,928temp);929window = 0;930window_bits = 0;931}932} while (!(E_bit_index == 0 && E_limb_index == 0));933}934935void mbedtls_mpi_core_exp_mod(mbedtls_mpi_uint *X,936const mbedtls_mpi_uint *A,937const mbedtls_mpi_uint *N, size_t AN_limbs,938const mbedtls_mpi_uint *E, size_t E_limbs,939const mbedtls_mpi_uint *RR,940mbedtls_mpi_uint *T)941{942mbedtls_mpi_core_exp_mod_optionally_safe(X,943A,944N,945AN_limbs,946E,947E_limbs,948MBEDTLS_MPI_IS_SECRET,949RR,950T);951}952953void mbedtls_mpi_core_exp_mod_unsafe(mbedtls_mpi_uint *X,954const mbedtls_mpi_uint *A,955const mbedtls_mpi_uint *N, size_t AN_limbs,956const mbedtls_mpi_uint *E, size_t E_limbs,957const mbedtls_mpi_uint *RR,958mbedtls_mpi_uint *T)959{960mbedtls_mpi_core_exp_mod_optionally_safe(X,961A,962N,963AN_limbs,964E,965E_limbs,966MBEDTLS_MPI_IS_PUBLIC,967RR,968T);969}970971mbedtls_mpi_uint mbedtls_mpi_core_sub_int(mbedtls_mpi_uint *X,972const mbedtls_mpi_uint *A,973mbedtls_mpi_uint c, /* doubles as carry */974size_t limbs)975{976for (size_t i = 0; i < limbs; i++) {977mbedtls_mpi_uint s = A[i];978mbedtls_mpi_uint t = s - c;979c = (t > s);980X[i] = t;981}982983return c;984}985986mbedtls_ct_condition_t mbedtls_mpi_core_check_zero_ct(const mbedtls_mpi_uint *A,987size_t limbs)988{989volatile const mbedtls_mpi_uint *force_read_A = A;990mbedtls_mpi_uint bits = 0;991992for (size_t i = 0; i < limbs; i++) {993bits |= force_read_A[i];994}995996return mbedtls_ct_bool(bits);997}998999void mbedtls_mpi_core_to_mont_rep(mbedtls_mpi_uint *X,1000const mbedtls_mpi_uint *A,1001const mbedtls_mpi_uint *N,1002size_t AN_limbs,1003mbedtls_mpi_uint mm,1004const mbedtls_mpi_uint *rr,1005mbedtls_mpi_uint *T)1006{1007mbedtls_mpi_core_montmul(X, A, rr, AN_limbs, N, AN_limbs, mm, T);1008}10091010void mbedtls_mpi_core_from_mont_rep(mbedtls_mpi_uint *X,1011const mbedtls_mpi_uint *A,1012const mbedtls_mpi_uint *N,1013size_t AN_limbs,1014mbedtls_mpi_uint mm,1015mbedtls_mpi_uint *T)1016{1017const mbedtls_mpi_uint Rinv = 1; /* 1/R in Mont. rep => 1 */10181019mbedtls_mpi_core_montmul(X, A, &Rinv, 1, N, AN_limbs, mm, T);1020}10211022/*1023* Compute X = A - B mod N.1024* Both A and B must be in [0, N) and so will the output.1025*/1026static void mpi_core_sub_mod(mbedtls_mpi_uint *X,1027const mbedtls_mpi_uint *A,1028const mbedtls_mpi_uint *B,1029const mbedtls_mpi_uint *N,1030size_t limbs)1031{1032mbedtls_mpi_uint c = mbedtls_mpi_core_sub(X, A, B, limbs);1033(void) mbedtls_mpi_core_add_if(X, N, limbs, (unsigned) c);1034}10351036/*1037* Divide X by 2 mod N in place, assuming N is odd.1038* The input must be in [0, N) and so will the output.1039*/1040MBEDTLS_STATIC_TESTABLE1041void mbedtls_mpi_core_div2_mod_odd(mbedtls_mpi_uint *X,1042const mbedtls_mpi_uint *N,1043size_t limbs)1044{1045/* If X is odd, add N to make it even before shifting. */1046unsigned odd = (unsigned) X[0] & 1;1047mbedtls_mpi_uint c = mbedtls_mpi_core_add_if(X, N, limbs, odd);1048mbedtls_mpi_core_shift_r(X, limbs, 1);1049X[limbs - 1] |= c << (biL - 1);1050}10511052/*1053* Constant-time GCD and modular inversion - odd modulus.1054*1055* Pre-conditions: see public documentation.1056*1057* See https://www.jstage.jst.go.jp/article/transinf/E106.D/9/E106.D_2022ICP0009/_pdf1058*1059* The paper gives two computationally equivalent algorithms: Alg 7 (readable)1060* and Alg 8 (constant-time). We use a third version that's hopefully both:1061*1062* u, v = A, N # N is called p in the paper but doesn't have to be prime1063* q, r = 0, 11064* repeat bits(A_limbs + N_limbs) times:1065* d = v - u # t1 in Alg 71066* t1 = (u and v both odd) ? u : d # t1 in Alg 81067* t2 = (u and v both odd) ? d : (u odd) ? v : u # t2 in Alg 81068* t2 >>= 11069* swap = t1 > t2 # similar to s, z in Alg 81070* u, v = (swap) ? t2, t1 : t1, t21071*1072* d = r - q mod N # t2 in Alg 71073* t1 = (u and v both odd) ? q : d # t3 in Alg 81074* t2 = (u and v both odd) ? d : (u odd) ? r : q # t4 Alg 81075* t2 /= 2 mod N # see below (pre_com)1076* q, r = (swap) ? t2, t1 : t1, t21077* return v, q # v: GCD, see Alg 6; q: no mult by pre_com, see below1078*1079* The ternary operators in the above pseudo-code need to be realised in a1080* constant-time fashion. We use conditional assign for t1, t2 and conditional1081* swap for the final update. (Note: the similarity between branches of Alg 71082* are highlighted in tables 2 and 3 and the surrounding text.)1083*1084* Also, we re-order operations, grouping things related to the inverse, which1085* facilitates making its computation optional, and requires fewer temporaries.1086*1087* The only actual change from the paper is dropping the trick with pre_com,1088* which I think complicates things for no benefit.1089* See the comment on the big I != NULL block below for details.1090*/1091void mbedtls_mpi_core_gcd_modinv_odd(mbedtls_mpi_uint *G,1092mbedtls_mpi_uint *I,1093const mbedtls_mpi_uint *A,1094size_t A_limbs,1095const mbedtls_mpi_uint *N,1096size_t N_limbs,1097mbedtls_mpi_uint *T)1098{1099/* GCD and modinv, names common to Alg 7 and Alg 8 */1100mbedtls_mpi_uint *u = T + 0 * N_limbs;1101mbedtls_mpi_uint *v = G;11021103/* GCD and modinv, my name (t1, t2 from Alg 7) */1104mbedtls_mpi_uint *d = T + 1 * N_limbs;11051106/* GCD and modinv, names from Alg 8 (note: t1, t2 from Alg 7 are d above) */1107mbedtls_mpi_uint *t1 = T + 2 * N_limbs;1108mbedtls_mpi_uint *t2 = T + 3 * N_limbs;11091110/* modinv only, names common to Alg 7 and Alg 8 */1111mbedtls_mpi_uint *q = I;1112mbedtls_mpi_uint *r = I != NULL ? T + 4 * N_limbs : NULL;11131114/*1115* Initial values:1116* u, v = A, N1117* q, r = 0, 11118*1119* We only write to G (aka v) after reading from inputs (A and N), which1120* allows aliasing, except with N when I != NULL, as then we'll be operating1121* mod N on q and r later - see the public documentation.1122*/1123if (A_limbs > N_limbs) {1124/* Violating this precondition should not result in memory errors. */1125A_limbs = N_limbs;1126}1127memcpy(u, A, A_limbs * ciL);1128memset((char *) u + A_limbs * ciL, 0, (N_limbs - A_limbs) * ciL);11291130/* Avoid possible UB with memcpy when src == dst. */1131if (v != N) {1132memcpy(v, N, N_limbs * ciL);1133}11341135if (I != NULL) {1136memset(q, 0, N_limbs * ciL);11371138memset(r, 0, N_limbs * ciL);1139r[0] = 1;1140}11411142/*1143* At each step, out of u, v, v - u we keep one, shift another, and discard1144* the third, then update (u, v) with the ordered result.1145* Then we mirror those actions with q, r, r - q mod N.1146*1147* Loop invariants:1148* u <= v (on entry: A <= N)1149* GCD(u, v) == GCD(A, N) (on entry: trivial)1150* v = A * q mod N (on entry: N = A * 0 mod N)1151* u = A * r mod N (on entry: A = A * 1 mod N)1152* q, r in [0, N) (on entry: 0, 1)1153*1154* On exit:1155* u = 01156* v = GCD(A, N) = A * q mod N1157* if v == 1 then 1 = A * q mod N ie q is A's inverse mod N1158* r = 01159*1160* The exit state is a fixed point of the loop's body.1161* Alg 7 and Alg 8 use 2 * bitlen(N) iterations but Theorem 2 (above in the1162* paper) says bitlen(A) + bitlen(N) is actually enough.1163*/1164for (size_t i = 0; i < (A_limbs + N_limbs) * biL; i++) {1165/* s, z in Alg 8 - use meaningful names instead */1166mbedtls_ct_condition_t u_odd = mbedtls_ct_bool(u[0] & 1);1167mbedtls_ct_condition_t v_odd = mbedtls_ct_bool(v[0] & 1);11681169/* Other conditions that will be useful below */1170mbedtls_ct_condition_t u_odd_v_odd = mbedtls_ct_bool_and(u_odd, v_odd);1171mbedtls_ct_condition_t v_even = mbedtls_ct_bool_not(v_odd);1172mbedtls_ct_condition_t u_odd_v_even = mbedtls_ct_bool_and(u_odd, v_even);11731174/* This is called t1 in Alg 7 (no name in Alg 8).1175* We know that u <= v so there is no carry */1176(void) mbedtls_mpi_core_sub(d, v, u, N_limbs);11771178/* t1 (the thing that's kept) can be d (default) or u (if t2 is d) */1179memcpy(t1, d, N_limbs * ciL);1180mbedtls_mpi_core_cond_assign(t1, u, N_limbs, u_odd_v_odd);11811182/* t2 (the thing that's shifted) can be u (if even), or v (if even),1183* or d (which is even if both u and v were odd) */1184memcpy(t2, u, N_limbs * ciL);1185mbedtls_mpi_core_cond_assign(t2, v, N_limbs, u_odd_v_even);1186mbedtls_mpi_core_cond_assign(t2, d, N_limbs, u_odd_v_odd);11871188mbedtls_mpi_core_shift_r(t2, N_limbs, 1); // t2 is even11891190/* Update u, v and re-order them if needed */1191memcpy(u, t1, N_limbs * ciL);1192memcpy(v, t2, N_limbs * ciL);1193mbedtls_ct_condition_t swap = mbedtls_mpi_core_lt_ct(v, u, N_limbs);1194mbedtls_mpi_core_cond_swap(u, v, N_limbs, swap);11951196/* Now, if modinv was requested, do the same with q, r, but:1197* - decisions still based on u and v (their initial values);1198* - operations are now mod N;1199* - we re-use t1, t2 for what the paper calls t3, t4 in Alg 8.1200*1201* Here we slightly diverge from the paper and instead do the obvious1202* thing that preserves the invariants involving q and r: mirror1203* operations on u and v, ie also divide by 2 here (mod N).1204*1205* The paper uses a trick where it replaces division by 2 with1206* multiplication by 2 here, and compensates in the end by multiplying1207* by pre_com, which is probably intended as an optimisation.1208*1209* However I believe it's not actually an optimisation, since1210* constant-time modular multiplication by 2 (left-shift + conditional1211* subtract) is just as costly as constant-time modular division by 21212* (conditional add + right-shift). So, skip it and keep things simple.1213*/1214if (I != NULL) {1215/* This is called t2 in Alg 7 (no name in Alg 8). */1216mpi_core_sub_mod(d, q, r, N, N_limbs);12171218/* t3 (the thing that's kept) */1219memcpy(t1, d, N_limbs * ciL);1220mbedtls_mpi_core_cond_assign(t1, r, N_limbs, u_odd_v_odd);12211222/* t4 (the thing that's shifted) */1223memcpy(t2, r, N_limbs * ciL);1224mbedtls_mpi_core_cond_assign(t2, q, N_limbs, u_odd_v_even);1225mbedtls_mpi_core_cond_assign(t2, d, N_limbs, u_odd_v_odd);12261227mbedtls_mpi_core_div2_mod_odd(t2, N, N_limbs);12281229/* Update and possibly swap */1230memcpy(r, t1, N_limbs * ciL);1231memcpy(q, t2, N_limbs * ciL);1232mbedtls_mpi_core_cond_swap(r, q, N_limbs, swap);1233}1234}12351236/* G and I already hold the correct values by virtue of being aliased */1237}12381239#endif /* MBEDTLS_BIGNUM_C */124012411242