C & C++

C & C++

Made by DeepSource

Audit required: improper seeding of pseudorandom number generator CXX-A1000

Bug risk
Minor

Improper seeding or failing to seed a pseudorandom number generator (PRNG) can lead to vulnerabilities, especially in security protocols, as an attacker can predict the sequence of random numbers that will be generated in future runs of the program. The solution is to properly seed the PRNG with an initial seed value that is not predictable or controllable by an attacker to ensure that a different sequence of random numbers is generated each time the program runs.

This issue applies only to algorithmic PRNGs that can be seeded, as true random number generators that rely on hardware to produce completely unpredictable results do not need to be and cannot be seeded.

PRNGs should be seeded with non-predictable values such as the current time, process ID, or a random value from a true random number generator. Seeding the PRNG with a fixed value or a predictable value such as 0 is discouraged because it results in a predictable sequence of random numbers.

Bad practice

#include <random>
#include <cstdint>
#include <iostream>

// Both of these functions will repeat random numbers

void generateRand() {
  std::mt19937 generator;
  for (int i = 0; i < 10; ++i) {
    std::cout << generator() << ", ";
  }
}

void generateRandUsingSeed() {
  std::uint_fast32_t seed(1);
  std::mt19937 generator(seed);

  for (int i = 0; i < 10; ++i) {
    std::cout << generator() << ", ";
  }

}

Recommended

#include <random>
#include <iostream>

void generateRand() {
  std::random_device rand_dev;
  std::mt19937 generator(rand_dev());

  for (int i = 0; i < 10; ++i) {
    std::cout << w() << ", ";
  }
}

References