From 060abbf5f94e5eba53b13e288202350dc61c065f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?B=C3=A9n=C3=A9dikt=20Tran?= <10796600+picnixz@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:43:09 -0700 Subject: [PATCH] gh-159811: Raise OpenSSL errors in `_hashlib.HMAC` after re-attaching the thread state `hashlib_openssl_HMAC_update_once()` set an exception when the OpenSSL HMAC update function failed, but it was called inside a GIL-released region, with the object's mutex held, by `_hashlib.HMAC.update()` and `_hashlib.hmac_new()` when the data exceeds HASHLIB_GIL_MINSIZE bytes. Setting the exception with the thread state detached crashed the interpreter instead of raising an exception. Remove that helper, call the OpenSSL HMAC update function directly in `_hmac_update()`, and set the exception once the thread state is re-attached and the mutex is released, as it was done before gh-134531. The OpenSSL error queue is per thread, so the exception type and message are unaffected. --- ...-10-19-23-25-29.gh-issue-159811.P6yy0z.rst | 3 +++ Modules/_hashopenssl.c | 19 +++++++------------ 2 files changed, 10 insertions(+), 12 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-10-19-23-25-29.gh-issue-159811.P6yy0z.rst diff --git a/Misc/NEWS.d/next/Library/2026-10-19-23-25-29.gh-issue-159811.P6yy0z.rst b/Misc/NEWS.d/next/Library/2026-10-19-23-25-29.gh-issue-159811.P6yy0z.rst new file mode 100644 index 000000000000000..bcd76f209e52647 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-10-19-23-25-29.gh-issue-159811.P6yy0z.rst @@ -0,0 +1,3 @@ +Fix a crash in :mod:`hmac` when the OpenSSL routine used by +:meth:`hmac.HMAC.update` or by :func:`hmac.new` fails on data larger +than 2048 bytes. Patch by Bénédikt Tran. diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c index d23767afeb96cfb..393ae8aea126315 100644 --- a/Modules/_hashopenssl.c +++ b/Modules/_hashopenssl.c @@ -1976,16 +1976,6 @@ hashlib_HMAC_get_hashlib_digest_name(HMACobject *self) #endif } -static int -hashlib_openssl_HMAC_update_once(PY_HMAC_CTX_TYPE *ctx, const Py_buffer *v) -{ - if (!PY_HMAC_update(ctx, (const unsigned char *)v->buf, (size_t)v->len)) { - notify_smart_ssl_error_occurred_in(Py_STRINGIFY(PY_HMAC_update)); - return -1; - } - return 0; -} - /* Thin wrapper around PY_HMAC_CTX_free that allows to pass a NULL 'ctx'. */ static inline void hashlib_openssl_HMAC_CTX_free(PY_HMAC_CTX_TYPE *ctx) @@ -2240,10 +2230,15 @@ _hmac_update(HMACobject *self, PyObject *obj) GET_BUFFER_VIEW_OR_ERROR(obj, &view, return -1); HASHLIB_EXTERNAL_INSTRUCTIONS_LOCKED( self, view.len, - r = hashlib_openssl_HMAC_update_once(self->ctx, &view) + r = PY_HMAC_update(self->ctx, (const unsigned char *)view.buf, + (size_t)view.len) ); PyBuffer_Release(&view); - return r; + if (r == 0) { + notify_smart_ssl_error_occurred_in(Py_STRINGIFY(PY_HMAC_update)); + return -1; + } + return 0; } /*[clinic input]