CWE-761 Variante Incompleto

Free of Pointer not at Start of Buffer

This vulnerability occurs when a program incorrectly frees a memory pointer that no longer points to the beginning of the allocated heap buffer, often due to pointer arithmetic.

Definición

What is CWE-761?

This vulnerability occurs when a program incorrectly frees a memory pointer that no longer points to the beginning of the allocated heap buffer, often due to pointer arithmetic.
This issue typically happens when you allocate memory using functions like `malloc()`, `calloc()`, or `realloc()`, and then later modify the pointer—for example, by incrementing it to traverse a data structure. When you later pass this offset pointer to `free()`, the memory manager cannot correctly identify the original memory block's metadata, leading to heap corruption. This corruption can cause immediate crashes, unpredictable behavior, or even create opportunities for attackers to manipulate program data or execution flow. To prevent this, always ensure you free the exact pointer returned by the allocation function, or use a separate tracking variable to preserve the original starting address.
Impacto en el mundo real

Real-world CVEs caused by CWE-761

  • function "internally calls 'calloc' and returns a pointer at an index... inside the allocated buffer. This led to freeing invalid memory."

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    In this example, the programmer dynamically allocates a buffer to hold a string and then searches for a specific character. After completing the search, the programmer attempts to release the allocated memory and return SUCCESS or FAILURE to the caller. Note: for simplification, this example uses a hard-coded "Search Me!" string and a constant string length of 20.

  2. 2

    However, if the character is not at the beginning of the string, or if it is not in the string at all, then the pointer will not be at the start of the buffer when the programmer frees it.

  3. 3

    Instead of freeing the pointer in the middle of the buffer, the programmer can use an indexing pointer to step through the memory or abstract the memory calculations by using array indexing.

  4. 4

    This code attempts to tokenize a string and place it into an array using the strsep function, which inserts a \0 byte in place of whitespace or a tab character. After finishing the loop, each string in the AP array points to a location within the input string.

  5. 5

    Since strsep is not allocating any new memory, freeing an element in the middle of the array is equivalent to free a pointer in the middle of inputstring.

Ejemplo de código vulnerable

Vulnerable C

In this example, the programmer dynamically allocates a buffer to hold a string and then searches for a specific character. After completing the search, the programmer attempts to release the allocated memory and return SUCCESS or FAILURE to the caller. Note: for simplification, this example uses a hard-coded "Search Me!" string and a constant string length of 20.

Vulnerable C
#define SUCCESS (1)
  #define FAILURE (0)
  int contains_char(char c){
  		char *str;
  		str = (char*)malloc(20*sizeof(char));
  		strcpy(str, "Search Me!");
  		while( *str != NULL){
  				if( *str == c ){
```
/* matched char, free string and return success */* 
  						free(str);
  						return SUCCESS;}
  				
  				 */* didn't match yet, increment pointer and try next char */* 
  				
  				str = str + 1;}
  		
  		 */* we did not match the char in the string, free mem and return failure */* 
  		
  		free(str);
  		return FAILURE;}
Ejemplo de código seguro

Secure C

Instead of freeing the pointer in the middle of the buffer, the programmer can use an indexing pointer to step through the memory or abstract the memory calculations by using array indexing.

Seguro C
#define SUCCESS (1)
  #define FAILURE (0)
  int cointains_char(char c){
  		char *str;
  		int i = 0;
  		str = (char*)malloc(20*sizeof(char));
  		strcpy(str, "Search Me!");
  		while( i < strlen(str) ){
  				if( str[i] == c ){
```
/* matched char, free string and return success */* 
  						free(str);
  						return SUCCESS;}
  				
  				 */* didn't match yet, increment pointer and try next char */* 
  				
  				i = i + 1;}
  		
  		 */* we did not match the char in the string, free mem and return failure */* 
  		
  		free(str);
  		return FAILURE;}
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-761

  • Implementation When utilizing pointer arithmetic to traverse a buffer, use a separate variable to track progress through memory and preserve the originally allocated address for later freeing.
  • Implementation When programming in C++, consider using smart pointers provided by the boost library to help correctly and consistently manage memory.
  • 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. For example, glibc in Linux provides protection against free of invalid pointers.
  • Architecture and Design Use a language that provides abstractions for memory allocation and deallocation.
  • Testing Use a tool that dynamically detects memory management problems, such as valgrind.
Señales de detección

How to detect CWE-761

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

This vulnerability occurs when a program incorrectly frees a memory pointer that no longer points to the beginning of the allocated heap buffer, often due to pointer arithmetic.

¿Qué gravedad tiene CWE-761?

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

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

When utilizing pointer arithmetic to traverse a buffer, use a separate variable to track progress through memory and preserve the originally allocated address for later freeing. When programming in C++, consider using smart pointers provided by the boost library to help correctly and consistently manage memory.

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

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

MITRE publica la definición canónica en https://cwe.mitre.org/data/definitions/761.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.