make lua script calls sandboxed

This commit is contained in:
falsycat 2022-06-07 00:25:05 +09:00
parent 8945eb8943
commit 1e92ac27f8
3 changed files with 40 additions and 2 deletions

View File

@ -64,7 +64,10 @@ target_sources(nf7
common/lock.hh
common/logger.hh
common/logger_ref.hh
common/luajit.hh
common/luajit_obj.hh
common/luajit_queue.hh
common/luajit_ref.hh
common/memento.hh
common/native_file.hh
common/node.hh

34
common/luajit.hh Normal file
View File

@ -0,0 +1,34 @@
#pragma once
#include <lua.hpp>
namespace nf7::luajit {
void PushImmEnv(lua_State* L) noexcept {
if (luaL_newmetatable(L, "nf7::luajit::PushImmEnv")) {
lua_createtable(L, 0, 0);
lua_pushvalue(L, LUA_GLOBALSINDEX);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, [](auto L) { return luaL_error(L, "global is immutable"); });
lua_setfield(L, -2, "__newindex");
lua_setmetatable(L, -2);
}
}
int SandboxCall(lua_State* L, int narg, int nret) noexcept {
constexpr size_t kSandboxInstructionLimit = 10000000;
static const auto kHook = [](auto L, auto) {
luaL_error(L, "reached instruction limit (<=1e7)");
};
lua_sethook(L, kHook, LUA_MASKCOUNT, kSandboxInstructionLimit);
PushImmEnv(L);
lua_setfenv(L, -narg-2);
return lua_pcall(L, narg, nret, 0);
}
} // namespace nf7

View File

@ -19,9 +19,10 @@
#include "common/generic_context.hh"
#include "common/generic_type_info.hh"
#include "common/lock.hh"
#include "common/logger_ref.hh"
#include "common/luajit.hh"
#include "common/luajit_obj.hh"
#include "common/luajit_queue.hh"
#include "common/logger_ref.hh"
#include "common/ptr_selector.hh"
#include "common/yas_nf7.hh"
@ -248,7 +249,7 @@ class Obj::ExecTask final : public nf7::Context, public std::enable_shared_from_
Error(lua_tostring(L, -1));
return;
}
if (0 != lua_pcall(L, 0, 1, 0)) {
if (0 != nf7::luajit::SandboxCall(L, 0, 1)) {
Error(lua_tostring(L, -1));
return;
}