Codiga has joined Datadog!

Read the Blog·

Interested in our Static Analysis?

Sign up
← All posts
Julien Delange Tuesday, October 25, 2022

Python: random is not so random (CWE-330)

Share

AUTHOR

Julien Delange, Founder and CEO

Julien is the CEO of Codiga. Before starting Codiga, Julien was a software engineer at Twitter and Amazon Web Services.

Julien has a PhD in computer science from Universite Pierre et Marie Curie in Paris, France.

See all articles

What is the random Python module?

The Python random module generates pseudo-random numbers. The function relies on the Mersenne Twister number generator that is known to be reliable and fast.

Why the Python module might be unsafe?

The problem with the random Python module is that it generates "pseudo" random numbers, which are not really so random. This might be okay is you are just looking for a random value to put into your application but it may also be an important vulnerability if you use this value for security or crytographic purposes.

In fact, if the value is "pseudo-random`, it means that somebody else (e.g. an attacker) may guess the value. If the value is a secret and your system relies on it, using a "pseudo-random" value may introduce a vulnerability.

How to avoid security or safety issues coming from the random Python module?

When generating a random value for security purposes, the secrets Python module should be prefered.

For example, the following call:

import random

random.random()

could be replaced by the following call (read carefully the randbelow documentation for the arguments values to pass).

import secrets

secrets.randbelow(100) / 100

Automatically detect invalid uses of the Python random module

Codiga provides IDE plugins and integrations with GitHub, GitLab, or Bitbucket to detect unsafe uses of the random module and automatically fix it. The Codiga static code analysis detects invalid use of the random module directly in your IDE or code reviews.

There are multiple rules in the Codiga engine that checks for invalid uses of the random module, there is an example of a rule that detects SQL invalid uses of the Python random module.

Detect random() usage

To use this rule consistently, all you need to do is to install the integration in your IDE (for VS Code or JetBrains) or code management system and add a codiga.yml file at the root of your profile with the following content:

rulesets:
  - python-security

It will then check all your Python code against 100+ rules that detect unsafe and insecure code and suggests fixes for each of them.

More resources

Are you interested in Datadog Static Analysis?

Sign up