diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/_cffi_src/build_openssl.py | 1 | ||||
-rw-r--r-- | src/_cffi_src/openssl/engine.py | 11 | ||||
-rw-r--r-- | src/_cffi_src/openssl/err.py | 1 | ||||
-rw-r--r-- | src/_cffi_src/openssl/osrandom_engine.py | 31 | ||||
-rw-r--r-- | src/_cffi_src/openssl/src/osrandom_engine.c | 167 | ||||
-rw-r--r-- | src/_cffi_src/openssl/src/osrandom_engine.h | 6 | ||||
-rw-r--r-- | src/cryptography/hazmat/backends/openssl/backend.py | 19 | ||||
-rw-r--r-- | src/cryptography/hazmat/backends/openssl/x509.py | 40 | ||||
-rw-r--r-- | src/cryptography/hazmat/bindings/openssl/binding.py | 49 | ||||
-rw-r--r-- | src/cryptography/hazmat/primitives/ciphers/base.py | 19 | ||||
-rw-r--r-- | src/cryptography/hazmat/primitives/ciphers/modes.py | 2 |
11 files changed, 122 insertions, 224 deletions
diff --git a/src/_cffi_src/build_openssl.py b/src/_cffi_src/build_openssl.py index 1ebadccb..dac3e4d8 100644 --- a/src/_cffi_src/build_openssl.py +++ b/src/_cffi_src/build_openssl.py @@ -78,7 +78,6 @@ ffi = build_ffi_for_binding( "nid", "objects", "opensslv", - "osrandom_engine", "pem", "pkcs7", "pkcs12", diff --git a/src/_cffi_src/openssl/engine.py b/src/_cffi_src/openssl/engine.py index 3ebfa6c1..5079fd69 100644 --- a/src/_cffi_src/openssl/engine.py +++ b/src/_cffi_src/openssl/engine.py @@ -17,9 +17,16 @@ typedef ... DSA_METHOD; typedef ... ECDH_METHOD; typedef ... ECDSA_METHOD; typedef ... DH_METHOD; -typedef ... RAND_METHOD; +typedef struct { + void (*seed)(const void *, int); + int (*bytes)(unsigned char *, int); + void (*cleanup)(); + void (*add)(const void *, int, double); + int (*pseudorand)(unsigned char *, int); + int (*status)(); +} RAND_METHOD; typedef ... STORE_METHOD; -typedef ... *ENGINE_GEN_INT_FUNC_PTR; +typedef int (*ENGINE_GEN_INT_FUNC_PTR)(ENGINE *); typedef ... *ENGINE_CTRL_FUNC_PTR; typedef ... *ENGINE_LOAD_KEY_PTR; typedef ... *ENGINE_CIPHERS_PTR; diff --git a/src/_cffi_src/openssl/err.py b/src/_cffi_src/openssl/err.py index 0ee19c9e..eebf19ba 100644 --- a/src/_cffi_src/openssl/err.py +++ b/src/_cffi_src/openssl/err.py @@ -251,6 +251,7 @@ unsigned long ERR_peek_error_line(const char **, int *); unsigned long ERR_peek_last_error_line(const char **, int *); unsigned long ERR_get_error_line_data(const char **, int *, const char **, int *); +void ERR_clear_error(void); unsigned long ERR_peek_error_line_data(const char **, int *, const char **, int *); unsigned long ERR_peek_last_error_line_data(const char **, diff --git a/src/_cffi_src/openssl/osrandom_engine.py b/src/_cffi_src/openssl/osrandom_engine.py deleted file mode 100644 index a8479b07..00000000 --- a/src/_cffi_src/openssl/osrandom_engine.py +++ /dev/null @@ -1,31 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import absolute_import, division, print_function - -import os - -with open(os.path.join( - os.path.dirname(__file__), "src/osrandom_engine.h" -)) as f: - INCLUDES = f.read() - -TYPES = """ -static const char *const Cryptography_osrandom_engine_name; -static const char *const Cryptography_osrandom_engine_id; -""" - -FUNCTIONS = """ -int Cryptography_add_osrandom_engine(void); -""" - -MACROS = """ -""" - -with open(os.path.join( - os.path.dirname(__file__), "src/osrandom_engine.c" -)) as f: - CUSTOMIZATIONS = f.read() - -CONDITIONAL_NAMES = {} diff --git a/src/_cffi_src/openssl/src/osrandom_engine.c b/src/_cffi_src/openssl/src/osrandom_engine.c deleted file mode 100644 index 27894712..00000000 --- a/src/_cffi_src/openssl/src/osrandom_engine.c +++ /dev/null @@ -1,167 +0,0 @@ -static const char *Cryptography_osrandom_engine_id = "osrandom"; -static const char *Cryptography_osrandom_engine_name = "osrandom_engine"; - -#if defined(_WIN32) -static HCRYPTPROV hCryptProv = 0; - -static int osrandom_init(ENGINE *e) { - if (hCryptProv > 0) { - return 1; - } - if (CryptAcquireContext(&hCryptProv, NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { - return 1; - } else { - return 0; - } -} - -static int osrandom_rand_bytes(unsigned char *buffer, int size) { - if (hCryptProv == 0) { - return 0; - } - - if (!CryptGenRandom(hCryptProv, (DWORD)size, buffer)) { - ERR_put_error( - ERR_LIB_RAND, 0, ERR_R_RAND_LIB, "osrandom_engine.py", 0 - ); - return 0; - } - return 1; -} - -static int osrandom_finish(ENGINE *e) { - if (CryptReleaseContext(hCryptProv, 0)) { - hCryptProv = 0; - return 1; - } else { - return 0; - } -} - -static int osrandom_rand_status(void) { - if (hCryptProv == 0) { - return 0; - } else { - return 1; - } -} -#else -static int urandom_fd = -1; - -static int osrandom_finish(ENGINE *e); - -static int osrandom_init(ENGINE *e) { - if (urandom_fd > -1) { - return 1; - } - urandom_fd = open("/dev/urandom", O_RDONLY); - if (urandom_fd > -1) { - int flags = fcntl(urandom_fd, F_GETFD); - if (flags == -1) { - osrandom_finish(e); - return 0; - } else if (fcntl(urandom_fd, F_SETFD, flags | FD_CLOEXEC) == -1) { - osrandom_finish(e); - return 0; - } - return 1; - } else { - return 0; - } -} - -static int osrandom_rand_bytes(unsigned char *buffer, int size) { - ssize_t n; - while (size > 0) { - do { - n = read(urandom_fd, buffer, (size_t)size); - } while (n < 0 && errno == EINTR); - if (n <= 0) { - ERR_put_error( - ERR_LIB_RAND, 0, ERR_R_RAND_LIB, "osrandom_engine.py", 0 - ); - return 0; - } - buffer += n; - size -= n; - } - return 1; -} - -static int osrandom_finish(ENGINE *e) { - int n; - do { - n = close(urandom_fd); - } while (n < 0 && errno == EINTR); - urandom_fd = -1; - if (n < 0) { - return 0; - } else { - return 1; - } -} - -static int osrandom_rand_status(void) { - if (urandom_fd == -1) { - return 0; - } else { - return 1; - } -} -#endif - -/* This replicates the behavior of the OpenSSL FIPS RNG, which returns a - -1 in the event that there is an error when calling RAND_pseudo_bytes. */ -static int osrandom_pseudo_rand_bytes(unsigned char *buffer, int size) { - int res = osrandom_rand_bytes(buffer, size); - if (res == 0) { - return -1; - } else { - return res; - } -} - -static RAND_METHOD osrandom_rand = { - NULL, - osrandom_rand_bytes, - NULL, - NULL, - osrandom_pseudo_rand_bytes, - osrandom_rand_status, -}; - -/* Returns 1 if successfully added, 2 if engine has previously been added, - and 0 for error. */ -int Cryptography_add_osrandom_engine(void) { - ENGINE *e; - e = ENGINE_by_id(Cryptography_osrandom_engine_id); - if (e != NULL) { - ENGINE_free(e); - return 2; - } else { - ERR_clear_error(); - } - - e = ENGINE_new(); - if (e == NULL) { - return 0; - } - if(!ENGINE_set_id(e, Cryptography_osrandom_engine_id) || - !ENGINE_set_name(e, Cryptography_osrandom_engine_name) || - !ENGINE_set_RAND(e, &osrandom_rand) || - !ENGINE_set_init_function(e, osrandom_init) || - !ENGINE_set_finish_function(e, osrandom_finish)) { - ENGINE_free(e); - return 0; - } - if (!ENGINE_add(e)) { - ENGINE_free(e); - return 0; - } - if (!ENGINE_free(e)) { - return 0; - } - - return 1; -} diff --git a/src/_cffi_src/openssl/src/osrandom_engine.h b/src/_cffi_src/openssl/src/osrandom_engine.h deleted file mode 100644 index 11a3159e..00000000 --- a/src/_cffi_src/openssl/src/osrandom_engine.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifdef _WIN32 -#include <Wincrypt.h> -#else -#include <fcntl.h> -#include <unistd.h> -#endif diff --git a/src/cryptography/hazmat/backends/openssl/backend.py b/src/cryptography/hazmat/backends/openssl/backend.py index 51f68899..f05b0515 100644 --- a/src/cryptography/hazmat/backends/openssl/backend.py +++ b/src/cryptography/hazmat/backends/openssl/backend.py @@ -217,7 +217,7 @@ class Backend(object): self.activate_builtin_random() # Fetches an engine by id and returns it. This creates a structural # reference. - e = self._lib.ENGINE_by_id(self._lib.Cryptography_osrandom_engine_id) + e = self._lib.ENGINE_by_id(self._binding._osrandom_engine_id) assert e != self._ffi.NULL # Initialize the engine for use. This adds a functional reference. res = self._lib.ENGINE_init(e) @@ -872,25 +872,20 @@ class Backend(object): ) for extension in builder._extensions: if isinstance(extension.value, x509.BasicConstraints): - pp, r = _encode_basic_constraints( - self, extension.value, - ) + pp, r = _encode_basic_constraints(self, extension.value) elif isinstance(extension.value, x509.SubjectAlternativeName): - pp, r = _encode_subject_alt_name( - self, extension.value, - ) + pp, r = _encode_subject_alt_name(self, extension.value) else: raise NotImplementedError('Extension not yet supported.') obj = _txt2obj(self, extension.oid.dotted_string) - extension = backend._lib.X509_EXTENSION_create_by_OBJ( - backend._ffi.NULL, + extension = self._lib.X509_EXTENSION_create_by_OBJ( + self._ffi.NULL, obj, 1 if extension.critical else 0, - _encode_asn1_str(backend, pp[0], r) + _encode_asn1_str(self, pp[0], r), ) - assert extension != backend._ffi.NULL - + assert extension != self._ffi.NULL res = self._lib.sk_X509_EXTENSION_push(extensions, extension) assert res == 1 res = self._lib.X509_REQ_add_extensions(x509_req, extensions) diff --git a/src/cryptography/hazmat/backends/openssl/x509.py b/src/cryptography/hazmat/backends/openssl/x509.py index 804bce66..80e5f2b1 100644 --- a/src/cryptography/hazmat/backends/openssl/x509.py +++ b/src/cryptography/hazmat/backends/openssl/x509.py @@ -86,13 +86,17 @@ def _decode_general_name(backend, gn): # This is a wildcard name. We need to remove the leading wildcard, # IDNA decode, then re-add the wildcard. Wildcard characters should # always be left-most (RFC 2595 section 2.4). - data = u"*." + idna.decode(data[2:]) + decoded = u"*." + idna.decode(data[2:]) else: # Not a wildcard, decode away. If the string has a * in it anywhere # invalid this will raise an InvalidCodePoint - data = idna.decode(data) + decoded = idna.decode(data) + if data.startswith(b"."): + # idna strips leading periods. Name constraints can have that + # so we need to re-add it. Sigh. + decoded = u"." + decoded - return x509.DNSName(data) + return x509.DNSName(decoded) elif gn.type == backend._lib.GEN_URI: data = backend._ffi.buffer( gn.d.uniformResourceIdentifier.data, @@ -537,6 +541,35 @@ def _decode_issuer_alt_name(backend, ext): ) +def _decode_name_constraints(backend, ext): + nc = backend._ffi.cast( + "NAME_CONSTRAINTS *", backend._lib.X509V3_EXT_d2i(ext) + ) + assert nc != backend._ffi.NULL + nc = backend._ffi.gc(nc, backend._lib.NAME_CONSTRAINTS_free) + permitted = _decode_general_subtrees(backend, nc.permittedSubtrees) + excluded = _decode_general_subtrees(backend, nc.excludedSubtrees) + return x509.NameConstraints( + permitted_subtrees=permitted, excluded_subtrees=excluded + ) + + +def _decode_general_subtrees(backend, stack_subtrees): + if stack_subtrees == backend._ffi.NULL: + return None + + num = backend._lib.sk_GENERAL_SUBTREE_num(stack_subtrees) + subtrees = [] + + for i in range(num): + obj = backend._lib.sk_GENERAL_SUBTREE_value(stack_subtrees, i) + assert obj != backend._ffi.NULL + name = _decode_general_name(backend, obj.base) + subtrees.append(name) + + return subtrees + + def _decode_extended_key_usage(backend, ext): sk = backend._ffi.cast( "Cryptography_STACK_OF_ASN1_OBJECT *", @@ -728,6 +761,7 @@ _CERTIFICATE_EXTENSION_PARSER = _X509ExtensionParser( x509.OID_OCSP_NO_CHECK: _decode_ocsp_no_check, x509.OID_INHIBIT_ANY_POLICY: _decode_inhibit_any_policy, x509.OID_ISSUER_ALTERNATIVE_NAME: _decode_issuer_alt_name, + x509.OID_NAME_CONSTRAINTS: _decode_name_constraints, } ) diff --git a/src/cryptography/hazmat/bindings/openssl/binding.py b/src/cryptography/hazmat/bindings/openssl/binding.py index e0a83972..b7178bb2 100644 --- a/src/cryptography/hazmat/bindings/openssl/binding.py +++ b/src/cryptography/hazmat/bindings/openssl/binding.py @@ -4,11 +4,25 @@ from __future__ import absolute_import, division, print_function +import os import threading from cryptography.hazmat.bindings._openssl import ffi, lib +@ffi.callback("int (*)(unsigned char *, int)", error=-1) +def _osrandom_rand_bytes(buf, size): + signed = ffi.cast("char *", buf) + result = os.urandom(size) + signed[0:size] = result + return 1 + + +@ffi.callback("int (*)(void)") +def _osrandom_rand_status(): + return 1 + + class Binding(object): """ OpenSSL API wrapper. @@ -21,10 +35,42 @@ class Binding(object): _init_lock = threading.Lock() _lock_init_lock = threading.Lock() + _osrandom_engine_id = ffi.new("const char[]", b"osrandom") + _osrandom_engine_name = ffi.new("const char[]", b"osrandom_engine") + _osrandom_method = ffi.new( + "RAND_METHOD *", + dict(bytes=_osrandom_rand_bytes, pseudorand=_osrandom_rand_bytes, + status=_osrandom_rand_status) + ) + def __init__(self): self._ensure_ffi_initialized() @classmethod + def _register_osrandom_engine(cls): + assert cls.lib.ERR_peek_error() == 0 + looked_up_engine = cls.lib.ENGINE_by_id(cls._osrandom_engine_id) + if looked_up_engine != ffi.NULL: + raise RuntimeError("osrandom engine already registered") + + cls.lib.ERR_clear_error() + + engine = cls.lib.ENGINE_new() + assert engine != cls.ffi.NULL + try: + result = cls.lib.ENGINE_set_id(engine, cls._osrandom_engine_id) + assert result == 1 + result = cls.lib.ENGINE_set_name(engine, cls._osrandom_engine_name) + assert result == 1 + result = cls.lib.ENGINE_set_RAND(engine, cls._osrandom_method) + assert result == 1 + result = cls.lib.ENGINE_add(engine) + assert result == 1 + finally: + result = cls.lib.ENGINE_free(engine) + assert result == 1 + + @classmethod def _ensure_ffi_initialized(cls): if cls._lib_loaded: return @@ -32,8 +78,7 @@ class Binding(object): with cls._init_lock: if not cls._lib_loaded: cls._lib_loaded = True - res = cls.lib.Cryptography_add_osrandom_engine() - assert res != 0 + cls._register_osrandom_engine() @classmethod def init_static_locks(cls): diff --git a/src/cryptography/hazmat/primitives/ciphers/base.py b/src/cryptography/hazmat/primitives/ciphers/base.py index 8f3028fc..dae93655 100644 --- a/src/cryptography/hazmat/primitives/ciphers/base.py +++ b/src/cryptography/hazmat/primitives/ciphers/base.py @@ -149,6 +149,8 @@ class _CipherContext(object): class _AEADCipherContext(object): def __init__(self, ctx): self._ctx = ctx + self._bytes_processed = 0 + self._aad_bytes_processed = 0 self._tag = None self._updated = False @@ -156,6 +158,14 @@ class _AEADCipherContext(object): if self._ctx is None: raise AlreadyFinalized("Context was already finalized.") self._updated = True + self._bytes_processed += len(data) + if self._bytes_processed > self._ctx._mode._MAX_ENCRYPTED_BYTES: + raise ValueError( + "{0} has a maximum encrypted byte limit of {1}".format( + self._ctx._mode.name, self._ctx._mode._MAX_ENCRYPTED_BYTES + ) + ) + return self._ctx.update(data) def finalize(self): @@ -171,6 +181,15 @@ class _AEADCipherContext(object): raise AlreadyFinalized("Context was already finalized.") if self._updated: raise AlreadyUpdated("Update has been called on this context.") + + self._aad_bytes_processed += len(data) + if self._aad_bytes_processed > self._ctx._mode._MAX_AAD_BYTES: + raise ValueError( + "{0} has a maximum AAD byte limit of {0}".format( + self._ctx._mode.name, self._ctx._mode._MAX_AAD_BYTES + ) + ) + self._ctx.authenticate_additional_data(data) diff --git a/src/cryptography/hazmat/primitives/ciphers/modes.py b/src/cryptography/hazmat/primitives/ciphers/modes.py index e31c9060..4284042d 100644 --- a/src/cryptography/hazmat/primitives/ciphers/modes.py +++ b/src/cryptography/hazmat/primitives/ciphers/modes.py @@ -139,6 +139,8 @@ class CTR(object): @utils.register_interface(ModeWithAuthenticationTag) class GCM(object): name = "GCM" + _MAX_ENCRYPTED_BYTES = (2 ** 39 - 256) // 8 + _MAX_AAD_BYTES = (2 ** 64) // 8 def __init__(self, initialization_vector, tag=None, min_tag_length=16): # len(initialization_vector) must in [1, 2 ** 64), but it's impossible |