Sand Boxes

lua-users home
wiki

This page discusses issues relating to sandboxing: running untrusted Lua code in a restricted Lua environment.

A Simple Sandbox

The following is the simplest sandbox and one of the most restrictive:

-- make environment
local env = {}

-- run code under environment
local function run(untrusted_code)
  local untrusted_function, message = loadstring(untrusted_code)
  if not untrusted_function then return nil, message end
  setfenv(untrusted_function, env)
  return pcall(untrusted_function)
end

-- test
assert(run [[function f(x) return x^2 end; t={2}; t[1]=f(t[1])]])

Code in this sandbox can create variables in the sandbox environment, create values of primitive types (thereby allocating memory), and perform computations. There is no limit to memory usage and computation, so the untrusted code could still severely impact system performance unless further restrictions are made. The sandbox does not have access to I/O nor functions and variables outside its environment. The only way for the sandbox to communicate with the external world is by affecting its environment (e.g. getting and setting variables and calling functions in that environment), assuming there is code outside the sandbox that also has access to those variables and functions.

Table of Variables

The following is a list of Lua 5.1 variables with descriptions of how safe they for use in sandbox environments. Note that whether a variable is safe or not may depend on the security requirements of your particular application and your Lua state. No warranty is given that the following listing is complete or correct, but it is only a guideline.

local oldloadstring = loadstring
local function safeloadstring(s, chunkname)
  local f, message = oldloadstring(s, chunkname)
  if not f then
    return f, message
  end
  setfenv(f, getfenv(2))
  return f
end

--DavidManura

Older Comments

Anonymous: Attacks to consider:

See Also


FindPage · RecentChanges · preferences
edit · history
Last edited September 20, 2007 1:23 am GMT (diff)