For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/rust-security/insecure-random.md. A documentation index is available at /llms.txt.
This product is not supported for your selected Datadog site. ().

Metadata

ID: rust-security/insecure-random

Language: Rust

Severity: Warning

Category: Security

CWE: 338

Description

Several pseudo-random number generators (PRNGs) in the Rust ecosystem are explicitly not cryptographically secure. Unlike a CSPRNG, their internal state can be recovered by observing a small number of outputs, making them unsuitable in security-sensitive contexts such as generating authentication tokens, API keys, or cryptographic keys.

This rule flags uses of SmallRng, the companion crates rand_pcg, rand_xoshiro, rand_xorshift, and rand_isaac, the third-party crates fastrand, nanorand, and oorandom.

Use rand::random(), rand::rng(), StdRng::from_entropy(), or OsRng instead.

Non-Compliant Code Examples

use rand::rngs::SmallRng;
use rand_pcg::Pcg32;
use rand_xoshiro::Xoshiro256PlusPlus;
use rand::SeedableRng;
use rand::rngs::StdRng;

fn small_rng_uses() {
    let _ = SmallRng::from_entropy();
    let _ = SmallRng::seed_from_u64(0);
}

fn fully_qualified() {
    let _ = rand_pcg::Pcg32::new(0, 0);
    let _ = fastrand::u32(0..100);
}

Compliant Code Examples

use rand::random;
use rand::Rng;
use rand::rngs::OsRng;
use rand::rngs::StdRng;
use rand::SeedableRng;
use rand_chacha::ChaCha20Rng;

fn ok_calls() {
    let _: u32 = rand::random();
    let _: u32 = rand::rng().gen();
    let _: u32 = rand::thread_rng().gen();
    let _ = StdRng::from_entropy();
    let _ = ChaCha20Rng::from_entropy();
    let mut buf = [0u8; 32];
    OsRng.fill(&mut buf);
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security