Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ Changelog
* Fixed a regression in 51.0.0 where :class:`~cryptography.fernet.MultiFernet`
no longer accepted a generator (or any other iterable that is not a
sequence) of :class:`~cryptography.fernet.Fernet` instances.
* Fixed a regression in 51.0.0 where :class:`~cryptography.fernet.Fernet`
rejected keys and tokens whose base64 encoding has non-zero trailing bits or
contains ASCII whitespace.

.. _v51-0-0:

Expand Down
33 changes: 25 additions & 8 deletions src/rust/src/fernet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,31 @@ fn invalid_token() -> CryptographyError {
CryptographyError::from(InvalidToken::new_err(()))
}

// Padding is optional when decoding.
// Padding is optional when decoding, and non-zero trailing bits are ignored,
// matching Python's `base64.urlsafe_b64decode`.
const URL_SAFE_LENIENT: GeneralPurpose = GeneralPurpose::new(
&base64::alphabet::URL_SAFE,
GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
GeneralPurposeConfig::new()
.with_decode_padding_mode(DecodePaddingMode::Indifferent)
.with_decode_allow_trailing_bits(true),
);

/// Decodes url-safe base64, ignoring ASCII whitespace anywhere in the input
/// (e.g. a trailing newline from reading a key or token from a file), for
/// compatibility with the previous Python implementation.
fn b64decode_lenient(data: &[u8]) -> Option<Vec<u8>> {
if data.iter().any(u8::is_ascii_whitespace) {
let stripped = data
.iter()
.copied()
.filter(|b| !b.is_ascii_whitespace())
.collect::<Vec<u8>>();
URL_SAFE_LENIENT.decode(stripped).ok()
} else {
URL_SAFE_LENIENT.decode(data).ok()
}
}

fn b64encode<'p>(
py: pyo3::Python<'p>,
data: &[u8],
Expand Down Expand Up @@ -82,9 +101,9 @@ fn unverified_token_data(
token: &pyo3::Bound<'_, pyo3::PyAny>,
) -> CryptographyResult<(u64, Vec<u8>)> {
let data = if let Ok(s) = token.cast::<pyo3::types::PyString>() {
URL_SAFE_LENIENT.decode(s.to_cow()?.as_bytes()).ok()
b64decode_lenient(s.to_cow()?.as_bytes())
} else if let Ok(b) = token.cast::<pyo3::types::PyBytes>() {
URL_SAFE_LENIENT.decode(b.as_bytes()).ok()
b64decode_lenient(b.as_bytes())
} else {
return Err(CryptographyError::from(
pyo3::exceptions::PyTypeError::new_err("token must be bytes or str"),
Expand Down Expand Up @@ -246,11 +265,9 @@ impl Fernet {
))
};
let key = if let Ok(s) = key.cast::<pyo3::types::PyString>() {
URL_SAFE_LENIENT.decode(s.to_cow()?.as_bytes()).ok()
b64decode_lenient(s.to_cow()?.as_bytes())
} else {
URL_SAFE_LENIENT
.decode(key.extract::<CffiBuf<'_>>()?.as_bytes())
.ok()
b64decode_lenient(key.extract::<CffiBuf<'_>>()?.as_bytes())
};
let key = key.ok_or_else(invalid_key)?;
if key.len() != KEY_LEN {
Expand Down
31 changes: 31 additions & 0 deletions tests/test_fernet.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,37 @@ def test_bad_key(self, key):
with pytest.raises(ValueError):
Fernet(key)

@pytest.mark.parametrize(
"key",
[
# Non-zero trailing bits (canonical encoding ends in "des=").
"dev0dev0dev0dev0dev0dev0dev0dev0dev0dev0dev=",
b"dev0dev0dev0dev0dev0dev0dev0dev0dev0dev0dev=",
# Whitespace
"dev0dev0dev0dev0dev0dev0dev0dev0dev0dev0des=\n",
b" dev0dev0dev0dev0dev0dev0dev0dev0\r\ndev0dev0des=\n",
],
)
def test_lenient_key(self, key):
canonical = Fernet(b"dev0dev0dev0dev0dev0dev0dev0dev0dev0dev0des=")
f = Fernet(key)
assert f.decrypt(canonical.encrypt(b"abc")) == b"abc"

def test_lenient_token(self):
f = Fernet(Fernet.generate_key())
# A 73-byte token, so the encoding ends in "==" with unused bits.
token = f.encrypt(b"")
assert token.endswith(b"==")
alphabet = (
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
)
last = alphabet[alphabet.index(token[-3]) + 1]
non_canonical = token[:-3] + bytes([last]) + b"=="
assert f.decrypt(non_canonical) == b""
assert f.decrypt(token + b"\n") == b""
assert f.decrypt(token.decode() + "\r\n") == b""
assert f.extract_timestamp(token + b"\n") == f.extract_timestamp(token)

def test_extract_timestamp(self):
f = Fernet(base64.urlsafe_b64encode(b"\x00" * 32))
current_time = 1526138327
Expand Down
Loading