Building a Restricted Sandbox
Create a safe _ENV whitelist and execute untrusted code with load().
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 },
}
endAll lessons in this course
- The _ENV Model in Lua 5.2+
- Building a Restricted Sandbox
- Preventing Sandbox Escapes
- Resource Limits and Instrumentation