# 07 · Binary Exploitation (Pwn)

[Home](../../README.md) › [Categories](../CATEGORIES_OVERVIEW.md) › **Binary exploitation**
&nbsp;·&nbsp; Presentation: slides 23–24 (live buffer-overflow memory boxes on 23) &nbsp;·&nbsp; [← 06 · Reverse engineering](06-REVERSE-ENGINEERING.md) · [08 · Miscellaneous →](08-MISCELLANEOUS.md)

> [!NOTE]
> This guide is **introductory**. It focuses on understanding memory, recognising bugs and debugging deliberately vulnerable programs that **you compile yourself** or that training platforms provide. It doesn't teach exploit development against real software. Never target programs or systems you don't own or aren't authorised to test.

---

## Contents

- [A. Introduction](#a-introduction)
- [B. Prerequisites](#b-prerequisites)
- [C. Understanding the challenges](#c-understanding-the-challenges)
- [D. Step-by-step methodology](#d-step-by-step-methodology)
- [E. Tools and their usage](#e-tools-and-their-usage)
- [F. Recommended learning resources](#f-recommended-learning-resources)
- [G. Mini practice exercises](#g-mini-practice-exercises)
- [H. What to learn next](#h-what-to-learn-next)

---

## A. Introduction

### A scenario

A sign-up form asks for your name, and the programmer reserved space for 16 characters. You type 200. In a memory-safe language you'd get an error message. In a C program that doesn't check, those extra characters spill into whatever sits next to the name in memory, maybe a variable that says whether you're an admin, maybe the address the program returns to next. That spill is a **buffer overflow**, one of the oldest and most important bugs in computing.

### What it is

**Binary exploitation** ("pwn", gamer slang for "own") is the art of making a compiled program do something its author never intended by abusing a memory bug. In CTFs, you usually get a small vulnerable program (and often its source) running on a server, and you must make it reveal the flag.

### What problems it deals with

- Programs that write past the end of a buffer (overflows).
- Programs that trust user input to describe memory (format-string bugs, out-of-bounds indexes).
- Programs that use memory after freeing it (use-after-free).
- Bypassing the protections operating systems add to make these bugs harder to abuse.

### Where you meet it in real life

Memory-safety bugs cause a large share of serious vulnerabilities in software written in C and C++: browsers, operating systems, routers, phones. This is why many organisations now encourage memory-safe languages such as Rust, and why vulnerability researchers who understand these bugs are in demand.

### Why it's interesting

You see how programs really live in memory, and the "aha" moment when a crash turns into understanding is unforgettable. It's the deepest technical category in CTFs.

### How it relates to cybersecurity

Understanding memory corruption explains why patches matter, why certain languages are safer, and how protections like stack canaries and ASLR work. Defenders, developers and researchers all benefit.

---

## B. Prerequisites

| Level | What | Why |
|---|---|---|
| **Essential** | Basic C programming (variables, arrays, functions, pointers at a basic level) | Pwn bugs are C bugs. [CS50x](https://cs50.harvard.edu/x/) is a great free start. |
| **Essential** | Hexadecimal | Addresses are written in hex. |
| **Helpful** | Linux command line | Challenges are almost always Linux programs. |
| **Helpful** | [Reverse engineering](06-REVERSE-ENGINEERING.md) basics | You must understand a program before you can misuse it. |
| **Helpful** | GDB basics | To watch memory while the program runs. |
| **Advanced** | x86-64 assembly and calling conventions | For anything beyond the simplest challenges. |
| **Advanced** | Python with pwntools | To script interactions with remote challenges. |

- **Programming:** C (to understand bugs) and Python (to interact with challenges).
- **Linux:** yes. Use a Linux VM or WSL on Windows.
- **Networking:** minimal. You'll connect to challenges with `nc host port`.
- **Learned while solving:** assembly, GDB, memory layout.

> [!TIP]
> Pwn is usually **not** the best first category. Try crypto, forensics or web first, then come here once you're comfortable with C and the command line.

---

## C. Understanding the challenges

### What a typical challenge looks like

> *(Fictional example written for this guide.)*
> **"Name Tag" · 200 points**
> Our badge printer asks for your name. Can you print a VIP badge?
> 📎 `nametag` (ELF), `nametag.c` · 🔗 `nc challenge.example 4000`

### What you're usually given

- A Linux binary, frequently with its C source.
- Sometimes the exact C library (`libc.so.6`) used on the server.
- A `host:port` to connect to with `nc`. The flag lives on the server, so you must make the remote program reveal it.

### Clues to look for

| Clue | Meaning |
|---|---|
| `gets()`, `scanf("%s")`, `strcpy()` with no length | Classic overflow candidates: they don't limit input length |
| `read(0, buf, 200)` into `char buf[64]` | Reads more than the buffer holds |
| `printf(user_input)` (no format string) | Format-string bug |
| A function like `win()` or `print_flag()` that's never called | The goal is to redirect execution there |
| A variable checked after input, e.g. `if (is_vip)` | Overflow may overwrite it |
| "Segmentation fault" when you send long input | Memory was corrupted: you're on the right track |

### Common challenge patterns (introductory)

1. **Overwrite a neighbouring variable:** overflow a buffer to change a flag variable next to it.
2. **Redirect to a hidden function:** overwrite the saved return address so the function "returns" into `win()`.
3. **Format-string leak:** make `printf` print values from memory.
4. **Integer issues:** negative or huge numbers bypass a size check.

### Common beginner mistakes

| Mistake | Better habit |
|---|---|
| Skipping the source code | Read it carefully first. The bug is usually visible. |
| Guessing input lengths randomly | Use a debugger to measure exactly where your input lands. |
| Ignoring protections | Run `checksec` first; it tells you which techniques are possible. |
| Testing only remotely | Reproduce locally first; remote attempts are slow and noisy. |
| Diving in without C basics | Learn C fundamentals first. It makes everything faster. |

---

## D. Step-by-step methodology

### 1. Understand memory first

**Why:** every pwn technique is about *where things are* in memory.

When a program runs, the operating system gives it a memory layout roughly like this:

```
 high addresses
 ┌────────────────────┐
 │ stack              │  local variables, function return addresses (grows downward ↓)
 │        ↓           │
 │                    │
 │        ↑           │
 │ heap               │  memory requested at runtime with malloc() (grows upward ↑)
 ├────────────────────┤
 │ .data / .bss       │  global variables
 │ .text              │  the program's machine code
 └────────────────────┘
 low addresses
```

- **Variables and addresses:** every variable lives at a memory address (a number, shown in hex like `0x7ffd1234abcd`). A **pointer** is a variable that stores an address.
- **Stack:** fast, automatic memory for local variables. Each function call gets a **stack frame** containing its locals and the **saved return address**, which says where to continue when the function finishes.
- **Heap:** memory the program explicitly requests (`malloc`) and must release (`free`). Used for data whose size or lifetime isn't known in advance.

### 2. Understand the bug: a buffer overflow, conceptually

**Why:** this is the bug behind the most famous pwn challenges.

```c
char name[16];
int  is_vip = 0;
scanf("%s", name);     // no length limit!
```

`name` has room for 16 bytes. `scanf("%s")` keeps writing as long as input keeps coming. Extra bytes overwrite whatever is stored next to `name`: another variable, saved registers or the return address. If the return address is corrupted with garbage, the program jumps to an invalid address and the OS kills it with a **segmentation fault** ("segfault": the program touched memory it isn't allowed to).

> The exact order of variables on the stack depends on the compiler and its settings. That's why you measure it in a debugger rather than assume it. The presentation's slide 23 animates this idea.

**The fix (input validation):** always limit input to the buffer size:

```c
fgets(name, sizeof name, stdin);   // reads at most 15 chars + terminator
scanf("%15s", name);               // width limit
```

and, at a higher level, prefer memory-safe languages where possible.

### 3. Check the protections

**Why:** modern systems add defences, and they decide which techniques are possible.

| Protection | What it does |
|---|---|
| **Stack canary** | A secret value placed before the return address; if it changes, the program aborts |
| **NX** (non-executable stack) | Data on the stack can't be run as code |
| **PIE** | The program loads at a random address each run |
| **ASLR** | The OS randomises the location of the stack, heap and libraries |
| **RELRO** | Makes some internal tables read-only |

`checksec` shows these at a glance. CTF challenges often disable some deliberately to make a technique learnable.

### 4. Read the source (or decompile)

**Why:** find the input function, the buffer size and what lies after it.

### 5. Reproduce the crash locally

**Why:** a crash proves you control something. Send increasingly long input and watch for a segfault.

### 6. Investigate in a debugger

**Why:** GDB shows you exactly which memory your input overwrote, which turns "it crashed" into "I understand why".

### 7. Go further on training platforms

From here, techniques (controlling the return address, ROP, heap exploitation) are best learned with structured guidance on platforms built for it. See section F.

---

## E. Tools and their usage

### GDB (GNU Debugger)

Full entry in [06 · Reverse engineering → GDB](06-REVERSE-ENGINEERING.md#gdb-gnu-debugger). Essential pwn commands:

```text
gdb ./program
(gdb) run                       start (type input when asked, or: run < input.txt)
(gdb) bt                        backtrace: which functions were active at the crash
(gdb) info registers rip rsp    where execution was and where the stack is
(gdb) x/16gx $rsp               show 16 8-byte values at the top of the stack
(gdb) disassemble main          assembly of main
```

### pwndbg

| | |
|---|---|
| **Website** | <https://github.com/pwndbg/pwndbg> |
| **Documentation** | [pwndbg docs](https://pwndbg.re/stable/) · [Setup](https://pwndbg.re/stable/setup/) |
| **Purpose** | A GDB plug-in that shows registers, stack, code and memory automatically after every step |
| **Problem it solves** | Plain GDB requires many commands to see context; pwndbg shows it all at once and adds exploitation-focused commands |
| **Platform** | Linux (macOS partially, via LLDB support) |
| **Type · Cost** | Installed · Free, open source |
| **Level** | Intermediate |
| **When to use** | Any pwn or RE debugging session |
| **Installation** | Follow the [official setup page](https://pwndbg.re/stable/setup/). It offers an install script, release packages and other options. The current README lists GDB 12.1+ and Python 3.10+ as requirements. Read any script before piping it into a shell. |
| **Alternative** | GEF (single-file GDB extension), plain GDB |

### checksec

| | |
|---|---|
| **Website / Docs** | <https://github.com/slimm609/checksec> (README) |
| **Purpose** | Lists the security protections of an executable (canary, NX, PIE, RELRO, FORTIFY) |
| **Problem it solves** | Knowing which defences you're up against before you start |
| **Platform** | Linux |
| **Type · Cost** | Installed · Free, open source |
| **Level** | Beginner (to run), intermediate (to interpret) |
| **When to use** | First command on every pwn binary |
| **Installation** | Download a release from GitHub (see README). Alternatively, [pwntools](https://docs.pwntools.com/en/stable/commandline.html) provides a `checksec` command too (`pip install pwntools`). |
| **Alternative** | `pwn checksec ./program` (pwntools) |

```bash
checksec file ./program
```

Example output from the checksec README for `/bin/ls`: *Partial RELRO · Canary found · NX enabled · PIE enabled*.

### Ghidra

Full entry in [06 · Reverse engineering → Ghidra](06-REVERSE-ENGINEERING.md#ghidra). In pwn, use it when no source is provided: find the input function, note buffer sizes from the decompiled declarations (`char local_28 [32]`) and spot hidden functions like `win`.

### Next-step tool: pwntools (intermediate)

[pwntools](https://docs.pwntools.com/en/stable/) is a Python library for scripting interactions with local and remote challenges (`pip install pwntools`). Learn it once you're solving challenges on training platforms.

---

## F. Recommended learning resources

| Resource | Type | Why it's useful |
|---|---|---|
| [pwn.college](https://pwn.college/) | Free course (account) | Arizona State University's free, structured dojos: the best guided path into pwn, starting from the basics. |
| [CyLab Security Academy library](https://learn.cylabacademy.org/library) | Practice (free account) | Filter by Binary Exploitation; several gentle buffer-overflow challenges with hints. |
| [OverTheWire: Narnia](https://overthewire.org/wargames/narnia/) | Practice (no account) | Classic beginner exploitation wargame with source code. |
| [CS50x](https://cs50.harvard.edu/x/) | Free course | Solid C and memory fundamentals. |
| [GDB online manual](https://sourceware.org/gdb/current/onlinedocs/gdb.html/) | Official docs | Complete debugger reference. |
| [pwntools docs](https://docs.pwntools.com/en/stable/) | Official docs | The standard scripting library for pwn. |
| [LiveOverflow on YouTube](https://www.youtube.com/@LiveOverflow) | Free videos | Well-known "binary exploitation" playlist explaining concepts visually. |

---

## G. Mini practice exercises

### Exercise 1: Memory on paper

- **Objective:** Understand overflow into a neighbouring variable without any tools.
- **Given:** Imagine this simplified (fictional) stack layout, with `name` placed directly before `is_vip`:

```
 address  0x10  0x11 … 0x1f   0x20 0x21 0x22 0x23
          [ name: 16 bytes  ] [ is_vip: 4 bytes ]
          initial: zeros      00 00 00 00
```

  The program runs `scanf("%s", name);` and you type 20 characters: `AAAAAAAAAAAAAAAAAAAA`.
- **Questions:** Which bytes change? What is `is_vip` afterwards? (`A` = `0x41`.)
- **Hints:** 16 characters fill `name`. Where do the other 4 go? Don't forget that `scanf` also writes a terminating zero byte after the input.
- **Learning outcome:** You understand what "overflow into an adjacent variable" means.
- **Solution:** Bytes `0x10–0x1f` become `41`. Bytes `0x20–0x23` become `41 41 41 41`, so `is_vip` is now `0x41414141` (non-zero → "true"). The terminating `00` lands at `0x24`, beyond `is_vip`, corrupting whatever is there. In real programs the compiler may order variables differently or add a canary, which is why you check in a debugger.

### Exercise 2: Make your own program crash, then read the crash

- **Objective:** Observe a segmentation fault and inspect it with GDB, on a program **you compile yourself** in a Linux VM or WSL.
- **Given:** Save as `crash.c`:

```c
#include <stdio.h>

void greet(void) {
    char name[16];
    printf("Name: ");
    scanf("%s", name);            /* deliberately unsafe for learning */
    printf("Hello, %s!\n", name);
}

int main(void) { greet(); return 0; }
```

  Compile with debug info and the stack canary disabled, so you can see the raw effect: `gcc -g -fno-stack-protector crash.c -o crash`
- **Steps:** Run `./crash` and type a short name (works). Run again and type 100 `A`s. Then `gdb ./crash` → `run` → type 100 `A`s → `bt` → `info registers rip rsp`.
- **Hints:** Look for `0x4141414141414141` in registers or the backtrace: that's your input (`A` = `0x41`).
- **Learning outcome:** You see that input overwrote saved data on the stack, and the program crashed trying to use it.
- **Solution:** Long input causes `Segmentation fault`. In GDB, the backtrace or saved frame data shows `0x41414141…`. Now fix it: change the `scanf` line to `scanf("%15s", name);`, recompile, and confirm long input no longer crashes it. Also try compiling *without* `-fno-stack-protector`: you'll likely get `*** stack smashing detected ***` instead, which is the stack canary at work.

### Exercise 3: Read the protections

- **Objective:** Interpret `checksec` output.
- **Given:** Your `crash` binary from exercise 2 and a system binary like `/bin/ls`.
- **Steps:** `checksec file ./crash` and `checksec file /bin/ls`.
- **Learning outcome:** You know which protections are on by default and how compile flags change them.
- **Solution:** `/bin/ls` typically shows canary, NX and PIE enabled. `crash` shows **no canary** because of `-fno-stack-protector`, which is exactly why exercise 2 crashed "cleanly" instead of aborting.

---

## H. What to learn next

| Stage | Learn | Resources |
|---|---|---|
| **Beginner** | C, memory layout, stack vs heap, segfaults, GDB basics, `checksec` | Exercises above, [CS50x](https://cs50.harvard.edu/x/), [CyLab library](https://learn.cylabacademy.org/library) |
| **Intermediate** | Calling conventions, controlling the return address on training binaries, format-string bugs, pwntools | [pwn.college](https://pwn.college/), [Narnia](https://overthewire.org/wargames/narnia/) |
| **Advanced** | ROP, ASLR bypasses, heap exploitation, kernel basics | pwn.college advanced dojos, advanced pwn [writeups](https://ctftime.org/writeups) |

**Related guides:** [06 · Reverse engineering](06-REVERSE-ENGINEERING.md) · [Cheat sheets: GDB](../resources/CHEAT-SHEETS.md#gdb) · [Linux essentials](../tools/LINUX-ESSENTIALS.md)

---

[← 06 · Reverse engineering](06-REVERSE-ENGINEERING.md) &nbsp;|&nbsp; [08 · Miscellaneous →](08-MISCELLANEOUS.md)
