Lua 沙盒 - 消除函数创建
我已经在 Lua wiki / 这里 / 等上阅读了如何对 lua 代码进行沙箱处理。但我还没有找到不允许创建函数的东西。例如,示例此处提供的示例代码如下:
assert(run [[function f(x) return x^2 end; t={2}; t[1]=f(t[1])]])
这是一个空环境。但我想消除创建函数(代码的第一部分)的能力 - 例如,仅允许表达式。关于如何做到这一点有什么想法吗?它必须以某种方式在 C 中吗?提前致谢!
I've read on the Lua wiki / here / etc. on how to sandbox lua code generally. But I haven't been able to find something that disallows function creation. For example, the example here provides a sample code as:
assert(run [[function f(x) return x^2 end; t={2}; t[1]=f(t[1])]])
And that's with an empty environment. But I want to eliminate the ability to create a function (the 1st part of the code) - e.g., just allow expressions. Any idea on how to do that? Does it have to be in C somehow? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只想计算表达式,您可以尝试以下操作:(
省略错误处理)
这个简单的解决方案将防止大多数“攻击”,但不能消除它们,因为可以说它
定义了一个名为
f
的新函数。最好的选择是使用沙箱,而不用担心用户对环境做了什么,因为它不会是您的环境。
If you want to evaluate expressions only, you could try this:
(error handling omitted)
This simple solution will prevent most `attacks', but not eliminate them because one can say
which defines a new function named
f
.Your best bet is to use a sandbox and not worry about what the user does to the environment, because it'll not be your environment.
在允许执行 lua 脚本之前,您可以尝试通过查找字符串“function”来检测函数的创建。例如,从您的 C/C++ 后端。
如果出现“函数”,则会抛出“不允许创建函数”错误,并且不执行代码。
一些注意事项:
string
表就有几个这样的函数。如果不创建函数,用户将很难使用字符串(使用函数已经已经够困难了...)You can try detecting the creation of functions by looking for the string "function" before allowing the execution of the lua script. For example from your C/C++ backend.
If "function" appears throw a "you are not allowed to create functions" error and don't execute the code.
A couple notes:
string
table has several of those. Without creating functions, it'll be very difficult for your users to work with strings (it is already difficult enough with functions...)