LuaL_openlibs() and sandboxing scripts
Solution 1
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
Solution 2
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);
}
}
Solution 3
The simplest solution of them all: just do io=nil;os=nil
after loading the libraries.
Related videos on Youtube
skyeagle
Updated on June 04, 2022Comments
-
skyeagle almost 2 years
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?
-
skyeagle about 13 yearsthanks for the answer (I'm spoilt for choice). Would have voted +1 for this answer (unfortunately, I can't vote!). I had to choose Tung's answer because he answered first with similar info. But I appreciate both answers
-
Aktau over 10 yearsI should note that this is for lua 5.1, and while it might work with lua 5.2, it's not the recommended way anymore. The best thing is to look in the linit.c file of the lua distribution and see how they do it
-
aganm over 3 yearsThat's not enough, the user can require them back
io=require('io')