> 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/05.-return-oriented-programming/01.-fundamentals.md).

# ROP 01 — Fundamentals

> What ROP is, why it works, when to use it, and the core mental model.

## What Is ROP?

**Return-Oriented Programming (ROP)** is a code-reuse attack technique where an attacker chains together small snippets of existing executable code — called **gadgets** — instead of injecting new shellcode.

Each gadget ends with a `ret` instruction. The attacker overwrites the **saved return address** on the stack with the address of the first gadget. When the function returns, the CPU pops that address and jumps there. That gadget does its work, hits `ret`, pops the *next* address the attacker planted, and jumps again — forming a chain.

```
STACK (attacker-controlled):          CPU EXECUTION FLOW:

┌──────────────────────────┐
│  addr of gadget 1        │ ◄── overwritten return address
│  value for gadget 1      │          │
│  addr of gadget 2        │          ▼
│  value for gadget 2      │     gadget 1:  pop rdi
│  addr of gadget 3        │               ret        ──► jumps to gadget 2
│  addr of system()        │          │
│  addr of "/bin/sh"       │          ▼
└──────────────────────────┘     gadget 2:  pop rsi
                                            ret        ──► jumps to gadget 3
                                       │
                                       ▼
                                  gadget 3:  xor rdx, rdx
                                             ret        ──► jumps to system()
                                       │
                                       ▼
                                  system("/bin/sh")  ──► 🐚 shell
```

**Key insight**: The attacker never executes new code — they orchestrate existing legitimate code in a new order. This completely defeats NX/DEP, which only blocks *injected* shellcode.

***

## Etymology & History

| Year  | Milestone                                                                         |
| ----- | --------------------------------------------------------------------------------- |
| 1997  | Solar Designer's **ret2libc** — first "return to existing code" attack            |
| 2001  | **ret2libc** chaining described by Nergal                                         |
| 2007  | Hovav Shacham coins **Return-Oriented Programming** — proves it's Turing complete |
| 2008  | ROP demonstrated on SPARC, ARM, x86 — architecture-independent                    |
| 2010  | Automatic ROP chain generation tools (Q, ROPgadget)                               |
| 2014  | **SROP** (Sigreturn-Oriented Programming) — works with just 1 gadget              |
| 2017  | Intel CET announced as hardware ROP defense                                       |
| 2020+ | CET available in CPUs; ROP research moves to JOP/COP bypasses                     |

***

## Why ROP Works

Modern CPUs have no concept of "this `ret` is returning from the right place." The `ret` instruction simply:

1. Reads the value at `[RSP]`
2. Increments `RSP` by 8 (on 64-bit)
3. Jumps to that value

If the attacker controls the stack, they control where every `ret` goes.

```asm
; ret is literally equivalent to:
pop rip          ; (conceptually — rip isn't directly addressable)

; Which means:
mov rip, [rsp]
add rsp, 8
```

The CPU has no memory of where `call` came from. There is no "call stack" in hardware — that's entirely a software convention.

***

## The Stack as a Turing Machine

With enough gadgets, ROP is **Turing complete**. You can build:

| Capability             | Example Gadget Sequence                             |
| ---------------------- | --------------------------------------------------- |
| **Load values**        | `pop rdi ; ret`                                     |
| **Arithmetic**         | `add rax, rbx ; ret`                                |
| **Memory read**        | `mov rax, [rdi] ; ret`                              |
| **Memory write**       | `mov [rdi], rax ; ret`                              |
| **Syscall**            | `syscall ; ret`                                     |
| **Conditional branch** | Compare + conditional jump gadget (rare but exists) |
| **Loop**               | Return back to start of chain with modified state   |

In practice, most exploits only need 3–10 gadgets to get a shell.

***

## When Is ROP Used?

### Primary trigger: NX/DEP is enabled

NX marks the stack as non-executable. You can't run injected shellcode. But you CAN return into existing `.text` — ROP bypasses NX completely.

### Attack surface map

| Vulnerability                    | How ROP Applies                                        |
| -------------------------------- | ------------------------------------------------------ |
| **Stack buffer overflow**        | Classic: overwrite return address directly             |
| **Heap overflow → func ptr**     | Corrupt a vtable or callback pointer with gadget addr  |
| **Format string → arb. write**   | Write gadget addresses into GOT or onto the stack      |
| **Use-after-free**               | Overwrite freed object's vtable with ROP chain pointer |
| **Type confusion**               | Control virtual dispatch to hit first gadget           |
| **Integer overflow → OOB write** | Gain write primitive, use to set up chain              |
| **Kernel exploits (ring 0)**     | ROP to disable SMEP/SMAP, then drop to shellcode       |
| **Browser exploits**             | JIT output in executable memory contains known gadgets |
| **Embedded / IoT**               | Even stripped binaries carry libc gadgets              |
| **ASLR bypass (2-stage)**        | ROP chain 1 leaks an address; chain 2 gets shell       |

***

## Memory Layout Prerequisite

ROP requires controlling the **saved return address**. This sits on the stack at a known offset from the overflowed buffer:

```
HIGH ADDRESS
┌──────────────────────┐
│  caller's frame      │
├──────────────────────┤  ← RSP at function entry
│  return address      │  ← OVERWRITE THIS (offset = buf_size + saved_rbp)
│  saved RBP           │  ← +8 bytes above buffer end (64-bit)
│  [padding/locals]    │
│  char buf[64]        │  ← overflow starts here
├──────────────────────┤
│  ...                 │
LOW ADDRESS
```

Typical offset calculation:

* `offset = sizeof(buf) + 8` (for saved RBP in 64-bit)
* Verify with cyclic pattern (see `03_chain_construction.md`)

***

## ROP vs Other Techniques

| Technique                    | NX bypass         | Needs leak  | Shellcode | Notes                         |
| ---------------------------- | ----------------- | ----------- | --------- | ----------------------------- |
| **Classic shellcode**        | ❌ (blocked by NX) | ❌           | ✅         | Legacy; only works without NX |
| **ret2libc**                 | ✅                 | ❌ (no ASLR) | ❌         | Simplest code-reuse attack    |
| **ROP**                      | ✅                 | Sometimes   | ❌         | Full control, Turing complete |
| **SROP**                     | ✅                 | Sometimes   | ❌         | Needs almost no gadgets       |
| **JOP**                      | ✅                 | Sometimes   | ❌         | Bypasses CET shadow stack     |
| **ret2mprotect + shellcode** | ✅                 | Sometimes   | ✅         | Hybrid: ROP to re-enable exec |

***

## Minimal ROP Example (Conceptual)

Even without knowing any gadget addresses, the shape of every ROP exploit is:

```
[PADDING]           ← fill buffer + saved RBP
[gadget_1_addr]     ← hijack execution here
[gadget_1_data]     ← data consumed by gadget 1's pop(s)
[gadget_2_addr]
[gadget_2_data]
...
[target_function]   ← final call (system, execve, etc.)
[target_args]
```

The CPU processes this as a linked list, following `ret` pointers through attacker-controlled memory.

*REDmw Reference — For authorized security research and CTF use only.*


---

# 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/05.-return-oriented-programming/01.-fundamentals.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.
