Part 4 of 7 · 2 min read
Non-executable memory
Think of a notice board where people may pin papers (write) but the office door is opened only by a signed order (execute). A pinned paper can say anything and still opens nothing. The analogy stops in one place: the board and the office are separate rooms in the building, while for a CPU the same memory can be either unless a page is marked.
In plain words: Each page of memory has permission bits for read, write and execute (Level 7). In the oldest designs the stack was executable, so a program that copied bytes onto the stack could run them as code. The NX bit (no-execute) lets the hardware refuse to run code from a page that is marked as data. The rule is called write xor execute (W^X): a page may be writable or executable, and never both at once. A program file records its needs in a header, GNU_STACK, which the loader reads.
A worked example. readelf -lW on the program compiled normally shows the stack header with flags RW: readable and writable, not executable. The same program compiled with -z execstack shows RWE. The kernel refuses to run code from the first and allows it in the second. The attack of section 1 then cannot simply place its own code on the stack. It must instead reuse code that already exists in the program and in libraries, by chaining return addresses. That is harder, and it is the reason the next defence matters.
The key lines. NX protects against injected code. It does not protect against reused code.
NX bit and W^X
The NX bit is a page-table flag that makes the CPU refuse to execute instructions from a page. W^X (write xor execute) is the rule that no page is both writable and executable, so data written by a program cannot be run as code.
Example: a stack page marked RW raises a fault if the CPU tries to jump into it.
Check yourself:
1. What does RWE in GNU_STACK allow that RW does not?
2. What does the W^X rule say?
3. What kind of attack still works against a non-executable stack?