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[] = {
122 static const char *package_whitelist[] = {
128 static const char *jit_whitelist[] = {
142 lua_State *L = getStack();
144 // Backup globals to the registry
145 lua_getglobal(L, "_G");
146 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
148 // Replace the global environment with an empty one
149 #if LUA_VERSION_NUM <= 501
150 int is_main = lua_pushthread(L); // Push the main thread
151 FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
152 "isn't the main Lua thread!");
154 lua_newtable(L); // Create new environment
155 lua_pushvalue(L, -1);
156 lua_setfield(L, -2, "_G"); // Set _G of new environment
157 #if LUA_VERSION_NUM >= 502 // Lua >= 5.2
158 // Set the global environment
159 lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
161 // Set the environment of the main thread
162 FATAL_ERROR_IF(!lua_setfenv(L, -2), "Security: Unable to set "
163 "environment of the main Lua thread!");
164 lua_pop(L, 1); // Pop thread
168 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
169 int old_globals = lua_gettop(L);
172 // Copy safe base functions
173 lua_getglobal(L, "_G");
174 copy_safe(L, whitelist, sizeof(whitelist));
176 // And replace unsafe ones
177 SECURE_API(g, dofile);
179 SECURE_API(g, loadfile);
180 SECURE_API(g, loadstring);
181 SECURE_API(g, require);
185 // Copy safe IO functions
186 lua_getfield(L, old_globals, "io");
188 copy_safe(L, io_whitelist, sizeof(io_whitelist));
190 // And replace unsafe ones
191 SECURE_API(io, open);
192 SECURE_API(io, input);
193 SECURE_API(io, output);
194 SECURE_API(io, lines);
196 lua_setglobal(L, "io");
197 lua_pop(L, 1); // Pop old IO
200 // Copy safe OS functions
201 lua_getfield(L, old_globals, "os");
203 copy_safe(L, os_whitelist, sizeof(os_whitelist));
205 // And replace unsafe ones
206 SECURE_API(os, remove);
207 SECURE_API(os, rename);
209 lua_setglobal(L, "os");
210 lua_pop(L, 1); // Pop old OS
213 // Copy safe debug functions
214 lua_getfield(L, old_globals, "debug");
216 copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
217 lua_setglobal(L, "debug");
218 lua_pop(L, 1); // Pop old debug
221 // Copy safe package fields
222 lua_getfield(L, old_globals, "package");
224 copy_safe(L, package_whitelist, sizeof(package_whitelist));
225 lua_setglobal(L, "package");
226 lua_pop(L, 1); // Pop old package
229 // Copy safe jit functions, if they exist
230 lua_getfield(L, -1, "jit");
231 if (!lua_isnil(L, -1)) {
233 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
234 lua_setglobal(L, "jit");
236 lua_pop(L, 1); // Pop old jit
238 lua_pop(L, 1); // Pop globals_backup
242 bool ScriptApiSecurity::isSecure(lua_State *L)
244 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
245 bool secure = !lua_isnil(L, -1);
251 #define CHECK_FILE_ERR(ret, fp) \
253 if (fp) std::fclose(fp); \
254 lua_pushfstring(L, "%s: %s", path, strerror(errno)); \
259 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path)
265 chunk_name = const_cast<char *>("=stdin");
267 fp = fopen(path, "rb");
269 lua_pushfstring(L, "%s: %s", path, strerror(errno));
272 chunk_name = new char[strlen(path) + 2];
274 chunk_name[1] = '\0';
275 strcat(chunk_name, path);
279 int c = std::getc(fp);
281 // Skip the first line
282 while ((c = std::getc(fp)) != EOF && c != '\n');
283 if (c == '\n') c = std::getc(fp);
284 start = std::ftell(fp);
287 if (c == LUA_SIGNATURE[0]) {
288 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
293 int ret = std::fseek(fp, 0, SEEK_END);
294 CHECK_FILE_ERR(ret, fp);
297 lua_pushfstring(L, "%s: %s", path, strerror(errno));
300 size_t size = std::ftell(fp) - start;
301 char *code = new char[size];
302 ret = std::fseek(fp, start, SEEK_SET);
303 CHECK_FILE_ERR(ret, fp);
306 lua_pushfstring(L, "%s: %s", path, strerror(errno));
309 size_t num_read = std::fread(code, 1, size, fp);
313 if (num_read != size) {
314 lua_pushliteral(L, "Error reading file to load.");
318 if (luaL_loadbuffer(L, code, size, chunk_name)) {
323 delete [] chunk_name;
329 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path)
331 std::string str; // Transient
333 std::string norel_path = fs::RemoveRelativePathComponents(path);
334 std::string abs_path = fs::AbsolutePath(norel_path);
336 if (!abs_path.empty()) {
337 // Don't allow accessing the settings file
338 str = fs::AbsolutePath(g_settings_path);
339 if (str == abs_path) return false;
342 // If we couldn't find the absolute path (path doesn't exist) then
343 // try removing the last components until it works (to allow
344 // non-existent files/folders for mkdir).
345 std::string cur_path = norel_path;
347 while (abs_path.empty() && !cur_path.empty()) {
348 std::string tmp_rmed;
349 cur_path = fs::RemoveLastPathComponent(cur_path, &tmp_rmed);
350 removed = tmp_rmed + (removed.empty() ? "" : DIR_DELIM + removed);
351 abs_path = fs::AbsolutePath(cur_path);
353 if (abs_path.empty()) return false;
354 // Add the removed parts back so that you can't, eg, create a
355 // directory in worldmods if worldmods doesn't exist.
356 if (!removed.empty()) abs_path += DIR_DELIM + removed;
358 // Get server from registry
359 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
360 ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
362 const Server *server = script->getServer();
364 if (!server) return false;
367 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
368 if (lua_isstring(L, -1)) {
369 std::string mod_name = lua_tostring(L, -1);
371 // Builtin can access anything
372 if (mod_name == BUILTIN_MOD_NAME) {
376 // Allow paths in mod path
377 const ModSpec *mod = server->getModSpec(mod_name);
379 str = fs::AbsolutePath(mod->path);
380 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
385 lua_pop(L, 1); // Pop mod name
387 str = fs::AbsolutePath(server->getWorldPath());
388 if (str.empty()) return false;
389 // Don't allow access to world mods. We add to the absolute path
390 // of the world instead of getting the absolute paths directly
391 // because that won't work if they don't exist.
392 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
393 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
396 // Allow all other paths in world path
397 if (fs::PathStartsWith(abs_path, str)) {
401 // Default to disallowing
406 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
408 int nret = sl_g_loadfile(L);
411 // code after this function isn't executed
413 int top_precall = lua_gettop(L);
414 lua_call(L, 0, LUA_MULTRET);
415 // Return number of arguments returned by the function,
416 // adjusting for the function being poped.
417 return lua_gettop(L) - (top_precall - 1);
421 int ScriptApiSecurity::sl_g_load(lua_State *L)
426 const char *chunk_name = "=(load)";
428 luaL_checktype(L, 1, LUA_TFUNCTION);
429 if (!lua_isnone(L, 2)) {
430 luaL_checktype(L, 2, LUA_TSTRING);
431 chunk_name = lua_tostring(L, 2);
437 int t = lua_type(L, -1);
440 } else if (t != LUA_TSTRING) {
442 lua_pushliteral(L, "Loader didn't return a string");
445 buf = lua_tolstring(L, -1, &len);
446 code += std::string(buf, len);
447 lua_pop(L, 1); // Pop return value
449 if (code[0] == LUA_SIGNATURE[0]) {
451 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
454 if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name)) {
456 lua_insert(L, lua_gettop(L) - 1);
463 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
465 const char *path = NULL;
467 if (lua_isstring(L, 1)) {
468 path = lua_tostring(L, 1);
469 CHECK_SECURE_PATH(L, path);
472 if (!safeLoadFile(L, path)) {
482 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
484 const char *chunk_name = "=(load)";
486 luaL_checktype(L, 1, LUA_TSTRING);
487 if (!lua_isnone(L, 2)) {
488 luaL_checktype(L, 2, LUA_TSTRING);
489 chunk_name = lua_tostring(L, 2);
493 const char *code = lua_tolstring(L, 1, &size);
495 if (size > 0 && code[0] == LUA_SIGNATURE[0]) {
497 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
500 if (luaL_loadbuffer(L, code, size, chunk_name)) {
502 lua_insert(L, lua_gettop(L) - 1);
509 int ScriptApiSecurity::sl_g_require(lua_State *L)
511 lua_pushliteral(L, "require() is disabled when mod security is on.");
516 int ScriptApiSecurity::sl_io_open(lua_State *L)
518 luaL_checktype(L, 1, LUA_TSTRING);
519 const char *path = lua_tostring(L, 1);
520 CHECK_SECURE_PATH(L, path);
522 push_original(L, "io", "open");
530 int ScriptApiSecurity::sl_io_input(lua_State *L)
532 if (lua_isstring(L, 1)) {
533 const char *path = lua_tostring(L, 1);
534 CHECK_SECURE_PATH(L, path);
537 push_original(L, "io", "input");
544 int ScriptApiSecurity::sl_io_output(lua_State *L)
546 if (lua_isstring(L, 1)) {
547 const char *path = lua_tostring(L, 1);
548 CHECK_SECURE_PATH(L, path);
551 push_original(L, "io", "output");
558 int ScriptApiSecurity::sl_io_lines(lua_State *L)
560 if (lua_isstring(L, 1)) {
561 const char *path = lua_tostring(L, 1);
562 CHECK_SECURE_PATH(L, path);
565 push_original(L, "io", "lines");
567 int top_precall = lua_gettop(L);
568 lua_call(L, 1, LUA_MULTRET);
569 // Return number of arguments returned by the function,
570 // adjusting for the function being poped.
571 return lua_gettop(L) - (top_precall - 1);
575 int ScriptApiSecurity::sl_os_rename(lua_State *L)
577 luaL_checktype(L, 1, LUA_TSTRING);
578 const char *path1 = lua_tostring(L, 1);
579 CHECK_SECURE_PATH(L, path1);
581 luaL_checktype(L, 2, LUA_TSTRING);
582 const char *path2 = lua_tostring(L, 2);
583 CHECK_SECURE_PATH(L, path2);
585 push_original(L, "os", "rename");
593 int ScriptApiSecurity::sl_os_remove(lua_State *L)
595 luaL_checktype(L, 1, LUA_TSTRING);
596 const char *path = lua_tostring(L, 1);
597 CHECK_SECURE_PATH(L, path);
599 push_original(L, "os", "remove");