Python cryptography.exceptions.InternalError() Examples

The following are 17 code examples of cryptography.exceptions.InternalError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cryptography.exceptions , or try the search function .
Example #1
Source File: binding.py    From quickstart-git2s3 with Apache License 2.0 6 votes vote down vote up
def _openssl_assert(lib, ok):
    if not ok:
        errors = _consume_errors(lib)
        errors_with_text = []
        for err in errors:
            err_text_reason = ffi.string(
                lib.ERR_error_string(err.code, ffi.NULL)
            )
            errors_with_text.append(
                _OpenSSLErrorWithText(
                    err.code, err.lib, err.func, err.reason, err_text_reason
                )
            )

        raise InternalError(
            "Unknown OpenSSL error. This error is commonly encountered when "
            "another library is not cleaning up the OpenSSL error stack. If "
            "you are using cryptography with another library that uses "
            "OpenSSL try disabling it before reporting a bug. Otherwise "
            "please file an issue at https://github.com/pyca/cryptography/"
            "issues with information on how to reproduce "
            "this. ({0!r})".format(errors_with_text),
            errors_with_text
        ) 
Example #2
Source File: binding.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _openssl_assert(lib, ok):
    if not ok:
        errors = _consume_errors(lib)
        errors_with_text = []
        for err in errors:
            buf = ffi.new("char[]", 256)
            lib.ERR_error_string_n(err.code, buf, len(buf))
            err_text_reason = ffi.string(buf)

            errors_with_text.append(
                _OpenSSLErrorWithText(
                    err.code, err.lib, err.func, err.reason, err_text_reason
                )
            )

        raise InternalError(
            "Unknown OpenSSL error. This error is commonly encountered when "
            "another library is not cleaning up the OpenSSL error stack. If "
            "you are using cryptography with another library that uses "
            "OpenSSL try disabling it before reporting a bug. Otherwise "
            "please file an issue at https://github.com/pyca/cryptography/"
            "issues with information on how to reproduce "
            "this. ({0!r})".format(errors_with_text),
            errors_with_text
        ) 
Example #3
Source File: test_point_serializers.py    From pyUmbral with GNU General Public License v3.0 6 votes vote down vote up
def test_point_not_on_curve():
    """
    We want to be unable to create a Point that's not on the curve.

    When we try, we get cryptography.exceptions.InternalError - is that specifically because it isn't
    on the curve?  It seems to be reliably raised in the event of the Point being off the curve.

    The OpenSSL docs don't explicitly say that they raise an error for this reason:
    https://www.openssl.org/docs/man1.1.0/crypto/EC_GFp_simple_method.html
    """
    point_on_koblitz256_but_not_P256 = Point.from_bytes(b'\x03%\x98Dk\x88\xe2\x97\xab?\xabZ\xef\xd4' \
    b'\x9e\xaa\xc6\xb3\xa4\xa3\x89\xb2\xd7b.\x8f\x16Ci_&\xe0\x7f', curve=SECP256K1)

    from cryptography.exceptions import InternalError
    with pytest.raises(InternalError):
        Point.from_bytes(point_on_koblitz256_but_not_P256.to_bytes(), curve=SECP256R1) 
Example #4
Source File: test_point_serializers.py    From pyUmbral with GNU General Public License v3.0 6 votes vote down vote up
def test_bytes_serializers(point_bytes, nid, curve):
    point_with_curve = Point.from_bytes(point_bytes, curve=curve) # from curve
    assert isinstance(point_with_curve, Point)

    the_same_point_bytes = point_with_curve.to_bytes()
    assert point_bytes == the_same_point_bytes

    representations = (point_bytes, # Compressed representation
                       point_with_curve.to_bytes(is_compressed=False)) # Uncompressed

    for point_representation in representations:

        malformed_point_bytes = point_representation + b'0x'
        with pytest.raises(InternalError):
            _ = Point.from_bytes(malformed_point_bytes)

        malformed_point_bytes = point_representation[1:]
        with pytest.raises(InternalError):
            _ = Point.from_bytes(malformed_point_bytes)

        malformed_point_bytes = point_representation[:-1]
        with pytest.raises(InternalError):
            _ = Point.from_bytes(malformed_point_bytes) 
Example #5
Source File: binding.py    From quickstart-redhat-openshift with Apache License 2.0 6 votes vote down vote up
def _openssl_assert(lib, ok):
    if not ok:
        errors = _consume_errors(lib)
        errors_with_text = []
        for err in errors:
            buf = ffi.new("char[]", 256)
            lib.ERR_error_string_n(err.code, buf, len(buf))
            err_text_reason = ffi.string(buf)

            errors_with_text.append(
                _OpenSSLErrorWithText(
                    err.code, err.lib, err.func, err.reason, err_text_reason
                )
            )

        raise InternalError(
            "Unknown OpenSSL error. This error is commonly encountered when "
            "another library is not cleaning up the OpenSSL error stack. If "
            "you are using cryptography with another library that uses "
            "OpenSSL try disabling it before reporting a bug. Otherwise "
            "please file an issue at https://github.com/pyca/cryptography/"
            "issues with information on how to reproduce "
            "this. ({0!r})".format(errors_with_text),
            errors_with_text
        ) 
Example #6
Source File: binding.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _openssl_assert(lib, ok):
    if not ok:
        errors = _consume_errors(lib)
        errors_with_text = []
        for err in errors:
            buf = ffi.new("char[]", 256)
            lib.ERR_error_string_n(err.code, buf, len(buf))
            err_text_reason = ffi.string(buf)

            errors_with_text.append(
                _OpenSSLErrorWithText(
                    err.code, err.lib, err.func, err.reason, err_text_reason
                )
            )

        raise InternalError(
            "Unknown OpenSSL error. This error is commonly encountered when "
            "another library is not cleaning up the OpenSSL error stack. If "
            "you are using cryptography with another library that uses "
            "OpenSSL try disabling it before reporting a bug. Otherwise "
            "please file an issue at https://github.com/pyca/cryptography/"
            "issues with information on how to reproduce "
            "this. ({0!r})".format(errors_with_text),
            errors_with_text
        ) 
Example #7
Source File: binding.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _openssl_assert(lib, ok):
    if not ok:
        errors = _consume_errors(lib)
        errors_with_text = []
        for err in errors:
            buf = ffi.new("char[]", 256)
            lib.ERR_error_string_n(err.code, buf, len(buf))
            err_text_reason = ffi.string(buf)

            errors_with_text.append(
                _OpenSSLErrorWithText(
                    err.code, err.lib, err.func, err.reason, err_text_reason
                )
            )

        raise InternalError(
            "Unknown OpenSSL error. This error is commonly encountered when "
            "another library is not cleaning up the OpenSSL error stack. If "
            "you are using cryptography with another library that uses "
            "OpenSSL try disabling it before reporting a bug. Otherwise "
            "please file an issue at https://github.com/pyca/cryptography/"
            "issues with information on how to reproduce "
            "this. ({0!r})".format(errors_with_text),
            errors_with_text
        ) 
Example #8
Source File: binding.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _openssl_assert(lib, ok):
    if not ok:
        errors = _consume_errors(lib)
        errors_with_text = []
        for err in errors:
            buf = ffi.new("char[]", 256)
            lib.ERR_error_string_n(err.code, buf, len(buf))
            err_text_reason = ffi.string(buf)

            errors_with_text.append(
                _OpenSSLErrorWithText(
                    err.code, err.lib, err.func, err.reason, err_text_reason
                )
            )

        raise InternalError(
            "Unknown OpenSSL error. This error is commonly encountered when "
            "another library is not cleaning up the OpenSSL error stack. If "
            "you are using cryptography with another library that uses "
            "OpenSSL try disabling it before reporting a bug. Otherwise "
            "please file an issue at https://github.com/pyca/cryptography/"
            "issues with information on how to reproduce "
            "this. ({0!r})".format(errors_with_text),
            errors_with_text
        ) 
Example #9
Source File: binding.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _openssl_assert(lib, ok):
    if not ok:
        errors = _consume_errors(lib)
        errors_with_text = []
        for err in errors:
            buf = ffi.new("char[]", 256)
            lib.ERR_error_string_n(err.code, buf, len(buf))
            err_text_reason = ffi.string(buf)

            errors_with_text.append(
                _OpenSSLErrorWithText(
                    err.code, err.lib, err.func, err.reason, err_text_reason
                )
            )

        raise InternalError(
            "Unknown OpenSSL error. This error is commonly encountered when "
            "another library is not cleaning up the OpenSSL error stack. If "
            "you are using cryptography with another library that uses "
            "OpenSSL try disabling it before reporting a bug. Otherwise "
            "please file an issue at https://github.com/pyca/cryptography/"
            "issues with information on how to reproduce "
            "this. ({0!r})".format(errors_with_text),
            errors_with_text
        ) 
Example #10
Source File: backend.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _check_cipher_response(self, response):
        if response == self._lib.kCCSuccess:
            return
        elif response == self._lib.kCCAlignmentError:
            # This error is not currently triggered due to a bug filed as
            # rdar://15589470
            raise ValueError(
                "The length of the provided data is not a multiple of "
                "the block length."
            )
        else:
            raise InternalError(
                "The backend returned an unknown error, consider filing a bug."
                " Code: {0}.".format(response),
                response
            ) 
Example #11
Source File: binding.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _openssl_assert(lib, ok):
    if not ok:
        errors = _consume_errors(lib)
        errors_with_text = []
        for err in errors:
            err_text_reason = ffi.string(
                lib.ERR_error_string(err.code, ffi.NULL)
            )
            errors_with_text.append(
                _OpenSSLErrorWithText(
                    err.code, err.lib, err.func, err.reason, err_text_reason
                )
            )

        raise InternalError(
            "Unknown OpenSSL error. This error is commonly encountered when "
            "another library is not cleaning up the OpenSSL error stack. If "
            "you are using cryptography with another library that uses "
            "OpenSSL try disabling it before reporting a bug. Otherwise "
            "please file an issue at https://github.com/pyca/cryptography/"
            "issues with information on how to reproduce "
            "this. ({0!r})".format(errors_with_text),
            errors_with_text
        ) 
Example #12
Source File: backend.py    From oss-ftp with MIT License 6 votes vote down vote up
def _check_cipher_response(self, response):
        if response == self._lib.kCCSuccess:
            return
        elif response == self._lib.kCCAlignmentError:
            # This error is not currently triggered due to a bug filed as
            # rdar://15589470
            raise ValueError(
                "The length of the provided data is not a multiple of "
                "the block length."
            )
        else:
            raise InternalError(
                "The backend returned an unknown error, consider filing a bug."
                " Code: {0}.".format(response),
                response
            ) 
Example #13
Source File: binding.py    From oss-ftp with MIT License 5 votes vote down vote up
def _openssl_assert(lib, ok):
    if not ok:
        errors = _consume_errors(lib)
        raise InternalError(
            "Unknown OpenSSL error. Please file an issue at https://github.com"
            "/pyca/cryptography/issues with information on how to reproduce "
            "this. ({0!r})".format(errors),
            errors
        ) 
Example #14
Source File: decryptor.py    From mac_apt with MIT License 5 votes vote down vote up
def decrypt_keybag(self, wrapped_keybag, offset, key):
        """
        Decrypts the wrapped binary keybag that will be decrypted using the Container's UUID.
        Uses the setKey function as the cipher
        The UUID is set as both the first and second key in the cipher
        param: wrapped_keybag: The wrapped binary keybag that will be decrypted using the Container's UUID
        """

        cs_factor = self.block_size // 0x200
        uno = offset * cs_factor
        complete_plaintext = b""

        # Cipher is AES-XTS with the container UUID as the first and second key

        try:
            log.debug("Attempting to decrypt the keybag")
            k = 0
            size = len(wrapped_keybag)
            while k < size:
                tweak = struct.pack("<QQ", uno, 0)
                decryptor = Cipher(algorithms.AES(key + key), modes.XTS(tweak), backend=default_backend()).decryptor()
                complete_plaintext += decryptor.update(wrapped_keybag[k:k + 0x200]) + decryptor.finalize()
                uno += 1
                k += 0x200

            log.debug("Successfully decrypted the keybag")
            return complete_plaintext
        except InternalError as ex:
            log.exception("Could not decrypt the keybag.")
        return '' 
Example #15
Source File: keys.py    From pyUmbral with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self,
                 password: bytes,
                 salt: bytes,
                 **kwargs) -> bytes:
        """
        Derives a symmetric encryption key from a pair of password and salt.
        It also accepts an additional _scrypt_cost argument.
        WARNING: RFC7914 recommends that you use a 2^20 cost value for sensitive
        files. It is NOT recommended to change the `_scrypt_cost` value unless
        you know what you are doing.
        :param password: byte-encoded password used to derive a symmetric key
        :param salt: cryptographic salt added during key derivation
        :return:
        """

        _scrypt_cost = kwargs.get('_scrypt_cost', Scrypt.__DEFAULT_SCRYPT_COST)
        try:
            derived_key = CryptographyScrypt(
                salt=salt,
                length=SecretBox.KEY_SIZE,
                n=2 ** _scrypt_cost,
                r=8,
                p=1,
                backend=default_backend()
            ).derive(password)
        except InternalError as e:
            required_memory = 128 * 2**_scrypt_cost * 8 // (10**6)
            if e.err_code[0].reason == 65:
                raise MemoryError(
                    "Scrypt key derivation requires at least {} MB of memory. "
                    "Please free up some memory and try again.".format(required_memory)
                )
            else:
                raise e
        else:
            return derived_key 
Example #16
Source File: test_point_serializers.py    From pyUmbral with GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_points(random_ec_point2):

    point_bytes = bytearray(random_ec_point2.to_bytes(is_compressed=False))
    point_bytes[-1] = point_bytes[-1] ^ 0x01        # Flips last bit
    point_bytes = bytes(point_bytes)

    with pytest.raises(InternalError) as e:
        _point = Point.from_bytes(point_bytes)

    # We want to catch specific InternalExceptions:
    # - Point not in the curve (code 107)
    # - Invalid compressed point (code 110)
    # https://github.com/openssl/openssl/blob/master/include/openssl/ecerr.h#L228
    assert e.value.err_code[0].reason in (107, 110) 
Example #17
Source File: random_oracles.py    From pyUmbral with GNU General Public License v3.0 4 votes vote down vote up
def unsafe_hash_to_point(data: bytes = b'',
                         params: UmbralParameters = None,
                         label: bytes = b'',
                         hash_class = Blake2b,
                         ) -> 'Point':
    """
    Hashes arbitrary data into a valid EC point of the specified curve,
    using the try-and-increment method.
    It admits an optional label as an additional input to the hash function.
    It uses BLAKE2b (with a digest size of 64 bytes) as the internal hash function.

    WARNING: Do not use when the input data is secret, as this implementation is not
    in constant time, and hence, it is not safe with respect to timing attacks.
    """

    params = params if params is not None else default_params()

    len_data = len(data).to_bytes(4, byteorder='big')
    len_label = len(label).to_bytes(4, byteorder='big')

    label_data = len_label + label + len_data + data

    # We use an internal 32-bit counter as additional input
    i = 0
    while i < 2**32:
        ibytes = i.to_bytes(4, byteorder='big')
        hash_function = hash_class()
        hash_function.update(label_data + ibytes)
        hash_digest = hash_function.finalize()[:1 + params.CURVE_KEY_SIZE_BYTES]

        sign = b'\x02' if hash_digest[0] & 1 == 0 else b'\x03'
        compressed_point = sign + hash_digest[1:]

        try:
            return Point.from_bytes(compressed_point, params.curve)
        except InternalError as e:
            # We want to catch specific InternalExceptions:
            # - Point not in the curve (code 107)
            # - Invalid compressed point (code 110)
            # https://github.com/openssl/openssl/blob/master/include/openssl/ecerr.h#L228
            if e.err_code[0].reason in (107, 110):
                pass
            else:
                # Any other exception, we raise it
                raise e
        i += 1

    # Only happens with probability 2^(-32)
    raise ValueError('Could not hash input into the curve')