# Insecure Randomness

#### Tools recognizing this:

<kbd>Opengrep</kbd> <kbd>Fortify</kbd> <kbd>Checkmarx</kbd> <kbd>SonarQube</kbd> <kbd>Snyk</kbd> <kbd>Semgrep</kbd> <kbd>CodeQL</kbd>

## What is Insecure Randomness and How Does it Work?

Insecure Randomness is a security vulnerability that occurs when applications use weak random number generators for security-critical operations. It happens when developers use predictable random number generation methods instead of cryptographically secure alternatives.

Using weak random number generators can lead to various security issues:

* Predictable session IDs or tokens
* Weak cryptographic keys
* Guessable password reset codes
* Vulnerable temporary file names
* Exploitable game mechanics or gambling systems

This guide covers Insecure Randomness vulnerabilities, examples, prevention methods, and how to implement secure random number generation using real-world techniques.

## One Simple Insecure Randomness Example

Consider this classic example of generating a session token:

{% code overflow="wrap" %}

```
String sessionToken = String.valueOf(Math.random() * 1000000);
```

{% endcode %}

An attacker could predict the next token because:

<mark style="color:red;">`Math.random()`</mark> <mark style="color:red;">uses a weak pseudo-random number generator</mark>

The resulting tokens would be:

<kbd>Using Math.random():</kbd> <kbd><mark style="color:red;">Predictable sequence based on seed<mark style="color:red;"></kbd>

This allows attackers to potentially guess valid session tokens and hijack user sessions.

## Insecure Randomness Prevention Methods: How to Fix Your Code

The most efficient way to fix an Insecure Randomness issue in your code is using cryptographically secure random number generators.

Secure random number generators use entropy from the system to generate unpredictable values, making them suitable for security-critical operations. They ensure that generated values cannot be predicted even if an attacker knows previous values.

### Code Samples

{% tabs %}
{% tab title="Java" %}
**Vulnerable Code**

<pre class="language-java"><code class="lang-java">Random random = new Random();
String token = String.valueOf(<a data-footnote-ref href="#user-content-fn-1">random.nextInt(1000000)</a>);
</code></pre>

**Fixed Code**

```java
SecureRandom secureRandom = new SecureRandom();
String token = String.valueOf(secureRandom.nextInt(1000000));
```

**Fix Explanation**

The vulnerable code uses java.util.Random which is not cryptographically secure.The fix uses SecureRandom which provides cryptographically strong random numbers.SecureRandom uses the operating system's entropy pool for better randomness.The generated values are suitable for security-sensitive operations.
{% endtab %}

{% tab title="JavaScript" %}
**Vulnerable Code**

```javascript
const token = Math.floor(Math.random() * 1000000);
const sessionId = token.toString();
```

**Fixed Code**

```javascript
const crypto = require('crypto');
const token = crypto.randomInt(1000000);
const sessionId = token.toString();
```

**Fix Explanation**

The vulnerable code uses Math.random() which is not cryptographically secure.The fix uses the crypto.randomInt() method from Node's crypto module.The crypto module provides cryptographically strong random numbers.The generated values are suitable for security-sensitive operations.
{% endtab %}

{% tab title="Python" %}
**Vulnerable Code**

```python
import random
token = random.randint(0, 1000000)
session_id = str(token)
```

**Fixed Code**

```python
import secrets
token = secrets.randbelow(1000000)
session_id = str(token)
```

**Fix Explanation**

The vulnerable code uses random.randint which is not cryptographically secure.The fix uses the secrets module which is designed for generating cryptographic secrets.The secrets module provides methods specifically for security-sensitive operations.The generated values are suitable for tokens, keys, and other secure values.
{% endtab %}

{% tab title="C#" %}
**Vulnerable Code**

```csharp
Random random = new Random();
string token = random.Next(1000000).ToString();
```

**Fixed Code**

```csharp
using System.Security.Cryptography;
string token = RandomNumberGenerator.GetInt32(1000000).ToString();
```

**Fix Explanation**

The vulnerable code uses System.Random which is not cryptographically secure.The fix uses RandomNumberGenerator from System.Security.Cryptography.RandomNumberGenerator provides cryptographically strong random numbers.The generated values are suitable for security-sensitive operations.
{% endtab %}

{% tab title="PHP" %}
**Vulnerable Code**

```php
$token = rand(0, 1000000);
$sessionId = strval($token);
```

**Fixed Code**

```php
$token = random_int(0, 1000000);
$sessionId = strval($token);
```

**Fix Explanation**

The vulnerable code uses rand() which is not cryptographically secure.The fix uses random\_int() which generates cryptographically secure random integers.random\_int() uses the operating system's source of randomness.The generated values are suitable for security-sensitive operations.
{% endtab %}

{% tab title="C/C++" %}
**Vulnerable Code**

```cpp
srand(time(NULL));
int token = rand() % 1000000;
string sessionId = to_string(token);
```

**Fixed Code**

```cpp
#include <random>
std::random_device rd;
std::uniform_int_distribution<int> dist(0, 999999);
int token = dist(rd);
string sessionId = to_string(token);
```

**Fix Explanation**

The vulnerable code uses rand() which is not cryptographically secure.The fix uses std::random\_device which provides high-quality random numbers.random\_device uses hardware entropy sources when available.The generated values are suitable for security-sensitive operations.
{% endtab %}
{% endtabs %}

## Need more help in preventing Insecure Randomness?

[Mobb](https://mobb.ai) supports fixing many forms of Insecure Randomness vulnerabilities, and can mitigate your issues in batch.

Start now for free at [app.mobb.ai](https://app.mobb.ai)

### We’d love your feedback!

We’re excited to hear your thoughts and ideas about fixing vulnerabilities.

[Book a meeting](https://calendly.com/mobbai/demo) or [Contact us](https://content.mobb.ai/contact) if you have any corrections, questions or suggestions.

[^1]: This is the vulnerable part


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mobb.ai/mobb-user-docs/fixing-guides/insecure-randomness-fix-guide.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
