# MSC32-C: Properly seed pseudorandom number generators

This query implements the CERT-C rule MSC32-C:

> Properly seed pseudorandom number generators


## Description

A pseudorandom number generator (PRNG) is a deterministic algorithm capable of generating sequences of numbers that approximate the properties of random numbers. Each sequence is completely determined by the initial state of the PRNG and the algorithm for changing the state. Most PRNGs make it possible to set the initial state, also called the *seed state*. Setting the initial state is called *seeding* the PRNG.

Calling a PRNG in the same initial state, either without seeding it explicitly or by seeding it with the same value, results in generating the same sequence of random numbers in different runs of the program. Consider a PRNG function that is seeded with some initial seed value and is consecutively called to produce a sequence of random numbers, `S`. If the PRNG is subsequently seeded with the same initial seed value, then it will generate the same sequence `S`.

As a result, after the first run of an improperly seeded PRNG, an attacker can predict the sequence of random numbers that will be generated in the future runs. Improperly seeding or failing to seed the PRNG can lead to [vulnerabilities](https://wiki.sei.cmu.edu/confluence/display/c/BB.+Definitions#BB.Definitions-vulnerability), especially in security protocols.

The solution is to ensure that the PRNG is always properly seeded. A properly seeded PRNG will generate a different sequence of random numbers each time it is run.

Not all random number generators can be seeded. True random number generators that rely on hardware to produce completely unpredictable results do not need to be and cannot be seeded. Some high-quality PRNGs, such as the `/dev/random` device on some UNIX systems, also cannot be seeded. This rule applies only to algorithmic pseudorandom number generators that can be seeded.

## Noncompliant Code Example (POSIX)

This noncompliant code example generates a sequence of 10 pseudorandom numbers using the `random()` function. When `random()` is not seeded, it behaves like `rand()`, producing the same sequence of random numbers each time any program that uses it is run.

```cpp
#include <stdio.h>
#include <stdlib.h>
 
void func(void) {
  for (unsigned int i = 0; i < 10; ++i) {
    /* Always generates the same sequence */
    printf("%ld, ", random());
  }
}
```
The output is as follows:

```cpp
1st run: 1804289383, 846930886, 1681692777, 1714636915, 1957747793, 424238335, 719885386, 1649760492, 596516649,
         1189641421,
2nd run: 1804289383, 846930886, 1681692777, 1714636915, 1957747793, 424238335, 719885386, 1649760492, 596516649,
         1189641421,
...
nth run: 1804289383, 846930886, 1681692777, 1714636915, 1957747793, 424238335, 719885386, 1649760492, 596516649,
         1189641421,
```

## Compliant Solution (POSIX)

Call `srandom()` before invoking `random()` to seed the random sequence generated by `random()`. This compliant solution produces different random number sequences each time the function is called, depending on the resolution of the system clock:

```cpp
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
void func(void) {
  struct timespec ts;
  if (timespec_get(&ts, TIME_UTC) == 0) {
    /* Handle error */
  } else {
    srandom(ts.tv_nsec ^ ts.tv_sec);
    for (unsigned int i = 0; i < 10; ++i) {
      /* Generates different sequences at different runs */
      printf("%ld, ", random());
    }
  }
}

```
The output is as follows:

```cpp
1st run: 198682410, 2076262355, 910374899, 428635843, 2084827500, 1558698420, 4459146, 733695321, 2044378618, 1649046624,
2nd run: 1127071427, 252907983, 1358798372, 2101446505, 1514711759, 229790273, 954268511, 1116446419, 368192457,
         1297948050,
3rd run: 2052868434, 1645663878, 731874735, 1624006793, 938447420, 1046134947, 1901136083, 418123888, 836428296,
         2017467418,
```
This may not be sufficiently random for concurrent execution, which may lead to correlated generated series in different threads. Depending on the application and the desired level of security, a programmer may choose alternative ways to seed PRNGs. In general, hardware is more capable than software of generating real random numbers (for example, by sampling the thermal noise of a diode).

## Compliant Solution (Windows)

The [BCryptGenRandom()](https://docs.microsoft.com/en-us/windows/desktop/api/bcrypt/nf-bcrypt-bcryptgenrandom) function does not run the risk of not being properly seeded because its arguments serve as seeders:

```cpp
#include <stdio.h>
#include <Windows.h>
#include <Bcrypt.h>
#include <Ntstatus.h>
#include <Wincrypt.h>

void func(void) {
  BCRYPT_ALG_HANDLE hAlgorithm = NULL;
  long rand_buf;
  PUCHAR pbBuffer = (PUCHAR) &rand_buf;
  ULONG cbBuffer = sizeof(rand_buf);
  ULONG dwFlags = BCRYPT_USE_SYSTEM_PREFERRED_RNG;
  NTSTATUS status;
  for (unsigned int i = 0; i < 10; ++i) {
    status = BCryptGenRandom(hAlgorithm, pbBuffer, cbBuffer, dwFlags);
    if (status == STATUS_SUCCESS) {
      printf("%ld, ", rand_buf);
    } else {
      /* Handle Error */
    }
  }
}

```
The output is as follows:

```cpp
1st run: -683378946, 1957231690, 1933176011, -1745403355, -883473417, 882992405, 169629816, 1824800038, 899851668, 1702784647, 
2nd run: -58750553, -1921870721, -1973269161, 1512649964, -673518452, 234003619, -1622633366, 1312389688, -2125631172, 2067680022, 
3rd run: -189899579, 1220698973, 752205360, -1826365616, 79310867, 1430950090, -283206168, -941773185, 129633665, 543448789, 
```

## Risk Assessment

<table> <tbody> <tr> <th> Rule </th> <th> Severity </th> <th> Likelihood </th> <th> Remediation Cost </th> <th> Priority </th> <th> Level </th> </tr> <tr> <td> MSC32-C </td> <td> Medium </td> <td> Likely </td> <td> Low </td> <td> <strong>P18</strong> </td> <td> <strong>L1</strong> </td> </tr> </tbody> </table>


## Automated Detection

<table> <tbody> <tr> <th> Tool </th> <th> Version </th> <th> Checker </th> <th> Description </th> </tr> <tr> <td> <a> Astrée </a> </td> <td> 22.04 </td> <td> </td> <td> Supported, but no explicit checker </td> </tr> <tr> <td> <a> Axivion Bauhaus Suite </a> </td> <td> 7.2.0 </td> <td> <strong>CertC-MSC32</strong> </td> <td> </td> </tr> <tr> <td> <a> CodeSonar </a> </td> <td> 7.0p0 </td> <td> <strong>HARDCODED.SEED</strong> <strong>MISC.CRYPTO.TIMESEED</strong> </td> <td> Hardcoded Seed in PRNG Predictable Seed in PRNG </td> </tr> <tr> <td> <a> Helix QAC </a> </td> <td> 2022.2 </td> <td> <strong>C5031</strong> <strong>C++5036</strong> </td> <td> </td> </tr> <tr> <td> <a> Klocwork </a> </td> <td> 2022.2 </td> <td> <strong>CERT.MSC.SEED_RANDOM</strong> </td> <td> </td> </tr> <tr> <td> <a> PC-lint Plus </a> </td> <td> 1.4 </td> <td> <strong>2460, 2461, 2760</strong> </td> <td> Fully supported </td> </tr> <tr> <td> <a> Polyspace Bug Finder </a> </td> <td> R2022a </td> <td> <a> CERT C: Rule MSC32-C </a> </td> <td> Checks for: Deterministic random output from constant seedeterministic random output from constant seed, predictable random output from predictable seedredictable random output from predictable seed. Rule fully covered. </td> </tr> <tr> <td> <a> Parasoft C/C++test </a> </td> <td> 2022.1 </td> <td> <strong>CERT_C-MSC32-d</strong> </td> <td> Properly seed pseudorandom number generators </td> </tr> <tr> <td> <a> PRQA QA-C </a> </td> <td> 9.7 </td> <td> <strong>5031 </strong> </td> <td> </td> </tr> </tbody> </table>


## Related Vulnerabilities

Search for [vulnerabilities](https://wiki.sei.cmu.edu/confluence/display/c/BB.+Definitions#BB.Definitions-vulnerability) resulting from the violation of this rule on the [CERT website](https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+MSC32-C).

## Related Guidelines

[Key here](https://wiki.sei.cmu.edu/confluence/display/c/How+this+Coding+Standard+is+Organized#HowthisCodingStandardisOrganized-RelatedGuidelines) (explains table format and definitions)

<table> <tbody> <tr> <th> Taxonomy </th> <th> Taxonomy item </th> <th> Relationship </th> </tr> <tr> <td> <a> CERT C Secure Coding Standard </a> </td> <td> <a> MSC30-C. Do not use the rand() function for generating pseudorandom numbers </a> </td> <td> Prior to 2018-01-12: CERT: Unspecified Relationship </td> </tr> <tr> <td> <a> CERT C </a> </td> <td> <a> MSC51-CPP. Ensure your random number generator is properly seeded </a> </td> <td> Prior to 2018-01-12: CERT: Unspecified Relationship </td> </tr> <tr> <td> <a> CWE 2.11 </a> </td> <td> <a> CWE-327 </a> , Use of a Broken or Risky Cryptographic Algorithm </td> <td> 2017-05-16: CERT: Rule subset of CWE </td> </tr> <tr> <td> <a> CWE 2.11 </a> </td> <td> <a> CWE-330 </a> , Use of Insufficiently Random Values </td> <td> 2017-06-28: CERT: Rule subset of CWE </td> </tr> <tr> <td> <a> CWE 2.11 </a> </td> <td> <a> CWE-331 </a> , Insufficient Entropy </td> <td> 2017-06-28: CERT: Exact </td> </tr> </tbody> </table>


## CERT-CWE Mapping Notes

[Key here](https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152408#HowthisCodingStandardisOrganized-CERT-CWEMappingNotes) for mapping notes

**CWE-327 and MSC32-C**

* Intersection( MSC30-C, MSC32-C) = Ø
* MSC32-C says to properly seed pseudorandom number generators. For example, if you call rand(), make sure to seed it properly by calling srand() first. So far, we haven’t found any calls to rand().
* Failure to seed a PRNG causes it to produce reproducible (hence insecure) series of random numbers.
* CWE-327 = Union( MSC32-C, list) where list =
* Invocation of broken/risky crypto algorithms that are not properly seeded
**CWE-330 and MSC32-C**

Independent( MSC30-C, MSC32-C, CON33-C)

CWE-330 = Union( MSC30-C, MSC32-C, CON33-C, list) where list = other improper use or creation of random values. (EG the would qualify)

MSC30-C, MSC32-C and CON33-C are independent, they have no intersections. They each specify distinct errors regarding PRNGs.

## Bibliography

<table> <tbody> <tr> <td> \[ <a> MSDN </a> \] </td> <td> " <a> BCryptGenRandom() Function </a> " </td> </tr> </tbody> </table>


## Implementation notes

This rule will be checked by looking for calls to random that are no preceded by a call to srandom(). We perform a simple check for the argument to srandom() and verify it is not a literal (or a value easily deduced to be a literal).

## References

* CERT-C: [MSC32-C: Properly seed pseudorandom number generators](https://wiki.sei.cmu.edu/confluence/display/c)
