佚名通过本文主要向大家介绍了sandbox,srs audio sandbox,universe sandbox,360sandbox,360sandbox是什么文件等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
问题:如何为Lua构建一个安全sandbox?
描述:
解决方案1:
描述:
在我的应用程序中,Lua语言是执行安全“用户脚本”(user scripts)最理想的选择。但是,lua在实行嵌入功能时会加载全部标准库,包括io和package。所以,我可以从解释器中筛选出这些库,包括对基础库的筛选,例如读取filesystem的dofile和loadfile功能。
如果不关闭解释器,我怎样才能移除或者关闭这些不安全的功能?
原问题:How can I create a secure Lua sandbox?
解决方案1:
Lua 5.2 相对 Lua 5.1 做了修改。
http://blog.codingnow.com/2011/12/lua_52_env.html
解决方案2:答:Karl Voigtland
你可以设定函数的环境,使一些不受信任的代码通过setfenv()顺利运行,下面是一个基本的思路:
local env = {ipairs}
setfenv(user_script, env)
pcall(user_script)
user_script功能只能读取环境内部的数据,所以你可以在这项功能中特别添加一些功能,以便识别不受信任的代码可以。这样,user_script只能读取ipairs,不会读取类似于dofile,loadfile的数据了。
答:BMitch
下面是一个针对于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
在使用,可以调用以下代码:
pcall_rc, result_or_err_msg = run_sandbox(sandbox_env, my_func, arg1, arg2)
答:lhf
在Lua live demo中就可以免费找到sandbox,不过版本有些特殊。