Skip to content

secrets — weak token

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

secrets_token_bytes.py
1
2
3
4
import secrets


token = secrets.token_bytes(4)
Example Output
> precli tests/unit/rules/python/stdlib/secrets/examples/secrets_token_bytes.py
⛔️ Error on line 4 in tests/unit/rules/python/stdlib/secrets/examples/secrets_token_bytes.py
PY028: Inadequate Encryption Strength
A token size of '4' is less than the recommended '32' bytes, which can be vulnerable to brute-force attacks.

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.

secrets_token_bytes.py
1
2
3
4
import secrets


token = secrets.token_bytes()

Default Configuration

enabled = true
level = "warning"
warning_token_size = 32
error_token_size = 16

See also

New in version 0.3.14