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"
33 #define SECURE_API(lib, name) \
34 lua_pushcfunction(L, sl_##lib##_##name); \
35 lua_setfield(L, -2, #name);
38 static inline void copy_safe(lua_State *L, const char *list[], unsigned len, int from=-2, int to=-1)
40 if (from < 0) from = lua_gettop(L) + from + 1;
41 if (to < 0) to = lua_gettop(L) + to + 1;
42 for (unsigned i = 0; i < (len / sizeof(list[0])); i++) {
43 lua_getfield(L, from, list[i]);
44 lua_setfield(L, to, list[i]);
48 static void shallow_copy_table(lua_State *L, int from=-2, int to=-1)
50 if (from < 0) from = lua_gettop(L) + from + 1;
51 if (to < 0) to = lua_gettop(L) + to + 1;
53 while (lua_next(L, from) != 0) {
54 assert(lua_type(L, -1) != LUA_TTABLE);
55 // duplicate key and value for lua_rawset
63 // Pushes the original version of a library function on the stack, from the old version
64 static inline void push_original(lua_State *L, const char *lib, const char *func)
66 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
67 lua_getfield(L, -1, lib);
68 lua_remove(L, -2); // Remove globals_backup
69 lua_getfield(L, -1, func);
70 lua_remove(L, -2); // Remove lib
74 void ScriptApiSecurity::initializeSecurity()
76 static const char *whitelist[] = {
102 static const char *whitelist_tables[] = {
103 // These libraries are completely safe BUT we need to duplicate their table
104 // to ensure the sandbox can't affect the insecure env
110 static const char *io_whitelist[] = {
118 static const char *os_whitelist[] = {
127 static const char *debug_whitelist[] = {
139 static const char *package_whitelist[] = {
146 static const char *jit_whitelist[] = {
160 lua_State *L = getStack();
162 // Backup globals to the registry
163 lua_getglobal(L, "_G");
164 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
166 // Replace the global environment with an empty one
167 int thread = getThread(L);
169 setLuaEnv(L, thread);
172 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
173 int old_globals = lua_gettop(L);
176 // Copy safe base functions
177 lua_getglobal(L, "_G");
178 copy_safe(L, whitelist, sizeof(whitelist));
180 // And replace unsafe ones
181 SECURE_API(g, dofile);
183 SECURE_API(g, loadfile);
184 SECURE_API(g, loadstring);
185 SECURE_API(g, require);
189 // Copy safe libraries
190 for (const char *libname : whitelist_tables) {
191 lua_getfield(L, old_globals, libname);
193 shallow_copy_table(L);
195 lua_setglobal(L, libname);
200 // Copy safe IO functions
201 lua_getfield(L, old_globals, "io");
203 copy_safe(L, io_whitelist, sizeof(io_whitelist));
205 // And replace unsafe ones
206 //SECURE_API(io, open);
207 SECURE_API(io, input);
208 SECURE_API(io, output);
209 SECURE_API(io, lines);
211 lua_setglobal(L, "io");
212 lua_pop(L, 1); // Pop old IO
215 // Copy safe OS functions
216 lua_getfield(L, old_globals, "os");
218 copy_safe(L, os_whitelist, sizeof(os_whitelist));
220 // And replace unsafe ones
221 SECURE_API(os, remove);
222 SECURE_API(os, rename);
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 lua_pop(L, 1); // Pop globals_backup
258 * In addition to copying the tables in whitelist_tables, we also need to
259 * replace the string metatable. Otherwise old_globals.string would
260 * be accessible via getmetatable("").__index from inside the sandbox.
262 lua_pushliteral(L, "");
264 lua_getglobal(L, "string");
265 lua_setfield(L, -2, "__index");
266 lua_setmetatable(L, -2);
267 lua_pop(L, 1); // Pop empty string
270 void ScriptApiSecurity::initializeSecurityClient()
272 static const char *whitelist[] = {
289 // getmetatable can be used to escape the sandbox
297 // Completely safe libraries
303 static const char *os_whitelist[] = {
309 static const char *debug_whitelist[] = {
314 static const char *jit_whitelist[] = {
329 lua_State *L = getStack();
330 int thread = getThread(L);
332 // Backup globals to the registry
333 lua_getglobal(L, "_G");
334 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
336 // create an empty environment
339 // Copy safe base functions
340 lua_getglobal(L, "_G");
341 lua_getfield(L, -2, "_G");
342 copy_safe(L, whitelist, sizeof(whitelist));
344 // And replace unsafe ones
345 SECURE_API(g, dofile);
347 SECURE_API(g, loadfile);
348 SECURE_API(g, loadstring);
349 SECURE_API(g, require);
352 // Copy safe OS functions
353 lua_getglobal(L, "os");
355 copy_safe(L, os_whitelist, sizeof(os_whitelist));
356 lua_setfield(L, -3, "os");
357 lua_pop(L, 1); // Pop old OS
360 // Copy safe debug functions
361 lua_getglobal(L, "debug");
363 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
364 lua_setfield(L, -3, "debug");
365 lua_pop(L, 1); // Pop old debug
369 // Copy safe jit functions, if they exist
370 lua_getglobal(L, "jit");
372 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
373 lua_setfield(L, -3, "jit");
374 lua_pop(L, 1); // Pop old jit
377 // Set the environment to the one we created earlier
378 setLuaEnv(L, thread);
381 int ScriptApiSecurity::getThread(lua_State *L)
383 #if LUA_VERSION_NUM <= 501
384 int is_main = lua_pushthread(L); // Push the main thread
385 FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
386 "isn't the main Lua thread!");
387 return lua_gettop(L);
392 void ScriptApiSecurity::createEmptyEnv(lua_State *L)
394 lua_newtable(L); // Create new environment
395 lua_pushvalue(L, -1);
396 lua_setfield(L, -2, "_G"); // Create the _G loop
399 void ScriptApiSecurity::setLuaEnv(lua_State *L, int thread)
401 #if LUA_VERSION_NUM >= 502 // Lua >= 5.2
402 // Set the global environment
403 lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
405 // Set the environment of the main thread
406 FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set "
407 "environment of the main Lua thread!");
408 lua_pop(L, 1); // Pop thread
412 bool ScriptApiSecurity::isSecure(lua_State *L)
414 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
415 bool secure = !lua_isnil(L, -1);
420 bool ScriptApiSecurity::safeLoadString(lua_State *L, const std::string &code, const char *chunk_name)
422 if (code.size() > 0 && code[0] == LUA_SIGNATURE[0]) {
423 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
426 if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name))
431 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name)
439 chunk_name = const_cast<char *>("=stdin");
441 fp = fopen(path, "rb");
443 lua_pushfstring(L, "%s: %s", path, strerror(errno));
446 size_t len = strlen(display_name) + 2;
447 chunk_name = new char[len];
448 snprintf(chunk_name, len, "@%s", display_name);
452 int c = std::getc(fp);
454 // Skip the first line
455 while ((c = std::getc(fp)) != EOF && c != '\n') {}
458 start = std::ftell(fp);
462 int ret = std::fseek(fp, 0, SEEK_END);
464 lua_pushfstring(L, "%s: %s", path, strerror(errno));
467 delete [] chunk_name;
472 size_t size = std::ftell(fp) - start;
473 std::string code(size, '\0');
474 ret = std::fseek(fp, start, SEEK_SET);
476 lua_pushfstring(L, "%s: %s", path, strerror(errno));
479 delete [] chunk_name;
484 size_t num_read = std::fread(&code[0], 1, size, fp);
487 if (num_read != size) {
488 lua_pushliteral(L, "Error reading file to load.");
490 delete [] chunk_name;
494 bool result = safeLoadString(L, code, chunk_name);
496 delete [] chunk_name;
501 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
502 bool write_required, bool *write_allowed)
505 *write_allowed = false;
507 std::string str; // Transient
509 std::string abs_path = fs::AbsolutePath(path);
511 if (!abs_path.empty()) {
512 // Don't allow accessing the settings file
513 str = fs::AbsolutePath(g_settings_path);
514 if (str == abs_path) return false;
517 // If we couldn't find the absolute path (path doesn't exist) then
518 // try removing the last components until it works (to allow
519 // non-existent files/folders for mkdir).
520 std::string cur_path = path;
522 while (abs_path.empty() && !cur_path.empty()) {
523 std::string component;
524 cur_path = fs::RemoveLastPathComponent(cur_path, &component);
525 if (component == "..") {
526 // Parent components can't be allowed or we could allow something like
527 // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
528 // If we have previous non-relative elements in the path we might be
529 // able to remove them so that things like worlds/foo/noexist/../auth.txt
530 // could be allowed, but those paths will be interpreted as nonexistent
531 // by the operating system anyways.
534 removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed);
535 abs_path = fs::AbsolutePath(cur_path);
537 if (abs_path.empty())
539 // Add the removed parts back so that you can't, eg, create a
540 // directory in worldmods if worldmods doesn't exist.
541 if (!removed.empty())
542 abs_path += DIR_DELIM + removed;
544 // Get gamedef from registry
545 ScriptApiBase *script = ModApiBase::getScriptApiBase(L);
546 const IGameDef *gamedef = script->getGameDef();
551 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
552 if (lua_isstring(L, -1)) {
553 std::string mod_name = readParam<std::string>(L, -1);
555 // Builtin can access anything
556 if (mod_name == BUILTIN_MOD_NAME) {
557 if (write_allowed) *write_allowed = true;
561 // Allow paths in mod path
562 // Don't bother if write access isn't important, since it will be handled later
563 if (write_required || write_allowed != NULL) {
564 const ModSpec *mod = gamedef->getModSpec(mod_name);
566 str = fs::AbsolutePath(mod->path);
567 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
568 if (write_allowed) *write_allowed = true;
574 lua_pop(L, 1); // Pop mod name
576 // Allow read-only access to all mod directories
577 if (!write_required) {
578 const std::vector<ModSpec> &mods = gamedef->getMods();
579 for (const ModSpec &mod : mods) {
580 str = fs::AbsolutePath(mod.path);
581 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
587 str = fs::AbsolutePath(gamedef->getWorldPath());
589 // Don't allow access to other paths in the world mod/game path.
590 // These have to be blocked so you can't override a trusted mod
591 // by creating a mod with the same name in a world mod directory.
592 // We add to the absolute path of the world instead of getting
593 // the absolute paths directly because that won't work if they
595 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
596 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
599 // Allow all other paths in world path
600 if (fs::PathStartsWith(abs_path, str)) {
601 if (write_allowed) *write_allowed = true;
606 // Default to disallowing
611 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
613 int nret = sl_g_loadfile(L);
616 // code after this function isn't executed
618 int top_precall = lua_gettop(L);
619 lua_call(L, 0, LUA_MULTRET);
620 // Return number of arguments returned by the function,
621 // adjusting for the function being poped.
622 return lua_gettop(L) - (top_precall - 1);
626 int ScriptApiSecurity::sl_g_load(lua_State *L)
631 const char *chunk_name = "=(load)";
633 luaL_checktype(L, 1, LUA_TFUNCTION);
634 if (!lua_isnone(L, 2)) {
635 luaL_checktype(L, 2, LUA_TSTRING);
636 chunk_name = lua_tostring(L, 2);
642 int t = lua_type(L, -1);
647 if (t != LUA_TSTRING) {
649 lua_pushliteral(L, "Loader didn't return a string");
652 buf = lua_tolstring(L, -1, &len);
653 code += std::string(buf, len);
654 lua_pop(L, 1); // Pop return value
656 if (!safeLoadString(L, code, chunk_name)) {
665 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
668 ScriptApiBase *script = ModApiBase::getScriptApiBase(L);
670 // Client implementation
671 if (script->getType() == ScriptingType::Client) {
672 std::string path = readParam<std::string>(L, 1);
673 const std::string *contents = script->getClient()->getModFile(path);
675 std::string error_msg = "Coudln't find script called: " + path;
677 lua_pushstring(L, error_msg.c_str());
681 std::string chunk_name = "@" + path;
682 if (!safeLoadString(L, *contents, chunk_name.c_str())) {
691 // Server implementation
692 const char *path = NULL;
693 if (lua_isstring(L, 1)) {
694 path = lua_tostring(L, 1);
695 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
698 if (!safeLoadFile(L, path)) {
708 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
710 const char *chunk_name = "=(load)";
712 luaL_checktype(L, 1, LUA_TSTRING);
713 if (!lua_isnone(L, 2)) {
714 luaL_checktype(L, 2, LUA_TSTRING);
715 chunk_name = lua_tostring(L, 2);
719 const char *code = lua_tolstring(L, 1, &size);
720 std::string code_s(code, size);
722 if (!safeLoadString(L, code_s, chunk_name)) {
731 int ScriptApiSecurity::sl_g_require(lua_State *L)
733 lua_pushliteral(L, "require() is disabled when mod security is on.");
738 int ScriptApiSecurity::sl_io_open(lua_State *L)
740 bool with_mode = lua_gettop(L) > 1;
742 luaL_checktype(L, 1, LUA_TSTRING);
743 const char *path = lua_tostring(L, 1);
745 bool write_requested = false;
747 luaL_checktype(L, 2, LUA_TSTRING);
748 const char *mode = lua_tostring(L, 2);
749 write_requested = strchr(mode, 'w') != NULL ||
750 strchr(mode, '+') != NULL ||
751 strchr(mode, 'a') != NULL;
753 CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
755 push_original(L, "io", "open");
761 lua_call(L, with_mode ? 2 : 1, 2);
766 int ScriptApiSecurity::sl_io_input(lua_State *L)
768 if (lua_isstring(L, 1)) {
769 const char *path = lua_tostring(L, 1);
770 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
773 push_original(L, "io", "input");
780 int ScriptApiSecurity::sl_io_output(lua_State *L)
782 if (lua_isstring(L, 1)) {
783 const char *path = lua_tostring(L, 1);
784 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
787 push_original(L, "io", "output");
794 int ScriptApiSecurity::sl_io_lines(lua_State *L)
796 if (lua_isstring(L, 1)) {
797 const char *path = lua_tostring(L, 1);
798 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
801 int top_precall = lua_gettop(L);
802 push_original(L, "io", "lines");
804 lua_call(L, 1, LUA_MULTRET);
805 // Return number of arguments returned by the function,
806 // adjusting for the function being poped.
807 return lua_gettop(L) - top_precall;
811 int ScriptApiSecurity::sl_os_rename(lua_State *L)
813 luaL_checktype(L, 1, LUA_TSTRING);
814 const char *path1 = lua_tostring(L, 1);
815 CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
817 luaL_checktype(L, 2, LUA_TSTRING);
818 const char *path2 = lua_tostring(L, 2);
819 CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
821 push_original(L, "os", "rename");
829 int ScriptApiSecurity::sl_os_remove(lua_State *L)
831 luaL_checktype(L, 1, LUA_TSTRING);
832 const char *path = lua_tostring(L, 1);
833 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
835 push_original(L, "os", "remove");