Fix setting sandbox on Lua instance without strlib (#1156)

Currently calling `luaL_sandbox` on Lua instance without loaded strlib
causes crash (assertion).
It happens because inside `luaL_sandbox` there is no check that
metatable for strings is present.
This commit is contained in:
Alex Orlenko 2024-01-30 15:23:58 +00:00 committed by GitHub
parent c0b17daebd
commit d409f7946d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 3 deletions

View File

@ -43,9 +43,13 @@ void luaL_sandbox(lua_State* L)
// set all builtin metatables to read-only
lua_pushliteral(L, "");
lua_getmetatable(L, -1);
lua_setreadonly(L, -1, true);
lua_pop(L, 2);
if (lua_getmetatable(L, -1))
{
lua_setreadonly(L, -1, true);
lua_pop(L, 2);
}
else
lua_pop(L, 1);
// set globals to readonly and activate safeenv since the env is immutable
lua_setreadonly(L, LUA_GLOBALSINDEX, true);

View File

@ -884,6 +884,17 @@ TEST_CASE("NewUserdataOverflow")
CHECK(strcmp(lua_tostring(L, -1), "memory allocation error: block too big") == 0);
}
TEST_CASE("SandboxWithoutLibs")
{
StateRef globalState(luaL_newstate(), lua_close);
lua_State* L = globalState.get();
luaopen_base(L); // Load only base library
luaL_sandbox(L);
CHECK(lua_getreadonly(L, LUA_GLOBALSINDEX));
}
TEST_CASE("ApiTables")
{
StateRef globalState(luaL_newstate(), lua_close);