Safeguard
Application Security•

CWE-331 Insufficient Entropy: Random Values With Patterns

When a generator leaves patterns or clusters, some values are likelier than others and attackers exploit that. CWE-331 explained with practical fixes.

Safeguard Security Team
2 min read

CWE-331, Insufficient Entropy, covers products that use an algorithm or scheme which produces too little entropy. The output has patterns or clusters, so some values are more likely to occur than others.

Entropy is the unpredictability behind random numbers. If a system has too little of it, everything built on top, such as keys, session tokens and certificates, inherits the weakness.

How it happens

An output can look random and still be skewed. Causes include seeding from a small set of possibilities, using too few bits, or a flaw in the generation arithmetic.

Observed examples show both ends. CVE-2001-0950 used insufficiently random data to generate session tokens with C rand(), and also weak data for certificate and key generation. CVE-2008-2108 is a chain in which insufficient precision in a random number generator caused some zero bits to be reliably generated.

# Vulnerable: few possible outcomes, easily enumerated
session_id = random.randint(0, 99999)

What an attacker gains

An attacker can guess the numbers the generator produces and gain unauthorized access, bypassing a protection mechanism that relied on them.

How to find it

Static analysis can find some uses of known weak generators. For output quality, sample many values and examine their distribution. Review the bit length of any key, seed or token.

How to fix it

MITRE says to determine the entropy needed to provide adequate randomness and unpredictability, and to achieve it by increasing the number of bits in objects such as keys and seeds. Draw from the operating system secure generator instead of building your own.

# Fixed: 128 bits from the OS source
session_id = secrets.token_hex(16)

Quick check

Is more length always enough?

Only if the extra bits are unpredictable. Padding a weak value does not add entropy.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.