CWE-665 Clase Borrador Medium likelihood

Improper Initialization

This vulnerability occurs when software fails to properly set up a resource before use, or provides incorrect starting values, leaving it in an unpredictable and potentially dangerous state.

Definición

What is CWE-665?

This vulnerability occurs when software fails to properly set up a resource before use, or provides incorrect starting values, leaving it in an unpredictable and potentially dangerous state.
Improper initialization happens when a developer doesn't assign a correct starting value to a variable, object, or system resource. Without this crucial setup step, the resource contains whatever random data was already in memory (often called "garbage values"), leading to erratic and unpredictable behavior when the program tries to use it. From a security perspective, this flaw is critical because many security decisions rely on checking the state of a variable. For example, an authentication flag that isn't explicitly set to "false" might accidentally retain a "true" value from a previous operation, granting unauthorized access. Always explicitly initialize all variables and resources to a known, safe state to eliminate this risk.
Impacto en el mundo real

Real-world CVEs caused by CWE-665

  • chain: an invalid value prevents a library file from being included, skipping initialization of key variables, leading to resultant eval injection.

  • Improper error checking in protection mechanism produces an uninitialized variable, allowing security bypass and code execution.

  • Use of uninitialized memory may allow code execution.

  • Free of an uninitialized pointer leads to crash and possible code execution.

  • OS kernel does not reset a port when starting a setuid program, allowing local users to access the port and gain privileges.

  • Product does not clear memory contents when generating an error message, leading to information leak.

  • Lack of initialization triggers NULL pointer dereference or double-free.

  • Uninitialized variable leads to code execution in popular desktop application.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    Here, a boolean initiailized field is consulted to ensure that initialization tasks are only completed once. However, the field is mistakenly set to true during static initialization, so the initialization code is never reached.

  2. 2

    The following code intends to limit certain operations to the administrator only.

  3. 3

    If the application is unable to extract the state information - say, due to a database timeout - then the $uid variable will not be explicitly set by the programmer. This will cause $uid to be regarded as equivalent to "0" in the conditional, allowing the original user to perform administrator actions. Even if the attacker cannot directly influence the state data, unexpected errors could cause incorrect privileges to be assigned to a user just by accident.

  4. 4

    The following code intends to concatenate a string to a variable and print the string.

  5. 5

    This might seem innocent enough, but str was not initialized, so it contains random memory. As a result, str[0] might not contain the null terminator, so the copy might start at an offset other than 0. The consequences can vary, depending on the underlying memory.

Ejemplo de código vulnerable

Vulnerable Java

Here, a boolean initiailized field is consulted to ensure that initialization tasks are only completed once. However, the field is mistakenly set to true during static initialization, so the initialization code is never reached.

Vulnerable Java
private boolean initialized = true;
  public void someMethod() {
  		if (!initialized) {
```
// perform initialization tasks* 
  				...
  				
  				initialized = true;}
Ejemplo 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 prevención

How to prevent CWE-665

  • Requirements Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, in Java, if the programmer does not explicitly initialize a variable, then the code could produce a compile-time error (if the variable is local) or automatically initialize the variable to the default value for the variable's type. In Perl, if explicit initialization is not performed, then a default value of undef is assigned, which is interpreted as 0, false, or an equivalent value depending on the context in which the variable is accessed.
  • Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
  • Implementation Explicitly initialize all your variables and other data stores, either during declaration or just before the first usage.
  • Implementation Pay close attention to complex conditionals that affect initialization, since some conditions might not perform the initialization.
  • Implementation Avoid race conditions (CWE-362) during initialization routines.
  • Build and Compilation Run or compile your product with settings that generate warnings about uninitialized variables or data.
  • 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.
Señales de detección

How to detect CWE-665

Automated Dynamic Analysis Moderate

This weakness can be detected using dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results. Initialization problems may be detected with a stress-test by calling the software simultaneously from a large number of threads or processes, and look for evidence of any unexpected behavior. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results.

Manual Dynamic Analysis

Identify error conditions that are not likely to occur during normal usage and trigger them. For example, run the program under low memory conditions, run with insufficient privileges or permissions, interrupt a transaction before it is completed, or disable connectivity to basic network services such as DNS. Monitor the software for any unexpected behavior. If you trigger an unhandled exception or similar error that was discovered and handled by the application's environment, it may still indicate unexpected conditions that were not handled by the application itself.

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

Auto-corrección de Plexicus

Plexicus detecta automáticamente CWE-665 y abre un PR de corrección en menos de 60 segundos.

Codex Remedium escanea cada commit, identifica esta debilidad concreta y entrega un pull request listo para revisión con el parche. Sin tickets. Sin traspasos.

Preguntas frecuentes

Frequently asked questions

¿Qué es CWE-665?

This vulnerability occurs when software fails to properly set up a resource before use, or provides incorrect starting values, leaving it in an unpredictable and potentially dangerous state.

¿Qué gravedad tiene CWE-665?

MITRE califica la probabilidad de explotación como Media — la explotación es realista pero suele requerir condiciones específicas.

¿Qué lenguajes o plataformas se ven afectados por CWE-665?

MITRE no ha especificado plataformas afectadas para esta CWE — puede aplicar a la mayoría de los stacks de aplicaciones.

¿Cómo puedo prevenir CWE-665?

Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, in Java, if the programmer does not explicitly initialize a variable, then the code could produce a compile-time error (if the variable is local) or automatically initialize the variable to the default value for the variable's type. In Perl, if explicit initialization is not performed, then a default value of undef is assigned, which is interpreted as 0, false,…

¿Cómo detecta y corrige Plexicus CWE-665?

El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-665 en cada commit. Cuando hay coincidencia, nuestro agente Codex Remedium abre un PR de corrección con el código corregido, las pruebas y un resumen de una línea para el revisor.

¿Dónde puedo aprender más sobre CWE-665?

MITRE publica la definición canónica en https://cwe.mitre.org/data/definitions/665.html. También puedes consultar la documentación de OWASP y NIST para guías relacionadas.

Debilidades relacionadas

Weaknesses related to CWE-665

CWE-664 Padre

Improper Control of a Resource Through its Lifetime

This vulnerability occurs when software fails to properly manage a resource throughout its entire lifecycle—from creation and active use…

CWE-118 Hermano

Incorrect Access of Indexable Resource ('Range Error')

This vulnerability occurs when software fails to properly check the boundaries of an indexed resource, like an array, buffer, or file,…

CWE-1229 Hermano

Creation of Emergent Resource

This vulnerability occurs when a system's normal operations unintentionally create new, exploitable resources that attackers can use to…

CWE-1250 Hermano

Improper Preservation of Consistency Between Independent Representations of Shared State

This vulnerability occurs when a system with multiple independent components (like distributed services or separate hardware units) each…

CWE-1329 Hermano

Reliance on Component That is Not Updateable

This vulnerability occurs when a product depends on a component that cannot be updated or patched to fix security flaws or critical bugs.

CWE-221 Hermano

Information Loss or Omission

This weakness occurs when an application fails to log critical security events or records them inaccurately, which can misguide security…

CWE-372 Hermano

Incomplete Internal State Distinction

This vulnerability occurs when an application fails to accurately track its own operational state. The system incorrectly assumes it's in…

CWE-400 Hermano

Uncontrolled Resource Consumption

This vulnerability occurs when an application fails to properly manage a finite resource, allowing an attacker to exhaust it and cause a…

CWE-404 Hermano

Improper Resource Shutdown or Release

This vulnerability occurs when a program fails to properly close or release a system resource—like a file handle, database connection, or…

Listo cuando tú lo estés

Deja de pagar por desarrollador.
Empieza a cerrar el bucle.

Plexicus es el ASPM nativo de IA que escanea, filtra, corrige, pentestea y explica — de forma autónoma. Desarrolladores ilimitados, repos ilimitados, acciones de IA de uso justo. Nivel gratuito real, €269/mo anual cuando estés listo.