Hacker News new | ask | show | jobs
by muricula 1666 days ago
Zeroing out freed memory in no way prevents UAFs. Consider what happens if the memory which was freed was recycled for a new allocation? Maybe an example will help make it clearer? This is in pseudo-C++.

    struct AttackerChosenColor {
        size_t foreground_color;
        size_t background_color;
    };
    struct Array {
        size_t length;
        size_t *items;
    };

    int main() {
    // A program creates an array, uses it, frees it, but accidentally forgets that it's been freed and keeps using it anyway. Mistakes happen. This sort of thing happens all of the time in large programs.
    struct Array *array = new Array();
    ...
    free(array); // Imagine the allocation is zeroed here like you said. The array length is 0 and the pointer to the first item is 0.
    ...
    struct AttackerChosenColor *attacker = new AttackerChosenColor();
    // The allocator can reuse the memory previously used for array and return it to the attacker. Getting this to happen reliably is sometimes tricky, but it can be done.

    // The attacker chooses the foreground color. They choose a color value which is also the value of SIZE_T_MAX.
    // The foreground_color *overlaps\* with the array's length, so when we change the foreground color we also change the array's size.
attacker->foreground_color = SIZE_T_MAX; // The background_color overlaps with the array's size, so when we change the background color we also change the array's start. // The attacker chooses the background color. They choose a color value which is 0. attacker->background_color = 0;

    // Now say the attacker is able to reuse the dangling/stale pointer.
    // Say that they can write a value which they want to wherever they want in the array. This is 
    // Like you suggested it was zeroed when it was freed, but now it's been recycled as a color pair and filled in with values of the attacker's choosing.
    // Now the attacker can write whatever value they want wherever they want in memory. They can change return addresses, stack values, secret cookies, whatever they need to change to take control of the program. They win.
    if (attacker_chosen_index < array->length) {
         array->items[attacker_chosen_index] = attacker_chosen_value;
    }
    }
1 comments

> Zeroing out freed memory in no way prevents UAFs.

Maybe they meant it zeroes out all the references on free? This is possible if you have a precise GC, although not sure if it's useful.