首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建安全的Lua沙箱?

如何创建安全的Lua沙箱?
EN

Stack Overflow用户
提问于 2009-08-03 21:23:45
回答 6查看 30.2K关注 0票数 75

因此,Lua似乎是在我的应用程序中实现安全的“用户脚本”的理想选择。

然而,大多数嵌入lua的示例似乎包括加载所有标准库,包括"io“和"package”。

因此,我可以从我的解释器中排除这些库,但即使是基库也包含访问文件系统的函数"dofile“和"loadfile”。

我怎样才能删除/阻止任何不安全的函数,而不只是一个连基本的东西都没有的解释器,比如"ipairs“函数?

EN

回答 6

Stack Overflow用户

发布于 2009-08-03 21:37:01

您可以通过setfenv()设置在其中运行不可信代码的函数环境。下面是一个提纲:

代码语言:javascript
复制
local env = {ipairs}
setfenv(user_script, env)
pcall(user_script)

user_script函数只能访问其环境中的内容。因此,您可以显式地添加您希望不受信任的代码能够访问的函数(白名单)。在这种情况下,用户脚本只能访问ipairs,而不能访问其他内容(dofileloadfile等)。

有关lua沙箱的示例和更多信息,请参阅Lua Sandboxes

票数 53
EN

Stack Overflow用户

发布于 2011-08-08 20:25:49

下面是Lua 5.2的一个解决方案(包括一个也可以在5.1中工作的示例环境):

代码语言:javascript
复制
-- 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):

代码语言:javascript
复制
pcall_rc, result_or_err_msg = run_sandbox(sandbox_env, my_func, arg1, arg2)
票数 35
EN

Stack Overflow用户

发布于 2009-08-04 01:31:09

Lua live demo包含一个(专用的)沙箱。source是免费提供的。

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1224708

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档