simplification
Download
251 lines 11.8 KiBMoonScriptModified 2026-11-09 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
-- This file makes sandboxes for running untrusted Nomsu code. A sandbox has two parts:
--  * A compile context, which has the compiler and the compile rules the sandbox allows.
--    Compile rules get the compile context, but sandboxed code never does.
--  * A runtime environment, which is the only environment sandboxed code runs in. It only
--    has values that are safe to give to untrusted code: safe Lua functions, copies of
--    Lua's libraries, the core language, and what the program running Nomsu provides.
-- Anything that isn't specifically allowed is left out.
Errhand = require "error_handling"
Text = require "text"
SyntaxTree = require "syntax_tree"
{:LuaCode, :NomsuCode, :Source} = require "code_obj"
{:fail_at} = require "nomsu_compiler"
Files = require "files"
bootstrap = require "bootstrap"
Limits = require "nomsu_limits"

-- Metatables that every Nomsu instance (and the program running Nomsu) shares, which
-- sandboxed code mustn't be able to get, since it could change them
shared_metatables = {
    [getmetatable("")]: true, [Errhand.ExitSignal]: true, [SyntaxTree.__base]: true,
    [LuaCode.__base]: true, [NomsuCode.__base]: true, [Source.__base]: true,
}
safe_getmetatable = (x)->
    mt = getmetatable(x)
    return nil if shared_metatables[mt]
    return mt

-- A sandbox mustn't attach a __gc metamethod, since the finalizer would run later in the
-- program that's running Nomsu, outside the sandbox's limits
safe_setmetatable = (t, mt)->
    if type(mt) == 'table' and rawget(mt, "__gc") != nil
        error("A sandbox can't use the __gc metamethod.", 2)
    return setmetatable(t, mt)

-- A view of a table that can't be changed (and can't have its metatable changed)
read_only = (t, call)->
    return setmetatable {}, {
        __index: t, __call: call and ((_, ...)-> call(...)) or nil,
        __newindex: -> error("This can't be changed.", 2)
        __metatable: false
    }

copy = (t)-> {k,v for k,v in pairs(t)}
-- Copies of Lua's libraries for a sandbox, which check the limits in functions that can
-- match patterns or make a lot of text in one call
limited_table_library = ->
    lib = copy(table)
    lib.concat = Limits.checking_memory_after(table.concat)
    return lib

-- Values that sandboxed code can't have, even if a module exports them under another name
dangerous_values = {}
-- (Some of these don't exist in every version of Lua, so they're looked up by name)
for name in *{"io", "os", "package", "debug", "jit"}
    if lib = _G[name]
        dangerous_values[lib] = true
        for _,v in pairs(lib) do dangerous_values[v] = true
for lib in *{Files, require('lpeg'), require('re')}
    dangerous_values[lib] = true
    for _,v in pairs(lib) do dangerous_values[v] = true
for name in *{"require", "load", "loadstring", "loadfile", "dofile", "getfenv", "setfenv", "collectgarbage"}
    dangerous_values[_G[name]] = true if _G[name]
dangerous_values[getmetatable] = nil -- This is replaced with safe_getmetatable
-- The real string library is the __index of the string metatable that everything shares,
-- so sandboxed code mustn't be able to change it (its functions are fine)
dangerous_values[string] = true

-- The safe form of a value for a sandbox: nil if it's dangerous, the safe version of the
-- shared Lua functions, or the value itself
safe_value = (v)->
    return nil if dangerous_values[v]
    return safe_getmetatable if v == getmetatable
    return safe_setmetatable if v == setmetatable
    return v

-- The Lua functions and Nomsu helpers that sandboxed code can use. These are made for each
-- sandbox, so that sandboxes can't change each other's (or Nomsu's) libraries.
safe_base_values = (environment)->
    -- Errors only show code that this instance has run, so (fail) can't show other files
    sources = environment.SOURCES
    safe_fail_at = (source, msg)->
        filename = if type(source) == 'string' then Source\from_string(source).filename
        elseif Source\is_instance(source) then source.filename
        elseif SyntaxTree\is_instance(source) then source.source.filename
        if filename and rawget(sources, filename)
            return fail_at(source, tostring(msg))
        error(tostring(msg), 0)
    -- The exit code is always a number, since the program running Nomsu gets it, and
    -- anything else could run sandboxed code (e.g. with __tostring) outside the limits
    safe_exit = (code=0)-> Errhand.exit_signal(tonumber(code) or 1)
    return {
        :next, :select, :tonumber, :tostring, pairs: environment.pairs, :ipairs, :error,
        pcall: Limits.pcall, xpcall: Limits.xpcall, :assert, :rawequal, :rawlen, :rawget, :rawset, setmetatable: safe_setmetatable,
        getmetatable: safe_getmetatable, unpack: unpack or table.unpack, lua_type_of: type,
        yield: coroutine.yield, resume: Limits.resume, coroutine_status_of: coroutine.status,
        coroutine_wrap: Limits.wrap, coroutine_from: coroutine.create,
        coroutine_values: environment.coroutine_values,
        math: copy(environment.math), string: Limits.limited_string_library!, table: limited_table_library!,
        Text: read_only(Text, Limits.checking_memory_after(Text)),
        _VERSION: environment._VERSION, LUA_VERSION: environment.LUA_VERSION,
        LUA_API: environment.LUA_API, NOMSU_VERSION: copy(environment.NOMSU_VERSION),
        enhance_error: Errhand.enhance_error, IS_EXIT_SIGNAL: Errhand.is_exit_signal,
        exit: safe_exit, quit: safe_exit,
        at_1_fail: safe_fail_at,
        _1_as_nomsu: environment._1_as_nomsu, _1_as_inline_nomsu: environment._1_as_inline_nomsu,
        _1_as_text: environment._1_as_text, _1_deeply_equals: environment._1_deeply_equals,
        _1_fields_as_text: environment._1_fields_as_text,
    }

-- Fields that Nomsu uses to run environments, which sandboxed code never gets
internal_names = {
    _ENV: true, _G: true, _IMPORTS: true, COMPILE_RULES: true, PUBLIC_COMPILE_RULES: true,
    TESTS: true, MODULE_NAME: true, globals: true, _rules_before_public: true,
    _tests_to_compile: true, COMPILING_TESTS: true, WAS_RUN_DIRECTLY: true,
}

-- The core modules that sandboxed code can use
safe_core_modules = {
    "core/collections": true, "core/control_flow": true, "core/coroutines": true,
    "core/errors": true, "core/math": true, "core/operators": true, "core/text": true,
    "core/io": true,
}

-- Most of core/metaprogramming is for writing compile rules and running code, which
-- sandboxed code can't do, but these parts are just part of the language
safe_metaprogramming = {
    -- Values:
    _1_is: true, _1_is_text: true, _1_isn_x27_t_text: true, _1_is_not_text: true,
    type_of: true, quote: true,
    -- Compile rules:
    "* extra arguments *": true, "->": true, "1 ->": true, "1 means": true,
    "1 all mean": true, "1 is not": true, "1 isn ' t": true, "nil": true, "no": true,
    "yes": true, "return": true,
}

-- The bootstrap compile rules that sandboxed code can use (the rest are for inline Lua,
-- modules, and running files)
safe_bootstrap_rules = {
    "": true, "local": true, "local 1 =": true, "public": true, "public 1 =": true,
    "Lua version": true, "is jit": true, "use": true, "export": true,
}

-- Iterate over an environment's (or compile rule table's) own fields and its imports
visible_fields = (t)->
    return coroutine.wrap ->
        seen = {}
        for k,v in pairs(t)
            seen[k] = true
            coroutine.yield k, v
        for k,v in pairs(rawget(t, "_IMPORTS") or {})
            coroutine.yield k, v unless seen[k]

-- Make a sandbox from an instance's environment, keeping only what's safe. host_names are
-- the names of values that the program running Nomsu added to the environment, which the
-- sandbox keeps.
-- Returns the sandbox's compile context.
make_sandbox = (environment, host_names)->
    module_allowed = (name, key)->
        if safe_core_modules[name] then return true
        if name == "core/metaprogramming" then return safe_metaprogramming[key] or false
        return false

    -- Which values and compile rules come from core modules, and whether they're allowed.
    -- If any module disallows something, it's not allowed.
    core_values, core_rules = {}, {}
    host_values, host_rules = {}, {}
    for name, mod in pairs(environment.LOADED_MODULES)
        continue unless type(name) == 'string' and not name\match("%.")
        if name\match("^core/") or name == "core"
            continue if name == "core" -- Everything in core comes from a core/ module
            for k,v in pairs(mod)
                continue if internal_names[k]
                core_values[v] = (core_values[v] != false) and module_allowed(name, k)
            for k,v in pairs(rawget(mod, "PUBLIC_COMPILE_RULES") or {})
                core_rules[v] = (core_rules[v] != false) and module_allowed(name, k)
        else
            -- Modules that the program running Nomsu loaded before sealing
            for k,v in pairs(mod)
                host_values[v] = true unless internal_names[k]
            for k,v in pairs(rawget(mod, "PUBLIC_COMPILE_RULES") or {})
                host_rules[v] = true

    runtime = {}
    base = safe_base_values(environment)
    for k,v in visible_fields(environment)
        continue if internal_names[k]
        if base[k] != nil
            runtime[k] = base[k]
        elseif dangerous_values[v]
            continue
        elseif core_values[v] != nil
            if core_values[v]
                -- Core values that are the shared, unsafe Lua functions (which core may
                -- have captured before sealing) get the sandbox's safe versions
                runtime[k] = switch v
                    when getmetatable then safe_getmetatable
                    when setmetatable then safe_setmetatable
                    else v
        elseif host_names[k] or host_values[v]
            runtime[k] = v
    runtime._ENV = runtime
    runtime._G = runtime

    rules = {}
    for stub, rule in visible_fields(environment.COMPILE_RULES)
        continue if stub == "_IMPORTS"
        allowed = if bootstrap[stub] == rule then safe_bootstrap_rules[stub]
        elseif core_rules[rule] != nil then core_rules[rule]
        else host_rules[rule]
        rules[stub] = rule if allowed

    context = environment.new_environment!
    context.MODULE_NAME = "sandbox"
    context.COMPILE_RULES = rules
    context.RUNTIME_ENV = runtime

    -- The safe exports of each module that was loaded before sealing, which sandboxed
    -- code can bring into scope with (use). A sandbox can't load new modules from disk.
    sandbox_modules = {}
    for name, mod in pairs(environment.LOADED_MODULES)
        continue unless type(name) == 'string' and not name\match("%.")
        is_core = name == "core" or name\match("^core/")
        values, module_rules = {}, {}
        for k,v in pairs(mod)
            continue if internal_names[k]
            -- Only the core values that sandboxed code is allowed
            continue if is_core and not core_values[v]
            sv = safe_value(v)
            values[k] = sv if sv != nil
        for k,rule in pairs(rawget(mod, "PUBLIC_COMPILE_RULES") or {})
            continue if is_core and not core_rules[rule]
            module_rules[k] = rule
        sandbox_modules[name] = {:values, rules: module_rules}

    -- (use) in a sandbox brings a pre-loaded module's safe exports into scope. Like (use)
    -- normally, it runs at compile time, so later code can use what it imports.
    import_module = (package_name)->
        mod = sandbox_modules[package_name]
        unless mod
            error("The module '#{package_name}' isn't available in this sandbox. A sandbox "..
                "can only use modules that were loaded before it was sealed.", 0)
        for k,v in pairs(mod.values)
            runtime[k] = v
        for k,rule in pairs(mod.rules)
            rules[k] = rule
        return nil
    runtime.use = (package_name)=> import_module(package_name)
    runtime.export = runtime.use
    return context

return {:make_sandbox}