From fa98a26f68c6cb27a3feea0b10475e7ff2ade74a Mon Sep 17 00:00:00 2001 From: Daiki Ueno Date: Tue, 30 Mar 2021 09:22:47 +0200 Subject: [PATCH] Port upstream hardening of EC scaler multiplication Some internal functions used in point multiplications are known to misbehave if the scaler is out-of-range. This performs canonical reduction on scalers, before point multiplication. Signed-off-by: Daiki Ueno --- ecc-ecdsa-sign.c | 5 +++-- ecc-ecdsa-verify.c | 14 ++++++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/ecc-ecdsa-sign.c b/ecc-ecdsa-sign.c index cdf37746..acfb2a2e 100644 --- a/ecc-ecdsa-sign.c +++ b/ecc-ecdsa-sign.c @@ -88,8 +88,9 @@ ecc_ecdsa_sign (const struct ecc_curve *ecc, ecc_modq_mul (ecc, tp, zp, rp); ecc_modq_add (ecc, hp, hp, tp); ecc_modq_mul (ecc, tp, hp, kinv); - - mpn_copyi (sp, tp, ecc->size); + /* Ensure canonical reduction. */ + cy = mpn_sub_n (sp, tp, ecc->q, ecc->size); + cnd_copy (cy, sp, tp, ecc->size); #undef P #undef hp #undef kinv diff --git a/ecc-ecdsa-verify.c b/ecc-ecdsa-verify.c index f24eff37..5015271c 100644 --- a/ecc-ecdsa-verify.c +++ b/ecc-ecdsa-verify.c @@ -66,6 +66,8 @@ ecc_ecdsa_verify (const struct ecc_curve *ecc, const mp_limb_t *rp, const mp_limb_t *sp, mp_limb_t *scratch) { + mp_limb_t cy; + /* Procedure, according to RFC 6090, "KT-I". q denotes the group order. @@ -88,6 +90,7 @@ ecc_ecdsa_verify (const struct ecc_curve *ecc, #define u2 (scratch + 4*ecc->size) #define hp (scratch + 4*ecc->size) #define u1 (scratch + 6*ecc->size) +#define tp (scratch + 7*ecc->size) if (! (ecdsa_in_range (ecc, rp) && ecdsa_in_range (ecc, sp))) @@ -102,14 +105,20 @@ ecc_ecdsa_verify (const struct ecc_curve *ecc, ecc_modq_inv (ecc, sinv, sinv + ecc->size, P2); /* u2 = r / s, P2 = u2 * Y */ - ecc_modq_mul (ecc, u2, rp, sinv); + ecc_modq_mul (ecc, tp, rp, sinv); + /* Ensure canonical reduction. */ + cy = mpn_sub_n (u2, tp, ecc->q, ecc->size); + cnd_copy (cy, u2, tp, ecc->size); /* Total storage: 5*ecc->size + ECC_MUL_A_ITCH (ecc->size) */ ecc_mul_a (ecc, 1, P2, u2, pp, u2 + ecc->size); /* u1 = h / s, P1 = u1 * G */ ecc_hash (ecc, hp, length, digest); - ecc_modq_mul (ecc, u1, hp, sinv); + ecc_modq_mul (ecc, tp, hp, sinv); + /* Ensure canonical reduction. */ + cy = mpn_sub_n (u1, tp, ecc->q, ecc->size); + cnd_copy (cy, u1, tp, ecc->size); /* u = 0 can happen only if h = 0 or h = q, which is extremely unlikely. */ @@ -147,4 +156,5 @@ ecc_ecdsa_verify (const struct ecc_curve *ecc, #undef u2 #undef hp #undef u1 +#undef tp } -- 2.30.2