diff --git a/CHANGELOG.rst b/CHANGELOG.rst index d71e9c006b81..721a3892fd1f 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -51,6 +51,9 @@ Changelog * In the next release (43.0.0) of cryptography, loading an X.509 certificate with a negative serial number will raise an exception. This has been deprecated since 36.0.0. +* Added support for + :class:`~cryptography.hazmat.primitives.ciphers.aead.AESGCMSIV` when using + OpenSSL 3.2.0+. .. _v41-0-7: diff --git a/docs/hazmat/primitives/aead.rst b/docs/hazmat/primitives/aead.rst index db9ef96d1ab7..776f9b77271a 100644 --- a/docs/hazmat/primitives/aead.rst +++ b/docs/hazmat/primitives/aead.rst @@ -164,6 +164,79 @@ also support providing integrity for associated data which is not encrypted. when the ciphertext has been changed, but will also occur when the key, nonce, or associated data are wrong. +.. class:: AESGCMSIV(key) + + .. versionadded:: 42.0.0 + + The AES-GCM-SIV construction is defined in :rfc:`8452` and is composed of + the :class:`~cryptography.hazmat.primitives.ciphers.algorithms.AES` block + cipher utilizing Galois Counter Mode (GCM) and a synthetic initialization + vector (SIV). + + :param key: A 128, 192, or 256-bit key. This **must** be kept secret. + :type key: :term:`bytes-like` + + :raises cryptography.exceptions.UnsupportedAlgorithm: If the version of + OpenSSL does not support AES-GCM-SIV. + + .. doctest:: + + >>> import os + >>> from cryptography.hazmat.primitives.ciphers.aead import AESGCMSIV + >>> data = b"a secret message" + >>> aad = b"authenticated but unencrypted data" + >>> key = AESGCMSIV.generate_key(bit_length=128) + >>> aesgcmsiv = AESGCMSIV(key) + >>> nonce = os.urandom(12) + >>> ct = aesgcmsiv.encrypt(nonce, data, aad) + >>> aesgcmsiv.decrypt(nonce, ct, aad) + b'a secret message' + + .. classmethod:: generate_key(bit_length) + + Securely generates a random AES-GCM-SIV key. + + :param bit_length: The bit length of the key to generate. Must be + 128, 192, or 256. + + :returns bytes: The generated key. + + .. method:: encrypt(nonce, data, associated_data) + + Encrypts and authenticates the ``data`` provided as well as + authenticating the ``associated_data``. The output of this can be + passed directly to the ``decrypt`` method. + + :param nonce: A 12-byte value. + :type nonce: :term:`bytes-like` + :param data: The data to encrypt. + :type data: :term:`bytes-like` + :param associated_data: Additional data that should be + authenticated with the key, but is not encrypted. Can be ``None``. + :type associated_data: :term:`bytes-like` + :returns bytes: The ciphertext bytes with the 16 byte tag appended. + :raises OverflowError: If ``data`` or ``associated_data`` is larger + than 2\ :sup:`32` - 1 bytes. + + .. method:: decrypt(nonce, data, associated_data) + + Decrypts the ``data`` and authenticates the ``associated_data``. If you + called encrypt with ``associated_data`` you must pass the same + ``associated_data`` in decrypt or the integrity check will fail. + + :param nonce: A 12-byte value. + :type nonce: :term:`bytes-like` + :param data: The data to decrypt (with tag appended). + :type data: :term:`bytes-like` + :param associated_data: Additional data to authenticate. Can be + ``None`` if none was passed during encryption. + :type associated_data: :term:`bytes-like` + :returns bytes: The original plaintext. + :raises cryptography.exceptions.InvalidTag: If the authentication tag + doesn't validate this exception will be raised. This will occur + when the ciphertext has been changed, but will also occur when the + key, nonce, or associated data are wrong. + .. class:: AESOCB3(key) .. versionadded:: 36.0.0 diff --git a/src/cryptography/hazmat/bindings/_rust/openssl/aead.pyi b/src/cryptography/hazmat/bindings/_rust/openssl/aead.pyi index 981d69d13219..62f1d8772b0b 100644 --- a/src/cryptography/hazmat/bindings/_rust/openssl/aead.pyi +++ b/src/cryptography/hazmat/bindings/_rust/openssl/aead.pyi @@ -33,3 +33,20 @@ class AESOCB3: data: bytes, associated_data: bytes | None, ) -> bytes: ... + +class AESGCMSIV: + def __init__(self, key: bytes) -> None: ... + @staticmethod + def generate_key(key_size: int) -> bytes: ... + def encrypt( + self, + nonce: bytes, + data: bytes, + associated_data: bytes | None, + ) -> bytes: ... + def decrypt( + self, + nonce: bytes, + data: bytes, + associated_data: bytes | None, + ) -> bytes: ... diff --git a/src/cryptography/hazmat/primitives/ciphers/aead.py b/src/cryptography/hazmat/primitives/ciphers/aead.py index 291513d75f04..9752d786cea3 100644 --- a/src/cryptography/hazmat/primitives/ciphers/aead.py +++ b/src/cryptography/hazmat/primitives/ciphers/aead.py @@ -16,12 +16,14 @@ "ChaCha20Poly1305", "AESCCM", "AESGCM", + "AESGCMSIV", "AESOCB3", "AESSIV", ] AESSIV = rust_openssl.aead.AESSIV AESOCB3 = rust_openssl.aead.AESOCB3 +AESGCMSIV = rust_openssl.aead.AESGCMSIV class ChaCha20Poly1305: diff --git a/src/rust/build.rs b/src/rust/build.rs index 4587c9b1f6ea..f247822e0dcd 100644 --- a/src/rust/build.rs +++ b/src/rust/build.rs @@ -12,6 +12,9 @@ fn main() { if version >= 0x3_00_00_00_0 { println!("cargo:rustc-cfg=CRYPTOGRAPHY_OPENSSL_300_OR_GREATER"); } + if version >= 0x3_02_00_00_0 { + println!("cargo:rustc-cfg=CRYPTOGRAPHY_OPENSSL_320_OR_GREATER"); + } } if let Ok(version) = env::var("DEP_OPENSSL_LIBRESSL_VERSION_NUMBER") { diff --git a/src/rust/src/backend/aead.rs b/src/rust/src/backend/aead.rs index 7ae93ff06b11..ba14900d5f71 100644 --- a/src/rust/src/backend/aead.rs +++ b/src/rust/src/backend/aead.rs @@ -410,11 +410,121 @@ impl AesOcb3 { } } +#[pyo3::prelude::pyclass( + frozen, + module = "cryptography.hazmat.bindings._rust.openssl.aead", + name = "AESGCMSIV" +)] +struct AesGcmSiv { + ctx: EvpCipherAead, +} + +#[pyo3::prelude::pymethods] +impl AesGcmSiv { + #[new] + fn new(py: pyo3::Python<'_>, key: pyo3::Py) -> CryptographyResult { + let key_buf = key.extract::>(py)?; + let cipher_name = match key_buf.as_bytes().len() { + 16 => "aes-128-gcm-siv", + 24 => "aes-192-gcm-siv", + 32 => "aes-256-gcm-siv", + _ => { + return Err(CryptographyError::from( + pyo3::exceptions::PyValueError::new_err( + "AES-GCM-SIV key must be 128, 192 or 256 bits.", + ), + )) + } + }; + + cfg_if::cfg_if! { + if #[cfg(not(CRYPTOGRAPHY_OPENSSL_320_OR_GREATER))] { + let _ = cipher_name; + Err(CryptographyError::from( + exceptions::UnsupportedAlgorithm::new_err(( + "AES-GCM-SIV is not supported by this version of OpenSSL", + exceptions::Reasons::UNSUPPORTED_CIPHER, + )), + )) + } else { + if cryptography_openssl::fips::is_enabled() { + return Err(CryptographyError::from( + exceptions::UnsupportedAlgorithm::new_err(( + "AES-GCM-SIV is not supported by this version of OpenSSL", + exceptions::Reasons::UNSUPPORTED_CIPHER, + )), + )); + } + let cipher = openssl::cipher::Cipher::fetch(None, cipher_name, None)?; + Ok(AesGcmSiv { + ctx: EvpCipherAead::new(&cipher, key_buf.as_bytes(), 16, false)?, + }) + } + } + } + + #[staticmethod] + fn generate_key(py: pyo3::Python<'_>, bit_length: usize) -> CryptographyResult<&pyo3::PyAny> { + if bit_length != 128 && bit_length != 192 && bit_length != 256 { + return Err(CryptographyError::from( + pyo3::exceptions::PyValueError::new_err("bit_length must be 128, 192, or 256"), + )); + } + + Ok(types::OS_URANDOM.get(py)?.call1((bit_length / 8,))?) + } + + #[pyo3(signature = (nonce, data, associated_data))] + fn encrypt<'p>( + &self, + py: pyo3::Python<'p>, + nonce: CffiBuf<'_>, + data: CffiBuf<'_>, + associated_data: Option>, + ) -> CryptographyResult<&'p pyo3::types::PyBytes> { + let nonce_bytes = nonce.as_bytes(); + let data_bytes = data.as_bytes(); + let aad = associated_data.map(Aad::Single); + + if data_bytes.is_empty() { + return Err(CryptographyError::from( + pyo3::exceptions::PyValueError::new_err("data must not be zero length"), + )); + }; + if nonce_bytes.len() != 12 { + return Err(CryptographyError::from( + pyo3::exceptions::PyValueError::new_err("Nonce must be 12 bytes long"), + )); + } + self.ctx.encrypt(py, data_bytes, aad, Some(nonce_bytes)) + } + + #[pyo3(signature = (nonce, data, associated_data))] + fn decrypt<'p>( + &self, + py: pyo3::Python<'p>, + nonce: CffiBuf<'_>, + data: CffiBuf<'_>, + associated_data: Option>, + ) -> CryptographyResult<&'p pyo3::types::PyBytes> { + let nonce_bytes = nonce.as_bytes(); + let aad = associated_data.map(Aad::Single); + if nonce_bytes.len() != 12 { + return Err(CryptographyError::from( + pyo3::exceptions::PyValueError::new_err("Nonce must be 12 bytes long"), + )); + } + self.ctx + .decrypt(py, data.as_bytes(), aad, Some(nonce_bytes)) + } +} + pub(crate) fn create_module(py: pyo3::Python<'_>) -> pyo3::PyResult<&pyo3::prelude::PyModule> { let m = pyo3::prelude::PyModule::new(py, "aead")?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; Ok(m) } diff --git a/tests/hazmat/primitives/test_aead.py b/tests/hazmat/primitives/test_aead.py index 57ddf1816ab6..a4624cefc555 100644 --- a/tests/hazmat/primitives/test_aead.py +++ b/tests/hazmat/primitives/test_aead.py @@ -14,6 +14,7 @@ from cryptography.hazmat.primitives.ciphers.aead import ( AESCCM, AESGCM, + AESGCMSIV, AESOCB3, AESSIV, ChaCha20Poly1305, @@ -830,3 +831,155 @@ def test_buffer_protocol(self, backend): assert ct2 == ct computed_pt2 = aessiv.decrypt(ct2, ad) assert computed_pt2 == pt + + +@pytest.mark.skipif( + not _aead_supported(AESGCMSIV), + reason="Does not support AESGCMSIV", +) +class TestAESGCMSIV: + @pytest.mark.skipif( + sys.platform not in {"linux", "darwin"}, reason="mmap required" + ) + def test_data_too_large(self): + key = AESGCMSIV.generate_key(256) + nonce = os.urandom(12) + aesgcmsiv = AESGCMSIV(key) + + large_data = large_mmap() + + with pytest.raises(OverflowError): + aesgcmsiv.encrypt(nonce, large_data, None) + + with pytest.raises(OverflowError): + aesgcmsiv.encrypt(nonce, b"irrelevant", large_data) + + with pytest.raises(OverflowError): + aesgcmsiv.decrypt(nonce, b"very very irrelevant", large_data) + + def test_invalid_nonce_length(self, backend): + key = AESGCMSIV.generate_key(128) + aesgcmsiv = AESGCMSIV(key) + pt = b"hello" + nonce = os.urandom(14) + with pytest.raises(ValueError): + aesgcmsiv.encrypt(nonce, pt, None) + + with pytest.raises(ValueError): + aesgcmsiv.decrypt(nonce, pt, None) + + def test_no_empty_encryption(self): + key = AESGCMSIV.generate_key(256) + aesgcmsiv = AESGCMSIV(key) + nonce = os.urandom(12) + + with pytest.raises(ValueError): + aesgcmsiv.encrypt(nonce, b"", None) + + with pytest.raises(InvalidTag): + aesgcmsiv.decrypt(nonce, b"", None) + + def test_vectors(self, backend, subtests): + vectors = _load_all_params( + os.path.join("ciphers", "AES", "GCM-SIV"), + [ + "openssl.txt", + "aes-192-gcm-siv.txt", + ], + load_nist_vectors, + ) + for vector in vectors: + with subtests.test(): + key = binascii.unhexlify(vector["key"]) + nonce = binascii.unhexlify(vector["iv"]) + aad = binascii.unhexlify(vector.get("aad", b"")) + ct = binascii.unhexlify(vector["ciphertext"]) + tag = binascii.unhexlify(vector["tag"]) + pt = binascii.unhexlify(vector.get("plaintext", b"")) + aesgcmsiv = AESGCMSIV(key) + computed_ct = aesgcmsiv.encrypt(nonce, pt, aad) + assert computed_ct[:-16] == ct + assert computed_ct[-16:] == tag + computed_pt = aesgcmsiv.decrypt(nonce, computed_ct, aad) + assert computed_pt == pt + + def test_vectors_invalid(self, backend, subtests): + vectors = _load_all_params( + os.path.join("ciphers", "AES", "GCM-SIV"), + [ + "openssl.txt", + "aes-192-gcm-siv.txt", + ], + load_nist_vectors, + ) + for vector in vectors: + with subtests.test(): + key = binascii.unhexlify(vector["key"]) + nonce = binascii.unhexlify(vector["iv"]) + aad = binascii.unhexlify(vector.get("aad", b"")) + ct = binascii.unhexlify(vector["ciphertext"]) + aesgcmsiv = AESGCMSIV(key) + with pytest.raises(InvalidTag): + badkey = AESGCMSIV(AESGCMSIV.generate_key(256)) + badkey.decrypt(nonce, ct, aad) + with pytest.raises(InvalidTag): + aesgcmsiv.decrypt(nonce, ct, b"nonsense") + with pytest.raises(InvalidTag): + aesgcmsiv.decrypt(nonce, b"nonsense", aad) + + @pytest.mark.parametrize( + ("nonce", "data", "associated_data"), + [ + [object(), b"data", b""], + [b"0" * 12, object(), b""], + [b"0" * 12, b"data", object()], + ], + ) + def test_params_not_bytes(self, nonce, data, associated_data, backend): + key = AESGCMSIV.generate_key(256) + aesgcmsiv = AESGCMSIV(key) + with pytest.raises(TypeError): + aesgcmsiv.encrypt(nonce, data, associated_data) + + with pytest.raises(TypeError): + aesgcmsiv.decrypt(nonce, data, associated_data) + + def test_bad_key(self, backend): + with pytest.raises(TypeError): + AESGCMSIV(object()) # type:ignore[arg-type] + + with pytest.raises(ValueError): + AESGCMSIV(b"0" * 31) + + def test_bad_generate_key(self, backend): + with pytest.raises(TypeError): + AESGCMSIV.generate_key(object()) # type:ignore[arg-type] + + with pytest.raises(ValueError): + AESGCMSIV.generate_key(129) + + def test_associated_data_none_equal_to_empty_bytestring(self, backend): + key = AESGCMSIV.generate_key(256) + aesgcmsiv = AESGCMSIV(key) + nonce = os.urandom(12) + ct1 = aesgcmsiv.encrypt(nonce, b"some_data", None) + ct2 = aesgcmsiv.encrypt(nonce, b"some_data", b"") + assert ct1 == ct2 + pt1 = aesgcmsiv.decrypt(nonce, ct1, None) + pt2 = aesgcmsiv.decrypt(nonce, ct2, b"") + assert pt1 == pt2 + + def test_buffer_protocol(self, backend): + key = AESGCMSIV.generate_key(256) + aesgcmsiv = AESGCMSIV(key) + nonce = os.urandom(12) + pt = b"encrypt me" + ad = b"additional" + ct = aesgcmsiv.encrypt(nonce, pt, ad) + computed_pt = aesgcmsiv.decrypt(nonce, ct, ad) + assert computed_pt == pt + aesgcmsiv = AESGCMSIV(bytearray(key)) + ct2 = aesgcmsiv.encrypt(nonce, pt, ad) + assert ct2 == ct + computed_pt2 = aesgcmsiv.decrypt(nonce, ct2, ad) + assert computed_pt2 == pt