From 8fa48349b3a6167449773f609e171d010efc4767 Mon Sep 17 00:00:00 2001
From: Jo Johnson <pyrojoe314@gmail.com>
Date: Mon, 5 Feb 2024 12:03:59 -0800
Subject: [PATCH] Add config to allow sandbox bypass

---
 src/detect-lua.c | 16 ++++++++++++++--
 src/detect-lua.h |  1 +
 2 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/src/detect-lua.c b/src/detect-lua.c
index 3f1ee3cf06b6..9bd4d22f9204 100644
--- a/src/detect-lua.c
+++ b/src/detect-lua.c
@@ -614,7 +614,11 @@ static void *DetectLuaThreadInit(void *data)
         goto error;
     }
 
-    luaL_openlibs(t->luastate);
+    if(lua->allow_restricted_functions) {
+        luaL_openlibs(t->luastate); 
+    } else {
+        sb_loadrestricted(t->luastate);
+    }
 
     LuaRegisterExtensions(t->luastate);
 
@@ -713,7 +717,11 @@ static int DetectLuaSetupPrime(DetectEngineCtx *de_ctx, DetectLuaData *ld, const
     lua_State *luastate = sb_newstate(ld->alloc_limit, ld->instruction_limit);
     if (luastate == NULL)
         return -1;
-    luaL_openlibs(luastate); // TODO: get sandbox config and load appropriate libs
+    if(ld->allow_restricted_functions) {
+        luaL_openlibs(luastate); 
+    } else {
+        sb_loadrestricted(luastate);
+    }
 
     /* hackish, needed to allow unittests to pass buffers as scripts instead of files */
 #ifdef UNITTESTS
@@ -1035,6 +1043,10 @@ static int DetectLuaSetup (DetectEngineCtx *de_ctx, Signature *s, const char *st
     lua->alloc_limit = lua_alloc_limit;
     lua->instruction_limit = lua_instruction_limit;
 
+    int allow_restricted_functions = 0;
+    (void)ConfGetBool("security.lua.allow-restricted-functions", &allow_restricted_functions);
+    lua->allow_restricted_functions = allow_restricted_functions;
+
     if (DetectLuaSetupPrime(de_ctx, lua, s) == -1) {
         goto error;
     }
diff --git a/src/detect-lua.h b/src/detect-lua.h
index fdb0405044bd..5fbd6ada11fe 100644
--- a/src/detect-lua.h
+++ b/src/detect-lua.h
@@ -57,6 +57,7 @@ typedef struct DetectLuaData {
     uint32_t gid;
     uint64_t alloc_limit;
     uint64_t instruction_limit;
+    int      allow_restricted_functions;
 } DetectLuaData;
 
 #endif /* HAVE_LUA */