Skip to content

Commit c29d756

Browse files
raminfppicnixz
andauthored
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>
1 parent 64afa94 commit c29d756

File tree

3 files changed

+11
-0
lines changed

3 files changed

+11
-0
lines changed

Lib/test/test_hmac.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import unittest
2525
import warnings
2626
from _operator import _compare_digest as operator_compare_digest
27+
from test import support
2728
from test.support import _4G, bigmemtest
2829
from test.support import check_disallow_instantiation
2930
from test.support import hashlib_helper, import_helper
@@ -1024,6 +1025,13 @@ def test_hmac_digest_digestmod_parameter(self):
10241025
):
10251026
self.hmac_digest(b'key', b'msg', value)
10261027

1028+
@support.subTests("xof_name", ("shake_128", "shake_256"))
1029+
def test_hmac_new_xof_digestmod(self, xof_name):
1030+
# gh-145200: XOF digests (SHAKE) are not supported by HMAC.
1031+
# Verify that the error path does not leak the EVP_MAC_CTX.
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: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:mod:`hashlib`: fix a memory leak when allocating
2+
or initializing an OpenSSL HMAC context fails.

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)