Commit Graph

103 Commits (97766d708b98f6e1e37b053c9ccfa39cd7b4c0b3)

Author SHA1 Message Date
Robert de Vries 97766d708b Address more review comments.
Also added a line to the change log to mention that typing information
has been added.
2026-07-06 22:02:48 +02:00
Robert de Vries 66b2ffb7c8 Addressed more review comments. 2026-07-06 22:02:48 +02:00
Robert de Vries 747243cc50 Address more review comments.
Tests are now also type checked as this helps verifying the correctness
of the type annotations.
2026-07-06 22:02:48 +02:00
Robert de Vries 1fb34e5cd8 Address review comments and annotate overrides. 2026-07-06 22:02:48 +02:00
Robert de Vries 2081edd6d7 Add typing information to ciphers.py
This has some fallout in random.py to simplify checks.
Also one test is slightly adapted to produced the desired failure.
2026-07-06 22:02:48 +02:00
David Garske c69d2f1eea
Merge pull request #134 from mjdemilliano/prepare-v5.9.2
Prepare for v5.9.2 release
2026-07-02 16:42:48 -07:00
Martijn de Milliano 38c541ab42 ML-DSA: Move check on signing/verifying without context to top
This makes it more clear what the requirements for calling this
function are and avoids unnecessary computations for objects
which are not used.
2026-07-02 13:21:58 +02:00
Martijn de Milliano c4d926950c AES-GCM stream tests
Test response by library explicitly when called with unsupported
number of tag bytes.
2026-06-29 18:41:17 +02:00
Martijn de Milliano afcebbf946 Rename flag to ML_DSA_NO_CTX_ENABLED 2026-06-29 18:41:17 +02:00
Martijn de Milliano 8d87cb4d13 ML-DSA: fix wording of message and docstrings 2026-06-26 00:05:15 +02:00
Juliusz Sosinowicz b13aeea62b Address Copilot review on wolfcrypt-py (F-4015, F-4463)
- 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.
2026-06-24 08:48:54 +00:00
Juliusz Sosinowicz 39acd415fc Reject ChaCha encrypt/decrypt before set_iv (F-4463)
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.
2026-06-23 11:35:58 +00:00
Juliusz Sosinowicz 53b3f6cef9 Remove contradictory cipher mode validation (F-4015)
_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.
2026-06-23 11:30:00 +00:00
Martijn de Milliano 52886c4034 ML-DSA: Deal with signing without context not always supported
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.
2026-06-04 18:03:35 +02:00
Robert de Vries 18701e3b62 Use format specifiers instead of percent format.
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.
2026-05-17 16:14:52 +02:00
Andrew Hutchings ef4195f99a Address Fenrir findings
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.
2026-05-12 13:15:35 +01:00
Andrew Hutchings 98215b60f6 Address Copilot concerns 2026-05-11 13:05:23 +01:00
Andrew Hutchings 57cca0e90d Validate raw element lengths in EccPublic/EccPrivate.decode_key_raw
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
2026-05-11 12:33:41 +01:00
Andrew Hutchings 000472761c Fix Ed448 ctx cdef to match wolfSSL header signature
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
2026-05-11 12:27:23 +01:00
Andrew Hutchings e961e83656 Avoid passing Python bytes to non-const wc_GetPkcs8TraditionalOffset
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
2026-05-11 12:15:51 +01:00
Andrew Hutchings 5e01d07e7f Fix ChaCha._set_key wiping encrypt stream state on first decrypt
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
2026-05-11 12:03:48 +01:00
Andrew Hutchings 6c1c1b76bb Fix AesSiv silently mangling associated data
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
2026-05-11 11:47:56 +01:00
David Garske 4ec45a6511
Merge pull request #110 from roberthdevries/special-wc-api-retval-exceptions
Raise specialized WolfCryptApiError for failed API calls.
2026-05-08 15:59:50 -07:00
Robert de Vries 2bcc7031bd
Revert change to raising WolfCryptError 2026-05-08 17:12:50 +02:00
Robert de Vries 8d80db4914
Pass error return value to exception
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.
2026-05-08 16:38:59 +02:00
David Garske e48fb07c43
Merge pull request #113 from roberthdevries/remove-redundant-stuff
Remove redundant parentheses and bytes() calls.
2026-05-05 11:16:44 -07:00
David Garske efe131ee96
Merge pull request #109 from kareem-wolfssl/gh108
Wrap _delete/_copy class attrs in staticmethod so self isn't bound as an extra arg.
2026-05-05 10:43:56 -07:00
David Garske b0708870ba
Merge pull request #93 from roberthdevries/rsa-public-add-rng-param
Make the random generator of _Rsa and RsaPublic configurable.
2026-05-05 10:35:04 -07:00
David Garske c17f7f0401
Merge pull request #105 from roberthdevries/missing-definition-ML_DSA_KEYGEN_SEED_LENGTH
Add missing definition ML_DSA_KEYGEN_SEED_LENGTH.
2026-05-05 10:35:01 -07:00
Robert de Vries 17dad74a20 Remove redundant parentheses and bytes() calls. 2026-04-24 22:51:00 +02:00
Robert de Vries 0ac207d34a Raise specialized WolfCryptApiError for failed API calls.
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.
2026-04-24 22:01:02 +02:00
Kareem f6c27bf55d Wrap _delete/_copy class attrs in staticmethod so self isn't bound as an extra arg.
Fixes #108.
2026-04-22 16:19:41 -07:00
Robert de Vries 7002b01e46 EccPrivate: Do lazy creation of random generator in make_key(). 2026-04-20 21:01:47 +02:00
Robert de Vries 377542f1f9 Add rng parameter to from_pem classmethod, add unit tests. 2026-04-17 23:19:29 +02:00
Robert de Vries 96bf7b14db Make the random generator of _Rsa and RsaPublic configurable.
This was the only class that has hardcoded the random number generator
in the implementation.
2026-04-17 23:19:29 +02:00
Robert de Vries a114bca77b Add missing definition ML_DSA_KEYGEN_SEED_LENGTH. 2026-04-17 23:19:13 +02:00
Robert de Vries b4ddce17de Keep reference to random number generator in EccPrivate.
Add a test for the case where no random number generator is passed
to EccPrivate.
2026-04-17 23:18:58 +02:00
Robert de Vries 26203d77d2 Fix mutable arguments passed as default arguments.
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.
2026-04-17 23:18:58 +02:00
Jeremiah Mackey 664e887f09 Fix hash copy semantics and add tests 2026-04-16 14:34:26 +00:00
Jeremiah Mackey 88bd75957d Add tests and fix build issues 2026-04-16 14:34:26 +00:00
Jeremiah Mackey cbdc388cc4 Fix low severity static analysis issues 2026-04-16 14:34:26 +00:00
Jeremiah Mackey c65ceaabd0 Fix resource leaks 2026-04-16 14:33:55 +00:00
Jeremiah Mackey 3eafda78f6 Fix cipher logic and validation 2026-04-16 14:33:55 +00:00
David Garske 3a675bb91a
Merge pull request #104 from roberthdevries/remove-inherit-from-object
Remove parent class object everywhere.
2026-04-15 15:04:24 -07:00
David Garske 1ec10b3c0d
Merge pull request #102 from roberthdevries/fix-various-minor-issues-caught-by-ruff
Fix various minor issues caught by `ruff check` in default mode.
2026-04-15 15:00:53 -07:00
David Garske 0297859652
Merge pull request #90 from mjdemilliano/ml-dsa-sign-with-context
ML-DSA: Add optional context to signing and verification
2026-04-15 14:59:20 -07:00
Daniele Lacamera 90f21e1d13
Merge branch 'master' into ml-dsa-generate-from-seed 2026-04-15 06:56:56 +02:00
Daniele Lacamera 9ebe2fe266
Merge branch 'master' into ml-dsa-sign-with-context 2026-04-15 06:51:11 +02:00
Martijn de Milliano ac6eee4f84 Process Copilot comments
- Use constant from ciphers.py
- Raise ValueError or TypeError in sign_with_seed instead of assert
- Add missing test case
2026-04-15 06:48:36 +02:00
Martijn de Milliano e36859cb9c ML-DSA: Support deterministic signing 2026-04-15 06:48:36 +02:00