Skip to content

Commit 997dbdc

Browse files
committed
gh-145200: Fix EVP_MAC_CTX leak in hashlib HMAC on init failure
1 parent 1ac9d13 commit 997dbdc

File tree

3 files changed

+12
-0
lines changed

3 files changed

+12
-0
lines changed

Lib/test/test_hmac.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1024,6 +1024,14 @@ def test_hmac_digest_digestmod_parameter(self):
10241024
):
10251025
self.hmac_digest(b'key', b'msg', value)
10261026

1027+
def test_hmac_new_xof_digestmod(self):
1028+
# gh-145200: XOF digests (SHAKE) are not supported by HMAC.
1029+
# Verify that the error path does not leak the EVP_MAC_CTX.
1030+
for xof_name in ('shake_128', 'shake_256'):
1031+
with self.subTest(digestmod=xof_name):
1032+
with self.assertRaises(_hashlib.UnsupportedDigestmodError):
1033+
self.hmac_new(b'key', digestmod=xof_name)
1034+
10271035

10281036
class BuiltinConstructorTestCase(ThroughBuiltinAPIMixin,
10291037
ExtensionConstructorTestCaseMixin,
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix memory leak in :mod:`hashlib` HMAC when ``EVP_MAC_init()`` or
2+
``HMAC_Init_ex()`` fails (e.g., with an XOF digest such as SHAKE). The
3+
``EVP_MAC_CTX`` is now freed on the error path.

Modules/_hashopenssl.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2103,6 +2103,7 @@ hashlib_HMAC_CTX_new_from_digestmod(_hashlibstate *state,
21032103
PY_EVP_MD_free(md);
21042104
#endif
21052105
if (r == 0) {
2106+
hashlib_openssl_HMAC_CTX_free(ctx);
21062107
if (is_xof) {
21072108
/* use a better default error message if an XOF is used */
21082109
raise_unsupported_algorithm_error(state, digestmod);

0 commit comments

Comments
 (0)