CWE-330 Classe Estável High likelihood

Use of Insufficiently Random Values

This vulnerability occurs when an application uses random values that are not sufficiently unpredictable in security-sensitive operations, making them easier for attackers to guess or calculate.

Definição

What is CWE-330?

This vulnerability occurs when an application uses random values that are not sufficiently unpredictable in security-sensitive operations, making them easier for attackers to guess or calculate.
Many security mechanisms rely on the complete unpredictability of random values. This includes generating session tokens, cryptographic keys, password reset tokens, or initialization vectors. If the random values are predictable—due to a weak random number generator, a small range of possible values, or using a seed that is not random—attackers can guess or brute-force these values, bypassing the intended security control. To prevent this, developers should use cryptographically secure random number generators (CSPRNGs) provided by the platform's security libraries, which are designed to produce values that are statistically random and unpredictable. Avoid using standard, non-cryptographic functions like `rand()` for security purposes. Always ensure the random source has sufficient entropy and that the generated values have a large enough range to withstand brute-force attacks.
Vulnerability Diagram CWE-330
Insufficient Randomness Token generator srand(time()) rand() % 1e6 → predictable non-CSPRNG issued tokens 10:00 → 482917 10:01 → 482918 10:02 → 482919 10:03 → 482920 ? attacker guesses next Reset link forged session hijack 2FA code guessed Predictable PRNG output is brute-forced or anticipated.
Impacto no mundo real

Real-world CVEs caused by CWE-330

  • PHP framework uses mt_rand() function (Marsenne Twister) when generating tokens

  • Cloud application on Kubernetes generates passwords using a weak random number generator based on deployment time.

  • Crypto product uses rand() library function to generate a recovery key, making it easier to conduct brute force attacks.

  • Random number generator can repeatedly generate the same value.

  • Web application generates predictable session IDs, allowing session hijacking.

  • Password recovery utility generates a relatively small number of random passwords, simplifying brute force attacks.

  • Cryptographic key created with a seed based on the system time.

  • Kernel function does not have a good entropy source just after boot.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    This code attempts to generate a unique random identifier for a user's session.

  2. 2

    Because the seed for the PRNG is always the user's ID, the session ID will always be the same. An attacker could thus predict any user's session ID and potentially hijack the session.

  3. 3

    This example also exhibits a Small Seed Space (CWE-339).

  4. 4

    The following code uses a statistical PRNG to create a URL for a receipt that remains active for some period of time after a purchase.

  5. 5

    This code uses the Random.nextInt() function to generate "unique" identifiers for the receipt pages it generates. Because Random.nextInt() is a statistical PRNG, it is easy for an attacker to guess the strings it generates. Although the underlying design of the receipt system is also faulty, it would be more secure if it used a random number generator that did not produce predictable receipt identifiers, such as a cryptographic PRNG.

Exemplo de código vulnerável

Vulnerable PHP

This code attempts to generate a unique random identifier for a user's session.

Vulnerável PHP
function generateSessionID($userID){
  	srand($userID);
  	return rand();
  }
Exemplo de código seguro

Secure pseudo

Seguro pseudo
// Validate, sanitize, or use a safe API before reaching the sink.
function handleRequest(input) {
  const safe = validateAndEscape(input);
  return executeWithGuards(safe);
}
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Lista de verificação de prevenção

How to prevent CWE-330

  • Architecture and Design Use a well-vetted algorithm that is currently considered to be strong by experts in the field, and select well-tested implementations with adequate length seeds. In general, if a pseudo-random number generator is not advertised as being cryptographically secure, then it is probably a statistical PRNG and should not be used in security-sensitive contexts. Pseudo-random number generators can produce predictable numbers if the generator is known and the seed can be guessed. A 256-bit seed is a good starting point for producing a "random enough" number.
  • Implementation Consider a PRNG that re-seeds itself as needed from high quality pseudo-random output sources, such as hardware devices.
  • Testing Use automated static analysis tools that target this type of weakness. Many modern techniques use data flow analysis to minimize the number of false positives. This is not a perfect solution, since 100% accuracy and coverage are not feasible.
  • Architecture and Design / Requirements Use products or modules that conform to FIPS 140-2 [REF-267] to avoid obvious entropy problems. Consult FIPS 140-2 Annex C ("Approved Random Number Generators").
  • Testing Use tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session. These may be more effective than strictly automated techniques. This is especially the case with weaknesses that are related to design and business rules.
Sinais de deteção

How to detect CWE-330

Black Box

Use monitoring tools that examine the software's process as it interacts with the operating system and the network. This technique is useful in cases when source code is unavailable, if the software was not developed by you, or if you want to verify that the build phase did not introduce any new weaknesses. Examples include debuggers that directly attach to the running process; system-call tracing utilities such as truss (Solaris) and strace (Linux); system activity monitors such as FileMon, RegMon, Process Monitor, and other Sysinternals utilities (Windows); and sniffers and protocol analyzers that monitor network traffic. Attach the monitor to the process and look for library functions that indicate when randomness is being used. Run the process multiple times to see if the seed changes. Look for accesses of devices or equivalent resources that are commonly used for strong (or weak) randomness, such as /dev/urandom on Linux. Look for library or system calls that access predictable information such as process IDs and system time.

Automated Static Analysis - Binary or Bytecode SOAR Partial

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Cost effective for partial coverage: ``` Bytecode Weakness Analysis - including disassembler + source code weakness analysis Binary Weakness Analysis - including disassembler + source code weakness analysis

Manual Static Analysis - Binary or Bytecode SOAR Partial

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Cost effective for partial coverage: ``` Binary / Bytecode disassembler - then use manual analysis for vulnerabilities & anomalies

Dynamic Analysis with Manual Results Interpretation SOAR Partial

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Cost effective for partial coverage: ``` Man-in-the-middle attack tool

Manual Static Analysis - Source Code High

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Focused Manual Spotcheck - Focused manual analysis of source Manual Source Code Review (not inspections)

Automated Static Analysis - Source Code SOAR Partial

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Cost effective for partial coverage: ``` Source code Weakness Analyzer Context-configured Source Code Weakness Analyzer

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-330 e abre um PR de correção em menos de 60 segundos.

O Codex Remedium analisa cada commit, identifica esta fraqueza exata e entrega um pull request pronto para revisão com o patch. Sem tickets. Sem transferências.

Perguntas frequentes

Frequently asked questions

O que é o CWE-330?

This vulnerability occurs when an application uses random values that are not sufficiently unpredictable in security-sensitive operations, making them easier for attackers to guess or calculate.

Qual a gravidade do CWE-330?

A MITRE classifica a probabilidade de exploração como Alta — esta fraqueza é ativamente explorada em campo e deve ser priorizada para remediação.

Que linguagens ou plataformas são afetadas pelo CWE-330?

MITRE lists the following affected platforms: Not Technology-Specific.

Como posso prevenir o CWE-330?

Use a well-vetted algorithm that is currently considered to be strong by experts in the field, and select well-tested implementations with adequate length seeds. In general, if a pseudo-random number generator is not advertised as being cryptographically secure, then it is probably a statistical PRNG and should not be used in security-sensitive contexts. Pseudo-random number generators can produce predictable numbers if the generator is known and the seed can be guessed. A 256-bit seed is a…

Como é que o Plexicus deteta e corrige o CWE-330?

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-330 em cada commit. Quando é encontrada uma correspondência, o nosso agente Codex Remedium abre um PR de correção com o código corrigido, testes e um resumo de uma linha para o revisor.

Onde posso saber mais sobre o CWE-330?

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/330.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.

Fraquezas relacionadas

Weaknesses related to CWE-330

CWE-693 Pai

Protection Mechanism Failure

This weakness occurs when software either lacks a necessary security control, implements one that is too weak, or fails to activate an…

CWE-1039 Irmão

Inadequate Detection or Handling of Adversarial Input Perturbations in Automated Recognition Mechanism

This vulnerability occurs when a system uses automated AI or machine learning to classify complex inputs like images, audio, or text, but…

CWE-1248 Irmão

Semiconductor Defects in Hardware Logic with Security-Sensitive Implications

A security-critical hardware component contains physical flaws in its semiconductor material, which can cause it to malfunction and…

CWE-1253 Irmão

Incorrect Selection of Fuse Values

This vulnerability occurs when a hardware security fuse is incorrectly programmed to represent a 'secure' state as logic 0 (unblown). An…

CWE-1269 Irmão

Product Released in Non-Release Configuration

This vulnerability occurs when a product ships to customers while still configured with its pre-production or manufacturing settings,…

CWE-1278 Irmão

Missing Protection Against Hardware Reverse Engineering Using Integrated Circuit (IC) Imaging Techniques

This vulnerability occurs when hardware lacks safeguards against physical inspection, allowing attackers to extract sensitive data by…

CWE-1291 Irmão

Public Key Re-Use for Signing both Debug and Production Code

This vulnerability occurs when the same cryptographic key is used to sign both development/debug software builds and final production…

CWE-1318 Irmão

Missing Support for Security Features in On-chip Fabrics or Buses

This vulnerability occurs when the communication channels (fabrics or buses) within a chip lack built-in or enabled security features,…

CWE-1319 Irmão

Improper Protection against Electromagnetic Fault Injection (EM-FI)

This vulnerability occurs when a hardware device lacks sufficient shielding against electromagnetic interference, allowing attackers to…

Pronto quando você estiver

Pare de pagar por desenvolvedor.
Comece a fechar o ciclo.

O Plexicus é o ASPM nativo de IA que verifica, filtra, corrige, pentesta e explica — de forma autónoma. Programadores ilimitados, repos ilimitados, ações de IA de utilização justa. Nível gratuito real, €269/mo anual quando estiver pronto.