Lua Academy · Lesson

Building a Restricted Sandbox

Create a safe _ENV whitelist and execute untrusted code with load().

Lesson 2 of 412 steps

Building a Restricted Sandbox is a free Lua Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.

Goal

A restricted sandbox lets you run untrusted Lua code safely: it can compute, use strings and math, but cannot access the filesystem, OS, or network.

Whitelist Approach

Build the sandbox environment from scratch, including only safe, well-understood functions.

local function makeSandbox()
  return {
    print   = print,
    type    = type,
    tostring = tostring,
    tonumber = tonumber,
    pairs   = pairs,
    ipairs  = ipairs,
    next    = next,
    select  = select,
    unpack  = table.unpack,
    error   = error,
    pcall   = pcall,
    xpcall  = xpcall,
    math    = math,
    string  = { format=string.format, find=string.find,
                match=string.match, gmatch=string.gmatch,
                gsub=string.gsub, sub=string.sub,
                len=string.len, byte=string.byte, char=string.char },
    table   = { insert=table.insert, remove=table.remove,
                concat=table.concat, sort=table.sort,
                unpack=table.unpack, move=table.move },
  }
end

Running Code in the Sandbox

Load and execute user code with the sandbox as its _ENV.

local function runSandboxed(code, env)
  local fn, err = load(code, "user", "t", env)
  if not fn then return nil, err end
  return pcall(fn)
end
local env = makeSandbox()
local ok, err = runSandboxed("return 1+1", env)
print(ok, err)  -- true  2

Capturing Output

Replace print with a custom function that appends to a buffer instead of writing to stdout.

local output = {}
env.print = function(...)
  local parts = {}
  for i = 1, select("#", ...) do
    parts[i] = tostring(select(i, ...))
  end
  output[#output+1] = table.concat(parts, "\t")
end

Returning Values

To allow the sandboxed code to return values, call the compiled chunk as a function and capture its return values.

local fn = load("return math.sqrt(144)", "user", "t", env)
if fn then
  local ok, result = pcall(fn)
  print(ok, result)  -- true  12.0
end

Blocking Metamethod Exploits

Sandboxed code should not get references to metatables or rawget/rawset to avoid bypassing field restrictions.

Limiting String Length

Override string operations to limit output length and prevent DoS via huge string allocations.

Resource Limits with debug.sethook

Add an instruction counter hook to terminate runaway code.

local function sandboxWithLimit(code, env, maxOps)
  local ops = 0
  debug.sethook(function()
    ops = ops + 1
    if ops > maxOps then error("Instruction limit exceeded") end
  end, "", 100)
  local result = table.pack(runSandboxed(code, env))
  debug.sethook()
  return table.unpack(result, 1, result.n)
end

Testing the Sandbox

Write tests that try known escape vectors: accessing _G, calling load, using debug, and verify they all fail.

Known Escape Vectors

Common escape routes: string.rep("x",2^30) (memory DoS), ({}).__index on standard objects, debug via string metatable, io via package.loaded.

Sandbox Question

Why does a sandbox not include load or dofile?

Recap: Building a Restricted Sandbox

Whitelist only safe functions in a custom env table. Use load(code, name, "t", env). Add instruction counting with debug.sethook. Test escape vectors. Never include load, dofile, debug, or global table access.

Free to start

Learn Lua with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
40
Lessons
159

Frequently Asked Questions

Is the “Building a Restricted Sandbox” lesson free?

Yes — any 3 lessons of the Lua Academy learning path, including “Building a Restricted Sandbox”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.

What will I learn in “Building a Restricted Sandbox”?

Create a safe _ENV whitelist and execute untrusted code with load(). You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Building a Restricted Sandbox” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The _ENV Model in Lua 5.2+
  2. Building a Restricted Sandbox
  3. Preventing Sandbox Escapes
  4. Resource Limits and Instrumentation
← Back to Lua Academy