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) {
69 ctx->alloc_bytes += nsize;
74 ssize_t diff = nsize - osize;
76 if (
ctx->alloc_bytes + diff >
ctx->alloc_limit) {
79 ctx->memory_limit_error =
true;
85 BUG_ON((ssize_t)
ctx->alloc_bytes + diff < 0);
87 ctx->alloc_bytes += diff;
100 static int LuaBlockedFunction(
lua_State *L)
105 lua_getstack(L, 0, &ar);
106 lua_getinfo(L,
"n", &ar);
108 luaL_error(L,
"Blocked Lua function called: %s", ar.name);
110 luaL_error(L,
"Blocked Lua function: name not available");
120 static bool IsAllowed(
const char *module,
const char *fname)
122 static const char *base_allowed[] = {
142 static const char *table_allowed[] = {
154 static const char *string_allowed[] = {
176 static const char *math_allowed[] = {
212 static const char *utf8_allowed[] = {
221 const char **allowed = NULL;
223 if (strcmp(module, LUA_GNAME) == 0) {
224 allowed = base_allowed;
225 }
else if (strcmp(module, LUA_TABLIBNAME) == 0) {
226 allowed = table_allowed;
227 }
else if (strcmp(module, LUA_STRLIBNAME) == 0) {
228 allowed = string_allowed;
229 }
else if (strcmp(module, LUA_MATHLIBNAME) == 0) {
230 allowed = math_allowed;
231 }
else if (strcmp(module, LUA_UTF8LIBNAME) == 0) {
232 allowed = utf8_allowed;
239 for (
int i = 0; allowed[i] != NULL; i++) {
240 if (strcmp(allowed[i], fname) == 0) {
252 static const luaL_Reg AllowedLibs[] = {
254 { LUA_GNAME, luaopen_base },
255 { LUA_TABLIBNAME, luaopen_table },
256 { LUA_STRLIBNAME, luaopen_string },
257 { LUA_MATHLIBNAME, luaopen_math },
258 { LUA_UTF8LIBNAME, luaopen_utf8 },
265 const char *module_name = luaL_checkstring(L, 1);
267 if (strcmp(module_name,
"suricata.dataset") == 0) {
272 return luaL_error(L,
"Module not found: %s", module_name);
285 for (lib = AllowedLibs; lib->func; lib++) {
286 luaL_requiref(L, lib->name, lib->func, 1);
291 lua_getglobal(L, lib->name);
293 while (lua_next(L, -2)) {
294 if (lua_type(L, -1) == LUA_TFUNCTION) {
295 const char *
name = lua_tostring(L, -2);
296 if (!IsAllowed(lib->name,
name)) {
298 lua_pushstring(L,
name);
299 lua_pushcfunction(L, LuaBlockedFunction);
311 lua_pushcfunction(L, SCLuaSbRequire);
312 lua_setglobal(L,
"require");
333 sb->
L = lua_newstate(LuaAlloc, sb);
340 lua_pushlightuserdata(sb->
L, sb);
341 lua_settable(sb->
L, LUA_REGISTRYINDEX);
356 lua_gettable(L, LUA_REGISTRYINDEX);
373 static void HookFunc(
lua_State *L, lua_Debug *ar)
382 luaL_error(L,
"instruction limit exceeded");