Topic: Crypto Callbacks: Managing HSM hash context and context copying
Hi all,
I’m integrating the wolfSSL (v5.7.6) library into an Infineon Aurix (tc3xx) which utilizes a HSM (etas Cycur HSM). I'm trying to offload various crypto functions to the HSM and am running into issues.
Because the HSM is not stateless, each hash operation needs its own session/context, which must be managed per hash object.
Current approach:
On first update, I allocate a context from a memory pool and store it in the devCtx pointer of the wolfSSL hash object.
On finalize, I close the HSM session, free the context, and set devCtx to NULL.
I'm currently not yet at the point where I actually feed the HSM with data, as I am testing if the opening and closing of sessions with the pools themselves work.
Problem:
I’ve observed that wolfSSL sometimes internally copies (clones) the SHA256 context via the wc_Sha256GetHash() function - including my devCtx pointer.
This results in both the original and the copy calling finalize (and freeing the same context), leading to double-free or resource leaks, because there’s no way to distinguish the “real” owner from a clone.
I’ve noticed:
Some device ports (e.g., for ESP, PIC, STM32) and features like WOLFSSL_ASYNC_CRYPT seem to support callback hooks or custom context copy/free handling.
But I haven’t found a generic, portable way to handle context lifecycle events (copy/clone/free) for my own MCU/HSM, or a way to enable these hooks via public configuration.
My questions:
Is there a portable way (not device-specific) to get notified when wolfSSL copies or destroys a hash context, or to customize this process?
If not, is patching the library to add these hooks the only solution, like adding my own wc_Sha256* functions? Another idea would be to omit the sha256.c file and compile in my own instead that handles lifecycle and so on.
Are there plans to expose such lifecycle hooks for generic crypto callback users, or are there any existing workarounds (besides buffering all hash input)?
Why I need this:
My HSM context can’t be blindly copied or freed multiple times.
I need to track ownership, ideally with explicit create/copy/free callbacks, to avoid double-free and allow robust session management - especially if wolfSSL hashes in parallel or clones contexts internally.
Any advice, or pointers to a non-device-specific solution, would be greatly appreciated!
Thanks!