1
votes

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!

2
If this is possible (I doubt it): Please don't do this. Not to mention that you'd remove an important part of the language (not of the library, of the language - as if an embedded device didn't support pointers in their weird C offshot!), that also means you'd severely damage the versatility and expressiveness of whatever scripts are written in your embedded Lua. - user395760
if you disallow functions, you disallow lambdas. if you disallow lambdas you disallow an entire class of simple expressions. - Chris Becke

2 Answers

6
votes

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.

1
votes

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