Lua Sandboxing
A sandbox is a table that holds only the safe functions a chunk may use. Untrusted code runs with that table as its environment, so it cannot reach anything outside it.
Allowed functions still work
Math is in the table, so the chunk can use it. The floor of 3.7 is 3.
local env = {print = print, math = math}
local f = load('print(math.floor(3.7))', 'chunk', 't', env)
f()Blocked names read as nil
Neither name is in the table, so both read as nil. The chunk never calls them.
local env = {print = print}
local f = load('print(os)\nprint(io)', 'chunk', 't', env)
f()String work stays allowed
The string table is in the sandbox, so its functions work. Uppercase safe is SAFE.
local env = {print = print, string = string}
local f = load('print(string.upper("safe"))', 'chunk', 't', env)
f()Example
local env = {print = print, string = string}
local f = load('print(string.len("hello"))\nprint(os)\nprint(io)', 'chunk', 't', env)
f()Key points
- Sandbox: a table with only the functions a chunk is allowed to call.
- Safe function: a function whose effect stays inside the chunk's own values.
- Untrusted code: code from a source the program does not fully control.
- Blocked name: a name absent from the sandbox table reads as nil.
- Calling nil: a chunk cannot call a blocked name, because nil is not a function.
In this example, the sandbox holds print and string only. The chunk first prints the length of hello, which is 5, then reads os and io, which are absent and print as nil.
Note
a sandbox controls names only, and arithmetic on plain numbers still works inside it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A sandbox holds print and math only. What does a chunk reading os give?