Global environment leakage from restricted setfenv environment tables
0 reputation · 14 Aug 2023, 20:58 UTC
In Lua 5.1, replacing a function's environment with a restricted table via setfenv is a common least-privilege pattern for blocking io and os. Lua 5.2 removed setfenv in favor of _ENV upvalues, shifting environment switching to compile time, yet the isolation guarantee is expected to remain equivalent for pure Lua code.
An unresolved concern is whether a sandboxed function can recover the true global environment through metatable manipulation—for example, by following an __index chain or capturing a reference before the environment is swapped—or through C-API calls that bypass the Lua-level environment table. If such a path exists, the restricted table is not a security boundary.
Assuming a Lua 5.1 interpreter without hostile C extensions, what is the authoritative behavior when a function's environment is replaced with a table whose metatable lacks a __index fallback to _G? Can a pure Lua function inside that environment still reach the original global table, and if so, through which documented mechanism? How should this be verified across Lua 5.1 and 5.2+ without relying on version-specific error strings?