如何为Lua构建一个安全sandbox?

在我的应用程序中,Lua语言是执行安全“用户脚本”(user scripts)最理想的选择。但是,lua在实行嵌入功能时会加载全部标准库,包括io和package。所以,我可以从解释器中筛选出这些库,包括对基础库的筛选,例如读取filesystem的dofile和loadfile功能。
如果不关闭解释器,我怎样才能移除或者关闭这些不安全的功能?

原问题:How can I create a secure Lua sandbox?

阅读 6.6k
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,不过版本有些特殊。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进