diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 7cb98ce0498b..63ca552042d3 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -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: diff --git a/src/rust/src/fernet.rs b/src/rust/src/fernet.rs index a0eca3522b5e..2aead947d058 100644 --- a/src/rust/src/fernet.rs +++ b/src/rust/src/fernet.rs @@ -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> { + if data.iter().any(u8::is_ascii_whitespace) { + let stripped = data + .iter() + .copied() + .filter(|b| !b.is_ascii_whitespace()) + .collect::>(); + URL_SAFE_LENIENT.decode(stripped).ok() + } else { + URL_SAFE_LENIENT.decode(data).ok() + } +} + fn b64encode<'p>( py: pyo3::Python<'p>, data: &[u8], @@ -82,9 +101,9 @@ fn unverified_token_data( token: &pyo3::Bound<'_, pyo3::PyAny>, ) -> CryptographyResult<(u64, Vec)> { let data = if let Ok(s) = token.cast::() { - URL_SAFE_LENIENT.decode(s.to_cow()?.as_bytes()).ok() + b64decode_lenient(s.to_cow()?.as_bytes()) } else if let Ok(b) = token.cast::() { - 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"), @@ -246,11 +265,9 @@ impl Fernet { )) }; let key = if let Ok(s) = key.cast::() { - URL_SAFE_LENIENT.decode(s.to_cow()?.as_bytes()).ok() + b64decode_lenient(s.to_cow()?.as_bytes()) } else { - URL_SAFE_LENIENT - .decode(key.extract::>()?.as_bytes()) - .ok() + b64decode_lenient(key.extract::>()?.as_bytes()) }; let key = key.ok_or_else(invalid_key)?; if key.len() != KEY_LEN { diff --git a/tests/test_fernet.py b/tests/test_fernet.py index 5930df4992a1..6dcf21d068a1 100644 --- a/tests/test_fernet.py +++ b/tests/test_fernet.py @@ -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