diff options
author | Samuel Weiser <samuel.weiser@iaik.tugraz.at> | 2017-12-05 15:55:17 +0100 |
---|---|---|
committer | Matt Caswell <matt@openssl.org> | 2018-03-21 17:36:40 +0000 |
commit | 9db724cfede4ba7a3668bff533973ee70145ec07 (patch) | |
tree | d097f67e8958d1ed6a8e233386f26579f1185ef4 | |
parent | 178a2a6f1c25d05d801544e6f18963726d90ac0b (diff) |
Replaced variable-time GCD with consttime inversion to avoid side-channel attacks on RSA key generation
Reviewed-by: Rich Salz <rsalz@openssl.org>
Reviewed-by: Kurt Roeckx <kurt@roeckx.be>
Reviewed-by: Matt Caswell <matt@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/5170)
-rw-r--r-- | crypto/rsa/rsa_gen.c | 30 |
1 files changed, 24 insertions, 6 deletions
diff --git a/crypto/rsa/rsa_gen.c b/crypto/rsa/rsa_gen.c index 4ced965519..a287ed7385 100644 --- a/crypto/rsa/rsa_gen.c +++ b/crypto/rsa/rsa_gen.c @@ -42,6 +42,7 @@ static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp; int bitsp, bitsq, ok = -1, n = 0; BN_CTX *ctx = NULL; + unsigned long error = 0; /* * When generating ridiculously small keys, we can get stuck @@ -88,16 +89,25 @@ static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, if (BN_copy(rsa->e, e_value) == NULL) goto err; + BN_set_flags(rsa->e, BN_FLG_CONSTTIME); /* generate p and q */ for (;;) { if (!BN_generate_prime_ex(rsa->p, bitsp, 0, NULL, NULL, cb)) goto err; if (!BN_sub(r2, rsa->p, BN_value_one())) goto err; - if (!BN_gcd(r1, r2, rsa->e, ctx)) - goto err; - if (BN_is_one(r1)) + if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { + /* GCD == 1 since inverse exists */ break; + } + error = ERR_peek_last_error(); + if (ERR_GET_LIB(error) == ERR_LIB_BN + && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { + /* GCD != 1 */ + ERR_clear_error(); + } else { + goto err; + } if (!BN_GENCB_call(cb, 2, n++)) goto err; } @@ -110,10 +120,18 @@ static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, } while (BN_cmp(rsa->p, rsa->q) == 0); if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; - if (!BN_gcd(r1, r2, rsa->e, ctx)) - goto err; - if (BN_is_one(r1)) + if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { + /* GCD == 1 since inverse exists */ break; + } + error = ERR_peek_last_error(); + if (ERR_GET_LIB(error) == ERR_LIB_BN + && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { + /* GCD != 1 */ + ERR_clear_error(); + } else { + goto err; + } if (!BN_GENCB_call(cb, 2, n++)) goto err; } |