insufficient-randomness-anti-pattern

insufficient-randomness-anti-pattern

Security anti-pattern for insufficient randomness vulnerabilities (CWE-330). Use when generating or reviewing code that creates security tokens, session IDs, encryption keys, nonces, or any security-critical random values. Detects use of Math.random() or predictable seeds.

2звезд
1форков
Обновлено 1/22/2026
SKILL.md
readonlyread-only
name
"insufficient-randomness-anti-pattern"
description

"Security anti-pattern for insufficient randomness vulnerabilities (CWE-330). Use when generating or reviewing code that creates security tokens, session IDs, encryption keys, nonces, or any security-critical random values. Detects use of Math.random() or predictable seeds."

Insufficient Randomness Anti-Pattern

Severity: High

Summary

Insufficient randomness is a critical vulnerability that occurs when a security-sensitive value, such as a session token, password reset code, or encryption key, is generated using a predictable or non-cryptographically secure random number generator (PRNG). AI models often suggest using standard PRNGs like Math.random() or Python's random module because they are simple and common in general-purpose programming. However, these generators are not designed for security. Their output can be predicted by an attacker who observes a few values, allowing them to forge tokens, hijack sessions, or compromise cryptographic operations.

The Anti-Pattern

The anti-pattern is using a predictable, non-cryptographic random number generator for any value that needs to be unpredictable for security reasons.

BAD Code Example

// VULNERABLE: Using Math.random() to generate a session token.

function generateSessionToken() {
    let token = '';
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    // Math.random() is a standard PRNG, not a cryptographically secure one.
    // Its output is predictable if an attacker can observe enough previous values
    // or has some knowledge of the initial seed (which can be time-based).
    for (let i = 0; i < 32; i++) {
        token += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return token;
}

// An attacker who obtains a few of these tokens can potentially
// reverse-engineer the PRNG's internal state and predict future tokens.

GOOD Code Example

// SECURE: Using a cryptographically secure pseudo-random number generator (CSPRNG).
const crypto = require('crypto');

function generateSessionToken() {
    // `crypto.randomBytes()` generates random data using the operating system's
    // underlying entropy sources, making it unpredictable.
    // It is designed specifically for cryptographic use cases.
    const buffer = crypto.randomBytes(32); // Generate 32 bytes of random data.
    return buffer.toString('hex'); // Convert to a hex string for easy use.
}

// The resulting token is 64 characters long and has 256 bits of entropy,
// making it infeasible for an attacker to guess or predict.

Detection

  • Search the codebase for the use of non-cryptographic random functions in security-sensitive contexts. Look for:
    • Math.random() in JavaScript.
    • The random module in Python.
    • The java.util.Random class in Java.
    • rand() in PHP or C.
  • Review seeding: Look for any manual seeding of a random number generator, especially using a predictable value like the current time (random.seed(time.time())). CSPRNGs do not need to be manually seeded.
  • Check token generation logic: Examine how session IDs, password reset tokens, API keys, and other secrets are created.

Prevention

  • [ ] Always use a cryptographically secure pseudo-random number generator (CSPRNG) for any security-related value.
  • [ ] Know your language's CSPRNG:
    • Python: Use the secrets module or os.urandom().
    • JavaScript (Node.js): Use crypto.randomBytes() or crypto.getRandomValues().
    • Java: Use java.security.SecureRandom.
    • Go: Use the crypto/rand package.
    • C#: Use System.Security.Cryptography.RandomNumberGenerator.
  • [ ] Ensure sufficient entropy: Generate at least 128 bits (16 bytes) of randomness for tokens and unique identifiers. Use 256 bits (32 bytes) for encryption keys.
  • [ ] Never seed a CSPRNG manually. They are designed to automatically draw entropy from the operating system.

Related Security Patterns & Anti-Patterns

References

You Might Also Like

Related Skills

coding-agent

coding-agent

179Kdev-codegen

Run Codex CLI, Claude Code, OpenCode, or Pi Coding Agent via background process for programmatic control.

add-uint-support

add-uint-support

97Kdev-codegen

Add unsigned integer (uint) type support to PyTorch operators by updating AT_DISPATCH macros. Use when adding support for uint16, uint32, uint64 types to operators, kernels, or when user mentions enabling unsigned types, barebones unsigned types, or uint support.

at-dispatch-v2

at-dispatch-v2

97Kdev-codegen

Convert PyTorch AT_DISPATCH macros to AT_DISPATCH_V2 format in ATen C++ code. Use when porting AT_DISPATCH_ALL_TYPES_AND*, AT_DISPATCH_FLOATING_TYPES*, or other dispatch macros to the new v2 API. For ATen kernel files, CUDA kernels, and native operator implementations.

skill-writer

skill-writer

97Kdev-codegen

Guide users through creating Agent Skills for Claude Code. Use when the user wants to create, write, author, or design a new Skill, or needs help with SKILL.md files, frontmatter, or skill structure.

Implements JavaScript classes in C++ using JavaScriptCore. Use when creating new JS classes with C++ bindings, prototypes, or constructors.

Creates JavaScript classes using Bun's Zig bindings generator (.classes.ts). Use when implementing new JS APIs in Zig with JSC integration.