Lua Host Sandboxes
A host sandbox is a restricted environment for guest code.
A missing global reads as nil
The sandbox holds only print. The guest reads os and gets nil.
local sandbox = { print = print }
local guest = load("print(os)", "guest", "t", sandbox)
guest()Safe helpers stay available
The sandbox also holds the string library. The guest uses it and still cannot see io.
local sandbox = { print = print, string = string }
local guest = load([[
print(string.upper("hi"))
print(io)
]], "guest", "t", sandbox)
guest()A dangerous call fails
The guest tries a system call. The call fails because os is missing.
local sandbox = { print = print }
local guest = load('os.execute("echo hi")', "guest", "t", sandbox)
local ok = pcall(guest)
print(ok)Example
local sandbox = { print = print, string = string }
local guest = load([[
print(string.upper("safe"))
print(os)
print(io)
]], "guest", "t", sandbox)
guest()Key points
- Model: the host side here is modelled in Lua and no C code runs in this lesson.
- Sandbox: a sandbox is a restricted environment for guest code.
- Safe names: the sandbox holds only the names the guest may use.
- Missing names: a name outside the sandbox reads as nil inside the guest.
- Dangerous calls: a call to a missing name fails instead of running.
- Host control: the host chooses the sandbox contents before it loads the guest.
In this example, the sandbox holds print and the string library. The guest uppercases a word with the safe helper. It then reads os and io, and both print as nil because neither is in the sandbox.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Guest code in a sandbox reads io. What value does it get?