如何创建安全的 Lua 沙箱? [英] How can I create a secure Lua sandbox?

查看:54
本文介绍了如何创建安全的 Lua 沙箱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,Lua 似乎非常适合在我的应用程序中实现安全的用户脚本".

So Lua seems ideal for implementing secure "user scripts" inside my application.

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

However, most examples of embedding lua seem to include loading all the standard libraries, including "io" and "package".

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

So I can exclude those libs from my interpreter, but even the base library includes the functions "dofile" and "loadfile" which access the filesystem.

我怎样才能删除/阻止任何像这样的不安全的函数,而不只是最终得到一个甚至没有像ipairs"函数这样的基本东西的解释器?

How can I remove/block any unsafe functions like these, without just ending up with an interpreter that doesn't even have basic stuff like the "ipairs" function?

推荐答案

您可以通过 setfenv().大纲如下:

You can set the function environment that you run the untrusted code in via setfenv(). Here's an outline:

local env = {ipairs}
setfenv(user_script, env)
pcall(user_script)

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

The user_script function can only access what is in its environment. So you can then explicitly add in the functions that you want the untrusted code to have access to (whitelist). In this case the user script only has access to ipairs but nothing else (dofile, loadfile, etc).

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

See Lua Sandboxes for an example and more information on lua sandboxing.

这篇关于如何创建安全的 Lua 沙箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆