Binary Exploitation
Easy
150 points

Canary Intro

Recuite 2025 - HCMUS
6 tháng 10, 2025
Stack Canary
Information Leak
Buffer Overflow
Recuite 2025 - HCMUS
Binary Exploitation

Canary Intro - Writeup

Challenge Information

  • Category: Pwn
  • Difficulty: Beginner
  • Protections: Full (PIE, NX, Canary, RELRO, SHSTK, IBT)

Analysis

Stack Canary Protection

The program demonstrates the stack canary mechanism:

  1. Prints win function address to screen
  2. Calls dumpstack() displaying the canary value!
  3. Receives input with scanf("%s") → can cause buffer overflow due to unlimited length
  4. main function finishes and returns

Stack Layout

[rbp-0x20]  buffer[24 bytes]    ← where scanf writes data
[rbp-0x08]  canary [8 bytes]    ← MUST be preserved!
[rbp+0x00]  saved rbp [8]
[rbp+0x08]  return addr [8]     ← target: return address → win

Vulnerability & Leaks

  1. Buffer overflow: scanf("%s") has no length limit → can overwrite buffer
  2. Canary Leak: dumpstack() prints the canary value, so attacker knows the actual canary
  3. PIE Leak: win function address is printed (PIE leaked or program has PIE disabled)

Key idea: When canary is leaked, we can bypass the check by writing back that exact value in the payload.

Exploitation Technique

Payload Structure

payload = b"A" * 24          # Fill buffer
payload += p64(canary)       # Write correct canary to avoid triggering __stack_chk_fail
payload += b"B" * 8          # Saved RBP (doesn't matter)
payload += p64(win_addr)     # Return address -> win

Exploitation Steps

  1. Read (parse) win address from program output.
  2. Read (parse) canary value from stack dump (line saying "<=== Stack canary" or similar).
  3. Build payload with the exact leaked canary value.
  4. Send payload to program.
  5. When canary is preserved, the check succeeds → program does not call __stack_chk_fail.
  6. When main returns, return address points to win() → spawn shell.
  7. Get flag (e.g. cat flag.txt).

Flag

BPCTF{canary_guards_your_stack_f1994a7d1cb2e0aaf69241ba160693ab}

Key Takeaways

  1. Stack canaries are effective against overflows without leaks.
  2. Information Leaks can destroy canary effectiveness — if attacker knows the canary value, bypass is trivial.
  3. Defense in depth: Canary is just one layer of protection — need to combine with ASLR/RELRO/NX/...
  4. Absolutely do not print/expose sensitive data (like stack dump) in production environment.

Technical Details

  • Canary on x86-64 Linux is usually fetched from fs:[0x28].
  • Before returning, it checks: cmp rax, fs:[0x28] (or sub rax, fs:[0x28] then je ok) — if wrong call __stack_chk_fail.
  • Therefore payload must preserve the canary value intact to pass the check.
150
Points
Easy
Difficulty
Binary Exploitation
Category