Skip to content

Insecure Randomness

What does this mean ?

Insecure randomness errors occur when a function that can produce predictable values is used as a source of randomness in security-sensitive context. Standard pseudo-random number generators cannot withstand cryptographic attacks.

What can happen ?

Using a cryptographically weak pseudo-random number generator to generate a security-sensitive value, such as a password, makes it easier for an attacker to predict the value.

Recommendation

  • Use a well-vetted algorithm that is currently considered to be strong by experts in the field, and select well-tested implementations with adequate length seeds.

Sample Code

Vulnerable :

using System;

class ExampleClass
{
    public void ExampleMethod(Random random)
    {
        var sensitiveVariable = random.Next();
    }
}

Non Vulnerable :

using System;
using System.Security.Cryptography;

class ExampleClass
{
    public void ExampleMethod(RandomNumberGenerator randomNumberGenerator, int toExclusive)
    {
        var sensitiveVariable = randomNumberGenerator.GetInt32(toExclusive);
    }
}

Vulnerable :

Import java.util.Random
public static int generateRandomInt(int upperRange)
{
  Random random = new Random();
  return random.nextInt(upperRange);
}

Non Vulnerable :

Import java.security.SecureRandom
public static int generateRandom(int maximumValue)
{
  SecureRandom ranGen = new SecureRandom();
  return ranGen.nextInt(maximumValue);
}

Vulnerable :

$random = rand();
$random2 = mt_rand(0, 99);

Non Vulnerable :

$randomInt = random_int(0,99); // Compliant; generates a cryptographically secure random integer

References