Variant · Low-Medium

CWE-761: Free of Pointer not at Start of Buffer

The product calls free() on a pointer to a memory resource that was allocated on the heap, but the pointer is not at the start of the buffer.

CWE-761 · Variant Level ·1 CVEs ·4 Mitigations

Description

The product calls free() on a pointer to a memory resource that was allocated on the heap, but the pointer is not at the start of the buffer.

This can cause the product to crash, or in some cases, modify critical program variables or execute code. This weakness often occurs when the memory is allocated explicitly on the heap with one of the malloc() family functions and free() is called, but pointer arithmetic has caused the pointer to be in the interior or end of the buffer.

Potential Impact

Integrity, Availability, Confidentiality

Modify Memory, DoS: Crash, Exit, or Restart, Execute Unauthorized Code or Commands

Demonstrative Examples

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.
Bad
#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;
                     }
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.
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.
Good
#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;
                     }
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.
Bad
char **ap, *argv[10], *inputstring;for (ap = argv; (*ap = strsep(&inputstring, " \t")) != NULL;)
                        if (**ap != '\0')if (++ap >= &argv[10])break;
                           
                        
                     
                     /.../free(ap[4]);
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.
Consider the following code in the context of a parsing application to extract commands out of user data. The intent is to parse each command and add it to a queue of commands to be executed, discarding each malformed entry.
Bad
//hardcode input length for simplicity
                     char* input = (char*) malloc(40*sizeof(char));char *tok;char* sep = " \t";
                     get_user_input( input );
                     
                     /* The following loop will parse and process each token in the input string */
                     
                     tok = strtok( input, sep);while( NULL != tok ){
                        if( isMalformed( tok ) ){
                              
                                 
                                 /* ignore and discard bad data */
                                 free( tok );
                           }else{add_to_command_queue( tok );}tok = strtok( NULL, sep));
                     }
While the above code attempts to free memory associated with bad commands, since the memory was all allocated in one chunk, it must all be freed together.
One way to fix this problem would be to copy the commands into a new memory location before placing them in the queue. Then, after all commands have been processed, the memory can safely be freed.
Good
//hardcode input length for simplicity
                     char* input = (char*) malloc(40*sizeof(char));char *tok, *command;char* sep = " \t";
                     get_user_input( input );
                     
                     /* The following loop will parse and process each token in the input string */
                     
                     tok = strtok( input, sep);while( NULL != tok ){
                        if( !isMalformed( command ) ){
                              
                                 
                                 /* copy and enqueue good data */
                                 command = (char*) malloc( (strlen(tok) + 1) * sizeof(char) );strcpy( command, tok );add_to_command_queue( command );
                           }tok = strtok( NULL, sep));
                     }
                     free( input )

Mitigations & Prevention

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.

Detection Methods

  • Automated Dynamic Analysis Moderate — Use tools that are integrated during compilation to insert runtime error-checking mechanisms related to memory safety errors, such as AddressSanitizer (ASan) for C/C++ [REF-1518] or valgrind [REF-480].

Real-World CVE Examples

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

Taxonomy Mappings

  • Software Fault Patterns: SFP12 — Faulty Memory Release

Frequently Asked Questions

What is CWE-761?

CWE-761 (Free of Pointer not at Start of Buffer) is a software weakness identified by MITRE's Common Weakness Enumeration. It is classified as a Variant-level weakness. The product calls free() on a pointer to a memory resource that was allocated on the heap, but the pointer is not at the start of the buffer.

How can CWE-761 be exploited?

Attackers can exploit CWE-761 (Free of Pointer not at Start of Buffer) to modify memory, dos: crash, exit, or restart, execute unauthorized code or commands. This weakness is typically introduced during the Implementation phase of software development.

How do I prevent CWE-761?

Key mitigations include: 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.

What is the severity of CWE-761?

CWE-761 is classified as a Variant-level weakness (Low-Medium abstraction). It has been observed in 1 real-world CVEs.