From 7d5226994bedd350f5edd370751f7ac89709650a Mon Sep 17 00:00:00 2001 From: tuxxy Date: Tue, 17 Apr 2018 23:30:38 -0600 Subject: [PATCH 1/2] Expose BIGNUM constant time operations This commit exposes the following functions: BN_set_flags BN_get_flags BN_MONT_CTX_new BN_MONT_CTX_set BN_MONT_CTX_free BN_mod_exp_mont BN_mod_exp_mont_consttime This commit also exposes the BN_FLG_CONSTTIME flag. --- src/_cffi_src/openssl/bignum.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/_cffi_src/openssl/bignum.py b/src/_cffi_src/openssl/bignum.py index 2c140c93eeb3..0f1f83c31c98 100644 --- a/src/_cffi_src/openssl/bignum.py +++ b/src/_cffi_src/openssl/bignum.py @@ -10,11 +10,17 @@ TYPES = """ typedef ... BN_CTX; +typedef ... BN_MONT_CTX; typedef ... BIGNUM; typedef int... BN_ULONG; """ FUNCTIONS = """ +#define BN_FLG_CONSTTIME ... + +void BN_set_flags(BIGNUM *, int); +int BN_get_flags(const BIGNUM *, int); + BIGNUM *BN_new(void); void BN_free(BIGNUM *); void BN_clear_free(BIGNUM *); @@ -29,6 +35,10 @@ BIGNUM *BN_CTX_get(BN_CTX *); void BN_CTX_end(BN_CTX *); +BN_MONT_CTX *BN_MONT_CTX_new(void); +int BN_MONT_CTX_set(BN_MONT_CTX *, BIGNUM *, BN_CTX *); +void BN_MONT_CTX_free(BN_MONT_CTX *); + BIGNUM *BN_copy(BIGNUM *, const BIGNUM *); BIGNUM *BN_dup(const BIGNUM *); @@ -63,6 +73,10 @@ int BN_exp(BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *); int BN_mod_exp(BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *); +int BN_mod_exp_mont(BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, + BN_CTX *, BN_MONT_CTX *); +int BN_mod_exp_mont_consttime(BIGNUM *, const BIGNUM *, const BIGNUM *, + const BIGNUM *, BN_CTX *, BN_MONT_CTX *); int BN_gcd(BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *); BIGNUM *BN_mod_inverse(BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *); From ccdc933edc0c4f1f6c848a9262e46d12766bd6e9 Mon Sep 17 00:00:00 2001 From: tuxxy Date: Tue, 17 Apr 2018 23:33:06 -0600 Subject: [PATCH 2/2] Add _tmp_bn_mont_ctx context manager --- src/cryptography/hazmat/backends/openssl/backend.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/cryptography/hazmat/backends/openssl/backend.py b/src/cryptography/hazmat/backends/openssl/backend.py index 85e13b57266f..d1982053d149 100644 --- a/src/cryptography/hazmat/backends/openssl/backend.py +++ b/src/cryptography/hazmat/backends/openssl/backend.py @@ -1461,6 +1461,17 @@ def _tmp_bn_ctx(self): finally: self._lib.BN_CTX_end(bn_ctx) + @contextmanager + def _tmp_bn_mont_ctx(self, modulus): + bn_mont_ctx = self._lib.BN_MONT_CTX_new() + self.openssl_assert(bn_mont_ctx != self._ffi.NULL) + bn_mont_ctx = self._ffi.gc(bn_mont_ctx, self._lib.BN_MONT_CTX_free) + + with self._tmp_bn_ctx() as bn_ctx: + res = self._lib.BN_MONT_CTX_set(bn_mont_ctx, modulus, bn_ctx) + self.openssl_assert(res == 1) + yield bn_mont_ctx + def _ec_key_determine_group_get_func(self, ctx): """ Given an EC_KEY determine the group and what function is required to