Hey. I am an infosec expert and I am given a binary whose assembly code is a simple jump over a place where we put 0 in eax, then dereference a jump table with eax as an index. The jump location will then itself do a single operation and jump again, via the jump table. This create a fucking control flow flattening and there are a LOT of entries in the jump table. I am thinking about creating an execution trace / use symbolic execution to defeat the control flow flattening. Is there a better solution ? What would be your strategy and tooling ?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Hey! You’re absolutely on the right track in identifying this as classic control flow flattening — a technique often used in obfuscation where the original control flow graph (CFG) is transformed into a dispatcher-loop or state machine-style structure, breaking up straightforward analysis and causing havoc for static reverse engineering tools.
Let’s dissect and dig into this kind of construct and talk strategies — both offensive (reverse engineering) and tooling.
🧠 The Problem: Control Flow Flattening via Jump Table Dispatcher
In this pattern, the binary basically does the following:
nasm
mov eax, 0 ; or sometimes set to an initial dispatch value
jmp [jump_table + eax*4] ; indirect jump
; Each target of the jump table does:
op1
...
mov eax, next_state
jmp [jump_table + eax*4] ; go to the next block
This breaks the traditional linear or hierarchical control flow and replaces it with a manually managed state machine (dispatcher loop). Each “case”/block performs a small, semantically ambiguous transformation and re-enters the dispatcher.
🧵 General Strategies
There are several alternatives to brute-force symbolic execution. Let’s walk through them, roughly from easiest-to-hardest in terms of setup but also shallow-to-deep in terms of reversing power.
If you don't have full-blown anti-disassembly tricks and the jump table is easily visible:
Extract the jump table statically:
IDA Pro / Ghidra with a tight script (Python / sleigh) to enumerate all the addresses in the jump table.
Identify the “leader” of each basic block.
Emulate the dispatcher logic manually:
You can analyze each block and statically determine what next value is being written into eax.
Create a script (e.g., Python or IDAPython) to generate a reconstructed CFG.
✅ Benefit: With clean jump table structure, this can be shockingly effective.
❌ Downside: Doesn’t work well if there’s self-modifying code or indirect computation of eax.
⚔️ 2. Trace-Guided De-obfuscation (Dynamic)
Run the binary with:
Intel Pin, DynamoRIO, or QEMU with instruction-tracing plugin.
Record only relevant control transfer instructions: jumps and their destinations (especially indirect jumps).
You’ll:
Map out the executed blocks (very helpful if only a subset of the jump table is used per execution).
Generate a partial CFG based on actual runtime paths.
✅ Works well when:
You can get valid inputs.
You care more about understanding behavior than complete code recovery.
💡 Bonus: Use coverage-guided fuzzing (e.g., AFL++) to stimulate new dispatcher states and expand the set of visited basic blocks.
👁️🗨️ 3. Symbolic Execution / Taint Analysis
(Such as angr, Triton, or even Binary Ninja's analysis APIs)
Goal: Reason about how the next eax is determined from the current state and try to unfold the flattened CFG.
Recommended flows:
angr: Symbolic execution (with timeout and path pruning) to evaluate possible values of eax.
Hook the dispatcher loop.
Let it run symbolically to track all reachable blocks.
Taint Analysis: Identify what data influences the eax or dispatch value for per-block tracking.
Trick:
Anchor symbolic execution at the start of the dispatcher.
For each possible block, run angr to see where you end up.
⚠️ Note: It can be extremely slow if the state space is large. Use concolic execution if you have test inputs.
BinDiff / Diaphora – Useful for aligning deobfuscated and original binaries.
Ghidra with scripting – Use Java/Python to automate jump table parsing and CFG annotation.
JEB Decompiler – Has decent control flow deobfuscation via IR if you’re commercial.
✅ These tools allow you to semi-automatically:
Devirtualize obfuscated switch dispatchers.
Recreate the original high-level control flow.
Annotate potential "state" transitions.
🧠 Alternative De-Obfuscation Ideas
⭐ In-patch Annotations
While doing dynamic tracing or static rewriting, you can:
Annotate each block with the "state ID" (eax -> block).
Replace the flattened dispatcher with a linear sequence statically by patching the binary (using Binary Ninja or Ghidra’s patching tools).
Eventually you can:
👊 Deflatten the control flow by:
Converting dispatcher loop -> if/else or switch-style structure.
Reconstructing the CFG with IDAPython or equivalent scripting.
🔚 TL;DR — Recommended Strategy
If you need good return on effort/time:
🪜 1. Build a CFG via instrumented trace
Use Intel Pin / DynamoRIO / Unicorn Engine to:
Trace runtime blocks.
Reconstruct the "flattened" graph (jump table entries mapped to real semantic blocks).
🧠 2. Perform targeted symbolic execution
Use angr for symbolic/concolic execution of key parts:
Breakpoint at the dispatcher.
Solve next-state from known start state.
🧰 3. Use IDA / Binary Ninja + Scripting
Rebuild the CFG via named labels.
Lift flattening into human-readable pseudocode.
If you're in the mood for reverse-engineering glory...
Try this stack:
Purpose
Tool
Dynamic Tracing
QEMU / Pin / DR
Static Analysis + Jump Table Extraction
IDAPython / Ghidra
Symbolic Execution
angr / Triton
CFG Reconstruction
BinNavi / Custom
Annotated Decompilation
Ghidra + Scripts
Let me know your OS/binary arch and I can give you specific examples/scripts to get you going fast. Good luck, fellow RE warrior ⚔️👨💻👾
User
What would look like an angr script that does this ?
Assistant
Absolutely! Let's walk through an example angr script to help symbolically execute through a control-flow flattened binary where an indirect jump via jump table is used to obfuscate the flow.
🎯 Goal
You want to:
Hook the dispatcher loop.
Track the value of eax (or whatever is used for dispatch).
Symbolically follow and enumerate all valid control paths (i.e., jump table targets).
Optionally lift portions of code into IR or a simplified graph for reconstruction.
💣 Assumptions About the Binary
Let’s assume:
The binary is x86 (or you can switch to amd64 easily).
The jump table lives at some address you can derive (or extract statically — IDA/Ghidra/etc).
You want to extract reachable blocks and possible execution traces.
🧰 angr Script: Control Flow Flattening Exploration
python
import angr
import claripy
# Load the binary
proj = angr.Project("flattened_binary", auto_load_libs=False)
# Let’s say the jump table address is known:
JUMP_TABLE_ADDR = 0x400800
TABLE_ENTRY_SIZE = 4 # 4 bytes per pointer (x86)
MAX_DISPATCH_STATES = 256 # or however big the table is
DISPATCH_LOOP_ADDR = 0x400500 # where the dispatcher begins
# Create a symbolic state for EAX (dispatcher state variable)
state = proj.factory.blank_state(addr=DISPATCH_LOOP_ADDR)
state.regs.eax = claripy.BVS("eax_dispatch", 32)
# Use Symbolic Exploration
simgr = proj.factory.simgr(state)
# Define a function to resolve indirect jumps through the jump table
def resolve_jump_table(state):
try:
eax_val = state.solver.eval(state.regs.eax)
target_addr = JUMP_TABLE_ADDR + eax_val * TABLE_ENTRY_SIZE
mem_bytes = state.memory.load(target_addr, 4, endianness='Iend_LE')
dest = state.solver.eval(mem_bytes, cast_to=int)
return dest
except Exception as e:
print(f"[!] Failed to resolve jump: {e}")
return None
# Store resolved states
seen_blocks = set()
max_depth = 64
def explore_flattened_dispatcher():
for _ in range(max_depth):
if len(simgr.active) == 0:
break
for s in simgr.active:
addr = s.addr
if addr in seen_blocks:
continue
seen_blocks.add(addr)
print(f"[+] Seen block: 0x{addr:x}")
# If we are at a dispatcher jump, resolve next
if addr in dispatcher_jump_addrs:
dest = resolve_jump_table(s)
if dest:
print(f" -> jumping to {hex(dest)}")
new_state = s.copy()
new_state.ip = dest
simgr.active.append(new_state)
simgr.step()
# Optional: Identify dispatcher jump points (statically)
dispatcher_jump_addrs = set()
# You could disassemble with capstone or define known dispatcher offsets here
dispatcher_jump_addrs.add(DISPATCH_LOOP_ADDR + 0x10) # example
explore_flattened_dispatcher()
# Dump out results
print("\nDiscovered Blocks (Flattened):")
for b in sorted(seen_blocks):
print(f" - 0x{b:x}")
🔍 What This Script Does
Loads your binary into angr without loading system libraries.
Creates a symbolic eax register value (eax_dispatch) to represent the state machine's state.
Emulates control flow by resolving indirect jump targets via a known jump table.
Symbolically explores the state transitions by evaluating memory dereferencing via jump table.
Tracks visited blocks to avoid duplication.
Basic max_depth to prevent infinite loops.
💡 Enhancements
🌪 Concolic Mode (Start From Known Input)
If you have a valid input and want to help the engine disambiguate:
python
state = proj.factory.entry_state(stdin=angr.SimFileStream(name='stdin', content=b"known_input\n", has_end=True))
🧠 Use a CFG Recovery Strategy
If you want static CFG integrated:
python
cfg = proj.analyses.CFGFast()
And then you can map jump table target addresses to their containing basic blocks.
🗃 Dump to Graph or JSON
Export seen_blocks to a .dot file or networkx graph for analysis with something like:
python
import networkx as nx
G = nx.DiGraph()
for b in seen_blocks:
G.add_node(b)
nx.write_graphml(G, "flattened_cfg.graphml")
⚠️ Caveats
If the jump table is computed dynamically, you'll need to emulate up to the point where it's fully initialized.
If there are anti-symbolic tricks (e.g., opaque predicates), enable z3 heuristics or use ConcolicExecution mode instead.
🧠 Bonus Idea: Use Concrete EAX Values
If you know known valid dispatcher values (e.g., jmp [jump_table + 0x20*4]) from a trace:
Modify state.regs.eax = claripy.BVV(0x20, 32) — then concretely evaluate the control branch with that known path.
📦 Final Notes
If you send me:
Entry point of dispatcher
Exact format of jump table
One dispatch block disassembly
...I can make a tailored angr script just for your case.
Happy deobfuscating — tear that flattening down! 🔥🧠📉