CWE-843 Base Incompleto

Access of Resource Using Incompatible Type ('Type Confusion')

Type confusion occurs when a program creates a resource—like a pointer, object, or variable—with one data type, but later incorrectly accesses it as a different, incompatible type.

Definición

What is CWE-843?

Type confusion occurs when a program creates a resource—like a pointer, object, or variable—with one data type, but later incorrectly accesses it as a different, incompatible type.
This mismatch can cause the program to misinterpret the data in memory, leading to logical errors, crashes, or unexpected behavior because the resource lacks the properties the code expects. In memory-unsafe languages like C and C++, this often results in dangerous out-of-bounds memory access, corrupting data or creating security vulnerabilities. While commonly seen with C/C++ unions when parsing complex data structures, type confusion can appear in many languages. For instance, PHP might fail if an array is passed where a single value is required, and languages like Perl that perform automatic type conversion can also introduce subtle bugs when variables are accessed as unintended types.
Impacto en el mundo real

Real-world CVEs caused by CWE-843

  • Type confusion in CSS sequence leads to out-of-bounds read.

  • Size inconsistency allows code execution, first discovered when it was actively exploited in-the-wild.

  • Improperly-parsed file containing records of different types leads to code execution when a memory location is interpreted as a different object than intended.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    The following code uses a union to support the representation of different types of messages. It formats messages differently, depending on their type.

  2. 2

    The code intends to process the message as a NAME_TYPE, and sets the default message to "Hello World." However, since both buf.name and buf.nameID are part of the same union, they can act as aliases for the same memory location, depending on memory layout after compilation.

  3. 3

    As a result, modification of buf.nameID - an int - can effectively modify the pointer that is stored in buf.name - a string.

  4. 4

    Execution of the program might generate output such as:

  5. 5

    ``` Pointer of name is 10830 Pointer of name is now 10831 Message: ello World ```

Ejemplo de código vulnerable

Vulnerable C

The following code uses a union to support the representation of different types of messages. It formats messages differently, depending on their type.

Vulnerable C
#define NAME_TYPE 1
  #define ID_TYPE 2
  struct MessageBuffer
  {
  	int msgType;
  	union {
  		char *name;
  		int nameID;
  	};
  };
  int main (int argc, char **argv) {
  		struct MessageBuffer buf;
  		char *defaultMessage = "Hello World";
  		buf.msgType = NAME_TYPE;
  		buf.name = defaultMessage;
  		printf("Pointer of buf.name is %p\n", buf.name);
```
/* This particular value for nameID is used to make the code architecture-independent. If coming from untrusted input, it could be any value. */* 
  		
  		buf.nameID = (int)(defaultMessage + 1);
  		printf("Pointer of buf.name is now %p\n", buf.name);
  		if (buf.msgType == NAME_TYPE) {
  		```
  			printf("Message: %s\n", buf.name);
  		}
  		else {
  			printf("Message: Use ID %d\n", buf.nameID);
  		}
  }
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-843

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

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

Type confusion occurs when a program creates a resource—like a pointer, object, or variable—with one data type, but later incorrectly accesses it as a different, incompatible type.

¿Qué gravedad tiene CWE-843?

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

MITRE lists the following affected platforms: C, C++.

¿Cómo puedo prevenir CWE-843?

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

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

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

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.