Okay, here is a very simple example of a custom virtual machine (VM) implemented in Lua.
This VM has:
- A simple register set.
- A separate constant pool.
- A small, fixed instruction set.
- A basic fetch-decode-execute loop.
- A simple assembler to make writing the bytecode easier to read.
The obfuscation potential comes from:
- The bytecode being non-standard.
- The instruction set being potentially arbitrary or highly specific.
- Control flow being represented purely by jumps within the bytecode.
Disclaimer: This is a minimal example for demonstration. A real obfuscation VM would be significantly more complex, potentially including:
- More registers or a stack-based architecture.
- More complex data types (strings, tables, booleans, etc.).
- More instructions, including bitwise ops, function calls (potentially nested VM calls or calls to native Lua).
- More sophisticated control flow (loops, conditionals, exceptions).
- Anti-debugging/anti-analysis features.
- Bytecode encryption or mutation.
- A compiler that translates Lua code (or a subset) into the VM's bytecode.
-- ===================================================================
-- 1. Define the Instruction Set (Opcodes)
-- These are just numbers representing different operations.
-- ===================================================================
local OP_HALT = 0 -- Stop execution
local OP_LOADK = 1 -- Load constant into register: R[A] = K[B]
local OP_MOVE = 2 -- Move value from one register to another: R[A] = R[B]
local OP_ADD = 3 -- Add registers: R[A] = R[B] + R[C]
local OP_SUB = 4 -- Subtract registers: R[A] = R[B] - R[C]
local OP_MUL = 5 -- Multiply registers: R[A] = R[B] * R[C]
local OP_DIV = 6 -- Divide registers: R[A] = R[B] / R[C]
local OP_JMP = 7 -- Unconditional jump: IP = IP + A (relative)
local OP_JEQ = 8 -- Jump if equal: if R[B] == R[C] then IP = IP + A (relative)
local OP_JLT = 9 -- Jump if less than: if R[B] < R[C] then IP = IP + A (relative)
local OP_PRINT = 10 -- Print register value: print(R[A])
-- Map opcode names to numbers for the assembler
local OPCODES = {
HALT = OP_HALT,
LOADK = OP_LOADK,
MOVE = OP_MOVE,
ADD = OP_ADD,
SUB = OP_SUB,
MUL = OP_MUL,
DIV = OP_DIV,
JMP = OP_JMP,
JEQ = OP_JEQ,
JLT = OP_JLT,
PRINT = OP_PRINT,
}
-- ===================================================================
-- 2. Define the VM Execution Engine
-- ===================================================================
-- The main execution function
-- bytecode: A list of instructions. Each instruction is a list: [opcode, A, B, C]
-- constants: A list of constant values, indexed starting from 1
function execute_vm(bytecode, constants)
-- VM State
local registers = {} -- Use a simple table for registers (R[1], R[2], ...)
local ip = 1 -- Instruction Pointer (1-based index into bytecode)
-- Initialize registers (e.g., 16 registers)
for i = 1, 16 do
registers[i] = nil -- Or 0, depending on VM design
end
-- Execution loop
while ip <= #bytecode do
local instruction = bytecode[ip]
if not instruction then
error("VM Error: Attempted to execute beyond bytecode boundary at IP " .. ip)
end
local opcode = instruction[1]
local A = instruction[2]
local B = instruction[3]
local C = instruction[4] -- C might be nil for opcodes that don't use it
-- Default: move to the next instruction
ip = ip + 1
-- Decode and Execute
if opcode == OP_HALT then
print("VM Halted.")
break -- Exit the loop
elseif opcode == OP_LOADK then
-- A is register index, B is constant index
registers[A] = constants[B]
elseif opcode == OP_MOVE then
-- A is dest register, B is src register
registers[A] = registers[B]
elseif opcode == OP_ADD then
-- A is dest register, B and C are source registers
registers[A] = registers[B] + registers[C]
elseif opcode == OP_SUB then
-- A is dest register, B and C are source registers
registers[A] = registers[B] - registers[C]
elseif opcode == OP_MUL then
-- A is dest register, B and C are source registers
registers[A] = registers[B] * registers[C]
elseif opcode == OP_DIV then
-- A is dest register, B and C are source registers
-- Basic error check
if registers[C] == 0 then
error("VM Error: Division by zero at IP " .. (ip-1))
end
registers[A] = registers[B] / registers[C]
elseif opcode == OP_JMP then
-- A is the relative jump offset
-- IP was already incremented by 1, so jump is relative to the *next* instruction slot
ip = ip + A - 1 -- Adjust because ip was already incremented
elseif opcode == OP_JEQ then
-- A is relative jump offset, B and C are registers to compare
if registers[B] == registers[C] then
ip = ip + A - 1 -- Adjust because ip was already incremented
end
elseif opcode == OP_JLT then
-- A is relative jump offset, B and C are registers to compare
if registers[B] < registers[C] then
ip = ip + A - 1 -- Adjust because ip was already incremented
end
elseif opcode == OP_PRINT then
-- A is register index to print
print("VM Output:", registers[A])
else
error("VM Error: Unknown opcode " .. tostring(opcode) .. " at IP " .. (ip-1))
end
-- Basic safety break for infinite loops (remove in real usage)
if ip > #bytecode * 10 then
error("VM Error: Possible infinite loop detected.")
end
end
end
-- ===================================================================
-- 3. Simple Assembler (for easier bytecode definition)
-- ===================================================================
-- Takes a list of assembly-like instructions and constants,
-- returns the compiled bytecode and constant pool.
--
-- Assembly format: { "OP_NAME", arg1, arg2, arg3 } or { "LABEL_NAME:" }
-- Arguments can be:
-- - Numbers: Treated as register indices (R[1], R[2], etc.) or immediate values (for JMP/JEQ/JLT offset)
-- - Strings enclosed in quotes ('...' or "..."): Treated as constant values. Will be added to constant pool.
-- - Strings *without* quotes: Treated as jump labels. Will be resolved to relative offsets.
function assemble(asm_instructions)
local bytecode = {}
local constants = {}
local constants_map = {} -- Maps constant value -> index
local labels = {} -- Maps label name -> instruction index (1-based)
local temp_bytecode = {} -- Stores instructions before resolving labels/constants
-- Pass 1: Collect labels and raw instructions
local current_index = 1
for _, instruction in ipairs(asm_instructions) do
if type(instruction) == 'table' and type(instruction[1]) == 'string' then
local first_arg = instruction[1]
if first_arg:sub(-1) == ':' then
-- It's a label
local label_name = first_arg:sub(1, -2)
if labels[label_name] then
error("Assembler Error: Duplicate label '" .. label_name .. "'")
end
labels[label_name] = current_index
else
-- It's an instruction
temp_bytecode[current_index] = instruction
current_index = current_index + 1
end
else
error("Assembler Error: Invalid instruction format: " .. tostring(instruction))
end
end
-- Pass 2: Resolve operands (constants, labels) and generate numeric bytecode
for i = 1, #temp_bytecode do
local instruction = temp_bytecode[i]
local opcode_name = instruction[1]
local opcode = OPCODES[opcode_name]
if opcode == nil then
error("Assembler Error: Unknown opcode '" .. opcode_name .. "' at instruction " .. i)
end
local A, B, C
-- Helper function to get constant index
local function get_constant_index(value)
-- Lua strings are good keys. Numbers need care (1 vs 1.0).
local key = (type(value) == 'number' or type(value) == 'string' or type(value) == 'boolean' or value == nil)
and value or tostring(value) -- Use tostring for tables/userdata etc., though basic VM likely only uses number/string/bool
if constants_map[key] then
return constants_map[key]
else
local index = #constants + 1
constants[index] = value
constants_map[key] = index
return index
end
end
-- Helper function to resolve argument (register, constant, label)
local function resolve_arg(arg)
if type(arg) == 'number' then
-- Assume register index
return arg
elseif type(arg) == 'string' then
if arg:sub(1,1) == "'" or arg:sub(1,1) == '"' then
-- It's a constant string literal
local str_value = load("return " .. arg)() -- Safely evaluate string literal
return get_constant_index(str_value)
else
-- It's a label reference (for jumps)
local target_index = labels[arg]
if not target_index then
error("Assembler Error: Unknown label '" .. arg .. "' referenced at instruction " .. i)
end
-- Calculate relative offset: target_index - (current_instruction_index + 1)
-- IP is the index *before* the fetch. After fetch, IP increments. Jump is relative to *that* new IP.
-- So if we are at index i, IP becomes i+1. Target is target_index. Offset = target_index - (i + 1).
return target_index - (i + 1)
end
-- Add other types if your VM supports them (booleans, nil, etc.)
-- elseif type(arg) == 'boolean' then return get_constant_index(arg) end
-- elseif arg == nil then return get_constant_index(arg) end
else
error("Assembler Error: Invalid argument type for: " .. tostring(arg) .. " at instruction " .. i)
end
end
-- Decode args based on expected opcode signature (simple version)
-- [opcode, A, B, C] format where usage varies by opcode
A = resolve_arg(instruction[2]) -- A is always processed
if instruction[3] then B = resolve_arg(instruction[3]) end
if instruction[4] then C = resolve_arg(instruction[4]) end
-- Special handling for LOADK: B is constant index, not register
if opcode == OP_LOADK then
-- instruction[3] *must* be the constant value itself
if instruction[3] == nil then
error("Assembler Error: LOADK expects a constant value, got nil at instruction " .. i)
end
B = get_constant_index(instruction[3])
-- instruction[4] (C) is unused for LOADK
C = nil -- Or 0, depends on VM encoding
end
-- Special handling for PRINT: only A is used
if opcode == OP_PRINT then
-- instruction[3] (B) and instruction[4] (C) are unused
B = nil
C = nil
end
-- Add the numeric instruction to the bytecode
bytecode[i] = { opcode, A, B, C }
end
return bytecode, constants
end
-- ===================================================================
-- 4. Example Usage
-- ===================================================================
print("--- Example 1: Simple Arithmetic (Calculate (10 + 20) * 3) ---")
local asm_code_1 = {
{"LOADK", 1, 10}, -- R1 = 10
{"LOADK", 2, 20}, -- R2 = 20
{"ADD", 3, 1, 2}, -- R3 = R1 + R2 (R3 = 30)
{"LOADK", 4, 3}, -- R4 = 3
{"MUL", 3, 3, 4}, -- R3 = R3 * R4 (R3 = 90)
{"PRINT", 3}, -- Print R3
{"HALT"} -- Stop
}
local bytecode_1, constants_1 = assemble(asm_code_1)
print("Bytecode:")
for i, inst in ipairs(bytecode_1) do
print(string.format("%3d: %s", i, table.concat(inst, ", ")))
end
print("Constants:", table.concat(constants_1, ", "))
print("\nExecuting VM:")
execute_vm(bytecode_1, constants_1)
print("\n--- Example 2: Simple Loop (Calculate sum of 1 to 5) ---")
local asm_code_2 = {
{"LOADK", 1, 0}, -- R1 = sum = 0
{"LOADK", 2, 1}, -- R2 = counter = 1
{"LOADK", 3, 5}, -- R3 = limit = 5
{"LOOP_START:"}, -- Label for the start of the loop
{"JLT", "LOOP_END", 3, 2}, -- If R3 < R2 (limit < counter), jump to LOOP_END. This means if counter > limit, exit.
{"ADD", 1, 1, 2}, -- R1 = R1 + R2 (sum = sum + counter)
{"LOADK", 4, 1}, -- R4 = 1 (Need the constant 1 again)
{"ADD", 2, 2, 4}, -- R2 = R2 + R4 (counter = counter + 1)
{"JMP", "LOOP_START"}, -- Jump back to the start of the loop
{"LOOP_END:"}, -- Label for the end of the loop
{"PRINT", 1}, -- Print R1 (the final sum)
{"HALT"} -- Stop
}
local bytecode_2, constants_2 = assemble(asm_code_2)
print("Bytecode:")
for i, inst in ipairs(bytecode_2) do
print(string.format("%3d: %s", i, table.concat(inst, ", ")))
end
print("Constants:", table.concat(constants_2, ", "))
print("\nExecuting VM:")
execute_vm(bytecode_2, constants_2)
Explanation:
- Instruction Set: We define numerical constants for each operation (ADD, LOADK, JMP, etc.). A mapping
OPCODES helps the assembler.
- VM Execution (
execute_vm):
- It initializes
registers (a simple Lua table) and ip (the instruction pointer, starting at 1).
- The
while loop fetches instructions one by one based on ip.
ip is incremented before executing the instruction. This is a common VM pattern. For jump instructions, the jump offset A is added to this new ip value, and then 1 is subtracted to account for the initial increment, effectively making the jump relative to the instruction after the current one in the bytecode array.
- An
if/elseif structure decodes the opcode and performs the corresponding action using the registers and constants tables.
- Arithmetic ops (
ADD, etc.) read from registers B and C and write to register A.
LOADK loads a value from the constants pool (indexed by B) into register A.
JMP unconditionally changes ip.
JEQ and JLT conditionally change ip based on a comparison between registers B and C.
PRINT is a simple way to show output.
HALT breaks the execution loop.
- Assembler (
assemble):
- This function takes a more human-readable list of instructions (using opcode names and labels).
- Pass 1: It scans through the list, identifying labels (lines ending with
:) and storing their corresponding instruction index (1-based). It also builds a temporary list of the actual instructions, ignoring labels.
- Pass 2: It iterates through the temporary instructions.
- For each instruction name, it looks up the numerical opcode.
- For each argument:
- Numbers are treated as register indices.
- Strings in quotes (
'...' or "...") are treated as literal constants. They are added to the pool, and their index is used in the bytecode.
How this relates to Obfuscation:
- Non-Standard Execution: The original Lua code is gone. It's replaced by bytecode that only this specific VM knows how to execute. An attacker must reverse-engineer the VM's instruction set and execution logic first.
- Opaque Control Flow: The original structure (if statements, loops, function calls) is flattened into a linear sequence of VM instructions with explicit jumps (
JMP, JEQ, JLT). Understanding the program flow requires tracing these jumps manually or building a control flow graph from the bytecode, which is harder than reading structured Lua code.
- Data Obscurity: Values are stored in registers and a constant pool specific to the VM. Understanding what a register or constant represents requires analyzing how it's used across multiple VM instructions.
- Customization: You can design a VM with arbitrary, complex, or confusing instructions. You could add instructions that perform multiple operations, use unusual operand encoding, or rely on global VM state in non-obvious ways.
- Layering: This VM execution could itself be wrapped inside other obfuscation layers, making it even harder to find and analyze the VM execution code.
Again, this is a basic foundation. Advanced obfuscation VMs often feature self-modifying code (VM instructions change other VM instructions), polymorphism (the VM interpreter code changes), virtualization of the original program's environment, and complex anti-analysis tricks.