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[] = {
121 static const char *os_whitelist[] = {
128 static const char *debug_whitelist[] = {
138 static const char *package_whitelist[] = {
145 static const char *jit_whitelist[] = {
159 lua_State *L = getStack();
161 // Backup globals to the registry
162 lua_getglobal(L, "_G");
163 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
165 // Replace the global environment with an empty one
166 int thread = getThread(L);
168 setLuaEnv(L, thread);
171 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
172 int old_globals = lua_gettop(L);
175 // Copy safe base functions
176 lua_getglobal(L, "_G");
177 copy_safe(L, whitelist, sizeof(whitelist));
179 // And replace unsafe ones
180 SECURE_API(g, dofile);
182 SECURE_API(g, loadfile);
183 SECURE_API(g, loadstring);
184 SECURE_API(g, require);
188 // Copy safe libraries
189 for (const char *libname : whitelist_tables) {
190 lua_getfield(L, old_globals, libname);
192 shallow_copy_table(L);
194 lua_setglobal(L, libname);
199 // Copy safe IO functions
200 lua_getfield(L, old_globals, "io");
202 copy_safe(L, io_whitelist, sizeof(io_whitelist));
204 // And replace unsafe ones
205 //SECURE_API(io, open);
206 SECURE_API(io, input);
207 SECURE_API(io, output);
208 SECURE_API(io, lines);
210 lua_setglobal(L, "io");
211 lua_pop(L, 1); // Pop old IO
214 // Copy safe OS functions
215 lua_getfield(L, old_globals, "os");
217 copy_safe(L, os_whitelist, sizeof(os_whitelist));
219 // And replace unsafe ones
220 SECURE_API(os, remove);
221 SECURE_API(os, rename);
222 SECURE_API(os, setlocale);
224 lua_setglobal(L, "os");
225 lua_pop(L, 1); // Pop old OS
228 // Copy safe debug functions
229 lua_getfield(L, old_globals, "debug");
231 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
232 lua_setglobal(L, "debug");
233 lua_pop(L, 1); // Pop old debug
236 // Copy safe package fields
237 lua_getfield(L, old_globals, "package");
239 copy_safe(L, package_whitelist, sizeof(package_whitelist));
240 lua_setglobal(L, "package");
241 lua_pop(L, 1); // Pop old package
244 // Copy safe jit functions, if they exist
245 lua_getfield(L, -1, "jit");
246 if (!lua_isnil(L, -1)) {
248 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
249 lua_setglobal(L, "jit");
251 lua_pop(L, 1); // Pop old jit
254 // Get rid of 'core' in the old globals, we don't want anyone thinking it's
255 // safe or even usable.
257 lua_setfield(L, old_globals, "core");
261 lua_setfield(L, old_globals, "vector");
263 lua_pop(L, 1); // Pop globals_backup
267 * In addition to copying the tables in whitelist_tables, we also need to
268 * replace the string metatable. Otherwise old_globals.string would
269 * be accessible via getmetatable("").__index from inside the sandbox.
271 lua_pushliteral(L, "");
273 lua_getglobal(L, "string");
274 lua_setfield(L, -2, "__index");
275 lua_setmetatable(L, -2);
276 lua_pop(L, 1); // Pop empty string
279 void ScriptApiSecurity::initializeSecurityClient()
281 static const char *whitelist[] = {
298 // getmetatable can be used to escape the sandbox <- ???
307 // Completely safe libraries
314 static const char *os_whitelist[] = {
320 static const char *debug_whitelist[] = {
321 "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 // Backup globals to the registry
344 lua_getglobal(L, "_G");
345 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
347 // create an empty environment
350 // Copy safe base functions
351 lua_getglobal(L, "_G");
352 lua_getfield(L, -2, "_G");
353 copy_safe(L, whitelist, sizeof(whitelist));
355 // And replace unsafe ones
356 SECURE_API(g, dofile);
358 SECURE_API(g, loadfile);
359 SECURE_API(g, loadstring);
360 SECURE_API(g, require);
363 // Copy safe OS functions
364 lua_getglobal(L, "os");
366 copy_safe(L, os_whitelist, sizeof(os_whitelist));
367 lua_setfield(L, -3, "os");
368 lua_pop(L, 1); // Pop old OS
371 // Copy safe debug functions
372 lua_getglobal(L, "debug");
374 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
375 lua_setfield(L, -3, "debug");
376 lua_pop(L, 1); // Pop old debug
380 // Copy safe jit functions, if they exist
381 lua_getglobal(L, "jit");
383 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
384 lua_setfield(L, -3, "jit");
385 lua_pop(L, 1); // Pop old jit
388 // Set the environment to the one we created earlier
389 setLuaEnv(L, thread);
392 int ScriptApiSecurity::getThread(lua_State *L)
394 #if LUA_VERSION_NUM <= 501
395 int is_main = lua_pushthread(L); // Push the main thread
396 FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
397 "isn't the main Lua thread!");
398 return lua_gettop(L);
403 void ScriptApiSecurity::createEmptyEnv(lua_State *L)
405 lua_newtable(L); // Create new environment
406 lua_pushvalue(L, -1);
407 lua_setfield(L, -2, "_G"); // Create the _G loop
410 void ScriptApiSecurity::setLuaEnv(lua_State *L, int thread)
412 #if LUA_VERSION_NUM >= 502 // Lua >= 5.2
413 // Set the global environment
414 lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
416 // Set the environment of the main thread
417 FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set "
418 "environment of the main Lua thread!");
419 lua_pop(L, 1); // Pop thread
423 bool ScriptApiSecurity::isSecure(lua_State *L)
425 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
426 bool secure = !lua_isnil(L, -1);
431 bool ScriptApiSecurity::safeLoadString(lua_State *L, const std::string &code, const char *chunk_name)
433 if (code.size() > 0 && code[0] == LUA_SIGNATURE[0]) {
434 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
437 if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name))
442 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name)
450 chunk_name = const_cast<char *>("=stdin");
452 fp = fopen(path, "rb");
454 lua_pushfstring(L, "%s: %s", path, strerror(errno));
457 size_t len = strlen(display_name) + 2;
458 chunk_name = new char[len];
459 snprintf(chunk_name, len, "@%s", display_name);
463 int c = std::getc(fp);
465 // Skip the first line
466 while ((c = std::getc(fp)) != EOF && c != '\n') {}
469 start = std::ftell(fp);
473 int ret = std::fseek(fp, 0, SEEK_END);
475 lua_pushfstring(L, "%s: %s", path, strerror(errno));
478 delete [] chunk_name;
483 size_t size = std::ftell(fp) - start;
484 std::string code(size, '\0');
485 ret = std::fseek(fp, start, SEEK_SET);
487 lua_pushfstring(L, "%s: %s", path, strerror(errno));
490 delete [] chunk_name;
495 size_t num_read = std::fread(&code[0], 1, size, fp);
498 if (num_read != size) {
499 lua_pushliteral(L, "Error reading file to load.");
501 delete [] chunk_name;
505 bool result = safeLoadString(L, code, chunk_name);
507 delete [] chunk_name;
512 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
513 bool write_required, bool *write_allowed)
516 *write_allowed = false;
518 std::string str; // Transient
520 std::string abs_path = fs::AbsolutePath(path);
522 if (!abs_path.empty()) {
523 // Don't allow accessing the settings file
524 str = fs::AbsolutePath(g_settings_path);
525 if (str == abs_path) return false;
528 // If we couldn't find the absolute path (path doesn't exist) then
529 // try removing the last components until it works (to allow
530 // non-existent files/folders for mkdir).
531 std::string cur_path = path;
533 while (abs_path.empty() && !cur_path.empty()) {
534 std::string component;
535 cur_path = fs::RemoveLastPathComponent(cur_path, &component);
536 if (component == "..") {
537 // Parent components can't be allowed or we could allow something like
538 // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
539 // If we have previous non-relative elements in the path we might be
540 // able to remove them so that things like worlds/foo/noexist/../auth.txt
541 // could be allowed, but those paths will be interpreted as nonexistent
542 // by the operating system anyways.
545 removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed);
546 abs_path = fs::AbsolutePath(cur_path);
548 if (abs_path.empty())
550 // Add the removed parts back so that you can't, eg, create a
551 // directory in worldmods if worldmods doesn't exist.
552 if (!removed.empty())
553 abs_path += DIR_DELIM + removed;
555 // Get gamedef from registry
556 ScriptApiBase *script = ModApiBase::getScriptApiBase(L);
557 const IGameDef *gamedef = script->getGameDef();
562 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
563 if (lua_isstring(L, -1)) {
564 std::string mod_name = readParam<std::string>(L, -1);
566 // Builtin can access anything
567 if (mod_name == BUILTIN_MOD_NAME) {
568 if (write_allowed) *write_allowed = true;
572 // Allow paths in mod path
573 // Don't bother if write access isn't important, since it will be handled later
574 if (write_required || write_allowed != NULL) {
575 const ModSpec *mod = gamedef->getModSpec(mod_name);
577 str = fs::AbsolutePath(mod->path);
578 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
579 if (write_allowed) *write_allowed = true;
585 lua_pop(L, 1); // Pop mod name
587 // Allow read-only access to all mod directories
588 if (!write_required) {
589 const std::vector<ModSpec> &mods = gamedef->getMods();
590 for (const ModSpec &mod : mods) {
591 str = fs::AbsolutePath(mod.path);
592 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
598 str = fs::AbsolutePath(gamedef->getWorldPath());
600 // Don't allow access to other paths in the world mod/game path.
601 // These have to be blocked so you can't override a trusted mod
602 // by creating a mod with the same name in a world mod directory.
603 // We add to the absolute path of the world instead of getting
604 // the absolute paths directly because that won't work if they
606 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
607 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
610 // Allow all other paths in world path
611 if (fs::PathStartsWith(abs_path, str)) {
612 if (write_allowed) *write_allowed = true;
617 // Default to disallowing
621 bool ScriptApiSecurity::checkWhitelisted(lua_State *L, const std::string &setting)
623 assert(str_starts_with(setting, "secure."));
625 // We have to make sure that this function is being called directly by
626 // a mod, otherwise a malicious mod could override this function and
627 // steal its return value.
630 // Make sure there's only one item below this function on the stack...
631 if (lua_getstack(L, 2, &info))
633 FATAL_ERROR_IF(!lua_getstack(L, 1, &info), "lua_getstack() failed");
634 FATAL_ERROR_IF(!lua_getinfo(L, "S", &info), "lua_getinfo() failed");
636 // ...and that that item is the main file scope.
637 if (strcmp(info.what, "main") != 0)
640 // Mod must be listed in secure.http_mods or secure.trusted_mods
641 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
642 if (!lua_isstring(L, -1))
644 std::string mod_name = readParam<std::string>(L, -1);
646 std::string value = g_settings->get(setting);
647 value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
648 auto mod_list = str_split(value, ',');
650 return CONTAINS(mod_list, mod_name);
654 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
656 int nret = sl_g_loadfile(L);
659 // code after this function isn't executed
661 int top_precall = lua_gettop(L);
662 lua_call(L, 0, LUA_MULTRET);
663 // Return number of arguments returned by the function,
664 // adjusting for the function being poped.
665 return lua_gettop(L) - (top_precall - 1);
669 int ScriptApiSecurity::sl_g_load(lua_State *L)
674 const char *chunk_name = "=(load)";
676 luaL_checktype(L, 1, LUA_TFUNCTION);
677 if (!lua_isnone(L, 2)) {
678 luaL_checktype(L, 2, LUA_TSTRING);
679 chunk_name = lua_tostring(L, 2);
685 int t = lua_type(L, -1);
690 if (t != LUA_TSTRING) {
692 lua_pushliteral(L, "Loader didn't return a string");
695 buf = lua_tolstring(L, -1, &len);
696 code += std::string(buf, len);
697 lua_pop(L, 1); // Pop return value
699 if (!safeLoadString(L, code, chunk_name)) {
708 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
711 ScriptApiBase *script = ModApiBase::getScriptApiBase(L);
713 // Client implementation
714 if (script->getType() == ScriptingType::Client) {
715 std::string path = readParam<std::string>(L, 1);
716 const std::string *contents = script->getClient()->getModFile(path);
718 std::string error_msg = "Coudln't find script called: " + path;
720 lua_pushstring(L, error_msg.c_str());
724 std::string chunk_name = "@" + path;
725 if (!safeLoadString(L, *contents, chunk_name.c_str())) {
734 // Server implementation
735 const char *path = NULL;
736 if (lua_isstring(L, 1)) {
737 path = lua_tostring(L, 1);
738 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
741 if (!safeLoadFile(L, path)) {
751 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
753 const char *chunk_name = "=(load)";
755 luaL_checktype(L, 1, LUA_TSTRING);
756 if (!lua_isnone(L, 2)) {
757 luaL_checktype(L, 2, LUA_TSTRING);
758 chunk_name = lua_tostring(L, 2);
762 const char *code = lua_tolstring(L, 1, &size);
763 std::string code_s(code, size);
765 if (!safeLoadString(L, code_s, chunk_name)) {
774 int ScriptApiSecurity::sl_g_require(lua_State *L)
776 lua_pushliteral(L, "require() is disabled when mod security is on.");
781 int ScriptApiSecurity::sl_io_open(lua_State *L)
783 bool with_mode = lua_gettop(L) > 1;
785 luaL_checktype(L, 1, LUA_TSTRING);
786 const char *path = lua_tostring(L, 1);
788 bool write_requested = false;
790 luaL_checktype(L, 2, LUA_TSTRING);
791 const char *mode = lua_tostring(L, 2);
792 write_requested = strchr(mode, 'w') != NULL ||
793 strchr(mode, '+') != NULL ||
794 strchr(mode, 'a') != NULL;
796 CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
798 push_original(L, "io", "open");
804 lua_call(L, with_mode ? 2 : 1, 2);
809 int ScriptApiSecurity::sl_io_input(lua_State *L)
811 if (lua_isstring(L, 1)) {
812 const char *path = lua_tostring(L, 1);
813 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
816 push_original(L, "io", "input");
823 int ScriptApiSecurity::sl_io_output(lua_State *L)
825 if (lua_isstring(L, 1)) {
826 const char *path = lua_tostring(L, 1);
827 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
830 push_original(L, "io", "output");
837 int ScriptApiSecurity::sl_io_lines(lua_State *L)
839 if (lua_isstring(L, 1)) {
840 const char *path = lua_tostring(L, 1);
841 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
844 int top_precall = lua_gettop(L);
845 push_original(L, "io", "lines");
847 lua_call(L, 1, LUA_MULTRET);
848 // Return number of arguments returned by the function,
849 // adjusting for the function being poped.
850 return lua_gettop(L) - top_precall;
854 int ScriptApiSecurity::sl_os_rename(lua_State *L)
856 luaL_checktype(L, 1, LUA_TSTRING);
857 const char *path1 = lua_tostring(L, 1);
858 CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
860 luaL_checktype(L, 2, LUA_TSTRING);
861 const char *path2 = lua_tostring(L, 2);
862 CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
864 push_original(L, "os", "rename");
872 int ScriptApiSecurity::sl_os_remove(lua_State *L)
874 luaL_checktype(L, 1, LUA_TSTRING);
875 const char *path = lua_tostring(L, 1);
876 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
878 push_original(L, "os", "remove");
885 int ScriptApiSecurity::sl_os_setlocale(lua_State *L)
887 const bool cat = lua_gettop(L) > 1;
888 // Don't allow changes
889 if (!lua_isnoneornil(L, 1)) {
894 push_original(L, "os", "setlocale");
898 lua_call(L, cat ? 2 : 1, 1);