Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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 Setting the initial state is called 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. Suppose Consider a PRNG function that is seeded with some initial seed value and is consecutively called 10 times consecutively to produce a sequence of 10 random numbers. Suppose also that this , S. If the PRNG is not subsequently seeded . Running the code for the first time produces the sequence S = <r1, r2, r3, r4, r5, r6, r7, r8, r9, r10>. Running the code a second time produces exactly the same S sequence. Generally, any subsequent runs of the code with the same initial seed value, then it will generate the same sequence S sequence.

As a result, after the first run of the 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 many vulnerabilities, especially in security protocols.

The solution is to always to ensure that your the PRNG is always properly seeded. Seeding a PRNG means that it A properly seeded PRNG will generate a different sequences sequence of random numbers at any call.each time it is run.

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

MSC30-C. Do not use the rand() function for generating pseudorandom numbers addresses PRNGs from a different perspective, which is the cycle of the pseudorandom number sequence—that is, during a single run of a PRNG, the time interval after which the PRNG generates the same random numbers. MSC30-C deprecates the rand() function because it generates numbers that have a comparatively short cycle. The same rule proposes the use of the random() function for POSIX and CryptGenRandom() function for Windows.

The current rule (MSC32-C) examines, in terms of seeding, all three PRNGs mentioned in rule MSC30-C. Noncompliant code examples correspond to the use of a PRNG without a seed, while compliant solutions correspond to the same PRNG being properly seeded. MSC32-C complies with MSC30-C and does not recommend the use of the rand() function. Nevertheless, if it is unavoidable to use rand(), it should at least be properly number generators that can be seeded.

Noncompliant Code Example (POSIX)

This noncompliant code example generates a sequence of 10 pseudorandom numbers using the randrandom() function. When randrandom() is not seeded, it uses 1 as a default seed. No matter how many times this code is executed, it always produces the same sequencebehaves like rand(), producing the same sequence of random numbers each time any program that uses it is run.

Code Block
bgColor#FFCCCC
langc
int i=0;
for (i=0; i<10; i++) {
  printf("%d, ", rand()); /* Always generates the same sequence */
}

output:
1st run: 41, 18467, 6334, 26500, 19169, 15724, 11478, 29358, 26962, 24464,
2nd run: 41, 18467, 6334, 26500, 19169, 15724, 11478, 29358, 26962, 24464,
...
nth run: 41, 18467, 6334, 26500, 19169, 15724, 11478, 29358, 26962, 24464,

Noncompliant Code Example

Use srand() before rand() to seed the random sequence generated by rand(). The code produces different random number sequences at different calls.

Code Block
bgColor#FFCCCC
langc
srand(time(NULL)); /* Create seed based on current time */
int i=0;
for (i=0; i<10; i++#include <stdio.h>
#include <stdlib.h>
 
void func(void) {
  for (unsigned int i = 0; i < 10; ++i) {
  printf("%d, ", rand()); /* GeneratesAlways differentgenerates sequencesthe atsame differentsequence runs */
}

output:
1st run: 25121, 15571, 29839, 2454, 6844, 10186, 27534, 6693, 12456, 5756,
2nd run: 25134, 25796, 2992, 403, 15334, 25893, 7216, 27752, 12966, 13931,
3rd run: 25503, 27950, 22795, 32582, 1233, 10862, 31243, 24650, 11000, 7328,
...

Although the rand() function is now properly seeded, this solution is still noncompliant because the numbers generated by rand() have a comparatively short cycle, and the numbers can be predictable. (See MSC30-C. Do not use the rand() function for generating pseudorandom numbers.)

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 at different calls.

Code Block
bgColor#FFCCCC
langc
int i=0;
for (i=0; i<10; i++) {
  printf("%ld, ", random());
  }
}

The output is as follows:

Code Block
/* Always generates the same sequence */
}

output:
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)

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

Code Block
bgColor#ccccff
langc
srandom(time(NULL));#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
void func(void) {
  struct timespec ts;
  if (timespec_get(&ts, TIME_UTC) == 0) {
    /* CreateHandle seederror based*/
 on current} timeelse counted{
 as seconds from 01/01/1970 */
int i=0;
for (i=0; i<10; i++ srandom(ts.tv_nsec ^ ts.tv_sec);
    for (unsigned int i = 0; i < 10; ++i) {
  printf("%ld, ", random());    /* Generates different sequences at different runs */
      printf("%ld, ", random());
    }
  }
}

The output is as follows:

Code Block
:
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 threadsIn the previous examples, seeding in rand() and random() is done using the time() function, which returns the current time calculated as the number of seconds that have passed since January 1, 1970. Depending on the application and the desirable desired level of security, a programmer may choose alternative ways to seed PRNGs. In general, hardware is more capable than humans software of generating real random numbers (for example, by generating a sequence of bits by sampling the thermal noise of a diode and using the result as a seed).

Compliant Solution (Windows)

CryptGenRandomThe BCryptGenRandom() function does not run the risk of not being properly seeded because its arguments serve as seeders. From the Microsoft Developer Network CryptGenRandom() reference [MSDN]:

The CryptGenRandom() function fills a buffer with cryptographically random bytes.

Syntax
Code Block
BOOL WINAPI CryptGenRandom(
  __in     HCRYPTPROV hProv,
  __in     DWORD dwLen,
  __inout  BYTE *pbBuffer
);
Parameters

hProv [in]
    Handle of a cryptographic service provider (CSP) created by a call toCryptAcquireContext.
dwLen [in]
    Number of bytes of random data to be generated.
pbBuffer [in, out]
    Buffer to receive the returned data. This buffer must be at leastdwLenbytes in length.
    Optionally, the application can fill this buffer with data to use as an auxiliary random seed.

:

Code Block
bgColor#ccccff
langc
#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)
Code Block
bgColor#ccccff
langc
HCRYPTPROV   hCryptProv;

/* union stores the random number generated by CryptGenRandom() */
union  {
  BYTE bs[sizeof(long int)];
  long int li;
} rand_buf;

/* An example of instantiating the CSP */
if (CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0)) {
  printf("CryptAcquireContext succeeded.\n");
}
else {
  printf("Error during CryptAcquireContext!\n");
}

for (int i=0; i<10; i++) {
  if (!CryptGenRandom(hCryptProv, sizeof(rand_buf), (BYTE*) &rand_buf)) {
      printf("Error\n"%ld, ", rand_buf);
  }
  } else {
     printf("%ld, ", rand_buf.li); /* Handle Error */
    }
  }
}

The output is as follows:

Code Block
:
1st run: -1597837311683378946, 9061306821957231690, -13080318861933176011, 1048837407-1745403355, -931041900883473417, -658114613882992405, -1709220953169629816, -10196972891824800038, 1802206541899851668, 4065058411702784647, 
2nd run: 885904119-58750553, -6873795561921870721, -17822968541973269161, 14437019161512649964, -624291047673518452, 2049692692234003619, -9904515631622633366, 1312389688, -1423078042125631172, 12570792112067680022, 897185104,
3rd run: 190598304-189899579, -15374094641220698973, 1594174739752205360, -4244019161826365616, -197515347479310867, 8269129271430950090, 1705549595-283206168, -1515331215941773185, 474951399129633665, 1982500583,
...
543448789, 

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC32-C

medium

Medium

likely

Likely

low

Low

P18

L1

Automated Detection

Tool

Version

Checker

Description

Compass/ROSE

 

 

Astrée
Include Page
Astrée_V
Astrée_V

Supported, but no explicit checker
Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC-MSC32
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

HARDCODED.SEED
MISC.CRYPTO.TIMESEED

Hardcoded Seed in PRNG
Predictable Seed in PRNG

Cppcheck Premium

Include Page
Cppcheck Premium_V
Cppcheck Premium_V

premium-cert-msc32-cFully implemented
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C5031

C++5036


Klocwork
Include Page
Klocwork_V
Klocwork_V

CERT.MSC.SEED_RANDOM


PC-lint Plus

Include Page
PC-lint Plus_V
PC-lint Plus_V

2460, 2461, 2760

Fully supported

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C: Rule MSC32-C


Checks for:

  • Deterministic random output from constant seed
  • Predictable random output from predictable seed

Rule fully covered.

Parasoft C/C++test

Include Page
Parasoft_V
Parasoft_V

CERT_C-MSC32-d

Properly seed pseudorandom number generators

 

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

Key here (explains table format and definitions)

Taxonomy

Taxonomy item

Relationship

CERT C

...

...

...

MITRE CWE: CWE-327 , "Use of a broken or risky cryptographic algorithm"

MITRE CWE: CWE-330, "Use of insufficiently random values"

Sources

[C++ Reference] Standard C Library

...

Prior to 2018-01-12: CERT: Unspecified Relationship
CWE 2.11CWE-327, Use of a Broken or Risky Cryptographic Algorithm2017-05-16: CERT: Rule subset of CWE
CWE 2.11CWE-330, Use of Insufficiently Random Values2017-06-28: CERT: Rule subset of CWE
CWE 2.11CWE-331, Insufficient Entropy2017-06-28: CERT: Exact

CERT-CWE Mapping Notes

Key here 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

...


...

Image Modified Image Modified Image Modified