开发者

Lua Sandboxing - Eliminating Function Creation

开发者 https://www.devze.com 2023-02-13 14:34 出处:网络
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 sampl

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 [[开发者_Go百科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!


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.


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...)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号