From e9ffb6c8e9c0476cbfb450249c05ba8b97f6f5c4 Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Mon, 12 Dec 2022 11:26:02 +0000 Subject: [PATCH 01/13] Fix mbedtls_platform_zeroize() call in mbedtls_mpi_mod_modulus_free() Signed-off-by: Tom Cosgrove --- library/bignum_mod.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/bignum_mod.c b/library/bignum_mod.c index 0057ebae2..ac0be995d 100644 --- a/library/bignum_mod.c +++ b/library/bignum_mod.c @@ -79,7 +79,7 @@ void mbedtls_mpi_mod_modulus_free( mbedtls_mpi_mod_modulus *m ) if (m->rep.mont.rr != NULL) { mbedtls_platform_zeroize( (mbedtls_mpi_uint *) m->rep.mont.rr, - m->limbs ); + m->limbs * sizeof(mbedtls_mpi_uint) ); mbedtls_free( (mbedtls_mpi_uint *)m->rep.mont.rr ); m->rep.mont.rr = NULL; } From 30f3b4d60112ffe68cc162cc01938b84d18c9960 Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Mon, 12 Dec 2022 16:54:57 +0000 Subject: [PATCH 02/13] Add mbedtls_mpi_core_check_zero_ct() and tests Signed-off-by: Tom Cosgrove --- library/bignum_core.c | 11 +++++++++++ library/bignum_core.h | 13 +++++++++++++ scripts/mbedtls_dev/bignum_core.py | 14 ++++++++++++++ tests/suites/test_suite_bignum_core.function | 19 +++++++++++++++++++ 4 files changed, 57 insertions(+) diff --git a/library/bignum_core.c b/library/bignum_core.c index 1ce84574e..75cce0577 100644 --- a/library/bignum_core.c +++ b/library/bignum_core.c @@ -742,6 +742,17 @@ mbedtls_mpi_uint mbedtls_mpi_core_sub_int( mbedtls_mpi_uint *X, return( c ); } +mbedtls_mpi_uint mbedtls_mpi_core_check_zero_ct( const mbedtls_mpi_uint *A, + size_t limbs ) +{ + mbedtls_mpi_uint bits = 0; + + for( size_t i = 0; i < limbs; i++ ) + bits |= A[i]; + + return( bits ); +} + /* END MERGE SLOT 3 */ /* BEGIN MERGE SLOT 4 */ diff --git a/library/bignum_core.h b/library/bignum_core.h index b7af4d0aa..7f5375ee1 100644 --- a/library/bignum_core.h +++ b/library/bignum_core.h @@ -572,6 +572,19 @@ mbedtls_mpi_uint mbedtls_mpi_core_sub_int( mbedtls_mpi_uint *X, mbedtls_mpi_uint b, size_t limbs ); +/** + * \brief Determine if a given MPI has the value \c 0 in constant time with + * respect to the value (but not with respect to the number of limbs). + * + * \param[in] A The MPI to test. + * \param limbs Number of limbs in \p A. + * + * \return 0 if `A == 0` + * non-0 (may be any value) if `A != 0`. + */ +mbedtls_mpi_uint mbedtls_mpi_core_check_zero_ct( const mbedtls_mpi_uint *A, + size_t limbs ); + /* END MERGE SLOT 3 */ /* BEGIN MERGE SLOT 4 */ diff --git a/scripts/mbedtls_dev/bignum_core.py b/scripts/mbedtls_dev/bignum_core.py index 158ada99d..1a8c22bfa 100644 --- a/scripts/mbedtls_dev/bignum_core.py +++ b/scripts/mbedtls_dev/bignum_core.py @@ -818,6 +818,20 @@ class BignumCoreSubInt(BignumCoreTarget, bignum_common.OperationCommon): str(-borrow) ] +class BignumCoreZeroCheckCT(BignumCoreTarget, bignum_common.OperationCommon): + """Test cases for bignum core zero check (constant flow).""" + count = 0 + symbol = "== 0" + test_function = "mpi_core_check_zero_ct" + test_name = "mpi_core_check_zero_ct" + input_style = "variable" + arity = 1 + suffix = True + + def result(self) -> List[str]: + result = 1 if self.int_a == 0 else 0 + return [str(result)] + # END MERGE SLOT 3 # BEGIN MERGE SLOT 4 diff --git a/tests/suites/test_suite_bignum_core.function b/tests/suites/test_suite_bignum_core.function index 78721158f..9392f51d5 100644 --- a/tests/suites/test_suite_bignum_core.function +++ b/tests/suites/test_suite_bignum_core.function @@ -1162,6 +1162,25 @@ exit: } /* END_CASE */ +/* BEGIN_CASE */ +void mpi_core_check_zero_ct( char *input_X, int expected_is_zero ) +{ + mbedtls_mpi_uint *X = NULL; + size_t X_limbs; + + TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &X, &X_limbs, input_X ) ); + + TEST_CF_SECRET( X, X_limbs * sizeof( mbedtls_mpi_uint ) ); + + mbedtls_mpi_uint check = mbedtls_mpi_core_check_zero_ct( X, X_limbs ); + int is_zero = (check == 0); + TEST_EQUAL( is_zero, expected_is_zero ); + +exit: + mbedtls_free( X ); +} +/* END_CASE */ + /* END MERGE SLOT 3 */ /* BEGIN MERGE SLOT 4 */ From 28ff92cc3a72d98885e4fa6dc19e9725db5f9ac7 Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Mon, 12 Dec 2022 17:06:27 +0000 Subject: [PATCH 03/13] Add an explicit mbedtls_mpi_core_montmul_working_limbs() function Signed-off-by: Tom Cosgrove --- library/bignum_core.h | 21 +++++++++++++++++++ library/bignum_mod_raw.c | 4 ++-- library/bignum_mod_raw.h | 4 ++++ tests/suites/test_suite_bignum_core.function | 8 ++++++- .../suites/test_suite_bignum_mod_raw.function | 4 ++++ 5 files changed, 38 insertions(+), 3 deletions(-) diff --git a/library/bignum_core.h b/library/bignum_core.h index 7f5375ee1..7b5787c9c 100644 --- a/library/bignum_core.h +++ b/library/bignum_core.h @@ -502,6 +502,10 @@ int mbedtls_mpi_core_fill_random( mbedtls_mpi_uint *X, size_t X_limbs, * \brief Returns the number of limbs of working memory required for * a call to `mbedtls_mpi_core_exp_mod()`. * + * \note This will always be at least + * `mbedtls_mpi_core_montmul_working_limbs(AN_limbs)`, + * i.e. sufficient for a call to `mbedtls_mpi_core_montmul()`. + * * \param AN_limbs The number of limbs in the input `A` and the modulus `N` * (they must be the same size) that will be given to * `mbedtls_mpi_core_exp_mod()`. @@ -585,6 +589,23 @@ mbedtls_mpi_uint mbedtls_mpi_core_sub_int( mbedtls_mpi_uint *X, mbedtls_mpi_uint mbedtls_mpi_core_check_zero_ct( const mbedtls_mpi_uint *A, size_t limbs ); +/** + * \brief Returns the number of limbs of working memory required for + * a call to `mbedtls_mpi_core_montmul()`. + * + * \param AN_limbs The number of limbs in the input `A` and the modulus `N` + * (they must be the same size) that will be given to + * `mbedtls_mpi_core_montmul()` or one of the other functions + * that specifies this as the amount of working memory needed. + * + * \return The number of limbs of working memory required by + * `mbedtls_mpi_core_montmul()` (or other similar function). + */ +static inline size_t mbedtls_mpi_core_montmul_working_limbs( size_t AN_limbs ) +{ + return( 2 * AN_limbs + 1 ); +} + /* END MERGE SLOT 3 */ /* BEGIN MERGE SLOT 4 */ diff --git a/library/bignum_mod_raw.c b/library/bignum_mod_raw.c index c98a1c1cb..be8fc868d 100644 --- a/library/bignum_mod_raw.c +++ b/library/bignum_mod_raw.c @@ -183,7 +183,7 @@ int mbedtls_mpi_mod_raw_to_mont_rep( mbedtls_mpi_uint *X, const mbedtls_mpi_mod_modulus *m ) { mbedtls_mpi_uint *T; - const size_t t_limbs = m->limbs * 2 + 1; + const size_t t_limbs = mbedtls_mpi_core_montmul_working_limbs( m->limbs ); if( ( T = (mbedtls_mpi_uint *) mbedtls_calloc( t_limbs, ciL ) ) == NULL ) return( MBEDTLS_ERR_MPI_ALLOC_FAILED ); @@ -200,7 +200,7 @@ int mbedtls_mpi_mod_raw_from_mont_rep( mbedtls_mpi_uint *X, const mbedtls_mpi_mod_modulus *m ) { const mbedtls_mpi_uint one = 1; - const size_t t_limbs = m->limbs * 2 + 1; + const size_t t_limbs = mbedtls_mpi_core_montmul_working_limbs( m->limbs ); mbedtls_mpi_uint *T; if( ( T = (mbedtls_mpi_uint *) mbedtls_calloc( t_limbs, ciL ) ) == NULL ) diff --git a/library/bignum_mod_raw.h b/library/bignum_mod_raw.h index f9968ba74..73eaf1881 100644 --- a/library/bignum_mod_raw.h +++ b/library/bignum_mod_raw.h @@ -178,6 +178,10 @@ void mbedtls_mpi_mod_raw_sub( mbedtls_mpi_uint *X, * \brief Returns the number of limbs of working memory required for * a call to `mbedtls_mpi_mod_raw_inv_prime()`. * + * \note This will always be at least + * `mbedtls_mpi_core_montmul_working_limbs(AN_limbs)`, + * i.e. sufficient for a call to `mbedtls_mpi_core_montmul()`. + * * \param AN_limbs The number of limbs in the input `A` and the modulus `N` * (they must be the same size) that will be given to * `mbedtls_mpi_mod_raw_inv_prime()`. diff --git a/tests/suites/test_suite_bignum_core.function b/tests/suites/test_suite_bignum_core.function index 9392f51d5..038ee6b5a 100644 --- a/tests/suites/test_suite_bignum_core.function +++ b/tests/suites/test_suite_bignum_core.function @@ -798,7 +798,9 @@ void mpi_core_montmul( int limbs_AN4, int limbs_B4, TEST_EQUAL( 0, mbedtls_mpi_grow( X, limbs_AN ) ); TEST_EQUAL( 0, mbedtls_mpi_grow( &B, limbs_B ) ); - TEST_EQUAL( 0, mbedtls_mpi_grow( &T, limbs_AN * 2 + 1 ) ); + size_t working_limbs = mbedtls_mpi_core_montmul_working_limbs( limbs_AN ); + TEST_EQUAL( working_limbs, limbs_AN * 2 + 1 ); + TEST_EQUAL( 0, mbedtls_mpi_grow( &T, working_limbs ) ); /* Calculate the Montgomery constant (this is unit tested separately) */ mbedtls_mpi_uint mm = mbedtls_mpi_core_montmul_init( N.p ); @@ -1083,6 +1085,10 @@ void mpi_core_exp_mod( char * input_N, char * input_A, TEST_LE_U( min_expected_working_limbs, working_limbs ); TEST_LE_U( working_limbs, max_expected_working_limbs ); + /* Should also be at least mbedtls_mpi_core_montmul_working_limbs() */ + TEST_LE_U( mbedtls_mpi_core_montmul_working_limbs( N_limbs ), + working_limbs ); + ASSERT_ALLOC( T, working_limbs ); mbedtls_mpi_core_exp_mod( Y, A, N, N_limbs, E, E_limbs, R2, T ); diff --git a/tests/suites/test_suite_bignum_mod_raw.function b/tests/suites/test_suite_bignum_mod_raw.function index 83e1f543e..ef0f71227 100644 --- a/tests/suites/test_suite_bignum_mod_raw.function +++ b/tests/suites/test_suite_bignum_mod_raw.function @@ -394,6 +394,10 @@ void mpi_mod_raw_inv_prime( char * input_N, char * input_A, char * input_X ) TEST_LE_U( min_expected_working_limbs, working_limbs ); TEST_LE_U( working_limbs, max_expected_working_limbs ); + /* Should also be at least mbedtls_mpi_core_montmul_working_limbs() */ + TEST_LE_U( mbedtls_mpi_core_montmul_working_limbs( N_limbs ), + working_limbs ); + ASSERT_ALLOC( T, working_limbs ); mbedtls_mpi_mod_raw_inv_prime( Y, A, N, N_limbs, R2, T ); From 786848b5c56cdebc046c72703e0110200849d918 Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Tue, 13 Dec 2022 10:45:19 +0000 Subject: [PATCH 04/13] Add low-level Montgomery conversion functions to bignum_core Signed-off-by: Tom Cosgrove --- library/bignum_core.c | 23 +++++ library/bignum_core.h | 75 ++++++++++++++++ library/bignum_mod_raw.c | 8 +- .../suites/test_suite_bignum_mod_raw.function | 86 ++++++++++++++++--- 4 files changed, 173 insertions(+), 19 deletions(-) diff --git a/library/bignum_core.c b/library/bignum_core.c index 75cce0577..74efb38f2 100644 --- a/library/bignum_core.c +++ b/library/bignum_core.c @@ -753,6 +753,29 @@ mbedtls_mpi_uint mbedtls_mpi_core_check_zero_ct( const mbedtls_mpi_uint *A, return( bits ); } +void mbedtls_mpi_core_to_mont_rep( mbedtls_mpi_uint *X, + const mbedtls_mpi_uint *A, + const mbedtls_mpi_uint *N, + size_t AN_limbs, + mbedtls_mpi_uint mm, + const mbedtls_mpi_uint *rr, + mbedtls_mpi_uint *T ) +{ + mbedtls_mpi_core_montmul( X, A, rr, AN_limbs, N, AN_limbs, mm, T ); +} + +void mbedtls_mpi_core_from_mont_rep( mbedtls_mpi_uint *X, + const mbedtls_mpi_uint *A, + const mbedtls_mpi_uint *N, + size_t AN_limbs, + mbedtls_mpi_uint mm, + mbedtls_mpi_uint *T ) +{ + const mbedtls_mpi_uint Rinv = 1; /* 1/R in Mont. rep => 1 */ + + mbedtls_mpi_core_montmul( X, A, &Rinv, 1, N, AN_limbs, mm, T ); +} + /* END MERGE SLOT 3 */ /* BEGIN MERGE SLOT 4 */ diff --git a/library/bignum_core.h b/library/bignum_core.h index 7b5787c9c..b8985274c 100644 --- a/library/bignum_core.h +++ b/library/bignum_core.h @@ -606,6 +606,81 @@ static inline size_t mbedtls_mpi_core_montmul_working_limbs( size_t AN_limbs ) return( 2 * AN_limbs + 1 ); } +/** Convert an MPI into Montgomery form. + * + * \p X may be aliased to \p A, but may not otherwise overlap it. + * + * \p X may not alias \p N (it is in canonical form, so must be stricly less + * than \p N). Nor may it alias or overlap \p rr (this is unlikely to be + * required in practice.) + * + * This function is a thin wrapper around `mbedtls_mpi_core_montmul()` that is + * an alternative to calling `mbedtls_mpi_mod_raw_to_mont_rep()` when we + * don't want to allocate memory. + * + * \param[out] X The result of the conversion. + * Must have the same number of limbs as \p A. + * \param[in] A The MPI to convert into Montgomery form. + * Must have the same number of limbs as the modulus. + * \param[in] N The address of the modulus, which gives the size of + * the base `R` = 2^(biL*m->limbs). + * \param[in] AN_limbs The number of limbs in \p X, \p A, \p N and \p rr. + * \param mm The Montgomery constant for \p N: -N^-1 mod 2^biL. + * This can be determined by calling + * `mbedtls_mpi_core_montmul_init()`. + * \param[in] rr The residue for `2^{2*n*biL} mod N`. + * \param[in,out] T Temporary storage of size at least + * `mbedtls_mpi_core_montmul_working_limbs(AN_limbs)` + * limbs. + * Its initial content is unused and + * its final content is indeterminate. + * It must not alias or otherwise overlap any of the + * other parameters. + */ +void mbedtls_mpi_core_to_mont_rep( mbedtls_mpi_uint *X, + const mbedtls_mpi_uint *A, + const mbedtls_mpi_uint *N, + size_t AN_limbs, + mbedtls_mpi_uint mm, + const mbedtls_mpi_uint *rr, + mbedtls_mpi_uint *T ); + +/** Convert an MPI from Montgomery form. + * + * \p X may be aliased to \p A, but may not otherwise overlap it. + * + * \p X may not alias \p N (it is in canonical form, so must be stricly less + * than \p N). + * + * This function is a thin wrapper around `mbedtls_mpi_core_montmul()` that is + * an alternative to calling `mbedtls_mpi_mod_raw_from_mont_rep()` when we + * don't want to allocate memory. + * + * \param[out] X The result of the conversion. + * Must have the same number of limbs as \p A. + * \param[in] A The MPI to convert from Montgomery form. + * Must have the same number of limbs as the modulus. + * \param[in] N The address of the modulus, which gives the size of + * the base `R` = 2^(biL*m->limbs). + * \param[in] AN_limbs The number of limbs in \p X, \p A and \p N. + * \param mm The Montgomery constant for \p N: -N^-1 mod 2^biL. + * This can be determined by calling + * `mbedtls_mpi_core_montmul_init()`. + * \param[in,out] T Temporary storage of size at least + * `mbedtls_mpi_core_montmul_working_limbs(AN_limbs)` + * limbs. + * Its initial content is unused and + * its final content is indeterminate. + * It must not alias or otherwise overlap any of the + * other parameters. + */ +void mbedtls_mpi_core_from_mont_rep( mbedtls_mpi_uint *X, + const mbedtls_mpi_uint *A, + const mbedtls_mpi_uint *N, + size_t AN_limbs, + mbedtls_mpi_uint mm, + mbedtls_mpi_uint *T ); + /* END MERGE SLOT 3 */ /* BEGIN MERGE SLOT 4 */ diff --git a/library/bignum_mod_raw.c b/library/bignum_mod_raw.c index be8fc868d..d2d93d3c9 100644 --- a/library/bignum_mod_raw.c +++ b/library/bignum_mod_raw.c @@ -188,8 +188,8 @@ int mbedtls_mpi_mod_raw_to_mont_rep( mbedtls_mpi_uint *X, if( ( T = (mbedtls_mpi_uint *) mbedtls_calloc( t_limbs, ciL ) ) == NULL ) return( MBEDTLS_ERR_MPI_ALLOC_FAILED ); - mbedtls_mpi_core_montmul( X, X, m->rep.mont.rr, m->limbs, m->p, m->limbs, - m->rep.mont.mm, T ); + mbedtls_mpi_core_to_mont_rep( X, X, m->p, m->limbs, + m->rep.mont.mm, m->rep.mont.rr, T ); mbedtls_platform_zeroize( T, t_limbs * ciL ); mbedtls_free( T ); @@ -199,15 +199,13 @@ int mbedtls_mpi_mod_raw_to_mont_rep( mbedtls_mpi_uint *X, int mbedtls_mpi_mod_raw_from_mont_rep( mbedtls_mpi_uint *X, const mbedtls_mpi_mod_modulus *m ) { - const mbedtls_mpi_uint one = 1; const size_t t_limbs = mbedtls_mpi_core_montmul_working_limbs( m->limbs ); mbedtls_mpi_uint *T; if( ( T = (mbedtls_mpi_uint *) mbedtls_calloc( t_limbs, ciL ) ) == NULL ) return( MBEDTLS_ERR_MPI_ALLOC_FAILED ); - mbedtls_mpi_core_montmul( X, X, &one, 1, m->p, m->limbs, - m->rep.mont.mm, T ); + mbedtls_mpi_core_from_mont_rep( X, X, m->p, m->limbs, m->rep.mont.mm, T ); mbedtls_platform_zeroize( T, t_limbs * ciL ); mbedtls_free( T ); diff --git a/tests/suites/test_suite_bignum_mod_raw.function b/tests/suites/test_suite_bignum_mod_raw.function index ef0f71227..50fdac317 100644 --- a/tests/suites/test_suite_bignum_mod_raw.function +++ b/tests/suites/test_suite_bignum_mod_raw.function @@ -533,8 +533,10 @@ void mpi_mod_raw_to_mont_rep( char * input_N, char * input_A, char * input_X ) { mbedtls_mpi_uint *N = NULL; mbedtls_mpi_uint *A = NULL; + mbedtls_mpi_uint *R = NULL; /* for result of low-level conversion */ mbedtls_mpi_uint *X = NULL; - size_t n_limbs, a_limbs, x_limbs, x_bytes; + mbedtls_mpi_uint *T = NULL; + size_t n_limbs, a_limbs, x_limbs; mbedtls_mpi_mod_modulus m; mbedtls_mpi_mod_modulus_init( &m ); @@ -543,23 +545,50 @@ void mpi_mod_raw_to_mont_rep( char * input_N, char * input_A, char * input_X ) TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &N, &n_limbs, input_N ) ); TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &A, &a_limbs, input_A ) ); TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &X, &x_limbs, input_X ) ); - x_bytes = x_limbs * sizeof(mbedtls_mpi_uint); - /* Test that input does not require more limbs than modulo */ - TEST_LE_U(a_limbs, n_limbs); + /* Number to convert must have same number of limbs as modulus */ + TEST_EQUAL(a_limbs, n_limbs); + + /* Higher-level conversion is in-place, so expected result must have the + * same number of limbs too */ + TEST_EQUAL(x_limbs, n_limbs); + + size_t limbs = n_limbs; + size_t bytes = limbs * sizeof(mbedtls_mpi_uint); TEST_EQUAL( 0, mbedtls_mpi_mod_modulus_setup( &m, N, n_limbs, - MBEDTLS_MPI_MOD_REP_MONTGOMERY ) ); + MBEDTLS_MPI_MOD_REP_MONTGOMERY ) ); + + /* 1. Test low-level function first */ + + /* It has separate output, and requires temporary working storage */ + size_t temp_limbs = mbedtls_mpi_core_montmul_working_limbs( limbs ); + ASSERT_ALLOC( T, temp_limbs ); + ASSERT_ALLOC( R, limbs ); + mbedtls_mpi_core_to_mont_rep( R, A, N, n_limbs, + m.rep.mont.mm, m.rep.mont.rr, T ); + /* Test that the low-level function gives the required value */ + ASSERT_COMPARE( R, bytes, X, bytes ); + + /* Test when output is aliased to input */ + memcpy( R, A, bytes ); + mbedtls_mpi_core_to_mont_rep( R, R, N, n_limbs, + m.rep.mont.mm, m.rep.mont.rr, T ); + ASSERT_COMPARE( R, bytes, X, bytes ); + + /* 2. Test higher-level cannonical to Montgomery conversion */ - /* Convert from cannonical into Montgomery representation */ TEST_EQUAL(0, mbedtls_mpi_mod_raw_to_mont_rep( A, &m ) ); /* The result matches expected value */ - ASSERT_COMPARE( A, x_bytes, X, x_bytes ); + ASSERT_COMPARE( A, bytes, X, bytes ); + exit: mbedtls_mpi_mod_modulus_free( &m ); + mbedtls_free( T ); mbedtls_free( N ); mbedtls_free( A ); + mbedtls_free( R ); mbedtls_free( X ); } /* END_CASE */ @@ -569,8 +598,10 @@ void mpi_mod_raw_from_mont_rep( char * input_N, char * input_A, char * input_X ) { mbedtls_mpi_uint *N = NULL; mbedtls_mpi_uint *A = NULL; + mbedtls_mpi_uint *R = NULL; /* for result of low-level conversion */ mbedtls_mpi_uint *X = NULL; - size_t n_limbs, a_limbs, x_limbs, x_bytes; + mbedtls_mpi_uint *T = NULL; + size_t n_limbs, a_limbs, x_limbs; mbedtls_mpi_mod_modulus m; mbedtls_mpi_mod_modulus_init( &m ); @@ -579,23 +610,50 @@ void mpi_mod_raw_from_mont_rep( char * input_N, char * input_A, char * input_X ) TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &N, &n_limbs, input_N ) ); TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &A, &a_limbs, input_A ) ); TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &X, &x_limbs, input_X ) ); - x_bytes = x_limbs * sizeof(mbedtls_mpi_uint); - /* Test that input does not require more limbs than modulo */ - TEST_LE_U(a_limbs, n_limbs); + /* Number to convert must have same number of limbs as modulus */ + TEST_EQUAL(a_limbs, n_limbs); + + /* Higher-level conversion is in-place, so expected result must have the + * same number of limbs too */ + TEST_EQUAL(x_limbs, n_limbs); + + size_t limbs = n_limbs; + size_t bytes = limbs * sizeof(mbedtls_mpi_uint); TEST_EQUAL( 0, mbedtls_mpi_mod_modulus_setup( &m, N, n_limbs, - MBEDTLS_MPI_MOD_REP_MONTGOMERY ) ); + MBEDTLS_MPI_MOD_REP_MONTGOMERY ) ); + + /* 1. Test low-level function first */ + + /* It has separate output, and requires temporary working storage */ + size_t temp_limbs = mbedtls_mpi_core_montmul_working_limbs( limbs ); + ASSERT_ALLOC( T, temp_limbs ); + ASSERT_ALLOC( R, limbs ); + mbedtls_mpi_core_from_mont_rep( R, A, N, n_limbs, + m.rep.mont.mm, T ); + /* Test that the low-level function gives the required value */ + ASSERT_COMPARE( R, bytes, X, bytes ); + + /* Test when output is aliased to input */ + memcpy( R, A, bytes ); + mbedtls_mpi_core_from_mont_rep( R, R, N, n_limbs, + m.rep.mont.mm, T ); + ASSERT_COMPARE( R, bytes, X, bytes ); + + /* 2. Test higher-level Montgomery to cannonical conversion */ - /* Convert from Montgomery into cannonical representation */ TEST_EQUAL(0, mbedtls_mpi_mod_raw_from_mont_rep( A, &m ) ); /* The result matches expected value */ - ASSERT_COMPARE( A, x_bytes, X, x_bytes ); + ASSERT_COMPARE( A, bytes, X, bytes ); + exit: mbedtls_mpi_mod_modulus_free( &m ); + mbedtls_free( T ); mbedtls_free( N ); mbedtls_free( A ); + mbedtls_free( R ); mbedtls_free( X ); } /* END_CASE */ From 4302d02fa8cf8f4b9083f70935abb402ff7ab7f5 Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Tue, 13 Dec 2022 10:46:39 +0000 Subject: [PATCH 05/13] Add mbedtls_mpi_mod_inv() Signed-off-by: Tom Cosgrove --- library/bignum_mod.c | 101 +++++++++++++++++++++++++++++++++++++++++++ library/bignum_mod.h | 26 +++++++++++ 2 files changed, 127 insertions(+) diff --git a/library/bignum_mod.c b/library/bignum_mod.c index ac0be995d..216b20f8f 100644 --- a/library/bignum_mod.c +++ b/library/bignum_mod.c @@ -191,6 +191,107 @@ int mbedtls_mpi_mod_sub( mbedtls_mpi_mod_residue *X, return( 0 ); } + +int mbedtls_mpi_mod_inv( mbedtls_mpi_mod_residue *X, + const mbedtls_mpi_mod_residue *A, + const mbedtls_mpi_mod_modulus *N ) +{ + if( X->limbs != N->limbs || A->limbs != N->limbs ) + return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); + + /* Zero has the same value regardless of Montgomery form or not */ + if( mbedtls_mpi_core_check_zero_ct( A->p, A->limbs ) == 0 ) + return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); + + /* Will we need to do Montgomery conversion? */ + int mont_conv_needed; + switch( N->int_rep ) + { + case MBEDTLS_MPI_MOD_REP_MONTGOMERY: + mont_conv_needed = 0; + break; + case MBEDTLS_MPI_MOD_REP_OPT_RED: + mont_conv_needed = 1; + break; + default: + return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); + } + + int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; + + /* If the input is already in Montgomery form, we have little to do but + * allocate working memory and call mbedtls_mpi_mod_raw_inv_prime(). + * + * If it's not, we need to + * 1. Create a Montgomery version of the modulus; + * 2. Convert the input into Mont. form, using X->p to hold it; + * 3. (allocate and convert, same as if already in Mont. form); + * 4. Convert the inverted output back from Mont. form. + * + * Since the Montgomery conversion functions are in-place, we'll need to + * copy A into X before we start working on it (which could be avoided if + * there was a not-in-place function to convert to Montgomery form. + */ + + /* Montgomery version of modulus (if not already in Mont. form). + * We will only call setup if the input is not already in Montgomery form. + * We will re-use N->p from input modulus, and make use of the fact that + * mbedtls_mpi_mod_raw_to_mont_rep() won't free it. */ + mbedtls_mpi_mod_modulus Nmont; + mbedtls_mpi_mod_modulus_init( &Nmont ); + + size_t working_limbs = + mbedtls_mpi_mod_raw_inv_prime_working_limbs( N->limbs ); + + mbedtls_mpi_uint *working_memory = mbedtls_calloc( working_limbs, + sizeof(mbedtls_mpi_uint) ); + if( working_memory == NULL ) + { + ret = MBEDTLS_ERR_MPI_ALLOC_FAILED; + goto cleanup; + } + + const mbedtls_mpi_uint *to_invert; /* Will alias A->p or X->p */ + const mbedtls_mpi_mod_modulus *Nuse; /* Which of N and Nmont to use */ + + if( mont_conv_needed ) + { + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_modulus_setup( &Nmont, N->p, N->limbs, + MBEDTLS_MPI_MOD_REP_MONTGOMERY ) ); + + mbedtls_mpi_core_to_mont_rep( X->p, A->p, Nmont.p, Nmont.limbs, + Nmont.rep.mont.mm, Nmont.rep.mont.rr, + working_memory ); + to_invert = X->p; + Nuse = &Nmont; + } + else + { + to_invert = A->p; + Nuse = N; + } + + mbedtls_mpi_mod_raw_inv_prime( X->p, to_invert, + Nuse->p, Nuse->limbs, + Nuse->rep.mont.rr, + working_memory ); + + if( mont_conv_needed ) + mbedtls_mpi_core_from_mont_rep( X->p, X->p, Nmont.p, Nmont.limbs, + Nmont.rep.mont.mm, working_memory ); + +cleanup: + mbedtls_mpi_mod_modulus_free( &Nmont ); + + if (working_memory != NULL ) + { + mbedtls_platform_zeroize( working_memory, + working_limbs * sizeof(mbedtls_mpi_uint) ); + mbedtls_free( working_memory ); + } + + return( ret ); +} /* END MERGE SLOT 3 */ /* BEGIN MERGE SLOT 4 */ diff --git a/library/bignum_mod.h b/library/bignum_mod.h index 11b4e980f..b2c36a978 100644 --- a/library/bignum_mod.h +++ b/library/bignum_mod.h @@ -192,6 +192,32 @@ int mbedtls_mpi_mod_sub( mbedtls_mpi_mod_residue *X, const mbedtls_mpi_mod_residue *A, const mbedtls_mpi_mod_residue *B, const mbedtls_mpi_mod_modulus *N ); + +/** + * \brief Perform modular inversion of an MPI with respect to a modulus \p N. + * + * \p X may be aliased to \p A. + * + * \warning Currently only supports prime moduli, but does not check for them. + * + * \param[out] X The modular inverse of \p A with respect to \p N. + * \param[in] A The number to calculate the modular inverse of. + * Must not be 0. + * \param[in] N The modulus to use. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p A and \p N do not + * have the same number of limbs. + * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p A is zero. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if couldn't allocate enough + * memory (needed for conversion to and from Mongtomery form + * when not in Montgomery form already, and for temporary use + * by the inversion calculation itself). + */ + +int mbedtls_mpi_mod_inv( mbedtls_mpi_mod_residue *X, + const mbedtls_mpi_mod_residue *A, + const mbedtls_mpi_mod_modulus *N ); /* END MERGE SLOT 3 */ /* BEGIN MERGE SLOT 4 */ From a9e0f95903c3c2881011ab413454490762712dc6 Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Tue, 13 Dec 2022 11:57:57 +0000 Subject: [PATCH 06/13] Split mbedtls_mpi_mod_inv() into separate functions for mont/non-mont form Signed-off-by: Tom Cosgrove --- library/bignum_mod.c | 144 ++++++++++++++++++++----------------------- 1 file changed, 66 insertions(+), 78 deletions(-) diff --git a/library/bignum_mod.c b/library/bignum_mod.c index 216b20f8f..7c89b57d7 100644 --- a/library/bignum_mod.c +++ b/library/bignum_mod.c @@ -192,6 +192,54 @@ int mbedtls_mpi_mod_sub( mbedtls_mpi_mod_residue *X, return( 0 ); } +static int mbedtls_mpi_mod_inv_mont( mbedtls_mpi_mod_residue *X, + const mbedtls_mpi_mod_residue *A, + const mbedtls_mpi_mod_modulus *N, + mbedtls_mpi_uint *working_memory ) +{ + /* Input already in Montgomery form, so there's little to do */ + mbedtls_mpi_mod_raw_inv_prime( X->p, A->p, + N->p, N->limbs, + N->rep.mont.rr, + working_memory ); + return( 0 ); +} + +static int mbedtls_mpi_mod_inv_non_mont( mbedtls_mpi_mod_residue *X, + const mbedtls_mpi_mod_residue *A, + const mbedtls_mpi_mod_modulus *N, + mbedtls_mpi_uint *working_memory ) +{ + /* Need to convert input into Montgomery form */ + + int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; + + mbedtls_mpi_mod_modulus Nmont; + mbedtls_mpi_mod_modulus_init( &Nmont ); + + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_modulus_setup( &Nmont, N->p, N->limbs, + MBEDTLS_MPI_MOD_REP_MONTGOMERY ) ); + + /* We'll use X->p to hold the Montgomery form of the input A->p */ + mbedtls_mpi_core_to_mont_rep( X->p, A->p, Nmont.p, Nmont.limbs, + Nmont.rep.mont.mm, Nmont.rep.mont.rr, + working_memory ); + + mbedtls_mpi_mod_raw_inv_prime( X->p, X->p, + Nmont.p, Nmont.limbs, + Nmont.rep.mont.rr, + working_memory ); + + /* And convert back from Montgomery form */ + + mbedtls_mpi_core_from_mont_rep( X->p, X->p, Nmont.p, Nmont.limbs, + Nmont.rep.mont.mm, working_memory ); + +cleanup: + mbedtls_mpi_mod_modulus_free( &Nmont ); + return( ret ); +} + int mbedtls_mpi_mod_inv( mbedtls_mpi_mod_residue *X, const mbedtls_mpi_mod_residue *A, const mbedtls_mpi_mod_modulus *N ) @@ -203,94 +251,34 @@ int mbedtls_mpi_mod_inv( mbedtls_mpi_mod_residue *X, if( mbedtls_mpi_core_check_zero_ct( A->p, A->limbs ) == 0 ) return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); - /* Will we need to do Montgomery conversion? */ - int mont_conv_needed; - switch( N->int_rep ) - { - case MBEDTLS_MPI_MOD_REP_MONTGOMERY: - mont_conv_needed = 0; - break; - case MBEDTLS_MPI_MOD_REP_OPT_RED: - mont_conv_needed = 1; - break; - default: - return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); - } - - int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; - - /* If the input is already in Montgomery form, we have little to do but - * allocate working memory and call mbedtls_mpi_mod_raw_inv_prime(). - * - * If it's not, we need to - * 1. Create a Montgomery version of the modulus; - * 2. Convert the input into Mont. form, using X->p to hold it; - * 3. (allocate and convert, same as if already in Mont. form); - * 4. Convert the inverted output back from Mont. form. - * - * Since the Montgomery conversion functions are in-place, we'll need to - * copy A into X before we start working on it (which could be avoided if - * there was a not-in-place function to convert to Montgomery form. - */ - - /* Montgomery version of modulus (if not already in Mont. form). - * We will only call setup if the input is not already in Montgomery form. - * We will re-use N->p from input modulus, and make use of the fact that - * mbedtls_mpi_mod_raw_to_mont_rep() won't free it. */ - mbedtls_mpi_mod_modulus Nmont; - mbedtls_mpi_mod_modulus_init( &Nmont ); - size_t working_limbs = mbedtls_mpi_mod_raw_inv_prime_working_limbs( N->limbs ); mbedtls_mpi_uint *working_memory = mbedtls_calloc( working_limbs, sizeof(mbedtls_mpi_uint) ); if( working_memory == NULL ) + return( MBEDTLS_ERR_MPI_ALLOC_FAILED ); + + int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; + + switch( N->int_rep ) { - ret = MBEDTLS_ERR_MPI_ALLOC_FAILED; - goto cleanup; + case MBEDTLS_MPI_MOD_REP_MONTGOMERY: + ret = mbedtls_mpi_mod_inv_mont( X, A, N, working_memory ); + break; + case MBEDTLS_MPI_MOD_REP_OPT_RED: + ret = mbedtls_mpi_mod_inv_non_mont( X, A, N, working_memory ); + break; + default: + ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; + break; } - const mbedtls_mpi_uint *to_invert; /* Will alias A->p or X->p */ - const mbedtls_mpi_mod_modulus *Nuse; /* Which of N and Nmont to use */ + mbedtls_platform_zeroize( working_memory, + working_limbs * sizeof(mbedtls_mpi_uint) ); + free( working_memory ); - if( mont_conv_needed ) - { - MBEDTLS_MPI_CHK( mbedtls_mpi_mod_modulus_setup( &Nmont, N->p, N->limbs, - MBEDTLS_MPI_MOD_REP_MONTGOMERY ) ); - - mbedtls_mpi_core_to_mont_rep( X->p, A->p, Nmont.p, Nmont.limbs, - Nmont.rep.mont.mm, Nmont.rep.mont.rr, - working_memory ); - to_invert = X->p; - Nuse = &Nmont; - } - else - { - to_invert = A->p; - Nuse = N; - } - - mbedtls_mpi_mod_raw_inv_prime( X->p, to_invert, - Nuse->p, Nuse->limbs, - Nuse->rep.mont.rr, - working_memory ); - - if( mont_conv_needed ) - mbedtls_mpi_core_from_mont_rep( X->p, X->p, Nmont.p, Nmont.limbs, - Nmont.rep.mont.mm, working_memory ); - -cleanup: - mbedtls_mpi_mod_modulus_free( &Nmont ); - - if (working_memory != NULL ) - { - mbedtls_platform_zeroize( working_memory, - working_limbs * sizeof(mbedtls_mpi_uint) ); - mbedtls_free( working_memory ); - } - - return( ret ); + return ret; } /* END MERGE SLOT 3 */ From dbac60924b5c1cddc586c6f2b578f82b0c439f2f Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Wed, 14 Dec 2022 08:27:18 +0000 Subject: [PATCH 07/13] mbedtls_mpi_mod_raw_inv_prime() tests should be arch_split Signed-off-by: Tom Cosgrove --- scripts/mbedtls_dev/bignum_data.py | 3 +++ scripts/mbedtls_dev/bignum_mod_raw.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/mbedtls_dev/bignum_data.py b/scripts/mbedtls_dev/bignum_data.py index 965893320..0a48e538d 100644 --- a/scripts/mbedtls_dev/bignum_data.py +++ b/scripts/mbedtls_dev/bignum_data.py @@ -121,6 +121,9 @@ MODULI_DEFAULT = [ ONLY_PRIME_MODULI = [ "53", # safe prime "8ac72304057392b5", # 9999999997777777333 (longer, not safe, prime) + # The next prime has a different R in Montgomery form depending on + # whether 32- or 64-bit MPIs are used. + "152d02c7e14af67fe0bf", # 99999999999999999991999 SAFE_PRIME_192_BIT_SEED_1, # safe prime SAFE_PRIME_1024_BIT_SEED_3, # safe prime ] diff --git a/scripts/mbedtls_dev/bignum_mod_raw.py b/scripts/mbedtls_dev/bignum_mod_raw.py index 6fc4c919b..0084898be 100644 --- a/scripts/mbedtls_dev/bignum_mod_raw.py +++ b/scripts/mbedtls_dev/bignum_mod_raw.py @@ -61,7 +61,7 @@ class BignumModRawInvPrime(bignum_common.ModOperationCommon, symbol = "^ -1" test_function = "mpi_mod_raw_inv_prime" test_name = "mbedtls_mpi_mod_raw_inv_prime (Montgomery form only)" - input_style = "fixed" + input_style = "arch_split" arity = 1 suffix = True From d692ba4248c565c906cacdebb37840274e9444b4 Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Wed, 14 Dec 2022 09:53:45 +0000 Subject: [PATCH 08/13] Note that (as usual) for mbedtls_mpi_mod_inv() residues must be associated with the modulus Signed-off-by: Tom Cosgrove --- library/bignum_mod.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/library/bignum_mod.h b/library/bignum_mod.h index b2c36a978..a708be6e9 100644 --- a/library/bignum_mod.h +++ b/library/bignum_mod.h @@ -196,6 +196,9 @@ int mbedtls_mpi_mod_sub( mbedtls_mpi_mod_residue *X, /** * \brief Perform modular inversion of an MPI with respect to a modulus \p N. * + * \p A and \p X must be associated with the modulus \p N and will therefore + * have the same number of limbs as \p N. + * * \p X may be aliased to \p A. * * \warning Currently only supports prime moduli, but does not check for them. From b38c2ed3d94017fc7181d9f3e17c40383899ee5f Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Wed, 14 Dec 2022 13:11:46 +0000 Subject: [PATCH 09/13] Fix double space between words Signed-off-by: Tom Cosgrove --- library/bignum_core.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/bignum_core.h b/library/bignum_core.h index b8985274c..b079850d9 100644 --- a/library/bignum_core.h +++ b/library/bignum_core.h @@ -626,7 +626,7 @@ static inline size_t mbedtls_mpi_core_montmul_working_limbs( size_t AN_limbs ) * the base `R` = 2^(biL*m->limbs). * \param[in] AN_limbs The number of limbs in \p X, \p A, \p N and \p rr. * \param mm The Montgomery constant for \p N: -N^-1 mod 2^biL. - * This can be determined by calling + * This can be determined by calling * `mbedtls_mpi_core_montmul_init()`. * \param[in] rr The residue for `2^{2*n*biL} mod N`. * \param[in,out] T Temporary storage of size at least @@ -664,7 +664,7 @@ void mbedtls_mpi_core_to_mont_rep( mbedtls_mpi_uint *X, * the base `R` = 2^(biL*m->limbs). * \param[in] AN_limbs The number of limbs in \p X, \p A and \p N. * \param mm The Montgomery constant for \p N: -N^-1 mod 2^biL. - * This can be determined by calling + * This can be determined by calling * `mbedtls_mpi_core_montmul_init()`. * \param[in,out] T Temporary storage of size at least * `mbedtls_mpi_core_montmul_working_limbs(AN_limbs)` From dc197593273864636bb8cb49b73ed38ea81a7886 Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Thu, 15 Dec 2022 16:59:40 +0000 Subject: [PATCH 10/13] Add tests for mbedtls_mpi_mod_inv() Signed-off-by: Tom Cosgrove --- scripts/mbedtls_dev/bignum_mod.py | 51 ++++++++++ tests/suites/test_suite_bignum_mod.function | 100 +++++++++++++++++++ tests/suites/test_suite_bignum_mod.misc.data | 44 ++++++++ 3 files changed, 195 insertions(+) diff --git a/scripts/mbedtls_dev/bignum_mod.py b/scripts/mbedtls_dev/bignum_mod.py index a16699a64..9f98131bd 100644 --- a/scripts/mbedtls_dev/bignum_mod.py +++ b/scripts/mbedtls_dev/bignum_mod.py @@ -18,6 +18,7 @@ from typing import Dict, List from . import test_data_generation from . import bignum_common +from .bignum_data import ONLY_PRIME_MODULI class BignumModTarget(test_data_generation.BaseTarget): #pylint: disable=abstract-method, too-few-public-methods @@ -48,6 +49,56 @@ class BignumModSub(bignum_common.ModOperationCommon, BignumModTarget): # generated cases return [self.format_result(result), "0"] +class BignumModInvNonMont(bignum_common.ModOperationCommon, BignumModTarget): + """Test cases for bignum mpi_mod_inv() - not in Montgomery form.""" + moduli = ONLY_PRIME_MODULI # for now only prime moduli supported + symbol = "^ -1" + test_function = "mpi_mod_inv_non_mont" + test_name = "mbedtls_mpi_mod_inv non-Mont. form" + input_style = "fixed" + arity = 1 + suffix = True + + @property + def is_valid(self) -> bool: + return self.int_a > 0 and self.int_a < self.int_n + + def result(self) -> List[str]: + result = bignum_common.invmod(self.int_a, self.int_n) + if result < 0: + result += self.int_n + # To make negative tests easier, append 0 for success to the + # generated cases + return [self.format_result(result), "0"] + +class BignumModInvMont(bignum_common.ModOperationCommon, BignumModTarget): + """Test cases for bignum mpi_mod_inv() - Montgomery form.""" + moduli = ONLY_PRIME_MODULI # for now only prime moduli supported + symbol = "^ -1" + test_function = "mpi_mod_inv_mont" + test_name = "mbedtls_mpi_mod_inv Mont. form" + input_style = "arch_split" # Mont. form requires arch_split + arity = 1 + suffix = True + + @property + def is_valid(self) -> bool: + return self.int_a > 0 and self.int_a < self.int_n + + @property + def arg_a(self) -> str: + mont_a = self.to_montgomery(self.int_a) + return self.format_arg('{:x}'.format(mont_a)) + + def result(self) -> List[str]: + result = bignum_common.invmod(self.int_a, self.int_n) + if result < 0: + result += self.int_n + mont_result = self.to_montgomery(result) + # To make negative tests easier, append 0 for success to the + # generated cases + return [self.format_result(mont_result), "0"] + # END MERGE SLOT 3 # BEGIN MERGE SLOT 4 diff --git a/tests/suites/test_suite_bignum_mod.function b/tests/suites/test_suite_bignum_mod.function index 507920afd..4b77a4a7e 100644 --- a/tests/suites/test_suite_bignum_mod.function +++ b/tests/suites/test_suite_bignum_mod.function @@ -203,6 +203,106 @@ exit: mbedtls_free( X_raw ); } /* END_CASE */ + +/* BEGIN_CASE */ +void mpi_mod_inv_mont( char * input_N, + char * input_A, char * input_I, + int expected_ret ) +{ + mbedtls_mpi_mod_residue a = { NULL, 0 }; /* argument */ + mbedtls_mpi_mod_residue i = { NULL, 0 }; /* expected inverse wrt N */ + mbedtls_mpi_mod_residue x = { NULL, 0 }; /* output */ + mbedtls_mpi_uint *X_raw = NULL; + + mbedtls_mpi_mod_modulus N; + mbedtls_mpi_mod_modulus_init( &N ); + + TEST_EQUAL( 0, + test_read_modulus( &N, MBEDTLS_MPI_MOD_REP_MONTGOMERY, input_N ) ); + + /* test_read_residue() normally checks that inputs have the same number of + * limbs as the modulus. For negative testing we can ask it to skip this + * with a non-zero final parameter. */ + TEST_EQUAL( 0, test_read_residue( &a, &N, input_A, expected_ret != 0 ) ); + TEST_EQUAL( 0, test_read_residue( &i, &N, input_I, expected_ret != 0 ) ); + + size_t limbs = N.limbs; + size_t bytes = limbs * sizeof( *X_raw ); + + ASSERT_ALLOC( X_raw, limbs ); + + TEST_EQUAL( 0, mbedtls_mpi_mod_residue_setup( &x, &N, X_raw, limbs ) ); + + TEST_EQUAL( expected_ret, mbedtls_mpi_mod_inv( &x, &a, &N ) ); + if( expected_ret == 0 ) + { + TEST_COMPARE_MPI_RESIDUES( x, i ); + + /* a^-1: alias x to a => Correct result */ + memcpy( x.p, a.p, bytes ); + TEST_EQUAL( 0, mbedtls_mpi_mod_inv( &x, &x, &N ) ); + TEST_COMPARE_MPI_RESIDUES( x, i ); + } + +exit: + mbedtls_free( (void *)N.p ); /* mbedtls_mpi_mod_modulus_free() sets N.p = NULL */ + mbedtls_mpi_mod_modulus_free( &N ); + + mbedtls_free( a.p ); + mbedtls_free( i.p ); + mbedtls_free( X_raw ); +} +/* END_CASE */ + +/* BEGIN_CASE */ +void mpi_mod_inv_non_mont( char * input_N, + char * input_A, char * input_I, + int expected_ret ) +{ + mbedtls_mpi_mod_residue a = { NULL, 0 }; /* argument */ + mbedtls_mpi_mod_residue i = { NULL, 0 }; /* expected inverse wrt N */ + mbedtls_mpi_mod_residue x = { NULL, 0 }; /* output */ + mbedtls_mpi_uint *X_raw = NULL; + + mbedtls_mpi_mod_modulus N; + mbedtls_mpi_mod_modulus_init( &N ); + + TEST_EQUAL( 0, + test_read_modulus( &N, MBEDTLS_MPI_MOD_REP_OPT_RED, input_N ) ); + + /* test_read_residue() normally checks that inputs have the same number of + * limbs as the modulus. For negative testing we can ask it to skip this + * with a non-zero final parameter. */ + TEST_EQUAL( 0, test_read_residue( &a, &N, input_A, expected_ret != 0 ) ); + TEST_EQUAL( 0, test_read_residue( &i, &N, input_I, expected_ret != 0 ) ); + + size_t limbs = N.limbs; + size_t bytes = limbs * sizeof( *X_raw ); + + ASSERT_ALLOC( X_raw, limbs ); + + TEST_EQUAL( 0, mbedtls_mpi_mod_residue_setup( &x, &N, X_raw, limbs ) ); + + TEST_EQUAL( expected_ret, mbedtls_mpi_mod_inv( &x, &a, &N ) ); + if( expected_ret == 0 ) + { + TEST_COMPARE_MPI_RESIDUES( x, i ); + + /* a^-1: alias x to a => Correct result */ + memcpy( x.p, a.p, bytes ); + TEST_EQUAL( 0, mbedtls_mpi_mod_inv( &x, &x, &N ) ); + TEST_COMPARE_MPI_RESIDUES( x, i ); + } + +exit: + mbedtls_free( (void *)N.p ); /* mbedtls_mpi_mod_modulus_free() sets N.p = NULL */ + mbedtls_mpi_mod_modulus_free( &N ); + + mbedtls_free( a.p ); + mbedtls_free( i.p ); + mbedtls_free( X_raw ); +} +/* END_CASE */ /* END MERGE SLOT 3 */ /* BEGIN MERGE SLOT 4 */ diff --git a/tests/suites/test_suite_bignum_mod.misc.data b/tests/suites/test_suite_bignum_mod.misc.data index 7b1c85fb0..6240e214b 100644 --- a/tests/suites/test_suite_bignum_mod.misc.data +++ b/tests/suites/test_suite_bignum_mod.misc.data @@ -38,6 +38,50 @@ mpi_mod_sub:"014320a022ccb75bdf470ddf25":"a99c71c7":"00033b2e3c9fd0803ce8000f93" mpi_mod_sub with second input too short mpi_mod_sub:"014320a022ccb75bdf470ddf25":"000000025a55a46e5da99c71c7":"e8000f93":"00":MBEDTLS_ERR_MPI_BAD_INPUT_DATA +mbedtls_mpi_mod_inv non-Mont. form - base case for negative testing (N, A, A^-1) +mpi_mod_inv_non_mont:"000000000000152d02c7e14af67fe0bf":"00000000000000000000000000000038":"000000000000097418193b6f2e0b5fc3":0 + +mbedtls_mpi_mod_inv non-Mont. form - A == 0 +mpi_mod_inv_non_mont:"000000000000152d02c7e14af67fe0bf":"00000000000000000000000000000000":"00":MBEDTLS_ERR_MPI_BAD_INPUT_DATA + +mbedtls_mpi_mod_inv non-Mont. form - A too long +mpi_mod_inv_non_mont:"000000000000152d02c7e14af67fe0bf":"0000000000000000000000000000000000000038":"00":MBEDTLS_ERR_MPI_BAD_INPUT_DATA + +mbedtls_mpi_mod_inv non-Mont. form - A too short +mpi_mod_inv_non_mont:"000000000000152d02c7e14af67fe0bf":"0000000000000038":"000000000000097418193b6f2e0b5fc3":MBEDTLS_ERR_MPI_BAD_INPUT_DATA + +mbedtls_mpi_mod_inv 32-bit Mont. form - base case for negative testing, A = 1 (N, mont(A), mont(A^-1)) +depends_on:MBEDTLS_HAVE_INT32 +mpi_mod_inv_mont:"000000000000152d02c7e14af67fe0bf":"0000000000000d71d51539b9c02b7b28":"0000000000000d71d51539b9c02b7b28":0 + +mbedtls_mpi_mod_inv 32-bit Mont. form - A == 0 +depends_on:MBEDTLS_HAVE_INT32 +mpi_mod_inv_mont:"000000000000152d02c7e14af67fe0bf":"00000000000000000000000000000000":"00":MBEDTLS_ERR_MPI_BAD_INPUT_DATA + +mbedtls_mpi_mod_inv 32-bit Mont. form - A too long +depends_on:MBEDTLS_HAVE_INT32 +mpi_mod_inv_mont:"000000000000152d02c7e14af67fe0bf":"000000000000000000000d71d51539b9c02b7b28":"00":MBEDTLS_ERR_MPI_BAD_INPUT_DATA + +mbedtls_mpi_mod_inv 32-bit Mont. form - A too short +depends_on:MBEDTLS_HAVE_INT32 +mpi_mod_inv_mont:"000000000000152d02c7e14af67fe0bf":"00000d71d51539b9c02b7b28":"0000000000000d71d51539b9c02b7b28":MBEDTLS_ERR_MPI_BAD_INPUT_DATA + +mbedtls_mpi_mod_inv 64-bit Mont. form - base case for negative testing, A = 1 (N, mont(A), mont(A^-1)) +depends_on:MBEDTLS_HAVE_INT64 +mpi_mod_inv_mont:"0000000000000000000000000000152d02c7e14af67fe0bf":"000000000000000000000000000009545642424381c611fb":"000000000000000000000000000009545642424381c611fb":0 + +mbedtls_mpi_mod_inv 64-bit Mont. form - A == 0 +depends_on:MBEDTLS_HAVE_INT64 +mpi_mod_inv_mont:"0000000000000000000000000000152d02c7e14af67fe0bf":"000000000000000000000000000000000000000000000000":"000000000000000000000000000009545642424381c611fb":MBEDTLS_ERR_MPI_BAD_INPUT_DATA + +mbedtls_mpi_mod_inv 64-bit Mont. form - A too long +depends_on:MBEDTLS_HAVE_INT64 +mpi_mod_inv_mont:"0000000000000000000000000000152d02c7e14af67fe0bf":"0000000000000000000000000000000000000000000009545642424381c611fb":"000000000000000000000000000009545642424381c611fb":MBEDTLS_ERR_MPI_BAD_INPUT_DATA + +mbedtls_mpi_mod_inv 64-bit Mont. form - A too short +depends_on:MBEDTLS_HAVE_INT64 +mpi_mod_inv_mont:"0000000000000000000000000000152d02c7e14af67fe0bf":"00000000000009545642424381c611fb":"000000000000000000000000000009545642424381c611fb":MBEDTLS_ERR_MPI_BAD_INPUT_DATA + # END MERGE SLOT 3 # BEGIN MERGE SLOT 4 From 1133d2325b9bd3a00fcdbf647de27991562ae35c Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Fri, 16 Dec 2022 03:53:17 +0000 Subject: [PATCH 11/13] Attempt to pacify pylint in bignum tests Signed-off-by: Tom Cosgrove --- scripts/mbedtls_dev/bignum_common.py | 17 +++++++++++++++++ scripts/mbedtls_dev/bignum_core.py | 10 +--------- scripts/mbedtls_dev/bignum_mod.py | 24 +++++------------------- scripts/mbedtls_dev/bignum_mod_raw.py | 16 +++------------- 4 files changed, 26 insertions(+), 41 deletions(-) diff --git a/scripts/mbedtls_dev/bignum_common.py b/scripts/mbedtls_dev/bignum_common.py index 0339b1ad1..dd4fc3684 100644 --- a/scripts/mbedtls_dev/bignum_common.py +++ b/scripts/mbedtls_dev/bignum_common.py @@ -39,6 +39,11 @@ def invmod(a: int, n: int) -> int: return b raise ValueError("Not invertible") +def invmod_positive(a: int, n: int) -> int: + """Return a non-negative inverse of a to modulo n.""" + inv = invmod(a, n) + return inv if inv >= 0 else inv + n + def hex_to_int(val: str) -> int: """Implement the syntax accepted by mbedtls_test_read_mpi(). @@ -244,6 +249,8 @@ class ModOperationCommon(OperationCommon): #pylint: disable=abstract-method """Target for bignum mod_raw test case generation.""" moduli = MODULI_DEFAULT # type: List[str] + mongtomgery_form_a = False + disallow_zero_a = False def __init__(self, val_n: str, val_a: str, val_b: str = "0", bits_in_limb: int = 64) -> None: @@ -263,6 +270,14 @@ class ModOperationCommon(OperationCommon): def boundary(self) -> int: return self.int_n + @property + def arg_a(self) -> str: + if self.mongtomgery_form_a: + value_a = self.to_montgomery(self.int_a) + else: + value_a = self.int_a + return self.format_arg('{:x}'.format(value_a)) + @property def arg_n(self) -> str: return self.format_arg(self.val_n) @@ -287,6 +302,8 @@ class ModOperationCommon(OperationCommon): def is_valid(self) -> bool: if self.int_a >= self.int_n: return False + if self.disallow_zero_a and self.int_a == 0: + return False if self.arity == 2 and self.int_b >= self.int_n: return False return True diff --git a/scripts/mbedtls_dev/bignum_core.py b/scripts/mbedtls_dev/bignum_core.py index 1a8c22bfa..3bd7f111c 100644 --- a/scripts/mbedtls_dev/bignum_core.py +++ b/scripts/mbedtls_dev/bignum_core.py @@ -757,15 +757,7 @@ class BignumCoreExpMod(BignumCoreTarget, bignum_common.ModOperationCommon): test_function = "mpi_core_exp_mod" test_name = "Core modular exponentiation (Mongtomery form only)" input_style = "fixed" - - def arguments(self) -> List[str]: - # Input 'a' has to be given in Montgomery form - mont_a = self.to_montgomery(self.int_a) - arg_mont_a = self.format_arg('{:x}'.format(mont_a)) - return [bignum_common.quote_str(n) for n in [self.arg_n, - arg_mont_a, - self.arg_b] - ] + self.result() + mongtomgery_form_a = True def result(self) -> List[str]: # Result has to be given in Montgomery form too diff --git a/scripts/mbedtls_dev/bignum_mod.py b/scripts/mbedtls_dev/bignum_mod.py index 9f98131bd..642887354 100644 --- a/scripts/mbedtls_dev/bignum_mod.py +++ b/scripts/mbedtls_dev/bignum_mod.py @@ -58,15 +58,10 @@ class BignumModInvNonMont(bignum_common.ModOperationCommon, BignumModTarget): input_style = "fixed" arity = 1 suffix = True - - @property - def is_valid(self) -> bool: - return self.int_a > 0 and self.int_a < self.int_n + disallow_zero_a = True def result(self) -> List[str]: - result = bignum_common.invmod(self.int_a, self.int_n) - if result < 0: - result += self.int_n + result = bignum_common.invmod_positive(self.int_a, self.int_n) # To make negative tests easier, append 0 for success to the # generated cases return [self.format_result(result), "0"] @@ -80,20 +75,11 @@ class BignumModInvMont(bignum_common.ModOperationCommon, BignumModTarget): input_style = "arch_split" # Mont. form requires arch_split arity = 1 suffix = True - - @property - def is_valid(self) -> bool: - return self.int_a > 0 and self.int_a < self.int_n - - @property - def arg_a(self) -> str: - mont_a = self.to_montgomery(self.int_a) - return self.format_arg('{:x}'.format(mont_a)) + disallow_zero_a = True + mongtomgery_form_a = True def result(self) -> List[str]: - result = bignum_common.invmod(self.int_a, self.int_n) - if result < 0: - result += self.int_n + result = bignum_common.invmod_positive(self.int_a, self.int_n) mont_result = self.to_montgomery(result) # To make negative tests easier, append 0 for success to the # generated cases diff --git a/scripts/mbedtls_dev/bignum_mod_raw.py b/scripts/mbedtls_dev/bignum_mod_raw.py index 0084898be..461b1f2b9 100644 --- a/scripts/mbedtls_dev/bignum_mod_raw.py +++ b/scripts/mbedtls_dev/bignum_mod_raw.py @@ -64,21 +64,11 @@ class BignumModRawInvPrime(bignum_common.ModOperationCommon, input_style = "arch_split" arity = 1 suffix = True - - @property - def is_valid(self) -> bool: - return self.int_a > 0 and self.int_a < self.int_n - - @property - def arg_a(self) -> str: - # Input has to be given in Montgomery form - mont_a = self.to_montgomery(self.int_a) - return self.format_arg('{:x}'.format(mont_a)) + mongtomgery_form_a = True + disallow_zero_a = True def result(self) -> List[str]: - result = bignum_common.invmod(self.int_a, self.int_n) - if result < 0: - result += self.int_n + result = bignum_common.invmod_positive(self.int_a, self.int_n) mont_result = self.to_montgomery(result) return [self.format_result(mont_result)] From 342d00bc220a9aea38563f6ce58be76a844a7995 Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Fri, 16 Dec 2022 11:02:06 +0000 Subject: [PATCH 12/13] Oops, use mbedtls_free() not plain free() Signed-off-by: Tom Cosgrove --- library/bignum_mod.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/bignum_mod.c b/library/bignum_mod.c index 7c89b57d7..31e18e741 100644 --- a/library/bignum_mod.c +++ b/library/bignum_mod.c @@ -276,7 +276,7 @@ int mbedtls_mpi_mod_inv( mbedtls_mpi_mod_residue *X, mbedtls_platform_zeroize( working_memory, working_limbs * sizeof(mbedtls_mpi_uint) ); - free( working_memory ); + mbedtls_free( working_memory ); return ret; } From f723754f6db2014c738ded5b80ab00dca4634178 Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Fri, 16 Dec 2022 16:10:36 +0000 Subject: [PATCH 13/13] Fix typos Signed-off-by: Tom Cosgrove --- library/bignum_core.h | 4 ++-- scripts/mbedtls_dev/bignum_common.py | 4 ++-- scripts/mbedtls_dev/bignum_core.py | 2 +- scripts/mbedtls_dev/bignum_mod.py | 2 +- scripts/mbedtls_dev/bignum_mod_raw.py | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/library/bignum_core.h b/library/bignum_core.h index b079850d9..d9e16ee3b 100644 --- a/library/bignum_core.h +++ b/library/bignum_core.h @@ -623,7 +623,7 @@ static inline size_t mbedtls_mpi_core_montmul_working_limbs( size_t AN_limbs ) * \param[in] A The MPI to convert into Montgomery form. * Must have the same number of limbs as the modulus. * \param[in] N The address of the modulus, which gives the size of - * the base `R` = 2^(biL*m->limbs). + * the base `R` = 2^(biL*N->limbs). * \param[in] AN_limbs The number of limbs in \p X, \p A, \p N and \p rr. * \param mm The Montgomery constant for \p N: -N^-1 mod 2^biL. * This can be determined by calling @@ -661,7 +661,7 @@ void mbedtls_mpi_core_to_mont_rep( mbedtls_mpi_uint *X, * \param[in] A The MPI to convert from Montgomery form. * Must have the same number of limbs as the modulus. * \param[in] N The address of the modulus, which gives the size of - * the base `R` = 2^(biL*m->limbs). + * the base `R` = 2^(biL*N->limbs). * \param[in] AN_limbs The number of limbs in \p X, \p A and \p N. * \param mm The Montgomery constant for \p N: -N^-1 mod 2^biL. * This can be determined by calling diff --git a/scripts/mbedtls_dev/bignum_common.py b/scripts/mbedtls_dev/bignum_common.py index dd4fc3684..c4efabfcc 100644 --- a/scripts/mbedtls_dev/bignum_common.py +++ b/scripts/mbedtls_dev/bignum_common.py @@ -249,7 +249,7 @@ class ModOperationCommon(OperationCommon): #pylint: disable=abstract-method """Target for bignum mod_raw test case generation.""" moduli = MODULI_DEFAULT # type: List[str] - mongtomgery_form_a = False + montgomery_form_a = False disallow_zero_a = False def __init__(self, val_n: str, val_a: str, val_b: str = "0", @@ -272,7 +272,7 @@ class ModOperationCommon(OperationCommon): @property def arg_a(self) -> str: - if self.mongtomgery_form_a: + if self.montgomery_form_a: value_a = self.to_montgomery(self.int_a) else: value_a = self.int_a diff --git a/scripts/mbedtls_dev/bignum_core.py b/scripts/mbedtls_dev/bignum_core.py index 3bd7f111c..24d37cbc7 100644 --- a/scripts/mbedtls_dev/bignum_core.py +++ b/scripts/mbedtls_dev/bignum_core.py @@ -757,7 +757,7 @@ class BignumCoreExpMod(BignumCoreTarget, bignum_common.ModOperationCommon): test_function = "mpi_core_exp_mod" test_name = "Core modular exponentiation (Mongtomery form only)" input_style = "fixed" - mongtomgery_form_a = True + montgomery_form_a = True def result(self) -> List[str]: # Result has to be given in Montgomery form too diff --git a/scripts/mbedtls_dev/bignum_mod.py b/scripts/mbedtls_dev/bignum_mod.py index 642887354..25afe3053 100644 --- a/scripts/mbedtls_dev/bignum_mod.py +++ b/scripts/mbedtls_dev/bignum_mod.py @@ -76,7 +76,7 @@ class BignumModInvMont(bignum_common.ModOperationCommon, BignumModTarget): arity = 1 suffix = True disallow_zero_a = True - mongtomgery_form_a = True + montgomery_form_a = True def result(self) -> List[str]: result = bignum_common.invmod_positive(self.int_a, self.int_n) diff --git a/scripts/mbedtls_dev/bignum_mod_raw.py b/scripts/mbedtls_dev/bignum_mod_raw.py index 461b1f2b9..ae855e829 100644 --- a/scripts/mbedtls_dev/bignum_mod_raw.py +++ b/scripts/mbedtls_dev/bignum_mod_raw.py @@ -64,7 +64,7 @@ class BignumModRawInvPrime(bignum_common.ModOperationCommon, input_style = "arch_split" arity = 1 suffix = True - mongtomgery_form_a = True + montgomery_form_a = True disallow_zero_a = True def result(self) -> List[str]: