因此,Lua似乎是在我的应用程序中实现安全的“用户脚本”的理想选择。
然而,大多数嵌入lua的示例似乎包括加载所有标准库,包括"io“和"package”。
因此,我可以从我的解释器中排除这些库,但即使是基库也包含访问文件系统的函数"dofile“和"loadfile”。
我怎样才能删除/阻止任何不安全的函数,而不只是一个连基本的东西都没有的解释器,比如"ipairs“函数?
发布于 2009-08-03 21:37:01
您可以通过setfenv()设置在其中运行不可信代码的函数环境。下面是一个提纲:
local env = {ipairs}
setfenv(user_script, env)
pcall(user_script)user_script函数只能访问其环境中的内容。因此,您可以显式地添加您希望不受信任的代码能够访问的函数(白名单)。在这种情况下,用户脚本只能访问ipairs,而不能访问其他内容(dofile、loadfile等)。
有关lua沙箱的示例和更多信息,请参阅Lua Sandboxes。
发布于 2011-08-08 20:25:49
下面是Lua 5.2的一个解决方案(包括一个也可以在5.1中工作的示例环境):
-- save a pointer to globals that would be unreachable in sandbox
local e=_ENV
-- sample sandbox environment
sandbox_env = {
ipairs = ipairs,
next = next,
pairs = pairs,
pcall = pcall,
tonumber = tonumber,
tostring = tostring,
type = type,
unpack = unpack,
coroutine = { create = coroutine.create, resume = coroutine.resume,
running = coroutine.running, status = coroutine.status,
wrap = coroutine.wrap },
string = { byte = string.byte, char = string.char, find = string.find,
format = string.format, gmatch = string.gmatch, gsub = string.gsub,
len = string.len, lower = string.lower, match = string.match,
rep = string.rep, reverse = string.reverse, sub = string.sub,
upper = string.upper },
table = { insert = table.insert, maxn = table.maxn, remove = table.remove,
sort = table.sort },
math = { abs = math.abs, acos = math.acos, asin = math.asin,
atan = math.atan, atan2 = math.atan2, ceil = math.ceil, cos = math.cos,
cosh = math.cosh, deg = math.deg, exp = math.exp, floor = math.floor,
fmod = math.fmod, frexp = math.frexp, huge = math.huge,
ldexp = math.ldexp, log = math.log, log10 = math.log10, max = math.max,
min = math.min, modf = math.modf, pi = math.pi, pow = math.pow,
rad = math.rad, random = math.random, sin = math.sin, sinh = math.sinh,
sqrt = math.sqrt, tan = math.tan, tanh = math.tanh },
os = { clock = os.clock, difftime = os.difftime, time = os.time },
}
function run_sandbox(sb_env, sb_func, ...)
local sb_orig_env=_ENV
if (not sb_func) then return nil end
_ENV=sb_env
local sb_ret={e.pcall(sb_func, ...)}
_ENV=sb_orig_env
return e.table.unpack(sb_ret)
end然后,要使用它,您可以像下面这样调用函数(my_func):
pcall_rc, result_or_err_msg = run_sandbox(sandbox_env, my_func, arg1, arg2)发布于 2009-08-04 01:31:09
Lua live demo包含一个(专用的)沙箱。source是免费提供的。
https://stackoverflow.com/questions/1224708
复制相似问题