diff --git a/Misc/NEWS.d/next/Library/2026-03-02-19-41-39.gh-issue-145376.OOzSOh.rst b/Misc/NEWS.d/next/Library/2026-03-02-19-41-39.gh-issue-145376.OOzSOh.rst new file mode 100644 index 00000000000000..466b9a9117d85d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-03-02-19-41-39.gh-issue-145376.OOzSOh.rst @@ -0,0 +1 @@ +Fix double free and null pointer dereference in unusual error scenarios in :mod:`md5module` and :mod:`hmacmodule`. diff --git a/Modules/hmacmodule.c b/Modules/hmacmodule.c index f074f24807703c..d45ddbe58e6d5d 100644 --- a/Modules/hmacmodule.c +++ b/Modules/hmacmodule.c @@ -1378,7 +1378,6 @@ static void py_hmac_hinfo_ht_free(void *hinfo) { py_hmac_hinfo *entry = (py_hmac_hinfo *)hinfo; - assert(entry->display_name != NULL); if (--(entry->refcnt) == 0) { Py_CLEAR(entry->display_name); PyMem_Free(hinfo); @@ -1457,7 +1456,9 @@ py_hmac_hinfo_ht_new(void) do { \ int rc = py_hmac_hinfo_ht_add(table, KEY, value); \ if (rc < 0) { \ - PyMem_Free(value); \ + if (value->refcnt == 0) { \ + PyMem_Free(value); \ + } \ goto error; \ } \ else if (rc == 1) { \ @@ -1474,7 +1475,8 @@ py_hmac_hinfo_ht_new(void) e->hashlib_name == NULL ? e->name : e->hashlib_name ); if (value->display_name == NULL) { - PyMem_Free(value); + /* value is owned by the table (refcnt > 0), so + _Py_hashtable_destroy() will free it. */ goto error; } } diff --git a/Modules/md5module.c b/Modules/md5module.c index 56e9faf4c62002..e598b1fe67240d 100644 --- a/Modules/md5module.c +++ b/Modules/md5module.c @@ -87,7 +87,10 @@ static void MD5_dealloc(PyObject *op) { MD5object *ptr = _MD5object_CAST(op); - Hacl_Hash_MD5_free(ptr->hash_state); + if (ptr->hash_state != NULL) { + Hacl_Hash_MD5_free(ptr->hash_state); + ptr->hash_state = NULL; + } PyTypeObject *tp = Py_TYPE(op); PyObject_GC_UnTrack(ptr); PyObject_GC_Del(ptr);