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[] = {
126 static const char *jit_whitelist[] = {
140 lua_State *L = getStack();
143 int old_globals = backupGlobals(L);
146 // Copy safe base functions
147 lua_getglobal(L, "_G");
148 copy_safe(L, whitelist, sizeof(whitelist));
150 // And replace unsafe ones
151 SECURE_API(g, dofile);
153 SECURE_API(g, loadfile);
154 SECURE_API(g, loadstring);
155 SECURE_API(g, require);
159 // Copy safe IO functions
160 lua_getfield(L, old_globals, "io");
162 copy_safe(L, io_whitelist, sizeof(io_whitelist));
164 // And replace unsafe ones
165 SECURE_API(io, open);
166 SECURE_API(io, input);
167 SECURE_API(io, output);
168 SECURE_API(io, lines);
170 lua_setglobal(L, "io");
171 lua_pop(L, 1); // Pop old IO
174 // Copy safe OS functions
175 lua_getfield(L, old_globals, "os");
177 copy_safe(L, os_whitelist, sizeof(os_whitelist));
179 // And replace unsafe ones
180 SECURE_API(os, remove);
181 SECURE_API(os, rename);
183 lua_setglobal(L, "os");
184 lua_pop(L, 1); // Pop old OS
187 // Copy safe debug functions
188 lua_getfield(L, old_globals, "debug");
190 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
191 lua_setglobal(L, "debug");
192 lua_pop(L, 1); // Pop old debug
195 // Copy safe package fields
196 lua_getfield(L, old_globals, "package");
198 copy_safe(L, package_whitelist, sizeof(package_whitelist));
199 lua_setglobal(L, "package");
200 lua_pop(L, 1); // Pop old package
203 // Copy safe jit functions, if they exist
204 lua_getfield(L, -1, "jit");
205 if (!lua_isnil(L, -1)) {
207 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
208 lua_setglobal(L, "jit");
210 lua_pop(L, 1); // Pop old jit
213 lua_pop(L, 1); // Pop globals_backup
216 void ScriptApiSecurity::initializeSecurityClient()
218 static const char *whitelist[] = {
242 // Completely safe libraries
248 static const char *io_whitelist[] = {
255 static const char *os_whitelist[] = {
262 static const char *debug_whitelist[] = {
266 static const char *jit_whitelist[] = {
280 lua_State *L = getStack();
283 int old_globals = backupGlobals(L);
286 // Copy safe base functions
287 lua_getglobal(L, "_G");
288 copy_safe(L, whitelist, sizeof(whitelist));
290 // And replace unsafe ones
291 SECURE_API(g, dofile);
292 SECURE_API(g, loadstring);
293 SECURE_API(g, require);
297 // Copy safe IO functions
298 lua_getfield(L, old_globals, "io");
300 copy_safe(L, io_whitelist, sizeof(io_whitelist));
302 // And replace unsafe ones
303 SECURE_API(io, open);
304 SECURE_API(io, input);
305 SECURE_API(io, output);
306 SECURE_API(io, lines);
308 lua_setglobal(L, "io");
309 lua_pop(L, 1); // Pop old IO
312 // Copy safe OS functions
313 lua_getfield(L, old_globals, "os");
315 copy_safe(L, os_whitelist, sizeof(os_whitelist));
316 lua_setglobal(L, "os");
317 lua_pop(L, 1); // Pop old OS
320 // Copy safe debug functions
321 lua_getfield(L, old_globals, "debug");
323 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
324 lua_setglobal(L, "debug");
325 lua_pop(L, 1); // Pop old debug
327 // Remove all of package
329 lua_setglobal(L, "package");
332 // Copy safe jit functions, if they exist
333 lua_getfield(L, -1, "jit");
334 if (!lua_isnil(L, -1)) {
336 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
337 lua_setglobal(L, "jit");
339 lua_pop(L, 1); // Pop old jit
342 lua_pop(L, 1); // Pop globals_backup
345 int ScriptApiSecurity::backupGlobals(lua_State *L)
347 // Backup globals to the registry
348 lua_getglobal(L, "_G");
349 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
351 // Replace the global environment with an empty one
352 #if LUA_VERSION_NUM <= 501
353 int is_main = lua_pushthread(L); // Push the main thread
354 FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
355 "isn't the main Lua thread!");
357 lua_newtable(L); // Create new environment
358 lua_pushvalue(L, -1);
359 lua_setfield(L, -2, "_G"); // Set _G of new environment
360 #if LUA_VERSION_NUM >= 502 // Lua >= 5.2
361 // Set the global environment
362 lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
364 // Set the environment of the main thread
365 FATAL_ERROR_IF(!lua_setfenv(L, -2), "Security: Unable to set "
366 "environment of the main Lua thread!");
367 lua_pop(L, 1); // Pop thread
371 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
372 return lua_gettop(L);
375 bool ScriptApiSecurity::isSecure(lua_State *L)
377 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
378 bool secure = !lua_isnil(L, -1);
384 #define CHECK_FILE_ERR(ret, fp) \
386 lua_pushfstring(L, "%s: %s", path, strerror(errno)); \
387 if (fp) std::fclose(fp); \
392 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path)
398 chunk_name = const_cast<char *>("=stdin");
400 fp = fopen(path, "rb");
402 lua_pushfstring(L, "%s: %s", path, strerror(errno));
405 chunk_name = new char[strlen(path) + 2];
407 chunk_name[1] = '\0';
408 strcat(chunk_name, path);
412 int c = std::getc(fp);
414 // Skip the first line
415 while ((c = std::getc(fp)) != EOF && c != '\n');
416 if (c == '\n') c = std::getc(fp);
417 start = std::ftell(fp);
420 if (c == LUA_SIGNATURE[0]) {
421 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
424 delete [] chunk_name;
430 int ret = std::fseek(fp, 0, SEEK_END);
431 CHECK_FILE_ERR(ret, fp);
433 size_t size = std::ftell(fp) - start;
434 char *code = new char[size];
435 ret = std::fseek(fp, start, SEEK_SET);
437 lua_pushfstring(L, "%s: %s", path, strerror(errno));
441 delete [] chunk_name;
446 size_t num_read = std::fread(code, 1, size, fp);
450 if (num_read != size) {
451 lua_pushliteral(L, "Error reading file to load.");
454 delete [] chunk_name;
459 if (luaL_loadbuffer(L, code, size, chunk_name)) {
467 delete [] chunk_name;
473 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
474 bool write_required, bool *write_allowed)
477 *write_allowed = false;
479 std::string str; // Transient
481 std::string abs_path = fs::AbsolutePath(path);
483 if (!abs_path.empty()) {
484 // Don't allow accessing the settings file
485 str = fs::AbsolutePath(g_settings_path);
486 if (str == abs_path) return false;
489 // If we couldn't find the absolute path (path doesn't exist) then
490 // try removing the last components until it works (to allow
491 // non-existent files/folders for mkdir).
492 std::string cur_path = path;
494 while (abs_path.empty() && !cur_path.empty()) {
495 std::string component;
496 cur_path = fs::RemoveLastPathComponent(cur_path, &component);
497 if (component == "..") {
498 // Parent components can't be allowed or we could allow something like
499 // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
500 // If we have previous non-relative elements in the path we might be
501 // able to remove them so that things like worlds/foo/noexist/../auth.txt
502 // could be allowed, but those paths will be interpreted as nonexistent
503 // by the operating system anyways.
506 removed = component + (removed.empty() ? "" : DIR_DELIM + removed);
507 abs_path = fs::AbsolutePath(cur_path);
509 if (abs_path.empty())
511 // Add the removed parts back so that you can't, eg, create a
512 // directory in worldmods if worldmods doesn't exist.
513 if (!removed.empty())
514 abs_path += DIR_DELIM + removed;
516 // Get server from registry
517 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
518 ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
520 const IGameDef *gamedef = script->getGameDef();
525 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
526 if (lua_isstring(L, -1)) {
527 std::string mod_name = lua_tostring(L, -1);
529 // Builtin can access anything
530 if (mod_name == BUILTIN_MOD_NAME) {
531 if (write_allowed) *write_allowed = true;
535 // Allow paths in mod path
536 // Don't bother if write access isn't important, since it will be handled later
537 if (write_required || write_allowed != NULL) {
538 const ModSpec *mod = gamedef->getModSpec(mod_name);
540 str = fs::AbsolutePath(mod->path);
541 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
542 if (write_allowed) *write_allowed = true;
548 lua_pop(L, 1); // Pop mod name
550 // Allow read-only access to all mod directories
551 if (!write_required) {
552 const std::vector<ModSpec> mods = gamedef->getMods();
553 for (size_t i = 0; i < mods.size(); ++i) {
554 str = fs::AbsolutePath(mods[i].path);
555 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
561 str = fs::AbsolutePath(gamedef->getWorldPath());
563 // Don't allow access to other paths in the world mod/game path.
564 // These have to be blocked so you can't override a trusted mod
565 // by creating a mod with the same name in a world mod directory.
566 // We add to the absolute path of the world instead of getting
567 // the absolute paths directly because that won't work if they
569 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
570 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
573 // Allow all other paths in world path
574 if (fs::PathStartsWith(abs_path, str)) {
575 if (write_allowed) *write_allowed = true;
580 // Default to disallowing
585 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
587 int nret = sl_g_loadfile(L);
590 // code after this function isn't executed
592 int top_precall = lua_gettop(L);
593 lua_call(L, 0, LUA_MULTRET);
594 // Return number of arguments returned by the function,
595 // adjusting for the function being poped.
596 return lua_gettop(L) - (top_precall - 1);
600 int ScriptApiSecurity::sl_g_load(lua_State *L)
605 const char *chunk_name = "=(load)";
607 luaL_checktype(L, 1, LUA_TFUNCTION);
608 if (!lua_isnone(L, 2)) {
609 luaL_checktype(L, 2, LUA_TSTRING);
610 chunk_name = lua_tostring(L, 2);
616 int t = lua_type(L, -1);
619 } else if (t != LUA_TSTRING) {
621 lua_pushliteral(L, "Loader didn't return a string");
624 buf = lua_tolstring(L, -1, &len);
625 code += std::string(buf, len);
626 lua_pop(L, 1); // Pop return value
628 if (code[0] == LUA_SIGNATURE[0]) {
630 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
633 if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name)) {
635 lua_insert(L, lua_gettop(L) - 1);
642 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
644 const char *path = NULL;
646 if (lua_isstring(L, 1)) {
647 path = lua_tostring(L, 1);
648 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
651 if (!safeLoadFile(L, path)) {
661 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
663 const char *chunk_name = "=(load)";
665 luaL_checktype(L, 1, LUA_TSTRING);
666 if (!lua_isnone(L, 2)) {
667 luaL_checktype(L, 2, LUA_TSTRING);
668 chunk_name = lua_tostring(L, 2);
672 const char *code = lua_tolstring(L, 1, &size);
674 if (size > 0 && code[0] == LUA_SIGNATURE[0]) {
676 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
679 if (luaL_loadbuffer(L, code, size, chunk_name)) {
681 lua_insert(L, lua_gettop(L) - 1);
688 int ScriptApiSecurity::sl_g_require(lua_State *L)
690 lua_pushliteral(L, "require() is disabled when mod security is on.");
695 int ScriptApiSecurity::sl_io_open(lua_State *L)
697 bool with_mode = lua_gettop(L) > 1;
699 luaL_checktype(L, 1, LUA_TSTRING);
700 const char *path = lua_tostring(L, 1);
702 bool write_requested = false;
704 luaL_checktype(L, 2, LUA_TSTRING);
705 const char *mode = lua_tostring(L, 2);
706 write_requested = strchr(mode, 'w') != NULL ||
707 strchr(mode, '+') != NULL ||
708 strchr(mode, 'a') != NULL;
710 CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
712 push_original(L, "io", "open");
718 lua_call(L, with_mode ? 2 : 1, 2);
723 int ScriptApiSecurity::sl_io_input(lua_State *L)
725 if (lua_isstring(L, 1)) {
726 const char *path = lua_tostring(L, 1);
727 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
730 push_original(L, "io", "input");
737 int ScriptApiSecurity::sl_io_output(lua_State *L)
739 if (lua_isstring(L, 1)) {
740 const char *path = lua_tostring(L, 1);
741 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
744 push_original(L, "io", "output");
751 int ScriptApiSecurity::sl_io_lines(lua_State *L)
753 if (lua_isstring(L, 1)) {
754 const char *path = lua_tostring(L, 1);
755 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
758 int top_precall = lua_gettop(L);
759 push_original(L, "io", "lines");
761 lua_call(L, 1, LUA_MULTRET);
762 // Return number of arguments returned by the function,
763 // adjusting for the function being poped.
764 return lua_gettop(L) - top_precall;
768 int ScriptApiSecurity::sl_os_rename(lua_State *L)
770 luaL_checktype(L, 1, LUA_TSTRING);
771 const char *path1 = lua_tostring(L, 1);
772 CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
774 luaL_checktype(L, 2, LUA_TSTRING);
775 const char *path2 = lua_tostring(L, 2);
776 CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
778 push_original(L, "os", "rename");
786 int ScriptApiSecurity::sl_os_remove(lua_State *L)
788 luaL_checktype(L, 1, LUA_TSTRING);
789 const char *path = lua_tostring(L, 1);
790 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
792 push_original(L, "os", "remove");