有没有办法避免 Lua 中的这个安全问题? [英] Is there anyway to avoid this security issue in Lua?
问题描述
我只是在研究可本地化的 Lua 字符串解决方案,当我想出这个 hack 时,问题是我不知道如何避免被它攻击 :)所以我想知道是否有人做过类似的事情,或者知道如何防止这种攻击.(在用户代码中)
I was just working on a localizable Lua string solution, when I came up with this hack, problem is I don't know how to avoid getting hacked by it :) So I was wondering if anyone, has done something similar and or knows how to protect from this kind of attack. (in user code)
既然我们可以这样做:
=("foo"):upper() -->output: FOO
它可以像这样被黑客入侵:
It can be hacked like this:
getmetatable("foo").__index.upper = function() print("bye bye sucker");os.exit() end
=("foo"):upper() -->output: bye bye sucker (application quits)
-- or this way
=string.upper("bar") -->output: bye bye sucker (application quits)
有什么想法吗?
推荐答案
首先,也是最重要的,只在沙盒环境中执行不受信任的代码——正如其他海报所说的那样.除了加载字节码块,Lua 允许涵盖所有其他沙盒问题.(并且字节码块问题会在发现后立即得到修复.)
First and foremost execute untrusted code in sandboxed environment only – as it was said by other posters. Except for loading bytecode chunks, Lua allows all other sandboxing issues to be covered. (And bytecode chunk problems get fixed promptly as discovered.)
请参阅 Lua Live Demo 以获取沙盒示例.来源在这里.
See Lua Live Demo for an example of sandboxing. Sources are available here.
通过设置 __metatable
字段可以解决元表的具体问题:
Your specific problem with metatables is solved by setting a __metatable
field:
如果您在元表中设置了 __metatable
字段,getmetatable
将返回该字段的值,而 setmetatable
会引发错误.
If you set a
__metatable
field in the metatable,getmetatable
will return the value of this field, whereassetmetatable
will raise an error.
– Roberto Ierusalimschy,Lua 编程第 1 版,13.3 - 库定义的元方法
– Roberto Ierusalimschy, Programming in Lua 1st edition, 13.3 - Library-Defined Metamethods
例如:
> mt = { __metatable = true }
> t = {}
> setmetatable(t, mt)
> setmetatable(t, mt)
stdin:1: cannot change a protected metatable
stack traceback:
[C]: in function 'setmetatable'
stdin:1: in main chunk
[C]: ?
所以,你所要做的就是:
So, all you have to do is:
getmetatable("").__metatable = true
这篇关于有没有办法避免 Lua 中的这个安全问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!