- ChaCha.set_iv(): only mark _iv_set after _set_key() succeeds, and clear
it first, so a failed re-key cannot leave encrypt()/decrypt() unblocked
with a stale or partially-applied IV. Add a regression test.
- Update _Cipher.new()/encrypt()/decrypt() docstrings that still referred
to CFB/segment-size behavior to match the actually supported modes
(MODE_CBC, MODE_CTR) and their IV requirements.
_Hmac inherited _Hash.copy(), which - lacking a wolfCrypt copy function
for Hmac - fell back to a byte-level memmove and returned an object
marked _shallow_copy that aliases the original's internal C state. In
async or hardware-accelerated builds those internal pointers are shared,
so freeing the original leaves the copy with stale state
(use-after-free, wrong MACs, or corruption). wolfCrypt exposes no safe
public Hmac copy, so override copy() to raise NotImplementedError.
digest()/hexdigest() are unaffected. Update the shared hash tests to
expect this for HMAC.
ChaCha.__init__ leaves _IV_nonce empty and requires set_iv() before
use, but encrypt()/decrypt() (inherited from _Cipher) did not check
this. The first call ran _set_key(), which passed the empty nonce to
wc_Chacha_SetIV() - a function that unconditionally reads 12 bytes -
reading past the buffer and silently producing output with an
undefined IV. Track an _iv_set flag and override encrypt()/decrypt()
to raise WolfCryptError until set_iv() has been called.
_FEEDBACK_MODES advertised MODE_ECB/MODE_CFB/MODE_OFB as supported, but
_Cipher.__init__ then rejected every mode other than CBC/CTR with a
contradictory 'not supported by this cipher' error after they had
already passed the 'is supported' check. Prune _FEEDBACK_MODES to the
modes the cipher actually implements (CBC, CTR) so unsupported modes
get a single, accurate rejection, and drop the now-dead else branch.
In the newer wolfSSL signing and verifying without context is
not available unless it is explicitly enabled.
This change modifies the Python binding and test suite to
accommodate this.
printf-style string formatting has a number of quirks, and leads to less
readable code than using str.format calls or f-strings.
In general, prefer the newer str.format and f-strings constructs over
printf-style string formatting.
F-3340: AesGcmStream.final decrypt path passed len(authTag) straight to
wc_AesGcmDecryptFinal, letting a caller truncate the verification window
(forgery probability ~2^-32 instead of 2^-128 for a 4-byte tag against a
16-byte configuration). Reject len(authTag) != self._tag_bytes and pass
self._tag_bytes to wolfSSL, mirroring ChaCha20Poly1305.decrypt. Added
test_decrypt_rejects_wrong_tag_length. Also fixed test_encrypt_short_tag
which was relying on the bug (decrypt side defaulted to tag_bytes=16
against a 12-byte tag).
F-3089: Declare label as const byte* in the wc_RsaPublicEncrypt_ex and
wc_RsaPrivateDecrypt_ex cdefs so CFFI can accept Python bytes without
exposing a writable pointer into immutable memory. wolfSSL does not
modify label.
F-3090: Declare nonce as const byte* in the wc_InitRngNonce and
wc_InitRngNonce_ex cdefs for the same reason.
F-1983, F-1984: Add minimum + upper bounds to requirements/{prod,test,
docs}.txt so a hijacked release of cffi, tox, pytest, types-cffi,
Sphinx, or sphinx_rtd_theme does not get pulled silently on the next
pip install. setup.txt resolves transitively via prod.txt.
wc_ecc_import_unsigned takes no length parameters for qx/qy/d: it
reads exactly curve_size bytes from each pointer based on curve_id,
via mp_read_unsigned_bin in wc_ecc_import_raw_private. The Python
decode_key_raw wrappers handed the user-supplied buffers straight
through without any length check, so a shorter buffer caused the C
library to read past the end of the Python buffer (OOB read of
adjacent memory, potentially leaking it into the imported key or
segfaulting). A longer buffer silently dropped the extra bytes.
Add wc_ecc_get_curve_size_from_id to the CFFI cdef, then in both
decode_key_raw methods t2b the inputs, look up the expected curve
size, and raise ValueError if any of qx/qy/d does not match. Reject
unknown curve_id values with a clear message rather than falling
through to wolfSSL with a bogus size.
Add test_ecc_decode_key_raw_rejects_wrong_length covering short qx,
long qy, short d, unknown curve_id, and the happy path on both
EccPublic and EccPrivate.
F-3088
scripts/build_ffi.py declared wc_ed448_sign_msg and wc_ed448_verify_msg
with two cdef discrepancies vs the wolfSSL header (ed448.h):
- ctx was typed `byte*` instead of `const byte*`. CFFI was therefore
happy to forward a writable pointer into Python bytes storage.
The wolfSSL functions are const-correct and do not mutate ctx, so
this had no runtime impact, but it widened the surface CFFI was
willing to permit.
- ctx_len was typed `word32` instead of `byte`. RFC 8032 caps Ed448
context at 255 bytes, and wolfSSL's prototype reflects that with a
1-byte parameter. The mismatch happens to work on x86_64 SysV
because the low byte is what the callee reads, but it is still a
real ABI discrepancy and would not be guaranteed on other
platforms or calling conventions.
Update the cdef to const byte* / byte to match the header on both
functions. Add a guard in Ed448Public.verify and Ed448Private.sign so
callers passing a ctx longer than 255 bytes get a clear ValueError
rather than relying on CFFI's narrowing behavior.
ML-DSA's wc_dilithium_sign_ctx_msg / wc_dilithium_verify_ctx_msg cdefs
were also reviewed and already match the wolfSSL header.
F-3086
wc_GetPkcs8TraditionalOffset is declared in the wolfSSL public header
as taking byte* input (non-const), even though the current
implementation only reads from the buffer via ToTraditionalInline_ex.
RsaPrivate.__init__ was passing a Python bytes object directly into
that non-const parameter on the PKCS#8 fallback path, which lets CFFI
hand the C library a writable pointer into immutable storage. There is
no observable mutation today, but the contract permits it, and any
future wolfSSL change to actually write through the parameter would
silently corrupt the caller's bytes object.
Copy the key into a CFFI-owned byte array for that one call. The
adjacent wc_RsaPrivateKeyDecode calls are unaffected since their cdef
is already const byte*. PKCS#8 key load is a one-time cost at
construction, so the extra allocation is negligible.
Not changing the cdef to const byte* because the wolfSSL public header
itself declares the parameter non-const; diverging from the header
would cause compile warnings in the CFFI-generated glue code. If
wolfSSL ever const-corrects the header upstream, this copy can be
dropped.
F-2664
ChaCha._set_key ignored its `direction` argument and unconditionally
re-keyed both self._enc and self._dec whenever either was allocated.
Because _Cipher.encrypt and _Cipher.decrypt only call _set_key the
first time their respective context is allocated, doing
`encrypt(...); decrypt(...); encrypt(...)` on the same instance
silently rewound the encryption stream: the first decrypt() allocated
self._dec and re-keyed self._enc back to counter 0, so the second
encrypt() produced ciphertext as if starting from the beginning of the
keystream rather than continuing it. set_iv() relies on the
both-directions reset to change the IV, so that path must be preserved.
Honor the direction argument: direction _ENCRYPTION / _DECRYPTION only
touches the matching context, while direction 0 (the value set_iv
passes) keeps the existing reset-both behavior.
Add two regression tests: one that interleaves encrypt/decrypt/encrypt
and compares against a baseline two-encrypt sequence to catch any
future re-introduction of cross-direction state stomping, and one that
locks in set_iv's reset-both semantics so the fix is not later
narrowed in a way that breaks IV changes.
F-3586
Random.__init__ used _lib.INVALID_DEVID as a default parameter value,
but INVALID_DEVID is only declared in the CFFI cdef inside
`if features["ML_KEM"] or features["ML_DSA"]`. Since default parameters
are evaluated at module import time, any wolfSSL build that lacks both
ML-KEM and ML-DSA (e.g. via USE_LOCAL_WOLFSSL pointing at a custom
build) raises AttributeError on `import wolfcrypt.random`, cascading
into wolfcrypt.ciphers and effectively breaking the entire library.
Hardcode the default to -2, matching the convention already used by
_Hmac._init and AesGcmStream.__init__ (which call wc_HmacInit /
wc_AesInit with -2 directly rather than referencing _lib.INVALID_DEVID).
Add a build-no-pqc GitHub Actions job that builds wolfSSL with
--disable-kyber --disable-dilithium, installs wolfcrypt-py against it
via USE_LOCAL_WOLFSSL, and runs an import-smoke step plus the full
pytest suite. The smoke step is the explicit regression guard: it
imports wolfcrypt.random and instantiates Random(), which would fail
at import time if the default ever again references a CFFI symbol that
is only conditionally declared.
F-2659
AesSiv._prepare_associated_data only checked for str and bytes when
deciding whether the input was a single associated-data block, so
bytearray and memoryview fell through to the "list of blocks" branch.
Iterating those types yields integers, which t2b() then turned into
ASCII decimal byte-strings (b'16', b'17', ...), producing many bogus
blocks instead of one. The C SIV computation succeeded over wrong
associated data, so encryption/decryption silently produced an
incorrect tag rather than raising. This broke interoperability between
callers passing the same content as different buffer types.
Match the set of types accepted by t2b() by including bytearray and
memoryview in the isinstance check.
Add a parametrized test that reuses the OpenSSL KAT vectors with bytes,
bytearray, and memoryview wrappers; a round-trip test would not have
caught this since both sides mangle identically.
F-1981
If the size return value is negative, an error is detected. In that case raise an exception. Even though a zero is not a valid size value, it would indicate success in other cases. But a 0 return value would not make much sense as a return value for this function.
This exception takes the return value and converts that to
a human-readable string (if error string support is compiled in.)
The specialized exception is derived from WolfCryptError meaning
that existing users will not notice the difference except for the
nicer description.
Function defaults are evaluated once, when the function is defined.
The same mutable object is then shared across all calls to the function.
If the object is modified, those modifications will persist across calls,
which can lead to unexpected behavior.