lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

I am writing a program where an external user script is loaded and
executed. Therefore it is AFAIK good practice to implement a sandbox which
restricts the user to use only a certain set of functions. Still I would
like to enable the user to use most of Lua's functions and restrict only
those functions which would enable the user to break the sandbox and e.g.
access _G.

E.g. I found out that it is not enough to call loadfile("external_file")
with a restricted environment because if external_file loads a second
external file this has access to the global environment again. What I did
was to implement some code like this:

function envloadfile(file)  -- secure loadfile
  local x
  x = loadfile(file)
  setfenv(x, env)
  return x

env = {loadfile=envloadfile}  -- see comment

local f,ret,err
f = envloadfile("external_file")
ret,err = pcall(f)

I know that the env environment is very restrictive and is there for test
purposes only. But as far as I can tell it works (second external file is
in restricted environment).

My first question is: Is the above code ok, or would you implement it in
another way?

My second question is: What other functions need to be either blocked or
restricted so that the user has no chance to break the sandbox? For
example, do I need to block the setfenv function?

The third question is: Instead of defining which functions are allowed one
by one, I would rather like to copy an existing environment (_G) and
change it. I tried this with the following code:

function table.copy(data)  -- taken from book "Lua Programming", p149
  local t = {}
  for Key, Val in pairs(data) do
    Key = type(Key) == "table" and table.copy(Key) or Key
    Val = type(Val) == "table" and table.copy(Val) or Val
    t[Key] = Val
  return t

env = table.copy(_G)
env.loadfile = envloadfile

The problem is that the table.copy function runs infinitely. I guess this
is because _G refers to itself. But I do not know how to avoid that.

Thank you very much,

...using RiscLua 4.14, built from Lua 5.1.3