Versions Compared

Key

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

Calling a random 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 a constant value, results RNG) that is not seeded will result in generating the same sequence of random numbers in different runs of the program. Suppose there is code that calls an RNG function 10 times Consider a PRNG function that is seeded with some initial seed value and is consecutively called to produce a sequence of 10 random numbers. Suppose, also, that this RNG is not seeded. Running the code the first time will produce the sequence S = <r1, r2, r3, r4, r5, r6, r7, r8, r9, r10>. Running the code again a second time will produce the exact same sequence S. Generally, any subsequent runs of the code  If the PRNG is subsequently seeded with the same initial seed value, then it will generate the same sequence S.

As a resultConsequently, after the first run of the RNGan improperly seeded PRNG, an attacker will know can predict the sequence of random numbers that will be generated in the future runs. Knowing the sequence of random numbers that will be generated beforehand can lead to many  Improperly seeding or failing to seed the PRNG can lead to vulnerabilities, especially when in security protocols are concerned.

As a solution, you should always ensure that your RNG is properly seeded. Seeding an RNG means that it will generate different sequences of random numbers at any call.

Rule MSC30-CPP. Do not use the rand() function for generating pseudorandom numbers addresses RNGs from a different perspective, i.e., the time until the first collision occurs. In other words, during a single run of an RNG, the time interval after which the RNG generates the same random numbers. Rule MSC30-CPP deprecates the rand() function because it generates numbers which have a comparatively short cycle. The same rule proposes the use of the random() function for POSIX and the CryptGenRandom() function for Windows.

The solution is to ensure that a PRNG is always properly seeded with an initial seed value that will not be predictable or controllable by an attacker. 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 PRNGs that can be The current rule (MSC32-CPP) examines these three RNGs in terms of seeding. Noncompliant code examples correspond to the use of an RNG without a seed, while compliant solutions correspond to the same RNG being properly seeded. Rule MSC32-CPP addresses all three RNGs mentioned in rule MSC30-CPP for completeness. Rule MSC32-CPP complies to MSC30-CPP and does not recommend the use of the rand() function. Nevertheless, if it is unavoidable to use rand(), it should at least be properly seeded.

Noncompliant Code Example

This noncompliant code example generates a sequence of 10 pseudorandom numbers using the rand() function. When rand() is not seeded, it uses 1 as a default seed. Mersenne Twister engine. No matter how many times this code is executed, it always produces the same sequence because the default seed is used for the engine.

Code Block
bgColor#FFCCCC
langcpp
#include <random>
int i=0;
for (i=0; i<10; i++#include <iostream>

void f() {
    cout<<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,

Compliant Solution (C Standard)

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#ccccff

srand(time(NULL)); /* Create seed based on current time */
int i=0;
for (i=0; i<10; i++std::mt19937 engine;
  
  for (int i = 0; i < 10; ++i) {
    cout<<rand std::cout << engine() << ", ";
 /* Generates different sequences at different runs */
}

output }
}

The output of this example follows.

Code Block
:
1st run: 251213499211612, 15571581869302, 298393890346734, 24543586334585, 6844545404204, 101864161255391, 275343922919429, 6693949333985, 124562715962298, 57561323567403, 
2nd run: 251343499211612, 25796581869302, 29923890346734, 4033586334585, 15334545404204, 258934161255391, 72163922919429, 27752949333985, 129662715962298, 139311323567403, 
...
3rdnth run: 255033499211612, 27950581869302, 227953890346734, 325823586334585, 1233545404204, 108624161255391, 312433922919429, 24650949333985, 110002715962298, 7328,
...
1323567403, 

Noncompliant Code Example

This noncompliant code example improves the previous noncompliant code example generates a sequence of 10 pseudorandom numbers using the random() function. When random() is not seeded, it behaves like rand() and thus produces the same sequence of random numbers at different callsby seeding the random number generation engine with the current time. However, this approach is still unsuitable when an attacker can control the time at which the seeding is executed. Predictable seed values can result in exploits when the subverted PRNG is used.

Code Block
bgColor#FFCCCC
langcpp

int i=0;
for (i=0; i<10; i++#include <ctime>
#include <random>
#include <iostream>

void f() {
    cout<<random()<<", "; /* 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 srandom() before random() to seed the random sequence generated by random(). The code produces different random number sequences at different calls.

Code Block
bgColor#ccccff

srandom(time(NULL)); /* Create seed based on current time counted as seconds from 01/01/1970 */
int i=0;
for (i=0; i<10; i++) {
    cout<<random()<<", "; /* Generates different sequences at different runs */
}

output:
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,
...

In 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 past since 01/01/1970. Depending on the application and the desirable level of security, a programmer may choose alternative ways to seed RNGs. In general, hardware is more capable of generating real random numbers (for example, generate a sequence of bits by sampling the thermal noise of a diode and use this as a seed).

Compliant Solution (Windows)

Wiki Markup
The [{{CryptGenRandom()}}|http://msdn.microsoft.com/en-us/library/aa379942.aspx]does not run the risk of not being properly seeded. The reason for that is that its arguments serve as seeders. From the Microsoft Developer Network {{CryptGenRandom()}} reference \[[MSDN|https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References#AA.CReferences-MSDN]\]:

The CryptGenRandom function fills a buffer with cryptographically random bytes.

Syntax

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

Parameters

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

std::time_t t;
  std::mt19937 engine(std::time(&t));
  
  for (int i = 0; i < 10; ++i) {
    std::cout << engine() << ", ";
  }
}

Compliant Solution

This compliant solution uses std::random_device to generate a random value for seeding the Mersenne Twister engine object. The values generated by std::random_device are nondeterministic random numbers when possible, relying on random number generation devices, such as /dev/random. When such a device is not available, std::random_device may employ a random number engine; however, the initial value generated should have sufficient randomness to serve as a seed value.

Code Block
bgColor#ccccff
langcpp
#include <random>
#include <iostream>

void f() {
  std::random_device dev;
  std::mt19937 engine(dev());
  
  for (int i = 0; i < 10; ++i) {
    std::cout << engine() << ", ";
  }
} 

The output of this example follows.

Code Block
1st run: 3921124303, 1253168518, 1183339582, 197772533, 83186419, 2599073270, 3238222340, 101548389, 296330365, 3335314032, 
2nd run: 2392369099, 2509898672, 2135685437, 3733236524, 883966369, 2529945396, 764222328, 138530885, 4209173263, 1693483251, 
3rd run: 914243768, 2191798381, 2961426773, 3791073717, 2222867426, 1092675429, 2202201605, 850375565, 3622398137, 422940882,
...
Code Block
bgColor#ccccff

HCRYPTPROV   hCryptProv;

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

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

for(int i=0;i<10;i++)
{
	if (!CryptGenRandom(hCryptProv, sizeof(rand_buf), (BYTE*) &rand_buf))
	{
		cerr<<"Error during CryptGenRandom"<<endl;
	}
	else
	{
		cout<<rand_buf.li<<", ";
	}
}

output:
1st run: -1597837311, 906130682, -1308031886, 1048837407, -931041900, -658114613, -1709220953, -1019697289, 1802206541, 406505841,
2nd run: 885904119, -687379556, -1782296854, 1443701916, -624291047, 2049692692, -990451563, -142307804, 1257079211, 897185104,
3rd run: 190598304, -1537409464, 1594174739, -424401916, -1975153474, 826912927, 1705549595, -1515331215, 474951399, 1982500583,
...

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC32

MSC51-CPP

medium

Medium

likely

Likely

low

Low

P18

L1

Automated Detection

...

Compass/ROSE can detect violations of this rule.

Tool

Version

Checker

Description

Astrée

Include Page
Astrée_V
Astrée_V

default-construction
Partially checked
Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC++-MSC51
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

HARDCODED.SEED
MISC.CRYPTO.TIMESEED

Hardcoded Seed in PRNG
Predictable Seed in PRNG

Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C++5041
Klocwork
Include Page
Klocwork_V
Klocwork_V
AUTOSAR.STDLIB.RANDOM.NBR_GEN_DEFAULT_INIT
Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C++: MSC51-CPP

Checks for:

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

Rule partially covered.

Parasoft C/C++test

Include Page
Parasoft_V
Parasoft_V

CERT_CPP-MSC51-a

Properly seed pseudorandom number generators

PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V1057
RuleChecker
Include Page
RuleChecker_V
RuleChecker_V
default-construction
Partially checked

Related Vulnerabilities

Using a predictable seed value, such as the current time, result in numerous vulnerabilities, such as the one described by CVE-2008-1637.

...

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

Other Languages

...

Related Guidelines

...

Properly seed pseudorandom number generators
MITRE CWE

CWE-327, Use of a Broken or Risky Cryptographic Algorithm

CWE-330, Use of Insufficiently Random Values

CWE-337, Predictable Seed in PRNG

Bibliography

[ISO/IEC 9899:2011]Subclause 7.22.2, "Pseudo-random Sequence Generation Functions"
[ISO/IEC 14882-2014]Subclause 26.5, "Random Number Generation"


...

Image Added Image Added Image Added

Bibliography

Wiki Markup
\[[C+\+ Reference|https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References#AA.CReferences-CPPReference]\] Standard C Library
\[[MITRE 07|AA.+C+References#MITRE 07]\] [CWE ID 327 |http://cwe.mitre.org/data/definitions/327.html], "Use of a Broken or Risky Cryptographic Algorithm," [CWE ID 330|http://cwe.mitre.org/data/definitions/330.html], "Use of Insufficiently Random Values"
\[[MSDN|https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References#AA.CReferences-MSDN]\] "[CryptGenRandom Function|http://msdn.microsoft.com/en-us/library/aa379942.aspx]"

MSC31-CPP. Ensure that return values are compared against the proper type      49. Miscellaneous (MSC)      MSC33-CPP. Obey the One Definition Rule