So Lua seems ideal for implementing secure "user scripts" inside my application.
However, most examples of embedding lua seem to include loading all the standard libraries, including "io" and "package".
So I can exclude those libs from my interpreter, but even the base library includes the functions "dofile" and "loadfile" which access the filesystem.
How can I remove/block any unsafe functions like these, without just ending up with an interpreter that doesn't even have basic stuff like the "ipairs" function?
You can set the function environment that you run the untrusted code in via setfenv(). Here's an outline:
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 toipairs
but nothing else (dofile
,loadfile
, etc).See Lua Sandboxes for an example and more information on lua sandboxing.
If you're using Lua 5.1 try this:
The Lua live demo contains a (specialized) sandbox. The source is freely available.
You can use the
lua_setglobal
function provided by the Lua API to set those values in the global namespace tonil
which will effectively prevent any user scripts from being able to access them.Here's a solution for Lua 5.2 (including a sample environment that would also work in 5.1):
Then to use it, you would call your function (
my_func
) like the following:One of the easiest ways to clear out undesirables is to first load a Lua script of your own devising, that does things like:
Alternatively, you can use
setfenv
to create a restricted environment that you can insert specific safe functions into.Totally safe sandboxing is a little harder. If you load code from anywhere, be aware that precompiled code can crash Lua. Even completely restricted code can go into an infinite loop and block indefinitely if you don't have system for shutting it down.