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"
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 // Pushes the original version of a library function on the stack, from the old version
49 static inline void push_original(lua_State *L, const char *lib, const char *func)
51 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
52 lua_getfield(L, -1, lib);
53 lua_remove(L, -2); // Remove globals_backup
54 lua_getfield(L, -1, func);
55 lua_remove(L, -2); // Remove lib
59 void ScriptApiSecurity::initializeSecurity()
61 static const char *whitelist[] = {
86 // Completely safe libraries
92 static const char *io_whitelist[] = {
100 static const char *os_whitelist[] = {
109 static const char *debug_whitelist[] = {
121 static const char *package_whitelist[] = {
128 static const char *jit_whitelist[] = {
142 lua_State *L = getStack();
144 // Backup globals to the registry
145 lua_getglobal(L, "_G");
146 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
148 // Replace the global environment with an empty one
149 int thread = getThread(L);
151 setLuaEnv(L, thread);
154 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
155 int old_globals = lua_gettop(L);
158 // Copy safe base functions
159 lua_getglobal(L, "_G");
160 copy_safe(L, whitelist, sizeof(whitelist));
162 // And replace unsafe ones
163 SECURE_API(g, dofile);
165 SECURE_API(g, loadfile);
166 SECURE_API(g, loadstring);
167 SECURE_API(g, require);
171 // Copy safe IO functions
172 lua_getfield(L, old_globals, "io");
174 copy_safe(L, io_whitelist, sizeof(io_whitelist));
176 // And replace unsafe ones
177 //SECURE_API(io, open);
178 SECURE_API(io, input);
179 SECURE_API(io, output);
180 SECURE_API(io, lines);
182 lua_setglobal(L, "io");
183 lua_pop(L, 1); // Pop old IO
186 // Copy safe OS functions
187 lua_getfield(L, old_globals, "os");
189 copy_safe(L, os_whitelist, sizeof(os_whitelist));
191 // And replace unsafe ones
192 SECURE_API(os, remove);
193 SECURE_API(os, rename);
195 lua_setglobal(L, "os");
196 lua_pop(L, 1); // Pop old OS
199 // Copy safe debug functions
200 lua_getfield(L, old_globals, "debug");
202 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
203 lua_setglobal(L, "debug");
204 lua_pop(L, 1); // Pop old debug
207 // Copy safe package fields
208 lua_getfield(L, old_globals, "package");
210 copy_safe(L, package_whitelist, sizeof(package_whitelist));
211 lua_setglobal(L, "package");
212 lua_pop(L, 1); // Pop old package
215 // Copy safe jit functions, if they exist
216 lua_getfield(L, -1, "jit");
217 if (!lua_isnil(L, -1)) {
219 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
220 lua_setglobal(L, "jit");
222 lua_pop(L, 1); // Pop old jit
225 lua_pop(L, 1); // Pop globals_backup
228 void ScriptApiSecurity::initializeSecurityClient()
230 static const char *whitelist[] = {
247 // getmetatable can be used to escape the sandbox
255 // Completely safe libraries
261 static const char *os_whitelist[] = {
267 static const char *debug_whitelist[] = {
272 static const char *jit_whitelist[] = {
287 lua_State *L = getStack();
288 int thread = getThread(L);
290 // Backup globals to the registry
291 lua_getglobal(L, "_G");
292 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
294 // create an empty environment
297 // Copy safe base functions
298 lua_getglobal(L, "_G");
299 lua_getfield(L, -2, "_G");
300 copy_safe(L, whitelist, sizeof(whitelist));
302 // And replace unsafe ones
303 SECURE_API(g, dofile);
305 SECURE_API(g, loadfile);
306 SECURE_API(g, loadstring);
307 SECURE_API(g, require);
310 // Copy safe OS functions
311 lua_getglobal(L, "os");
313 copy_safe(L, os_whitelist, sizeof(os_whitelist));
314 lua_setfield(L, -3, "os");
315 lua_pop(L, 1); // Pop old OS
318 // Copy safe debug functions
319 lua_getglobal(L, "debug");
321 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
322 lua_setfield(L, -3, "debug");
323 lua_pop(L, 1); // Pop old debug
327 // Copy safe jit functions, if they exist
328 lua_getglobal(L, "jit");
330 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
331 lua_setfield(L, -3, "jit");
332 lua_pop(L, 1); // Pop old jit
335 // Set the environment to the one we created earlier
336 setLuaEnv(L, thread);
339 int ScriptApiSecurity::getThread(lua_State *L)
341 #if LUA_VERSION_NUM <= 501
342 int is_main = lua_pushthread(L); // Push the main thread
343 FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
344 "isn't the main Lua thread!");
345 return lua_gettop(L);
350 void ScriptApiSecurity::createEmptyEnv(lua_State *L)
352 lua_newtable(L); // Create new environment
353 lua_pushvalue(L, -1);
354 lua_setfield(L, -2, "_G"); // Create the _G loop
357 void ScriptApiSecurity::setLuaEnv(lua_State *L, int thread)
359 #if LUA_VERSION_NUM >= 502 // Lua >= 5.2
360 // Set the global environment
361 lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
363 // Set the environment of the main thread
364 FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set "
365 "environment of the main Lua thread!");
366 lua_pop(L, 1); // Pop thread
370 bool ScriptApiSecurity::isSecure(lua_State *L)
372 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
373 bool secure = !lua_isnil(L, -1);
378 bool ScriptApiSecurity::safeLoadString(lua_State *L, const std::string &code, const char *chunk_name)
380 if (code.size() > 0 && code[0] == LUA_SIGNATURE[0]) {
381 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
384 if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name))
389 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name)
397 chunk_name = const_cast<char *>("=stdin");
399 fp = fopen(path, "rb");
401 lua_pushfstring(L, "%s: %s", path, strerror(errno));
404 size_t len = strlen(display_name) + 2;
405 chunk_name = new char[len];
406 snprintf(chunk_name, len, "@%s", display_name);
410 int c = std::getc(fp);
412 // Skip the first line
413 while ((c = std::getc(fp)) != EOF && c != '\n') {}
416 start = std::ftell(fp);
420 int ret = std::fseek(fp, 0, SEEK_END);
422 lua_pushfstring(L, "%s: %s", path, strerror(errno));
425 delete [] chunk_name;
430 size_t size = std::ftell(fp) - start;
431 std::string code(size, '\0');
432 ret = std::fseek(fp, start, SEEK_SET);
434 lua_pushfstring(L, "%s: %s", path, strerror(errno));
437 delete [] chunk_name;
442 size_t num_read = std::fread(&code[0], 1, size, fp);
445 if (num_read != size) {
446 lua_pushliteral(L, "Error reading file to load.");
448 delete [] chunk_name;
452 bool result = safeLoadString(L, code, chunk_name);
454 delete [] chunk_name;
459 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
460 bool write_required, bool *write_allowed)
463 *write_allowed = false;
465 std::string str; // Transient
467 std::string abs_path = fs::AbsolutePath(path);
469 if (!abs_path.empty()) {
470 // Don't allow accessing the settings file
471 str = fs::AbsolutePath(g_settings_path);
472 if (str == abs_path) return false;
475 // If we couldn't find the absolute path (path doesn't exist) then
476 // try removing the last components until it works (to allow
477 // non-existent files/folders for mkdir).
478 std::string cur_path = path;
480 while (abs_path.empty() && !cur_path.empty()) {
481 std::string component;
482 cur_path = fs::RemoveLastPathComponent(cur_path, &component);
483 if (component == "..") {
484 // Parent components can't be allowed or we could allow something like
485 // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
486 // If we have previous non-relative elements in the path we might be
487 // able to remove them so that things like worlds/foo/noexist/../auth.txt
488 // could be allowed, but those paths will be interpreted as nonexistent
489 // by the operating system anyways.
492 removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed);
493 abs_path = fs::AbsolutePath(cur_path);
495 if (abs_path.empty())
497 // Add the removed parts back so that you can't, eg, create a
498 // directory in worldmods if worldmods doesn't exist.
499 if (!removed.empty())
500 abs_path += DIR_DELIM + removed;
502 // Get server from registry
503 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
504 ScriptApiBase *script;
505 #if INDIRECT_SCRIPTAPI_RIDX
506 script = (ScriptApiBase *) *(void**)(lua_touserdata(L, -1));
508 script = (ScriptApiBase *) lua_touserdata(L, -1);
511 const IGameDef *gamedef = script->getGameDef();
516 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
517 if (lua_isstring(L, -1)) {
518 std::string mod_name = readParam<std::string>(L, -1);
520 // Builtin can access anything
521 if (mod_name == BUILTIN_MOD_NAME) {
522 if (write_allowed) *write_allowed = true;
526 // Allow paths in mod path
527 // Don't bother if write access isn't important, since it will be handled later
528 if (write_required || write_allowed != NULL) {
529 const ModSpec *mod = gamedef->getModSpec(mod_name);
531 str = fs::AbsolutePath(mod->path);
532 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
533 if (write_allowed) *write_allowed = true;
539 lua_pop(L, 1); // Pop mod name
541 // Allow read-only access to all mod directories
542 if (!write_required) {
543 const std::vector<ModSpec> &mods = gamedef->getMods();
544 for (const ModSpec &mod : mods) {
545 str = fs::AbsolutePath(mod.path);
546 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
552 str = fs::AbsolutePath(gamedef->getWorldPath());
554 // Don't allow access to other paths in the world mod/game path.
555 // These have to be blocked so you can't override a trusted mod
556 // by creating a mod with the same name in a world mod directory.
557 // We add to the absolute path of the world instead of getting
558 // the absolute paths directly because that won't work if they
560 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
561 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
564 // Allow all other paths in world path
565 if (fs::PathStartsWith(abs_path, str)) {
566 if (write_allowed) *write_allowed = true;
571 // Default to disallowing
576 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
578 int nret = sl_g_loadfile(L);
581 // code after this function isn't executed
583 int top_precall = lua_gettop(L);
584 lua_call(L, 0, LUA_MULTRET);
585 // Return number of arguments returned by the function,
586 // adjusting for the function being poped.
587 return lua_gettop(L) - (top_precall - 1);
591 int ScriptApiSecurity::sl_g_load(lua_State *L)
596 const char *chunk_name = "=(load)";
598 luaL_checktype(L, 1, LUA_TFUNCTION);
599 if (!lua_isnone(L, 2)) {
600 luaL_checktype(L, 2, LUA_TSTRING);
601 chunk_name = lua_tostring(L, 2);
607 int t = lua_type(L, -1);
612 if (t != LUA_TSTRING) {
614 lua_pushliteral(L, "Loader didn't return a string");
617 buf = lua_tolstring(L, -1, &len);
618 code += std::string(buf, len);
619 lua_pop(L, 1); // Pop return value
621 if (!safeLoadString(L, code, chunk_name)) {
630 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
633 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
634 #if INDIRECT_SCRIPTAPI_RIDX
635 ScriptApiBase *script = (ScriptApiBase *) *(void**)(lua_touserdata(L, -1));
637 ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
641 // Client implementation
642 if (script->getType() == ScriptingType::Client) {
643 std::string path = readParam<std::string>(L, 1);
644 const std::string *contents = script->getClient()->getModFile(path);
646 std::string error_msg = "Coudln't find script called: " + path;
648 lua_pushstring(L, error_msg.c_str());
652 std::string chunk_name = "@" + path;
653 if (!safeLoadString(L, *contents, chunk_name.c_str())) {
662 // Server implementation
663 const char *path = NULL;
664 if (lua_isstring(L, 1)) {
665 path = lua_tostring(L, 1);
666 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
669 if (!safeLoadFile(L, path)) {
679 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
681 const char *chunk_name = "=(load)";
683 luaL_checktype(L, 1, LUA_TSTRING);
684 if (!lua_isnone(L, 2)) {
685 luaL_checktype(L, 2, LUA_TSTRING);
686 chunk_name = lua_tostring(L, 2);
690 const char *code = lua_tolstring(L, 1, &size);
691 std::string code_s(code, size);
693 if (!safeLoadString(L, code_s, chunk_name)) {
702 int ScriptApiSecurity::sl_g_require(lua_State *L)
704 lua_pushliteral(L, "require() is disabled when mod security is on.");
709 int ScriptApiSecurity::sl_io_open(lua_State *L)
711 bool with_mode = lua_gettop(L) > 1;
713 luaL_checktype(L, 1, LUA_TSTRING);
714 const char *path = lua_tostring(L, 1);
716 bool write_requested = false;
718 luaL_checktype(L, 2, LUA_TSTRING);
719 const char *mode = lua_tostring(L, 2);
720 write_requested = strchr(mode, 'w') != NULL ||
721 strchr(mode, '+') != NULL ||
722 strchr(mode, 'a') != NULL;
724 CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
726 push_original(L, "io", "open");
732 lua_call(L, with_mode ? 2 : 1, 2);
737 int ScriptApiSecurity::sl_io_input(lua_State *L)
739 if (lua_isstring(L, 1)) {
740 const char *path = lua_tostring(L, 1);
741 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
744 push_original(L, "io", "input");
751 int ScriptApiSecurity::sl_io_output(lua_State *L)
753 if (lua_isstring(L, 1)) {
754 const char *path = lua_tostring(L, 1);
755 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
758 push_original(L, "io", "output");
765 int ScriptApiSecurity::sl_io_lines(lua_State *L)
767 if (lua_isstring(L, 1)) {
768 const char *path = lua_tostring(L, 1);
769 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
772 int top_precall = lua_gettop(L);
773 push_original(L, "io", "lines");
775 lua_call(L, 1, LUA_MULTRET);
776 // Return number of arguments returned by the function,
777 // adjusting for the function being poped.
778 return lua_gettop(L) - top_precall;
782 int ScriptApiSecurity::sl_os_rename(lua_State *L)
784 luaL_checktype(L, 1, LUA_TSTRING);
785 const char *path1 = lua_tostring(L, 1);
786 CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
788 luaL_checktype(L, 2, LUA_TSTRING);
789 const char *path2 = lua_tostring(L, 2);
790 CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
792 push_original(L, "os", "rename");
800 int ScriptApiSecurity::sl_os_remove(lua_State *L)
802 luaL_checktype(L, 1, LUA_TSTRING);
803 const char *path = lua_tostring(L, 1);
804 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
806 push_original(L, "os", "remove");