Building a Restricted Sandbox
Create a safe _ENV whitelist and execute untrusted code with load().
Building a Restricted Sandbox is a free Lua Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Goal
A restricted sandbox lets you run untrusted Lua code safely: it can compute, use strings and math, but cannot access the filesystem, OS, or network.
Whitelist Approach
Build the sandbox environment from scratch, including only safe, well-understood functions.
local function makeSandbox()
return {
print = print,
type = type,
tostring = tostring,
tonumber = tonumber,
pairs = pairs,
ipairs = ipairs,
next = next,
select = select,
unpack = table.unpack,
error = error,
pcall = pcall,
xpcall = xpcall,
math = math,
string = { format=string.format, find=string.find,
match=string.match, gmatch=string.gmatch,
gsub=string.gsub, sub=string.sub,
len=string.len, byte=string.byte, char=string.char },
table = { insert=table.insert, remove=table.remove,
concat=table.concat, sort=table.sort,
unpack=table.unpack, move=table.move },
}
endRunning Code in the Sandbox
Load and execute user code with the sandbox as its _ENV.
local function runSandboxed(code, env)
local fn, err = load(code, "user", "t", env)
if not fn then return nil, err end
return pcall(fn)
end
local env = makeSandbox()
local ok, err = runSandboxed("return 1+1", env)
print(ok, err) -- true 2Capturing Output
Replace print with a custom function that appends to a buffer instead of writing to stdout.
local output = {}
env.print = function(...)
local parts = {}
for i = 1, select("#", ...) do
parts[i] = tostring(select(i, ...))
end
output[#output+1] = table.concat(parts, "\t")
endReturning Values
To allow the sandboxed code to return values, call the compiled chunk as a function and capture its return values.
local fn = load("return math.sqrt(144)", "user", "t", env)
if fn then
local ok, result = pcall(fn)
print(ok, result) -- true 12.0
endBlocking Metamethod Exploits
Sandboxed code should not get references to metatables or rawget/rawset to avoid bypassing field restrictions.
Limiting String Length
Override string operations to limit output length and prevent DoS via huge string allocations.
Resource Limits with debug.sethook
Add an instruction counter hook to terminate runaway code.
local function sandboxWithLimit(code, env, maxOps)
local ops = 0
debug.sethook(function()
ops = ops + 1
if ops > maxOps then error("Instruction limit exceeded") end
end, "", 100)
local result = table.pack(runSandboxed(code, env))
debug.sethook()
return table.unpack(result, 1, result.n)
endTesting the Sandbox
Write tests that try known escape vectors: accessing _G, calling load, using debug, and verify they all fail.
Known Escape Vectors
Common escape routes: string.rep("x",2^30) (memory DoS), ({}).__index on standard objects, debug via string metatable, io via package.loaded.
Sandbox Question
Why does a sandbox not include load or dofile?
Recap: Building a Restricted Sandbox
Whitelist only safe functions in a custom env table. Use load(code, name, "t", env). Add instruction counting with debug.sethook. Test escape vectors. Never include load, dofile, debug, or global table access.
Frequently asked questions
Is the “Building a Restricted Sandbox” lesson free?
Yes — the full text of “Building a Restricted Sandbox” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.
What will I learn in “Building a Restricted Sandbox”?
Create a safe _ENV whitelist and execute untrusted code with load(). You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Lua Academy?
No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Building a Restricted Sandbox” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Lua Academy lesson?
Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The _ENV Model in Lua 5.2+
- Building a Restricted Sandbox
- Preventing Sandbox Escapes
- Resource Limits and Instrumentation