Raw HMAC bytes got decoded into a default-charset string before comparison. That mangles invalid byte sequences, so two different MACs can compare equal. Enough to defeat the check.
What goes wrong
A helper computed an HMAC and returned it by wrapping the raw bytes in a string using the platform default charset. Bytes are not text. A MAC is arbitrary binary, and most of it is not valid UTF-8 or whatever the platform happened to pick.
When the decoder meets a byte sequence it cannot map, it does not fail. It substitutes a replacement character or drops the sequence. Several different byte arrays can decode to the same string once those substitutions happen. Compare MACs as strings after that, and you have manufactured collisions where the raw bytes had none. An attacker who can nudge inputs toward colliding decodings gets a forged value accepted as authentic.
The fix is to keep the MAC in a form that survives a round trip. Compare the raw bytes directly, or encode with something injective like hex or Base64. Do the comparison in constant time while you are there.
The pattern
def mac_of(key, data):
raw = hmac_sha256(key, data)
return str(raw) # default charset, lossy
def verify(key, data, expected):
return mac_of(key, data) == expecteddef mac_of(key, data):
return hmac_sha256(key, data) # keep the raw bytes
def verify(key, data, expected_bytes):
return constant_time_equal(
mac_of(key, data), expected_bytes)Every gate held. The exploit path was reproduced against a negative control, the impact was calibrated, and the finding was signed report-ready.
Why it matters to you
An integrity check that can be tricked into a false match is worse than no check, because the rest of the system trusts it. If this MAC guards a token, a webhook signature, or the authenticity of a stored record, a collision is an authentication bypass hiding inside a line of glue code that looked like formatting.
Check your own code
- Search for MAC or hash output passed through a string or default-charset decode.
- Return and compare MACs as raw bytes or an injective encoding such as hex or Base64.
- Use a constant-time comparison for all MAC and token checks.