From: Ramin Farajpour Cami Date: Sat, 11 Apr 2026 22:10:43 +0000 (+0330) Subject: gh-145200: Fix EVP_MAC_CTX leak in hashlib HMAC on init failure (GH-145201) X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c29d75610b40d2052dc7a5394b416305adf61281;p=thirdparty%2FPython%2Fcpython.git gh-145200: Fix EVP_MAC_CTX leak in hashlib HMAC on init failure (GH-145201) Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com> --- diff --git a/Lib/test/test_hmac.py b/Lib/test/test_hmac.py index de4d200374bc..1ea182fec4ff 100644 --- a/Lib/test/test_hmac.py +++ b/Lib/test/test_hmac.py @@ -24,6 +24,7 @@ import random import unittest import warnings from _operator import _compare_digest as operator_compare_digest +from test import support from test.support import _4G, bigmemtest from test.support import check_disallow_instantiation from test.support import hashlib_helper, import_helper @@ -1024,6 +1025,13 @@ class OpenSSLConstructorTestCase(ThroughOpenSSLAPIMixin, ): self.hmac_digest(b'key', b'msg', value) + @support.subTests("xof_name", ("shake_128", "shake_256")) + def test_hmac_new_xof_digestmod(self, xof_name): + # gh-145200: XOF digests (SHAKE) are not supported by HMAC. + # Verify that the error path does not leak the EVP_MAC_CTX. + with self.assertRaises(_hashlib.UnsupportedDigestmodError): + self.hmac_new(b'key', digestmod=xof_name) + class BuiltinConstructorTestCase(ThroughBuiltinAPIMixin, ExtensionConstructorTestCaseMixin, diff --git a/Misc/NEWS.d/next/Library/2026-02-25-10-00-00.gh-issue-145200.m_4PAtcI.rst b/Misc/NEWS.d/next/Library/2026-02-25-10-00-00.gh-issue-145200.m_4PAtcI.rst new file mode 100644 index 000000000000..2fae260377cf --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-02-25-10-00-00.gh-issue-145200.m_4PAtcI.rst @@ -0,0 +1,2 @@ +:mod:`hashlib`: fix a memory leak when allocating +or initializing an OpenSSL HMAC context fails. diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c index 938a6ce5b962..5d86c2e5886a 100644 --- a/Modules/_hashopenssl.c +++ b/Modules/_hashopenssl.c @@ -2103,6 +2103,7 @@ hashlib_HMAC_CTX_new_from_digestmod(_hashlibstate *state, PY_EVP_MD_free(md); #endif if (r == 0) { + hashlib_openssl_HMAC_CTX_free(ctx); if (is_xof) { /* use a better default error message if an XOF is used */ raise_unsupported_algorithm_error(state, digestmod);