Bug #9056
closedlua: userdata metatable forgery -> FFI type confusion in unsandboxed states
Description
- Status: present in
main(9b7938aec); class-level hardening finding - Class: FFI type confusion / heap corruption possible from a script when metatables can be forged
- Component: all userdata-backed Lua libs; concrete example
src/util-lua-hashlib.c+rust/src/ffi/hashing.rs
Description¶
Every Lua lib validates objects with luaL_checkudata(), which compares the object's metatable with the registry metatable. When setmetatable / debug.setmetatable is reachable, a script can give one library's userdata another library's metatable; the check then passes and the C/FFI code reinterprets the payload pointer as the wrong type.
Concrete example (hashlib):
local hashing = require("suricata.hashlib")
local h = hashing.md5()
setmetatable(h, getmetatable(hashing.sha256()))
h:update("A")
h:finalize()
LuaHashLibSha256Update/Finalize pass the pointer to SCSha256Update/Finalize and Box::from_raw it as SCSha256 (rust/src/ffi/hashing.rs:51/121/186) although it is an SCMd5 allocation - wrong struct layout and wrong drop size (__gc has the same exposure). That is a heap-corruption primitive. The same forgery applies to the other userdata libs (packet, flow, file, rule, tls, http, dns, smtp, ssh, ntp, ja3), each with its own payload type.
Reachable in the unsandboxed output states (by design) and with security.lua.allow-restricted-functions: true; not reachable in the default rule/luaxform sandbox (setmetatable, getmetatable, debug are blocked). It does not cross a privilege boundary in output states, but it violates the "a script bug must not corrupt the engine" robustness goal and becomes a sandbox-integrity hazard if the sandbox rules ever change.
Fix direction¶
Do not rely on metatable identity alone: put an immutable type tag/magic inside each userdata (e.g. a uint32_t type_id field) and validate it in every method (and __gc) before using the payload. A shared helper (check_userdata_typed(L, idx, expected_id)) keeps it uniform across libs.
Test¶
lua-metatable-forgery: an output script swaps metatables between hashlib algorithms and between flow/packet/http handles and calls the methods under ASAN; the calls must fail cleanly (Lua error), not corrupt memory.
VJ Updated by Victor Julien about 2 months ago
- Status changed from New to In Progress
- Assignee changed from OISF Dev to Victor Julien
JI Updated by Jason Ish about 1 month ago
- Status changed from In Progress to In Review
MR1382