How can I create a secure Lua sandbox?

You can set the function environment that you run the untrusted code in via setfenv(). Here’s an outline:

local env = {ipairs}
setfenv(user_script, env)
pcall(user_script)

The user_script function can only access what is in its environment. So you can then explicitly add in the functions that you want the untrusted code to have access to (whitelist). In this case the user script only has access to ipairs but nothing else (dofile, loadfile, etc).

See Lua Sandboxes for an example and more information on lua sandboxing.

Leave a Comment