]> git.lizzy.rs Git - minetest.git/blob - src/script/cpp_api/s_security.cpp
Remove unused code in s_security.cpp (#4172)
[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                 "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                 return false;
289         }
290
291         // Read the file
292         int ret = std::fseek(fp, 0, SEEK_END);
293         CHECK_FILE_ERR(ret, fp);
294
295         size_t size = std::ftell(fp) - start;
296         char *code = new char[size];
297         ret = std::fseek(fp, start, SEEK_SET);
298         CHECK_FILE_ERR(ret, fp);
299
300         size_t num_read = std::fread(code, 1, size, fp);
301         if (path) {
302                 std::fclose(fp);
303         }
304         if (num_read != size) {
305                 lua_pushliteral(L, "Error reading file to load.");
306                 return false;
307         }
308
309         if (luaL_loadbuffer(L, code, size, chunk_name)) {
310                 return false;
311         }
312
313         if (path) {
314                 delete [] chunk_name;
315         }
316         return true;
317 }
318
319
320 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path)
321 {
322         std::string str;  // Transient
323
324         std::string norel_path = fs::RemoveRelativePathComponents(path);
325         std::string abs_path = fs::AbsolutePath(norel_path);
326
327         if (!abs_path.empty()) {
328                 // Don't allow accessing the settings file
329                 str = fs::AbsolutePath(g_settings_path);
330                 if (str == abs_path) return false;
331         }
332
333         // If we couldn't find the absolute path (path doesn't exist) then
334         // try removing the last components until it works (to allow
335         // non-existent files/folders for mkdir).
336         std::string cur_path = norel_path;
337         std::string removed;
338         while (abs_path.empty() && !cur_path.empty()) {
339                 std::string tmp_rmed;
340                 cur_path = fs::RemoveLastPathComponent(cur_path, &tmp_rmed);
341                 removed = tmp_rmed + (removed.empty() ? "" : DIR_DELIM + removed);
342                 abs_path = fs::AbsolutePath(cur_path);
343         }
344         if (abs_path.empty()) return false;
345         // Add the removed parts back so that you can't, eg, create a
346         // directory in worldmods if worldmods doesn't exist.
347         if (!removed.empty()) abs_path += DIR_DELIM + removed;
348
349         // Get server from registry
350         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
351         ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
352         lua_pop(L, 1);
353         const Server *server = script->getServer();
354
355         if (!server) return false;
356
357         // Get mod name
358         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
359         if (lua_isstring(L, -1)) {
360                 std::string mod_name = lua_tostring(L, -1);
361
362                 // Builtin can access anything
363                 if (mod_name == BUILTIN_MOD_NAME) {
364                         return true;
365                 }
366
367                 // Allow paths in mod path
368                 const ModSpec *mod = server->getModSpec(mod_name);
369                 if (mod) {
370                         str = fs::AbsolutePath(mod->path);
371                         if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
372                                 return true;
373                         }
374                 }
375         }
376         lua_pop(L, 1);  // Pop mod name
377
378         str = fs::AbsolutePath(server->getWorldPath());
379         if (str.empty()) return false;
380         // Don't allow access to world mods.  We add to the absolute path
381         // of the world instead of getting the absolute paths directly
382         // because that won't work if they don't exist.
383         if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
384                         fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
385                 return false;
386         }
387         // Allow all other paths in world path
388         if (fs::PathStartsWith(abs_path, str)) {
389                 return true;
390         }
391
392         // Default to disallowing
393         return false;
394 }
395
396
397 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
398 {
399         int nret = sl_g_loadfile(L);
400         if (nret != 1) {
401                 lua_error(L);
402                 // code after this function isn't executed
403         }
404         int top_precall = lua_gettop(L);
405         lua_call(L, 0, LUA_MULTRET);
406         // Return number of arguments returned by the function,
407         // adjusting for the function being poped.
408         return lua_gettop(L) - (top_precall - 1);
409 }
410
411
412 int ScriptApiSecurity::sl_g_load(lua_State *L)
413 {
414         size_t len;
415         const char *buf;
416         std::string code;
417         const char *chunk_name = "=(load)";
418
419         luaL_checktype(L, 1, LUA_TFUNCTION);
420         if (!lua_isnone(L, 2)) {
421                 luaL_checktype(L, 2, LUA_TSTRING);
422                 chunk_name = lua_tostring(L, 2);
423         }
424
425         while (true) {
426                 lua_pushvalue(L, 1);
427                 lua_call(L, 0, 1);
428                 int t = lua_type(L, -1);
429                 if (t == LUA_TNIL) {
430                         break;
431                 } else if (t != LUA_TSTRING) {
432                         lua_pushnil(L);
433                         lua_pushliteral(L, "Loader didn't return a string");
434                         return 2;
435                 }
436                 buf = lua_tolstring(L, -1, &len);
437                 code += std::string(buf, len);
438                 lua_pop(L, 1); // Pop return value
439         }
440         if (code[0] == LUA_SIGNATURE[0]) {
441                 lua_pushnil(L);
442                 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
443                 return 2;
444         }
445         if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name)) {
446                 lua_pushnil(L);
447                 lua_insert(L, lua_gettop(L) - 1);
448                 return 2;
449         }
450         return 1;
451 }
452
453
454 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
455 {
456         const char *path = NULL;
457
458         if (lua_isstring(L, 1)) {
459                 path = lua_tostring(L, 1);
460                 CHECK_SECURE_PATH(L, path);
461         }
462
463         if (!safeLoadFile(L, path)) {
464                 lua_pushnil(L);
465                 lua_insert(L, -2);
466                 return 2;
467         }
468
469         return 1;
470 }
471
472
473 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
474 {
475         const char *chunk_name = "=(load)";
476
477         luaL_checktype(L, 1, LUA_TSTRING);
478         if (!lua_isnone(L, 2)) {
479                 luaL_checktype(L, 2, LUA_TSTRING);
480                 chunk_name = lua_tostring(L, 2);
481         }
482
483         size_t size;
484         const char *code = lua_tolstring(L, 1, &size);
485
486         if (size > 0 && code[0] == LUA_SIGNATURE[0]) {
487                 lua_pushnil(L);
488                 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
489                 return 2;
490         }
491         if (luaL_loadbuffer(L, code, size, chunk_name)) {
492                 lua_pushnil(L);
493                 lua_insert(L, lua_gettop(L) - 1);
494                 return 2;
495         }
496         return 1;
497 }
498
499
500 int ScriptApiSecurity::sl_g_require(lua_State *L)
501 {
502         lua_pushliteral(L, "require() is disabled when mod security is on.");
503         return lua_error(L);
504 }
505
506
507 int ScriptApiSecurity::sl_io_open(lua_State *L)
508 {
509         luaL_checktype(L, 1, LUA_TSTRING);
510         const char *path = lua_tostring(L, 1);
511         CHECK_SECURE_PATH(L, path);
512
513         push_original(L, "io", "open");
514         lua_pushvalue(L, 1);
515         lua_pushvalue(L, 2);
516         lua_call(L, 2, 2);
517         return 2;
518 }
519
520
521 int ScriptApiSecurity::sl_io_input(lua_State *L)
522 {
523         if (lua_isstring(L, 1)) {
524                 const char *path = lua_tostring(L, 1);
525                 CHECK_SECURE_PATH(L, path);
526         }
527
528         push_original(L, "io", "input");
529         lua_pushvalue(L, 1);
530         lua_call(L, 1, 1);
531         return 1;
532 }
533
534
535 int ScriptApiSecurity::sl_io_output(lua_State *L)
536 {
537         if (lua_isstring(L, 1)) {
538                 const char *path = lua_tostring(L, 1);
539                 CHECK_SECURE_PATH(L, path);
540         }
541
542         push_original(L, "io", "output");
543         lua_pushvalue(L, 1);
544         lua_call(L, 1, 1);
545         return 1;
546 }
547
548
549 int ScriptApiSecurity::sl_io_lines(lua_State *L)
550 {
551         if (lua_isstring(L, 1)) {
552                 const char *path = lua_tostring(L, 1);
553                 CHECK_SECURE_PATH(L, path);
554         }
555
556         push_original(L, "io", "lines");
557         lua_pushvalue(L, 1);
558         int top_precall = lua_gettop(L);
559         lua_call(L, 1, LUA_MULTRET);
560         // Return number of arguments returned by the function,
561         // adjusting for the function being poped.
562         return lua_gettop(L) - (top_precall - 1);
563 }
564
565
566 int ScriptApiSecurity::sl_os_rename(lua_State *L)
567 {
568         luaL_checktype(L, 1, LUA_TSTRING);
569         const char *path1 = lua_tostring(L, 1);
570         CHECK_SECURE_PATH(L, path1);
571
572         luaL_checktype(L, 2, LUA_TSTRING);
573         const char *path2 = lua_tostring(L, 2);
574         CHECK_SECURE_PATH(L, path2);
575
576         push_original(L, "os", "rename");
577         lua_pushvalue(L, 1);
578         lua_pushvalue(L, 2);
579         lua_call(L, 2, 2);
580         return 2;
581 }
582
583
584 int ScriptApiSecurity::sl_os_remove(lua_State *L)
585 {
586         luaL_checktype(L, 1, LUA_TSTRING);
587         const char *path = lua_tostring(L, 1);
588         CHECK_SECURE_PATH(L, path);
589
590         push_original(L, "os", "remove");
591         lua_pushvalue(L, 1);
592         lua_call(L, 1, 2);
593         return 2;
594 }
595