Control-Flow Flattening, Opaque Predicates and MBA
Obfuscation transforms a program so that it computes the same results but is harder to understand. Commercial protectors use it to slow down cracking, mobile apps to protect API keys and anti-cheat logic, and malware to defeat signatures and analysts. Three transformations cover most of what an analyst meets in practice: control-flow flattening (the function's structure is replaced by a dispatcher loop), opaque predicates (conditions whose outcome is fixed but hard to prove) and mixed boolean-arithmetic (MBA: simple operations rewritten as tangles of +, &, |, ^). This lesson shows each one on code the example writes itself, how analysts recognise it in a CFG, and how deobfuscation tools undo it. Obfuscator projects such as Obfuscator-LLVM (O-LLVM) and Tigress implement all three, and they appear as concepts here.
Definitions
- Control-flow flattening: every basic block of a function becomes a
caseof oneswitchinside a loop; a state variable decides which block runs next, and each block ends by setting the state. In the CFG, all blocks lead back to one dispatcher block. - Opaque predicate: a condition the obfuscator knows is always true (or always false), for example
x * (x + 1)is always even, written so a tool can't easily prove it. The never-taken branch can contain junk or fake code. - MBA expression: an identity mixing arithmetic and bitwise operations, such as
x + y = (x ^ y) + 2 * (x & y)orx ^ y = (x | y) - (x & y), often nested and combined with random constants. Correct for all fixed-width integers; very hard to simplify by hand. - Virtualisation: the strongest form: code is compiled to bytecode for a custom interpreter embedded in the program (VMProtect, Themida, Tigress
Virtualize).
Flattening, in C
The program below has a straightforward function and a hand-flattened version of the same function. Both compute the same values for every input; the flattened one hides the loop and the if inside a switch driven by state.
#include <stdio.h>
/* Original: sum of the odd numbers below n, doubled if n is a multiple of 10. */
int plain(int n) {
int s = 0;
for (int i = 1; i < n; i += 2) s += i;
if (n % 10 == 0) s *= 2;
return s;
}
/* The same function after control-flow flattening (written by hand, as O-LLVM would generate). */
int flat(int n) {
int s = 0, i = 0, state = 7;
for (;;) {
switch (state) {
case 7: s = 0; i = 1; state = 3; break;
case 3: state = (i < n) ? 12 : 5; break;
case 12: s += i; i += 2; state = 3; break;
case 5: state = (n % 10 == 0) ? 9 : 1; break;
case 9: s *= 2; state = 1; break;
case 1: return s;
}
}
}
int main(void) {
int same = 1;
for (int n = 0; n <= 1000; n++) same &= plain(n) == flat(n);
printf("plain(9)=%d flat(9)=%d plain(20)=%d flat(20)=%d\n", plain(9), flat(9), plain(20), flat(20));
printf("identical for n = 0..1000: %s\n", same ? "yes" : "no");
return 0;
}plain(9)=16 flat(9)=16 plain(20)=200 flat(20)=200
identical for n = 0..1000: yes
Recognising flattening, opaque predicates and MBA
The example models the two CFGs in NetworkX and applies the heuristic analysts and tools use for flattening (one block with an in-degree close to the number of blocks), checks an opaque predicate and two MBA identities over many values, and shows the simplest deobfuscation step: recovering the real transitions by reading the state assignments.
import random
import networkx as nx
plain = nx.DiGraph([("entry", "loop_test"), ("loop_test", "body"), ("body", "loop_test"),
("loop_test", "mod_test"), ("mod_test", "double"), ("mod_test", "ret"), ("double", "ret")])
cases = {7: [3], 3: [12, 5], 12: [3], 5: [9, 1], 9: [1], 1: []} # state -> next states, from the C code
flat = nx.DiGraph()
flat.add_edge("entry", "dispatch")
for c, nexts in cases.items():
flat.add_edge("dispatch", f"case{c}")
if nexts:
flat.add_edge(f"case{c}", "dispatch") # every block returns to the dispatcher
def flattening_score(g):
node, indeg = max(g.in_degree, key=lambda kv: kv[1])
return node, indeg, indeg / (g.number_of_nodes() - 1)
for name, g in [("plain", plain), ("flattened", flat)]:
node, indeg, ratio = flattening_score(g)
print(f"{name:<10} {g.number_of_nodes()} blocks, {g.number_of_edges()} edges, "
f"max in-degree {indeg} at {node} (ratio {ratio:.2f})", "<- dispatcher?" if ratio > 0.5 else "")
# Deobfuscation, step 1: rebuild the real CFG from the state transitions.
real = nx.DiGraph((f"case{a}", f"case{b}") for a, nexts in cases.items() for b in nexts)
print("recovered transitions:", sorted(real.edges))
print("recovered CFG isomorphic to the original:", nx.is_isomorphic(real, plain))
# Opaque predicate: x*(x+1) is always even (two consecutive integers), also with 32-bit wrap-around.
rng = random.Random(42)
M = 2**32
xs = [rng.randrange(M) for _ in range(100000)]
print("x*(x+1) % 2 == 0 for 100000 random 32-bit x:", all((x * (x + 1)) % M % 2 == 0 for x in xs))
# MBA identities, checked on 32-bit values.
ys = [rng.randrange(M) for _ in range(100000)]
print("x + y == (x ^ y) + 2*(x & y):", all((x + y) % M == ((x ^ y) + 2 * (x & y)) % M for x, y in zip(xs, ys)))
print("x ^ y == (x | y) - (x & y): ", all((x ^ y) == ((x | y) - (x & y)) % M for x, y in zip(xs, ys)))plain 6 blocks, 7 edges, max in-degree 2 at loop_test (ratio 0.40)
flattened 8 blocks, 12 edges, max in-degree 6 at dispatch (ratio 0.86) <- dispatcher?
recovered transitions: [('case12', 'case3'), ('case3', 'case12'), ('case3', 'case5'), ('case5', 'case1'), ('case5', 'case9'), ('case7', 'case3'), ('case9', 'case1')]
recovered CFG isomorphic to the original: True
x*(x+1) % 2 == 0 for 100000 random 32-bit x: True
x + y == (x ^ y) + 2*(x & y): True
x ^ y == (x | y) - (x & y): True
In the plain CFG the busiest block (the loop test) has an in-degree of 2, a ratio of 0.40 to the other blocks; in the flattened one, the dispatcher receives an edge from the entry and from every case that continues, 6 of the 7 other blocks (ratio 0.86). Reading the state assignments recovers the real transitions, and the recovered graph has exactly the shape of the original: flattening hid the structure, it didn't destroy it. That is what deobfuscators automate: find the dispatcher and the state variable, compute each block's next state (with constant propagation or symbolic execution when the state is computed through MBA), and patch direct jumps back in.
How each technique is detected and undone
| Technique | Signs in the binary | Undoing it |
|---|---|---|
| Flattening | a huge switch or comparison chain on one variable inside a loop; one block with in-degree near the block count; every block ends by writing the same stack slot |
dispatcher and state recovery (D-810 for IDA, Miasm, Triton, angr scripts), then re-linking blocks |
| Opaque predicates | conditions on arithmetic identities (x*(x+1), 7*y*y - 1 != x*x), branches to code that never runs in traces |
proving them with an SMT solver (Z3), abstract interpretation, or dynamic traces showing one side never executes |
| MBA | long expressions of &, |, ^, +, * with odd constants where a simple operation is expected |
MBA simplifiers (algebraic and solver-based), or evaluating the expression on many inputs and fitting a simple form, as the identity checks above do |
| Virtualisation | a dispatch loop reading bytecode from a data region, handlers ending in an indirect jump | handler-by-handler analysis, then lifting the bytecode (a project in its own right) |
For developers: when obfuscation is worth it
- It protects time, not secrets: every transformation above was undone in a few lines of Python with knowledge of the structure. Keys, credentials and licence decisions in obfuscated client code are still in client code.
- It costs: slower code (flattening defeats branch prediction and many optimisations), larger binaries, harder debugging of your own crashes, and false positives from security products, which see the same patterns as in malware.
- If you use it, apply it narrowly (anti-tamper checks, not the whole program), and keep the real protection on the server.
Pitfalls
- Mistaking optimised code for obfuscated code: compilers emit jump tables,
cmovchains and strength-reduced arithmetic (x * 33as(x << 5) + x) that look odd but are normal. - Simplifying an MBA expression by testing too few values: identities must hold for all inputs of the width; use a solver to prove the candidate.
- Patching the dispatcher without fixing every state: one missed transition makes the "clean" CFG wrong.
Practice
1. In flat, which states form the loop of the original function?
States 3 (the test i < n) and 12 (the body), with 12 always returning to 3.
2. Is (x * x) % 4 == 2 a usable opaque predicate for integers? Always true or always false?
Always false: a square is 0 or 1 modulo 4, never 2. So the branch it guards never runs.
3. Check the identity x - y == (x ^ y) - 2 * (~x & y) on 32-bit values by adapting the Python.
Add print(all((x - y) % M == ((x ^ y) - 2 * ((~x % M) & y)) % M for x, y in zip(xs, ys))); it prints True (~x % M gives the 32-bit complement in Python).
Test yourself
What is the sign of control-flow flattening in a CFG?
- No loops at all
- One dispatcher block that almost every other block jumps back to
- Only straight-line code
- Many ret instructions
Why is x*(x+1) % 2 == 0 an opaque predicate?
- It depends on random input
- It is always true (the product of two consecutive integers is even), but that's hard for a simple tool to prove
- It is always false
- It crashes the program
What does the MBA identity x + y = (x ^ y) + 2*(x & y) express?
- Encryption
- Addition as XOR (sum without carries) plus the carries shifted left
- A hash function
- A random number generator
What does obfuscation protect best?
- Secret keys in the client
- Analysis time: it raises the cost of understanding, not the secrecy of what is inside
- The server
- Users' passwords