Description
Using predictable generators such as rand for security tokens, session identifiers, or key material can make the values guessable.
Potential impact
- Token prediction, session hijacking, or weakened cryptographic protection may result.
Remediation
Use an operating-system CSPRNG or a vetted cryptographic random API. Confirm that all requested bytes were obtained; do not use a failed output buffer as a token or key.
Examples
Before
c
int token = rand();
After
This is a Linux excerpt inside a function that returns -1 on error, with <sys/random.h> included.
c
unsigned char token[32];
if (getrandom(token, sizeof(token), 0) != (ssize_t)sizeof(token)) {
return -1;
}
Explanation:
- Before: A predictable general-purpose PRNG generates a security-sensitive value.
- After: The operating system supplies cryptographic random bytes, and processing stops if all 32 bytes are not obtained.