Erlang / Elixir hook (E1)
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.
The hook for services on the BEAM: Erlang and Elixir, with Cowboy, Plug.Cowboy, Bandit, Phoenix, Elli, ranch protocols and hand-written gen_tcp servers. It loads vulnboxd's core library into the node through a small NIF and follows each request with the BEAM's own tooling, call tracing and :telemetry, so it needs no code change and no configuration in the service. It gets in with a compose-only change: a read-only mount of the hook directory and one environment variable, ERL_AFLAGS (or ELIXIR_ERL_OPTIONS for Elixir releases). The image and the source stay untouched.
Covers
| Versions | |
|---|---|
| Erlang/OTP | 24–28 (one build of the hook for all of them) |
| Elixir | any on those OTP versions (tested: 1.17, 1.18) |
| C library | glibc (Debian-based images) and musl (Alpine); x86_64 and aarch64 |
| Cowboy | 2.x (tested: 2.12, with ranch 1.8), plain Erlang or through Plug.Cowboy (tested: 2.7) |
| Bandit | 1.x (tested: 1.13), with Plug or Phoenix |
| Phoenix | on Bandit or Cowboy (tested: Phoenix 1.8 on Bandit, as a mix release) |
| Elli | 3.x (tested: 3.3) |
| ranch | 1.6+ and 2.x raw protocols (tested: 2.1) |
gen_tcp | accept loops that hand each connection to a process |
| Ways to start | erl, rebar3, mix run, mix phx.server, iex, elixir, mix releases (bin/<name> start, embedded mode) |
Tested on these sample services, each in the events, chaos and baseline modes (see Safety), on x86_64:
| Sample | Image | Server | Started with |
|---|---|---|---|
gen_tcp | erlang:24-slim (glibc) | hand-written accept loop | erl -s |
ranch | erlang:25-slim (glibc) | ranch 2.1 raw protocol | erl -s |
cowboy | erlang:26-alpine (musl) | Cowboy 2.12 | erl -s |
elli | erlang:27-slim (glibc) | Elli 3.3 | erl -s |
bandit | elixir:1.17-otp-27-alpine | Plug on Bandit 1.13 | mix run --no-halt |
plug_cowboy | elixir:1.17-otp-27-alpine | Plug on Plug.Cowboy 2.7 | mix run --no-halt |
phoenix | elixir:1.18-otp-28 (glibc) | Phoenix 1.8 on Bandit | mix release, bin/sample start, ELIXIR_ERL_OPTIONS |
On aarch64 the gen_tcp (OTP 24, glibc) and cowboy (OTP 26, musl) samples were run the same way under qemu and match their expected events, with chaos responses identical. The single NIF and the .beam files were also loaded on OTP 24, 25, 26, 27 and 28, glibc and musl, x86_64, with every probe firing.
What the kernel links without the hook: nothing. BEAM processes are not OS threads: a handful of scheduler threads run all of the node's processes, so neither the kernel's process rule nor its thread rule ever applies, and every BEAM service needs the hook to link a request to what it does.
How it gets in
From a registry (local development, or a build with network; the same release as the hook directory): Hex: {:vbxtrace, "== 1.0.0"} (mix) or {vbxtrace, "1.0.0"} (rebar3), then call vbxtrace:start(); see Local development.
Compose-only. For Erlang services and Elixir services started with mix, elixir or iex, the hub proposes:
services:
<service>:
+ volumes:
+ - /usr/local/lib/vulnboxd/trace:/opt/vbxtrace:ro
+ environment:
+ ERL_AFLAGS: "-pa /opt/vbxtrace/beam/ebin -eval catch(code:load_file(vbxtrace)),catch(vbxtrace:start())."For Elixir releases (bin/<name> start), the same value goes into ELIXIR_ERL_OPTIONS, which the release script passes to the emulator:
+ environment:
+ ELIXIR_ERL_OPTIONS: "-pa /opt/vbxtrace/beam/ebin -eval catch(code:load_file(vbxtrace)),catch(vbxtrace:start())."If the service already sets the variable, the hook's flags are appended with a space. The value needs no quoting inside the container: it contains no spaces within an argument and nothing a shell expands.
The hub proposes this when it detects: mix.exs, rebar.config, erlang.mk or *.app.src in the service directory; a base image erlang:*, elixir:* or hexpm/*; a command running erl, rebar3, mix, elixir, iex or a release's bin/<name> start; or a dependency on cowboy, plug_cowboy, bandit, phoenix, elli or ranch. The templates are hooks/beam/e1/proposals/erlang.toml, elixir.toml and elixir-release.toml.
To apply it by hand, add the mount and the variable to the service in docker-compose.yml and restart the service.
What happens at startup:
-paputs/opt/vbxtrace/beam/ebinon the code path, and-evalruns once the node has booted (forerlandmix: before the application starts; for a release: once its boot script has started the applications). The expression is wrapped incatch, so a missing or broken hook directory can never stop the node from booting. (-s vbxtracewould: the node halts when an-smodule cannot be loaded.)code:load_file/1makes it work in releases that run in embedded mode, where modules are not loaded on demand.vbxtrace:start/0does nothing ifVBXTRACE=0is set. Otherwise it loads its modules and the NIF/opt/vbxtrace/beam/priv/vbxtrace_nif-<arch>.so, which opens the core/opt/vbxtrace/libvbxtrace-<arch>.so(<arch>from the emulator's system architecture,x86_64oraarch64). If anything is missing, the hook stays off and the service runs as before.- It starts one process,
vbxtrace_tracer, and returns. Everything else happens in that process.
The NIF is built without the C library (it imports only the emulator's enif_* functions) against the NIF API of OTP 24, which later releases accept, so one file per architecture loads into every OTP 24–28 image, Debian- or Alpine-based. The .beam files are compiled with OTP 24's compiler and load in OTP 24–28.
What it records
| Event | Emitted from | Join key |
|---|---|---|
request_begin / request_end | Cowboy: cowboy_stream_h:request_process/3 (start), the request process's exit (end), cowboy_req:reply/4 / stream_reply/3 (status) | peer address and port, request index (streamid) |
Bandit: [:bandit, :request, :start] and [:bandit, :request, :stop | :exception] telemetry | peer address and port, request index | |
Elli: elli_http:execute_callback/1 (start), handle_response/3 (status), the next keepalive_loop/5 or the process's exit (end) | peer address and port, request index | |
ranch raw protocols: ranch:handshake/1,2 returning the socket (start), gen_tcp:close/1 of it or the connection process's exit (end); one session per connection, protocol raw, index 0, status 0 | peer address and port | |
gen_tcp servers: gen_tcp:accept/1,2 returning the socket (start), gen_tcp:close/1 or the owner's exit (end) | peer address and port | |
spawned | erlang:open_port/2 (os:cmd, System.cmd, Port.open, open_port({spawn…})): the port's OS pid | child pid |
connected | gen_tcp:connect/4 (also behind :gen_tcp.connect, Mint, Finch, Postgrex, Redix, …) and ssl:connect/4: the socket's local port and peer | local port |
Request indexes are exact: Cowboy's streamid (HTTP/1.1: 1, 2, 3 … → index 0, 1, 2; HTTP/2: client stream 1, 3, 5 … → 0, 1, 2), Elli's own request counter, and for Bandit HTTP/1 a count of the requests on the connection (Bandit runs them one after the other in the connection's process); Bandit HTTP/2 uses the stream id. When Bandit's metadata lacks what is needed, the index is sent as unknown (VBX_REQUEST_INDEX_UNKNOWN), never guessed.
The hook emits no opened; see Known gaps.
How the hook sees calls without code changes
vbxtrace_tracer is the tracer of a BEAM trace session (OTP 27 and later: trace:session_create/3, isolated from any other tracing on the node) or, on OTP 24–26, of the node's tracing. It gives every process the call and arity trace flags and sets local call patterns on the dozen functions above; calls to any other function cost nothing. The patterns' match specs pick out only what is needed (for Cowboy: the request map's peer, sock, streamid and version), so a traced call sends a small tuple to the tracer, never a request, a header or a body. Return values (a port, {ok, Socket}) arrive as return_trace messages.
Trace patterns apply only to loaded code. The hook loads the modules it hooks that are on the code path when it starts, traces erlang:finish_loading/1 to notice code loaded later, and when the code path changes (mix run adds the dependencies after the node has booted) loads the hooked modules from there, before their first use, which in interactive mode would otherwise be the first request.
Bandit has stable telemetry events, so the hook uses them instead of tracing: its handlers (vbxtrace_bandit:handle/4) run synchronously in the request's own process. They are attached as soon as :telemetry runs (tried whenever code is loaded, and once a second).
Tracing and the telemetry handlers are switched on only while a tracer (vulnboxd's sensor) is attached to the core, checked once a second through vbx_v1_enabled(), and switched off when it detaches. With the sensor detached, the hook's only activity is that check.
Context following
A request's context id lives in a table owned by vbxtrace_tracer (process → context) and, for Bandit, in the request process's dictionary ('$vbxtrace_ctx'). The tracer handles the trace messages of one process in the order that process made the calls, so a request's context is always known before anything the request does is looked at.
Followed automatically:
- The request's own process: Cowboy's request process, Bandit's connection (HTTP/1) or stream (HTTP/2) process, Elli's connection process, the ranch connection process, the
gen_tcpsocket owner. - Processes it spawns, with
spawn,spawn_link,proc_libor anything built on them: a request process gets theprocsandset_on_spawntrace flags synchronously (set by the match spec, before it can spawn anything), so its children, and theirs, inherit the context. - Processes that work for it:
Task,Task.async_stream,GenServer.start_linkand otherproc_libprocesses started on its behalf carry'$callers'/'$ancestors'; a process without a context of its own is looked up through them. - A socket handed over:
gen_tcp:controlling_process/2moves a raw session's context to the new owner (how accept loops give a connection to a handler process).
Not followed, because nothing links them to the request: messages to long-running processes started elsewhere (a GenServer started by the application's supervisor, a connection pool's workers, an Ecto repo's connections). A connection a pool opened at startup is not a request's connection either: it is correctly reported without a context. For work handed to such a process, the source-change API below has vbxtrace:handoff/1.
Source change, for servers the hook does not know
Ctx = vbxtrace:request_begin(Socket, Index, http1), % or raw, http2, websocket
... % spawns, connects in this process are linked
vbxtrace:handoff(WorkerPid), % work continues in a process the hook can't see
vbxtrace:request_end(200).All of it is optional and does nothing while the hook is off.
Known gaps
- No
opened. A file's descriptor can only be read withprim_file:get_handle/1, which works only in the process that opened the file (anywhere else it raisesnot_on_controlling_process), and no hook runs code in that process without changing its code. Files are linked by the kernel's rules only, which for the BEAM means: not to a request. - Facts are read just after the call returns. The tracer reads a port's OS pid and a socket's local port when the return message arrives, from its own process. A command that has already finished, or a socket that is already closed by then, is not reported (dropped, never guessed). In the samples this needs a command to run for a few milliseconds and a peer to answer within more than that: the sample commands take 50 ms and the sample peer answers after 10 ms, because on a loaded test machine a
echothat ends within a millisecond or a local peer that answers within microseconds was sometimes missed. Real peers across a network and most real commands take longer than that. - Releases: from boot on. A release runs the hook's
-evalafter its boot script has started the applications, so requests in the first moments after the listener opens are not linked (thephoenixsample waits a second before its scripted requests). - OTP 24–26 share tracing with the node. The hook uses the node's tracer there and steps aside while another tracer is set (
dbg,recon_trace,redbug): no events until that tracing stops, when the hook takes over again (within a second). OTP 27 and later have trace sessions and no such conflict. - UDP is not reported (
connectedis for TCP;gen_udpis not hooked). - TLS:
ssl:connect/4is reported; the TCP connection the TLS connection process opens underneath is not (that process is started by thesslapplication, not by the request). - WebSocket upgrades on Cowboy end the HTTP request when the request process exits, which for a WebSocket handler is when the WebSocket closes.
- Ports opened by other processes (
erlexec, a port owner process started by a supervisor) are linked only if that process carries the request's context.
Safety
- Nothing in the request path but tracing. The service's code is not changed or reloaded. A traced call sends a small message to
vbxtrace_tracerand continues; it never waits for the hook. Bandit's telemetry handlers run in the request process, catch everything and only call the core and send a message. - Failures are contained. Every call into the core is guarded; any exception in the hook is counted, and after 5 internal errors the hook switches itself off for the node.
vbxtrace:start/0never raises, and the-evalis wrapped incatch, so a broken hook directory leaves the node booting as before. VBXTRACE=0in the environment keeps the hook from starting.- Chaos test: every sample also runs with
VBXTRACE_CHAOS=1, where every call into the core fails inside the guard; the responses are byte-identical to the run with the hook working, and to the run without the hook (baseline). All seven samples pass events, chaos and baseline. - Overhead: not measured yet (the measurement is a later phase). With the sensor detached the hook does one NIF call a second and has no trace flags or patterns set.
Turning it off
Set VBXTRACE=0 in the service's environment and restart it, or revert the change that added the hook; vulnboxd's rollback covers a hook that breaks a service.
Removing the hook by hand: delete the -pa /opt/vbxtrace/… vbxtrace:start()). part from ERL_AFLAGS (or ELIXIR_ERL_OPTIONS) and the /opt/vbxtrace mount. On a running node, vbxtrace:stop() in a remote shell switches tracing off until the next restart.
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? In a remote shell (
bin/<name> remote, orerl -remsh),vbxtrace:status().returns whether it is on, whether a tracer is attached (enabled), the internal error count, the tracing backend (sessionorlegacy), the hooked functions that are in place (applied), the number of processes with a context and whether the telemetry handlers are attached. The core and the NIF show up in/proc/<pid>/mapsof thebeam.smpprocess. - See what it sees: start the service with
VBXTRACE_DEBUG=1and the tracer prints every message it handles, and every exception in the hook, to standard error. - Which links did a flow get? The hub shows each link's method; this package's are
hook:E1. - Nothing recorded on OTP 24–26: another tracer is active (
erlang:trace_info(new, tracer)in a remote shell); stop it (dbg:stop()) and the hook takes over within a second. ERL_AFLAGSignored: a start script that runs the emulator with a cleared environment, or an escript, does not see it; use the start command's own way to pass emulator flags (for releases:ELIXIR_ERL_OPTIONS, or-pa/-evallines inrel/vm.args.eex).- The first requests after a release starts are missing: expected, see Known gaps.