C & C++

C & C++

By DeepSource

Improver seeding of pseudorandom number generator CXX-A1000

Bug risk

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.

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() << ", ";
  }
}