diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..1b73b0805 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -384,7 +384,8 @@ endif() if (WITH_LUA) set(DEFINITIONS ${DEFINITIONS} "WITH_LUA") - set(SOURCES ${SOURCES} "scripting/lua.cpp") + # the scenery scripts (lua.cpp) and the Lua screens (luaprogram.cpp) share the sandbox of luasandbox.cpp + set(SOURCES ${SOURCES} "scripting/lua.cpp" "scripting/luasandbox.cpp") endif() # the script screens (scripting/scriptscreens.cpp), with the Lua and the WebAssembly runtime when they're built diff --git a/script_screens_doc.md b/script_screens_doc.md index 52ccc9ced..09a4c2638 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -208,3 +208,25 @@ clang --target=wasm32 -O2 -nostdlib -Wl,--no-entry -o ekran.wasm ekran.c Any language that compiles to WebAssembly works the same way (Rust `wasm32-unknown-unknown`, Zig, AssemblyScript), as long as the module imports nothing but the `eu07` functions above. + +## Scenery scripts + +A scenery runs a Lua script with `lua ` in its `.scn`, while the scenery loads. The script registers events +and works with memcells, tracks and vehicles through the table `eu07.events` (`event_create`, `event_dispatch`, +`memcell_update`, `writelog` and the rest, see `scripting/lua.cpp`). It shares the sandbox of the Lua screens: + +- the file is a path relative to the scenery folder (`scenery/`), and stays inside it: no `..`, no drive, no leading + `/`. It is text, of at most 16 MB; precompiled code is not loaded; +- the script gets the base library, `table`, `string`, `math` and `bit`, and of `os` only the clock: `os.time`, + `os.clock`, `os.difftime` and `os.date` (with the C89 conversions only, `%Y`, `%d`, `%H` and so on). It gets no + `io`, the rest of `os`, `ffi`, `debug`, `jit`, `package`, `require`, `dofile`, `load`, `loadfile` or `loadstring`; +- a script that fails stops there, the error goes to the log with the file name and line, and the scenery goes on + loading. An event handler that fails is logged with the name of the event, and the simulation goes on. + +A script written for the earlier full libraries stops at the first call to one of them (`attempt to index global +'io' (a nil value)` in the log). For a scenery you trust, `eu07.ini` can give the scripts all of LuaJIT's libraries +again: + +| key | default | meaning | +|---------------------|---------|------------------------------------------------------------------------------------------| +| `lua.fulllibraries` | no | yes: the scenery scripts get all of LuaJIT's libraries (`io`, `os`, `ffi`, `require`...), and with them the files and programs of the computer. The Lua screens stay sandboxed | diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 14ecbb75d..0854579d9 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -5,6 +5,7 @@ #include "world/MemCell.h" #include "vehicle/Driver.h" #include "simulation/simulation.h" +#include "scripting/luasandbox.h" lua::lua() { @@ -12,7 +13,10 @@ lua::lua() if (!state) throw std::runtime_error("cannot create lua state"); lua_atpanic(state, atpanic); - luaL_openlibs(state); + // sandboxed as the script screens are: no io, ffi, debug, require or load*, and of os only the clock. + // lua.fulllibraries in eu07.ini opens the rest when the scenery loads its first script (interpret()) + lua_sandbox::open_safe_libraries(state); + lua_sandbox::open_clock_library(state); static constexpr luaL_Reg api[] = { @@ -51,21 +55,29 @@ lua::~lua() std::string lua::get_error() const { - return lua_tostring(state, -1); + auto const *error = lua_tostring(state, -1); + return error ? error : "unknown error"; } -void lua::interpret(const std::string& file) const +void lua::interpret(const std::string &folder, const std::string &file) { - if (luaL_dofile(state, file.c_str())) { - std::string str = lua_tostring(state, -1); - ErrorLog("lua: Runtime error: " + str, logtype::lua); + if (Global.lua_fulllibraries && !full_libraries) { + // all of LuaJIT's libraries, as before the sandbox: the scripts may then reach files, programs and ffi + luaL_openlibs(state); + full_libraries = true; + WriteLog("lua: lua.fulllibraries is on, the scenery scripts run with all libraries (io, os, ffi, require...)", logtype::lua); + } + // a relative path inside the scenery folder, a file of text, run in protected mode: a script that fails stops + // there, and the scenery goes on loading + if (auto const error = lua_sandbox::run_script_file(state, folder, file)) { + ErrorLog("lua: " + *error, logtype::lua); } } int lua::atpanic(lua_State *s) { - std::string err = lua_tostring(s, -1); - ErrorLog("lua: Runtime error: " + err, logtype::lua); + auto const *err = lua_tostring(s, -1); + ErrorLog(std::string("lua: Runtime error: ") + (err ? err : "unknown error"), logtype::lua); return 0; } @@ -81,7 +93,12 @@ void lua::dispatch_event(lua_State *L, const int handler, basic_event *event, co lua_rawgeti(L, LUA_REGISTRYINDEX, handler); lua_pushlightuserdata(L, event); lua_pushlightuserdata(L, const_cast(activator)); - lua_call(L, 2, 0); + // in protected mode: a handler that fails is logged, and the simulation goes on + if (lua_pcall(L, 2, 0, 0) != 0) { + auto const *error = lua_tostring(L, -1); + ErrorLog("lua: event " + (event ? event->m_name : std::string("?")) + ": " + (error ? error : "unknown error"), logtype::lua); + lua_pop(L, 1); + } } void lua::push_memcell_values(lua_State *L, const TMemCell *mc) @@ -103,7 +120,8 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) // For negative indices, we need to account for the extra item that is the key name/value extracted from the table. if (idx < 0) idx--; - memcell_values mc{nullptr, 0.0, 0.0}; + // no text in the table is an empty one: the memcell and the vehicle take the text as a string + memcell_values mc{"", 0.0, 0.0}; lua_pushstring(L, "str"); lua_gettable(L, idx); if (lua_isstring(L, -1)) @@ -124,7 +142,7 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) int lua::scriptapi_event_create(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); double delay = lua_tonumber(L, 2); double randomdelay = lua_tonumber(L, 3); lua_pushvalue(L, 4); @@ -144,7 +162,7 @@ int lua::scriptapi_event_create(lua_State *L) int lua::scriptapi_event_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) { @@ -157,7 +175,7 @@ int lua::scriptapi_event_find(lua_State *L) int lua::scriptapi_event_exists(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); basic_event *foundevent = simulation::Events.FindEvent(name); lua_pushboolean(L, foundevent != nullptr); return 1; @@ -186,7 +204,7 @@ int lua::scriptapi_event_dispatch(lua_State *L) int lua::scriptapi_event_dispatch_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); auto *activator = static_cast(lua_touserdata(L, 2)); double delay = lua_tonumber(L, 3); basic_event *foundevent = simulation::Events.FindEvent(name); @@ -199,7 +217,7 @@ int lua::scriptapi_event_dispatch_n(lua_State *L) int lua::scriptapi_track_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { @@ -223,7 +241,7 @@ int lua::scriptapi_track_isoccupied(lua_State *L) int lua::scriptapi_track_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { @@ -236,7 +254,7 @@ int lua::scriptapi_track_isoccupied_n(lua_State *L) int lua::scriptapi_isolated_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { @@ -260,7 +278,7 @@ int lua::scriptapi_isolated_isoccupied(lua_State *L) int lua::scriptapi_isolated_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { @@ -298,7 +316,7 @@ int lua::scriptapi_dynobj_putvalues(lua_State *L) int lua::scriptapi_memcell_find(lua_State *L) { - std::string str = lua_tostring(L, 1); + std::string str = luaL_checkstring(L, 1); TMemCell *mc = simulation::Memory.find(str); if (mc) { @@ -318,7 +336,7 @@ int lua::scriptapi_memcell_read(lua_State *L) int lua::scriptapi_memcell_read_n(lua_State *L) { - std::string str = lua_tostring(L, 1); + std::string str = luaL_checkstring(L, 1); TMemCell *mc = simulation::Memory.find(str); push_memcell_values(L, mc); if (!mc) @@ -338,7 +356,7 @@ int lua::scriptapi_memcell_update(lua_State *L) int lua::scriptapi_memcell_update_n(lua_State *L) { - std::string mstr = lua_tostring(L, 1); + std::string mstr = luaL_checkstring(L, 1); auto [str, num1, num2] = get_memcell_values(L, 2); TMemCell *mc = simulation::Memory.find(mstr); if (mc) @@ -359,14 +377,14 @@ int lua::scriptapi_random(lua_State *L) int lua::scriptapi_writelog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + std::string txt = luaL_checkstring(L, 1); WriteLog("lua: log: " + txt, logtype::lua); return 0; } int lua::scriptapi_writeerrorlog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + std::string txt = luaL_checkstring(L, 1); ErrorLog("lua: log: " + txt, logtype::lua); return 0; } diff --git a/scripting/lua.h b/scripting/lua.h index 07d729264..8663103df 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -10,6 +10,7 @@ struct memcell_values { const char *str; double num1; double num2; }; class lua { lua_State *state; + bool full_libraries = false; // lua.fulllibraries: all of LuaJIT's libraries opened static int atpanic(lua_State *s); @@ -41,7 +42,9 @@ public: ~lua(); std::string get_error() const; - void interpret(const std::string& file) const; + // runs the script file, a relative path inside folder (the scenery folder), sandboxed (scripting/luasandbox.h). + // a script that can't be read or fails is logged + void interpret(const std::string &folder, const std::string &file); static void unref(lua_State *L, int ref); static void dispatch_event(lua_State *L, int handler, basic_event *event, const TDynamicObject *activator); static void push_memcell_values(lua_State *L, const TMemCell *mc); diff --git a/scripting/luaprogram.cpp b/scripting/luaprogram.cpp index 36d95d271..07fe89a4b 100644 --- a/scripting/luaprogram.cpp +++ b/scripting/luaprogram.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreenprogram.h" #include "scripting/scriptscreendrawing.h" #include "scripting/scriptscreenkernels.h" +#include "scripting/luasandbox.h" #include "utilities/Logs.h" #include "utilities/dictionary.h" @@ -411,12 +412,7 @@ int api_read_file(lua_State *L) // loads a script as text: precompiled code is refused. leaves the chunk, or an error message, on the stack bool load_chunk(lua_State *L, std::string_view const Code, std::string const &Name) { - if (false == Code.empty() && Code.front() == '\x1b') - { - lua_pushfstring(L, "%s: precompiled scripts aren't loaded", Name.c_str()); - return false; - } - return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); + return lua_sandbox::load_text_chunk(L, Code, Name); } // eu07.include(path): runs another script below the script's folder and returns what it returns @@ -724,30 +720,10 @@ void push_state(lua_State *L, dictionary_source const &Input) } } -void open_library(lua_State *L, lua_CFunction Open, char const *Name) -{ - lua_pushcfunction(L, Open); - lua_pushstring(L, Name); - lua_call(L, 1, 0); -} - void lua_program::open_libraries() { - open_library(m_state, luaopen_base, ""); - open_library(m_state, luaopen_table, LUA_TABLIBNAME); - open_library(m_state, luaopen_string, LUA_STRLIBNAME); - open_library(m_state, luaopen_math, LUA_MATHLIBNAME); - open_library(m_state, luaopen_bit, LUA_BITLIBNAME); - // what reaches files or loads code - for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) - { - lua_pushnil(m_state); - lua_setglobal(m_state, name); - } - lua_getglobal(m_state, LUA_STRLIBNAME); - lua_pushnil(m_state); - lua_setfield(m_state, -2, "dump"); - lua_pop(m_state, 1); + // base, table, string, math and bit, without what reaches files or loads code + lua_sandbox::open_safe_libraries(m_state); } void lua_program::register_api() diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp new file mode 100644 index 000000000..8d80cdebf --- /dev/null +++ b/scripting/luasandbox.cpp @@ -0,0 +1,167 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "scripting/luasandbox.h" + +#include "scripting/scriptscreenrules.h" + +#include +#include +#include + +namespace lua_sandbox +{ + +namespace +{ + +void open_library(lua_State *L, lua_CFunction Open, char const *Name) +{ + lua_pushcfunction(L, Open); + lua_pushstring(L, Name); + lua_call(L, 1, 0); +} + +// the conversions of strftime in C89, which every C library knows. LuaJIT hands each one to strftime on its own +constexpr std::string_view date_conversions{"aAbBcdHIjmMpSUwWxXyYZ%"}; + +// os.date(format, time), the library's own (the upvalue) for a format of known conversions only: the Microsoft +// C library ends the program on one it doesn't know ("%Q", "%#") +int api_date(lua_State *L) +{ + std::size_t length{0}; + auto const *format{luaL_optlstring(L, 1, "%c", &length)}; + std::string_view const text{format, length}; + for (std::size_t idx = 0; idx + 1 < text.size(); ++idx) + { + if (text[idx] != '%') + { + continue; + } + ++idx; + if (date_conversions.find(text[idx]) == std::string_view::npos) + { + return luaL_error(L, "os.date: unknown conversion '%%%c'", text[idx]); + } + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); + return lua_gettop(L); +} + +} // namespace + +void open_safe_libraries(lua_State *L) +{ + open_library(L, luaopen_base, ""); + open_library(L, luaopen_table, LUA_TABLIBNAME); + open_library(L, luaopen_string, LUA_STRLIBNAME); + open_library(L, luaopen_math, LUA_MATHLIBNAME); + open_library(L, luaopen_bit, LUA_BITLIBNAME); + // what reaches files or loads code + for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) + { + lua_pushnil(L); + lua_setglobal(L, name); + } + lua_getglobal(L, LUA_STRLIBNAME); + lua_pushnil(L); + lua_setfield(L, -2, "dump"); + lua_pop(L, 1); +} + +void open_clock_library(lua_State *L) +{ + // the whole library, of which a new table takes what only reads the clock + open_library(L, luaopen_os, LUA_OSLIBNAME); + lua_getglobal(L, LUA_OSLIBNAME); + lua_newtable(L); + for (auto const *name : {"time", "clock", "difftime"}) + { + lua_getfield(L, -2, name); + lua_setfield(L, -2, name); + } + lua_getfield(L, -2, "date"); + lua_pushcclosure(L, api_date, 1); + lua_setfield(L, -2, "date"); + // the new table in place of the library: the global, and the one the libraries know as loaded, which + // luaL_openlibs fills up again rather than make a new global + lua_pushvalue(L, -1); + lua_setglobal(L, LUA_OSLIBNAME); + lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); + lua_pushvalue(L, -2); + lua_setfield(L, -2, LUA_OSLIBNAME); + // _LOADED, the new table, the library + lua_pop(L, 3); +} + +bool load_text_chunk(lua_State *L, std::string_view const Code, std::string const &Name) +{ + if (false == Code.empty() && Code.front() == '\x1b') + { + lua_pushfstring(L, "%s: precompiled scripts aren't loaded", Name.c_str()); + return false; + } + return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); +} + +std::optional read_script_file(std::string const &Folder, std::string_view const Path) +{ + if (false == script_screens::is_safe_relative_path(Path)) + { + return std::nullopt; + } + // a folder or a device (CON, NUL, COM1...) isn't a regular file. in the code page of the system, as the game opens + // its files + std::filesystem::path const path{Folder + std::string{Path}}; + std::error_code error; + if (false == std::filesystem::is_regular_file(path, error)) + { + return std::nullopt; + } + auto const size{std::filesystem::file_size(path, error)}; + if (error || size > max_script_file) + { + return std::nullopt; + } + std::ifstream file{path, std::ios::binary}; + if (false == file.is_open()) + { + return std::nullopt; + } + std::string contents(static_cast(size), '\0'); + file.read(contents.data(), static_cast(contents.size())); + // what was read, should the file have shrunk meanwhile + contents.resize(static_cast(file.gcount())); + return contents; +} + +std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view const Path) +{ + auto const name{Folder + std::string{Path}}; + auto const code{read_script_file(Folder, Path)}; + if (false == code.has_value()) + { + return name + ": not found, not a file, larger than " + std::to_string(max_script_file) + + " bytes, or outside the folder (an absolute path, a drive or '..')"; + } + if (false == load_text_chunk(L, *code, name) || 0 != lua_pcall(L, 0, 0, 0)) + { + std::size_t length{0}; + auto const *message{lua_tolstring(L, -1, &length)}; + std::string result{message != nullptr ? std::string{message, length} : name + ": unknown error"}; + lua_pop(L, 1); + return result; + } + return std::nullopt; +} + +} // namespace lua_sandbox diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h new file mode 100644 index 000000000..abdd21933 --- /dev/null +++ b/scripting/luasandbox.h @@ -0,0 +1,49 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// what the Lua states of the game share to run scripts sandboxed: the scenery scripts (scripting/lua.cpp, lua in the +// .scn) and the script screens (scripting/luaprogram.cpp). a sandboxed script reaches no files, no other programs, no +// ffi and no debug library, and loads no code of its own: no require, dofile, load or precompiled chunks + +#include + +#include +#include +#include +#include + +namespace lua_sandbox +{ + +// the largest script file a scenery loads +constexpr std::uintmax_t max_script_file{16 * 1024 * 1024}; + +// the libraries a sandboxed script gets: base, table, string, math and bit, without dofile, loadfile, load, +// loadstring, module, require and string.dump +void open_safe_libraries(lua_State *L); + +// the os table with only what reads the clock: os.time, os.clock, os.difftime and os.date, the last refusing the +// conversions the C library doesn't know (the Microsoft one ends the program on them) +void open_clock_library(lua_State *L); + +// loads Code as text, under the name Name: precompiled code is refused. leaves the chunk, or an error message, on the +// stack +bool load_text_chunk(lua_State *L, std::string_view Code, std::string const &Name); + +// the file Path of Folder, when Path is a relative path inside Folder (no '..', no drive, no leading separator) and +// names a regular file of at most max_script_file bytes. nothing otherwise +std::optional read_script_file(std::string const &Folder, std::string_view Path); + +// reads the script Path of Folder (as read_script_file), loads it as text and runs it in protected mode. nothing when +// it ran, otherwise why it didn't +std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view Path); + +} // namespace lua_sandbox diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 9d1e94869..c39870600 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -405,7 +405,8 @@ void state_serializer::deserialize_lua( cParser &Input, scene::scratch_data &Scr std::string file; Input >> file; #ifdef WITH_LUA - simulation::Lua.interpret(Global.asCurrentSceneryPath + file); + // the file is relative to the scenery folder, and stays inside it + simulation::Lua.interpret(Global.asCurrentSceneryPath, file); #else ErrorLog(file + ": lua scripts not supported in this build."); #endif diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index c1ad98f35..e24db024f 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -39,7 +39,7 @@ target_link_libraries(${UNIT_TESTS_NAME} PRIVATE eu07_core) # the script screen host, tested with the real runtimes (test_script_screen_host.cpp) target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/scriptscreens.cpp") if (WITH_LUA) - target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/luaprogram.cpp" "${CMAKE_SOURCE_DIR}/stb/stb_image.c") + target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/luaprogram.cpp" "${CMAKE_SOURCE_DIR}/scripting/luasandbox.cpp" "${CMAKE_SOURCE_DIR}/stb/stb_image.c") endif() if (WITH_WASM) target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/wasmprogram.cpp") diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp new file mode 100644 index 000000000..f23cb0406 --- /dev/null +++ b/tests/unit/test_lua_sandbox.cpp @@ -0,0 +1,218 @@ +#include "stdafx.h" +#include "doctest.h" + +// the sandbox the Lua states of the game share (scripting/luasandbox.cpp): the scenery scripts (lua in the .scn, +// scripting/lua.cpp) and the script screens (scripting/luaprogram.cpp, tested with the screens in +// test_script_screen_host.cpp). a script gets base, table, string, math and bit, and of os only the clock; it reaches +// no files, no programs, no ffi, loads no code of its own and no precompiled chunk, and a scenery reads its scripts +// only from its own folder + +#ifdef WITH_LUA + +#include "scripting/luasandbox.h" +#include "scratch.h" + +#include +#include +#include +#include + +namespace { + +// a state with the libraries of the scenery scripts +class sandboxed_state { + public: + sandboxed_state() : m_state{luaL_newstate()} { + lua_sandbox::open_safe_libraries(m_state); + lua_sandbox::open_clock_library(m_state); + } + ~sandboxed_state() { lua_close(m_state); } + sandboxed_state(sandboxed_state const &) = delete; + sandboxed_state &operator=(sandboxed_state const &) = delete; + + lua_State *get() const { return m_state; } + + // runs the code, which returns one value, and gives that value as text ("nil", "true", a number, a string), or + // "error: " and the message + std::string run(std::string_view const Code) const { + auto const top{lua_gettop(m_state)}; + std::string result; + if (false == lua_sandbox::load_text_chunk(m_state, Code, "test") || 0 != lua_pcall(m_state, 0, 1, 0)) { + result = std::string{"error: "} + lua_tostring(m_state, -1); + } else if (lua_isnil(m_state, -1)) { + result = "nil"; + } else if (lua_isboolean(m_state, -1)) { + result = lua_toboolean(m_state, -1) ? "true" : "false"; + } else { + auto const *text{lua_tostring(m_state, -1)}; + result = text != nullptr ? text : "?"; + } + lua_settop(m_state, top); + return result; + } + + private: + lua_State *m_state; +}; + +bool contains(std::string_view const Text, std::string_view const Part) { + return Text.find(Part) != std::string_view::npos; +} + +} // namespace + +TEST_CASE("lua sandbox: no library that reaches files, programs, ffi or the debugger, and nothing that loads code") { + sandboxed_state const lua; + for (auto const *name : {"io", "ffi", "debug", "package", "jit", "require", "module", "dofile", "loadfile", "load", "loadstring", + "string.dump", "os.execute", "os.exit", "os.remove", "os.rename", "os.getenv", "os.tmpname", + "os.setlocale"}) { + CAPTURE(name); + CHECK(lua.run(std::format("return {}", name)) == "nil"); + } + // what the scripts did with them fails, as a Lua error + CHECK(contains(lua.run("return io.open('eu07.ini')"), "attempt to index global 'io' (a nil value)")); + CHECK(contains(lua.run("return os.execute('cmd')"), "attempt to call field 'execute' (a nil value)")); + CHECK(contains(lua.run("return require('ffi')"), "attempt to call global 'require' (a nil value)")); +} + +TEST_CASE("lua sandbox: the libraries a script gets work") { + sandboxed_state const lua; + CHECK(lua.run("return math.floor(2.5) + #string.rep('a', 3) + bit.band(7, 4) + #table.concat({ 'a', 'b' })") == "11"); + CHECK(lua.run("return ('%d-%s'):format(7, 'x')") == "7-x"); + CHECK(lua.run("local ok, error = pcall(function() error('boom') end) return (not ok) and error:find('boom') ~= nil") == "true"); + CHECK(lua.run("local n = 0 for _, v in ipairs({ 1, 2, 3 }) do n = n + v end return n") == "6"); + CHECK(lua.run("return tostring(tonumber('12') + select('#', 1, 2))") == "14"); +} + +TEST_CASE("lua sandbox: os reads the clock, and nothing else") { + sandboxed_state const lua; + CHECK(lua.run("return type(os.time()) == 'number' and os.time() > 0") == "true"); + CHECK(lua.run("return type(os.clock()) == 'number'") == "true"); + CHECK(lua.run("return os.difftime(10, 4)") == "6"); + CHECK(lua.run("return os.time({ year = 2020, month = 1, day = 2, hour = 12 }) > 0") == "true"); + CHECK(lua.run("return os.date('!%Y-%m-%d', 0)") == "1970-01-01"); + CHECK(lua.run("return os.date('!*t', 86400 * 365).year") == "1971"); + CHECK(lua.run("return #os.date()") != "0"); + // a lone % at the end and %% are text + CHECK(lua.run("return os.date('!100%%', 0)") == "100%"); + CHECK(lua.run("return os.date('!100%', 0)") == "100%"); + // conversions the Microsoft C library doesn't know end the program there: refused before + CHECK(contains(lua.run("return os.date('%Q')"), "os.date: unknown conversion '%Q'")); + CHECK(contains(lua.run("return os.date('%#c')"), "os.date: unknown conversion '%#'")); + CHECK(contains(lua.run("return os.date('%Ey')"), "os.date: unknown conversion '%E'")); + // the table holds only the clock + CHECK(lua.run("local n = 0 for _ in pairs(os) do n = n + 1 end return n") == "4"); +} + +TEST_CASE("lua sandbox: all libraries opened over the sandbox are whole again (lua.fulllibraries)") { + sandboxed_state const lua; + luaL_openlibs(lua.get()); + for (auto const *name : {"io.open", "os.execute", "os.getenv", "os.date", "require", "loadstring", "dofile", "string.dump", "debug.traceback"}) { + CAPTURE(name); + CHECK(lua.run(std::format("return type({})", name)) == "function"); + } + CHECK(lua.run("return type(require('ffi'))") == "table"); + CHECK(lua.run("return rawequal(os, package.loaded.os)") == "true"); +} + +TEST_CASE("lua sandbox: precompiled code isn't loaded") { + // real LuaJIT bytecode, from a state with all libraries + auto *full{luaL_newstate()}; + luaL_openlibs(full); + // luaL_dostring is a || of two calls, a bool in C++ + REQUIRE_FALSE(luaL_dostring(full, "return string.dump(function() return 42 end)")); + std::size_t length{0}; + auto const *bytes{lua_tolstring(full, -1, &length)}; + std::string const bytecode{bytes, length}; + lua_close(full); + REQUIRE(false == bytecode.empty()); + CHECK(bytecode.front() == '\x1b'); + + sandboxed_state const lua; + auto const top{lua_gettop(lua.get())}; + CHECK_FALSE(lua_sandbox::load_text_chunk(lua.get(), bytecode, "compiled.lua")); + CHECK(contains(lua_tostring(lua.get(), -1), "compiled.lua: precompiled scripts aren't loaded")); + lua_settop(lua.get(), top); + // nor in a text that only starts with the marker + CHECK_FALSE(lua_sandbox::load_text_chunk(lua.get(), std::string_view{"\x1bLJ\x02 return 1"}, "fake.lua")); + lua_settop(lua.get(), top); +} + +TEST_CASE("lua sandbox: a scenery reads its scripts only from its own folder") { + test::scratch_folder const root{"lua_sandbox_paths"}; + root.write("outside.lua", "return 1"); + root.write("scenery/test.lua", "return 2"); + root.write("scenery/scripts/module.lua", "return 3"); + root.write("scenery/folder.lua/inner.lua", "return 4"); + auto const folder{root.path("scenery") + "/"}; + + CHECK(lua_sandbox::read_script_file(folder, "test.lua") == std::optional{"return 2"}); + CHECK(lua_sandbox::read_script_file(folder, "scripts/module.lua") == std::optional{"return 3"}); + CHECK(lua_sandbox::read_script_file(folder, "scripts\\module.lua") == std::optional{"return 3"}); + for (auto const &path : {std::string{"../outside.lua"}, std::string{"scripts/../../outside.lua"}, std::string{"..\\outside.lua"}, + root.path("outside.lua"), std::string{"/outside.lua"}, std::string{"\\outside.lua"}, std::string{"C:outside.lua"}, + std::string{"missing.lua"}, std::string{"folder.lua"}, std::string{"scripts"}, std::string{}}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::read_script_file(folder, path).has_value()); + } +} + +TEST_CASE("lua sandbox: a script larger than the limit isn't read") { + test::scratch_folder const root{"lua_sandbox_size"}; + root.write("scenery/limit.lua", std::string(static_cast(lua_sandbox::max_script_file), ' ')); + root.write("scenery/over.lua", std::string(static_cast(lua_sandbox::max_script_file) + 1, ' ')); + auto const folder{root.path("scenery") + "/"}; + CHECK(lua_sandbox::read_script_file(folder, "limit.lua").has_value()); + CHECK_FALSE(lua_sandbox::read_script_file(folder, "over.lua").has_value()); +} + +TEST_CASE("lua sandbox: a scenery script runs in protected mode, and its errors name the file") { + test::scratch_folder const root{"lua_sandbox_run"}; + root.write("scenery/good.lua", "ran = (ran or 0) + 1"); + root.write("scenery/fails.lua", "ran = 10\nlocal x = nil\nx.field = 1\nran = 20"); + root.write("scenery/files.lua", "local f = io.open('eu07.ini')"); + root.write("scenery/system.lua", "os.execute('cmd /c echo pwned')"); + root.write("scenery/syntax.lua", "this is not lua"); + root.write("scenery/compiled.lua", std::string_view{"\x1bLJ\x02 bytes"}); + auto const folder{root.path("scenery") + "/"}; + + sandboxed_state const lua; + auto *L{lua.get()}; + auto const top{lua_gettop(L)}; + + CHECK_FALSE(lua_sandbox::run_script_file(L, folder, "good.lua").has_value()); + CHECK(lua.run("return ran") == "1"); + + auto const fails{lua_sandbox::run_script_file(L, folder, "fails.lua")}; + REQUIRE(fails.has_value()); + CHECK(contains(*fails, "fails.lua:3:")); + // it stopped at the error + CHECK(lua.run("return ran") == "10"); + + auto const files{lua_sandbox::run_script_file(L, folder, "files.lua")}; + REQUIRE(files.has_value()); + CHECK(contains(*files, "files.lua:1: attempt to index global 'io' (a nil value)")); + + auto const system{lua_sandbox::run_script_file(L, folder, "system.lua")}; + REQUIRE(system.has_value()); + CHECK(contains(*system, "system.lua:1: attempt to call field 'execute' (a nil value)")); + + auto const syntax{lua_sandbox::run_script_file(L, folder, "syntax.lua")}; + REQUIRE(syntax.has_value()); + CHECK(contains(*syntax, "syntax.lua:1:")); + + auto const compiled{lua_sandbox::run_script_file(L, folder, "compiled.lua")}; + REQUIRE(compiled.has_value()); + CHECK(contains(*compiled, "compiled.lua: precompiled scripts aren't loaded")); + + auto const outside{lua_sandbox::run_script_file(L, folder, "../good.lua")}; + REQUIRE(outside.has_value()); + CHECK(contains(*outside, "outside the folder")); + + // nothing left on the stack, and the state still works + CHECK(lua_gettop(L) == top); + CHECK_FALSE(lua_sandbox::run_script_file(L, folder, "good.lua").has_value()); + CHECK(lua.run("return ran") == "11"); +} + +#endif diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a2cb6f59d..2b5684dab 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -956,6 +956,14 @@ bool global_settings::ConfigParseScriptScreens(cParser& Parser, std::string_view return true; } + // the scenery scripts (lua in the .scn) with all of LuaJIT's libraries, for a scenery that needs io, ffi or + // require: they then reach files and programs as the player does + if (token == "lua.fulllibraries") + { + ParseOne(Parser, lua_fulllibraries, 1); + return true; + } + if (token == "wasm.enabled") { ParseOne(Parser, wasm_enabled, 1); @@ -1962,6 +1970,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "python.uploadmain", python_uploadmain ); export_as_text( Output, "python.mipmaps", python_mipmaps ); export_as_text( Output, "luascreens.enabled", luascreens_enabled ); + export_as_text( Output, "lua.fulllibraries", lua_fulllibraries ); export_as_text( Output, "wasm.enabled", wasm_enabled ); export_as_text( Output, "screens.cabframes", screens_cabframes ); export_as_text( Output, "screens.externalframes", screens_externalframes ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 8d32a463c..25c7872c8 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -312,6 +312,7 @@ struct global_settings { bool python_uploadmain = true; std::chrono::duration python_minframetime {0.01f}; bool luascreens_enabled{true}; // screens drawn by Lua scripts (luascreen:, luadestinationsign: in the .mmd) + bool lua_fulllibraries{false}; // the scenery scripts (lua in the .scn) get all of LuaJIT's libraries (io, os, ffi, require...), not only the sandboxed ones bool wasm_enabled{true}; // screens drawn by WebAssembly modules (wasmscreen:, wasmdestinationsign: in the .mmd) int screens_cabframes{4}; // the script screens in the cab are refreshed every so many rendered frames int screens_externalframes{30}; // the script screens outside the cab (destination signs) are refreshed every so many rendered frames