35 #define SANDBOX_CTX "SANDBOX_CTX"
37 static void HookFunc(
lua_State *L, lua_Debug *ar);
49 static void *LuaAlloc(
void *ud,
void *ptr,
size_t osize,
size_t nsize)
62 ctx->alloc_bytes -= osize;
64 }
else if (ptr == NULL) {
68 ctx->alloc_bytes += nsize;
73 ssize_t diff = nsize - osize;
75 if (
ctx->alloc_bytes + diff >
ctx->alloc_limit) {
78 ctx->memory_limit_error =
true;
84 BUG_ON((ssize_t)
ctx->alloc_bytes + diff < 0);
86 ctx->alloc_bytes += diff;
99 static int LuaBlockedFunction(
lua_State *L)
104 lua_getstack(L, 0, &ar);
105 lua_getinfo(L,
"n", &ar);
107 luaL_error(L,
"Blocked Lua function called: %s", ar.name);
109 luaL_error(L,
"Blocked Lua function: name not available");
119 static bool IsAllowed(
const char *module,
const char *fname)
121 static const char *base_allowed[] = {
141 static const char *table_allowed[] = {
153 static const char *string_allowed[] = {
175 static const char *math_allowed[] = {
211 static const char *utf8_allowed[] = {
220 const char **allowed = NULL;
222 if (strcmp(module, LUA_GNAME) == 0) {
223 allowed = base_allowed;
224 }
else if (strcmp(module, LUA_TABLIBNAME) == 0) {
225 allowed = table_allowed;
226 }
else if (strcmp(module, LUA_STRLIBNAME) == 0) {
227 allowed = string_allowed;
228 }
else if (strcmp(module, LUA_MATHLIBNAME) == 0) {
229 allowed = math_allowed;
230 }
else if (strcmp(module, LUA_UTF8LIBNAME) == 0) {
231 allowed = utf8_allowed;
238 for (
int i = 0; allowed[i] != NULL; i++) {
239 if (strcmp(allowed[i], fname) == 0) {
251 static const luaL_Reg AllowedLibs[] = {
253 { LUA_GNAME, luaopen_base },
254 { LUA_TABLIBNAME, luaopen_table },
255 { LUA_STRLIBNAME, luaopen_string },
256 { LUA_MATHLIBNAME, luaopen_math },
257 { LUA_UTF8LIBNAME, luaopen_utf8 },
272 for (lib = AllowedLibs; lib->func; lib++) {
273 luaL_requiref(L, lib->name, lib->func, 1);
278 lua_getglobal(L, lib->name);
280 while (lua_next(L, -2)) {
281 if (lua_type(L, -1) == LUA_TFUNCTION) {
282 const char *name = lua_tostring(L, -2);
283 if (!IsAllowed(lib->name, name)) {
284 SCLogDebug(
"Blocking Lua function %s.%s", lib->name, name);
285 lua_pushstring(L, name);
286 lua_pushcfunction(L, LuaBlockedFunction);
289 SCLogDebug(
"Allowing Lua function %s.%s", lib->name, name);
316 sb->
L = lua_newstate(LuaAlloc, sb);
323 lua_pushlightuserdata(sb->
L, sb);
324 lua_settable(sb->
L, LUA_REGISTRYINDEX);
339 lua_gettable(L, LUA_REGISTRYINDEX);
356 static void HookFunc(
lua_State *L, lua_Debug *ar)
365 luaL_error(L,
"instruction limit exceeded");