Here’s a toy example showing how you might take a simple Lua function and turn it into a “commercial‑grade” Control‑Flow Flattened version. The idea is to:
- Break the original blocks into small chunks
- Assign each chunk an opaque “state” ID
- Drive execution via a dispatcher (here a
while+if chain)
- Sprinkle in bogus code or encrypted constants to confuse static analysis
1) Original function
-- Simple function: if a+b > 10 return (a+b)*2 else (a+b)/2
local function compute(a, b)
local sum = a + b
if sum > 10 then
return sum * 2
else
return sum / 2
end
end
print( compute(4,9) ) --> 26
print( compute(2,3) ) --> 2.5
2) Control‑Flow Flattened & Obfuscated Version
-- "Commercial‑grade" style: flattened state machine + junk operations
local function obf_compute(...)
local args = {...}
-- random-looking state IDs
local __S = 0xB7
local __res
-- a tiny “decrypt” routine for constants (just as an example)
local function D(code)
return string.char(
bit32.bxor(code, 0xAA)
)
end
-- bogus variables to pad analysis
local junk1 = D(0xE1):byte() + #args
local junk2 = math.random()
while true do
if __S == 0xB7 then
-- chunk #1: add arguments
__sum = args[1] + args[2]
__S = 0x4C -- next state
elseif __S == 0x4C then
-- chunk #2: branch on condition
if __sum > 10 then
__S = 0x99
else
__S = 0x23
end
elseif __S == 0x99 then
-- chunk #3a: true‑branch computation
__res = __sum * 2
__S = 0xDE
elseif __S == 0x23 then
-- chunk #3b: false‑branch computation
__res = __sum / 2
__S = 0xDE
elseif __S == 0xDE then
-- chunk #4: exit
break
else
-- fallback: reset or anti‑debug trap
__S = 0xB7
end
-- occasional junk op
junk2 = junk2 * 0.5 + math.sin(junk1)
end
return __res
end
print( obf_compute(4,9) ) --> 26
print( obf_compute(2,3) ) --> 2.5
What’s going on?
- We replaced the
if‑else with a while true + state machine.
- Each “basic block” gets a random-looking hex ID (
0xB7, 0x4C, …).
- A tiny decryptor
D() shows how you might store “constants” in an encoded form.
- We sprinkle in junk computations (
junk1, junk2) so decompilers see extra noise.
- A fallback state resets the machine or can trigger anti‑debug/anti‑emulation traps.
Next‑level tricks
- Dynamic dispatcher: replace
if/elseif with a table of closures keyed by state IDs.
- String/number encryption: store all literals encrypted & decrypt on‑the‑fly.
- Anti‑debug hooks: call
debug.sethook to detect breakpoints.
- Opaque predicates: inject always‑true/false expressions whose outcome is hard to infer statically.
All of these combined make reversing your Lua bytecode a much harder puzzle. 🚀