LuaL_openlibs() and sandboxing 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

Tags:

C++

C

Lua