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"
32 #define SECURE_API(lib, name) \
33 lua_pushcfunction(L, sl_##lib##_##name); \
34 lua_setfield(L, -2, #name);
37 static inline void copy_safe(lua_State *L, const char *list[], unsigned len, int from=-2, int to=-1)
39 if (from < 0) from = lua_gettop(L) + from + 1;
40 if (to < 0) to = lua_gettop(L) + to + 1;
41 for (unsigned i = 0; i < (len / sizeof(list[0])); i++) {
42 lua_getfield(L, from, list[i]);
43 lua_setfield(L, to, list[i]);
47 // Pushes the original version of a library function on the stack, from the old version
48 static inline void push_original(lua_State *L, const char *lib, const char *func)
50 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
51 lua_getfield(L, -1, lib);
52 lua_remove(L, -2); // Remove globals_backup
53 lua_getfield(L, -1, func);
54 lua_remove(L, -2); // Remove lib
58 void ScriptApiSecurity::initializeSecurity()
60 static const char *whitelist[] = {
85 // Completely safe libraries
91 static const char *io_whitelist[] = {
98 static const char *os_whitelist[] = {
107 static const char *debug_whitelist[] = {
120 static const char *package_whitelist[] = {
127 static const char *jit_whitelist[] = {
141 lua_State *L = getStack();
144 int old_globals = backupGlobals(L);
147 // Copy safe base functions
148 lua_getglobal(L, "_G");
149 copy_safe(L, whitelist, sizeof(whitelist));
151 // And replace unsafe ones
152 SECURE_API(g, dofile);
154 SECURE_API(g, loadfile);
155 SECURE_API(g, loadstring);
156 SECURE_API(g, require);
160 // Copy safe IO functions
161 lua_getfield(L, old_globals, "io");
163 copy_safe(L, io_whitelist, sizeof(io_whitelist));
165 // And replace unsafe ones
166 SECURE_API(io, open);
167 SECURE_API(io, input);
168 SECURE_API(io, output);
169 SECURE_API(io, lines);
171 lua_setglobal(L, "io");
172 lua_pop(L, 1); // Pop old IO
175 // Copy safe OS functions
176 lua_getfield(L, old_globals, "os");
178 copy_safe(L, os_whitelist, sizeof(os_whitelist));
180 // And replace unsafe ones
181 SECURE_API(os, remove);
182 SECURE_API(os, rename);
184 lua_setglobal(L, "os");
185 lua_pop(L, 1); // Pop old OS
188 // Copy safe debug functions
189 lua_getfield(L, old_globals, "debug");
191 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
192 lua_setglobal(L, "debug");
193 lua_pop(L, 1); // Pop old debug
196 // Copy safe package fields
197 lua_getfield(L, old_globals, "package");
199 copy_safe(L, package_whitelist, sizeof(package_whitelist));
200 lua_setglobal(L, "package");
201 lua_pop(L, 1); // Pop old package
204 // Copy safe jit functions, if they exist
205 lua_getfield(L, -1, "jit");
206 if (!lua_isnil(L, -1)) {
208 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
209 lua_setglobal(L, "jit");
211 lua_pop(L, 1); // Pop old jit
214 lua_pop(L, 1); // Pop globals_backup
217 void ScriptApiSecurity::initializeSecurityClient()
219 static const char *whitelist[] = {
243 // Completely safe libraries
249 static const char *os_whitelist[] = {
256 static const char *debug_whitelist[] = {
261 static const char *jit_whitelist[] = {
276 lua_State *L = getStack();
279 int old_globals = backupGlobals(L);
282 // Copy safe base functions
283 lua_getglobal(L, "_G");
284 copy_safe(L, whitelist, sizeof(whitelist));
286 // And replace unsafe ones
287 SECURE_API(g, dofile);
288 SECURE_API(g, loadstring);
289 SECURE_API(g, require);
294 // Copy safe OS functions
295 lua_getfield(L, old_globals, "os");
297 copy_safe(L, os_whitelist, sizeof(os_whitelist));
298 lua_setglobal(L, "os");
299 lua_pop(L, 1); // Pop old OS
302 // Copy safe debug functions
303 lua_getfield(L, old_globals, "debug");
305 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
306 lua_setglobal(L, "debug");
307 lua_pop(L, 1); // Pop old debug
310 // Copy safe jit functions, if they exist
311 lua_getfield(L, -1, "jit");
312 if (!lua_isnil(L, -1)) {
314 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
315 lua_setglobal(L, "jit");
317 lua_pop(L, 1); // Pop old jit
320 lua_pop(L, 1); // Pop globals_backup
323 int ScriptApiSecurity::backupGlobals(lua_State *L)
325 // Backup globals to the registry
326 lua_getglobal(L, "_G");
327 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
329 // Replace the global environment with an empty one
330 #if LUA_VERSION_NUM <= 501
331 int is_main = lua_pushthread(L); // Push the main thread
332 FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
333 "isn't the main Lua thread!");
335 lua_newtable(L); // Create new environment
336 lua_pushvalue(L, -1);
337 lua_setfield(L, -2, "_G"); // Set _G of new environment
338 #if LUA_VERSION_NUM >= 502 // Lua >= 5.2
339 // Set the global environment
340 lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
342 // Set the environment of the main thread
343 FATAL_ERROR_IF(!lua_setfenv(L, -2), "Security: Unable to set "
344 "environment of the main Lua thread!");
345 lua_pop(L, 1); // Pop thread
349 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
350 return lua_gettop(L);
353 bool ScriptApiSecurity::isSecure(lua_State *L)
355 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
356 bool secure = !lua_isnil(L, -1);
362 #define CHECK_FILE_ERR(ret, fp) \
364 lua_pushfstring(L, "%s: %s", path, strerror(errno)); \
365 if (fp) std::fclose(fp); \
370 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path)
376 chunk_name = const_cast<char *>("=stdin");
378 fp = fopen(path, "rb");
380 lua_pushfstring(L, "%s: %s", path, strerror(errno));
383 chunk_name = new char[strlen(path) + 2];
385 chunk_name[1] = '\0';
386 strcat(chunk_name, path);
390 int c = std::getc(fp);
392 // Skip the first line
393 while ((c = std::getc(fp)) != EOF && c != '\n');
394 if (c == '\n') c = std::getc(fp);
395 start = std::ftell(fp);
398 if (c == LUA_SIGNATURE[0]) {
399 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
402 delete [] chunk_name;
408 int ret = std::fseek(fp, 0, SEEK_END);
410 lua_pushfstring(L, "%s: %s", path, strerror(errno));
413 delete [] chunk_name;
418 size_t size = std::ftell(fp) - start;
419 char *code = new char[size];
420 ret = std::fseek(fp, start, SEEK_SET);
422 lua_pushfstring(L, "%s: %s", path, strerror(errno));
426 delete [] chunk_name;
431 size_t num_read = std::fread(code, 1, size, fp);
435 if (num_read != size) {
436 lua_pushliteral(L, "Error reading file to load.");
439 delete [] chunk_name;
444 if (luaL_loadbuffer(L, code, size, chunk_name)) {
452 delete [] chunk_name;
458 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
459 bool write_required, bool *write_allowed)
462 *write_allowed = false;
464 std::string str; // Transient
466 std::string abs_path = fs::AbsolutePath(path);
468 if (!abs_path.empty()) {
469 // Don't allow accessing the settings file
470 str = fs::AbsolutePath(g_settings_path);
471 if (str == abs_path) return false;
474 // If we couldn't find the absolute path (path doesn't exist) then
475 // try removing the last components until it works (to allow
476 // non-existent files/folders for mkdir).
477 std::string cur_path = path;
479 while (abs_path.empty() && !cur_path.empty()) {
480 std::string component;
481 cur_path = fs::RemoveLastPathComponent(cur_path, &component);
482 if (component == "..") {
483 // Parent components can't be allowed or we could allow something like
484 // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
485 // If we have previous non-relative elements in the path we might be
486 // able to remove them so that things like worlds/foo/noexist/../auth.txt
487 // could be allowed, but those paths will be interpreted as nonexistent
488 // by the operating system anyways.
491 removed = component + (removed.empty() ? "" : DIR_DELIM + removed);
492 abs_path = fs::AbsolutePath(cur_path);
494 if (abs_path.empty())
496 // Add the removed parts back so that you can't, eg, create a
497 // directory in worldmods if worldmods doesn't exist.
498 if (!removed.empty())
499 abs_path += DIR_DELIM + removed;
501 // Get server from registry
502 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
503 ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
505 const IGameDef *gamedef = script->getGameDef();
510 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
511 if (lua_isstring(L, -1)) {
512 std::string mod_name = lua_tostring(L, -1);
514 // Builtin can access anything
515 if (mod_name == BUILTIN_MOD_NAME) {
516 if (write_allowed) *write_allowed = true;
520 // Allow paths in mod path
521 // Don't bother if write access isn't important, since it will be handled later
522 if (write_required || write_allowed != NULL) {
523 const ModSpec *mod = gamedef->getModSpec(mod_name);
525 str = fs::AbsolutePath(mod->path);
526 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
527 if (write_allowed) *write_allowed = true;
533 lua_pop(L, 1); // Pop mod name
535 // Allow read-only access to all mod directories
536 if (!write_required) {
537 const std::vector<ModSpec> mods = gamedef->getMods();
538 for (size_t i = 0; i < mods.size(); ++i) {
539 str = fs::AbsolutePath(mods[i].path);
540 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
546 str = fs::AbsolutePath(gamedef->getWorldPath());
548 // Don't allow access to other paths in the world mod/game path.
549 // These have to be blocked so you can't override a trusted mod
550 // by creating a mod with the same name in a world mod directory.
551 // We add to the absolute path of the world instead of getting
552 // the absolute paths directly because that won't work if they
554 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
555 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
558 // Allow all other paths in world path
559 if (fs::PathStartsWith(abs_path, str)) {
560 if (write_allowed) *write_allowed = true;
565 // Default to disallowing
570 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
572 int nret = sl_g_loadfile(L);
575 // code after this function isn't executed
577 int top_precall = lua_gettop(L);
578 lua_call(L, 0, LUA_MULTRET);
579 // Return number of arguments returned by the function,
580 // adjusting for the function being poped.
581 return lua_gettop(L) - (top_precall - 1);
585 int ScriptApiSecurity::sl_g_load(lua_State *L)
590 const char *chunk_name = "=(load)";
592 luaL_checktype(L, 1, LUA_TFUNCTION);
593 if (!lua_isnone(L, 2)) {
594 luaL_checktype(L, 2, LUA_TSTRING);
595 chunk_name = lua_tostring(L, 2);
601 int t = lua_type(L, -1);
604 } else if (t != LUA_TSTRING) {
606 lua_pushliteral(L, "Loader didn't return a string");
609 buf = lua_tolstring(L, -1, &len);
610 code += std::string(buf, len);
611 lua_pop(L, 1); // Pop return value
613 if (code[0] == LUA_SIGNATURE[0]) {
615 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
618 if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name)) {
620 lua_insert(L, lua_gettop(L) - 1);
627 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
629 const char *path = NULL;
631 if (lua_isstring(L, 1)) {
632 path = lua_tostring(L, 1);
633 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
636 if (!safeLoadFile(L, path)) {
646 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
648 const char *chunk_name = "=(load)";
650 luaL_checktype(L, 1, LUA_TSTRING);
651 if (!lua_isnone(L, 2)) {
652 luaL_checktype(L, 2, LUA_TSTRING);
653 chunk_name = lua_tostring(L, 2);
657 const char *code = lua_tolstring(L, 1, &size);
659 if (size > 0 && code[0] == LUA_SIGNATURE[0]) {
661 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
664 if (luaL_loadbuffer(L, code, size, chunk_name)) {
666 lua_insert(L, lua_gettop(L) - 1);
673 int ScriptApiSecurity::sl_g_require(lua_State *L)
675 lua_pushliteral(L, "require() is disabled when mod security is on.");
680 int ScriptApiSecurity::sl_io_open(lua_State *L)
682 bool with_mode = lua_gettop(L) > 1;
684 luaL_checktype(L, 1, LUA_TSTRING);
685 const char *path = lua_tostring(L, 1);
687 bool write_requested = false;
689 luaL_checktype(L, 2, LUA_TSTRING);
690 const char *mode = lua_tostring(L, 2);
691 write_requested = strchr(mode, 'w') != NULL ||
692 strchr(mode, '+') != NULL ||
693 strchr(mode, 'a') != NULL;
695 CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
697 push_original(L, "io", "open");
703 lua_call(L, with_mode ? 2 : 1, 2);
708 int ScriptApiSecurity::sl_io_input(lua_State *L)
710 if (lua_isstring(L, 1)) {
711 const char *path = lua_tostring(L, 1);
712 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
715 push_original(L, "io", "input");
722 int ScriptApiSecurity::sl_io_output(lua_State *L)
724 if (lua_isstring(L, 1)) {
725 const char *path = lua_tostring(L, 1);
726 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
729 push_original(L, "io", "output");
736 int ScriptApiSecurity::sl_io_lines(lua_State *L)
738 if (lua_isstring(L, 1)) {
739 const char *path = lua_tostring(L, 1);
740 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
743 int top_precall = lua_gettop(L);
744 push_original(L, "io", "lines");
746 lua_call(L, 1, LUA_MULTRET);
747 // Return number of arguments returned by the function,
748 // adjusting for the function being poped.
749 return lua_gettop(L) - top_precall;
753 int ScriptApiSecurity::sl_os_rename(lua_State *L)
755 luaL_checktype(L, 1, LUA_TSTRING);
756 const char *path1 = lua_tostring(L, 1);
757 CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
759 luaL_checktype(L, 2, LUA_TSTRING);
760 const char *path2 = lua_tostring(L, 2);
761 CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
763 push_original(L, "os", "rename");
771 int ScriptApiSecurity::sl_os_remove(lua_State *L)
773 luaL_checktype(L, 1, LUA_TSTRING);
774 const char *path = lua_tostring(L, 1);
775 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
777 push_original(L, "os", "remove");