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[] = {
108 static const char *debug_whitelist[] = {
121 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 #if LUA_VERSION_NUM <= 501
149 int is_main = lua_pushthread(L); // Push the main thread
150 FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
151 "isn't the main Lua thread!");
153 lua_newtable(L); // Create new environment
154 lua_pushvalue(L, -1);
155 lua_setfield(L, -2, "_G"); // Set _G of new environment
156 #if LUA_VERSION_NUM >= 502 // Lua >= 5.2
157 // Set the global environment
158 lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
160 // Set the environment of the main thread
161 FATAL_ERROR_IF(!lua_setfenv(L, -2), "Security: Unable to set "
162 "environment of the main Lua thread!");
163 lua_pop(L, 1); // Pop thread
167 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
168 int old_globals = lua_gettop(L);
171 // Copy safe base functions
172 lua_getglobal(L, "_G");
173 copy_safe(L, whitelist, sizeof(whitelist));
175 // And replace unsafe ones
176 SECURE_API(g, dofile);
178 SECURE_API(g, loadfile);
179 SECURE_API(g, loadstring);
180 SECURE_API(g, require);
184 // Copy safe IO functions
185 lua_getfield(L, old_globals, "io");
187 copy_safe(L, io_whitelist, sizeof(io_whitelist));
189 // And replace unsafe ones
190 SECURE_API(io, open);
191 SECURE_API(io, input);
192 SECURE_API(io, output);
193 SECURE_API(io, lines);
195 lua_setglobal(L, "io");
196 lua_pop(L, 1); // Pop old IO
199 // Copy safe OS functions
200 lua_getfield(L, old_globals, "os");
202 copy_safe(L, os_whitelist, sizeof(os_whitelist));
204 // And replace unsafe ones
205 SECURE_API(os, remove);
206 SECURE_API(os, rename);
208 lua_setglobal(L, "os");
209 lua_pop(L, 1); // Pop old OS
212 // Copy safe debug functions
213 lua_getfield(L, old_globals, "debug");
215 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
216 lua_setglobal(L, "debug");
217 lua_pop(L, 1); // Pop old debug
220 // Copy safe package fields
221 lua_getfield(L, old_globals, "package");
223 copy_safe(L, package_whitelist, sizeof(package_whitelist));
224 lua_setglobal(L, "package");
225 lua_pop(L, 1); // Pop old package
228 // Copy safe jit functions, if they exist
229 lua_getfield(L, -1, "jit");
230 if (!lua_isnil(L, -1)) {
232 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
233 lua_setglobal(L, "jit");
235 lua_pop(L, 1); // Pop old jit
237 lua_pop(L, 1); // Pop globals_backup
241 bool ScriptApiSecurity::isSecure(lua_State *L)
243 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
244 bool secure = !lua_isnil(L, -1);
250 #define CHECK_FILE_ERR(ret, fp) \
252 lua_pushfstring(L, "%s: %s", path, strerror(errno)); \
253 if (fp) std::fclose(fp); \
258 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path)
264 chunk_name = const_cast<char *>("=stdin");
266 fp = fopen(path, "rb");
268 lua_pushfstring(L, "%s: %s", path, strerror(errno));
271 chunk_name = new char[strlen(path) + 2];
273 chunk_name[1] = '\0';
274 strcat(chunk_name, path);
278 int c = std::getc(fp);
280 // Skip the first line
281 while ((c = std::getc(fp)) != EOF && c != '\n');
282 if (c == '\n') c = std::getc(fp);
283 start = std::ftell(fp);
286 if (c == LUA_SIGNATURE[0]) {
287 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
290 delete [] chunk_name;
296 int ret = std::fseek(fp, 0, SEEK_END);
297 CHECK_FILE_ERR(ret, fp);
299 size_t size = std::ftell(fp) - start;
300 char *code = new char[size];
301 ret = std::fseek(fp, start, SEEK_SET);
303 lua_pushfstring(L, "%s: %s", path, strerror(errno));
307 delete [] chunk_name;
312 size_t num_read = std::fread(code, 1, size, fp);
316 if (num_read != size) {
317 lua_pushliteral(L, "Error reading file to load.");
320 delete [] chunk_name;
325 if (luaL_loadbuffer(L, code, size, chunk_name)) {
330 delete [] chunk_name;
336 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path)
338 std::string str; // Transient
340 std::string norel_path = fs::RemoveRelativePathComponents(path);
341 std::string abs_path = fs::AbsolutePath(norel_path);
343 if (!abs_path.empty()) {
344 // Don't allow accessing the settings file
345 str = fs::AbsolutePath(g_settings_path);
346 if (str == abs_path) return false;
349 // If we couldn't find the absolute path (path doesn't exist) then
350 // try removing the last components until it works (to allow
351 // non-existent files/folders for mkdir).
352 std::string cur_path = norel_path;
354 while (abs_path.empty() && !cur_path.empty()) {
355 std::string tmp_rmed;
356 cur_path = fs::RemoveLastPathComponent(cur_path, &tmp_rmed);
357 removed = tmp_rmed + (removed.empty() ? "" : DIR_DELIM + removed);
358 abs_path = fs::AbsolutePath(cur_path);
360 if (abs_path.empty()) return false;
361 // Add the removed parts back so that you can't, eg, create a
362 // directory in worldmods if worldmods doesn't exist.
363 if (!removed.empty()) abs_path += DIR_DELIM + removed;
365 // Get server from registry
366 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
367 ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
369 const Server *server = script->getServer();
371 if (!server) return false;
374 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
375 if (lua_isstring(L, -1)) {
376 std::string mod_name = lua_tostring(L, -1);
378 // Builtin can access anything
379 if (mod_name == BUILTIN_MOD_NAME) {
383 // Allow paths in mod path
384 const ModSpec *mod = server->getModSpec(mod_name);
386 str = fs::AbsolutePath(mod->path);
387 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
392 lua_pop(L, 1); // Pop mod name
394 str = fs::AbsolutePath(server->getWorldPath());
395 if (str.empty()) return false;
396 // Don't allow access to world mods. We add to the absolute path
397 // of the world instead of getting the absolute paths directly
398 // because that won't work if they don't exist.
399 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
400 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
403 // Allow all other paths in world path
404 if (fs::PathStartsWith(abs_path, str)) {
408 // Default to disallowing
413 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
415 int nret = sl_g_loadfile(L);
418 // code after this function isn't executed
420 int top_precall = lua_gettop(L);
421 lua_call(L, 0, LUA_MULTRET);
422 // Return number of arguments returned by the function,
423 // adjusting for the function being poped.
424 return lua_gettop(L) - (top_precall - 1);
428 int ScriptApiSecurity::sl_g_load(lua_State *L)
433 const char *chunk_name = "=(load)";
435 luaL_checktype(L, 1, LUA_TFUNCTION);
436 if (!lua_isnone(L, 2)) {
437 luaL_checktype(L, 2, LUA_TSTRING);
438 chunk_name = lua_tostring(L, 2);
444 int t = lua_type(L, -1);
447 } else if (t != LUA_TSTRING) {
449 lua_pushliteral(L, "Loader didn't return a string");
452 buf = lua_tolstring(L, -1, &len);
453 code += std::string(buf, len);
454 lua_pop(L, 1); // Pop return value
456 if (code[0] == LUA_SIGNATURE[0]) {
458 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
461 if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name)) {
463 lua_insert(L, lua_gettop(L) - 1);
470 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
472 const char *path = NULL;
474 if (lua_isstring(L, 1)) {
475 path = lua_tostring(L, 1);
476 CHECK_SECURE_PATH(L, path);
479 if (!safeLoadFile(L, path)) {
489 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
491 const char *chunk_name = "=(load)";
493 luaL_checktype(L, 1, LUA_TSTRING);
494 if (!lua_isnone(L, 2)) {
495 luaL_checktype(L, 2, LUA_TSTRING);
496 chunk_name = lua_tostring(L, 2);
500 const char *code = lua_tolstring(L, 1, &size);
502 if (size > 0 && code[0] == LUA_SIGNATURE[0]) {
504 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
507 if (luaL_loadbuffer(L, code, size, chunk_name)) {
509 lua_insert(L, lua_gettop(L) - 1);
516 int ScriptApiSecurity::sl_g_require(lua_State *L)
518 lua_pushliteral(L, "require() is disabled when mod security is on.");
523 int ScriptApiSecurity::sl_io_open(lua_State *L)
525 luaL_checktype(L, 1, LUA_TSTRING);
526 const char *path = lua_tostring(L, 1);
527 CHECK_SECURE_PATH(L, path);
529 push_original(L, "io", "open");
537 int ScriptApiSecurity::sl_io_input(lua_State *L)
539 if (lua_isstring(L, 1)) {
540 const char *path = lua_tostring(L, 1);
541 CHECK_SECURE_PATH(L, path);
544 push_original(L, "io", "input");
551 int ScriptApiSecurity::sl_io_output(lua_State *L)
553 if (lua_isstring(L, 1)) {
554 const char *path = lua_tostring(L, 1);
555 CHECK_SECURE_PATH(L, path);
558 push_original(L, "io", "output");
565 int ScriptApiSecurity::sl_io_lines(lua_State *L)
567 if (lua_isstring(L, 1)) {
568 const char *path = lua_tostring(L, 1);
569 CHECK_SECURE_PATH(L, path);
572 push_original(L, "io", "lines");
574 int top_precall = lua_gettop(L);
575 lua_call(L, 1, LUA_MULTRET);
576 // Return number of arguments returned by the function,
577 // adjusting for the function being poped.
578 return lua_gettop(L) - (top_precall - 1);
582 int ScriptApiSecurity::sl_os_rename(lua_State *L)
584 luaL_checktype(L, 1, LUA_TSTRING);
585 const char *path1 = lua_tostring(L, 1);
586 CHECK_SECURE_PATH(L, path1);
588 luaL_checktype(L, 2, LUA_TSTRING);
589 const char *path2 = lua_tostring(L, 2);
590 CHECK_SECURE_PATH(L, path2);
592 push_original(L, "os", "rename");
600 int ScriptApiSecurity::sl_os_remove(lua_State *L)
602 luaL_checktype(L, 1, LUA_TSTRING);
603 const char *path = lua_tostring(L, 1);
604 CHECK_SECURE_PATH(L, path);
606 push_original(L, "os", "remove");