https://github.com/python/cpython/commit/c29d75610b40d2052dc7a5394b416305adf61281
commit: c29d75610b40d2052dc7a5394b416305adf61281
branch: main
author: Ramin Farajpour Cami <[email protected]>
committer: gpshead <[email protected]>
date: 2026-04-11T15:10:43-07:00
summary:

gh-145200: Fix EVP_MAC_CTX leak in hashlib HMAC on init failure (GH-145201)

Co-authored-by: Bénédikt Tran <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-02-25-10-00-00.gh-issue-145200.m_4PAtcI.rst
M Lib/test/test_hmac.py
M Modules/_hashopenssl.c

diff --git a/Lib/test/test_hmac.py b/Lib/test/test_hmac.py
index de4d200374bcea..1ea182fec4ff18 100644
--- a/Lib/test/test_hmac.py
+++ b/Lib/test/test_hmac.py
@@ -24,6 +24,7 @@
 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 @@ def test_hmac_digest_digestmod_parameter(self):
             ):
                 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 00000000000000..2fae260377cf73
--- /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 938a6ce5b962d1..5d86c2e5886afd 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);

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to