Main Content

CWE Rule 244

Improper Clearing of Heap Memory Before Release ('Heap Inspection')

Since R2023a

Description

Rule Description

Using realloc() to resize buffers that store sensitive information can leave the sensitive information exposed to attack, because it is not removed from memory.

Polyspace Implementation

The rule checker checks for Sensitive heap memory not cleared before release.

Examples

expand all

Issue

This issue occurs when dynamically allocated memory contains sensitive data and you do not clear the data before you free the memory.

Risk

If the memory zone is reallocated, an attacker can still inspect the sensitive data in the old memory zone.

Fix

Before calling free, clear out the sensitive data using memset or SecureZeroMemory.

Example — Sensitive Buffer Freed, Not Cleared
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <pwd.h>

void sensitiveheapnotcleared(const char * my_user) {
    struct passwd* result, pwd;
    long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
    char* buf = (char*) malloc(1024);
    getpwnam_r(my_user, &pwd, buf, bufsize, &result);
    free(buf);  //Noncompliant
}

In this example, the function uses a buffer of passwords and frees the memory before the end of the function. However, the data in the memory is not cleared by using the free command.

Correction — Nullify Data

One possible correction is to write over the data to clear out the sensitive information. This example uses memset to write over the data with zeros.

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <pwd.h>
#include <assert.h>

#define isNull(arr) for(int i=0;i<(sizeof(arr)/sizeof(arr[0]));i++) assert(arr[i]==0)

void sensitiveheapnotcleared(const char * my_user) {
    struct passwd* result, pwd;
    long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
    char* buf = (char*) malloc(1024);

    if (buf) {
        getpwnam_r(my_user, &pwd, buf, bufsize, &result);
        memset(buf, 0, (size_t)1024);
        isNull(buf);
        free(buf); 
    }
}

Check Information

Category: Others

Version History

Introduced in R2023a