CWE-440 Base Borrador

Expected Behavior Violation

This weakness occurs when a software component, such as a function, API, or feature, fails to act as documented or intended. The system's actual behavior deviates from its promised specification,…

Definición

What is CWE-440?

This weakness occurs when a software component, such as a function, API, or feature, fails to act as documented or intended. The system's actual behavior deviates from its promised specification, leading to unpredictable results.
At its core, this violation is a trust issue between the developer and the component's interface. When you call a function or use an API, you rely on its documented contract—what inputs it accepts, what processing it performs, and what outputs or side effects it guarantees. If the component silently breaks this contract, your application logic can fail, security assumptions can be invalidated, and the entire system's stability is compromised. This often stems from ambiguous documentation, implementation bugs, or unintended side effects that the spec didn't account for. For developers, mitigating this requires a proactive approach. First, treat specifications as critical requirements, not suggestions. Implement rigorous input validation and error handling even for 'trusted' components. Second, employ defensive programming practices: write comprehensive unit and integration tests that verify both the happy path and edge cases against the documented behavior. Fuzz testing can be particularly effective in uncovering unexpected behaviors. Finally, when designing your own APIs, ensure your specifications are precise, complete, and tested, as unclear docs are a primary cause of downstream violations.
Impacto en el mundo real

Real-world CVEs caused by CWE-440

  • Program uses large timeouts on unconfirmed connections resulting from inconsistency in linked lists implementations.

  • "strncpy" in Linux kernel acts different than libc on x86, leading to expected behavior difference - sort of a multiple interpretation error?

  • Buffer overflow in product stems the use of a third party library function that is expected to have internal protection against overflows, but doesn't.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    The provided code is extracted from the Control and Status Register (CSR), csr_regfile, module within the Hack@DAC'21 OpenPiton System-on-Chip (SoC). This module is designed to implement CSR registers in accordance with the RISC-V specification. The mie (machine interrupt enable) register is a 64-bit register [REF-1384], where bits correspond to different interrupt sources. As the name suggests, mie is a machine-level register that determines which interrupts are enabled. Note that in the example below the mie_q and mie_d registers represent the conceptual mie reigster in the RISC-V specification. The mie_d register is the value to be stored in the mie register while the mie_q register holds the current value of the mie register [REF-1385].

  2. 2

    The mideleg (machine interrupt delegation) register, also 64-bit wide, enables the delegation of specific interrupt sources from machine privilege mode to lower privilege levels. By setting specific bits in the mideleg register, the handling of certain interrupts can be delegated to lower privilege levels without engaging the machine-level privilege mode. For example, in supervisor mode, the mie register is limited to a specific register called the sie (supervisor interrupt enable) register. If delegated, an interrupt becomes visible in the sip (supervisor interrupt pending) register and can be enabled or blocked using the sie register. If no delegation occurs, the related bits in sip and sie are set to zero.

  3. 3

    The sie register value is computed based on the current value of mie register, i.e., mie_q, and the mideleg register.

  4. 4

    The above code snippet illustrates an instance of a vulnerable implementation of the sie register update logic, where users can tamper with the mie_d register value through the utval (user trap value) register. This behavior violates the RISC-V specification.

  5. 5

    The code shows that the value of utval, among other signals, is used in updating the mie_d value within the sie update logic. While utval is a register accessible to users, it should not influence or compromise the integrity of sie. Through manipulation of the utval register, it becomes feasible to manipulate the sie register's value. This opens the door for potential attacks, as an adversary can gain control over or corrupt the sie value. Consequently, such manipulation empowers an attacker to enable or disable critical supervisor-level interrupts, resulting in various security risks such as privilege escalation or denial-of-service attacks.

Ejemplo de código vulnerable

Vulnerable Verilog

The sie register value is computed based on the current value of mie register, i.e., mie_q, and the mideleg register.

Vulnerable Verilog
module csr_regfile #(...)(...);
 ...
 // ---------------------------
 // CSR Write and update logic
 // ---------------------------
 ...

```
   if (csr_we) begin
  	 unique case (csr_addr.address)
  	 ...
  		 riscv::CSR_SIE: begin
  			 // the mideleg makes sure only delegate-able register
  			 //(and therefore also only implemented registers) are written
```
mie_d = (mie_q & ~mideleg_q) | (csr_wdata & mideleg_q) | utval_q;** 
  			 end
  		 ...
  		 endcase
  	 end
   endmodule
Ejemplo de código seguro

Secure Verilog

A fix to this issue is to remove the utval from the right-hand side of the assignment. That is the value of the mie_d should be updated as shown in the good code example [REF-1386].

Seguro Verilog
module csr_regfile #(...)(...);
 ...
 // ---------------------------
 // CSR Write and update logic
 // ---------------------------
 ...

```
   if (csr_we) begin
  	 unique case (csr_addr.address)
  	 ...
  		 riscv::CSR_SIE: begin
  			 // the mideleg makes sure only delegate-able register
  			 //(and therefore also only implemented registers) are written
```
mie_d = (mie_q & ~mideleg_q) | (csr_wdata & mideleg_q);** 
  			 end
  		 ...
  		 endcase
  	 end
   endmodule
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-440

  • Architecture Use safe-by-default frameworks and APIs that prevent the unsafe pattern from being expressible.
  • Implementation Validate input at trust boundaries; use allowlists, not denylists.
  • Implementation Apply the principle of least privilege to credentials, file paths, and runtime permissions.
  • Testing Cover this weakness in CI: SAST rules + targeted unit tests for the data flow.
  • Operation Monitor logs for the runtime signals listed in the next section.
Señales de detección

How to detect CWE-440

SAST High

Ejecuta análisis estático (SAST) sobre el código buscando el patrón inseguro en el flujo de datos.

DAST Moderate

Ejecuta pruebas dinámicas de seguridad de aplicaciones (DAST) contra el endpoint en vivo.

Runtime Moderate

Vigila los logs en tiempo de ejecución para detectar trazas de excepción inusuales, entradas malformadas o intentos de bypass de autorización.

Code review Moderate

Revisión de código: marca cualquier código nuevo que maneje entrada desde esta superficie sin usar los helpers validados del framework.

Auto-corrección de Plexicus

Plexicus detecta automáticamente CWE-440 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-440?

This weakness occurs when a software component, such as a function, API, or feature, fails to act as documented or intended. The system's actual behavior deviates from its promised specification, leading to unpredictable results.

¿Qué gravedad tiene CWE-440?

MITRE no ha publicado una calificación de probabilidad de explotación para esta debilidad. Trátala como de impacto medio hasta que tu modelo de amenazas demuestre lo contrario.

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

MITRE lists the following affected platforms: ICS/OT.

¿Cómo puedo prevenir CWE-440?

Use safe-by-default frameworks, validate untrusted input at trust boundaries, and apply the principle of least privilege. Cover the data-flow signature in CI with SAST.

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

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

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

Debilidades relacionadas

Weaknesses related to CWE-440

CWE-684 Padre

Incorrect Provision of Specified Functionality

This weakness occurs when software behaves differently than its documented specifications, which can mislead users and create security…

CWE-1245 Hermano

Improper Finite State Machines (FSMs) in Hardware Logic

This vulnerability occurs when hardware logic contains flawed Finite State Machines (FSMs). Attackers can exploit these design errors to…

CWE-392 Hermano

Missing Report of Error Condition

This vulnerability occurs when a system fails to properly signal that an error has happened. Instead of returning a clear error code,…

CWE-393 Hermano

Return of Wrong Status Code

This vulnerability occurs when a function returns an inaccurate status code or value that misrepresents the actual outcome of an…

CWE-446 Hermano

UI Discrepancy for Security Feature

This vulnerability occurs when a user interface incorrectly displays a security feature as active or properly configured, misleading users…

CWE-451 Hermano

User Interface (UI) Misrepresentation of Critical Information

This vulnerability occurs when a user interface fails to accurately display or highlight crucial information, potentially misleading users…

CWE-912 Hermano

Hidden Functionality

Hidden functionality refers to undocumented features, commands, or code within a product that are not part of its official specification…

CWE-1434 Hijo

Insecure Setting of Generative AI/ML Model Inference Parameters

This vulnerability occurs when a generative AI or ML model is deployed with inference parameters that are too permissive, causing it 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.