Insufficient Token Length
Tokens are often used as security-critical elements, such as for authentication, session management, or as part of cryptographic operations. The strength of a token is significantly influenced by its length and the randomness of its generation. Tokens with insufficient byte lengths lack the necessary entropy to withstand brute-force attacks, leading to a potential compromise of the system's security integrity.
All calls to secrets.token_bytes()
, secrets.token_hex()
, and
secrets.token_urlsafe()
MUST specify a byte size of at least 32.
This requirement ensures that the generated tokens have a strong level of
cryptographic security, reducing the risk of unauthorized access through
token prediction or brute-force attacks.
Example
import secrets
token = secrets.token_bytes(16)
Remediation
Its recommended to increase the token size to at least 32 bytes or leave
the nbytes
parameter unset or set to None to use a default entropy.
import secrets
token = secrets.token_bytes()
False Positives
In the case of a false positive the rule can be suppressed. Simply add a
trailing or preceding comment line with either the rule ID (PY028
) or
rule category name (insufficient_token_length
).
- Using rule ID
- Using category name
import secrets
# suppress: PY028
token = secrets.token_bytes(16)
import secrets
# suppress: insufficient_token_length
token = secrets.token_bytes(16)