LU

Lua Security

Lua security practices: sandbox isolation, input validation, and safe environment configuration

Details

Language / Topic
luaLua
Category
Security

Rules

balanced
- Never use `loadstring(user_input)()` or `load(user_input)()` — executing user-supplied Lua code is equivalent to remote code execution.
- Restrict sandboxed code by setting a custom environment: `load(code, 'sandbox', 't', sandbox_env)` with only safe functions exposed.
- Validate all external inputs (HTTP query params, file content, IPC messages) before passing to Lua functions that interpret them as data.
- Remove dangerous functions from sandbox environments: nil out `os.execute`, `io.popen`, `require`, `dofile`, and `loadfile` before exposing the environment.
- Use `string.format` with explicit format strings when building output from user data — never use `string.format('%s', user_table)` without validating type.
- Limit `pcall`-wrapped sandboxed code execution time using a debug hook: `debug.sethook(co, function() error('timeout') end, '', N)`.
- Store secrets in environment variables accessed via `os.getenv('SECRET_KEY')` — never hardcode credentials in Lua source files.