0Pricing
Lua Academy · Lesson

Building a Restricted Sandbox

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

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

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