Okay, let's create a very basic custom virtual machine (VM) in Lua. The primary purpose here, as you mentioned, is obfuscation. This means we'll translate some simple Lua logic into a custom "bytecode" format that only our specific VM can understand.
Key Concepts for Obfuscation:
- Custom Bytecode: The core Lua code is transformed into a series of instructions specific to our VM, not standard Lua bytecode. Tools like
luac -l won't be able to disassemble it.
- Custom VM: A Lua function (or set of functions) that interprets this custom bytecode.
- Separation: The original, readable Lua logic is gone. Only the bytecode and the VM remain.
Limitations:
- Performance: Interpreting custom bytecode within Lua will be significantly slower than running native Lua code or standard Lua bytecode.
- Complexity: Creating a robust VM that supports a large subset of Lua is very complex. This example will be highly simplified.
- Reverse Engineering: A determined attacker can still reverse-engineer the VM and the bytecode format. This adds a layer of difficulty, not unbreakable protection.
Example: A Simple Stack-Based VM
Let's create a VM that can perform basic arithmetic and print results.
1. Define the Instruction Set (Opcodes)
We need numeric codes for our operations.
local OP_HALT = 0 -- Stop execution
local OP_LOAD_CONST = 1 -- Push a constant value onto the stack (arg: constant index)
local OP_ADD = 2 -- Pop two values, add them, push result
local OP_SUB = 3 -- Pop two values, subtract (top - second), push result
local OP_MUL = 4 -- Pop two values, multiply, push result
local OP_DIV = 5 -- Pop two values, divide (top / second), push result
local OP_PRINT = 6 -- Pop a value and print it
local OP_LOAD_VAR = 7 -- Push variable value onto stack (arg: variable name)
local OP_STORE_VAR = 8 -- Pop value from stack and store in variable (arg: variable name)
local OP_JUMP_IF_FALSE = 9 -- Pop value, if false/nil, jump (arg: target instruction index)
local OP_JUMP = 10 -- Unconditional jump (arg: target instruction index)
2. The Virtual Machine Implementation
local CustomVM = {}
CustomVM.__index = CustomVM
function CustomVM:new(bytecode, constants)
local vm = setmetatable({}, CustomVM)
vm.bytecode = bytecode -- Table of instructions {opcode, arg1, arg2, ...}
vm.constants = constants -- Table of constant values (numbers, strings)
vm.stack = {} -- The VM's data stack
vm.ip = 1 -- Instruction Pointer (index into bytecode)
vm.globals = {} -- Simple global variable store for this VM
vm.running = true
return vm
end
-- Stack operations (basic error checking omitted for brevity)
function CustomVM:push(value)
table.insert(self.stack, value)
end
function CustomVM:pop()
return table.remove(self.stack)
end
-- The main execution loop
function CustomVM:run()
while self.running and self.ip <= #self.bytecode do
local instruction = self.bytecode[self.ip]
local opcode = instruction[1]
-- print("IP:", self.ip, "Opcode:", opcode, "Stack:", table.concat(self.stack, ", ")) -- Debug
self.ip = self.ip + 1 -- Increment IP *before* executing jump potentially
if opcode == OP_HALT then
self.running = false
print("VM Halted.")
elseif opcode == OP_LOAD_CONST then
local constIndex = instruction[2]
self:push(self.constants[constIndex])
elseif opcode == OP_ADD then
local b = self:pop()
local a = self:pop()
self:push(a + b)
elseif opcode == OP_SUB then
local b = self:pop()
local a = self:pop()
self:push(a - b) -- Note: Order matters (a - b)
elseif opcode == OP_MUL then
local b = self:pop()
local a = self:pop()
self:push(a * b)
elseif opcode == OP_DIV then
local b = self:pop()
local a = self:pop()
self:push(a / b) -- Note: Order matters (a / b)
elseif opcode == OP_PRINT then
print("VM Output:", self:pop())
elseif opcode == OP_LOAD_VAR then
local varName = instruction[2]
self:push(self.globals[varName]) -- Push nil if not found
elseif opcode == OP_STORE_VAR then
local varName = instruction[2]
self.globals[varName] = self:pop()
elseif opcode == OP_JUMP_IF_FALSE then
local value = self:pop()
if not value then -- Lua's definition of falsey (false or nil)
self.ip = instruction[2] -- Set IP to the target jump address
end
elseif opcode == OP_JUMP then
self.ip = instruction[2] -- Set IP to the target jump address
else
error("Unknown opcode: " .. tostring(opcode))
self.running = false
end
end
if self.running then
print("VM finished execution (reached end of bytecode).")
end
end
3. Example "Compilation" (Manual)
Let's manually "compile" this simple Lua logic:
-- Original Lua logic (for reference)
local x = 10
local y = 25
local z = (x + y) * 2
if z > 50 then
print(z - 10)
else
print(z)
end
print("Done")
Into our custom bytecode:
-- 1. Define Constants
local constants = {
10, -- index 1
25, -- index 2
2, -- index 3
50, -- index 4 (for comparison, though we need GT opcode)
-- Let's add GT opcode and modify:
-- OP_GT = 11 -- Pop b, Pop a, Push (a > b)
"Done" -- index 5 (string constant)
}
-- Add OP_GT = 11 to the opcode list and VM implementation if needed.
-- For simplicity here, let's restructure slightly to avoid adding new opcodes now.
-- Let's calculate z and print it directly, then add a simpler condition.
-- Revised Target Logic:
-- local x = 10
-- local y = 25
-- local z = (x + y) * 2
-- print(z) -- Will print 70
-- if x < y then
-- print("x is smaller")
-- end
-- print("Done")
-- Revised Constants:
local constants_example = {
10, -- index 1
25, -- index 2
2, -- index 3
"x is smaller", -- index 4
"Done" -- index 5
}
-- Add OP_LT = 11 -- Pop b, Pop a, Push (a < b)
-- (Need to add this to the VM code above as well)
local OP_LT = 11
-- 2. Create Bytecode (array of instructions {opcode, arg1, ...})
local bytecode_example = {
-- local x = 10
{OP_LOAD_CONST, 1}, -- IP 1: Push 10
{OP_STORE_VAR, "x"}, -- IP 2: Store stack top into variable 'x'
-- local y = 25
{OP_LOAD_CONST, 2}, -- IP 3: Push 25
{OP_STORE_VAR, "y"}, -- IP 4: Store stack top into variable 'y'
-- local z = (x + y) * 2
{OP_LOAD_VAR, "x"}, -- IP 5: Push value of 'x' (10)
{OP_LOAD_VAR, "y"}, -- IP 6: Push value of 'y' (25)
{OP_ADD}, -- IP 7: Pop 25, Pop 10, Push (10 + 25 = 35)
{OP_LOAD_CONST, 3}, -- IP 8: Push 2
{OP_MUL}, -- IP 9: Pop 2, Pop 35, Push (35 * 2 = 70)
{OP_STORE_VAR, "z"}, -- IP 10: Store stack top into variable 'z'
-- print(z)
{OP_LOAD_VAR, "z"}, -- IP 11: Push value of 'z' (70)
{OP_PRINT}, -- IP 12: Pop 70 and print it
-- if x < y then print("x is smaller") end
{OP_LOAD_VAR, "x"}, -- IP 13: Push value of 'x' (10)
{OP_LOAD_VAR, "y"}, -- IP 14: Push value of 'y' (25)
-- Assuming OP_LT = 11 is added to the VM:
{OP_LT}, -- IP 15: Pop 25, Pop 10, Push (10 < 25 = true)
{OP_JUMP_IF_FALSE, 19}, -- IP 16: Pop result (true). If false, jump to IP 19. Condition is true, so continue.
{OP_LOAD_CONST, 4}, -- IP 17: Push "x is smaller"
{OP_PRINT}, -- IP 18: Pop and print "x is smaller"
-- IP 19: Target of the jump (instruction after the 'then' block)
-- print("Done")
{OP_LOAD_CONST, 5}, -- IP 19: Push "Done"
{OP_PRINT}, -- IP 20: Pop and print "Done"
-- Halt execution
{OP_HALT} -- IP 21: Stop the VM
}
-- **Remember to add OP_LT to the VM implementation!**
-- Inside CustomVM:run()'s if/elseif chain:
-- elseif opcode == OP_LT then
-- local b = self:pop()
-- local a = self:pop()
-- self:push(a < b)
4. Running the VM
-- Assume CustomVM class definition and OP_LT addition are present above...
-- Create and run the VM instance
local myVM = CustomVM:new(bytecode_example, constants_example)
myVM:run()
-- Expected Output:
-- VM Output: 70
-- VM Output: x is smaller
-- VM Output: Done
-- VM Halted.
How this provides Obfuscation:
- The original Lua code (
local x = 10...) doesn't exist in the final script.
- Anyone looking at the
bytecode_example table sees only numbers and a few strings. They don't immediately know that {1, 1} means "load the first constant".
- They need to analyze the
CustomVM:run function to understand the meaning of each opcode and how the stack/variables work.
- This significantly raises the bar compared to plain Lua source code or even standard Lua bytecode (which has well-known tools for analysis).
Further Obfuscation Techniques (Optional):
- Randomize Opcodes: Don't use sequential numbers (0, 1, 2...). Use random-looking numbers or even strings for opcodes, potentially generated uniquely for each script.
- Encrypt Constants: Encrypt the
constants table and decrypt values within the VM just before use.
- VM Polymorphism: Slightly change the VM's instruction set or behavior for different parts of the code or different scripts.
- Instruction Encoding: Don't use simple Lua tables for instructions. Encode them into strings or large numbers where bits represent opcode and arguments.
- Anti-Debugging: Add checks within the VM loop to detect common debugging techniques (e.g., checking function environments, timing checks).
- Code Generation: Create a "compiler" tool that automatically translates Lua source code (or a subset of it) into your custom bytecode format. Manually creating bytecode is tedious and error-prone.
This example provides a foundational understanding of how a custom VM can be used for obfuscation in Lua. Remember the trade-offs regarding performance and the limits of security through obscurity.