]> git.lizzy.rs Git - minetest.git/blob - src/script/cpp_api/s_security.cpp
Remove os.exit from the Lua secure sandbox (#5090)
[minetest.git] / src / script / cpp_api / s_security.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "cpp_api/s_security.h"
21
22 #include "filesys.h"
23 #include "porting.h"
24 #include "server.h"
25 #include "settings.h"
26
27 #include <cerrno>
28 #include <string>
29 #include <iostream>
30
31
32 #define SECURE_API(lib, name) \
33         lua_pushcfunction(L, sl_##lib##_##name); \
34         lua_setfield(L, -2, #name);
35
36
37 static inline void copy_safe(lua_State *L, const char *list[], unsigned len, int from=-2, int to=-1)
38 {
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]);
44         }
45 }
46
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)
49 {
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
55 }
56
57
58 void ScriptApiSecurity::initializeSecurity()
59 {
60         static const char *whitelist[] = {
61                 "assert",
62                 "core",
63                 "collectgarbage",
64                 "DIR_DELIM",
65                 "error",
66                 "getfenv",
67                 "getmetatable",
68                 "ipairs",
69                 "next",
70                 "pairs",
71                 "pcall",
72                 "print",
73                 "rawequal",
74                 "rawget",
75                 "rawset",
76                 "select",
77                 "setfenv",
78                 "setmetatable",
79                 "tonumber",
80                 "tostring",
81                 "type",
82                 "unpack",
83                 "_VERSION",
84                 "xpcall",
85                 // Completely safe libraries
86                 "coroutine",
87                 "string",
88                 "table",
89                 "math",
90         };
91         static const char *io_whitelist[] = {
92                 "close",
93                 "flush",
94                 "read",
95                 "type",
96                 "write",
97         };
98         static const char *os_whitelist[] = {
99                 "clock",
100                 "date",
101                 "difftime",
102                 "getenv",
103                 "setlocale",
104                 "time",
105                 "tmpname",
106         };
107         static const char *debug_whitelist[] = {
108                 "gethook",
109                 "traceback",
110                 "getinfo",
111                 "getmetatable",
112                 "setupvalue",
113                 "setmetatable",
114                 "upvalueid",
115                 "upvaluejoin",
116                 "sethook",
117                 "debug",
118                 "setlocal",
119         };
120         static const char *package_whitelist[] = {
121                 "config",
122                 "cpath",
123                 "path",
124                 "searchpath",
125         };
126         static const char *jit_whitelist[] = {
127                 "arch",
128                 "flush",
129                 "off",
130                 "on",
131                 "opt",
132                 "os",
133                 "status",
134                 "version",
135                 "version_num",
136         };
137
138         m_secure = true;
139
140         lua_State *L = getStack();
141
142         // Backup globals to the registry
143         lua_getglobal(L, "_G");
144         lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
145
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!");
151 #endif
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);
158 #else  // Lua <= 5.1
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
163 #endif
164
165         // Get old globals
166         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
167         int old_globals = lua_gettop(L);
168
169
170         // Copy safe base functions
171         lua_getglobal(L, "_G");
172         copy_safe(L, whitelist, sizeof(whitelist));
173
174         // And replace unsafe ones
175         SECURE_API(g, dofile);
176         SECURE_API(g, load);
177         SECURE_API(g, loadfile);
178         SECURE_API(g, loadstring);
179         SECURE_API(g, require);
180         lua_pop(L, 1);
181
182
183         // Copy safe IO functions
184         lua_getfield(L, old_globals, "io");
185         lua_newtable(L);
186         copy_safe(L, io_whitelist, sizeof(io_whitelist));
187
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);
193
194         lua_setglobal(L, "io");
195         lua_pop(L, 1);  // Pop old IO
196
197
198         // Copy safe OS functions
199         lua_getfield(L, old_globals, "os");
200         lua_newtable(L);
201         copy_safe(L, os_whitelist, sizeof(os_whitelist));
202
203         // And replace unsafe ones
204         SECURE_API(os, remove);
205         SECURE_API(os, rename);
206
207         lua_setglobal(L, "os");
208         lua_pop(L, 1);  // Pop old OS
209
210
211         // Copy safe debug functions
212         lua_getfield(L, old_globals, "debug");
213         lua_newtable(L);
214         copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
215         lua_setglobal(L, "debug");
216         lua_pop(L, 1);  // Pop old debug
217
218
219         // Copy safe package fields
220         lua_getfield(L, old_globals, "package");
221         lua_newtable(L);
222         copy_safe(L, package_whitelist, sizeof(package_whitelist));
223         lua_setglobal(L, "package");
224         lua_pop(L, 1);  // Pop old package
225
226
227         // Copy safe jit functions, if they exist
228         lua_getfield(L, -1, "jit");
229         if (!lua_isnil(L, -1)) {
230                 lua_newtable(L);
231                 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
232                 lua_setglobal(L, "jit");
233         }
234         lua_pop(L, 1);  // Pop old jit
235
236         lua_pop(L, 1); // Pop globals_backup
237 }
238
239
240 bool ScriptApiSecurity::isSecure(lua_State *L)
241 {
242         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
243         bool secure = !lua_isnil(L, -1);
244         lua_pop(L, 1);
245         return secure;
246 }
247
248
249 #define CHECK_FILE_ERR(ret, fp) \
250         if (ret) { \
251                 lua_pushfstring(L, "%s: %s", path, strerror(errno)); \
252                 if (fp) std::fclose(fp); \
253                 return false; \
254         }
255
256
257 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path)
258 {
259         FILE *fp;
260         char *chunk_name;
261         if (path == NULL) {
262                 fp = stdin;
263                 chunk_name = const_cast<char *>("=stdin");
264         } else {
265                 fp = fopen(path, "rb");
266                 if (!fp) {
267                         lua_pushfstring(L, "%s: %s", path, strerror(errno));
268                         return false;
269                 }
270                 chunk_name = new char[strlen(path) + 2];
271                 chunk_name[0] = '@';
272                 chunk_name[1] = '\0';
273                 strcat(chunk_name, path);
274         }
275
276         size_t start = 0;
277         int c = std::getc(fp);
278         if (c == '#') {
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);
283         }
284
285         if (c == LUA_SIGNATURE[0]) {
286                 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
287                 std::fclose(fp);
288                 if (path) {
289                         delete [] chunk_name;
290                 }
291                 return false;
292         }
293
294         // Read the file
295         int ret = std::fseek(fp, 0, SEEK_END);
296         CHECK_FILE_ERR(ret, fp);
297
298         size_t size = std::ftell(fp) - start;
299         char *code = new char[size];
300         ret = std::fseek(fp, start, SEEK_SET);
301         if (ret) {
302                 lua_pushfstring(L, "%s: %s", path, strerror(errno));
303                 std::fclose(fp);
304                 delete [] code;
305                 if (path) {
306                         delete [] chunk_name;
307                 }
308                 return false;
309         }
310
311         size_t num_read = std::fread(code, 1, size, fp);
312         if (path) {
313                 std::fclose(fp);
314         }
315         if (num_read != size) {
316                 lua_pushliteral(L, "Error reading file to load.");
317                 delete [] code;
318                 if (path) {
319                         delete [] chunk_name;
320                 }
321                 return false;
322         }
323
324         if (luaL_loadbuffer(L, code, size, chunk_name)) {
325                 delete [] code;
326                 return false;
327         }
328
329         delete [] code;
330
331         if (path) {
332                 delete [] chunk_name;
333         }
334         return true;
335 }
336
337
338 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
339                 bool write_required, bool *write_allowed)
340 {
341         if (write_allowed)
342                 *write_allowed = false;
343
344         std::string str;  // Transient
345
346         std::string abs_path = fs::AbsolutePath(path);
347
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;
352         }
353
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;
358         std::string removed;
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.
369                         return false;
370                 }
371                 removed = component + (removed.empty() ? "" : DIR_DELIM + removed);
372                 abs_path = fs::AbsolutePath(cur_path);
373         }
374         if (abs_path.empty())
375                 return false;
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;
380
381         // Get server from registry
382         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
383         ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
384         lua_pop(L, 1);
385         const Server *server = script->getServer();
386
387         if (!server) return false;
388
389         // Get mod name
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);
393
394                 // Builtin can access anything
395                 if (mod_name == BUILTIN_MOD_NAME) {
396                         if (write_allowed) *write_allowed = true;
397                         return true;
398                 }
399
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);
404                         if (mod) {
405                                 str = fs::AbsolutePath(mod->path);
406                                 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
407                                         if (write_allowed) *write_allowed = true;
408                                         return true;
409                                 }
410                         }
411                 }
412         }
413         lua_pop(L, 1);  // Pop mod name
414
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)) {
421                                 return true;
422                         }
423                 }
424         }
425
426         str = fs::AbsolutePath(server->getWorldPath());
427         if (!str.empty()) {
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
433                 // don't exist.
434                 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
435                                 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
436                         return false;
437                 }
438                 // Allow all other paths in world path
439                 if (fs::PathStartsWith(abs_path, str)) {
440                         if (write_allowed) *write_allowed = true;
441                         return true;
442                 }
443         }
444
445         // Default to disallowing
446         return false;
447 }
448
449
450 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
451 {
452         int nret = sl_g_loadfile(L);
453         if (nret != 1) {
454                 lua_error(L);
455                 // code after this function isn't executed
456         }
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);
462 }
463
464
465 int ScriptApiSecurity::sl_g_load(lua_State *L)
466 {
467         size_t len;
468         const char *buf;
469         std::string code;
470         const char *chunk_name = "=(load)";
471
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);
476         }
477
478         while (true) {
479                 lua_pushvalue(L, 1);
480                 lua_call(L, 0, 1);
481                 int t = lua_type(L, -1);
482                 if (t == LUA_TNIL) {
483                         break;
484                 } else if (t != LUA_TSTRING) {
485                         lua_pushnil(L);
486                         lua_pushliteral(L, "Loader didn't return a string");
487                         return 2;
488                 }
489                 buf = lua_tolstring(L, -1, &len);
490                 code += std::string(buf, len);
491                 lua_pop(L, 1); // Pop return value
492         }
493         if (code[0] == LUA_SIGNATURE[0]) {
494                 lua_pushnil(L);
495                 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
496                 return 2;
497         }
498         if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name)) {
499                 lua_pushnil(L);
500                 lua_insert(L, lua_gettop(L) - 1);
501                 return 2;
502         }
503         return 1;
504 }
505
506
507 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
508 {
509         const char *path = NULL;
510
511         if (lua_isstring(L, 1)) {
512                 path = lua_tostring(L, 1);
513                 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
514         }
515
516         if (!safeLoadFile(L, path)) {
517                 lua_pushnil(L);
518                 lua_insert(L, -2);
519                 return 2;
520         }
521
522         return 1;
523 }
524
525
526 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
527 {
528         const char *chunk_name = "=(load)";
529
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);
534         }
535
536         size_t size;
537         const char *code = lua_tolstring(L, 1, &size);
538
539         if (size > 0 && code[0] == LUA_SIGNATURE[0]) {
540                 lua_pushnil(L);
541                 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
542                 return 2;
543         }
544         if (luaL_loadbuffer(L, code, size, chunk_name)) {
545                 lua_pushnil(L);
546                 lua_insert(L, lua_gettop(L) - 1);
547                 return 2;
548         }
549         return 1;
550 }
551
552
553 int ScriptApiSecurity::sl_g_require(lua_State *L)
554 {
555         lua_pushliteral(L, "require() is disabled when mod security is on.");
556         return lua_error(L);
557 }
558
559
560 int ScriptApiSecurity::sl_io_open(lua_State *L)
561 {
562         bool with_mode = lua_gettop(L) > 1;
563
564         luaL_checktype(L, 1, LUA_TSTRING);
565         const char *path = lua_tostring(L, 1);
566
567         bool write_requested = false;
568         if (with_mode) {
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;
574         }
575         CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
576
577         push_original(L, "io", "open");
578         lua_pushvalue(L, 1);
579         if (with_mode) {
580                 lua_pushvalue(L, 2);
581         }
582
583         lua_call(L, with_mode ? 2 : 1, 2);
584         return 2;
585 }
586
587
588 int ScriptApiSecurity::sl_io_input(lua_State *L)
589 {
590         if (lua_isstring(L, 1)) {
591                 const char *path = lua_tostring(L, 1);
592                 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
593         }
594
595         push_original(L, "io", "input");
596         lua_pushvalue(L, 1);
597         lua_call(L, 1, 1);
598         return 1;
599 }
600
601
602 int ScriptApiSecurity::sl_io_output(lua_State *L)
603 {
604         if (lua_isstring(L, 1)) {
605                 const char *path = lua_tostring(L, 1);
606                 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
607         }
608
609         push_original(L, "io", "output");
610         lua_pushvalue(L, 1);
611         lua_call(L, 1, 1);
612         return 1;
613 }
614
615
616 int ScriptApiSecurity::sl_io_lines(lua_State *L)
617 {
618         if (lua_isstring(L, 1)) {
619                 const char *path = lua_tostring(L, 1);
620                 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
621         }
622
623         int top_precall = lua_gettop(L);
624         push_original(L, "io", "lines");
625         lua_pushvalue(L, 1);
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;
630 }
631
632
633 int ScriptApiSecurity::sl_os_rename(lua_State *L)
634 {
635         luaL_checktype(L, 1, LUA_TSTRING);
636         const char *path1 = lua_tostring(L, 1);
637         CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
638
639         luaL_checktype(L, 2, LUA_TSTRING);
640         const char *path2 = lua_tostring(L, 2);
641         CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
642
643         push_original(L, "os", "rename");
644         lua_pushvalue(L, 1);
645         lua_pushvalue(L, 2);
646         lua_call(L, 2, 2);
647         return 2;
648 }
649
650
651 int ScriptApiSecurity::sl_os_remove(lua_State *L)
652 {
653         luaL_checktype(L, 1, LUA_TSTRING);
654         const char *path = lua_tostring(L, 1);
655         CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
656
657         push_original(L, "os", "remove");
658         lua_pushvalue(L, 1);
659         lua_call(L, 1, 2);
660         return 2;
661 }
662