]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/cpp_api/s_security.cpp
Security: Fix resolving of some relative paths
[dragonfireclient.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                 "exit",
103                 "getenv",
104                 "setlocale",
105                 "time",
106                 "tmpname",
107         };
108         static const char *debug_whitelist[] = {
109                 "gethook",
110                 "traceback",
111                 "getinfo",
112                 "getmetatable",
113                 "setupvalue",
114                 "setmetatable",
115                 "upvalueid",
116                 "upvaluejoin",
117                 "sethook",
118                 "debug",
119                 "setlocal",
120         };
121         static const char *package_whitelist[] = {
122                 "config",
123                 "cpath",
124                 "path",
125                 "searchpath",
126         };
127         static const char *jit_whitelist[] = {
128                 "arch",
129                 "flush",
130                 "off",
131                 "on",
132                 "opt",
133                 "os",
134                 "status",
135                 "version",
136                 "version_num",
137         };
138
139         m_secure = true;
140
141         lua_State *L = getStack();
142
143         // Backup globals to the registry
144         lua_getglobal(L, "_G");
145         lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
146
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!");
152 #endif
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);
159 #else  // Lua <= 5.1
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
164 #endif
165
166         // Get old globals
167         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
168         int old_globals = lua_gettop(L);
169
170
171         // Copy safe base functions
172         lua_getglobal(L, "_G");
173         copy_safe(L, whitelist, sizeof(whitelist));
174
175         // And replace unsafe ones
176         SECURE_API(g, dofile);
177         SECURE_API(g, load);
178         SECURE_API(g, loadfile);
179         SECURE_API(g, loadstring);
180         SECURE_API(g, require);
181         lua_pop(L, 1);
182
183
184         // Copy safe IO functions
185         lua_getfield(L, old_globals, "io");
186         lua_newtable(L);
187         copy_safe(L, io_whitelist, sizeof(io_whitelist));
188
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);
194
195         lua_setglobal(L, "io");
196         lua_pop(L, 1);  // Pop old IO
197
198
199         // Copy safe OS functions
200         lua_getfield(L, old_globals, "os");
201         lua_newtable(L);
202         copy_safe(L, os_whitelist, sizeof(os_whitelist));
203
204         // And replace unsafe ones
205         SECURE_API(os, remove);
206         SECURE_API(os, rename);
207
208         lua_setglobal(L, "os");
209         lua_pop(L, 1);  // Pop old OS
210
211
212         // Copy safe debug functions
213         lua_getfield(L, old_globals, "debug");
214         lua_newtable(L);
215         copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
216         lua_setglobal(L, "debug");
217         lua_pop(L, 1);  // Pop old debug
218
219
220         // Copy safe package fields
221         lua_getfield(L, old_globals, "package");
222         lua_newtable(L);
223         copy_safe(L, package_whitelist, sizeof(package_whitelist));
224         lua_setglobal(L, "package");
225         lua_pop(L, 1);  // Pop old package
226
227
228         // Copy safe jit functions, if they exist
229         lua_getfield(L, -1, "jit");
230         if (!lua_isnil(L, -1)) {
231                 lua_newtable(L);
232                 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
233                 lua_setglobal(L, "jit");
234         }
235         lua_pop(L, 1);  // Pop old jit
236
237         lua_pop(L, 1); // Pop globals_backup
238 }
239
240
241 bool ScriptApiSecurity::isSecure(lua_State *L)
242 {
243         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
244         bool secure = !lua_isnil(L, -1);
245         lua_pop(L, 1);
246         return secure;
247 }
248
249
250 #define CHECK_FILE_ERR(ret, fp) \
251         if (ret) { \
252                 lua_pushfstring(L, "%s: %s", path, strerror(errno)); \
253                 if (fp) std::fclose(fp); \
254                 return false; \
255         }
256
257
258 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path)
259 {
260         FILE *fp;
261         char *chunk_name;
262         if (path == NULL) {
263                 fp = stdin;
264                 chunk_name = const_cast<char *>("=stdin");
265         } else {
266                 fp = fopen(path, "rb");
267                 if (!fp) {
268                         lua_pushfstring(L, "%s: %s", path, strerror(errno));
269                         return false;
270                 }
271                 chunk_name = new char[strlen(path) + 2];
272                 chunk_name[0] = '@';
273                 chunk_name[1] = '\0';
274                 strcat(chunk_name, path);
275         }
276
277         size_t start = 0;
278         int c = std::getc(fp);
279         if (c == '#') {
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);
284         }
285
286         if (c == LUA_SIGNATURE[0]) {
287                 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
288                 std::fclose(fp);
289                 if (path) {
290                         delete [] chunk_name;
291                 }
292                 return false;
293         }
294
295         // Read the file
296         int ret = std::fseek(fp, 0, SEEK_END);
297         CHECK_FILE_ERR(ret, fp);
298
299         size_t size = std::ftell(fp) - start;
300         char *code = new char[size];
301         ret = std::fseek(fp, start, SEEK_SET);
302         if (ret) {
303                 lua_pushfstring(L, "%s: %s", path, strerror(errno));
304                 std::fclose(fp);
305                 delete [] code;
306                 if (path) {
307                         delete [] chunk_name;
308                 }
309                 return false;
310         }
311
312         size_t num_read = std::fread(code, 1, size, fp);
313         if (path) {
314                 std::fclose(fp);
315         }
316         if (num_read != size) {
317                 lua_pushliteral(L, "Error reading file to load.");
318                 delete [] code;
319                 if (path) {
320                         delete [] chunk_name;
321                 }
322                 return false;
323         }
324
325         if (luaL_loadbuffer(L, code, size, chunk_name)) {
326                 delete [] code;
327                 return false;
328         }
329
330         delete [] code;
331
332         if (path) {
333                 delete [] chunk_name;
334         }
335         return true;
336 }
337
338
339 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
340                 bool write_required, bool *write_allowed)
341 {
342         if (write_allowed)
343                 *write_allowed = false;
344
345         std::string str;  // Transient
346
347         std::string abs_path = fs::AbsolutePath(path);
348
349         if (!abs_path.empty()) {
350                 // Don't allow accessing the settings file
351                 str = fs::AbsolutePath(g_settings_path);
352                 if (str == abs_path) return false;
353         }
354
355         // If we couldn't find the absolute path (path doesn't exist) then
356         // try removing the last components until it works (to allow
357         // non-existent files/folders for mkdir).
358         std::string cur_path = path;
359         std::string removed;
360         while (abs_path.empty() && !cur_path.empty()) {
361                 std::string component;
362                 cur_path = fs::RemoveLastPathComponent(cur_path, &component);
363                 if (component == "..") {
364                         // Parent components can't be allowed or we could allow something like
365                         // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
366                         // If we have previous non-relative elements in the path we might be
367                         // able to remove them so that things like worlds/foo/noexist/../auth.txt
368                         // could be allowed, but those paths will be interpreted as nonexistent
369                         // by the operating system anyways.
370                         return false;
371                 }
372                 removed = component + (removed.empty() ? "" : DIR_DELIM + removed);
373                 abs_path = fs::AbsolutePath(cur_path);
374         }
375         if (abs_path.empty())
376                 return false;
377         // Add the removed parts back so that you can't, eg, create a
378         // directory in worldmods if worldmods doesn't exist.
379         if (!removed.empty())
380                 abs_path += DIR_DELIM + removed;
381
382         // Get server from registry
383         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
384         ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
385         lua_pop(L, 1);
386         const Server *server = script->getServer();
387
388         if (!server) return false;
389
390         // Get mod name
391         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
392         if (lua_isstring(L, -1)) {
393                 std::string mod_name = lua_tostring(L, -1);
394
395                 // Builtin can access anything
396                 if (mod_name == BUILTIN_MOD_NAME) {
397                         if (write_allowed) *write_allowed = true;
398                         return true;
399                 }
400
401                 // Allow paths in mod path
402                 // Don't bother if write access isn't important, since it will be handled later
403                 if (write_required || write_allowed != NULL) {
404                         const ModSpec *mod = server->getModSpec(mod_name);
405                         if (mod) {
406                                 str = fs::AbsolutePath(mod->path);
407                                 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
408                                         if (write_allowed) *write_allowed = true;
409                                         return true;
410                                 }
411                         }
412                 }
413         }
414         lua_pop(L, 1);  // Pop mod name
415
416         // Allow read-only access to all mod directories
417         if (!write_required) {
418                 const std::vector<ModSpec> mods = server->getMods();
419                 for (size_t i = 0; i < mods.size(); ++i) {
420                         str = fs::AbsolutePath(mods[i].path);
421                         if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
422                                 return true;
423                         }
424                 }
425         }
426
427         str = fs::AbsolutePath(server->getWorldPath());
428         if (!str.empty()) {
429                 // Don't allow access to other paths in the world mod/game path.
430                 // These have to be blocked so you can't override a trusted mod
431                 // by creating a mod with the same name in a world mod directory.
432                 // We add to the absolute path of the world instead of getting
433                 // the absolute paths directly because that won't work if they
434                 // don't exist.
435                 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
436                                 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
437                         return false;
438                 }
439                 // Allow all other paths in world path
440                 if (fs::PathStartsWith(abs_path, str)) {
441                         if (write_allowed) *write_allowed = true;
442                         return true;
443                 }
444         }
445
446         // Default to disallowing
447         return false;
448 }
449
450
451 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
452 {
453         int nret = sl_g_loadfile(L);
454         if (nret != 1) {
455                 lua_error(L);
456                 // code after this function isn't executed
457         }
458         int top_precall = lua_gettop(L);
459         lua_call(L, 0, LUA_MULTRET);
460         // Return number of arguments returned by the function,
461         // adjusting for the function being poped.
462         return lua_gettop(L) - (top_precall - 1);
463 }
464
465
466 int ScriptApiSecurity::sl_g_load(lua_State *L)
467 {
468         size_t len;
469         const char *buf;
470         std::string code;
471         const char *chunk_name = "=(load)";
472
473         luaL_checktype(L, 1, LUA_TFUNCTION);
474         if (!lua_isnone(L, 2)) {
475                 luaL_checktype(L, 2, LUA_TSTRING);
476                 chunk_name = lua_tostring(L, 2);
477         }
478
479         while (true) {
480                 lua_pushvalue(L, 1);
481                 lua_call(L, 0, 1);
482                 int t = lua_type(L, -1);
483                 if (t == LUA_TNIL) {
484                         break;
485                 } else if (t != LUA_TSTRING) {
486                         lua_pushnil(L);
487                         lua_pushliteral(L, "Loader didn't return a string");
488                         return 2;
489                 }
490                 buf = lua_tolstring(L, -1, &len);
491                 code += std::string(buf, len);
492                 lua_pop(L, 1); // Pop return value
493         }
494         if (code[0] == LUA_SIGNATURE[0]) {
495                 lua_pushnil(L);
496                 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
497                 return 2;
498         }
499         if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name)) {
500                 lua_pushnil(L);
501                 lua_insert(L, lua_gettop(L) - 1);
502                 return 2;
503         }
504         return 1;
505 }
506
507
508 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
509 {
510         const char *path = NULL;
511
512         if (lua_isstring(L, 1)) {
513                 path = lua_tostring(L, 1);
514                 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
515         }
516
517         if (!safeLoadFile(L, path)) {
518                 lua_pushnil(L);
519                 lua_insert(L, -2);
520                 return 2;
521         }
522
523         return 1;
524 }
525
526
527 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
528 {
529         const char *chunk_name = "=(load)";
530
531         luaL_checktype(L, 1, LUA_TSTRING);
532         if (!lua_isnone(L, 2)) {
533                 luaL_checktype(L, 2, LUA_TSTRING);
534                 chunk_name = lua_tostring(L, 2);
535         }
536
537         size_t size;
538         const char *code = lua_tolstring(L, 1, &size);
539
540         if (size > 0 && code[0] == LUA_SIGNATURE[0]) {
541                 lua_pushnil(L);
542                 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
543                 return 2;
544         }
545         if (luaL_loadbuffer(L, code, size, chunk_name)) {
546                 lua_pushnil(L);
547                 lua_insert(L, lua_gettop(L) - 1);
548                 return 2;
549         }
550         return 1;
551 }
552
553
554 int ScriptApiSecurity::sl_g_require(lua_State *L)
555 {
556         lua_pushliteral(L, "require() is disabled when mod security is on.");
557         return lua_error(L);
558 }
559
560
561 int ScriptApiSecurity::sl_io_open(lua_State *L)
562 {
563         bool with_mode = lua_gettop(L) > 1;
564
565         luaL_checktype(L, 1, LUA_TSTRING);
566         const char *path = lua_tostring(L, 1);
567
568         bool write_requested = false;
569         if (with_mode) {
570                 luaL_checktype(L, 2, LUA_TSTRING);
571                 const char *mode = lua_tostring(L, 2);
572                 write_requested = strchr(mode, 'w') != NULL ||
573                         strchr(mode, '+') != NULL ||
574                         strchr(mode, 'a') != NULL;
575         }
576         CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
577
578         push_original(L, "io", "open");
579         lua_pushvalue(L, 1);
580         if (with_mode) {
581                 lua_pushvalue(L, 2);
582         }
583
584         lua_call(L, with_mode ? 2 : 1, 2);
585         return 2;
586 }
587
588
589 int ScriptApiSecurity::sl_io_input(lua_State *L)
590 {
591         if (lua_isstring(L, 1)) {
592                 const char *path = lua_tostring(L, 1);
593                 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
594         }
595
596         push_original(L, "io", "input");
597         lua_pushvalue(L, 1);
598         lua_call(L, 1, 1);
599         return 1;
600 }
601
602
603 int ScriptApiSecurity::sl_io_output(lua_State *L)
604 {
605         if (lua_isstring(L, 1)) {
606                 const char *path = lua_tostring(L, 1);
607                 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
608         }
609
610         push_original(L, "io", "output");
611         lua_pushvalue(L, 1);
612         lua_call(L, 1, 1);
613         return 1;
614 }
615
616
617 int ScriptApiSecurity::sl_io_lines(lua_State *L)
618 {
619         if (lua_isstring(L, 1)) {
620                 const char *path = lua_tostring(L, 1);
621                 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
622         }
623
624         int top_precall = lua_gettop(L);
625         push_original(L, "io", "lines");
626         lua_pushvalue(L, 1);
627         lua_call(L, 1, LUA_MULTRET);
628         // Return number of arguments returned by the function,
629         // adjusting for the function being poped.
630         return lua_gettop(L) - top_precall;
631 }
632
633
634 int ScriptApiSecurity::sl_os_rename(lua_State *L)
635 {
636         luaL_checktype(L, 1, LUA_TSTRING);
637         const char *path1 = lua_tostring(L, 1);
638         CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
639
640         luaL_checktype(L, 2, LUA_TSTRING);
641         const char *path2 = lua_tostring(L, 2);
642         CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
643
644         push_original(L, "os", "rename");
645         lua_pushvalue(L, 1);
646         lua_pushvalue(L, 2);
647         lua_call(L, 2, 2);
648         return 2;
649 }
650
651
652 int ScriptApiSecurity::sl_os_remove(lua_State *L)
653 {
654         luaL_checktype(L, 1, LUA_TSTRING);
655         const char *path = lua_tostring(L, 1);
656         CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
657
658         push_original(L, "os", "remove");
659         lua_pushvalue(L, 1);
660         lua_call(L, 1, 2);
661         return 2;
662 }
663