Overwriting the Return Address
You already know local buffers and the return address share the same stack. Now we get specific. This lesson walks through what happens byte by byte when a write blows past the buffer boundary, mangles the saved frame pointer, and replaces the return address. The payoff is the most powerful primitive in exploitation: control of rip.
For the theoretical foundation, see Controlling Execution.
The Stack Before the Overflow
Cast back to our vulnerable function from the previous lesson. Call it with something tame like "AAAA" and the stack looks clean:
Buffer Overflow Simulator
Input: 0 bytes | Buffer: 64 bytes | Overflow: 0 bytes
Stack (high addresses at top):
Type into the simulator to watch the bytes land. vuln was built with -fno-stack-protector, so there's no canary: the saved rbp starts right at byte 64 and the return address at byte 72.
Four bytes plus the null terminator fit nowhere near the edge of a 64-byte buffer. The saved rbp and return address stay intact. When ret runs, it pops 0x00000000004011a0 into rip and execution heads back to main like nothing happened.
The Stack After the Overflow
Now picture the input as 72 bytes of 'A' (0x41) followed by the target address. The 72 'A's fill the buffer and the saved rbp, and the next bytes land in the return-address slot.
There's a catch with the address. 0x00000000deadbeef in little-endian is ef be ad de 00 00 00 00, and strcpy stops at the first zero byte, so the four upper bytes can't be part of the string. They don't need to be. strcpy copies the 72 'A's and ef be ad de, then writes its terminating NUL into the fifth byte of the slot, 77 bytes in all starting at [rbp-64]. The original return address (0x00000000004011a0) already had zeros in its top bytes, so the slot now reads 0x00000000deadbeef. User-space addresses on x86-64 always have their top two bytes zero, which is why this trick works so often.
What Happens at ret
ret does one thing — pop the top of the stack into rip. The exact sequence around it:
leave ; equivalent to: mov rsp, rbp; pop rbpret ; equivalent to: pop ripStep by step:
-
mov rsp, rbp— drags the stack pointer back to the frame pointer.rspnow points at the savedrbpslot, which we've overwritten with0x4141414141414141. -
pop rbp— pops 8 bytes off the stack intorbp, loading our garbage value0x4141414141414141.rspticks up by 8 and lands on the return-address slot. -
ret(effectivelypop rip) — pops 8 bytes into the instruction pointer, loading0x00000000deadbeef. -
The CPU starts fetching from
0x00000000deadbeef. If something executable lives there, it runs. If not, the process eats a segmentation fault.
The instant an attacker controls rip, they decide what the CPU runs next. This is the control-flow hijack primitive, and it's functionally equivalent to arbitrary code execution. Every modern mitigation — DEP, ASLR, stack canaries, CFI — exists to stop or muddle exactly this one moment. Set rip to an address holding code you wrote, and the process is yours.
Calculating the Exact Offset
Pinning down the exact byte count between the buffer's start and the return address is your opening move. A few ways to get it:
Manual calculation from disassembly:
lea rax, [rbp-64] ; buffer starts at rbp - 64The return address is at rbp + 8. So the offset is:
offset = (rbp + 8) - (rbp - 64) = 72 bytesYou need 72 bytes of padding, then your 8-byte target address.
Pattern-based discovery with cyclic patterns:
When the disassembly isn't handy, you can generate a De Bruijn sequence — a pattern where every 4- or 8-byte substring appears at most once. Feed the pattern in as input, watch the crash, and read the value sitting in rip:
Pattern: Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2...Don't expect to find the pattern in rip, though. Eight ASCII bytes make a non-canonical address: x86-64 only accepts addresses whose top 16 bits are copies of bit 47, and anything else makes ret fault before it jumps. So the crash is reported at the ret instruction itself, and the pattern bytes are still sitting at the top of the stack. Read them with x/gx $rsp. For this binary you'd see 0x6341356341346341, the ASCII bytes "Ac4Ac5Ac", and that substring starts at index 72 of the pattern: the offset.
GDB confirmation:
(gdb) run $(python3 -c "print('A'*72 + 'B'*6)")Program received signal SIGSEGVRIP: 0x424242424242Six Bs rather than eight keeps the address canonical: strcpy's NUL and the zero top byte of the old return address fill the slot out to 0x0000424242424242. Nothing is mapped there, so ret succeeds and the fault happens on the jump target, with the B's right there in rip. That confirms the offset is exactly 72 bytes.
Byte-by-Byte Corruption Walkthrough
Trace the corruption precisely. Our input is crafted like so:
payload = b'A' * 64 # fill the bufferpayload += b'B' * 8 # overwrite saved rbppayload += b'\xef\xbe\xad\xde\x00\x00\x00\x00' # overwrite return address (little-endian)Here's the frame just before leave, with that payload in place. Offsets count from the start of buffer. Bytes 0-63 are the As, bytes 64-71 the Bs over the saved rbp, and byte 72 is the start of the return address. The visualiser shows only that slot's first byte, 0xEF.
Stack Frame View
Mind the little-endian byte order. We write \xef\xbe\xad\xde\x00\x00\x00\x00 and the 64-bit value parked in memory reads as 0x00000000deadbeef.
The Exploit Flow
Hover over each step to see details
A stack-based buffer overflow exploit follows a tidy six-step recipe:
- Identify the vulnerable function - find an unchecked copy into a stack buffer
- Calculate the offset - determine the distance from buffer start to return address
- Craft the payload - padding bytes + new return address (+ optional shellcode)
- Deliver the payload - feed it as input to the vulnerable function
- Trigger the return - when the function returns,
riploads the attacker's value - Achieve execution - the CPU jumps to attacker-chosen code
Trampling the saved rbp is more than collateral damage. After leave runs, the caller's rbp is sitting at an attacker-chosen value. Any code in the caller that does rbp-relative addressing for its own locals will now read or write at a location the attacker picked. That's how a single overflow can snowball into a chain of corruption across the caller's frame.
Why Does strcpy Not Stop?
A fair question: why doesn't strcpy notice it's left the buffer? Because strcpy doesn't even know what a buffer is. Here's the gist of how it's implemented:
; Simplified strcpy logic.copy_loop: mov al, byte [rsi] ; load one byte from source mov byte [rdi], al ; store it at destination inc rsi ; advance source pointer inc rdi ; advance destination pointer test al, al ; was the byte zero? jnz .copy_loop ; if not, keep copyingThe loop tests one condition — is this byte zero? — and that's it. The destination's size is a fact strcpy was never told. That single oversight is the lineage behind every strcpy-based buffer overflow ever filed.
The Address Conundrum
Fair question: now that we own rip, where do we aim it? This is the heart of exploitation:
- To shellcode in the buffer - classic technique, but defeated by DEP/NX (the stack is not executable on modern systems)
- To a library function - ret2libc, which we will cover in Module 11
- To a chain of gadgets - ROP, also covered in Module 11
- To a known address - only works without ASLR
Different targets need different tradecraft, and modern defences make each one harder to land. They all share the same starting point though — owning the return address via a buffer overflow.
Confirming the Crash in GDB
A debugger makes the overwrite easy to confirm:
; Set a breakpoint on leave, before the frame is torn down; (gdb) break *vulnerable+62; (gdb) run $(python3 -c "print('A'*72 + 'B'*6)");; rbp still points at the frame here (leave hasn't run yet),; so read the saved-rbp slot and the return address off it:; (gdb) x/2xg $rbp; 0x7fffffffe1e0: 0x4141414141414141 <- saved rbp (overwritten); 0x7fffffffe1e8: 0x0000424242424242 <- return address (overwritten);; Continue execution:; (gdb) continue; Program received signal SIGSEGV, Segmentation fault.; 0x0000424242424242 in ?? ()The segfault at 0x0000424242424242 is the receipt: full control of the instruction pointer. Try it with eight Bs instead and the crash moves to the ret instruction, for the non-canonical reason above.
What is Next
Stack smashing now makes sense at the byte level — how data crosses the buffer boundary, mauls the frame pointer, and replaces the return address. The next lesson covers the classic exploitation move on top of it — NOP sleds and shellcode delivery — and explains why modern defences have all but retired the technique while the underlying ideas still matter.