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();
142 // Backup globals to the registry
143 lua_getglobal(L, "_G");
144 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
146 // Replace the global environment with an empty one
147 #if LUA_VERSION_NUM <= 501
148 int is_main = lua_pushthread(L); // Push the main thread
149 FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
150 "isn't the main Lua thread!");
152 lua_newtable(L); // Create new environment
153 lua_pushvalue(L, -1);
154 lua_setfield(L, -2, "_G"); // Set _G of new environment
155 #if LUA_VERSION_NUM >= 502 // Lua >= 5.2
156 // Set the global environment
157 lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
159 // Set the environment of the main thread
160 FATAL_ERROR_IF(!lua_setfenv(L, -2), "Security: Unable to set "
161 "environment of the main Lua thread!");
162 lua_pop(L, 1); // Pop thread
166 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
167 int old_globals = lua_gettop(L);
170 // Copy safe base functions
171 lua_getglobal(L, "_G");
172 copy_safe(L, whitelist, sizeof(whitelist));
174 // And replace unsafe ones
175 SECURE_API(g, dofile);
177 SECURE_API(g, loadfile);
178 SECURE_API(g, loadstring);
179 SECURE_API(g, require);
183 // Copy safe IO functions
184 lua_getfield(L, old_globals, "io");
186 copy_safe(L, io_whitelist, sizeof(io_whitelist));
188 // And replace unsafe ones
189 SECURE_API(io, open);
190 SECURE_API(io, input);
191 SECURE_API(io, output);
192 SECURE_API(io, lines);
194 lua_setglobal(L, "io");
195 lua_pop(L, 1); // Pop old IO
198 // Copy safe OS functions
199 lua_getfield(L, old_globals, "os");
201 copy_safe(L, os_whitelist, sizeof(os_whitelist));
203 // And replace unsafe ones
204 SECURE_API(os, remove);
205 SECURE_API(os, rename);
207 lua_setglobal(L, "os");
208 lua_pop(L, 1); // Pop old OS
211 // Copy safe debug functions
212 lua_getfield(L, old_globals, "debug");
214 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
215 lua_setglobal(L, "debug");
216 lua_pop(L, 1); // Pop old debug
219 // Copy safe package fields
220 lua_getfield(L, old_globals, "package");
222 copy_safe(L, package_whitelist, sizeof(package_whitelist));
223 lua_setglobal(L, "package");
224 lua_pop(L, 1); // Pop old package
227 // Copy safe jit functions, if they exist
228 lua_getfield(L, -1, "jit");
229 if (!lua_isnil(L, -1)) {
231 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
232 lua_setglobal(L, "jit");
234 lua_pop(L, 1); // Pop old jit
236 lua_pop(L, 1); // Pop globals_backup
240 bool ScriptApiSecurity::isSecure(lua_State *L)
242 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
243 bool secure = !lua_isnil(L, -1);
249 #define CHECK_FILE_ERR(ret, fp) \
251 lua_pushfstring(L, "%s: %s", path, strerror(errno)); \
252 if (fp) std::fclose(fp); \
257 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path)
263 chunk_name = const_cast<char *>("=stdin");
265 fp = fopen(path, "rb");
267 lua_pushfstring(L, "%s: %s", path, strerror(errno));
270 chunk_name = new char[strlen(path) + 2];
272 chunk_name[1] = '\0';
273 strcat(chunk_name, path);
277 int c = std::getc(fp);
279 // Skip the first line
280 while ((c = std::getc(fp)) != EOF && c != '\n');
281 if (c == '\n') c = std::getc(fp);
282 start = std::ftell(fp);
285 if (c == LUA_SIGNATURE[0]) {
286 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
289 delete [] chunk_name;
295 int ret = std::fseek(fp, 0, SEEK_END);
296 CHECK_FILE_ERR(ret, fp);
298 size_t size = std::ftell(fp) - start;
299 char *code = new char[size];
300 ret = std::fseek(fp, start, SEEK_SET);
302 lua_pushfstring(L, "%s: %s", path, strerror(errno));
306 delete [] chunk_name;
311 size_t num_read = std::fread(code, 1, size, fp);
315 if (num_read != size) {
316 lua_pushliteral(L, "Error reading file to load.");
319 delete [] chunk_name;
324 if (luaL_loadbuffer(L, code, size, chunk_name)) {
332 delete [] chunk_name;
338 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
339 bool write_required, bool *write_allowed)
342 *write_allowed = false;
344 std::string str; // Transient
346 std::string abs_path = fs::AbsolutePath(path);
348 if (!abs_path.empty()) {
349 // Don't allow accessing the settings file
350 str = fs::AbsolutePath(g_settings_path);
351 if (str == abs_path) return false;
354 // If we couldn't find the absolute path (path doesn't exist) then
355 // try removing the last components until it works (to allow
356 // non-existent files/folders for mkdir).
357 std::string cur_path = path;
359 while (abs_path.empty() && !cur_path.empty()) {
360 std::string component;
361 cur_path = fs::RemoveLastPathComponent(cur_path, &component);
362 if (component == "..") {
363 // Parent components can't be allowed or we could allow something like
364 // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
365 // If we have previous non-relative elements in the path we might be
366 // able to remove them so that things like worlds/foo/noexist/../auth.txt
367 // could be allowed, but those paths will be interpreted as nonexistent
368 // by the operating system anyways.
371 removed = component + (removed.empty() ? "" : DIR_DELIM + removed);
372 abs_path = fs::AbsolutePath(cur_path);
374 if (abs_path.empty())
376 // Add the removed parts back so that you can't, eg, create a
377 // directory in worldmods if worldmods doesn't exist.
378 if (!removed.empty())
379 abs_path += DIR_DELIM + removed;
381 // Get server from registry
382 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
383 ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
385 const Server *server = script->getServer();
387 if (!server) return false;
390 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
391 if (lua_isstring(L, -1)) {
392 std::string mod_name = lua_tostring(L, -1);
394 // Builtin can access anything
395 if (mod_name == BUILTIN_MOD_NAME) {
396 if (write_allowed) *write_allowed = true;
400 // Allow paths in mod path
401 // Don't bother if write access isn't important, since it will be handled later
402 if (write_required || write_allowed != NULL) {
403 const ModSpec *mod = server->getModSpec(mod_name);
405 str = fs::AbsolutePath(mod->path);
406 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
407 if (write_allowed) *write_allowed = true;
413 lua_pop(L, 1); // Pop mod name
415 // Allow read-only access to all mod directories
416 if (!write_required) {
417 const std::vector<ModSpec> mods = server->getMods();
418 for (size_t i = 0; i < mods.size(); ++i) {
419 str = fs::AbsolutePath(mods[i].path);
420 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
426 str = fs::AbsolutePath(server->getWorldPath());
428 // Don't allow access to other paths in the world mod/game path.
429 // These have to be blocked so you can't override a trusted mod
430 // by creating a mod with the same name in a world mod directory.
431 // We add to the absolute path of the world instead of getting
432 // the absolute paths directly because that won't work if they
434 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
435 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
438 // Allow all other paths in world path
439 if (fs::PathStartsWith(abs_path, str)) {
440 if (write_allowed) *write_allowed = true;
445 // Default to disallowing
450 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
452 int nret = sl_g_loadfile(L);
455 // code after this function isn't executed
457 int top_precall = lua_gettop(L);
458 lua_call(L, 0, LUA_MULTRET);
459 // Return number of arguments returned by the function,
460 // adjusting for the function being poped.
461 return lua_gettop(L) - (top_precall - 1);
465 int ScriptApiSecurity::sl_g_load(lua_State *L)
470 const char *chunk_name = "=(load)";
472 luaL_checktype(L, 1, LUA_TFUNCTION);
473 if (!lua_isnone(L, 2)) {
474 luaL_checktype(L, 2, LUA_TSTRING);
475 chunk_name = lua_tostring(L, 2);
481 int t = lua_type(L, -1);
484 } else if (t != LUA_TSTRING) {
486 lua_pushliteral(L, "Loader didn't return a string");
489 buf = lua_tolstring(L, -1, &len);
490 code += std::string(buf, len);
491 lua_pop(L, 1); // Pop return value
493 if (code[0] == LUA_SIGNATURE[0]) {
495 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
498 if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name)) {
500 lua_insert(L, lua_gettop(L) - 1);
507 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
509 const char *path = NULL;
511 if (lua_isstring(L, 1)) {
512 path = lua_tostring(L, 1);
513 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
516 if (!safeLoadFile(L, path)) {
526 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
528 const char *chunk_name = "=(load)";
530 luaL_checktype(L, 1, LUA_TSTRING);
531 if (!lua_isnone(L, 2)) {
532 luaL_checktype(L, 2, LUA_TSTRING);
533 chunk_name = lua_tostring(L, 2);
537 const char *code = lua_tolstring(L, 1, &size);
539 if (size > 0 && code[0] == LUA_SIGNATURE[0]) {
541 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
544 if (luaL_loadbuffer(L, code, size, chunk_name)) {
546 lua_insert(L, lua_gettop(L) - 1);
553 int ScriptApiSecurity::sl_g_require(lua_State *L)
555 lua_pushliteral(L, "require() is disabled when mod security is on.");
560 int ScriptApiSecurity::sl_io_open(lua_State *L)
562 bool with_mode = lua_gettop(L) > 1;
564 luaL_checktype(L, 1, LUA_TSTRING);
565 const char *path = lua_tostring(L, 1);
567 bool write_requested = false;
569 luaL_checktype(L, 2, LUA_TSTRING);
570 const char *mode = lua_tostring(L, 2);
571 write_requested = strchr(mode, 'w') != NULL ||
572 strchr(mode, '+') != NULL ||
573 strchr(mode, 'a') != NULL;
575 CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
577 push_original(L, "io", "open");
583 lua_call(L, with_mode ? 2 : 1, 2);
588 int ScriptApiSecurity::sl_io_input(lua_State *L)
590 if (lua_isstring(L, 1)) {
591 const char *path = lua_tostring(L, 1);
592 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
595 push_original(L, "io", "input");
602 int ScriptApiSecurity::sl_io_output(lua_State *L)
604 if (lua_isstring(L, 1)) {
605 const char *path = lua_tostring(L, 1);
606 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
609 push_original(L, "io", "output");
616 int ScriptApiSecurity::sl_io_lines(lua_State *L)
618 if (lua_isstring(L, 1)) {
619 const char *path = lua_tostring(L, 1);
620 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
623 int top_precall = lua_gettop(L);
624 push_original(L, "io", "lines");
626 lua_call(L, 1, LUA_MULTRET);
627 // Return number of arguments returned by the function,
628 // adjusting for the function being poped.
629 return lua_gettop(L) - top_precall;
633 int ScriptApiSecurity::sl_os_rename(lua_State *L)
635 luaL_checktype(L, 1, LUA_TSTRING);
636 const char *path1 = lua_tostring(L, 1);
637 CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
639 luaL_checktype(L, 2, LUA_TSTRING);
640 const char *path2 = lua_tostring(L, 2);
641 CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
643 push_original(L, "os", "rename");
651 int ScriptApiSecurity::sl_os_remove(lua_State *L)
653 luaL_checktype(L, 1, LUA_TSTRING);
654 const char *path = lua_tostring(L, 1);
655 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
657 push_original(L, "os", "remove");