Calling rand()
function several times to produce a sequence of pseudorandom numbers will result in generating generates the same sequence in different runs of the program.
This can lead to security threat since, after the first run, an attacker will know may predict the generated sequence to be generated.
Noncompliant Code Example
The following This noncompliant code example generates a sequence of 10 pseudorandom numbers. No matter how many times this code is executed, it always produces the same sequence.
Code Block | ||
---|---|---|
| ||
for (int i=0; i<10; i++) { Â printf printf("%d\n", rand()); /* Always generates the same sequence */ } |
Compliant Solution
Use srand()
before rand()
to seed the random sequence generated by rand()
.
Code Block |
---|
srand(time(NULL)); /* Create seed based on current time */ for (int i=0; i<10; i++) { Â printf("%d\n", rand()); /* Generates different sequences at different runs */ } |
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC18-C |
| likely |
|
|
|
Automated Automated Detection
TODO
Related Vulnerabilities
TODOSearch for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This recommendation appears in the C++ Secure Coding Standard as MSC32-CPP. Ensure your random number generator is properly seeded.
...