Executar análise estática (SAST) na base de código à procura do padrão inseguro no fluxo de dados.
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.
What is CWE-761?
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."
Trajeto do atacante passo a passo
- 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
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
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
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
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.
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.
#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;} 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.
#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;} 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.
How to detect CWE-761
Executar testes dinâmicos de segurança de aplicações (DAST) contra o endpoint em execução.
Monitorizar os registos em tempo de execução para traços de exceção invulgares, input malformado ou tentativas de contornar a autorização.
Revisão de código: sinalizar qualquer novo código que trate input desta superfície sem usar os ajudantes validados do framework.
O Plexicus deteta automaticamente o CWE-761 e abre um PR de correção em menos de 60 segundos.
O Codex Remedium analisa cada commit, identifica esta fraqueza exata e entrega um pull request pronto para revisão com o patch. Sem tickets. Sem transferências.
Frequently asked questions
O que é o 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.
Qual a gravidade do CWE-761?
A MITRE não publicou uma classificação de probabilidade de exploração para esta fraqueza. Trate-a como impacto médio até o seu modelo de ameaças provar o contrário.
Que linguagens ou plataformas são afetadas pelo CWE-761?
A MITRE não especificou as plataformas afetadas por este CWE — pode aplicar-se à maioria das stacks de aplicações.
Como posso prevenir o 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.
Como é que o Plexicus deteta e corrige o CWE-761?
O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-761 em cada commit. Quando é encontrada uma correspondência, o nosso agente Codex Remedium abre um PR de correção com o código corrigido, testes e um resumo de uma linha para o revisor.
Onde posso saber mais sobre o CWE-761?
A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/761.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.
Weaknesses related to CWE-761
Release of Invalid Pointer or Reference
This vulnerability occurs when a program tries to free a memory resource back to the system but uses an incorrect deallocation method or…
Mismatched Memory Management Routines
This vulnerability occurs when a program uses incompatible functions to allocate and free memory. For example, freeing memory with a…
Pare de pagar por desenvolvedor.
Comece a fechar o ciclo.
O Plexicus é o ASPM nativo de IA que verifica, filtra, corrige, pentesta e explica — de forma autónoma. Programadores ilimitados, repos ilimitados, ações de IA de utilização justa. Nível gratuito real, €269/mo anual quando estiver pronto.