]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/cpp_api/s_security.cpp
f68cd17771690ff7459c5dbb937ae915e5992dfc
[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 #include "lua_api/l_base.h"
22 #include "filesys.h"
23 #include "porting.h"
24 #include "server.h"
25 #include "client/client.h"
26 #include "settings.h"
27
28 #include <cerrno>
29 #include <string>
30 #include <algorithm>
31 #include <iostream>
32
33
34 #define SECURE_API(lib, name) \
35         lua_pushcfunction(L, sl_##lib##_##name); \
36         lua_setfield(L, -2, #name);
37
38
39 static inline void copy_safe(lua_State *L, const char *list[], unsigned len, int from=-2, int to=-1)
40 {
41         if (from < 0) from = lua_gettop(L) + from + 1;
42         if (to   < 0) to   = lua_gettop(L) + to   + 1;
43         for (unsigned i = 0; i < (len / sizeof(list[0])); i++) {
44                 lua_getfield(L, from, list[i]);
45                 lua_setfield(L, to,   list[i]);
46         }
47 }
48
49 static void shallow_copy_table(lua_State *L, int from=-2, int to=-1)
50 {
51         if (from < 0) from = lua_gettop(L) + from + 1;
52         if (to   < 0) to   = lua_gettop(L) + to   + 1;
53         lua_pushnil(L);
54         while (lua_next(L, from) != 0) {
55                 assert(lua_type(L, -1) != LUA_TTABLE);
56                 // duplicate key and value for lua_rawset
57                 lua_pushvalue(L, -2);
58                 lua_pushvalue(L, -2);
59                 lua_rawset(L, to);
60                 lua_pop(L, 1);
61         }
62 }
63
64 // Pushes the original version of a library function on the stack, from the old version
65 static inline void push_original(lua_State *L, const char *lib, const char *func)
66 {
67         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
68         lua_getfield(L, -1, lib);
69         lua_remove(L, -2);  // Remove globals_backup
70         lua_getfield(L, -1, func);
71         lua_remove(L, -2);  // Remove lib
72 }
73
74
75 void ScriptApiSecurity::initializeSecurity()
76 {
77         static const char *whitelist[] = {
78                 "assert",
79                 "core",
80                 "collectgarbage",
81                 "DIR_DELIM",
82                 "error",
83                 "getfenv",
84                 "getmetatable",
85                 "ipairs",
86                 "next",
87                 "pairs",
88                 "pcall",
89                 "print",
90                 "rawequal",
91                 "rawget",
92                 "rawset",
93                 "select",
94                 "setfenv",
95                 "setmetatable",
96                 "tonumber",
97                 "tostring",
98                 "type",
99                 "unpack",
100                 "_VERSION",
101                 "vector",
102                 "xpcall",
103         };
104         static const char *whitelist_tables[] = {
105                 // These libraries are completely safe BUT we need to duplicate their table
106                 // to ensure the sandbox can't affect the insecure env
107                 "coroutine",
108                 "string",
109                 "table",
110                 "math",
111                 "bit"
112         };
113         static const char *io_whitelist[] = {
114                 "close",
115                 "flush",
116                 "read",
117                 "type",
118                 "write",
119         };
120         static const char *os_whitelist[] = {
121                 "clock",
122                 "date",
123                 "difftime",
124                 "getenv",
125                 "time",
126         };
127         static const char *debug_whitelist[] = {
128                 "gethook",
129                 "traceback",
130                 "getinfo",
131                 "getmetatable",
132                 "setmetatable",
133                 "upvalueid",
134                 "sethook",
135                 "debug",
136         };
137         static const char *package_whitelist[] = {
138                 "config",
139                 "cpath",
140                 "path",
141                 "searchpath",
142         };
143 #if USE_LUAJIT
144         static const char *jit_whitelist[] = {
145                 "arch",
146                 "flush",
147                 "off",
148                 "on",
149                 "opt",
150                 "os",
151                 "status",
152                 "version",
153                 "version_num",
154         };
155 #endif
156         m_secure = true;
157
158         lua_State *L = getStack();
159
160         // Backup globals to the registry
161         lua_getglobal(L, "_G");
162         lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
163
164         // Replace the global environment with an empty one
165         int thread = getThread(L);
166         createEmptyEnv(L);
167         setLuaEnv(L, thread);
168
169         // Get old globals
170         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
171         int old_globals = lua_gettop(L);
172
173
174         // Copy safe base functions
175         lua_getglobal(L, "_G");
176         copy_safe(L, whitelist, sizeof(whitelist));
177
178         // And replace unsafe ones
179         SECURE_API(g, dofile);
180         SECURE_API(g, load);
181         SECURE_API(g, loadfile);
182         SECURE_API(g, loadstring);
183         SECURE_API(g, require);
184         lua_pop(L, 1);
185
186
187         // Copy safe libraries
188         for (const char *libname : whitelist_tables) {
189                 lua_getfield(L, old_globals, libname);
190                 lua_newtable(L);
191                 shallow_copy_table(L);
192
193                 lua_setglobal(L, libname);
194                 lua_pop(L, 1);
195         }
196
197
198         // Copy safe IO functions
199         lua_getfield(L, old_globals, "io");
200         lua_newtable(L);
201         copy_safe(L, io_whitelist, sizeof(io_whitelist));
202
203         // And replace unsafe ones
204         SECURE_API(io, open);
205         SECURE_API(io, input);
206         SECURE_API(io, output);
207         SECURE_API(io, lines);
208
209         lua_setglobal(L, "io");
210         lua_pop(L, 1);  // Pop old IO
211
212
213         // Copy safe OS functions
214         lua_getfield(L, old_globals, "os");
215         lua_newtable(L);
216         copy_safe(L, os_whitelist, sizeof(os_whitelist));
217
218         // And replace unsafe ones
219         SECURE_API(os, remove);
220         SECURE_API(os, rename);
221         SECURE_API(os, setlocale);
222
223         lua_setglobal(L, "os");
224         lua_pop(L, 1);  // Pop old OS
225
226
227         // Copy safe debug functions
228         lua_getfield(L, old_globals, "debug");
229         lua_newtable(L);
230         copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
231         lua_setglobal(L, "debug");
232         lua_pop(L, 1);  // Pop old debug
233
234
235         // Copy safe package fields
236         lua_getfield(L, old_globals, "package");
237         lua_newtable(L);
238         copy_safe(L, package_whitelist, sizeof(package_whitelist));
239         lua_setglobal(L, "package");
240         lua_pop(L, 1);  // Pop old package
241
242 #if USE_LUAJIT
243         // Copy safe jit functions, if they exist
244         lua_getfield(L, -1, "jit");
245         if (!lua_isnil(L, -1)) {
246                 lua_newtable(L);
247                 copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
248                 lua_setglobal(L, "jit");
249         }
250         lua_pop(L, 1);  // Pop old jit
251 #endif
252
253         // Get rid of 'core' in the old globals, we don't want anyone thinking it's
254         // safe or even usable.
255         lua_pushnil(L);
256         lua_setfield(L, old_globals, "core");
257
258         // 'vector' as well.
259         lua_pushnil(L);
260         lua_setfield(L, old_globals, "vector");
261
262         lua_pop(L, 1); // Pop globals_backup
263
264
265         /*
266          * In addition to copying the tables in whitelist_tables, we also need to
267          * replace the string metatable. Otherwise old_globals.string would
268          * be accessible via getmetatable("").__index from inside the sandbox.
269          */
270         lua_pushliteral(L, "");
271         lua_newtable(L);
272         lua_getglobal(L, "string");
273         lua_setfield(L, -2, "__index");
274         lua_setmetatable(L, -2);
275         lua_pop(L, 1); // Pop empty string
276 }
277
278 void ScriptApiSecurity::initializeSecurityClient()
279 {
280         static const char *whitelist[] = {
281                 "assert",
282                 "core",
283                 "collectgarbage",
284                 "DIR_DELIM",
285                 "error",
286                 "getfenv",
287                 "ipairs",
288                 "next",
289                 "pairs",
290                 "pcall",
291                 "print",
292                 "rawequal",
293                 "rawget",
294                 "rawset",
295                 "select",
296                 "setfenv",
297                 // getmetatable can be used to escape the sandbox <- ???
298                 "setmetatable",
299                 "tonumber",
300                 "tostring",
301                 "type",
302                 "unpack",
303                 "_VERSION",
304                 "vector",
305                 "xpcall",
306                 // Completely safe libraries
307                 "coroutine",
308                 "string",
309                 "table",
310                 "math",
311                 "bit",
312         };
313         static const char *os_whitelist[] = {
314                 "clock",
315                 "date",
316                 "difftime",
317                 "time"
318         };
319         static const char *debug_whitelist[] = {
320                 "getinfo", // used by builtin and unset before mods load
321                 "traceback"
322         };
323
324 #if USE_LUAJIT
325         static const char *jit_whitelist[] = {
326                 "arch",
327                 "flush",
328                 "off",
329                 "on",
330                 "opt",
331                 "os",
332                 "status",
333                 "version",
334                 "version_num",
335         };
336 #endif
337
338         m_secure = true;
339
340         lua_State *L = getStack();
341         int thread = getThread(L);
342
343         // create an empty environment
344         createEmptyEnv(L);
345
346         // Copy safe base functions
347         lua_getglobal(L, "_G");
348         lua_getfield(L, -2, "_G");
349         copy_safe(L, whitelist, sizeof(whitelist));
350
351         // And replace unsafe ones
352         SECURE_API(g, dofile);
353         SECURE_API(g, load);
354         SECURE_API(g, loadfile);
355         SECURE_API(g, loadstring);
356         SECURE_API(g, require);
357         lua_pop(L, 2);
358
359
360
361         // Copy safe OS functions
362         lua_getglobal(L, "os");
363         lua_newtable(L);
364         copy_safe(L, os_whitelist, sizeof(os_whitelist));
365         lua_setfield(L, -3, "os");
366         lua_pop(L, 1);  // Pop old OS
367
368
369         // Copy safe debug functions
370         lua_getglobal(L, "debug");
371         lua_newtable(L);
372         copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
373         lua_setfield(L, -3, "debug");
374         lua_pop(L, 1);  // Pop old debug
375
376 #if USE_LUAJIT
377         // Copy safe jit functions, if they exist
378         lua_getglobal(L, "jit");
379         lua_newtable(L);
380         copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
381         lua_setfield(L, -3, "jit");
382         lua_pop(L, 1);  // Pop old jit
383 #endif
384
385         // Set the environment to the one we created earlier
386         setLuaEnv(L, thread);
387 }
388
389 int ScriptApiSecurity::getThread(lua_State *L)
390 {
391 #if LUA_VERSION_NUM <= 501
392         int is_main = lua_pushthread(L);  // Push the main thread
393         FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
394                 "isn't the main Lua thread!");
395         return lua_gettop(L);
396 #endif
397         return 0;
398 }
399
400 void ScriptApiSecurity::createEmptyEnv(lua_State *L)
401 {
402         lua_newtable(L);  // Create new environment
403         lua_pushvalue(L, -1);
404         lua_setfield(L, -2, "_G");  // Create the _G loop
405 }
406
407 void ScriptApiSecurity::setLuaEnv(lua_State *L, int thread)
408 {
409 #if LUA_VERSION_NUM >= 502  // Lua >= 5.2
410         // Set the global environment
411         lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
412 #else  // Lua <= 5.1
413         // Set the environment of the main thread
414         FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set "
415                 "environment of the main Lua thread!");
416         lua_pop(L, 1);  // Pop thread
417 #endif
418 }
419
420 bool ScriptApiSecurity::isSecure(lua_State *L)
421 {
422         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
423         bool secure = !lua_isnil(L, -1);
424         lua_pop(L, 1);
425         return secure;
426 }
427
428 bool ScriptApiSecurity::safeLoadString(lua_State *L, const std::string &code, const char *chunk_name)
429 {
430         if (code.size() > 0 && code[0] == LUA_SIGNATURE[0]) {
431                 lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
432                 return false;
433         }
434         if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name))
435                 return false;
436         return true;
437 }
438
439 bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name)
440 {
441         FILE *fp;
442         char *chunk_name;
443         if (!display_name)
444                 display_name = path;
445         if (!path) {
446                 fp = stdin;
447                 chunk_name = const_cast<char *>("=stdin");
448         } else {
449                 fp = fopen(path, "rb");
450                 if (!fp) {
451                         lua_pushfstring(L, "%s: %s", path, strerror(errno));
452                         return false;
453                 }
454                 size_t len = strlen(display_name) + 2;
455                 chunk_name = new char[len];
456                 snprintf(chunk_name, len, "@%s", display_name);
457         }
458
459         size_t start = 0;
460         int c = std::getc(fp);
461         if (c == '#') {
462                 // Skip the first line
463                 while ((c = std::getc(fp)) != EOF && c != '\n') {}
464                 if (c == '\n')
465                         std::getc(fp);
466                 start = std::ftell(fp);
467         }
468
469         // Read the file
470         int ret = std::fseek(fp, 0, SEEK_END);
471         if (ret) {
472                 lua_pushfstring(L, "%s: %s", path, strerror(errno));
473                 if (path) {
474                         std::fclose(fp);
475                         delete [] chunk_name;
476                 }
477                 return false;
478         }
479
480         size_t size = std::ftell(fp) - start;
481         std::string code(size, '\0');
482         ret = std::fseek(fp, start, SEEK_SET);
483         if (ret) {
484                 lua_pushfstring(L, "%s: %s", path, strerror(errno));
485                 if (path) {
486                         std::fclose(fp);
487                         delete [] chunk_name;
488                 }
489                 return false;
490         }
491
492         size_t num_read = std::fread(&code[0], 1, size, fp);
493         if (path)
494                 std::fclose(fp);
495         if (num_read != size) {
496                 lua_pushliteral(L, "Error reading file to load.");
497                 if (path)
498                         delete [] chunk_name;
499                 return false;
500         }
501
502         bool result = safeLoadString(L, code, chunk_name);
503         if (path)
504                 delete [] chunk_name;
505         return result;
506 }
507
508
509 bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
510                 bool write_required, bool *write_allowed)
511 {
512         if (write_allowed)
513                 *write_allowed = false;
514
515         std::string str;  // Transient
516
517         std::string abs_path = fs::AbsolutePath(path);
518
519         if (!abs_path.empty()) {
520                 // Don't allow accessing the settings file
521                 str = fs::AbsolutePath(g_settings_path);
522                 if (str == abs_path) return false;
523         }
524
525         // If we couldn't find the absolute path (path doesn't exist) then
526         // try removing the last components until it works (to allow
527         // non-existent files/folders for mkdir).
528         std::string cur_path = path;
529         std::string removed;
530         while (abs_path.empty() && !cur_path.empty()) {
531                 std::string component;
532                 cur_path = fs::RemoveLastPathComponent(cur_path, &component);
533                 if (component == "..") {
534                         // Parent components can't be allowed or we could allow something like
535                         // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
536                         // If we have previous non-relative elements in the path we might be
537                         // able to remove them so that things like worlds/foo/noexist/../auth.txt
538                         // could be allowed, but those paths will be interpreted as nonexistent
539                         // by the operating system anyways.
540                         return false;
541                 }
542                 removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed);
543                 abs_path = fs::AbsolutePath(cur_path);
544         }
545         if (abs_path.empty())
546                 return false;
547         // Add the removed parts back so that you can't, eg, create a
548         // directory in worldmods if worldmods doesn't exist.
549         if (!removed.empty())
550                 abs_path += DIR_DELIM + removed;
551
552         // Get gamedef from registry
553         ScriptApiBase *script = ModApiBase::getScriptApiBase(L);
554         const IGameDef *gamedef = script->getGameDef();
555         if (!gamedef)
556                 return false;
557
558         // Get mod name
559         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
560         if (lua_isstring(L, -1)) {
561                 std::string mod_name = readParam<std::string>(L, -1);
562
563                 // Builtin can access anything
564                 if (mod_name == BUILTIN_MOD_NAME) {
565                         if (write_allowed) *write_allowed = true;
566                         return true;
567                 }
568
569                 // Allow paths in mod path
570                 // Don't bother if write access isn't important, since it will be handled later
571                 if (write_required || write_allowed != NULL) {
572                         const ModSpec *mod = gamedef->getModSpec(mod_name);
573                         if (mod) {
574                                 str = fs::AbsolutePath(mod->path);
575                                 if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
576                                         if (write_allowed) *write_allowed = true;
577                                         return true;
578                                 }
579                         }
580                 }
581         }
582         lua_pop(L, 1);  // Pop mod name
583
584         // Allow read-only access to all mod directories
585         if (!write_required) {
586                 const std::vector<ModSpec> &mods = gamedef->getMods();
587                 for (const ModSpec &mod : mods) {
588                         str = fs::AbsolutePath(mod.path);
589                         if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
590                                 return true;
591                         }
592                 }
593         }
594
595         str = fs::AbsolutePath(gamedef->getWorldPath());
596         if (!str.empty()) {
597                 // Don't allow access to other paths in the world mod/game path.
598                 // These have to be blocked so you can't override a trusted mod
599                 // by creating a mod with the same name in a world mod directory.
600                 // We add to the absolute path of the world instead of getting
601                 // the absolute paths directly because that won't work if they
602                 // don't exist.
603                 if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
604                                 fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
605                         return false;
606                 }
607                 // Allow all other paths in world path
608                 if (fs::PathStartsWith(abs_path, str)) {
609                         if (write_allowed) *write_allowed = true;
610                         return true;
611                 }
612         }
613
614         // Default to disallowing
615         return false;
616 }
617
618 bool ScriptApiSecurity::checkWhitelisted(lua_State *L, const std::string &setting)
619 {
620         assert(str_starts_with(setting, "secure."));
621
622         // We have to make sure that this function is being called directly by
623         // a mod, otherwise a malicious mod could override this function and
624         // steal its return value.
625         lua_Debug info;
626
627         // Make sure there's only one item below this function on the stack...
628         if (lua_getstack(L, 2, &info))
629                 return false;
630         FATAL_ERROR_IF(!lua_getstack(L, 1, &info), "lua_getstack() failed");
631         FATAL_ERROR_IF(!lua_getinfo(L, "S", &info), "lua_getinfo() failed");
632
633         // ...and that that item is the main file scope.
634         if (strcmp(info.what, "main") != 0)
635                 return false;
636
637         // Mod must be listed in secure.http_mods or secure.trusted_mods
638         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
639         if (!lua_isstring(L, -1))
640                 return false;
641         std::string mod_name = readParam<std::string>(L, -1);
642
643         std::string value = g_settings->get(setting);
644         value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
645         auto mod_list = str_split(value, ',');
646
647         return CONTAINS(mod_list, mod_name);
648 }
649
650
651 int ScriptApiSecurity::sl_g_dofile(lua_State *L)
652 {
653         int nret = sl_g_loadfile(L);
654         if (nret != 1) {
655                 lua_error(L);
656                 // code after this function isn't executed
657         }
658         int top_precall = lua_gettop(L);
659         lua_call(L, 0, LUA_MULTRET);
660         // Return number of arguments returned by the function,
661         // adjusting for the function being poped.
662         return lua_gettop(L) - (top_precall - 1);
663 }
664
665
666 int ScriptApiSecurity::sl_g_load(lua_State *L)
667 {
668         size_t len;
669         const char *buf;
670         std::string code;
671         const char *chunk_name = "=(load)";
672
673         luaL_checktype(L, 1, LUA_TFUNCTION);
674         if (!lua_isnone(L, 2)) {
675                 luaL_checktype(L, 2, LUA_TSTRING);
676                 chunk_name = lua_tostring(L, 2);
677         }
678
679         while (true) {
680                 lua_pushvalue(L, 1);
681                 lua_call(L, 0, 1);
682                 int t = lua_type(L, -1);
683                 if (t == LUA_TNIL) {
684                         break;
685                 }
686
687                 if (t != LUA_TSTRING) {
688                         lua_pushnil(L);
689                         lua_pushliteral(L, "Loader didn't return a string");
690                         return 2;
691                 }
692                 buf = lua_tolstring(L, -1, &len);
693                 code += std::string(buf, len);
694                 lua_pop(L, 1); // Pop return value
695         }
696         if (!safeLoadString(L, code, chunk_name)) {
697                 lua_pushnil(L);
698                 lua_insert(L, -2);
699                 return 2;
700         }
701         return 1;
702 }
703
704
705 int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
706 {
707 #ifndef SERVER
708         ScriptApiBase *script = ModApiBase::getScriptApiBase(L);
709
710         // Client implementation
711         if (script->getType() == ScriptingType::Client) {
712                 std::string path = readParam<std::string>(L, 1);
713                 const std::string *contents = script->getClient()->getModFile(path);
714                 if (!contents) {
715                         std::string error_msg = "Coudln't find script called: " + path;
716                         lua_pushnil(L);
717                         lua_pushstring(L, error_msg.c_str());
718                         return 2;
719                 }
720
721                 std::string chunk_name = "@" + path;
722                 if (!safeLoadString(L, *contents, chunk_name.c_str())) {
723                         lua_pushnil(L);
724                         lua_insert(L, -2);
725                         return 2;
726                 }
727                 return 1;
728         }
729 #endif
730
731         // Server implementation
732         const char *path = NULL;
733         if (lua_isstring(L, 1)) {
734                 path = lua_tostring(L, 1);
735                 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
736         }
737
738         if (!safeLoadFile(L, path)) {
739                 lua_pushnil(L);
740                 lua_insert(L, -2);
741                 return 2;
742         }
743
744         return 1;
745 }
746
747
748 int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
749 {
750         const char *chunk_name = "=(load)";
751
752         luaL_checktype(L, 1, LUA_TSTRING);
753         if (!lua_isnone(L, 2)) {
754                 luaL_checktype(L, 2, LUA_TSTRING);
755                 chunk_name = lua_tostring(L, 2);
756         }
757
758         size_t size;
759         const char *code = lua_tolstring(L, 1, &size);
760         std::string code_s(code, size);
761
762         if (!safeLoadString(L, code_s, chunk_name)) {
763                 lua_pushnil(L);
764                 lua_insert(L, -2);
765                 return 2;
766         }
767         return 1;
768 }
769
770
771 int ScriptApiSecurity::sl_g_require(lua_State *L)
772 {
773         lua_pushliteral(L, "require() is disabled when mod security is on.");
774         return lua_error(L);
775 }
776
777
778 int ScriptApiSecurity::sl_io_open(lua_State *L)
779 {
780         bool with_mode = lua_gettop(L) > 1;
781
782         luaL_checktype(L, 1, LUA_TSTRING);
783         const char *path = lua_tostring(L, 1);
784
785         bool write_requested = false;
786         if (with_mode) {
787                 luaL_checktype(L, 2, LUA_TSTRING);
788                 const char *mode = lua_tostring(L, 2);
789                 write_requested = strchr(mode, 'w') != NULL ||
790                         strchr(mode, '+') != NULL ||
791                         strchr(mode, 'a') != NULL;
792         }
793         CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
794
795         push_original(L, "io", "open");
796         lua_pushvalue(L, 1);
797         if (with_mode) {
798                 lua_pushvalue(L, 2);
799         }
800
801         lua_call(L, with_mode ? 2 : 1, 2);
802         return 2;
803 }
804
805
806 int ScriptApiSecurity::sl_io_input(lua_State *L)
807 {
808         if (lua_isstring(L, 1)) {
809                 const char *path = lua_tostring(L, 1);
810                 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
811         }
812
813         push_original(L, "io", "input");
814         lua_pushvalue(L, 1);
815         lua_call(L, 1, 1);
816         return 1;
817 }
818
819
820 int ScriptApiSecurity::sl_io_output(lua_State *L)
821 {
822         if (lua_isstring(L, 1)) {
823                 const char *path = lua_tostring(L, 1);
824                 CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
825         }
826
827         push_original(L, "io", "output");
828         lua_pushvalue(L, 1);
829         lua_call(L, 1, 1);
830         return 1;
831 }
832
833
834 int ScriptApiSecurity::sl_io_lines(lua_State *L)
835 {
836         if (lua_isstring(L, 1)) {
837                 const char *path = lua_tostring(L, 1);
838                 CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
839         }
840
841         int top_precall = lua_gettop(L);
842         push_original(L, "io", "lines");
843         lua_pushvalue(L, 1);
844         lua_call(L, 1, LUA_MULTRET);
845         // Return number of arguments returned by the function,
846         // adjusting for the function being poped.
847         return lua_gettop(L) - top_precall;
848 }
849
850
851 int ScriptApiSecurity::sl_os_rename(lua_State *L)
852 {
853         luaL_checktype(L, 1, LUA_TSTRING);
854         const char *path1 = lua_tostring(L, 1);
855         CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
856
857         luaL_checktype(L, 2, LUA_TSTRING);
858         const char *path2 = lua_tostring(L, 2);
859         CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
860
861         push_original(L, "os", "rename");
862         lua_pushvalue(L, 1);
863         lua_pushvalue(L, 2);
864         lua_call(L, 2, 2);
865         return 2;
866 }
867
868
869 int ScriptApiSecurity::sl_os_remove(lua_State *L)
870 {
871         luaL_checktype(L, 1, LUA_TSTRING);
872         const char *path = lua_tostring(L, 1);
873         CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
874
875         push_original(L, "os", "remove");
876         lua_pushvalue(L, 1);
877         lua_call(L, 1, 2);
878         return 2;
879 }
880
881
882 int ScriptApiSecurity::sl_os_setlocale(lua_State *L)
883 {
884         const bool cat = lua_gettop(L) > 1;
885         // Don't allow changes
886         if (!lua_isnoneornil(L, 1)) {
887                 lua_pushnil(L);
888                 return 1;
889         }
890
891         push_original(L, "os", "setlocale");
892         lua_pushnil(L);
893         if (cat)
894                 lua_pushvalue(L, 2);
895         lua_call(L, cat ? 2 : 1, 1);
896         return 1;
897 }