Lua 沙盒 - 消除函数创建

发布于 2024-10-19 02:15:59 字数 329 浏览 5 评论 0原文

我已经在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

氛圍 2024-10-26 02:15:59

如果您只想计算表达式,您可以尝试以下操作:(

function run(s) return loadstring("return "..s)() end

省略错误处理)

这个简单的解决方案将防止大多数“攻击”,但不能消除它们,因为可以说它

(function () f=function(x) print"hello" end end)()

定义了一个名为 f 的新函数。

最好的选择是使用沙箱,而不用担心用户对环境做了什么,因为它不会是的环境。

If you want to evaluate expressions only, you could try this:

function run(s) return loadstring("return "..s)() end

(error handling omitted)

This simple solution will prevent most `attacks', but not eliminate them because one can say

(function () f=function(x) print"hello" end end)()

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.

天涯沦落人 2024-10-26 02:15:59

在允许执行 lua 脚本之前,您可以尝试通过查找字符串“function”来检测函数的创建。例如,从您的 C/C++ 后端。

如果出现“函数”,则会抛出“不允许创建函数”错误,并且不执行代码。

一些注意事项:

  • 您可能想要尝试更多地自定义检测 - 例如,如果您检测到函数后跟空格和左括号,则仅抛出错误。我把它留作练习。
  • 您应该知道,有一些标准 lua 函数期望用户能够创建函数 - 例如,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:

  • You might want to try to customize the detection a bit more - only throw errors if you detect function followed by blanks and an opening parenthesis, for example. I'm leaving that as an exercise.
  • You should be aware that there are some standard lua functions that kindof expect the users to be able to create functions - for example, the 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...)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文