If your stack and heap are non-executable, how can your code run?

Adam Sh picture Adam Sh · Jul 14, 2012 · Viewed 16.9k times · Source

I read a book about buffer overflow, and it suggest the next to deal with:

Making the stack (and heap) non-executable provides a high degree of protection against many types of buffer overflow attacks for existing programs.

But I don't understand how we can do it - where the execute would take place, if not on the heap or on the stack?

Answer

Jim Balter picture Jim Balter · Jul 14, 2012

If I understand your question correctly, none of the other answers address it. The answer is that execution occurs in the code section, which is neither stack nor heap. In a typical paged memory system, the code from a program file (e.g., a .exe in Windows) is loaded into executable but read-only pages. Additional writable (and executable) pages are allocated to the process for the stack and heap. The suggestion here is that the operating system and hardware should cooperate to mark those pages writable but not executable (rgngl's answer explains how to do that in Windows).

Even with non-executable heap and stack, exploits are still possible that use the return-oriented programming mentioned in Alexey Frunze's answer, but there are protection techniques that stymie even those, such as stack-smashing protection and address space layout randomization -- see http://en.wikipedia.org/wiki/Return-to-libc_attack#Protection_from_return-to-libc_attacks