Improved sandbox

Posted by Nick Gammon on Sun 05 Nov 2006 09:35 PM — 1 posts, 6,419 views.

Australia Forum Administrator #0
There is a problem that often seems to happen to people when starting to use Lua scripting, which is that they run foul of the Lua "sandbox" which is a default set of restrictions placed on Lua scripts by MUSHclient.

The problem is that the original sandbox set various functions (like io.open, os.execute) to nil, and then attempts to use them were met with a confusing error message, like "attempt to index global 'io' (a nil value)".

Version 3.83 of MUSHclient changes this behaviour to replace such functions with a special "error" function that simply reports that the original function was disabled, like this:


Function 'io.open' disabled in Lua sandbox - see MUSHclient global preferences


To retrofit this functionality into existing MUSHclient installations, edit the Lua sandbox (in File -> Global Preferences) and change from:


function MakeSandbox ()

--->  down to ---->

end -- end of function MakeSandbox



... to read like this instead:


function MakeSandbox ()

  local function ReportDisabled (pkg, func)
     return function ()
       error (string.format (
        "Function '%s.%s' disabled in Lua sandbox - see MUSHclient global preferences",
        pkg, func), 2)
       end -- function
  end -- ReportDisabled 

  package.loadlib = ReportDisabled  ("package", "loadlib") -- disable loadlib function
  package.loaders [3] = nil  -- disable DLL loader
  package.loaders [4] = nil  -- disable all-in-one loader

  for k, v in pairs (io) do
    if type (v) == "function" then
      io [k] = ReportDisabled ("io", k)
    end -- type is function
  end -- for

  local orig_os = os -- so we know names of disabled ones

  -- replace 'os' table with one containing only safe functions
  os = {
       date = os.date,
       time = os.time, 
       setlocale = os.setlocale,
       clock = os.clock, 
       difftime = os.difftime,
       }

  for k, v in pairs (orig_os) do
    if not os [k] and type (v) == "function" then
      os [k] = ReportDisabled ("os", k)
    end -- not still active
  end -- for

   if warn_if_not_trusted then
     ColourNote ("yellow", "black", 
                 "Lua sandbox created, some functions disabled.")
   end -- if warn_if_not_trusted

end -- end of function MakeSandbox