Memory Protection: Virtual Memory, NX and ASLR
In the 1990s and early 2000s, a single overlong string could turn a network service into the attacker's program: copy too many bytes into a stack buffer, overwrite the function's return address with the address of the buffer, and the CPU happily executes the bytes you just sent. Worms like Code Red (2001) and SQL Slammer (2003) spread around the world with that recipe, Code Red in hours and Slammer in minutes.
The same bugs still exist in C and C++ code today, yet such a one-shot exploit rarely works on a modern system. The reason is a set of protections added to hardware, kernels and compilers, each closing one step of the old recipe. This lesson explains what they are, how to check that a program has them, and what they do not fix. The bugs themselves (overflows, use-after-free, format strings) with AddressSanitizer reports and a stack simulator are the subject of Memory Safety & Binary Exploitation Concepts.
Virtual memory and page permissions
Each process sees its own virtual address space. The CPU's memory-management unit translates virtual addresses to physical memory in pages (4 KiB on x86-64), and each page has permission bits: readable, writable, executable. The kernel sets them per region and the hardware enforces them on every access: a write to a read-only page or a jump into a non-executable page raises a fault and the kernel kills the process. Paging itself is explained in the OS course's virtual memory lesson.
That isolation is the first protection: one process simply cannot address another's memory. The second is the permissions inside a process, which you can read for any process in /proc/<pid>/maps. The session below runs in your sandbox and prints the permissions and mapped file of each region of cat itself (locale files left out for space):
cat /proc/self/maps | awk '{print $2, $6}' | grep -v -e locale -e gconvr--p /usr/bin/cat
r-xp /usr/bin/cat
r--p /usr/bin/cat
r--p /usr/bin/cat
rw-p /usr/bin/cat
rw-p [heap]
rw-p
rw-p
r--p /usr/lib/x86_64-linux-gnu/libc.so.6
r-xp /usr/lib/x86_64-linux-gnu/libc.so.6
r--p /usr/lib/x86_64-linux-gnu/libc.so.6
r--p /usr/lib/x86_64-linux-gnu/libc.so.6
rw-p /usr/lib/x86_64-linux-gnu/libc.so.6
rw-p
rw-p
r--p /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
r-xp /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
r--p /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
r--p /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
rw-p /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
rw-p [stack]
r--p [vvar]
r-xp [vdso]
--xp [vsyscall]
Read the four letters as read, write, execute and private (copy-on-write). Every file is mapped in several pieces: headers and constants r--p, machine code r-xp, relocated data that becomes read-only after start-up r--p, writable variables rw-p. The heap and the stack are rw-p. No region is both writable and executable. That rule is called W^X (write xor execute).
The protections, one per step of the old recipe
| Protection | Where | What it stops |
|---|---|---|
| NX / DEP (no-execute, data execution prevention) | CPU page bit, set by the kernel and requested by the binary (GNU_STACK without E) |
Running code from the stack or heap |
| ASLR (address space layout randomisation) | Kernel, at every program start | Knowing where the stack, heap and libraries are |
| PIE (position-independent executable) | Compiler and linker | Lets ASLR move the program's own code, not only the libraries |
Stack canary (-fstack-protector-strong) |
Compiler | A secret value before the return address; checked before return; a linear overflow destroys it first |
RELRO (relocation read-only), full with -z now |
Linker and loader | Overwriting the table of library function addresses (GOT) |
| CFI, shadow stacks (Intel CET, Arm PAC/BTI) | Compiler and CPU | Returning or jumping to places the program never intended |
None of these removes the bug. They turn "one bad input = code execution" into "the program crashes", and they make exploitation need several bugs chained together (an information leak to defeat ASLR, then a write). Attackers responded with techniques such as return-oriented programming (reusing snippets of existing executable code instead of injecting new code), which is why CFI and shadow stacks followed.
ASLR: watch the stack move
cat /proc/sys/kernel/randomize_va_space
for i in 1 2 3 4 5; do grep '\[stack\]' /proc/self/maps | cut -d- -f1; done | sort -u | wc -l2
5
2 is full randomisation (stack, libraries, heap, and PIE code). Five starts of grep put its stack at five different addresses. On 64-bit Linux there are far too many possible positions to guess, which is why exploits need a leak.
Checking a binary: checksec
The protections that depend on how a program was built can be read from the file. checksec does it in one line. Here the same toy program (a deliberate strcpy into a 16-byte buffer, a lab-only example) is built twice: once with Ubuntu's default flags, once with every protection switched off:
cat > toy.c <<'SRC'
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char name[16];
strcpy(name, argc > 1 ? argv[1] : "lab"); /* no length check: the bug */
printf("hello %s\n", name);
return 0;
}
SRC
gcc -O0 toy.c -o hardened
gcc -O0 -fno-stack-protector -no-pie -z execstack -z norelro toy.c -o weak
checksec --file=hardened
checksec --file=weak | tail -1
readelf -lW weak | grep GNU_STACK
./hardened lab
./hardened AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 2>&1 | cat
echo "exit code: ${PIPESTATUS[0]}"RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE
Full RELRO Canary found NX enabled PIE enabled No RPATH No RUNPATH 38 Symbols No 0 2 hardened
No RELRO No canary found NX disabled No PIE No RPATH No RUNPATH 35 Symbols No 0 2 weak
GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RWE 0x10
hello lab
*** stack smashing detected ***: terminated
exit code: 134
The default build has all four (full RELRO, canary, NX, PIE). The weak build's GNU_STACK program header asks for an RWE stack: readable, writable and executable, exactly what W^X forbids. With an overlong argument, the hardened build notices the destroyed canary and stops itself with SIGABRT (exit code 134 = 128 + 6) before the corrupted return address is ever used. The bug is still there; the canary turned it into a crash.
Detection and prevention
Detect weak binaries in your own estate: run checksec (or readelf/hardening-check) over every executable you ship and fail the build if a protection is missing; container scanners and Linux distribution policies do the same. Detect attacks: canary failures (stack smashing detected), segmentation faults in a service and repeated crashes of the same process are logged by the kernel and systemd (segfault at … ip … error), and a service that crashes on odd input is worth a bug report even before anyone exploits it.
Prevent in layers: keep the defaults (modern GCC and Clang on most distributions enable PIE, canaries and NX; add -D_FORTIFY_SOURCE=2 or 3 with optimisation and -Wl,-z,relro,-z,now), never ship with execstack, test with sanitizers and fuzzing, and for new code prefer memory-safe languages such as Rust, Go or Java, which remove the bug class rather than mitigating it.
Pitfalls
- Mitigations are not fixes. A canary can be skipped when the bug writes to a chosen offset instead of linearly, and ASLR falls to a single leaked pointer. Fix the overflow.
- Turning protections off "to make it work". Some old software needs an executable stack; that is a reason to replace it, not to disable NX.
- Forgetting the libraries. A hardened main program loading one old library without NX or RELRO gives the attacker a weak spot.
- Reading
-O0results as production results._FORTIFY_SOURCEonly acts with optimisation, so check the flags of the real build.
Practice
- You add
-z nowto the weak build's command line and keep-z norelro. Does its RELRO column change? What would you change to get Full RELRO? - A crash report says
*** stack smashing detected ***in a service. Has the service been exploited?
Answers
- No:
-z norelroswitches RELRO off entirely, so there is no read-only region for-z nowto protect. Remove-z norelroand add-z relro -z nowto get Full RELRO; with-z relroalone it is Partial RELRO (the GOT stays writable because functions are bound lazily). - Not necessarily, and the canary did its job: the program stopped before using the overwritten return address. But a stack buffer overflowed, so either a bug was hit by accident or someone is sending crafted input. Treat it as a security bug, collect the input that caused it, and look for other attempts in the logs.
Test yourself
What does W^X (write xor execute) mean?
- Files can't be both written and executed
- No memory page is both writable and executable at the same time
- Only root can execute programs
- The stack is encrypted
In the checksec session, why did the hardened program exit with code 134 for a long argument?
- It ran out of memory
- The stack canary check failed and the program aborted itself with SIGABRT (128 + 6)
- NX blocked the jump
- The kernel refused the argument
Which protection makes the stack, heap and library addresses different at every program start?
- NX
- RELRO
- ASLR
- Stack canaries
Why do modern exploits often need an information leak?
- To read the password file
- Because ASLR hides where code and data are, so the attacker must first learn an address
- Because NX encrypts memory
- Leaks are required by law