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[] = {
99 static const char *os_whitelist[] = {
108 static const char *debug_whitelist[] = {
120 static const char *package_whitelist[] = {
127 static const char *jit_whitelist[] = {
141 lua_State *L = getStack();
143 // Backup globals to the registry
144 lua_getglobal(L, "_G");
145 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
147 // Replace the global environment with an empty one
148 int thread = getThread(L);
150 setLuaEnv(L, thread);
153 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
154 int old_globals = lua_gettop(L);
157 // Copy safe base functions
158 lua_getglobal(L, "_G");
159 copy_safe(L, whitelist, sizeof(whitelist));
161 // And replace unsafe ones
162 SECURE_API(g, dofile);
164 SECURE_API(g, loadfile);
165 SECURE_API(g, loadstring);
166 SECURE_API(g, require);
170 // Copy safe IO functions
171 lua_getfield(L, old_globals, "io");
173 copy_safe(L, io_whitelist, sizeof(io_whitelist));
175 // And replace unsafe ones
176 SECURE_API(io, open);
177 SECURE_API(io, input);
178 SECURE_API(io, output);
179 SECURE_API(io, lines);
181 lua_setglobal(L, "io");
182 lua_pop(L, 1); // Pop old IO
185 // Copy safe OS functions
186 lua_getfield(L, old_globals, "os");
188 copy_safe(L, os_whitelist, sizeof(os_whitelist));
190 // And replace unsafe ones
191 SECURE_API(os, remove);
192 SECURE_API(os, rename);
194 lua_setglobal(L, "os");
195 lua_pop(L, 1); // Pop old OS
198 // Copy safe debug functions
199 lua_getfield(L, old_globals, "debug");
201 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
202 lua_setglobal(L, "debug");
203 lua_pop(L, 1); // Pop old debug
206 // Copy safe package fields
207 lua_getfield(L, old_globals, "package");
209 copy_safe(L, package_whitelist, sizeof(package_whitelist));
210 lua_setglobal(L, "package");
211 lua_pop(L, 1); // Pop old package
214 // Copy safe jit functions, if they exist
215 lua_getfield(L, -1, "jit");
216 if (!lua_isnil(L, -1)) {
218 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
219 lua_setglobal(L, "jit");
221 lua_pop(L, 1); // Pop old jit
224 lua_pop(L, 1); // Pop globals_backup
227 void ScriptApiSecurity::initializeSecurityClient()
229 static const char *whitelist[] = {
246 // getmetatable can be used to escape the sandbox
254 // Completely safe libraries
260 static const char *os_whitelist[] = {
266 static const char *debug_whitelist[] = {
272 static const char *jit_whitelist[] = {
287 lua_State *L = getStack();
288 int thread = getThread(L);
290 // create an empty environment
293 // Copy safe base functions
294 lua_getglobal(L, "_G");
295 lua_getfield(L, -2, "_G");
296 copy_safe(L, whitelist, sizeof(whitelist));
298 // And replace unsafe ones
299 SECURE_API(g, dofile);
301 SECURE_API(g, loadfile);
302 SECURE_API(g, loadstring);
303 SECURE_API(g, require);
308 // Copy safe OS functions
309 lua_getglobal(L, "os");
311 copy_safe(L, os_whitelist, sizeof(os_whitelist));
312 lua_setfield(L, -3, "os");
313 lua_pop(L, 1); // Pop old OS
316 // Copy safe debug functions
317 lua_getglobal(L, "debug");
319 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
320 lua_setfield(L, -3, "debug");
321 lua_pop(L, 1); // Pop old debug
324 // Copy safe jit functions, if they exist
325 lua_getglobal(L, "jit");
327 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
328 lua_setfield(L, -3, "jit");
329 lua_pop(L, 1); // Pop old jit
332 // Set the environment to the one we created earlier
333 setLuaEnv(L, thread);
336 int ScriptApiSecurity::getThread(lua_State *L)
338 #if LUA_VERSION_NUM <= 501
339 int is_main = lua_pushthread(L); // Push the main thread
340 FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
341 "isn't the main Lua thread!");
342 return lua_gettop(L);
347 void ScriptApiSecurity::createEmptyEnv(lua_State *L)
349 lua_newtable(L); // Create new environment
350 lua_pushvalue(L, -1);
351 lua_setfield(L, -2, "_G"); // Create the _G loop
354 void ScriptApiSecurity::setLuaEnv(lua_State *L, int thread)
356 #if LUA_VERSION_NUM >= 502 // Lua >= 5.2
357 // Set the global environment
358 lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
360 // Set the environment of the main thread
361 FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set "
362 "environment of the main Lua thread!");
363 lua_pop(L, 1); // Pop thread
367 bool ScriptApiSecurity::isSecure(lua_State *L)
369 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
370 bool secure = !lua_isnil(L, -1);
375 bool ScriptApiSecurity::safeLoadString(lua_State *L, const std::string &code, const char *chunk_name)
377 if (code.size() > 0 && code[0] == LUA_SIGNATURE[0]) {
378 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
381 if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name))
386 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name)
394 chunk_name = const_cast<char *>("=stdin");
396 fp = fopen(path, "rb");
398 lua_pushfstring(L, "%s: %s", path, strerror(errno));
401 chunk_name = new char[strlen(display_name) + 2];
403 chunk_name[1] = '\0';
404 strcat(chunk_name, display_name);
408 int c = std::getc(fp);
410 // Skip the first line
411 while ((c = std::getc(fp)) != EOF && c != '\n') {}
414 start = std::ftell(fp);
418 int ret = std::fseek(fp, 0, SEEK_END);
420 lua_pushfstring(L, "%s: %s", path, strerror(errno));
423 delete [] chunk_name;
428 size_t size = std::ftell(fp) - start;
429 std::string code(size, '\0');
430 ret = std::fseek(fp, start, SEEK_SET);
432 lua_pushfstring(L, "%s: %s", path, strerror(errno));
435 delete [] chunk_name;
440 size_t num_read = std::fread(&code[0], 1, size, fp);
443 if (num_read != size) {
444 lua_pushliteral(L, "Error reading file to load.");
446 delete [] chunk_name;
450 bool result = safeLoadString(L, code, chunk_name);
452 delete [] chunk_name;
457 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
458 bool write_required, bool *write_allowed)
461 *write_allowed = false;
463 std::string str; // Transient
465 std::string abs_path = fs::AbsolutePath(path);
467 if (!abs_path.empty()) {
468 // Don't allow accessing the settings file
469 str = fs::AbsolutePath(g_settings_path);
470 if (str == abs_path) return false;
473 // If we couldn't find the absolute path (path doesn't exist) then
474 // try removing the last components until it works (to allow
475 // non-existent files/folders for mkdir).
476 std::string cur_path = path;
478 while (abs_path.empty() && !cur_path.empty()) {
479 std::string component;
480 cur_path = fs::RemoveLastPathComponent(cur_path, &component);
481 if (component == "..") {
482 // Parent components can't be allowed or we could allow something like
483 // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
484 // If we have previous non-relative elements in the path we might be
485 // able to remove them so that things like worlds/foo/noexist/../auth.txt
486 // could be allowed, but those paths will be interpreted as nonexistent
487 // by the operating system anyways.
490 removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed);
491 abs_path = fs::AbsolutePath(cur_path);
493 if (abs_path.empty())
495 // Add the removed parts back so that you can't, eg, create a
496 // directory in worldmods if worldmods doesn't exist.
497 if (!removed.empty())
498 abs_path += DIR_DELIM + removed;
500 // Get server from registry
501 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
502 ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
504 const IGameDef *gamedef = script->getGameDef();
509 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
510 if (lua_isstring(L, -1)) {
511 std::string mod_name = readParam<std::string>(L, -1);
513 // Builtin can access anything
514 if (mod_name == BUILTIN_MOD_NAME) {
515 if (write_allowed) *write_allowed = true;
519 // Allow paths in mod path
520 // Don't bother if write access isn't important, since it will be handled later
521 if (write_required || write_allowed != NULL) {
522 const ModSpec *mod = gamedef->getModSpec(mod_name);
524 str = fs::AbsolutePath(mod->path);
525 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
526 if (write_allowed) *write_allowed = true;
532 lua_pop(L, 1); // Pop mod name
534 // Allow read-only access to all mod directories
535 if (!write_required) {
536 const std::vector<ModSpec> &mods = gamedef->getMods();
537 for (const ModSpec &mod : mods) {
538 str = fs::AbsolutePath(mod.path);
539 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
545 str = fs::AbsolutePath(gamedef->getWorldPath());
547 // Don't allow access to other paths in the world mod/game path.
548 // These have to be blocked so you can't override a trusted mod
549 // by creating a mod with the same name in a world mod directory.
550 // We add to the absolute path of the world instead of getting
551 // the absolute paths directly because that won't work if they
553 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
554 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
557 // Allow all other paths in world path
558 if (fs::PathStartsWith(abs_path, str)) {
559 if (write_allowed) *write_allowed = true;
564 // Default to disallowing
569 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
571 int nret = sl_g_loadfile(L);
574 // code after this function isn't executed
576 int top_precall = lua_gettop(L);
577 lua_call(L, 0, LUA_MULTRET);
578 // Return number of arguments returned by the function,
579 // adjusting for the function being poped.
580 return lua_gettop(L) - (top_precall - 1);
584 int ScriptApiSecurity::sl_g_load(lua_State *L)
589 const char *chunk_name = "=(load)";
591 luaL_checktype(L, 1, LUA_TFUNCTION);
592 if (!lua_isnone(L, 2)) {
593 luaL_checktype(L, 2, LUA_TSTRING);
594 chunk_name = lua_tostring(L, 2);
600 int t = lua_type(L, -1);
605 if (t != LUA_TSTRING) {
607 lua_pushliteral(L, "Loader didn't return a string");
610 buf = lua_tolstring(L, -1, &len);
611 code += std::string(buf, len);
612 lua_pop(L, 1); // Pop return value
614 if (!safeLoadString(L, code, chunk_name)) {
623 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
626 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
627 ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
630 // Client implementation
631 if (script->getType() == ScriptingType::Client) {
632 std::string path = readParam<std::string>(L, 1);
633 const std::string *contents = script->getClient()->getModFile(path);
635 std::string error_msg = "Coudln't find script called: " + path;
637 lua_pushstring(L, error_msg.c_str());
641 std::string chunk_name = "@" + path;
642 if (!safeLoadString(L, *contents, chunk_name.c_str())) {
651 // Server implementation
652 const char *path = NULL;
653 if (lua_isstring(L, 1)) {
654 path = lua_tostring(L, 1);
655 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
658 if (!safeLoadFile(L, path)) {
668 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
670 const char *chunk_name = "=(load)";
672 luaL_checktype(L, 1, LUA_TSTRING);
673 if (!lua_isnone(L, 2)) {
674 luaL_checktype(L, 2, LUA_TSTRING);
675 chunk_name = lua_tostring(L, 2);
679 const char *code = lua_tolstring(L, 1, &size);
680 std::string code_s(code, size);
682 if (!safeLoadString(L, code_s, chunk_name)) {
691 int ScriptApiSecurity::sl_g_require(lua_State *L)
693 lua_pushliteral(L, "require() is disabled when mod security is on.");
698 int ScriptApiSecurity::sl_io_open(lua_State *L)
700 bool with_mode = lua_gettop(L) > 1;
702 luaL_checktype(L, 1, LUA_TSTRING);
703 const char *path = lua_tostring(L, 1);
705 bool write_requested = false;
707 luaL_checktype(L, 2, LUA_TSTRING);
708 const char *mode = lua_tostring(L, 2);
709 write_requested = strchr(mode, 'w') != NULL ||
710 strchr(mode, '+') != NULL ||
711 strchr(mode, 'a') != NULL;
713 CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
715 push_original(L, "io", "open");
721 lua_call(L, with_mode ? 2 : 1, 2);
726 int ScriptApiSecurity::sl_io_input(lua_State *L)
728 if (lua_isstring(L, 1)) {
729 const char *path = lua_tostring(L, 1);
730 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
733 push_original(L, "io", "input");
740 int ScriptApiSecurity::sl_io_output(lua_State *L)
742 if (lua_isstring(L, 1)) {
743 const char *path = lua_tostring(L, 1);
744 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
747 push_original(L, "io", "output");
754 int ScriptApiSecurity::sl_io_lines(lua_State *L)
756 if (lua_isstring(L, 1)) {
757 const char *path = lua_tostring(L, 1);
758 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
761 int top_precall = lua_gettop(L);
762 push_original(L, "io", "lines");
764 lua_call(L, 1, LUA_MULTRET);
765 // Return number of arguments returned by the function,
766 // adjusting for the function being poped.
767 return lua_gettop(L) - top_precall;
771 int ScriptApiSecurity::sl_os_rename(lua_State *L)
773 luaL_checktype(L, 1, LUA_TSTRING);
774 const char *path1 = lua_tostring(L, 1);
775 CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
777 luaL_checktype(L, 2, LUA_TSTRING);
778 const char *path2 = lua_tostring(L, 2);
779 CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
781 push_original(L, "os", "rename");
789 int ScriptApiSecurity::sl_os_remove(lua_State *L)
791 luaL_checktype(L, 1, LUA_TSTRING);
792 const char *path = lua_tostring(L, 1);
793 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
795 push_original(L, "os", "remove");