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