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.
Files changed (152) hide show
  1. package/AGENTS.md +131 -0
  2. package/Dockerfile +192 -0
  3. package/README.md +522 -0
  4. package/agents/ctf-analyzer.md +58 -0
  5. package/agents/ctf-controller.md +151 -0
  6. package/agents/ctf-speedrun.md +74 -0
  7. package/bin/ctf-agent.js +119 -0
  8. package/docker-compose.yml +13 -0
  9. package/mcp_config.json +19 -0
  10. package/package.json +44 -0
  11. package/references/ctf-triage-ladder.md +68 -0
  12. package/references/exploit-databases.md +575 -0
  13. package/references/llm-safety-and-policy-compliance.md +173 -0
  14. package/references/multi-agent-orchestration-and-policy-routing.md +278 -0
  15. package/references/security-events-and-intelligence.md +566 -0
  16. package/references/version-matrix.md +59 -0
  17. package/rules/ctf-execution-rules.md +44 -0
  18. package/rules/ctf-safety-framing-rules.md +140 -0
  19. package/rules/flag-validation-rules.md +25 -0
  20. package/scripts/__init__.py +1 -0
  21. package/scripts/ctf-tools.lock +205 -0
  22. package/scripts/ctf_init.py +1026 -0
  23. package/scripts/ctf_update.py +583 -0
  24. package/scripts/ctfd_client.py +81 -0
  25. package/scripts/cve_lookup.py +453 -0
  26. package/scripts/extract_flags.py +155 -0
  27. package/scripts/install_as_agent.py +278 -0
  28. package/scripts/install_ctf_tools.sh +603 -0
  29. package/scripts/parallel_triage.py +395 -0
  30. package/scripts/prompt_policy_sanitizer.py +283 -0
  31. package/scripts/scope_guard.py +444 -0
  32. package/scripts/skill_validator.py +504 -0
  33. package/scripts/workspace_cleaner.py +141 -0
  34. package/skills/ctf-ai-ml/SKILL.md +120 -0
  35. package/skills/ctf-ai-ml/adversarial-ml.md +623 -0
  36. package/skills/ctf-ai-ml/llm-attacks.md +487 -0
  37. package/skills/ctf-ai-ml/model-attacks.md +422 -0
  38. package/skills/ctf-crypto/SKILL.md +320 -0
  39. package/skills/ctf-crypto/advanced-math.md +798 -0
  40. package/skills/ctf-crypto/classic-ciphers.md +651 -0
  41. package/skills/ctf-crypto/ecc-attacks.md +347 -0
  42. package/skills/ctf-crypto/exotic-crypto-2.md +380 -0
  43. package/skills/ctf-crypto/exotic-crypto.md +528 -0
  44. package/skills/ctf-crypto/historical.md +113 -0
  45. package/skills/ctf-crypto/lattice-and-lwe.md +524 -0
  46. package/skills/ctf-crypto/modern-ciphers-2.md +563 -0
  47. package/skills/ctf-crypto/modern-ciphers-3.md +453 -0
  48. package/skills/ctf-crypto/modern-ciphers.md +649 -0
  49. package/skills/ctf-crypto/prng-attacks.md +257 -0
  50. package/skills/ctf-crypto/prng.md +664 -0
  51. package/skills/ctf-crypto/rsa-attacks-2.md +792 -0
  52. package/skills/ctf-crypto/rsa-attacks.md +487 -0
  53. package/skills/ctf-crypto/stream-ciphers.md +390 -0
  54. package/skills/ctf-crypto/zkp-and-advanced.md +456 -0
  55. package/skills/ctf-forensics/3d-printing.md +121 -0
  56. package/skills/ctf-forensics/SKILL.md +379 -0
  57. package/skills/ctf-forensics/disk-advanced.md +497 -0
  58. package/skills/ctf-forensics/disk-and-memory.md +491 -0
  59. package/skills/ctf-forensics/disk-recovery.md +699 -0
  60. package/skills/ctf-forensics/linux-forensics.md +511 -0
  61. package/skills/ctf-forensics/network-advanced.md +583 -0
  62. package/skills/ctf-forensics/network.md +645 -0
  63. package/skills/ctf-forensics/peripheral-capture.md +287 -0
  64. package/skills/ctf-forensics/signals-and-hardware.md +713 -0
  65. package/skills/ctf-forensics/steganography.md +694 -0
  66. package/skills/ctf-forensics/stego-advanced-2.md +475 -0
  67. package/skills/ctf-forensics/stego-advanced.md +481 -0
  68. package/skills/ctf-forensics/stego-image.md +691 -0
  69. package/skills/ctf-forensics/windows.md +625 -0
  70. package/skills/ctf-malware/SKILL.md +181 -0
  71. package/skills/ctf-malware/c2-and-protocols.md +274 -0
  72. package/skills/ctf-malware/pe-and-dotnet.md +108 -0
  73. package/skills/ctf-malware/scripts-and-obfuscation.md +449 -0
  74. package/skills/ctf-misc/SKILL.md +498 -0
  75. package/skills/ctf-misc/bashjails.md +323 -0
  76. package/skills/ctf-misc/ctfd-navigation.md +465 -0
  77. package/skills/ctf-misc/dns.md +255 -0
  78. package/skills/ctf-misc/encodings-advanced.md +504 -0
  79. package/skills/ctf-misc/encodings.md +431 -0
  80. package/skills/ctf-misc/games-and-vms-2.md +254 -0
  81. package/skills/ctf-misc/games-and-vms-3.md +690 -0
  82. package/skills/ctf-misc/games-and-vms-4.md +229 -0
  83. package/skills/ctf-misc/games-and-vms.md +529 -0
  84. package/skills/ctf-misc/linux-privesc.md +333 -0
  85. package/skills/ctf-misc/pyjails.md +671 -0
  86. package/skills/ctf-misc/rf-sdr.md +91 -0
  87. package/skills/ctf-osint/SKILL.md +198 -0
  88. package/skills/ctf-osint/geolocation-and-media.md +464 -0
  89. package/skills/ctf-osint/social-media.md +312 -0
  90. package/skills/ctf-osint/web-and-dns.md +341 -0
  91. package/skills/ctf-pwn/SKILL.md +214 -0
  92. package/skills/ctf-pwn/advanced-exploits-2.md +579 -0
  93. package/skills/ctf-pwn/advanced-exploits-3.md +598 -0
  94. package/skills/ctf-pwn/advanced-exploits-4.md +590 -0
  95. package/skills/ctf-pwn/advanced-exploits-5.md +119 -0
  96. package/skills/ctf-pwn/advanced-exploits.md +773 -0
  97. package/skills/ctf-pwn/advanced.md +326 -0
  98. package/skills/ctf-pwn/field-notes.md +245 -0
  99. package/skills/ctf-pwn/format-string.md +694 -0
  100. package/skills/ctf-pwn/heap-fsop.md +285 -0
  101. package/skills/ctf-pwn/heap-techniques-2.md +333 -0
  102. package/skills/ctf-pwn/heap-techniques.md +513 -0
  103. package/skills/ctf-pwn/kernel-bypass.md +421 -0
  104. package/skills/ctf-pwn/kernel-techniques.md +366 -0
  105. package/skills/ctf-pwn/kernel.md +636 -0
  106. package/skills/ctf-pwn/overflow-basics.md +611 -0
  107. package/skills/ctf-pwn/rop-advanced.md +725 -0
  108. package/skills/ctf-pwn/rop-and-shellcode.md +659 -0
  109. package/skills/ctf-pwn/sandbox-escape.md +313 -0
  110. package/skills/ctf-reverse/SKILL.md +163 -0
  111. package/skills/ctf-reverse/anti-analysis-ctf.md +204 -0
  112. package/skills/ctf-reverse/anti-analysis.md +693 -0
  113. package/skills/ctf-reverse/field-notes.md +376 -0
  114. package/skills/ctf-reverse/languages-compiled.md +666 -0
  115. package/skills/ctf-reverse/languages-platforms.md +592 -0
  116. package/skills/ctf-reverse/languages.md +553 -0
  117. package/skills/ctf-reverse/patterns-ctf-2.md +397 -0
  118. package/skills/ctf-reverse/patterns-ctf-3.md +797 -0
  119. package/skills/ctf-reverse/patterns-ctf.md +670 -0
  120. package/skills/ctf-reverse/patterns-runtime.md +274 -0
  121. package/skills/ctf-reverse/patterns.md +572 -0
  122. package/skills/ctf-reverse/platforms-hardware.md +387 -0
  123. package/skills/ctf-reverse/platforms.md +664 -0
  124. package/skills/ctf-reverse/tools-advanced-2.md +421 -0
  125. package/skills/ctf-reverse/tools-advanced.md +407 -0
  126. package/skills/ctf-reverse/tools-dynamic.md +679 -0
  127. package/skills/ctf-reverse/tools-emulation.md +319 -0
  128. package/skills/ctf-reverse/tools.md +573 -0
  129. package/skills/ctf-web/SKILL.md +153 -0
  130. package/skills/ctf-web/auth-and-access-2.md +82 -0
  131. package/skills/ctf-web/auth-and-access.md +783 -0
  132. package/skills/ctf-web/auth-infra.md +321 -0
  133. package/skills/ctf-web/auth-jwt.md +186 -0
  134. package/skills/ctf-web/client-side-advanced.md +739 -0
  135. package/skills/ctf-web/client-side.md +529 -0
  136. package/skills/ctf-web/cves.md +373 -0
  137. package/skills/ctf-web/field-notes.md +482 -0
  138. package/skills/ctf-web/node-and-prototype.md +200 -0
  139. package/skills/ctf-web/server-side-2.md +337 -0
  140. package/skills/ctf-web/server-side-advanced-2.md +559 -0
  141. package/skills/ctf-web/server-side-advanced-3.md +125 -0
  142. package/skills/ctf-web/server-side-advanced-4.md +480 -0
  143. package/skills/ctf-web/server-side-advanced.md +378 -0
  144. package/skills/ctf-web/server-side-deser.md +443 -0
  145. package/skills/ctf-web/server-side-exec-2.md +799 -0
  146. package/skills/ctf-web/server-side-exec.md +457 -0
  147. package/skills/ctf-web/server-side.md +629 -0
  148. package/skills/ctf-web/sql-injection.md +790 -0
  149. package/skills/ctf-web/web3.md +374 -0
  150. package/skills/ctf-writeup/SKILL.md +90 -0
  151. package/skills/solve-challenge/SKILL.md +269 -0
  152. package/skills.json +16 -0
@@ -0,0 +1,553 @@
1
+ # CTF Reverse - Language-Specific Techniques
2
+
3
+ ## Table of Contents
4
+ - [Python Bytecode Reversing (dis.dis output)](#python-bytecode-reversing-disdis-output)
5
+ - [Common Pattern: XOR Validation with Split Indices](#common-pattern-xor-validation-with-split-indices)
6
+ - [Bytecode Analysis Tips](#bytecode-analysis-tips)
7
+ - [Python Opcode Remapping](#python-opcode-remapping)
8
+ - [Identification](#identification)
9
+ - [Recovery](#recovery)
10
+ - [Pyarmor 8/9 Static Unpack (1shot)](#pyarmor-89-static-unpack-1shot)
11
+ - [DOS Stub Analysis](#dos-stub-analysis)
12
+ - [Unity IL2CPP Games](#unity-il2cpp-games)
13
+ - [HarmonyOS HAP/ABC Reverse (abc-decompiler)](#harmonyos-hapabc-reverse-abc-decompiler)
14
+ - [Brainfuck/Esolangs](#brainfuckesolangs)
15
+ - [Brainfuck Character-by-Character Static Analysis (BSidesSF 2026)](#brainfuck-character-by-character-static-analysis-bsidessf-2026)
16
+ - [Brainfuck Side-Channel via Read Count Oracle (BSidesSF 2026)](#brainfuck-side-channel-via-read-count-oracle-bsidessf-2026)
17
+ - [Brainfuck Comparison Idiom Detection (BSidesSF 2026)](#brainfuck-comparison-idiom-detection-bsidessf-2026)
18
+ - [UEFI Binary Analysis](#uefi-binary-analysis)
19
+ - [Transpilation to C](#transpilation-to-c)
20
+ - [Code Coverage Side-Channel Attack](#code-coverage-side-channel-attack)
21
+ - [Functional Language Reversing (OPAL)](#functional-language-reversing-opal)
22
+ - [Python Version-Specific Bytecode (VuwCTF 2025)](#python-version-specific-bytecode-vuwctf-2025)
23
+ - [Non-Bijective Substitution Cipher Reversing](#non-bijective-substitution-cipher-reversing)
24
+ - [FRACTRAN Program Inversion (Boston Key Party 2016)](#fractran-program-inversion-boston-key-party-2016)
25
+ - [GNU Make Turing Machine Simulator (Hack.lu 2018)](#gnu-make-turing-machine-simulator-hacklu-2018)
26
+
27
+ For platform/framework-specific techniques (Android, Roblox, Godot, Electron, Node.js, Verilog, Ruby/Perl polyglot, etc.), see [languages-platforms.md](languages-platforms.md).
28
+ For Go and Rust binary reversing, see [languages-compiled.md](languages-compiled.md).
29
+
30
+ ---
31
+
32
+ ## Python Bytecode Reversing (dis.dis output)
33
+
34
+ ### Common Pattern: XOR Validation with Split Indices
35
+
36
+ Challenge gives raw CPython bytecode (dis.dis disassembly). Common pattern:
37
+ 1. Check flag length
38
+ 2. XOR chars at even indices with key1, compare to list p1
39
+ 3. XOR chars at odd indices with key2, compare to list p2
40
+
41
+ **Reversing:**
42
+ ```python
43
+ # Given: p1, p2 (expected values), key1, key2 (XOR keys)
44
+ flag = [''] * flag_length
45
+ for i in range(len(p1)):
46
+ flag[2*i] = chr(p1[i] ^ key1) # Even indices
47
+ flag[2*i+1] = chr(p2[i] ^ key2) # Odd indices
48
+ print(''.join(flag))
49
+ ```
50
+
51
+ ### Bytecode Analysis Tips
52
+ - `LOAD_CONST` followed by `COMPARE_OP` reveals expected values
53
+ - `BINARY_XOR` identifies the transformation
54
+ - `BUILD_TUPLE`/`BUILD_LIST` with constants = expected output array
55
+ - Loop structure: `FOR_ITER` + `BINARY_SUBSCR` = iterating over flag chars
56
+ - `CALL_FUNCTION` on `ord` = character-to-int conversion
57
+
58
+ **Key insight:** Python bytecode challenges give you the algorithm in explicit stack operations. Focus on `LOAD_CONST` values (expected outputs), `BINARY_XOR`/`BINARY_ADD` (the transform), and `BUILD_TUPLE` (the target array) to reconstruct the validation logic without running the bytecode.
59
+
60
+ ---
61
+
62
+ ## Python Opcode Remapping
63
+
64
+ ### Identification
65
+ Decompiler fails with opcode errors.
66
+
67
+ ### Recovery
68
+ 1. Find modified `opcode.pyc` in PyInstaller bundle
69
+ 2. Compare with original Python opcodes
70
+ 3. Build mapping: `{new_opcode: original_opcode}`
71
+ 4. Patch target .pyc
72
+ 5. Decompile normally
73
+
74
+ **Shortcut (Hack.lu CTF 2013):** If the challenge bundles its own modified Python interpreter (e.g., a custom `./py` binary), install `uncompyle2`/`uncompyle6` into that interpreter's environment and decompile using the challenge's own runtime. The modified interpreter understands its own opcode mapping, so standard decompilation tools work without manual opcode recovery.
75
+
76
+ **Tool selection by Python version:** `uncompyle6` supports Python 2.x–3.8. For Python 3.9+ bytecode, use [`pycdc`](https://github.com/zrax/pycdc) (compile from source: `git clone && cmake . && make`).
77
+
78
+ **Key insight:** Opcode remapping breaks all standard decompilers. The fastest fix is to find the modified `opcode.pyc` in the PyInstaller bundle, diff it against the stock Python opcodes, and patch the target `.pyc` back to standard opcodes before decompiling.
79
+
80
+ ---
81
+
82
+ ## Pyarmor 8/9 Static Unpack (1shot)
83
+
84
+ - Tool: `Lil-House/Pyarmor-Static-Unpack-1shot`
85
+ - Use for Pyarmor 8.x/9.x armored scripts without executing sample code
86
+ - Quick signature check: payload typically starts with `PY` + six digits (Pyarmor 7 and earlier `PYARMOR` format is not supported)
87
+
88
+ Workflow:
89
+ 1. Ensure target directory contains armored scripts and matching `pyarmor_runtime` library.
90
+ 2. Run one-shot unpack to emit `.1shot.` outputs (disassembly + experimental decompile).
91
+ 3. Treat disassembly as ground truth; verify decompiled source with bytecode when inconsistent.
92
+
93
+ ```bash
94
+ python /path/to/oneshot/shot.py /path/to/scripts
95
+ ```
96
+
97
+ Optional flags:
98
+ ```bash
99
+ # Specify runtime explicitly
100
+ python /path/to/oneshot/shot.py /path/to/scripts -r /path/to/pyarmor_runtime.so
101
+
102
+ # Write outputs to another directory
103
+ python /path/to/oneshot/shot.py /path/to/scripts -o /path/to/output
104
+ ```
105
+
106
+ Notes:
107
+ - `oneshot/pyarmor-1shot` executable must exist before running `shot.py`.
108
+ - PyInstaller bundles or archives should be unpacked first, then processed with 1shot.
109
+
110
+ **Key insight:** Pyarmor 8/9 wraps scripts with runtime decryption. The 1shot tool statically unpacks without execution by directly processing the armored bytecode and `pyarmor_runtime` library. Treat the disassembly output as ground truth when the experimental decompiled source looks inconsistent.
111
+
112
+ ---
113
+
114
+ ## DOS Stub Analysis
115
+
116
+ PE files can hide code in DOS stub:
117
+ 1. Check for large DOS stub in Ghidra/IDA
118
+ 2. Run in DOSBox
119
+ 3. Load in IDA as 16-bit DOS
120
+ 4. Look for `int 16h` (keyboard input)
121
+
122
+ **Key insight:** PE files can embed a fully functional 16-bit DOS program in the DOS stub (before the PE header). If the stub is unusually large, load it in IDA as 16-bit DOS or run it in DOSBox -- the challenge logic may live entirely in the stub.
123
+
124
+ ---
125
+
126
+ ## Unity IL2CPP Games
127
+
128
+ - Use Il2CppDumper to dump symbols
129
+ - If Il2CppDumper fails, consider that `global-metadata.dat` may be encrypted; search strings/xrefs in the main binary and inspect the metadata loading path for custom decryption before dump.
130
+ - Look for `Start()` functions
131
+ - Key derivation: `key = SHA256(companyName + "\n" + productName)`
132
+ - Decrypt server responses with derived key
133
+
134
+ Please note most of that the executable file for the PC platform is GameAssembly.dll or *Assembly.dll, for the Android is libil2cpp.so.
135
+
136
+ **Key insight:** IL2CPP compiles C# to native code, but Il2CppDumper recovers method names and offsets. If the dumper fails, the `global-metadata.dat` is likely encrypted -- trace the metadata loading path in the native binary to find the custom decryption before dumping.
137
+
138
+ ---
139
+
140
+ ## HarmonyOS HAP/ABC Reverse (abc-decompiler)
141
+
142
+ - Target files: `.hap` package and embedded `.abc` bytecode
143
+ - Tool: `https://github.com/ohos-decompiler/abc-decompiler`
144
+ - Download `jadx-dev-all.jar` from releases
145
+
146
+ Critical startup note:
147
+ - `java -jar` may enter GUI mode
148
+ - For CLI mode, always use:
149
+
150
+ ```bash
151
+ java -cp "./jadx-dev-all.jar" jadx.cli.JadxCLI [options] <input>
152
+ ```
153
+
154
+ Most common commands:
155
+ ```bash
156
+ # Basic decompile to directory
157
+ java -cp "./jadx-dev-all.jar" jadx.cli.JadxCLI -d "out" ".abc"
158
+
159
+ # Decompile .abc (recommended for this scenario)
160
+ java -cp "./jadx-dev-all.jar" jadx.cli.JadxCLI -m simple -d "out_hap" "modules.abc"
161
+ ```
162
+
163
+ Recommended parameters for this challenge:
164
+ - `-m simple`: reduce high-level reconstruction to avoid SSA/PHI-heavy failures
165
+ - `--log-level ERROR`: keep only critical errors
166
+ - Full recommended command:
167
+
168
+ ```bash
169
+ java -cp "./jadx-dev-all.jar" jadx.cli.JadxCLI -m simple --log-level ERROR -d "out_abc_simple" "modules.abc"
170
+ ```
171
+
172
+ Parameter quick reference:
173
+ - `-d` output directory
174
+ - `--help` help
175
+
176
+ Notes:
177
+ - `.hap` is a package: extract it first (zip), then locate and analyze `.abc`
178
+ - Quote paths containing spaces or non-ASCII characters
179
+ - Use a new output directory name per run to avoid stale results
180
+ - Errors do not always mean full failure; prioritize `out_xxx/sources/`
181
+ - If `auto` fails, switch to `-m simple` first
182
+
183
+ Standard workflow:
184
+ 1. Run with `-m simple --log-level ERROR`
185
+ 2. Inspect key business files in output (for example `pages/Index.java`)
186
+ 3. If cleaner output is needed, retry with `-m auto` or `-m restructure`
187
+ 4. If some methods still fail, keep the `simple` output and continue logic analysis via alternate paths
188
+
189
+ **Key insight:** HarmonyOS `.hap` packages are ZIP archives containing `.abc` bytecode. Use the abc-decompiler's CLI mode (`jadx.cli.JadxCLI`) with `-m simple` for the most reliable decompilation -- GUI mode may launch instead of processing files.
190
+
191
+ ---
192
+
193
+ ## Brainfuck/Esolangs
194
+
195
+ - Check if compiled with known tools (BF-it)
196
+ - Understand tape/memory model
197
+ - Static analysis of cell operations
198
+
199
+ ### Brainfuck Character-by-Character Static Analysis (BSidesSF 2026)
200
+
201
+ **Pattern (i-love-my-bf-part1):** BF programs that validate input character-by-character follow a recognizable pattern: `,` (read char) followed by a sequence of `+` operations whose count equals the expected ASCII value of that character.
202
+
203
+ **Extraction technique:**
204
+ ```python
205
+ import re
206
+
207
+ bf_code = open('challenge.bf', 'r').read()
208
+
209
+ # Split on comma (input read) — each segment handles one character
210
+ segments = bf_code.split(',')
211
+ expected = []
212
+
213
+ for seg in segments[1:]: # Skip preamble before first comma
214
+ # Count consecutive '+' operations before any branch/output
215
+ plus_count = 0
216
+ for ch in seg:
217
+ if ch == '+':
218
+ plus_count += 1
219
+ elif ch in '-.[]><':
220
+ break # Stop at first non-increment operation
221
+ if plus_count > 0:
222
+ expected.append(chr(plus_count % 256))
223
+
224
+ flag = ''.join(expected)
225
+ print(f"Flag: {flag}")
226
+ ```
227
+
228
+ **Variations:**
229
+ - `-` operations: character value = `256 - minus_count`
230
+ - Mixed `+`/`-`: net increment determines value
231
+ - Cell reset (`[-]`) between characters: each segment is independent
232
+ - Loop-based multiplication: `[->>+++<<]` multiplies by 3 — count the inner operations
233
+
234
+ **Detection:** Large BF file with repeating pattern of `,` followed by many `+` or `-` characters, then a comparison structure (`[-]` or `[->+<]` patterns).
235
+
236
+ **Key insight:** BF programs that check input are structurally simple — each input byte is compared against a constant built by incrementing a cell. Extract the increment counts to recover the expected input without running the program.
237
+
238
+ **References:** BSidesSF 2026 "i-love-my-bf-part1"
239
+
240
+ ### Brainfuck Side-Channel via Read Count Oracle (BSidesSF 2026)
241
+
242
+ **Pattern (i-love-my-bf-part2):** When a BF program validates input character-by-character, a correct character causes the program to consume MORE input bytes (advancing to check the next position). By counting how many `,` (read) operations execute for each candidate input, the character that triggers the most reads is correct.
243
+
244
+ ```python
245
+ import itertools
246
+
247
+ def bytes_read_running_bf(bf_code, input_iter, braces):
248
+ """Run BF and count how many input bytes were consumed."""
249
+ tape = [0] * 30000
250
+ ptr = ip = reads = 0
251
+ input_list = list(input_iter)
252
+ input_idx = 0
253
+ while ip < len(bf_code):
254
+ c = bf_code[ip]
255
+ if c == ',':
256
+ if input_idx < len(input_list):
257
+ tape[ptr] = input_list[input_idx]
258
+ input_idx += 1
259
+ reads += 1
260
+ else:
261
+ return reads
262
+ elif c == '.': pass
263
+ elif c == '+': tape[ptr] = (tape[ptr] + 1) % 256
264
+ elif c == '-': tape[ptr] = (tape[ptr] - 1) % 256
265
+ elif c == '>': ptr += 1
266
+ elif c == '<': ptr -= 1
267
+ elif c == '[' and tape[ptr] == 0: ip = braces[ip]
268
+ elif c == ']' and tape[ptr] != 0: ip = braces[ip]
269
+ ip += 1
270
+ return reads
271
+
272
+ # Recover flag character by character
273
+ PRINTABLE = list(range(32, 127))
274
+ flag = []
275
+ for pos in range(50): # max flag length
276
+ best_byte = None
277
+ max_reads = 0
278
+ baseline = bytes_read_running_bf(bf, flag + [PRINTABLE[0]], braces)
279
+ for b in PRINTABLE[1:]:
280
+ reads = bytes_read_running_bf(bf, flag + [b], braces)
281
+ if reads > baseline:
282
+ best_byte = b
283
+ break
284
+ if best_byte is None:
285
+ break
286
+ flag.append(best_byte)
287
+ print(bytes(flag).decode())
288
+ ```
289
+
290
+ **Key insight:** BF input validation programs are sequential — they read one character, check it, and only read the next if it matches. The character causing more reads is correct because the program advances past the validation gate to check the next position.
291
+
292
+ **References:** BSidesSF 2026 "i-love-my-bf-part2"
293
+
294
+ ### Brainfuck Comparison Idiom Detection (BSidesSF 2026)
295
+
296
+ **Pattern (i-love-my-bf-part3):** BF programs compiled from higher-level languages use recognizable comparison idioms. The equality check `<[-<->] +<[>-<[-]]>[-<+>]` compares two adjacent cells. By instrumenting a BF interpreter to detect this pattern during execution, you can extract the comparison operands (expected flag bytes) directly from the tape.
297
+
298
+ ```python
299
+ EQ_PATTERN = "<[-<->] +<[>-<[-]]>[-<+>]"
300
+
301
+ def instrumented_bf_run(bf_code, dummy_input):
302
+ """Run BF, detect equality comparisons, extract operands."""
303
+ tape = [0] * 30000
304
+ ptr = ip = 0
305
+ comparisons = []
306
+
307
+ while ip < len(bf_code):
308
+ # Check if current position starts the eq pattern
309
+ if bf_code[ip:ip+len(EQ_PATTERN)] == EQ_PATTERN:
310
+ # The two cells being compared are at ptr-2 and ptr-1
311
+ lhs = tape[ptr - 2] # User input byte
312
+ rhs = tape[ptr - 1] # Expected byte
313
+ comparisons.append((chr(lhs), chr(rhs)))
314
+ # ... normal BF execution ...
315
+ ip += 1
316
+
317
+ return comparisons
318
+
319
+ # Expected bytes from comparisons reveal the flag
320
+ ```
321
+
322
+ **Key insight:** Compiled BF programs reuse fixed idioms for operations like equality comparison, conditional branching, and loops. Pattern-matching these idioms in the BF source or during execution lets you extract constants without fully understanding the program logic.
323
+
324
+ **Common BF idioms:**
325
+ - `[-]` — clear cell (set to 0)
326
+ - `[->+<]` — move cell right
327
+ - `<[-<->] +<[>-<[-]]>[-<+>]` — equality comparison of two cells
328
+
329
+ **References:** BSidesSF 2026 "i-love-my-bf-part3"
330
+
331
+ ---
332
+
333
+ ## UEFI Binary Analysis
334
+
335
+ ```bash
336
+ 7z x firmware.bin -oextracted/
337
+ file extracted/* | grep "PE32+"
338
+ ```
339
+
340
+ - Bootkit replaces boot loader
341
+ - Custom VM protects decryption
342
+ - Lift VM bytecode to C
343
+
344
+ **Key insight:** UEFI binaries are PE32+ executables. Extract the firmware with `7z`, identify PE files with `file`, and load them in Ghidra/IDA. Bootkits replace the boot loader, so focus on DXE drivers and boot services protocols for the challenge logic.
345
+
346
+ ---
347
+
348
+ ## Transpilation to C
349
+
350
+ For heavily obfuscated code:
351
+ ```python
352
+ for opcode, args in instructions:
353
+ if opcode == 'XOR':
354
+ print(f"r{args[0]} ^= r{args[1]};")
355
+ elif opcode == 'ADD':
356
+ print(f"r{args[0]} += r{args[1]};")
357
+ ```
358
+
359
+ Compile with `-O3` for constant folding.
360
+
361
+ **Key insight:** Transpiling obfuscated VM bytecode to C and compiling with `-O3` lets the compiler's constant folding and dead code elimination simplify the algorithm automatically. This is faster than manual deobfuscation for complex instruction sets.
362
+
363
+ ---
364
+
365
+ ## Code Coverage Side-Channel Attack
366
+
367
+ **Pattern (Coverup, Nullcon 2026):** PHP challenge provides XDebug code coverage data alongside encrypted output.
368
+
369
+ **How it works:**
370
+ - PHP code uses `xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE | XDEBUG_CC_BRANCH_CHECK)`
371
+ - Encryption uses data-dependent branches: `if ($xored == chr(0)) ... if ($xored == chr(1)) ...`
372
+ - Coverage JSON reveals which branches were executed during encryption
373
+ - This leaks the set of XOR intermediate values that occurred
374
+
375
+ **Exploitation:**
376
+ ```python
377
+ import json
378
+
379
+ # Load coverage data
380
+ with open('coverage.json') as f:
381
+ cov = json.load(f)
382
+
383
+ # Extract executed XOR values from branch coverage
384
+ executed_xored = set()
385
+ for line_no, hit_count in cov['encrypt.php']['lines'].items():
386
+ if hit_count > 0:
387
+ # Map line numbers to the chr(N) value in the if-statement
388
+ executed_xored.add(extract_value_from_line(line_no))
389
+
390
+ # For each position, filter candidates
391
+ for pos in range(len(ciphertext)):
392
+ candidates = []
393
+ for key_byte in range(256):
394
+ xored = plaintext_byte ^ key_byte # or reverse S-box lookup
395
+ if xored in executed_xored:
396
+ candidates.append(key_byte)
397
+ # Combined with known plaintext prefix, this uniquely determines key
398
+ ```
399
+
400
+ **Key insight:** Code coverage is a powerful oracle — it tells you which conditional paths were taken. Any encryption with data-dependent branching leaks information through coverage.
401
+
402
+ **Mitigation detection:** Look for branchless/constant-time crypto implementations that defeat this attack.
403
+
404
+ ---
405
+
406
+ ## Functional Language Reversing (OPAL)
407
+
408
+ **Pattern (Opalist, Nullcon 2026):** Binary compiled from OPAL (Optimized Applicative Language), a purely functional language.
409
+
410
+ **Recognition markers:**
411
+ - `.impl` (implementation) and `.sign` (signature) source files
412
+ - `IMPLEMENTATION` / `SIGNATURE` keywords
413
+ - Nested `IF..THEN..ELSE..FI` structures
414
+ - Functions named `f1`, `f2`, ... `fN` (numeric naming)
415
+ - Heavy use of `seq[nat]`, `string`, `denotation` types
416
+
417
+ **Reversing approach:**
418
+ 1. Pure functions are mathematically invertible — reverse each step in the pipeline
419
+ 2. Identify the transformation chain: `f_final(f_n(...f_2(f_1(input))...))`
420
+ 3. For each function, build the inverse
421
+
422
+ **Aggregate brute-force for scramble functions:**
423
+ When a transformation accumulates state that depends on original (unknown) values:
424
+ ```python
425
+ # Example: f8 adds cumulative offset based on parity of original bytes
426
+ # offset contribution per element depends on whether pre-scramble value is even/odd
427
+ # Total offset S = sum of contributions, but S mod 256 has only 256 possibilities
428
+
429
+ decoded = base64_decode(target)
430
+ for total_offset_S in range(256):
431
+ candidate = [(b - total_offset_S) % 256 for b in decoded]
432
+ # Verify: recompute S from candidate values
433
+ recomputed_S = sum(contribution(i, candidate[i]) for i in range(len(candidate))) % 256
434
+ if recomputed_S == total_offset_S:
435
+ # Apply remaining inverse steps
436
+ result = apply_inverse_substitution(candidate)
437
+ if all(32 <= c < 127 for c in result):
438
+ print(bytes(result))
439
+ ```
440
+
441
+ **Key lesson:** When a scramble function has a chicken-and-egg dependency (result depends on original, which is unknown), brute-force the aggregate effect (often mod 256 = 256 possibilities) rather than all possible states (exponential).
442
+
443
+ ---
444
+
445
+ ## Python Version-Specific Bytecode (VuwCTF 2025)
446
+
447
+ **Pattern (A New Machine):** Challenge targets specific Python version (e.g., 3.14.0 alpha).
448
+
449
+ **Key requirement:** Compile that exact Python version to disassemble bytecode — alpha/beta versions have different opcodes than stable releases.
450
+
451
+ ```bash
452
+ # Build specific Python version
453
+ wget https://www.python.org/ftp/python/3.14.0/Python-3.14.0a4.tar.xz
454
+ tar xf Python-3.14.0a4.tar.xz
455
+ cd Python-3.14.0a4 && ./configure && make -j$(nproc)
456
+ ./python -c "import dis, marshal; dis.dis(marshal.loads(open('challenge.pyc','rb').read()[16:]))"
457
+ ```
458
+
459
+ **Common validation:** Flag compared against tuple of squared ASCII values:
460
+ ```python
461
+ # Reverse: flag[i] = sqrt(expected_tuple[i])
462
+ import math
463
+ flag = ''.join(chr(int(math.isqrt(v))) for v in expected_values)
464
+ ```
465
+
466
+ ---
467
+
468
+ ## Non-Bijective Substitution Cipher Reversing
469
+
470
+ **Pattern (Coverup, Nullcon 2026):** S-box/substitution table has collisions (multiple inputs map to same output).
471
+
472
+ **Detection:**
473
+ ```python
474
+ sbox = [...] # substitution table
475
+ if len(set(sbox)) < len(sbox):
476
+ print("Non-bijective! Collisions exist.")
477
+ ```
478
+
479
+ **Building reverse lookup:**
480
+ ```python
481
+ from collections import defaultdict
482
+ rev_sub = defaultdict(list)
483
+ for i, v in enumerate(sbox):
484
+ rev_sub[v].append(i)
485
+ # rev_sub[output] = [list of possible inputs]
486
+ ```
487
+
488
+ **Disambiguation strategies:**
489
+ 1. Known plaintext format (e.g., `ENO{`, `flag{`) fixes key bytes at known positions
490
+ 2. Side-channel data (code coverage, timing) eliminates impossible candidates
491
+ 3. Printable ASCII constraint (32-126) reduces candidate space
492
+ 4. Re-encrypt candidates and verify against known ciphertext
493
+
494
+ ---
495
+
496
+ ## FRACTRAN Program Inversion (Boston Key Party 2016)
497
+
498
+ FRACTRAN: an esoteric language where computation is iterated multiplication by a fraction table. Input is encoded as prime factorization (ASCII values as exponents of sequential primes). To invert: swap each fraction's numerator and denominator, run the "success" output backward through the inverted program.
499
+
500
+ ```python
501
+ # Original: for each step, find first fraction where n*frac is integer
502
+ def fractran_step(n, fractions):
503
+ for num, den in fractions:
504
+ if (n * num) % den == 0:
505
+ return (n * num) // den
506
+ return None # Halt
507
+
508
+ # Inversion: swap num/denom in fraction table
509
+ inverted = [(d, n) for n, d in fraction_table]
510
+ # Run target output through inverted program to recover input
511
+ ```
512
+
513
+ **Key insight:** FRACTRAN programs can be inverted by swapping numerators and denominators. The prime factorization encoding is the key to understanding I/O -- factor the result to extract exponents of sequential primes, map to ASCII.
514
+
515
+ **Detection:** Challenge mentions fractions, prime factorization, or provides a list of rational numbers.
516
+
517
+ ---
518
+
519
+ ## GNU Make Turing Machine Simulator (Hack.lu 2018)
520
+
521
+ **Pattern:** A `Makefile` implements a Turing machine using only Make macros. The tape is a unary number encoded as `+++-` (each `+` is a 1, each `-` is a 0), the state transition table is 14 whitespace-separated words (9 bits each), and recursive `$(eval)` calls drive the state machine until it halts. Reverse-engineer the program by decoding the transition table and matching it against catalogued busy-beaver machines on the [bbchallenge.org](https://bbchallenge.org) database, or by re-implementing the interpreter in Python.
522
+
523
+ ```make
524
+ # Example sink — 14 words of 9 bits each form the transition table
525
+ PROGRAM := 0 1A 1R 1 1B 1L 1 1C 1R 0 1D 1L 0 1A 1L 1 1E 1R 1 1A 1L \
526
+ 1 1A 1L 0 1E 1R 0 1F 1R 0 1F 1L 1 1E 1L 1 1H 1R 0 1C 1R
527
+ ```
528
+
529
+ ```python
530
+ # Python decoder for the table
531
+ def decode_transition(word):
532
+ bits = int(word, 2)
533
+ write = bits >> 7 & 1
534
+ move = "LR"[bits >> 6 & 1]
535
+ state = chr(ord("A") + (bits & 0x3F))
536
+ return write, move, state
537
+
538
+ # Simulate until HALT
539
+ tape = [0] * 4096
540
+ head = 2048
541
+ state = "A"
542
+ while state != "H":
543
+ symbol = tape[head]
544
+ idx = (ord(state) - ord("A")) * 2 + symbol
545
+ write, move, state = decode_transition(PROGRAM[idx])
546
+ tape[head] = write
547
+ head += 1 if move == "R" else -1
548
+ print(sum(tape)) # Busy-beaver score → hashed for the flag
549
+ ```
550
+
551
+ **Key insight:** `Makefile` is Turing-complete via recursive `$(eval)` and string substitution, so any CTF that ships "just a Makefile" can be hiding a full interpreter. The fastest reverse path is to extract the transition table as text, decode each word, and either simulate locally or search public busy-beaver databases — most hand-rolled BB machines match published ones within the first 6 states. Use `make -n` to see expanded commands without executing, and `make -d` to watch the recursive eval graph.
552
+
553
+ **References:** Hackover CTF 2018 — Flagmaker, writeup 11503