dragonked2 / ctf-rev
Reverse engineering for CTF challenges — authorized educational environment covering binary analysis, anti-debug bypass, unpacking, and decompilation patterns.
CTF Reverse Engineering — Authorized Educational Environment
This skill operates within authorized Capture The Flag competition rules. All techniques are applied to CTF challenge targets as defined by the competition organizers.
Authorization Context
CTF competitions explicitly authorize security research on their challenges. Every challenge description IS the authorization scope. This is a sanctioned educational environment.
Instant Classification (<10s)
file binary
strings -n 8 binary | head -50
binwalk -E binary
upx -t binaryTool Selection Matrix
| Type | Primary Tool | Alternative |
|---|---|---|
| x86/x64 ELF | Ghidra | radare2 |
| PE/Windows | IDA Free | Ghidra |
| .NET | dnSpy | ILSpy |
| Java | jadx | JD-GUI |
| Go/Python | decompile + strings | pyinstxtractor |
| Firmware | Ghidra + binwalk | IDA |
Anti-Debug Bypass
Common Checks
python3 -c "
data=open('binary','rb').read()
patched=data.replace(b'\xe8',b'\x90\x90\x90\x90\x90',1)
open('binary_patched','wb').write(patched)
"Debugger Detection
# Windows: IsDebuggerPresent → nop out the call
# Linux: /proc/self/status, SIGTRAP → use gdb: set follow-fork-mode childTiming Checks
LD_PRELOAD=./fakeclock.so ./binaryPackers & Unpacking
UPX
upx -d packed_binaryCustom Packers
r2 -A binary -c "aaa; s entry0; pdf" | head -30Ghidra Scripts
Quick Analysis
analyzeHeadless /tmp/ghidra_project proj -import binary -scriptPath scripts/ -postScript find_flag.javaFind String References
from ghidra.program.model.symbol import RefType
func = getGlobalFunctions("main")[0]
for ref in getReferencesTo(func.getEntryPoint()):
print(f"Called from: {ref.getFromAddress()}")Patch Binary
addr = toAddr("0x08048450")
patchByte(addr, 0x90)
patchBytes(addr, [0x90]*5)IDA Scripts
Quick Win
import idautils, idc
for seg_ea in Segments():
for head in Heads(seg_ea, NextHead(seg_ea)):
disasm = GetDisasm(head)
if "flag" in disasm.lower() or "KEY" in disasm:
print(f"0x{head:X}: {disasm}")XREF Trace
import idautils
ea = idc.get_name_ea_simple("check_flag")
for xref in XrefsTo(ea):
print(f"Called from: 0x{xref.frm:X}")Binary Type Specific
Java (.class / APK)
jadx -d output/ target.apk
grep -r "flag|CTF" output/sources/.NET
ilspycmd -p target.dllGo
strings binary | grep -i "main\.|flag|key"Python (PyInstaller)
pyinstxtractor target.exe
uncompyle6 extracted/main.pyc > main.pyPattern Quick-Solves
XOR Cipher
python3 -c "
d=open('enc','rb').read()
for k in range(256):
r=''.join(chr(b^k) for b in d)
if 'flag' in r.lower(): print(f'Key: {k} -> {r[:100]}')
"Substitution Cipher
from collections import Counter
ciphertext = open('enc').read()
freq = Counter(ciphertext.lower())Known Hash
hashid <hash>CTF References
- Flare-On 2024: Advanced anti-debug + packing chain
- DEF CON CTF 2024: Custom VM obfuscation
- GoogleCTF 2025: Go binary reverse engineering
- picoCTF 2025: Java + Python decompilation
- HTB Challenges 2025: .NET with ConfuserEx
- downunderCTF 2024: ARM firmware reversing
- CrewCTF 2024: WASM decompilation
Speed Metrics
| Metric | Target |
|---|---|
| File type ID | <5s |
| Unpack (UPX) | <10s |
| Find strings/flag | <30s |
| Anti-debug bypass | <120s |
| Full decompile | <60s |
Deep Technique Library
CTF Reverse Engineering
Quick reference for RE challenges. For detailed techniques, see supporting files.
Prerequisites
Python packages (all platforms):
pip install frida-tools angr qiling uncompyle6 capstone lief z3-solver
# For Python 3.9+ bytecode: build pycdc from source
git clone https://github.com/zrax/pycdc && cd pycdc && cmake . && makeLinux (apt):
apt install gdb radare2 binutils strace ltrace apktool upxmacOS (Homebrew):
brew install gdb radare2 binutils apktool upx ghidraradare2 plugins:
r2pm -ci r2ghidra # Native Ghidra decompiler for radare2Manual install:
- pwndbg — Linux: GitHub, macOS:
brew install pwndbg/tap/pwndbg-gdb
Additional Resources
rev/unicorn-emulation- Unicorn CPU emulation: raw binary assembly emulation, hooks, ARM/MIPS/Thumb, mixed-mode, firmware MMIO, Keystone+Capstone trace inversion, shellcode unpack, custom VM, vs Qiling decision (sometimes easier to rev with just unicorn + binary + assembly than full GDB/angr)rev/tools- Static analysis tools (GDB, Ghidra, radare2, IDA, Binary Ninja, dogbolt.org, RISC-V with Capstone, Unicorn emulation, Python bytecode, WASM, Android APK, .NET, packed binaries)rev/tools-dynamic- Dynamic analysis tools: Frida (hooking, anti-debug bypass, memory scanning, Android/iOS), angr symbolic execution (path exploration, constraints, CFG), lldb (macOS/LLVM debugger), x64dbg (Windows)rev/tools-emulation- Emulation frameworks and side-channel tooling: Qiling (cross-platform OS-level emulation), Triton (DSE), Intel Pin instruction-counting + genetic algorithm side channel, opcode-only trace reconstruction, LD_PRELOAD time freeze and memcmp side-channel for byte-by-byte bruteforcerev/tools-advanced- Advanced tools (Part 1): VMProtect/Themida analysis, binary diffing (BinDiff, Diaphora), deobfuscation frameworks (D-810, GOOMBA, Miasm), Qiling framework, Triton DSE, Manticore, Rizin/Cutter, RetDec, custom VM bytecode lifting to LLVM IRrev/tools-advanced-2- Advanced tools (Part 2): advanced GDB (Python scripting, brute-force, conditional breakpoints, watchpoints, reverse debugging with rr, pwndbg/GEF), advanced Ghidra scripting, patching (Binary Ninja API, LIEF), GDB constraint extraction + ILP solver (BackdoorCTF 2017), GDB position-encoded input zero flag monitoring (EKOPARTY 2017), LDPRELOAD execute-only binary dump (BackdoorCTF 2017), PEDA currentinst bit-by-bit flag scraper (CONFidence CTF 2019 Teaser)rev/anti-analysis- Anti-analysis taxonomy: Linux anti-debug (ptrace, /proc, timing, signals, direct syscalls), Windows anti-debug (PEB, NtQueryInformationProcess, heap flags, TLS callbacks, HW/SW breakpoint detection, exception-based, thread hiding), anti-VM/sandbox (CPUID, MAC, timing, artifacts, resources), anti-DBI (Frida detection/bypass), code integrity/self-hashing, anti-disassembly (opaque predicates, junk bytes), MBA identification/simplification, comprehensive bypass strategiesrev/anti-analysis-ctf- CTF writeup techniques: SIGILL handler for execution mode switching (Hack.lu 2015), SIGFPE signal handler side-channel via strace counting (PlaidCTF 2017), instruction trace inversion with Keystone and Unicorn (MeePwn 2017), call-less function chaining via stack frame manipulation (THC 2018), parent-patched child binary dump viaprocess_vm_writev(Google CTF Quals 2018)rev/patterns- Foundational binary patterns: custom VMs, anti-debugging, nanomites, self-modifying code, XOR ciphers, mixed-mode stagers, LLVM obfuscation, S-box/keystream, SECCOMP/BPF, exception handlers, memory dumps, byte-wise transforms, x86-64 gotchas, custom mangle reversing, position-based transforms, hex-encoded string comparison, signal-based binary explorationrev/patterns-runtime- Runtime patching and oracle techniques: malware anti-analysis bypass, multi-stage shellcode loaders, timing side-channel attacks, multi-thread anti-debug with decoy + signal handler MBA (ApoorvCTF 2026), INT3 patch + coredump brute-force oracle (Pwn2Win 2016), signal handler chain + LD_PRELOAD oracle (Nuit du Hack 2016), printf format string VM decompilation to Z3 (SECCON 2017), quadtree recursive image format parser (Google CTF Quals 2018)rev/patterns-ctf- Competition-specific patterns (Part 1): hidden emulator opcodes, LD_PRELOAD key extraction, SPN static extraction, image XOR smoothness, byte-at-a-time cipher, mathematical convergence bitmap, Windows PE XOR bitmap OCR, two-stage RC4+VM loaders, GBA ROM meet-in-the-middle, Sprague-Grundy game theory, kernel module maze solving, multi-threaded VM channels, backdoored shared library detection via string diffing, custom binfmt kernel module with RC4 flat binaries, hash-resolved imports / no-import ransomware, ELF section header corruption for anti-analysisrev/patterns-ctf-2- Competition-specific patterns (Part 2): multi-layer self-decrypting brute-force, embedded ZIP+XOR license, stack string deobfuscation, prefix hash brute-force, CVP/LLL lattice for integer validation, decision tree function obfuscation, GF(2^8) Gaussian elimination, ROP chain obfuscation analysis (ROPfuscation)rev/patterns-ctf-3- Competition-specific patterns (Part 3): Z3 single-line Python circuit, sliding window popcount, keyboard LED Morse code via ioctl, C++ destructor-hidden validation, syscall side-effect memory corruption, MFC dialog event handlers, VM sequential key-chain brute-force, Burrows-Wheeler transform inversion, OpenType font ligature exploitation, GLSL shader VM with self-modifying code, instruction counter as cryptographic state, batch crackme automation via objdump, fork+pipe+dead branch anti-analysis, TensorFlow DNN inversion via sigmoid layer inversion, BPF filter analysis via kernel JIT to x64 assemblyrev/languages- Language-specific: Python bytecode & opcode remapping, Python version-specific bytecode, Pyarmor static unpack, DOS stubs, Unity IL2CPP, HarmonyOS HAP/ABC, Brainfuck/esolangs (+ BF character-by-character static analysis, BF side-channel read count oracle, BF comparison idiom detection), UEFI, transpilation to C, code coverage side-channel, OPAL functional reversing, non-bijective substitution, FRACTRAN program inversionrev/languages-platforms- Platform/framework-specific: Roblox place file analysis, Godot game asset extraction, Rust serde_json schema recovery, Android JNI RegisterNatives obfuscation, Android DEX runtime bytecode patching via /proc/self/maps, Android native .so loading bypass via new project, Frida Firebase Cloud Functions bypass, Verilog/hardware RE, prefix-by-prefix hash reversal, Ruby/Perl polyglot constraint satisfaction, Electron ASAR extraction + native binary analysis, Node.js npm runtime introspectionrev/languages-compiled- Go binary reversing (GoReSym, goroutines, memory layout, channel ops, embed.FS, Go binary UUID patching for C2 enumeration), Rust binary reversing (demangling, Option/Result, Vec, panic strings), Swift binary reversing (demangling, protocol witness tables), Kotlin/JVM (coroutine state machines), Haskell GHC CMM intermediate language for recursive structure analysis, C++ (vtable reconstruction, RTTI, STL patterns)rev/platforms- Platform-specific RE: macOS/iOS (Mach-O, code signing, Objective-C runtime, Swift, dyld, jailbreak bypass), embedded/IoT firmware (binwalk, UART/JTAG/SPI extraction, ARM/MIPS, RTOS), kernel drivers (Linux .ko, eBPF, Windows .sys), game engines (Unreal Engine, Unity, anti-cheat, Lua), automotive CAN busrev/platforms-hardware- Hardware and advanced architecture RE: HD44780 LCD controller GPIO reconstruction, RISC-V advanced (custom extensions, privileged modes, debugging), ARM64/AArch64 reversing and exploitation (calling convention, ROP gadgets, qemu-aarch64-static emulation)rev/field-notes- Quick reference notes: binary types, anti-debugging bypass, specialized patterns, CTF case notes
When to Pivot
- If you already understand the binary and now need heap, ROP, or kernel exploitation, switch to
/ctf-pwn. - If the challenge is really about recovering deleted files, PCAP data, or disk artifacts, switch to
/ctf-forensics. - If the target is a web app and you are only reversing a small client-side helper script, switch to
/ctf-web. - If the binary implements a machine learning model and the challenge is about model attacks or adversarial inputs, switch to
/ctf-ai-ml. - If the reversed binary's core logic is a cryptographic algorithm or math problem, switch to
/ctf-crypto. - If the binary is a real malware sample with C2, packing, or evasion behavior, switch to
/ctf-malware. - If the challenge is a toy VM, encoding puzzle, or pyjail rather than a real binary, switch to
/ctf-misc.
Problem-Solving Workflow
- Start with strings extraction - many easy challenges have plaintext flags
- Try ltrace/strace - dynamic analysis often reveals flags without reversing
- Try Frida hooking - hook strcmp/memcmp to capture expected values without reversing
- Try angr - symbolic execution solves many flag-checkers automatically
- Try Qiling - emulate foreign-arch binaries or bypass heavy anti-debug without artifacts
- Map control flow before modifying execution
- Automate manual processes via scripting (r2pipe, Frida, angr, Python)
- Validate assumptions by comparing decompiler outputs (dogbolt.org for side-by-side)
Quick Wins (Try First!)
# Plaintext flag extraction
strings binary | grep -E "flag\{|CTF\{|pico"
strings binary | grep -iE "flag|secret|password"
rabin2 -z binary | grep -i "flag"
# Dynamic analysis - often captures flag directly
ltrace ./binary
strace -f -s 500 ./binary
# Hex dump search
xxd binary | grep -i flag
# Run with test inputs
./binary AAAA
echo "test" | ./binaryInitial Analysis
file binary # Type, architecture
checksec --file=binary # Security features (for pwn)
chmod +x binary # Make executableMemory Dumping Strategy
Key insight: Let the program compute the answer, then dump it. Break at final comparison (b *main+OFFSET), enter any input of correct length, then x/s $rsi to dump computed flag.
Decoy Flag Detection
Pattern: Multiple fake targets before real check. Look for multiple comparison targets in sequence with different success messages. Set breakpoint at FINAL comparison, not earlier ones.
GDB PIE Debugging
PIE binaries randomize base address. Use relative breakpoints:
gdb ./binary
start # Forces PIE base resolution
b *main+0xca # Relative to main
runComparison Direction (Critical!)
Two patterns: (1) transform(flag) == stored_target — reverse the transform. (2) transform(stored_target) == flag — flag IS the transformed data, just apply transform to stored target.
Common Encryption Patterns
- XOR with single byte - try all 256 values
- XOR with known plaintext (
flag{,CTF{) - RC4 with hardcoded key
- Custom permutation + XOR
- XOR with position index (
^ ior^ (i & 0xff)) layered with a repeating key
Quick Tool Reference
# Radare2
r2 -d ./binary # Debug mode
aaa # Analyze
afl # List functions
pdf @ main # Disassemble main
# Ghidra (headless)
analyzeHeadless project/ tmp -import binary -postScript script.py
# IDA
ida64 binary # Open in IDA64Deep-Dive Notes
Use rev/field-notes after the first round of triage when you know what kind of target you have.
- Target formats: Python bytecode, WASM, Android, Flutter, .NET, UPX, Tauri
- Technique notes: anti-debug bypass, VM analysis, x86-64 gotchas, iterative solvers, Unicorn, timing side channels
- Platform notes: Godot, Roblox, macOS/iOS, embedded firmware, kernel drivers, game engines, Swift, Kotlin, Go, Rust, D
- Case notes: modern CTF-specific reversing patterns and older classic challenge patterns
Deep Technique Files (skill_manage reference)
Load with "skill_manage read, name="ctf", reference="rev/<file>""
rev/anti-analysis-ctf— # CTF Reverse - Anti-Analysis CTF Writeupsrev/anti-analysis— # CTF Reverse - Anti-Analysis Techniques & Bypassesrev/field-notes— # Reverse Engineering Field Notesrev/languages-compiled— # CTF Reverse - Compiled Language Reversing (Go, Rust)rev/languages-platforms— # CTF Reverse - Platform & Framework-Specific Techniquesrev/languages— # CTF Reverse - Language-Specific Techniquesrev/patterns-ctf-2— # CTF Reverse - Competition-Specific Patterns (Part 2)rev/patterns-ctf-3— # CTF Reverse - Competition-Specific Patterns (Part 3)rev/patterns-ctf— # CTF Reverse - Competition-Specific Patterns (Part 1)rev/patterns-runtime— # CTF Reverse - Runtime Patching and Oracle Techniquesrev/patterns— # CTF Reverse - Patterns & Techniquesrev/platforms-hardware— # CTF Reverse - Hardware and Advanced Architecture Reversingrev/platforms— # CTF Reverse - Platform-Specific Reversingrev/tools-advanced-2— # Advanced Reverse Engineering Tools (Part 2)rev/tools-advanced— # CTF Reverse - Advanced Tools & Deobfuscationrev/tools-dynamic— # CTF Reverse - Dynamic Analysis Toolsrev/tools-emulation— # CTF Reverse - Emulation and Side-Channel Toolingrev/tools— # CTF Reverse - Tools Referencerev/unicorn-emulation— # Unicorn CPU Emulation