Python Weak Hmac Hash
Description
This detector identifies Python code that uses weak or insecure hashing algorithms (e.g., MD5, SHA1) within HMAC (Hash-based Message Authentication Code) operations. Using a cryptographically weak digest algorithm inside an HMAC undermines the integrity and authenticity guarantees of the MAC, making it potentially vulnerable to collision or preimage attacks. The risk is amplified when the HMAC is applied to sensitive data such as passwords, tokens, or personal information.
Detection Strategy
• Identify imports from known HMAC-related libraries (e.g., `hmac`) and weak digest libraries (e.g., `hashlib` functions like `md5`, `sha1`). If no relevant imports are found, no analysis is performed.
• For direct HMAC construction calls (e.g., `hmac.new(...)`) that accept a digest/hash argument: flag the call if the digest algorithm argument resolves to a known weak hash function AND the message argument is determined to be sensitive (e.g., contains passwords, tokens, or personal data).
• For HMAC update calls (e.g., `h.update(msg)`): trace back the receiver object to its definition site and check whether it was constructed using a weak digest algorithm. If so, and the message passed to `update()` is sensitive, the call site is flagged as vulnerable.
• A call is reported as vulnerable only when both conditions are simultaneously true: (1) a weak digest algorithm is used in the HMAC, and (2) the data being authenticated is classified as sensitive.
Vulnerable code example
import hashlib
import hmac
from hashlib import md5
from Crypto.Hash import HMAC
from Cryptodome.Hash import HMAC as DomeHMAC
from Cryptodome.Hash import SHA1
from cryptography.hazmat.primitives import hashes...✅ Secure code example
import hashlib
import hmac
from hashlib import sha256
from Crypto.Hash import HMAC, SHA256
from Cryptodome.Hash import HMAC as DomeHMAC
from Cryptodome.Hash import SHA256 as DomeSHA256
from cryptography.hazmat.primitives import hashes...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' pentesting team, fill out this contact form.