CWE-338 Base Rascunho Medium likelihood

Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)

This vulnerability occurs when software uses a pseudo-random number generator (PRNG) that is not cryptographically strong for security-sensitive operations, such as generating keys, tokens, or…

Definição

What is CWE-338?

This vulnerability occurs when software uses a pseudo-random number generator (PRNG) that is not cryptographically strong for security-sensitive operations, such as generating keys, tokens, or initialization vectors.
Using a non-cryptographic PRNG in a security context can expose your application to attacks. Attackers can often predict or reproduce the generated numbers, allowing them to forge sessions, decrypt data, or bypass authentication. This happens because these generators prioritize speed and efficiency over the unpredictability required for secure cryptography. Developers sometimes choose weaker PRNGs for performance reasons or because they are readily available in standard libraries. However, features that make these PRNGs efficient—like small internal states or deterministic seeding—are the same features that make them easy to break. For any security-related function, you must use a cryptographically secure pseudo-random number generator (CSPRNG) designed to withstand such analysis.
Impacto no mundo real

Real-world CVEs caused by CWE-338

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

  • 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.

  • SSL library uses a weak random number generator that only generates 65,536 unique keys.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    Identificar um caminho de código que trata input não confiável sem validação.

  2. 2

    Criar um payload que explora o comportamento inseguro — injeção, traversal, overflow ou abuso de lógica.

  3. 3

    Entregar o payload através de um pedido normal e observar a reação da aplicação.

  4. 4

    Iterar até que a resposta exponha dados, execute código do atacante ou escale privilégios.

Exemplo de código vulnerável

Vulnerable Java

Both of these examples use a statistical PRNG seeded with the current value of the system clock to generate a random number:

Vulnerável Java
Random random = new Random(System.currentTimeMillis());
  int accountID = random.nextInt();
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-338

  • Implementation Use functions or hardware which use a hardware-based random number generation for all crypto. This is the recommended solution. Use CyptGenRandom on Windows, or hw_rand() on Linux.
Sinais de deteção

How to detect CWE-338

Automated Static Analysis High

Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-338 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-338?

This vulnerability occurs when software uses a pseudo-random number generator (PRNG) that is not cryptographically strong for security-sensitive operations, such as generating keys, tokens, or initialization vectors.

Qual a gravidade do CWE-338?

A MITRE classifica a probabilidade de exploração como Média — a exploração é realista mas normalmente requer condições específicas.

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

A MITRE não especificou as plataformas afetadas por este CWE — pode aplicar-se à maioria das stacks de aplicações.

Como posso prevenir o CWE-338?

Use functions or hardware which use a hardware-based random number generation for all crypto. This is the recommended solution. Use CyptGenRandom on Windows, or hw_rand() on Linux.

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

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-338 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-338?

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

Fraquezas relacionadas

Weaknesses related to CWE-338

CWE-330 Pai

Use of Insufficiently Random Values

This vulnerability occurs when an application uses random values that are not sufficiently unpredictable in security-sensitive operations,…

CWE-1204 Irmão

Generation of Weak Initialization Vector (IV)

This vulnerability occurs when software uses a weak or predictable Initialization Vector (IV) for cryptographic operations. Many…

CWE-1241 Irmão

Use of Predictable Algorithm in Random Number Generator

This vulnerability occurs when a device or application relies on a predictable algorithm to generate pseudo-random numbers, making the…

CWE-331 Irmão

Insufficient Entropy

This vulnerability occurs when a system's random number generator or algorithm lacks sufficient unpredictability, creating patterns or…

CWE-334 Irmão

Small Space of Random Values

This vulnerability occurs when a system uses a random number generator that produces too few possible values. Attackers can easily predict…

CWE-335 Irmão

Incorrect Usage of Seeds in Pseudo-Random Number Generator (PRNG)

This vulnerability occurs when a Pseudo-Random Number Generator (PRNG) is used, but its initial seed value is not handled securely or…

CWE-340 Irmão

Generation of Predictable Numbers or Identifiers

This vulnerability occurs when a system creates numbers or identifiers that are too easy to guess, undermining security mechanisms that…

CWE-344 Irmão

Use of Invariant Value in Dynamically Changing Context

This vulnerability occurs when code uses a fixed, unchanging value (like a hardcoded string, number, or reference) in a situation where…

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.