Haskell, OCaml, Julia, R, Scala Native (C4)
Ready
The hub recognises the services this package fits and proposes the compose part of the change, if any; the source change stays by hand, with the steps and examples in the proposal's review. Nothing changes until a player approves it (Hook proposals). The cheat sheets have the steps by hand.
C4 is for services written in Haskell (Warp/WAI: Servant, Yesod, Scotty), OCaml (cohttp, Dream), Julia (HTTP.jl, Oxygen, Genie), R (plumber) and Scala Native. None of these runtimes can load a hook from outside, so the hook gets in by a source change: you copy a small binding into the service, wrap the server or router in it with one or two lines, and add a read-only mount of the hook directory to the compose entry. At run time the binding loads vulnboxd's core library from /opt/vbxtrace. Without the mount, or with VBXTRACE=0, the binding does nothing.
The Haskell, OCaml, R and Scala Native bindings compile the guarded C binding vbxhook.c of package C1 into the service and call it through each language's C FFI. The safety rules therefore live in one place. Julia's binding is pure Julia and needs no C compiler.
Covers
| Versions | |
|---|---|
| Haskell, GHC | 8.10 and later (tested: 9.10.3) |
| Warp / WAI | warp 3.3 and later, wai 3.2 (tested: warp 3.4.15, wai 3.2.5, network 3.2.9) |
| Servant, Yesod, Scotty, Spock | every version that produces a WAI Application on Warp |
| OCaml | 4.14 and later (tested: 5.3) |
| cohttp-lwt-unix | 5 and 6 (tested: 6.2.1, lwt 6.1.2, conduit-lwt-unix 8.0.0) |
| Dream | 1.0 alphas (tested: the opam release on the ocaml/opam 5.3 image) |
| Lwt / Eio | context helpers: Lwt 5.7 and later, Eio 1.x |
| Julia | 1.11 and later, because the binding needs Base.ScopedValues (tested: 1.12.7) |
| HTTP.jl | 1.x (tested: 1.10.19); Oxygen and Genie run on it |
| R / plumber | R 4.1 and later, plumber 1.x on httpuv (tested: R 4.5.1, plumber 1.3.0, httpuv 1.6.16, processx 3.8.6) |
| Scala Native | 0.5 with Scala 3 (tested: 0.5.8, Scala 3.3.7); servers on java.net.ServerSocket |
What the kernel already links without this hook. A server that forks a process per connection, or runs one OS thread per connection (a Scala Native ServerSocket server with a thread per connection, for example), is linked exactly by the kernel. There the hook adds only request boundaries on keep-alive connections. Everything else on this page multiplexes many requests over a few OS threads, so the kernel cannot tell which request a syscall was made for:
- GHC's green threads.
- Lwt and Eio fibers.
- Julia tasks.
plumber is a special case. R runs every handler on its main thread, one request at a time, but httpuv does the socket I/O on a second thread. The hook supplies the request boundaries and the exact peer.
How it gets in
On a developer machine: no registry package; copy the files from the hook directory that vulnboxctl hooks install-local puts in ~/.local/share/vulnboxd/trace, as below; see Local development.
Every language uses the same compose change, a read-only mount of the hook directory:
services:
<service>:
+ volumes:
+ - /usr/local/lib/vulnboxd/trace:/opt/vbxtrace:roThat is the whole compose change; no environment variable is needed. (The Haskell, OCaml, R and Scala Native bindings, through vbxhook.c, also take the file named by VBXTRACE_LIB first, ignored in setuid and file-capability binaries, and, only with VBXTRACE_DEV=1, a library in ~/.local/share/vulnboxd/trace that belongs to root or the user and nobody else can write, for local development. Julia loads /opt/vbxtrace only.) The source change differs per language. For each one, the files to copy come from the hook directory on the vulnbox (/usr/local/lib/vulnboxd/trace/, also visible as /opt/vbxtrace/ inside a container that has the mount). The C sources are always:
native/c/vbxhook.cnative/c/vbxhook.hinclude/vbxtrace.h
The hub's proposals and their example diffs are in hooks/native/c4/proposals/.
Haskell (Warp, Servant, Yesod)
- Copy
native/haskell/vbxtrace/to<service>/vendor/vbxtrace/, and the three C files intovendor/vbxtrace/cbits/. - Add
vendor/vbxtracetocabal.project(or thepackages:ofstack.yaml), andvbxtraceto the executable'sbuild-depends. - Wrap the application:
import Network.Wai.Handler.Warp (defaultSettings, runSettings, setPort)
+import VBXTrace.Wai (newVbx, vbxMiddleware, vbxSettings)
main :: IO ()
-main = runSettings (setPort 8080 defaultSettings) app
+main = do
+ vbx <- newVbx 8080
+ runSettings (vbxSettings vbx (setPort 8080 defaultSettings)) (vbxMiddleware vbx app)For Servant, Yesod and Scotty, wrap the WAI application they produce in the same way:
- Servant:
vbxMiddleware vbx (serve api server) - Yesod:
toWaiApp site >>= runSettings settings . vbxMiddleware vbx - Scotty:
scottyApp
vbxSettings keeps any setOnOpen / setOnClose you already have. On glibc older than 2.34, add extra-libraries: dl to vbxtrace.cabal. musl and current glibc need nothing.
OCaml (cohttp, Dream)
- Copy
native/ocaml/vbxtrace/to<service>/vendor/vbxtrace/, and the three C files intovendor/vbxtrace/src/. dune picks the library up from the vendored directory. - cohttp-lwt-unix: add
vbxtrace.cohttp-lwt-unixto the executable'slibrariesand replaceServer.make:
- (Cohttp_lwt_unix.Server.create ~mode:(`TCP (`Port 8080)) (Cohttp_lwt_unix.Server.make ~callback ()))
+ (Cohttp_lwt_unix.Server.create ~mode:(`TCP (`Port 8080)) (Vbxtrace_cohttp_lwt_unix.make ~callback ()))If you build the server with your own conn_closed, use let callback, conn_closed = Vbxtrace_cohttp_lwt_unix.wrap ~conn_closed callback.
- Dream: add
vbxtrace.dreamand put the middleware first, before anything that rewritesDream.client:
let () =
Dream.run ~port:8080
+ @@ Vbxtrace_dream.middleware ~port:8080
@@ Dream.router [ ... ]The optional libraries vbxtrace.lwt, vbxtrace.eio, vbxtrace.cohttp-lwt-unix and vbxtrace.dream build only when their dependencies are installed. The core library vbxtrace needs nothing beyond unix, and it uses plain external stubs, not ctypes.
Julia (HTTP.jl, Oxygen, Genie)
- Copy
native/julia/VBXTrace.jlandnative/julia/VBXTraceHTTP.jlto<service>/vbxtrace/. No C files and no compiler are needed. - Serve through the stream middleware:
using HTTP
+include("vbxtrace/VBXTrace.jl")
+include("vbxtrace/VBXTraceHTTP.jl")
...
-HTTP.serve(handler, "0.0.0.0", 8080)
+HTTP.serve(VBXTraceHTTP.middleware(HTTP.streamhandler(handler)), "0.0.0.0", 8080; stream = true)Stream handlers (HTTP.Stream -> nothing) are wrapped directly: VBXTraceHTTP.middleware(stream_handler). Oxygen and Genie build an HTTP.jl handler. Hand their router to HTTP.serve as above (Oxygen: Oxygen.router / serve(; handler)), so the middleware sits at the stream level, where the connection is visible.
R (plumber)
- Copy
native/r/vbxtrace.Randnative/r/vbxtrace_r.cto<service>/vbxtrace/, together with the three C files. - Build the shim in the image. The R images ship a compiler.
- Pass the router through
vbx_plumber():
# Dockerfile
+RUN cd vbxtrace && PKG_CPPFLAGS=-I. R CMD SHLIB -o vbxtrace_r.so vbxtrace_r.c vbxhook.c
# entrypoint.R
library(plumber)
+source("vbxtrace/vbxtrace.R")
+vbx_load("vbxtrace/vbxtrace_r.so")
-pr("plumber.R") |> pr_run(host = "0.0.0.0", port = 8000)
+pr("plumber.R") |> vbx_plumber() |> pr_run(host = "0.0.0.0", port = 8000)Scala Native
- Copy
native/scala-native/src/main/scala/vbxtrace/into the service'ssrc/main/scala/, and the three C files intosrc/main/resources/scala-native/. The Scala Native sbt plugin compiles C files found there. - Wrap the request handling. For a
ServerSocketserver with a thread per connection:
+import vbxtrace.VBXTrace
...
while hasRequest(s) do
- handle(s)
+ val ctx = VBXTrace.begin(s.getLocalPort, s.getInetAddress.getHostAddress, s.getPort, index)
+ val status = handle(s)
+ VBXTrace.end(ctx, status)
index += 1On glibc older than 2.34, add nativeConfig ~= (_.withLinkingOptions(_ :+ "-ldl")).
When the hub proposes it
The hub proposes each variant when it detects one of these:
| Language | Files | Image | Dependencies |
|---|---|---|---|
| Haskell | *.cabal, cabal.project, stack.yaml, package.yaml | haskell:, fpco/stack-build | warp, wai, servant-server, yesod, scotty, Spock |
| OCaml | dune-project, dune, *.opam | ocaml/opam | cohttp-lwt-unix, cohttp-eio, dream, lwt, eio |
| Julia | Project.toml, Manifest.toml, *.jl | julia: | HTTP, Oxygen, Genie |
| R | plumber.R, entrypoint.R, DESCRIPTION, renv.lock | rocker/, r-base, rstudio/plumber | plumber, httpuv |
| Scala Native | build.sbt, project/plugins.sbt, build.mill | sbtscala/scala-sbt | sbt-scala-native, snunit |
The Julia and R proposals also match the service's command line: julia for Julia, and Rscript or plumb( for R.
Building against the static archive instead
Compiled with -DVBXHOOK_STATIC and linked against libvbxtrace-<arch>.a, vbxhook puts the probes into the service binary itself and needs no mount. This applies to the cabal, dune, R and Scala Native builds; see C1's vbxhook.h.
What it records
The join keys are always:
request_begin/request_end: the accepted socket's local port, peer address and port, and the request index on the connection.spawned: the child pid.connected: the outgoing socket's local port.opened: pid + fd.
Haskell
| Event | Emitted from | Exactness |
|---|---|---|
request_begin / request_end | vbxMiddleware, around the WAI application; ends with the status of the response passed to respond, after Warp sent it (0 if the application threw) | peer = remoteHost; local port = the port given to newVbx. Request index: Warp reports every accepted connection to setOnOpen / setOnClose by peer address. Among the live connections of one listener, the peer address and port are unique, so a counter reset on open and dropped on close is exact. HTTP/2 streams count in the order Warp starts them, with protocol http2. |
spawned | spawnedHandle (vbxContext req) ph (System.Process getPid); call it before waitForProcess | child pid |
connected | connectedSocket ctx sock (network withFdSocket) | from the socket |
opened | opened ctx fd (openFlags mode flags) after System.Posix.IO.openFd | openFlags rebuilds exactly what unix ≥ 2.8 passes to open(2), from base's own O_* constants. Flags without a constant there (nofollow, cloexec, directory, sync) give "unknown". |
OCaml
| Event | Emitted from | Exactness |
|---|---|---|
request_begin / request_end (cohttp-lwt-unix) | Vbxtrace_cohttp_lwt_unix, around the callback; ends when the callback's promise resolves, with the response status (cohttp then writes the response) | local port and peer from the accepted fd (Conduit_lwt_unix.TCP {fd}). Request index: cohttp creates a fresh Cohttp.Connection.t per accepted connection and passes it to conn_closed, so the per-connection counter is exact. cohttp 6 marks the module deprecated, but the server still provides the identity. |
request_begin / request_end (Dream) | Vbxtrace_dream.middleware ~port | peer = Dream.client (the socket peer, as long as nothing rewrote it before the middleware); local port = the given port. Request index: unknown. Dream gives handlers no connection identity and no close notification, so the index is reported as VBX_REQUEST_INDEX_UNKNOWN instead of a guess. |
spawned | Vbxtrace.spawned ctx pid (Unix.create_process, Lwt_process #pid; Vbxtrace_lwt.spawned p) | child pid |
connected | Vbxtrace.connected_fd ctx fd (Unix.connect; Lwt_unix.unix_file_descr; Vbxtrace_lwt.connected) | from the socket |
opened | Vbxtrace.openfile ctx path flags perm (or Vbxtrace_lwt.openfile) | Vbxtrace.open_flags maps Unix.open_flag lists through the system's own O_* constants, exactly as Unix.openfile does. Keep-exec is the default, and O_CLOEXEC appears only if listed. |
Julia
| Event | Emitted from | Exactness |
|---|---|---|
request_begin / request_end | VBXTraceHTTP.middleware, around the stream handler; ends with stream.message.response.status after the handler returned, by which time HTTP.jl has written the response | local port and peer from the connection's TCPSocket (getsockname / getpeername). Request index: HTTP.jl keeps one HTTP.Connection object per accepted connection and reuses it for every request on it, so a counter per connection object (a WeakKeyDict) is exact. |
spawned | VBXTrace.spawned(p) for p = run(cmd; wait = false) | getpid(p) |
connected | VBXTrace.connected(sock) after Sockets.connect | from the socket |
opened | VBXTrace.open(path, mode) (wraps Base.open) | Julia always opens with O_CLOEXEC, so "w" is O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC = 0x80241 (checked with strace). Unknown modes give "unknown". |
R
| Event | Emitted from | Exactness |
|---|---|---|
request_begin / request_end | vbx_plumber(): the preroute hook opens the request; postserialize closes it, or postroute when a handler returns the response object itself (plumber then skips serialization). Ends with res$status. | peer = httpuv's REMOTE_ADDR / REMOTE_PORT; local port = SERVER_PORT. Request index: unknown. httpuv tells R neither which connection a request came on nor when one closes, so a count keyed by the peer would be wrong once a client port is reused. |
spawned | vbx_spawned(p$get_pid()) (processx; sys::exec_background returns the pid as well) | child pid. system() / system2() hide the pid; the kernel still sees R's main thread fork inside the request. |
connected, opened | vbx_connected(...) / vbx_opened(fd, flags) only when the caller knows the keys | base R's socketConnection() and file() expose no fd. What R's main thread does between request_begin and request_end belongs to that request, because plumber runs one at a time. |
Scala Native
| Event | Emitted from | Exactness |
|---|---|---|
request_begin / request_end | VBXTrace.begin(...) / VBXTrace.end(ctx, status) around your handler | local port, peer and peer port from java.net.Socket. The request index is a counter owned by the connection's thread, so it is exact. With a raw fd, use VBXTrace.beginFd(fd, index). |
spawned | VBXTrace.spawned(ctx, p.pid()) (ProcessBuilder) | child pid |
connected | VBXTrace.connected(ctx, sock.getLocalPort, ip, port) or connectedFd(ctx, fd) | from the socket |
opened | VBXTrace.opened(ctx, fd, flags) after posix fcntl.open | the flags you passed |
No C4 binding emits handoff or context_enter / context_exit; see below.
Context following
Every event a C4 binding emits carries its context id explicitly, and none of the joins depends on which OS thread made a call. So context following means making the id available to the code that spawns, connects or opens. Handoff is never needed. In GHC, Lwt, Eio and Julia, the OS thread carries no meaning anyway: lightweight threads move between OS threads, and many share one. For the same reason, the thread-current slot of vbxhook (vbxh_current) is offered only to Scala Native.
| Language | Mechanism | Follows automatically | Pass by hand |
|---|---|---|---|
| Haskell | the WAI request vault (vbxContext req, key ctxKey) | everything that has the Request | threads started with forkIO / async: capture the Ctx (a Word64) in the closure, e.g. let ctx = vbxContext req in forkIO (... spawnedHandle ctx ph ...) |
| OCaml + Lwt | an Lwt.key (Vbxtrace_lwt.current ()), set with Lwt.with_value by the cohttp and Dream wrappers | every promise and callback created inside the request: bind, Lwt.async, Lwt.pick, Lwt_unix I/O | Lwt_preemptive.detach, Thread.create: read current () first and pass the value in |
| OCaml + Eio | a fiber key (Vbxtrace_eio.with_ctx, current ()) | fibers forked inside: Fiber.fork, Fiber.both, Fiber.all, switch children | Domain_manager.run, executor pools, Eio_unix.run_in_systhread |
| Julia | a ScopedValue (VBXTrace.CTX, VBXTrace.current()), bound with @with by the middleware | every task started inside the request, on any thread: @async, Threads.@spawn, @sync, Channel producers | a worker task started before the request that receives work over a Channel: send current() with the work and call the helpers with ctx, or run it in VBXTrace.with_ctx(ctx) do ... end |
| R | one variable (vbx_current()), exact because plumber runs one request at a time; also req$.vbx_ctx | the whole handler | promises / future handlers: read req$.vbx_ctx; future and callr workers are separate processes, which the kernel links by fork |
| Scala Native | the Long; optionally vbxhook's per-thread slot (VBXTrace.setCurrent / current) | the connection's thread | Futures / executors: pass the value. If the work must show up as the request's on another OS thread, use handoff + enter / exit |
Example (Haskell): a handler that starts a worker thread.
handler req respond = do
let ctx = vbxContext req
_ <- forkIO $ do
(_, _, _, ph) <- createProcess (proc "/usr/bin/convert" args)
spawnedHandle ctx ph -- still linked to the request
void (waitForProcess ph)
respond (responseLBS status202 [] "")Known gaps
Request index unknown on plumber and Dream. Neither tells the application which connection a request came on. The binding sends
VBX_REQUEST_INDEX_UNKNOWN, and the sensor joins those requests by peer and time. Requests on a keep-alive connection are still told apart by their boundaries. Prefer cohttp over Dream where the exact index matters.TLS and Unix sockets. The cohttp wrapper handles TCP flows only. Julia's middleware needs a
TCPSocketat the top of the connection, whichSSLContextis not. Warp-TLS works, becauseremoteHostis still the socket's peer.Status timing. cohttp and Dream end the request when the handler's promise resolves. A streamed body is written after
request_end, and the kernel still attributes those writes to the connection.Requests that fail. A plumber request whose handler raises an R error reaches no hook, so it gets no
request_end. The sensor closes it at the nextrequest_beginon the thread.Calls without a helper. These are linked only by the kernel:
- R: base R
file()/socketConnection()andsystem(). - Haskell:
readFile/withFile. UseopenFd+openedwhere it matters. - Julia: libraries that open files or sockets inside C code.
Under green threads and fibers, the kernel's own link is ambiguous while several requests run at once.
- R: base R
cohttp-eio. Only the Eio context helper ships. A ready wrapper for cohttp-eio is not included yet;
vbxtrace_eio.mlshows how to open a request from the connection's fd.Scala Native frameworks. The sample uses
java.net.ServerSocket. snunit runs behind NGINX Unit, which owns the connections, and http4s-ember on Scala Native runs on Cats Effect fibers (useIOLocalfor the context). Neither has a ready wrapper.Julia before 1.11 has no
Base.ScopedValues. Use the ScopedValues.jl package and edit theusingline, or upgrade.
Safety
One guard implementation. Every call goes through vbxhook's gate:
- Nothing happens unless the core library loaded from
/opt/vbxtraceandvbx_v1_enabled()reports a tracer. This check comes before anything else. VBXTRACE=0at the first call switches the binding off for the process.- Internal errors (an unreadable socket address, an unparsable peer) are counted, and the fifth switches the binding off.
- vbxhook saves and restores
errnoand never blocks or allocates.
Julia's binding repeats exactly these rules in Julia (including
VBXTRACE_CHAOS), with every core call insidetry/catch.- Nothing happens unless the core library loaded from
Nothing escapes into the service.
- Haskell: the FFI calls are
unsafe ccalls that cannot throw. The process and socket helpers catch every exception. - OCaml: the stubs are
[@@noalloc]and raise nothing. - R: wraps every
.CallintryCatch, and the shim never raises an R error. - Scala Native: wraps every extern call in
try. - The middlewares rethrow the application's own exceptions unchanged, and never change requests or responses. Haskell adds one vault entry; Julia binds a scoped value.
- Haskell: the FFI calls are
Bookkeeping while no tracer is attached. The exact request counters (Haskell, Julia) are kept as long as the binding is not off for good, so indexes stay right when a tracer attaches mid-connection. That costs one map update per request.
Chaos-tested. Every sample runs with
VBXTRACE_CHAOS=1, which makes every core call fail inside the guard. Its responses are compared byte for byte with the normal run and with a build containing no hook code at all.
| Sample | events | chaos | baseline |
|---|---|---|---|
| haskell-warp | 13 events match | responses byte-identical (581 bytes) | byte-identical |
| ocaml-cohttp | 13 events match | byte-identical (488 bytes) | byte-identical |
| ocaml-dream | 13 events match (index unknown) | byte-identical (368 bytes) | byte-identical |
| julia-http | 13 events match | byte-identical (461 bytes) | byte-identical |
| r-plumber | 11 events match (index unknown, no fd for file/connect) | byte-identical (368 bytes) | byte-identical |
| scala-native-socket | 13 events match | byte-identical (368 bytes) | byte-identical |
Overhead (p99 with the hook loaded and the sensor detached, and attached) has not been measured yet. It will be added in the measurement phase.
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.
To remove the hook completely:
- Undo the middleware lines.
- Delete the vendored directory:
vendor/vbxtrace(Haskell, OCaml),vbxtrace/(Julia, R), orsrc/main/scala/vbxtraceplus the three C files undersrc/main/resources/scala-native/(Scala Native). - Drop the
/opt/vbxtracemount.
Removing only the mount also switches the hook off: the binding finds no core and stays inactive.
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? The core is loaded on the first request, not at startup. After one request,
grep libvbxtrace /proc/<pid>/mapsshows the library. If it is missing:- the mount is absent;
VBXTRACE=0is set;- the binary is fully static: build with
-DVBXHOOK_STATICand the archive instead (not Julia).
Inside the service, the binding reports how many internal errors it has counted (5 or more means off):
VBXTrace.errors(Haskell),Vbxtrace.errors ()(OCaml),VBXTrace.errors()(Julia),.Call("vbxr_errors")(R),VBXTrace.errors(Scala Native).Which links did a flow get? The hub shows each link's method; this package's are
hook:c4.No events from Warp.
vbxSettingswas not applied to the settings Warp actually runs with, so the middleware sees connections it was never told about and stays silent rather than guess. Pass the settings throughvbxSettingsand wrap the application with the samevbx.No events from cohttp. The server listens on TLS or a Unix socket, or
Server.makewas not replaced (check thatVbxtrace_cohttp_lwt_unixis linked).Julia: events but no
request_endstatus. The handler threw. HTTP.jl answered with a 500 of its own, and the binding reports status 0.R:
vbx_load()returns FALSE. The shim was not built (novbxtrace_r.so), it was built withoutvbxhook.c, orVBXTRACE=0is set.Builds fail on
dlopen. On glibc older than 2.34, link-ldl: cabalextra-libraries: dl, dune(c_library_flags -ldl), RPKG_LIBS=-ldl, Scala Native linking options.