]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-145200: Fix EVP_MAC_CTX leak in hashlib HMAC on init failure (GH-145201)
authorRamin Farajpour Cami <ramin.blackhat@gmail.com>
Sat, 11 Apr 2026 22:10:43 +0000 (01:40 +0330)
committerGitHub <noreply@github.com>
Sat, 11 Apr 2026 22:10:43 +0000 (15:10 -0700)
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Lib/test/test_hmac.py
Misc/NEWS.d/next/Library/2026-02-25-10-00-00.gh-issue-145200.m_4PAtcI.rst [new file with mode: 0644]
Modules/_hashopenssl.c

index de4d200374bcea851d6dd0ceb7a1e52f61b1f129..1ea182fec4ff189419955acd3ea2b2762e4cc1a1 100644 (file)
@@ -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 (file)
index 0000000..2fae260
--- /dev/null
@@ -0,0 +1,2 @@
+:mod:`hashlib`: fix a memory leak when allocating
+or initializing an OpenSSL HMAC context fails.
index 938a6ce5b962d14f6169ca3b8b9d72ced400871d..5d86c2e5886afdaa4ce1d29591945cb50871ab0e 100644 (file)
@@ -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);