Predictable Randomness

Predictable randomness in C#

Description

System.Random can produce predictable session IDs, authentication codes and tokens.

Potential impact

Someone who guesses a valid value may gain access to a user’s session or bypass an authentication check.

Remediation

Use a cryptographic generator such as RandomNumberGenerator for authentication values and keys. For nonces, follow the algorithm’s length and uniqueness requirements.

Examples

Before

csharp
var token = new Random().Next();

After

csharp
var token = RandomNumberGenerator.GetBytes(32);

RandomNumberGenerator.GetBytes(32) returns 32 random bytes for the token.

References