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

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

问题描述

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

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

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

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?

推荐答案

您可以通过

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天全站免登陆