Log crypto callback tracebacks, fail closed on handler errors and document the override contract

pull/114/head
David Garske 2026-10-19 12:53:48 -07:00
parent 3da4b6d0a3
commit db57784506
4 changed files with 14 additions and 10 deletions

View File

@ -69,13 +69,15 @@ if top_level_py not in ["setup.py", "build_ffi.py"]:
raise WolfCryptApiError("WolfCrypt_Init failed", ret)
if _lib.CRYPTO_CB_ENABLED:
def crypto_cb_error_handler(exception: Exception, exc_value: Exception, traceback: TracebackType | None) -> int: # noqa: ANN401
def crypto_cb_error_handler(
exc_type: object, exc_value: BaseException, traceback: TracebackType | None
) -> int:
if isinstance(exc_value, WolfCryptApiError):
return exc_value.err_code
log.error(exc_value)
log.error("crypto callback failed", exc_info=exc_value)
return _lib.WC_HW_E
@_ffi.def_extern(onerror=crypto_cb_error_handler)
@_ffi.def_extern(error=_lib.WC_HW_E, onerror=crypto_cb_error_handler)
def py_wc_crypto_callback(device_id: int, info: _lib.wc_CryptoInfo, ctx: FFI.CData) -> int:
if ctx == _ffi.NULL:
return _lib.CRYPTOCB_UNAVAILABLE

View File

@ -595,12 +595,7 @@ class wc_HashInfo:
data: FFI.CData
data_size: int
digest: FFI.CData
sha1: FFI.CData
sha256: FFI.CData
sha384: FFI.CData
sha512: FFI.CData
sha3: FFI.CData
ctx: FFI.CData
u: FFI.CData
@dataclass

View File

@ -83,6 +83,13 @@ if _lib.CRYPTO_CB_ENABLED:
class CryptoCallback:
"""
Registers a wolfCrypt crypto callback device for **device_id**.
Subclasses override rng_callback, or both hash_update_callback
and hash_finalize_callback. Operations that are not overridden
fall back to the software implementation.
"""
# Keeps each registered instance (and its ctx handle) alive until it is
# unregistered, and records which instance owns a device id.
_registered: ClassVar[dict[int, CryptoCallback]] = {}

View File

@ -349,7 +349,7 @@ if _lib.SHA3_ENABLED:
):
self._delete(self._native_object)
def __init__(self, string: BytesOrStr | None = None, size: int = SHA3_384_DIGEST_SIZE, device_id:int = _lib.INVALID_DEVID) -> None: # pylint: disable=W0231
def __init__(self, string: BytesOrStr | None = None, size: int = SHA3_384_DIGEST_SIZE, device_id: int = _lib.INVALID_DEVID) -> None: # pylint: disable=W0231
self._native_object = _ffi.new(self._native_type)
self._shallow_copy = False
self.digest_size = size