CWE-642 Clase Borrador High likelihood

External Control of Critical State Data

This vulnerability occurs when an application stores security-sensitive state data in locations that unauthorized users can access and modify.

Definición

What is CWE-642?

This vulnerability occurs when an application stores security-sensitive state data in locations that unauthorized users can access and modify.
Applications often track critical state information—like authentication status, user permissions, or session details—in client-side locations such as cookies, hidden form fields, URL parameters, environment variables, or configuration files. Attackers can tamper with this data because these storage mechanisms are frequently outside the application's direct control. If the app trusts this manipulated state without validation, it can lead to severe security breaches, such as letting an attacker forge an "authenticated=true" cookie to bypass login. To prevent this, developers must never rely on client-side storage for security-critical decisions without robust server-side verification. Treat all client-provided state data as untrusted input. Implement integrity checks like cryptographic signatures, store sensitive state exclusively on the server using secure sessions, and validate all state transitions on the backend to ensure attackers cannot manipulate application logic or access unauthorized resources.
Impacto en el mundo real

Real-world CVEs caused by CWE-642

  • Mail client stores password hashes for unrelated accounts in a hidden form field.

  • Privileged program trusts user-specified environment variable to modify critical configuration settings.

  • Telnet daemon allows remote clients to specify critical environment variables for the server, leading to code execution.

  • Untrusted search path vulnerability through modified LD_LIBRARY_PATH environment variable.

  • Untrusted search path vulnerability through modified LD_LIBRARY_PATH environment variable.

  • Calendar application allows bypass of authentication by setting a certain cookie value to 1.

  • Setting of a language preference in a cookie enables path traversal attack.

  • Application allows admin privileges by setting a cookie value to "admin."

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    In the following example, an authentication flag is read from a browser cookie, thus allowing for external control of user state data.

  2. 2

    The following code uses input from an HTTP request to create a file name. The programmer has not considered the possibility that an attacker could provide a file name such as "../../tomcat/conf/server.xml", which causes the application to delete one of its own configuration files (CWE-22).

  3. 3

    The following code uses input from a configuration file to determine which file to open and echo back to the user. If the program runs with privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension .txt.

  4. 4

    This program is intended to execute a command that lists the contents of a restricted directory, then performs other actions. Assume that it runs with setuid privileges in order to bypass the permissions check by the operating system.

  5. 5

    This code may look harmless at first, since both the directory and the command are set to fixed values that the attacker can't control. The attacker can only see the contents for DIR, which is the intended program behavior. Finally, the programmer is also careful to limit the code that executes with raised privileges.

Ejemplo de código vulnerable

Vulnerable Java

In the following example, an authentication flag is read from a browser cookie, thus allowing for external control of user state data.

Vulnerable Java
Cookie[] cookies = request.getCookies();
  for (int i =0; i< cookies.length; i++) {
  	Cookie c = cookies[i];
  	if (c.getName().equals("authenticated") && Boolean.TRUE.equals(c.getValue())) {
  		authenticated = true;
  	}
  }
Payload del atacante

However, because the program does not modify the PATH environment variable, the following attack would work:

Payload del atacante
- The user sets the PATH to reference a directory under the attacker's control, such as "/my/dir/".

  - The attacker creates a malicious program called "ls", and puts that program in /my/dir

  - The user executes the program.

  - When system() is executed, the shell consults the PATH to find the ls program

  - The program finds the attacker's malicious program, "/my/dir/ls". It doesn't find "/bin/ls" because PATH does not contain "/bin/".

  - The program executes the attacker's malicious program with the raised privileges.
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-642

  • Architecture and Design Understand all the potential locations that are accessible to attackers. For example, some programmers assume that cookies and hidden form fields cannot be modified by an attacker, or they may not consider that environment variables can be modified before a privileged program is invoked.
  • Architecture and Design Store state information and sensitive data on the server side only. Ensure that the system definitively and unambiguously keeps track of its own state and user state and has rules defined for legitimate state transitions. Do not allow any application user to affect state directly in any way other than through legitimate actions leading to state transitions. If information must be stored on the client, do not do so without encryption and integrity checking, or otherwise having a mechanism on the server side to catch tampering. Use a message authentication code (MAC) algorithm, such as Hash Message Authentication Code (HMAC) [REF-529]. Apply this against the state or sensitive data that has to be exposed, which can guarantee the integrity of the data - i.e., that the data has not been modified. Ensure that a strong hash function is used (CWE-328).
  • Architecture and Design Store state information on the server side only. Ensure that the system definitively and unambiguously keeps track of its own state and user state and has rules defined for legitimate state transitions. Do not allow any application user to affect state directly in any way other than through legitimate actions leading to state transitions.
  • Architecture and Design Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid [REF-1482]. With a stateless protocol such as HTTP, use some frameworks can maintain the state for you. Examples include ASP.NET View State and the OWASP ESAPI Session Management feature. Be careful of language features that provide state support, since these might be provided as a convenience to the programmer and may not be considering security.
  • Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
  • Operation / Implementation When using PHP, configure the application so that it does not use register_globals. During implementation, develop the application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.
  • 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.
  • Testing Use dynamic tools and techniques that interact with the product using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The product's operation may slow down, but it should not become unstable, crash, or generate incorrect results.
Señales de detección

How to detect CWE-642

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-642 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-642?

This vulnerability occurs when an application stores security-sensitive state data in locations that unauthorized users can access and modify.

¿Qué gravedad tiene CWE-642?

MITRE califica la probabilidad de explotación como Alta — esta debilidad se explota activamente en la práctica y debe priorizarse para su remediación.

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

MITRE lists the following affected platforms: Web Server.

¿Cómo puedo prevenir CWE-642?

Understand all the potential locations that are accessible to attackers. For example, some programmers assume that cookies and hidden form fields cannot be modified by an attacker, or they may not consider that environment variables can be modified before a privileged program is invoked. Store state information and sensitive data on the server side only. Ensure that the system definitively and unambiguously keeps track of its own state and user state and has rules defined for legitimate state…

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

El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-642 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-642?

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

Debilidades relacionadas

Weaknesses related to CWE-642

CWE-668 Padre

Exposure of Resource to Wrong Sphere

This vulnerability occurs when an application unintentionally makes a resource accessible to users or systems that should not have…

CWE-1189 Hermano

Improper Isolation of Shared Resources on System-on-a-Chip (SoC)

This vulnerability occurs when a System-on-a-Chip (SoC) fails to properly separate shared hardware resources between secure (trusted) and…

CWE-1282 Hermano

Assumed-Immutable Data is Stored in Writable Memory

This vulnerability occurs when data that should be permanent and unchangeable—like a bootloader, device IDs, or one-time configuration…

CWE-1327 Hermano

Binding to an Unrestricted IP Address

This vulnerability occurs when software or a service is configured to bind to the IP address 0.0.0.0 (or :: in IPv6), which acts as a…

CWE-1331 Hermano

Improper Isolation of Shared Resources in Network On Chip (NoC)

This vulnerability occurs when a Network on Chip (NoC) fails to properly separate its internal, shared resources—like buffers, switches,…

CWE-134 Hermano

Use of Externally-Controlled Format String

This vulnerability occurs when a program uses a format string from an untrusted, external source (like user input, a network packet, or a…

CWE-200 Hermano

Exposure of Sensitive Information to an Unauthorized Actor

This weakness occurs when an application unintentionally reveals sensitive data to someone who shouldn't have access to it.

CWE-374 Hermano

Passing Mutable Objects to an Untrusted Method

This vulnerability occurs when a function receives a direct reference to mutable data, such as an object or array, instead of a safe copy…

CWE-375 Hermano

Returning a Mutable Object to an Untrusted Caller

This vulnerability occurs when a method directly returns a reference to its internal mutable data, allowing untrusted calling code to…

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.