ASLR & Position-Independent Code
Exploit Mitigations · Exploitation Fundamentals track
9 min read
In this module
Shuffling the Deck
Back in Stack-Based Buffer Overflows, exploiting a buffer overflow meant knowing exact memory addresses. Where to drop shellcode. Where ROP gadgets sat. Where the stack lived. Address Space Layout Randomisation (ASLR) rips that certainty away by scrambling where everything loads in memory.
Each time a program starts, the OS places code, stack, heap, and shared libraries at different random base addresses. An address that was valid one run is garbage the next. With no idea where anything lives, the attacker can't build a reliable exploit.
What Gets Randomised
ASLR randomises the base addresses of several memory regions:
- Stack - local variables and return addresses are at different locations each run
- Heap - dynamically allocated memory starts at a different base
- Shared libraries - libc, the dynamic linker, and other libraries load at random addresses
- Program code - but only if compiled as Position-Independent Executable (PIE)
On Linux you can see it happen. cat /proc/sys/kernel/randomize_va_space prints 2 when full randomisation is on. Run cat /proc/self/maps twice and compare: the line for libc.so.6 starts at a different address each time, because each cat is a fresh process with a freshly shuffled layout.
Here are those regions in a 64-bit Linux address space. Hover over each block to see how much entropy ASLR gives its base, and notice that the program image only gets any if it was built as PIE:
64-bit Virtual Address Space Layout
Hover over a region to see details
Traditional executables are compiled to run at a fixed address. PIE compilation generates code that works at any address by using PC-relative addressing for all references. Without PIE, the main program binary loads at a known, fixed address even when ASLR is active - giving the attacker a reliable anchor point. Modern systems compile most programs as PIE by default.
The Entropy Problem
ASLR is only as strong as the randomness behind it. On 32-bit systems the address space is just 4 GB, and alignment requirements eat into that further. With Linux's defaults on 32-bit x86, a shared library's base gets just 8 bits of randomness: 256 possible positions. An attacker who can retry, against a server that restarts crashed workers for instance, will get lucky in a few hundred attempts. Brute force is very much on the table.
64-bit changes the maths. Linux's default for shared libraries on x86-64 is 28 bits, about 268 million possible bases, and brute-forcing stops being a serious plan.
Defeating ASLR with Information Leaks
The most common bypass is an information leak: a separate bug that hands the attacker a pointer from the running process. Integer Overflows & Type Confusion showed how format string flaws are perfect for this. A stray %p or %x in a format string can spill a stack or library address.
One leaked address is usually enough. The offset within a memory region is fixed, so the base falls out by simple subtraction, and from there gadgets, functions, and data structures all become addressable again. ASLR works best as part of a layered defence; on its own it raises the bar, but a single leak collapses the whole game.
Worked Example: One Leak, Whole Library
Say a format string bug leaks the address of puts inside libc: 0x7f3a1c2805a0. The attacker has a copy of the same libc build, and from its symbol table knows two fixed offsets (the values below are illustrative; every libc build has its own):
| Symbol | Offset inside libc |
|---|---|
puts | 0x805a0 |
system | 0x50d70 |
The arithmetic is two lines:
libc base = leaked puts − puts offset = 0x7f3a1c2805a0 − 0x805a0 = 0x7f3a1c200000system = libc base + system offset = 0x7f3a1c200000 + 0x50d70 = 0x7f3a1c250d70ASLR moved the whole library as one block, so the distance from puts to system never changed. Notice the base ends in 000: libraries are mapped at page boundaries, which gives you a handy sanity check. If your calculated base doesn't end in three zeros, you've got the wrong offset or the wrong libc.
Predict: run the program a hundred times and leak puts each time. Which part of the address never changes?
The last three hex digits, 5a0. Randomisation shifts regions by whole 4 KiB pages, and 4 KiB is 2¹² bytes, which is exactly three hex digits. The low 12 bits of every address are its offset within the page, so they're the same on every run. Attackers lean on this for partial overwrites: changing only the lowest one or two bytes of a pointer to retarget it nearby, without needing to know the randomised part at all.
Is the Binary Itself Moving?
Before planning a leak, find out what's already fixed. checksec answers in one line:
PIE: No PIE (0x400000)No PIE means the executable is an old-style ET_EXEC file that always loads at the address in brackets, 0x400000 being the usual x86-64 default. Its .text, its PLT stubs and its GOT all sit at the same addresses on every run, so any gadget inside the binary is usable without a leak. PIE enabled means the binary moves too, and you'll need a code pointer from the program itself before you can use its gadgets. The other checksec lines (RELRO, canary, NX, FORTIFY) are covered in DEP / NX.
Getting the Leak: Make the Program Tell You
The worked example assumed someone handed you puts's address. Against a non-PIE binary you can usually make the program hand it over. The Global Offset Table holds the real libc addresses of the functions the binary imports, and its own location is fixed. So the first stage of the exploit calls puts with a pointer to puts's GOT entry, which prints the libc address as raw bytes, then returns to main so the program runs again and accepts a second payload. In pwntools:
from pwn import *
elf = ELF("./vuln")libc = ELF("./libc.so.6") # the same build the target runsio = process("./vuln")
rop = ROP(elf)rop.puts(elf.got["puts"]) # pop rdi; ret + &puts@GOT + puts@PLTrop.call(elf.symbols["main"]) # come back for round twoio.sendline(flat({72: rop.chain()})) # 72 = offset to the return address (illustrative)
leak = u64(io.recvline().strip().ljust(8, b"\x00"))libc.address = leak - libc.symbols["puts"]log.info("libc base: " + hex(libc.address))Once libc.address is set, every libc.symbols[...] lookup returns a live address, and the second payload is an ordinary ret2libc. The .ljust(8, ...) is there because puts stops at the first null byte and user-space addresses on x86-64 have two zero bytes at the top, so you receive six at most. The ret2libc mechanics, including the extra ret that keeps rsp 16-byte aligned for system's movaps, are in Return-Oriented Programming.
What if you don't know which libc the target runs? The low three hex digits help again. Leak two functions, say puts and printf, and their page offsets form a fingerprint for the build. Searchable databases of libc builds map that fingerprint to a download, and from then on you have exact symbol offsets.
one_gadget: A Shell in a Single Address
Sometimes you control just one pointer: a single return address with no room for a chain after it, or one function pointer you can overwrite. For those cases there's one_gadget, a tool that scans a libc binary for spots where jumping in leads straight to execve("/bin/sh", ...). These live inside libc's own code that spawns shells, such as the guts of system. Run it against the exact libc you're targeting:
$ one_gadget ./libc.so.60x4f2a5 execve("/bin/sh", rsp+0x40, environ)constraints: rsp & 0xf == 0 rcx == NULL
0x4f302 execve("/bin/sh", rsp+0x40, environ)constraints: [rsp+0x40] == NULLThe offsets and constraints here are illustrative; every libc build gives its own list, and on some newer builds you'll see candidates that reach the shell through posix_spawn instead.
The constraints are the part that matters. You're jumping into the middle of a function, so "/bin/sh" is already set up, but the argv and envp arguments come from whatever happens to be in registers and on the stack when you land. execve needs argv to be a valid array or null; if [rsp+0x40] holds garbage, the kernel tries to read it as a list of string pointers and the call fails, or the program crashes on the way. Your overflow arrives with the registers the vulnerable function left behind, and you don't get to pick them.
So the workflow is practical rather than clever. Try every candidate. Prefer ones whose constraints your payload can satisfy: stack conditions are often easy, because the bytes after your return address are yours. If a register needs to be zero, see whether a cheap gadget in front can clear it. And if none fit, fall back to a full system("/bin/sh") chain.
Predict: you overwrite a return address with the second gadget above, whose constraint is [rsp+0x40] == NULL. Your payload ends straight after the return address, and the exploit crashes. What's the cheapest fix?
Append zero bytes after the return address. After ret pops your gadget address, rsp points at the eight bytes immediately following it. Those are payload bytes, if you send them. So [rsp+0x40] is the 8 bytes starting 0x40 past the return address slot: write at least 0x48 zero bytes after the address and the constraint holds. This only works if the input function accepts null bytes; read and gets do, strcpy stops at the first one.
The Ret2Libc lab runs with ASLR switched off and prints the libc base for you, so you can practise the address arithmetic from this lesson before adding a real leak stage. Once that's comfortable, try finding a working one_gadget for the lab's libc as an alternative to the system chain.
Defensive Thinking
Turn ASLR on at the OS level (modern Linux, macOS, and Windows already do). Compile binaries as PIE, so the main program moves too and doesn't hand attackers a fixed set of gadgets. And don't kid yourself: ASLR on its own won't save you. Pair it with mitigations that shut down the leaks an attacker would otherwise exploit, and treat any bug that discloses a pointer as a security bug, even if it looks harmless by itself.
Try the Simulations
Stack Canary Detection
Place a canary value between a buffer and return address. A simulated overflow corrupts the canary, and the check detects the corruption before the function returns.
DEP / NX Concept
Write the bytes of two instructions into a data area and jump there. Our simulator has no NX bit, so the injected code runs; a real CPU with DEP would fault and terminate the process.