3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "cpp_api/s_security.h"
21 #include "lua_api/l_base.h"
25 #include "client/client.h"
34 #define SECURE_API(lib, name) \
35 lua_pushcfunction(L, sl_##lib##_##name); \
36 lua_setfield(L, -2, #name);
39 static inline void copy_safe(lua_State *L, const char *list[], unsigned len, int from=-2, int to=-1)
41 if (from < 0) from = lua_gettop(L) + from + 1;
42 if (to < 0) to = lua_gettop(L) + to + 1;
43 for (unsigned i = 0; i < (len / sizeof(list[0])); i++) {
44 lua_getfield(L, from, list[i]);
45 lua_setfield(L, to, list[i]);
49 static void shallow_copy_table(lua_State *L, int from=-2, int to=-1)
51 if (from < 0) from = lua_gettop(L) + from + 1;
52 if (to < 0) to = lua_gettop(L) + to + 1;
54 while (lua_next(L, from) != 0) {
55 assert(lua_type(L, -1) != LUA_TTABLE);
56 // duplicate key and value for lua_rawset
64 // Pushes the original version of a library function on the stack, from the old version
65 static inline void push_original(lua_State *L, const char *lib, const char *func)
67 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
68 lua_getfield(L, -1, lib);
69 lua_remove(L, -2); // Remove globals_backup
70 lua_getfield(L, -1, func);
71 lua_remove(L, -2); // Remove lib
75 void ScriptApiSecurity::initializeSecurity()
77 static const char *whitelist[] = {
104 static const char *whitelist_tables[] = {
105 // These libraries are completely safe BUT we need to duplicate their table
106 // to ensure the sandbox can't affect the insecure env
113 static const char *io_whitelist[] = {
120 static const char *os_whitelist[] = {
127 static const char *debug_whitelist[] = {
137 static const char *package_whitelist[] = {
144 static const char *jit_whitelist[] = {
158 lua_State *L = getStack();
160 // Backup globals to the registry
161 lua_getglobal(L, "_G");
162 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
164 // Replace the global environment with an empty one
165 int thread = getThread(L);
167 setLuaEnv(L, thread);
170 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
171 int old_globals = lua_gettop(L);
174 // Copy safe base functions
175 lua_getglobal(L, "_G");
176 copy_safe(L, whitelist, sizeof(whitelist));
178 // And replace unsafe ones
179 SECURE_API(g, dofile);
181 SECURE_API(g, loadfile);
182 SECURE_API(g, loadstring);
183 SECURE_API(g, require);
187 // Copy safe libraries
188 for (const char *libname : whitelist_tables) {
189 lua_getfield(L, old_globals, libname);
191 shallow_copy_table(L);
193 lua_setglobal(L, libname);
198 // Copy safe IO functions
199 lua_getfield(L, old_globals, "io");
201 copy_safe(L, io_whitelist, sizeof(io_whitelist));
203 // And replace unsafe ones
204 SECURE_API(io, open);
205 SECURE_API(io, input);
206 SECURE_API(io, output);
207 SECURE_API(io, lines);
209 lua_setglobal(L, "io");
210 lua_pop(L, 1); // Pop old IO
213 // Copy safe OS functions
214 lua_getfield(L, old_globals, "os");
216 copy_safe(L, os_whitelist, sizeof(os_whitelist));
218 // And replace unsafe ones
219 SECURE_API(os, remove);
220 SECURE_API(os, rename);
221 SECURE_API(os, setlocale);
223 lua_setglobal(L, "os");
224 lua_pop(L, 1); // Pop old OS
227 // Copy safe debug functions
228 lua_getfield(L, old_globals, "debug");
230 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
231 lua_setglobal(L, "debug");
232 lua_pop(L, 1); // Pop old debug
235 // Copy safe package fields
236 lua_getfield(L, old_globals, "package");
238 copy_safe(L, package_whitelist, sizeof(package_whitelist));
239 lua_setglobal(L, "package");
240 lua_pop(L, 1); // Pop old package
243 // Copy safe jit functions, if they exist
244 lua_getfield(L, -1, "jit");
245 if (!lua_isnil(L, -1)) {
247 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
248 lua_setglobal(L, "jit");
250 lua_pop(L, 1); // Pop old jit
253 // Get rid of 'core' in the old globals, we don't want anyone thinking it's
254 // safe or even usable.
256 lua_setfield(L, old_globals, "core");
260 lua_setfield(L, old_globals, "vector");
262 lua_pop(L, 1); // Pop globals_backup
266 * In addition to copying the tables in whitelist_tables, we also need to
267 * replace the string metatable. Otherwise old_globals.string would
268 * be accessible via getmetatable("").__index from inside the sandbox.
270 lua_pushliteral(L, "");
272 lua_getglobal(L, "string");
273 lua_setfield(L, -2, "__index");
274 lua_setmetatable(L, -2);
275 lua_pop(L, 1); // Pop empty string
278 void ScriptApiSecurity::initializeSecurityClient()
280 static const char *whitelist[] = {
297 // getmetatable can be used to escape the sandbox <- ???
306 // Completely safe libraries
313 static const char *os_whitelist[] = {
319 static const char *debug_whitelist[] = {
320 "getinfo", // used by builtin and unset before mods load
325 static const char *jit_whitelist[] = {
340 lua_State *L = getStack();
341 int thread = getThread(L);
343 // create an empty environment
346 // Copy safe base functions
347 lua_getglobal(L, "_G");
348 lua_getfield(L, -2, "_G");
349 copy_safe(L, whitelist, sizeof(whitelist));
351 // And replace unsafe ones
352 SECURE_API(g, dofile);
354 SECURE_API(g, loadfile);
355 SECURE_API(g, loadstring);
356 SECURE_API(g, require);
361 // Copy safe OS functions
362 lua_getglobal(L, "os");
364 copy_safe(L, os_whitelist, sizeof(os_whitelist));
365 lua_setfield(L, -3, "os");
366 lua_pop(L, 1); // Pop old OS
369 // Copy safe debug functions
370 lua_getglobal(L, "debug");
372 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
373 lua_setfield(L, -3, "debug");
374 lua_pop(L, 1); // Pop old debug
377 // Copy safe jit functions, if they exist
378 lua_getglobal(L, "jit");
380 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
381 lua_setfield(L, -3, "jit");
382 lua_pop(L, 1); // Pop old jit
385 // Set the environment to the one we created earlier
386 setLuaEnv(L, thread);
389 int ScriptApiSecurity::getThread(lua_State *L)
391 #if LUA_VERSION_NUM <= 501
392 int is_main = lua_pushthread(L); // Push the main thread
393 FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
394 "isn't the main Lua thread!");
395 return lua_gettop(L);
400 void ScriptApiSecurity::createEmptyEnv(lua_State *L)
402 lua_newtable(L); // Create new environment
403 lua_pushvalue(L, -1);
404 lua_setfield(L, -2, "_G"); // Create the _G loop
407 void ScriptApiSecurity::setLuaEnv(lua_State *L, int thread)
409 #if LUA_VERSION_NUM >= 502 // Lua >= 5.2
410 // Set the global environment
411 lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
413 // Set the environment of the main thread
414 FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set "
415 "environment of the main Lua thread!");
416 lua_pop(L, 1); // Pop thread
420 bool ScriptApiSecurity::isSecure(lua_State *L)
422 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
423 bool secure = !lua_isnil(L, -1);
428 bool ScriptApiSecurity::safeLoadString(lua_State *L, const std::string &code, const char *chunk_name)
430 if (code.size() > 0 && code[0] == LUA_SIGNATURE[0]) {
431 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
434 if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name))
439 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name)
447 chunk_name = const_cast<char *>("=stdin");
449 fp = fopen(path, "rb");
451 lua_pushfstring(L, "%s: %s", path, strerror(errno));
454 size_t len = strlen(display_name) + 2;
455 chunk_name = new char[len];
456 snprintf(chunk_name, len, "@%s", display_name);
460 int c = std::getc(fp);
462 // Skip the first line
463 while ((c = std::getc(fp)) != EOF && c != '\n') {}
466 start = std::ftell(fp);
470 int ret = std::fseek(fp, 0, SEEK_END);
472 lua_pushfstring(L, "%s: %s", path, strerror(errno));
475 delete [] chunk_name;
480 size_t size = std::ftell(fp) - start;
481 std::string code(size, '\0');
482 ret = std::fseek(fp, start, SEEK_SET);
484 lua_pushfstring(L, "%s: %s", path, strerror(errno));
487 delete [] chunk_name;
492 size_t num_read = std::fread(&code[0], 1, size, fp);
495 if (num_read != size) {
496 lua_pushliteral(L, "Error reading file to load.");
498 delete [] chunk_name;
502 bool result = safeLoadString(L, code, chunk_name);
504 delete [] chunk_name;
509 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
510 bool write_required, bool *write_allowed)
513 *write_allowed = false;
515 std::string str; // Transient
517 std::string abs_path = fs::AbsolutePath(path);
519 if (!abs_path.empty()) {
520 // Don't allow accessing the settings file
521 str = fs::AbsolutePath(g_settings_path);
522 if (str == abs_path) return false;
525 // If we couldn't find the absolute path (path doesn't exist) then
526 // try removing the last components until it works (to allow
527 // non-existent files/folders for mkdir).
528 std::string cur_path = path;
530 while (abs_path.empty() && !cur_path.empty()) {
531 std::string component;
532 cur_path = fs::RemoveLastPathComponent(cur_path, &component);
533 if (component == "..") {
534 // Parent components can't be allowed or we could allow something like
535 // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
536 // If we have previous non-relative elements in the path we might be
537 // able to remove them so that things like worlds/foo/noexist/../auth.txt
538 // could be allowed, but those paths will be interpreted as nonexistent
539 // by the operating system anyways.
542 removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed);
543 abs_path = fs::AbsolutePath(cur_path);
545 if (abs_path.empty())
547 // Add the removed parts back so that you can't, eg, create a
548 // directory in worldmods if worldmods doesn't exist.
549 if (!removed.empty())
550 abs_path += DIR_DELIM + removed;
552 // Get gamedef from registry
553 ScriptApiBase *script = ModApiBase::getScriptApiBase(L);
554 const IGameDef *gamedef = script->getGameDef();
559 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
560 if (lua_isstring(L, -1)) {
561 std::string mod_name = readParam<std::string>(L, -1);
563 // Builtin can access anything
564 if (mod_name == BUILTIN_MOD_NAME) {
565 if (write_allowed) *write_allowed = true;
569 // Allow paths in mod path
570 // Don't bother if write access isn't important, since it will be handled later
571 if (write_required || write_allowed != NULL) {
572 const ModSpec *mod = gamedef->getModSpec(mod_name);
574 str = fs::AbsolutePath(mod->path);
575 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
576 if (write_allowed) *write_allowed = true;
582 lua_pop(L, 1); // Pop mod name
584 // Allow read-only access to all mod directories
585 if (!write_required) {
586 const std::vector<ModSpec> &mods = gamedef->getMods();
587 for (const ModSpec &mod : mods) {
588 str = fs::AbsolutePath(mod.path);
589 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
595 str = fs::AbsolutePath(gamedef->getWorldPath());
597 // Don't allow access to other paths in the world mod/game path.
598 // These have to be blocked so you can't override a trusted mod
599 // by creating a mod with the same name in a world mod directory.
600 // We add to the absolute path of the world instead of getting
601 // the absolute paths directly because that won't work if they
603 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
604 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
607 // Allow all other paths in world path
608 if (fs::PathStartsWith(abs_path, str)) {
609 if (write_allowed) *write_allowed = true;
614 // Default to disallowing
618 bool ScriptApiSecurity::checkWhitelisted(lua_State *L, const std::string &setting)
620 assert(str_starts_with(setting, "secure."));
622 // We have to make sure that this function is being called directly by
623 // a mod, otherwise a malicious mod could override this function and
624 // steal its return value.
627 // Make sure there's only one item below this function on the stack...
628 if (lua_getstack(L, 2, &info))
630 FATAL_ERROR_IF(!lua_getstack(L, 1, &info), "lua_getstack() failed");
631 FATAL_ERROR_IF(!lua_getinfo(L, "S", &info), "lua_getinfo() failed");
633 // ...and that that item is the main file scope.
634 if (strcmp(info.what, "main") != 0)
637 // Mod must be listed in secure.http_mods or secure.trusted_mods
638 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
639 if (!lua_isstring(L, -1))
641 std::string mod_name = readParam<std::string>(L, -1);
643 std::string value = g_settings->get(setting);
644 value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
645 auto mod_list = str_split(value, ',');
647 return CONTAINS(mod_list, mod_name);
651 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
653 int nret = sl_g_loadfile(L);
656 // code after this function isn't executed
658 int top_precall = lua_gettop(L);
659 lua_call(L, 0, LUA_MULTRET);
660 // Return number of arguments returned by the function,
661 // adjusting for the function being poped.
662 return lua_gettop(L) - (top_precall - 1);
666 int ScriptApiSecurity::sl_g_load(lua_State *L)
671 const char *chunk_name = "=(load)";
673 luaL_checktype(L, 1, LUA_TFUNCTION);
674 if (!lua_isnone(L, 2)) {
675 luaL_checktype(L, 2, LUA_TSTRING);
676 chunk_name = lua_tostring(L, 2);
682 int t = lua_type(L, -1);
687 if (t != LUA_TSTRING) {
689 lua_pushliteral(L, "Loader didn't return a string");
692 buf = lua_tolstring(L, -1, &len);
693 code += std::string(buf, len);
694 lua_pop(L, 1); // Pop return value
696 if (!safeLoadString(L, code, chunk_name)) {
705 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
708 ScriptApiBase *script = ModApiBase::getScriptApiBase(L);
710 // Client implementation
711 if (script->getType() == ScriptingType::Client) {
712 std::string path = readParam<std::string>(L, 1);
713 const std::string *contents = script->getClient()->getModFile(path);
715 std::string error_msg = "Coudln't find script called: " + path;
717 lua_pushstring(L, error_msg.c_str());
721 std::string chunk_name = "@" + path;
722 if (!safeLoadString(L, *contents, chunk_name.c_str())) {
731 // Server implementation
732 const char *path = NULL;
733 if (lua_isstring(L, 1)) {
734 path = lua_tostring(L, 1);
735 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
738 if (!safeLoadFile(L, path)) {
748 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
750 const char *chunk_name = "=(load)";
752 luaL_checktype(L, 1, LUA_TSTRING);
753 if (!lua_isnone(L, 2)) {
754 luaL_checktype(L, 2, LUA_TSTRING);
755 chunk_name = lua_tostring(L, 2);
759 const char *code = lua_tolstring(L, 1, &size);
760 std::string code_s(code, size);
762 if (!safeLoadString(L, code_s, chunk_name)) {
771 int ScriptApiSecurity::sl_g_require(lua_State *L)
773 lua_pushliteral(L, "require() is disabled when mod security is on.");
778 int ScriptApiSecurity::sl_io_open(lua_State *L)
780 bool with_mode = lua_gettop(L) > 1;
782 luaL_checktype(L, 1, LUA_TSTRING);
783 const char *path = lua_tostring(L, 1);
785 bool write_requested = false;
787 luaL_checktype(L, 2, LUA_TSTRING);
788 const char *mode = lua_tostring(L, 2);
789 write_requested = strchr(mode, 'w') != NULL ||
790 strchr(mode, '+') != NULL ||
791 strchr(mode, 'a') != NULL;
793 CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
795 push_original(L, "io", "open");
801 lua_call(L, with_mode ? 2 : 1, 2);
806 int ScriptApiSecurity::sl_io_input(lua_State *L)
808 if (lua_isstring(L, 1)) {
809 const char *path = lua_tostring(L, 1);
810 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
813 push_original(L, "io", "input");
820 int ScriptApiSecurity::sl_io_output(lua_State *L)
822 if (lua_isstring(L, 1)) {
823 const char *path = lua_tostring(L, 1);
824 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
827 push_original(L, "io", "output");
834 int ScriptApiSecurity::sl_io_lines(lua_State *L)
836 if (lua_isstring(L, 1)) {
837 const char *path = lua_tostring(L, 1);
838 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
841 int top_precall = lua_gettop(L);
842 push_original(L, "io", "lines");
844 lua_call(L, 1, LUA_MULTRET);
845 // Return number of arguments returned by the function,
846 // adjusting for the function being poped.
847 return lua_gettop(L) - top_precall;
851 int ScriptApiSecurity::sl_os_rename(lua_State *L)
853 luaL_checktype(L, 1, LUA_TSTRING);
854 const char *path1 = lua_tostring(L, 1);
855 CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
857 luaL_checktype(L, 2, LUA_TSTRING);
858 const char *path2 = lua_tostring(L, 2);
859 CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
861 push_original(L, "os", "rename");
869 int ScriptApiSecurity::sl_os_remove(lua_State *L)
871 luaL_checktype(L, 1, LUA_TSTRING);
872 const char *path = lua_tostring(L, 1);
873 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
875 push_original(L, "os", "remove");
882 int ScriptApiSecurity::sl_os_setlocale(lua_State *L)
884 const bool cat = lua_gettop(L) > 1;
885 // Don't allow changes
886 if (!lua_isnoneornil(L, 1)) {
891 push_original(L, "os", "setlocale");
895 lua_call(L, cat ? 2 : 1, 1);