Skip to main content

Insecure Generation of Random Numbers

Need

Prevent predictable sequences of random numbers

Context

  • Usage of Elixir (1.11 and above) for building scalable and fault-tolerant applications
  • Usage of Erlang/OTP for building scalable and fault-tolerant systems

Description

Non compliant code

defmodule MyApp.TokenGenerator do
def generate_token do
:random.seed(:erlang.now())
:random.uniform(100000)
end
end

This code is vulnerable as it uses the :random.uniform function from Erlang which is not suitable for generating secure random numbers. Also, it uses :erlang.now to seed the random number generator, which can be predictable and hence lead to generating predictable random numbers.

Steps

  • Avoid using the :random.uniform function for generating secure random numbers.
  • Use :crypto.strong_rand_bytes function for generating secure random numbers.
  • Use Base.encode16 function to convert the binary data to a hexadecimal string if needed.

Compliant code

defmodule MyApp.TokenGenerator do
def generate_token do
:crypto.strong_rand_bytes(16) |> Base.encode16()
end
end

This secure code uses the :crypto.strong_rand_bytes function for generating a binary string of random bytes, which is then converted into a hexadecimal string using Base.encode16. This ensures the generation of secure random numbers.

References