views:

878

answers:

1

How heap overflow attacks are done?

In case of stackoverflow attacks, the attacker replaces the function return address with his address.

How this is done in heap overflow attacks? Also, is it possible to run code from heap?

+11  A: 

Note this varies by platform, and my example is overly simplified. It basically comes down to heap managers having linked lists that could be overrun, and you can use the linked list pointers to overwrite random parts of the process's memory.

Imagine I have a naive heap implementation whose control blocks are like this:

struct HeapBlockHeader
{
    HeapBlockHeader* next;
    HeapBlockHeader* prev;
    int size;

    // Actual heap buffer follows this structure.
};

When the heap gets freed, this control block goes back into a list of freed blocks, by modifying the next/prev pointer. If I overrun a heap buffer, I can overwrite the pointers in the next control block with data I control. Suppose I override these links to point to a pointer to code (probably just in the buffer I overran) and to the return address of the function on the stack. When the heap manager tries to link the block back into a freed list, it will actually overwrite the return address on the stack with a pointer to code I control.

This article has a nice overview on heap overflow attacks: http://www.h-online.com/security/A-Heap-of-Risk--/features/74634

This article describes some of the hardening that went into Vista's heap manager to prevent this sort of attack: http://www.blackhat.com/presentations/bh-usa-06/BH-US-06-Marinescu.pdf

EDIT: On possibility to run code from heap, yes it's possible. Many platforms now make heap memory non-executable by default which raises the barrier to getting arbitrary code to run. However, you can still do a "jump to libc" style attack - Overwrite the return address to a known function which will be executable.

Michael
Great answer - I feel that I know a lot about my particular areas of programming, but I've never been able to dive into compilers, memory management, protection mechanisms - knowing where the processor's responsibities stop and the OS's start. Then again between OS and app code. I've read the intel x86 manual (vol 1) cover to cover. How did you come to learn these things?
uosɐſ