Skip to content

gh-146287: Fix signed/unsigned mismatch in _hashlib_hmac_digest_size#148407

Merged
gpshead merged 2 commits intopython:mainfrom
gpshead:fix-hmac-digest-size-signedness
Apr 12, 2026
Merged

gh-146287: Fix signed/unsigned mismatch in _hashlib_hmac_digest_size#148407
gpshead merged 2 commits intopython:mainfrom
gpshead:fix-hmac-digest-size-signedness

Conversation

@gpshead
Copy link
Copy Markdown
Member

@gpshead gpshead commented Apr 11, 2026

Summary

_hashlib_hmac_digest_size() returns unsigned int, but on the legacy OpenSSL 1.1.1 path it gets its value from EVP_MD_size() which returns int. A negative error return (-1) would silently wrap to UINT_MAX, bypassing the == 0 error check and propagating a bogus size to callers.

This can't be triggered through the Python API today (the md pointer is always validated before use), but the type mismatch means the safety net has a hole.

  • Change _hashlib_hmac_digest_size() return type to int
  • Add explicit < 0 guard in the legacy OpenSSL path
  • Use SystemError instead of ValueError for these checks, since
    they represent internal invariant violations
  • Add assert() to EVP_get_block_size and EVP_get_digest_size
    to document that the hash context is always initialized
  • Update callers to use int instead of unsigned int

fixes #146287

…gned wrapping

Change _hashlib_hmac_digest_size() return type from unsigned int to int
so that a hypothetical negative return from EVP_MD_size() is not
silently wrapped to a large positive value. Add an explicit check for
negative digest_size in the legacy OpenSSL path, and use SystemError
(not ValueError) since these conditions indicate internal invariant
violations. Also add debug-build asserts to EVP_get_block_size and
EVP_get_digest_size documenting that the hash context is always
initialized.
@gpshead
Copy link
Copy Markdown
Member Author

gpshead commented Apr 11, 2026

there's nothing observable to users in this change, so skip news added.

@gpshead gpshead marked this pull request as ready for review April 11, 2026 22:47
@gpshead gpshead requested a review from picnixz as a code owner April 11, 2026 22:47
@gpshead gpshead added needs backport to 3.14 bugs and security fixes and removed needs backport to 3.14 bugs and security fixes labels Apr 11, 2026
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
@gpshead gpshead enabled auto-merge (squash) April 11, 2026 23:41
@gpshead gpshead merged commit d761f53 into python:main Apr 12, 2026
92 of 94 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

_hashopenssl.c‍: Missing negative return check in EVP_get_block_size and EVP_get_digest_size

2 participants