OpenResty hook (L2)
Ready
The hub proposes this hook for the containers it fits, and nothing changes until a player approves the proposal (Hook proposals). The cheat sheet has the steps by hand.
For services that run Lua inside nginx: OpenResty (and nginx builds with lua-nginx-module), including the frameworks on top of it, such as Lapis. It gets in config-only: one nginx include file mounted into the container next to vulnboxd's read-only hook directory. The image and the Lua code stay untouched. The hook is plain Lua; it reaches the core library through LuaJIT's FFI, which every OpenResty build has.
Covers
| Versions | |
|---|---|
| OpenResty | tested 1.31.1.1 (Debian, glibc) and 1.27.1.2 (official Alpine image, musl); any release with LuaJIT and lua-resty-core |
Outgoing connections (connected) | releases whose lua-resty-core provides tcpsock:getfd(): present in 1.31.1.1, absent in 1.27.1.2 (see Known gaps) |
| Lua clients on cosockets | lua-resty-http, -mysql, -redis, -postgres, -memcached … (they all use ngx.socket.tcp) |
| Lapis, other OpenResty frameworks | covered by the same include (not sampled: see Known gaps) |
| Plain nginx without Lua | not covered (below) |
What the kernel already links, without this hook. Nothing per request: an nginx worker serves many connections from one event loop, so the kernel can't tell which request a fork, file or connection belongs to. Process lineage still links whole workers.
Plain nginx as a reverse proxy (no Lua). There is no hook, because nothing can run inside the worker without a module. The sensor can link a proxied upstream connection to the client request only when nginx opens one upstream connection per request (no keepalive in the upstream block, which is nginx's default). It can then match the client connection to the upstream connect by timing within the worker. With upstream keepalive, requests share upstream connections and the link is not exact. A dedicated nginx C module would be needed for that; it is out of scope. The upstream service's own hook still links what happens behind it.
How it gets in
From a registry (local development, or a build with network; the same release as the hook directory): opm get vulnboxd/lua-resty-vbxtrace and luarocks install vbxtrace 1.0.0-1 (the core); see Local development.
Config-only (default), for images that include /etc/nginx/conf.d/*.conf inside http {}. This includes the official openresty/openresty images. The hub proposes:
services:
<service>:
+ volumes:
+ - /usr/local/lib/vulnboxd/trace:/opt/vbxtrace:ro
+ - /usr/local/lib/vulnboxd/trace/openresty/vbxtrace.conf:/etc/nginx/conf.d/zz-vbxtrace.conf:roThe include contains only three http-level directives, each of which only calls into the hook:
rewrite_by_lua_block { ... v.begin() } # start the request
access_by_lua_block { ... v.begin() } # (whichever of the two runs first)
log_by_lua_block { ... v.finish() } # end itThe module /opt/vbxtrace/openresty/vbxtrace.lua is loaded on first use in each worker, by absolute path (dofile, cached in package.loaded). The include therefore takes none of the directives an app usually owns and that nginx allows only once per http block: lua_package_path, init_by_lua*, init_worker_by_lua*.
The hub proposes this when it detects any of:
- an
openresty/openresty,bitnami/openrestyorleafo/lapisimage; openrestyorlapis serverin the command;- an nginx configuration using
*_by_lua; - a Lapis
config.lua/config.moon, or a rockspec depending on Lapis or lua-resty-*.
The template is hooks/lua/l2/proposals/openresty.toml.
Source change, for a custom nginx.conf (Lapis's compiled nginx.conf, images that don't include conf.d). Add the hook mount and one line inside http {}:
+env VBXTRACE;
events { worker_connections 1024; }
http {
+ include /opt/vbxtrace/openresty/vbxtrace.conf;
include mime.types;The template is hooks/lua/l2/proposals/include.toml (with include.diff).
env VBXTRACE; nginx clears the environment of its workers except for variables declared with env in the main context. The hook can't read the original environment either: the worker's /proc/self/environ is overwritten by nginx's process title, and the master's is unreadable to the worker user. So VBXTRACE=0 switches the hook off only if nginx.conf declares env VBXTRACE;. Without it, remove the include to switch it off.
Location-level overrides. nginx replaces an inherited *_by_lua directive in any location that sets its own for the same phase:
- A location with its own
access_by_lua*: the inheritedrewrite_by_lua_blockstill starts the request (shown by the sample's/own-access). - A location with its own
rewrite_by_lua*andaccess_by_lua*: the first wrapped call (cosocket connect,io.open,os.execute,ngx.pipe.spawn,ngx.timer.at) in the content phase starts the request instead, at that point. - A location with its own
log_by_lua*: the request gets norequest_end. To keep both, call the hook from the location's own block:local v = package.loaded["vbxtrace.openresty"]; if v then v.finish() end.
What it records
| Event | Emitted from | Join key |
|---|---|---|
request_begin | rewrite or access phase (the first of ours that runs) | $server_port (the accepted socket's local port); $realip_remote_addr/$realip_remote_port (the socket's peer even when real_ip rewrites $remote_addr), else $remote_addr/$remote_port; request index = $connection_requests − 1 |
request_end | log phase, with ngx.status | context id |
connected | the cosocket method connect (shared by every ngx.socket.tcp object), after a new connection was established; local port and peer from getsockname/getpeername on tcpsock:getfd() | local port |
spawned | ngx.pipe.spawn, with proc:pid() | child pid |
context_enter / context_exit | around os.execute, io.popen and io.open: they block the worker, so the fork or open in that window is exactly this request's | the thread |
handoff | ngx.timer.at called during a request: the timer callback gets its own context, handed off from the request's | parent and child context ids |
Protocol: http1, http2 when $server_protocol is HTTP/2, websocket for an Upgrade: websocket request. Subrequests (ngx.location.capture) belong to their parent request and are not reported separately.
Context following
- Per request:
ngx.ctx. It follows the request through every phase, every cosocket yield andngx.thread.spawnlight threads, which run in the request's context automatically. - Internal redirects (
try_files … @named,error_page,ngx.exec) resetngx.ctx. The hook keeps the request's context in a per-worker table keyed by$connection/$connection_requests, so the redirected location continues the same request: onerequest_begin, onerequest_end(the sample's/redirect). The table is cleared in the log phase and capped at 4096 entries. - Timers (
ngx.timer.at) run outside any request. A one-shot timer created during a request gets a new context, linked byhandoff, and its blocking calls run in that context's windows.ngx.timer.everyrepeats indefinitely, so it is not linked. - Windows are used only around calls that can't yield. A cosocket call yields to other requests in the middle, so a window around it would be wrong; connects report
connectedinstead.
Known gaps
connectedneedstcpsock:getfd()(lua-resty-core). Without it there is no exact way to learn a cosocket's local port, so no event is sent. Verified: 1.31.1.1 has it, the 1.27.1.2 Alpine image doesn't. Reused keepalive connections (getreusedtimes() > 0) were established for an earlier request and are not reported again.- UDP cosockets (
ngx.socket.udp) andngx.socket.connectstream sockets in thestreamsubsystem are not wrapped. - Functions captured before the hook's first request keep the unwrapped version, because the wrappers are installed when a worker's first traced request starts. Examples:
local timer_at = ngx.timer.atorlocal spawn = require("ngx.pipe").spawnininit_by_lua. The cosocket method table is patched in place, soconnectis always covered. io.openis linked through its window, not by an explicitopenedwith the fd. LuaJIT's file objects expose no descriptor safely.- Body and header filter phases (
header_filter_by_lua,body_filter_by_lua) start no request. - Lapis is not sampled. It needs luarocks with C dependencies in the image. It runs on the same OpenResty phases and cosockets, so the include applies unchanged; add it to Lapis's
nginx.confwith the source proposal. - HTTP/2 request index: the index comes from
$connection_requestsas nginx reports it; HTTP/2 is not sampled.
Safety
What is wrapped, per worker, from its first traced request:
- the cosocket method
connect; io.open,io.popen,os.execute;ngx.pipe.spawn(the hook loadsngx.pipefrom lua-resty-core);ngx.timer.at.
How it stays invisible:
- Every wrapper returns exactly what the original returned and raises what it raised. Window wrappers re-raise the original error value unchanged.
- The hook's own work runs under
pcall. After 5 internal errors it switches itself off for the worker. - Without a tracer attached when a request starts (
vbx_v1_enabled()false), the request gets no context and every wrapper passes straight through. - The C declarations are made one at a time under
pcall, so an app's ownffi.cdefof e.g.getsocknamedoesn't conflict. VBXTRACE_CHAOS=1(tests only, needsenv VBXTRACE_CHAOS;) makes every call into the core fail. The samples answer byte-identically with the hook failing, working and absent.
Overhead has not been measured yet; that's a later phase.
Turning it off
Remove the include (or the mount that provides it) and reload nginx, or revert the change that added the hook; vulnboxd's rollback covers a hook that breaks a service. With env VBXTRACE; in nginx.conf, setting VBXTRACE=0 and restarting switches it off too.
Troubleshooting
Are the probes there?
readelf -n /usr/local/lib/vulnboxd/trace/libvbxtrace-x86_64.solists them;sudo bpftrace -l 'usdt:/usr/local/lib/vulnboxd/trace/libvbxtrace-x86_64.so:*'too.Is the hook loaded? After the first request,
grep vbxtrace /proc/<worker pid>/mapsshowslibvbxtrace-<arch>.so. Ifnginx -tcomplains about a duplicaterewrite_by_lua,access_by_luaorlog_by_lua, the app sets one at http level itself: use the source proposal and callv.begin()/v.finish()from the app's own blocks.Which links did a flow get? The hub shows each link's method; this package's are
hook:L2.No
request_endfor some locations: they set their ownlog_by_lua(see "Location-level overrides").No
connectedevents: checktcpsock:getfdexists:shgrep -c getfd /usr/local/openresty/lualib/resty/core/socket.lua0means an older lua-resty-core.VBXTRACE=0has no effect: addenv VBXTRACE;to the main context ofnginx.conf.