...
Failing to follow this recommendation has led to real-world vulnerabilities. For example, freeing memory in different modules resulted in a vulnerability in MIT Kerberos 5 MITKRB5-SA-2004-002 . The MIT Kerberos 5 code , in this case , contained error-handling logic, which freed memory allocated by the ASN.1 decoders if pointers to the allocated memory were non-null. However, if a detectable error occured, the ASN.1 decoders freed the memory that they had allocated. When some library functions received errors from the ASN.1 decoders, they also attempted to free, resulting in a double-free vulnerability.
...
This non-compliant code example illustrates a double-free vulnerability resulting from memory being allocated and freed at differing levels of abstraction. In this example, memory for the list
array is allocatd in the process_list()
function. The array is then passed to the verify_list()
function that performs error checking on the size of the list. If the size of the list is below a minimum size, the memory allocated to the list is freed , and the function returns to the caller. The calling function then frees this same memory again, resulting in a double-free and potentially exploitable vulnerability.
...
The call to free memory in the verify_list()
function takes place in a subroutine of the process_list()
function, at a different level of abstraction from the allocation, resulting in a violation of this recommendation. The memory deallocation also occurs in error handling code, which is frequently not as well tested as "green - paths" through the code.
Compliant Solution
...