Skip to content

Commit

Permalink
Add support for AES-GCM-SIV using OpenSSL>=3.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
facutuesca committed Nov 27, 2023
1 parent 7387983 commit b47723d
Show file tree
Hide file tree
Showing 10 changed files with 868 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,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-5:

Expand Down
2 changes: 2 additions & 0 deletions docs/development/test-vectors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,7 @@ Symmetric ciphers

* AES (CBC, CFB, ECB, GCM, OFB, CCM) from `NIST CAVP`_.
* AES CTR from :rfc:`3686`.
* AES-GCM-SIV from OpenSSL's `evpciph_aes_gcm_siv.txt`_.
* AES OCB3 from :rfc:`7253`, `dkg's additional OCB3 vectors`_, and `OpenSSL's OCB vectors`_.
* AES SIV from OpenSSL's `evpciph_aes_siv.txt`_.
* 3DES (CBC, CFB, ECB, OFB) from `NIST CAVP`_.
Expand Down Expand Up @@ -1055,6 +1056,7 @@ header format (substituting the correct information):
.. _`root-ed25519.pem`: https://github.com/openssl/openssl/blob/2a1e2fe145c6eb8e75aa2e1b3a8c3a49384b2852/test/certs/root-ed25519.pem
.. _`server-ed25519-cert.pem`: https://github.com/openssl/openssl/blob/2a1e2fe145c6eb8e75aa2e1b3a8c3a49384b2852/test/certs/server-ed25519-cert.pem
.. _`server-ed448-cert.pem`: https://github.com/openssl/openssl/blob/2a1e2fe145c6eb8e75aa2e1b3a8c3a49384b2852/test/certs/server-ed448-cert.pem
.. _`evpciph_aes_gcm_siv.txt`: https://github.com/openssl/openssl/blob/a2b1ab6100d5f0fb50b61d241471eea087415632/test/recipes/30-test_evp_data/evpciph_aes_gcm_siv.txt
.. _`evpciph_aes_siv.txt`: https://github.com/openssl/openssl/blob/d830526c711074fdcd82c70c24c31444366a1ed8/test/recipes/30-test_evp_data/evpciph_aes_siv.txt
.. _`dkg's additional OCB3 vectors`: https://gitlab.com/dkg/ocb-test-vectors
.. _`OpenSSL's OCB vectors`: https://github.com/openssl/openssl/commit/2f19ab18a29cf9c82cdd68bc8c7e5be5061b19be
Expand Down
73 changes: 73 additions & 0 deletions docs/hazmat/primitives/aead.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions src/cryptography/hazmat/bindings/_rust/openssl/aead.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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: ...
2 changes: 2 additions & 0 deletions src/cryptography/hazmat/primitives/ciphers/aead.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions src/rust/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand Down
111 changes: 111 additions & 0 deletions src/rust/src/backend/aead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,11 +410,122 @@ 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<pyo3::PyAny>) -> CryptographyResult<AesGcmSiv> {
let key_buf = key.extract::<CffiBuf<'_>>(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, 384 or 512 bits.",
),
))
}
};

#[cfg(not(CRYPTOGRAPHY_OPENSSL_320_OR_GREATER))]
{
Err(CryptographyError::from(
exceptions::UnsupportedAlgorithm::new_err((
"AES-GCM-SIV is not supported by this version of OpenSSL",
exceptions::Reasons::UNSUPPORTED_CIPHER,
)),
))
}
#[cfg(CRYPTOGRAPHY_OPENSSL_320_OR_GREATER)]
{
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, true)?,
})
}
}

#[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<CffiBuf<'_>>,
) -> 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<CffiBuf<'_>>,
) -> 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::<AesSiv>()?;
m.add_class::<AesOcb3>()?;
m.add_class::<AesGcmSiv>()?;

Ok(m)
}
20 changes: 20 additions & 0 deletions tests/bench/test_aead.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from cryptography.hazmat.primitives.ciphers.aead import (
AESCCM,
AESGCM,
AESGCMSIV,
AESOCB3,
AESSIV,
ChaCha20Poly1305,
Expand Down Expand Up @@ -100,3 +101,22 @@ def test_aesccm_decrypt(benchmark):
aes = AESCCM(b"\x00" * 32)
ct = aes.encrypt(b"\x00" * 12, b"hello world plaintext", None)
benchmark(aes.decrypt, b"\x00" * 12, ct, None)


@pytest.mark.skipif(
not _aead_supported(AESGCMSIV),
reason="Requires OpenSSL with AES-GCM-SIV support",
)
def test_aesgcmsiv_encrypt(benchmark):
aesgcmsiv = AESGCMSIV(b"\x00" * 32)
benchmark(aesgcmsiv.encrypt, b"\x00" * 12, b"hello world plaintext", None)


@pytest.mark.skipif(
not _aead_supported(AESGCMSIV),
reason="Requires OpenSSL with AES-GCM-SIV support",
)
def test_aesgcmsiv_decrypt(benchmark):
aesgcmsiv = AESGCMSIV(b"\x00" * 32)
ct = aesgcmsiv.encrypt(b"\x00" * 12, b"hello world plaintext", None)
benchmark(aesgcmsiv.decrypt, b"\x00" * 12, ct, None)
Loading

0 comments on commit b47723d

Please sign in to comment.