What is the random Python module?
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.
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.