Rules / C/C++
SHIELD-CPP-021
Insecure random for security tokens
What it detects
rand or random is not cryptographically secure and must not generate keys or tokens.
How to fix
Use a CSPRNG such as getrandom or RAND_bytes for security-sensitive values.
Vulnerable — Shield flags thistoken.c
#include <stdlib.h>
void make_session_token(unsigned char *out, size_t n) {
for (size_t i = 0; i < n; i++) {
/* rand() is predictable: tokens can be guessed */
out[i] = (unsigned char)(rand() & 0xff);
}
}
Fixed — scans cleantoken.c
#include <sys/random.h>
int make_session_token(unsigned char *out, size_t n) {
/* getrandom draws from the kernel CSPRNG */
if (getrandom(out, n, 0) != (ssize_t)n)
return -1;
return 0;
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-CPP-021, the fixed one does not.