Hi Matt, Thanks for the thumbs-up. I can confirm that it works as expected. If I cast away the const and call RSA_set_ex_data() then the session handle is updated and available the next time stunnel uses that same key.
Now I just need to figure out how to document this so that a potential code review doesn't freak out... Regards, Andrew. -----Original Message----- From: openssl-users [mailto:openssl-users-boun...@openssl.org] On Behalf Of Matt Caswell Sent: Tuesday, July 23, 2019 10:28 AM To: openssl-users@openssl.org Subject: Re: Engine updating a key's ex data in sign/encrypt method? On 22/07/2019 17:44, Lynch, Andrew wrote: > Hi, > > I am wondering whether it is ok to update a key's ex data from within an > engine method that is using the key. This is with both OpenSSL 1.1.1a and > 1.0.2j. > > In my engine's load_privkey() method I connect to the HSM and obtain handles > for a session and the key object. Both handles are then stored in the key's > ex data using RSA_set_ex_data() or EC_KEY_set_ex_data(). They will later be > released by the registered free_func. The sign and/or encrypt methods use > these handles when making their calls to the HSM API. > > This works fine for single operations like an openssl x509 command line, but > not for long running applications such as stunnel. It appears that stunnel > loads all configured keys and certs at startup and then waits for clients to > connect. If there is no activity for a while the HSM will time out my > session handle and the next sign operation using that session fails. I can > catch the error and reconnect, but this results in a new session handle. The > next time a client calls the same service, that key's ex data still contains > the old outdated session handle resulting in the same error all over again. > > So whenever I renew a session handle in the sign method I need to update the > ex data of the affected key with the new value. > > This appears to work fine for EC keys by calling EC_KEY_set_ex_data() from > within the engine's ecdsa_do_sign() method. The same goes for RSA keys in > rsa_private_decrypt() and rsa_private_encrypt(), but with rsa_sign() I have a > problem in that the key parameter is const RSA *. > > Is the lack of const in rsa_private_encrypt() and ecdsa_do_sign() an > oversight and I should not be manipulating ex data of the provided key in > this way? > Or is the const in rsa_sign() too strict and it is actually ok to modify the > ex data of the key? I can't see a problem with modifying the ex_data like that. Matt