36 #define SANDBOX_CTX "SANDBOX_CTX"
38 static void HookFunc(
lua_State *L, lua_Debug *ar);
50 static void *LuaAlloc(
void *ud,
void *ptr,
size_t osize,
size_t nsize)
63 ctx->alloc_bytes -= osize;
65 }
else if (ptr == NULL) {
67 if (
ctx->alloc_limit != 0 &&
ctx->alloc_bytes + nsize >
ctx->alloc_limit) {
70 ctx->memory_limit_error =
true;
76 ctx->alloc_bytes += nsize;
81 ssize_t diff = nsize - osize;
83 if (
ctx->alloc_limit != 0 &&
ctx->alloc_bytes + diff >
ctx->alloc_limit) {
86 ctx->memory_limit_error =
true;
94 ctx->alloc_bytes += diff;
107 static int LuaBlockedFunction(
lua_State *L)
112 if (lua_getstack(L, 0, &ar) && lua_getinfo(L,
"n", &ar) && ar.name) {
113 luaL_error(L,
"Blocked Lua function called: %s", ar.name);
115 luaL_error(L,
"Blocked Lua function: name not available");
127 static bool IsAllowed(
const char *module,
const char *fname)
129 static const char *base_allowed[] = {
149 static const char *table_allowed[] = {
161 static const char *string_allowed[] = {
183 static const char *math_allowed[] = {
219 static const char *utf8_allowed[] = {
228 const char **allowed = NULL;
230 if (strcmp(module, LUA_GNAME) == 0) {
231 allowed = base_allowed;
232 }
else if (strcmp(module, LUA_TABLIBNAME) == 0) {
233 allowed = table_allowed;
234 }
else if (strcmp(module, LUA_STRLIBNAME) == 0) {
235 allowed = string_allowed;
236 }
else if (strcmp(module, LUA_MATHLIBNAME) == 0) {
237 allowed = math_allowed;
238 }
else if (strcmp(module, LUA_UTF8LIBNAME) == 0) {
239 allowed = utf8_allowed;
246 for (
int i = 0; allowed[i] != NULL; i++) {
247 if (strcmp(allowed[i], fname) == 0) {
259 static const luaL_Reg AllowedLibs[] = {
261 { LUA_GNAME, luaopen_base },
262 { LUA_TABLIBNAME, luaopen_table },
263 { LUA_STRLIBNAME, luaopen_string },
264 { LUA_MATHLIBNAME, luaopen_math },
265 { LUA_UTF8LIBNAME, luaopen_utf8 },
272 const char *module_name = luaL_checkstring(L, 1);
278 return luaL_error(L,
"Module not found: %s", module_name);
291 for (lib = AllowedLibs; lib->func; lib++) {
292 luaL_requiref(L, lib->name, lib->func, 1);
297 lua_getglobal(L, lib->name);
299 while (lua_next(L, -2)) {
300 if (lua_type(L, -1) == LUA_TFUNCTION) {
301 const char *
name = lua_tostring(L, -2);
302 if (!IsAllowed(lib->name,
name)) {
304 lua_pushstring(L,
name);
305 lua_pushcfunction(L, LuaBlockedFunction);
317 lua_pushcfunction(L, SCLuaSbRequire);
318 lua_setglobal(L,
"require");
339 sb->
L = lua_newstate(LuaAlloc, sb);
346 lua_pushlightuserdata(sb->
L, sb);
347 lua_settable(sb->
L, LUA_REGISTRYINDEX);
362 lua_gettable(L, LUA_REGISTRYINDEX);
379 static void HookFunc(
lua_State *L, lua_Debug *ar)
388 luaL_error(L,
"instruction limit exceeded");
394 uint64_t cfg_limit = 0;