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[] = {
253 // Completely safe libraries
259 static const char *os_whitelist[] = {
265 static const char *debug_whitelist[] = {
270 static const char *jit_whitelist[] = {
285 lua_State *L = getStack();
286 int thread = getThread(L);
288 // create an empty environment
291 // Copy safe base functions
292 lua_getglobal(L, "_G");
293 lua_getfield(L, -2, "_G");
294 copy_safe(L, whitelist, sizeof(whitelist));
296 // And replace unsafe ones
297 SECURE_API(g, dofile);
299 SECURE_API(g, loadfile);
300 SECURE_API(g, loadstring);
301 SECURE_API(g, require);
306 // Copy safe OS functions
307 lua_getglobal(L, "os");
309 copy_safe(L, os_whitelist, sizeof(os_whitelist));
310 lua_setfield(L, -3, "os");
311 lua_pop(L, 1); // Pop old OS
314 // Copy safe debug functions
315 lua_getglobal(L, "debug");
317 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
318 lua_setfield(L, -3, "debug");
319 lua_pop(L, 1); // Pop old debug
322 // Copy safe jit functions, if they exist
323 lua_getglobal(L, "jit");
325 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
326 lua_setfield(L, -3, "jit");
327 lua_pop(L, 1); // Pop old jit
330 // Set the environment to the one we created earlier
331 setLuaEnv(L, thread);
334 int ScriptApiSecurity::getThread(lua_State *L)
336 #if LUA_VERSION_NUM <= 501
337 int is_main = lua_pushthread(L); // Push the main thread
338 FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
339 "isn't the main Lua thread!");
340 return lua_gettop(L);
345 void ScriptApiSecurity::createEmptyEnv(lua_State *L)
347 lua_newtable(L); // Create new environment
348 lua_pushvalue(L, -1);
349 lua_setfield(L, -2, "_G"); // Create the _G loop
352 void ScriptApiSecurity::setLuaEnv(lua_State *L, int thread)
354 #if LUA_VERSION_NUM >= 502 // Lua >= 5.2
355 // Set the global environment
356 lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
358 // Set the environment of the main thread
359 FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set "
360 "environment of the main Lua thread!");
361 lua_pop(L, 1); // Pop thread
365 bool ScriptApiSecurity::isSecure(lua_State *L)
367 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
368 bool secure = !lua_isnil(L, -1);
374 #define CHECK_FILE_ERR(ret, fp) \
376 lua_pushfstring(L, "%s: %s", path, strerror(errno)); \
377 if (fp) std::fclose(fp); \
382 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name)
390 chunk_name = const_cast<char *>("=stdin");
392 fp = fopen(path, "rb");
394 lua_pushfstring(L, "%s: %s", path, strerror(errno));
397 chunk_name = new char[strlen(display_name) + 2];
399 chunk_name[1] = '\0';
400 strcat(chunk_name, display_name);
404 int c = std::getc(fp);
406 // Skip the first line
407 while ((c = std::getc(fp)) != EOF && c != '\n');
408 if (c == '\n') c = std::getc(fp);
409 start = std::ftell(fp);
412 if (c == LUA_SIGNATURE[0]) {
413 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
416 delete [] chunk_name;
422 int ret = std::fseek(fp, 0, SEEK_END);
424 lua_pushfstring(L, "%s: %s", path, strerror(errno));
427 delete [] chunk_name;
432 size_t size = std::ftell(fp) - start;
433 char *code = new char[size];
434 ret = std::fseek(fp, start, SEEK_SET);
436 lua_pushfstring(L, "%s: %s", path, strerror(errno));
440 delete [] chunk_name;
445 size_t num_read = std::fread(code, 1, size, fp);
449 if (num_read != size) {
450 lua_pushliteral(L, "Error reading file to load.");
453 delete [] chunk_name;
458 if (luaL_loadbuffer(L, code, size, chunk_name)) {
466 delete [] chunk_name;
472 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
473 bool write_required, bool *write_allowed)
476 *write_allowed = false;
478 std::string str; // Transient
480 std::string abs_path = fs::AbsolutePath(path);
482 if (!abs_path.empty()) {
483 // Don't allow accessing the settings file
484 str = fs::AbsolutePath(g_settings_path);
485 if (str == abs_path) return false;
488 // If we couldn't find the absolute path (path doesn't exist) then
489 // try removing the last components until it works (to allow
490 // non-existent files/folders for mkdir).
491 std::string cur_path = path;
493 while (abs_path.empty() && !cur_path.empty()) {
494 std::string component;
495 cur_path = fs::RemoveLastPathComponent(cur_path, &component);
496 if (component == "..") {
497 // Parent components can't be allowed or we could allow something like
498 // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
499 // If we have previous non-relative elements in the path we might be
500 // able to remove them so that things like worlds/foo/noexist/../auth.txt
501 // could be allowed, but those paths will be interpreted as nonexistent
502 // by the operating system anyways.
505 removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed);
506 abs_path = fs::AbsolutePath(cur_path);
508 if (abs_path.empty())
510 // Add the removed parts back so that you can't, eg, create a
511 // directory in worldmods if worldmods doesn't exist.
512 if (!removed.empty())
513 abs_path += DIR_DELIM + removed;
515 // Get server from registry
516 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
517 ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
519 const IGameDef *gamedef = script->getGameDef();
524 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
525 if (lua_isstring(L, -1)) {
526 std::string mod_name = readParam<std::string>(L, -1);
528 // Builtin can access anything
529 if (mod_name == BUILTIN_MOD_NAME) {
530 if (write_allowed) *write_allowed = true;
534 // Allow paths in mod path
535 // Don't bother if write access isn't important, since it will be handled later
536 if (write_required || write_allowed != NULL) {
537 const ModSpec *mod = gamedef->getModSpec(mod_name);
539 str = fs::AbsolutePath(mod->path);
540 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
541 if (write_allowed) *write_allowed = true;
547 lua_pop(L, 1); // Pop mod name
549 // Allow read-only access to all mod directories
550 if (!write_required) {
551 const std::vector<ModSpec> &mods = gamedef->getMods();
552 for (const ModSpec &mod : mods) {
553 str = fs::AbsolutePath(mod.path);
554 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
560 str = fs::AbsolutePath(gamedef->getWorldPath());
562 // Don't allow access to other paths in the world mod/game path.
563 // These have to be blocked so you can't override a trusted mod
564 // by creating a mod with the same name in a world mod directory.
565 // We add to the absolute path of the world instead of getting
566 // the absolute paths directly because that won't work if they
568 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
569 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
572 // Allow all other paths in world path
573 if (fs::PathStartsWith(abs_path, str)) {
574 if (write_allowed) *write_allowed = true;
579 // Default to disallowing
584 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
586 int nret = sl_g_loadfile(L);
589 // code after this function isn't executed
591 int top_precall = lua_gettop(L);
592 lua_call(L, 0, LUA_MULTRET);
593 // Return number of arguments returned by the function,
594 // adjusting for the function being poped.
595 return lua_gettop(L) - (top_precall - 1);
599 int ScriptApiSecurity::sl_g_load(lua_State *L)
604 const char *chunk_name = "=(load)";
606 luaL_checktype(L, 1, LUA_TFUNCTION);
607 if (!lua_isnone(L, 2)) {
608 luaL_checktype(L, 2, LUA_TSTRING);
609 chunk_name = lua_tostring(L, 2);
615 int t = lua_type(L, -1);
620 if (t != LUA_TSTRING) {
622 lua_pushliteral(L, "Loader didn't return a string");
625 buf = lua_tolstring(L, -1, &len);
626 code += std::string(buf, len);
627 lua_pop(L, 1); // Pop return value
629 if (code[0] == LUA_SIGNATURE[0]) {
631 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
634 if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name)) {
636 lua_insert(L, lua_gettop(L) - 1);
643 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
646 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
647 ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
650 if (script->getType() == ScriptingType::Client) {
651 std::string display_path = readParam<std::string>(L, 1);
652 const std::string *path = script->getClient()->getModFile(display_path);
654 std::string error_msg = "Coudln't find script called:" + display_path;
656 lua_pushstring(L, error_msg.c_str());
659 if (!safeLoadFile(L, path->c_str(), display_path.c_str())) {
667 const char *path = NULL;
668 if (lua_isstring(L, 1)) {
669 path = lua_tostring(L, 1);
670 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
673 if (!safeLoadFile(L, path)) {
683 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
685 const char *chunk_name = "=(load)";
687 luaL_checktype(L, 1, LUA_TSTRING);
688 if (!lua_isnone(L, 2)) {
689 luaL_checktype(L, 2, LUA_TSTRING);
690 chunk_name = lua_tostring(L, 2);
694 const char *code = lua_tolstring(L, 1, &size);
696 if (size > 0 && code[0] == LUA_SIGNATURE[0]) {
698 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
701 if (luaL_loadbuffer(L, code, size, chunk_name)) {
703 lua_insert(L, lua_gettop(L) - 1);
710 int ScriptApiSecurity::sl_g_require(lua_State *L)
712 lua_pushliteral(L, "require() is disabled when mod security is on.");
717 int ScriptApiSecurity::sl_io_open(lua_State *L)
719 bool with_mode = lua_gettop(L) > 1;
721 luaL_checktype(L, 1, LUA_TSTRING);
722 const char *path = lua_tostring(L, 1);
724 bool write_requested = false;
726 luaL_checktype(L, 2, LUA_TSTRING);
727 const char *mode = lua_tostring(L, 2);
728 write_requested = strchr(mode, 'w') != NULL ||
729 strchr(mode, '+') != NULL ||
730 strchr(mode, 'a') != NULL;
732 CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
734 push_original(L, "io", "open");
740 lua_call(L, with_mode ? 2 : 1, 2);
745 int ScriptApiSecurity::sl_io_input(lua_State *L)
747 if (lua_isstring(L, 1)) {
748 const char *path = lua_tostring(L, 1);
749 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
752 push_original(L, "io", "input");
759 int ScriptApiSecurity::sl_io_output(lua_State *L)
761 if (lua_isstring(L, 1)) {
762 const char *path = lua_tostring(L, 1);
763 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
766 push_original(L, "io", "output");
773 int ScriptApiSecurity::sl_io_lines(lua_State *L)
775 if (lua_isstring(L, 1)) {
776 const char *path = lua_tostring(L, 1);
777 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
780 int top_precall = lua_gettop(L);
781 push_original(L, "io", "lines");
783 lua_call(L, 1, LUA_MULTRET);
784 // Return number of arguments returned by the function,
785 // adjusting for the function being poped.
786 return lua_gettop(L) - top_precall;
790 int ScriptApiSecurity::sl_os_rename(lua_State *L)
792 luaL_checktype(L, 1, LUA_TSTRING);
793 const char *path1 = lua_tostring(L, 1);
794 CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
796 luaL_checktype(L, 2, LUA_TSTRING);
797 const char *path2 = lua_tostring(L, 2);
798 CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
800 push_original(L, "os", "rename");
808 int ScriptApiSecurity::sl_os_remove(lua_State *L)
810 luaL_checktype(L, 1, LUA_TSTRING);
811 const char *path = lua_tostring(L, 1);
812 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
814 push_original(L, "os", "remove");