I am embedding Lua (5.1) in a C/C++ application.
I am using the LuaL_openlibs()
function to load the base libs. However, this function loads some other libraries which I want to disable so that they are not available to my Lua scripts.
Specifically, I want to disable the IO and OS modules. Is there a function I can call to programmativally disable (or unload) these modules so that I can create a safe sandbox environment for running Lua scripts?
luaL_openlibs
just iterates through a list of library loaders, declared in the same file. Simply delete/comment out the luaopen_io
and luaopen_os
lines. Done.
If you're adverse to editing the Lua source, then you can define your own function which leaves out those two libraries:
#define LUA_LIB
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
static const luaL_Reg lualibs[] = {
{"", luaopen_base},
{LUA_LOADLIBNAME, luaopen_package},
{LUA_TABLIBNAME, luaopen_table},
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_DBLIBNAME, luaopen_debug},
{NULL, NULL}
};
LUALIB_API void my_openlibs (lua_State *L) {
const luaL_Reg *lib = lualibs;
for (; lib->func; lib++) {
lua_pushcfunction(L, lib->func);
lua_pushstring(L, lib->name);
lua_call(L, 1, 0);
}
}
I don't know how to disable modules, but you can still choose which ones to load instead of loading them all with luaL_openlibs
. Section 7.3 of the Lua 5.1 manual says:
The
luaopen_*
functions (to open libraries) cannot be called directly, like a regular C function. They must be called through Lua, like a Lua function.
That is, instead of directly calling the function as in Lua 5.0:
luaopen_table(L);
... you push it as a C function with its name and use lua_call
or similar in Lua 5.1:
lua_pushcfunction(L, luaopen_table);
lua_pushliteral(L, LUA_TABLIBNAME);
lua_call(L, 1, 0);
The functions you can do this with are listed in lualib.h
:
Function | Name
----------------+-----------------
luaopen_base | ""
luaopen_table | LUA_TABLIBNAME
luaopen_io | LUA_IOLIBNAME
luaopen_os | LUA_OSLIBNAME
luaopen_string | LUA_STRLIBNAME
luaopen_math | LUA_MATHLIBNAME
luaopen_debug | LUA_DBLIBNAME
luaopen_package | LUA_LOADLIBNAME
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With