diff --git a/library/ecp_curves.c b/library/ecp_curves.c index db35e966cd..b07753a074 100644 --- a/library/ecp_curves.c +++ b/library/ecp_curves.c @@ -5533,7 +5533,6 @@ cleanup: * with R about 33 bits, used by the Koblitz curves. * * Write N as A0 + 2^224 A1, return A0 + R * A1. - * Actually do two passes, since R is big. */ #define P_KOBLITZ_R (8 / sizeof(mbedtls_mpi_uint)) // Limbs in R @@ -5571,7 +5570,11 @@ static inline int ecp_mod_koblitz(mbedtls_mpi_uint *X, mask = ((mbedtls_mpi_uint) 1 << shift) - 1; } - for (size_t pass = 0; pass < 2; pass++) { + /* Two passes are needed to reduce the value of `A0 + R * A1` and then + * we need an additional one to reduce the possible overflow during + * the addition. + */ + for (size_t pass = 0; pass < 3; pass++) { /* Copy A1 */ memcpy(A1, X + P_limbs - adjust, P_limbs * ciL); diff --git a/scripts/mbedtls_dev/ecp.py b/scripts/mbedtls_dev/ecp.py index 2dae703d86..5f0efcf1c3 100644 --- a/scripts/mbedtls_dev/ecp.py +++ b/scripts/mbedtls_dev/ecp.py @@ -518,6 +518,10 @@ class EcpP192K1Raw(bignum_common.ModOperationCommon, ("fffffffffffffffffffffffffffffffffffffffdffffdc6c" "0000000000000000000000000000000100002394013c7364"), + # Test case for overflow during addition + ("00000007ffff71b809e27dd832cfd5e04d9d2dbb9f8da217" + "0000000000000000000000000000000000000000520834f0"), + # First 8 number generated by random.getrandbits(384) - seed(2,2) ("cf1822ffbc6887782b491044d5e341245c6e433715ba2bdd" "177219d30e7a269fd95bafc8f2a4d27bdcf4bb99f4bea973"), @@ -582,6 +586,10 @@ class EcpP224K1Raw(bignum_common.ModOperationCommon, ("fffffffffffffffffffffffffffffffffffffffffffffffdffffcad8" "00000000000000000000000000000000000000010000352802c26590"), + # Test case for overflow during addition + ("0000007ffff2b68161180fd8cd92e1a109be158a19a99b1809db8032" + "0000000000000000000000000000000000000000000000000bf04f49"), + # First 8 number generated by random.getrandbits(448) - seed(2,2) ("da94e3e8ab73738fcf1822ffbc6887782b491044d5e341245c6e4337" "15ba2bdd177219d30e7a269fd95bafc8f2a4d27bdcf4bb99f4bea973"), @@ -647,6 +655,10 @@ class EcpP256K1Raw(bignum_common.ModOperationCommon, ("fffffffffffffffffffffffffffffffffffffffffffffffffffffffdfffff85c0" "00000000000000000000000000000000000000000000001000007a4000e9844"), + # Test case for overflow during addition + ("0000fffffc2f000e90a0c86a0a63234e5ba641f43a7e4aecc4040e67ec850562" + "00000000000000000000000000000000000000000000000000000000585674fd"), + # First 8 number generated by random.getrandbits(512) - seed(2,2) ("4067c3584ee207f8da94e3e8ab73738fcf1822ffbc6887782b491044d5e34124" "5c6e433715ba2bdd177219d30e7a269fd95bafc8f2a4d27bdcf4bb99f4bea973"),