Security rules

NGB046: Insecure randomness for security values

Reports Math.random() used to produce security-sensitive values: the result is stored in, or returned by a function named like, a token, password, secret, key, session ID, OAuth state / nonce, PKCE verifier, CSRF token, salt, IV, OTP or reset / invite code..

Property Value
Rule ID NGB046
Category Cryptography
Default severity high
CWE CWE-338, CWE-330
Built-in presets recommended: error, strict: error

Confidence is reported per finding (high, medium, low) and is independent of severity. See Reading findings.

What it checks

Reports Math.random() used to produce security-sensitive values: the result is stored in, or returned by a function named like, a token, password, secret, key, session ID, OAuth state / nonce, PKCE verifier, CSRF token, salt, IV, OTP or reset / invite code.

Why it matters

Math.random() is not a cryptographic generator: V8 uses xorshift128+, whose internal state can be recovered from a handful of outputs, after which every past and future value is predictable. Tokens, OAuth state, nonces and reset codes built from it can be guessed. crypto.getRandomValues() and crypto.randomUUID() are available in every supported browser and in Node.js.

Detection behavior and supported patterns

  • Math.random() (global, symbol-resolved) flowing — through arithmetic, toString(36), substring, Math.floor, template literals, array index lookups — into a variable, property, storage key or object property
  • Security names: credential vocabulary of NGB014/NGB016 plus nonce, state, csrf, salt, iv, verifier, challenge, otp, pin, secret, captcha, invite, reset, signature
  • The enclosing function name counts as well (generateToken(), createNonce(), randomPassword()) with medium confidence
  • Names about UI or test data (color, delay, jitter, shuffle, trackById, mock, id, uuid) are ignored

Example

TypeScript
const state = Math.random().toString(36).substring(2);

Safer alternative

TypeScript
const state = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))));

Remediation

Use crypto.getRandomValues(new Uint8Array(32)) (encode as base64url / hex) or crypto.randomUUID() for identifiers. In Node.js SSR code use crypto.randomBytes().

False-positive considerations

  • Non-security identifiers that use security words (e.g. a UI stateKey for animations) can be reported; rename or document.

Known limitations

  • Random values passed to other functions before being named are only classified by the enclosing function name.
  • Third-party random libraries (e.g. nanoid/non-secure, random-js with a Math.random engine) are not recognized.

References

Run it

Shell
ngbastion explain NGB046