Lua's built-in math
, string
, and table
libraries will always be safe. coroutine
is also safe, and extremely useful to some advanced lua programmers.
There are some other, not-so-safe libraries lua loads in by default (which you can easily disable)
os
lets you execute commands, and do other nasty things. However, os.time
and os.date
are useful functions, so keep those in.
io
allows you to read- and edit- any file on the computer. Probably best to leave it out.
debug
allows you to "reflect" on the program. This means that the program can edit certain parts about itself, and can be unwanted. It's a safe bet that user programs won't need this. Ever.
Instead of replacing something with an empty string, you can always replace it with setfenv
(Lua 5.1), like so:
local badCode = readFile("./code.lua")
local Func = loadstring(badCode)
setfenv(Func, {
-- If we leave nothing here, then the script will not be able to access any global variable.
-- It's perfectly sandboxed. But let's give it some stuff:
print = print, pcall = pcall, pairs = pairs, ipairs = ipairs, error = error, string = string, table = table, math = math, coroutine = coroutine,
-- Now, let's give it some functions that *could* be useful, from an otherwise sandboxed library
os = {
time = os.time,
date = os.date,
clock = os.clock,
},
-- All of these are "kind of" useful to the program.
})
-- Now that Func is properly sandboxed, let's run it!
Func()
-- This is how you should treat user code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…