Go module (G2)
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 sheet has the steps by hand.
The Go hook for services whose source you can change: a small Go module, vulnboxd.ctf.garden/vbxtrace, vendored into the service directory (so the build needs no network), plus one changed line where the server starts and a wrapper around each place a handler starts a process, dials out or opens a file. It reports which request each of those belongs to. It works for every Go binary — with or without cgo, static or dynamic, stripped (-ldflags='-s -w') or not — and for every server built on net/http (chi, gorilla/mux, echo, gin, ...), fasthttp, fiber and gRPC.
Go services can also be traced with no change at all by G1 (net/http, x/net/http2, gRPC, fasthttp and fiber); G2 is for what G1 cannot see: stripped binaries that serve through x/net, grpc-go or fasthttp (G1 needs their DWARF), Go releases not in G1's offset table, connected UDP and unix sockets, work handed to worker pools (vbxtrace.Handoff), and connections accepted before the sensor attached (reported with an unknown index).
Covers
| Versions | |
|---|---|
| Go | 1.17–1.26 (tested in the official golang:1.17–1.26 images, cgo on and off, with and without the recording build) |
| Architectures | amd64 and arm64 (arm64 pure-Go probes: Go 1.18+) |
| Binaries | static (CGO_ENABLED=0, scratch/distroless images) and dynamic; glibc and musl; stripped or not |
net/http | http.Server (HTTP/1.1, HTTP/2 over TLS, WebSocket upgrades), http.ServeMux |
Routers on net/http | chi, gorilla/mux, echo v4, gin (adapter vbxgin for passing *gin.Context) |
| fasthttp | any version with RequestCtx.ConnRequestNum (adapter vbxfasthttp) |
| fiber | v2 (adapter vbxfiber) |
| gRPC | grpc-go 1.60+ (adapter vbxgrpc, unary and streaming) |
| Raw TCP servers | vbxtrace.Session / vbxtrace.ConnRequest |
| Dependencies | the core module: standard library only; each adapter is its own module requiring only its framework |
What the kernel already links without any hook: nothing, for Go. Goroutines move between OS threads and one thread runs many requests' goroutines in turn, so the sensor's "one client socket per thread" rule never applies to a Go server.
How it gets in
From a registry (local development, or a build with network; the same release as the hook directory): go get vulnboxd.ctf.garden/vbxtrace@v1.0.0 (and /vbxgin, /vbxfiber, /vbxfasthttp, /vbxgrpc; Go 1.25 or later); see Local development.
Source change. The hub proposes a diff the player reviews; it goes out like a rule push and the service rebuilds in the normal deploy flow. All proposals share these steps:
Copy the hook directory's
go/vbxtrace(/usr/local/lib/vulnboxd/trace/go/vbxtraceon the vulnbox) into the service directory as./vbxtrace, next togo.mod.In
go.mod, require and replace it (and the adapter, if the framework needs one):diffrequire ( github.com/gin-gonic/gin v1.9.1 + vulnboxd.ctf.garden/vbxtrace v0.0.0 + vulnboxd.ctf.garden/vbxtrace/vbxgin v0.0.0 ) + +replace vulnboxd.ctf.garden/vbxtrace => ./vbxtrace + +replace vulnboxd.ctf.garden/vbxtrace/vbxgin => ./vbxtrace/vbxginReplaced local modules need no
go.sumlines. If the service has avendor/directory, the module is also copied tovendor/vulnboxd.ctf.garden/vbxtraceand listed invendor/modules.txt(# vulnboxd.ctf.garden/vbxtrace v0.0.0 => ./vbxtrace,## explicit; go 1.17, and its two packages).If the Dockerfile copies
go.modand runsgo mod downloadbefore copying the rest, it getsCOPY vbxtrace ./vbxtracebefore that step.The server line and the wrappers, per framework (next section).
Nothing else changes: no -ldflags change (stripped binaries work, see What it records), no compose change, no cgo requirement.
Per framework
| Framework | Change |
|---|---|
net/http, chi, gorilla/mux | http.ListenAndServe(addr, h) → vbxtrace.ListenAndServe(addr, h) (also ListenAndServeTLS, Serve, ServeTLS); a hand-built server: vbxtrace.Server(srv) before srv.ListenAndServe() |
| echo | e.Start(addr) → vbxtrace.ListenAndServe(addr, e); or keep e.Start and set e.Server.ConnContext = vbxtrace.ConnContext plus e.Pre(echo.WrapMiddleware(vbxtrace.Middleware)) |
| gin | r.Run(addr) → vbxtrace.ListenAndServe(addr, r), and r.Use(vbxgin.Middleware()) |
| fasthttp | fasthttp.ListenAndServe(addr, h) → fasthttp.ListenAndServe(addr, vbxfasthttp.Handler(h)) |
| fiber v2 | app.Use(vbxfiber.New()) first after fiber.New() |
| gRPC | grpc.NewServer(opts...) → grpc.NewServer(append(opts, vbxgrpc.ServerOptions()...)...) |
Then, wherever a handler starts a process, connects out or opens a file, the call goes through a wrapper that takes the request's context (r.Context(), the *gin.Context, c.Request().Context() in echo, c.UserContext() in fiber, the *fasthttp.RequestCtx, a gRPC handler's ctx):
| Instead of | Use |
|---|---|
cmd.Run(), cmd.Start(), cmd.Output(), cmd.CombinedOutput() | vbxtrace.Run(ctx, cmd), Start, Output, CombinedOutput |
os.StartProcess(...) | vbxtrace.StartProcess(ctx, ...) |
net.Dial, (&net.Dialer{}).DialContext | vbxtrace.DialContext(ctx, network, addr), or vbxtrace.Dialer{} |
a driver's or http.Transport's dial function | vbxtrace.WrapDialContext(dial) |
os.OpenFile, os.Open, os.Create | vbxtrace.OpenFile(ctx, ...), Open, Create |
| a connection or file obtained elsewhere | vbxtrace.Connected(ctx, conn), vbxtrace.Opened(ctx, f, flag) |
Example (the full proposal examples are in hooks/go/g2/proposals/*.diff):
import (
"github.com/go-chi/chi/v5"
+
+ "vulnboxd.ctf.garden/vbxtrace"
)
r.Get("/convert", func(w http.ResponseWriter, r *http.Request) {
- out, err := exec.Command("convert", r.URL.Query().Get("f"), "png:-").Output()
+ out, err := vbxtrace.Output(r.Context(), exec.Command("convert", r.URL.Query().Get("f"), "png:-"))
...
- log.Fatal(http.ListenAndServe(":8080", r))
+ log.Fatal(vbxtrace.ListenAndServe(":8080", r))The hub proposes this when it detects go.mod (with the framework among its requirements: net/http by default, github.com/gin-gonic/gin, github.com/labstack/echo/v4, github.com/valyala/fasthttp, github.com/gofiber/fiber/v2, google.golang.org/grpc, github.com/go-chi/chi, github.com/gorilla/mux) and a golang: build stage — and prefers G1 when the running binary is built by a Go release in G1's table (and, for x/net, gRPC or fasthttp, keeps its DWARF).
Applying it by hand
Do the four steps above. For a module checked out with network access you can also skip the copy and fetch it (go get vulnboxd.ctf.garden/vbxtrace) once its import page is published; during a CTF, vendor it.
Raw TCP servers
for {
c, _ := ln.Accept()
go func() {
ctx, req := vbxtrace.Session(context.Background(), c) // one "request" per connection
defer req.End(0)
handle(ctx, c)
}()
}A server with its own request loop on a connection reports each request with vbxtrace.ConnRequest(ctx, c, index, vbxtrace.ProtoRaw) and ends it with req.End(status). vbxtrace.Begin(ctx, localPort, peerIP, peerPort, index, proto) is the lowest level.
What it records
| Event | Emitted from | Join key |
|---|---|---|
request_begin / request_end | vbxtrace.Handler (installed by ListenAndServe/Server), vbxfasthttp.Handler, vbxfiber.New, vbxgrpc interceptors, Session, ConnRequest, Begin | the accepted connection's peer address and port, the request's index on it, the local port |
spawned | Run, Start, Output, CombinedOutput, StartProcess, Spawned | the child's pid |
connected | DialContext, Dialer, WrapDialContext, Connected | the connection's local port (TCP, connected UDP; unix sockets with transport unix) |
opened | OpenFile, Open, Create, Opened | pid + fd; flags are what os.OpenFile passes to open(2) (the flag plus O_CLOEXEC) |
handoff | vbxtrace.Handoff(ctx) | the two context ids |
Request index. It is exact or it is unknown, never a guess:
net/http:ConnContextstamps each connection accepted while a tracer listens and counts its requests. Connections accepted before the tracer attached (or by a server withoutConnContext) are reported with indexunknown(VBX_REQUEST_INDEX_UNKNOWN). If a request ever finds the tracer detached, every connection stamped before that is treated as unknown from then on, because requests in between were not counted. HTTP/2: the stream's position from its id ((id − 1) / 2).- fasthttp and fiber: fasthttp's own per-connection count (
ConnRequestNum), exact even for connections older than the tracer. - gRPC: the HTTP/2 stream id of the call, (id − 1) / 2.
How the events leave the process. Two backends, picked at the first hook call:
- Pure-Go probes (always available; the only one without cgo): eight
//go:noinlinefunctions with fixed names,vulnboxd.ctf.garden/vbxtrace/internal/probe.RequestBegin….Handoff, whose arguments sit in fixed registers at their first instruction (Go's register ABI). Their semaphores are a data array the kernel raises while the sensor is attached, followed by a 16-byte marker. The sensor finds the functions through.gopclntab(which even stripped Go binaries keep) and the semaphores by the marker, and attaches to them exactly like to the core library's USDT probes. - The core library (cgo builds, when
/opt/vbxtraceis mounted):libvbxtrace-<arch>.sois loaded withdlopenand its USDT probes fire, as for every other runtime. Without the mount the binary falls back to the pure-Go probes. Add the mount only if you prefer this path:- /usr/local/lib/vulnboxd/trace:/opt/vbxtrace:ro.
VBXTRACE_GO_BACKEND=go or =core forces one; vbxtrace.Status() says which is in use.
Context following
The request travels in Go's own context.Context, as Go code passes it anyway:
- The hook stores the request in the request's context (
r.Context(); in place, not on a copy of the request) under a string key, soc.Valuefinds it in a*gin.Context(aftervbxgin.Middleware) and in a*fasthttp.RequestCtx(its user values). go func(ctx context.Context) {...}(r.Context()),errgroup.WithContext, and anything else that passes the context follows automatically. The OS thread does not matter: every event carries an exact join key (pid, local port, fd).- Work handed to a pool that does not receive the context: pass
vbxtrace.Handoff(ctx)with the job. The worker uses it like a request context; the sensor links the two ids. - What does not follow: code that drops the context (
context.Background()in a handler, a global client created at start-up whose dials run without the request's context).
Known gaps
- Processes started after the sensor attached, with the probes in the binary. The kernel switches the probes on in such a process through a counter on the file page that holds the
.probessection. When the linker put that page into two LOAD segments (lld can, sharing it with the read-only-after-relocation data), the kernel's increment lands in the wrong mapping, so the sensor raises the counter itself in the process's own writable mapping (vulnboxd_sensor_usdt_semaphores_raised_totalcounts it). Go's linker has no switch to avoid the shared page. - Only wrapped calls are reported. A process started, a connection dialled or a file opened without the wrapper is linked only by the kernel's own rules, which for Go servers rarely apply. Database drivers usually take a dialer (
WrapDialContext);database/sqlpools reuse connections across requests, so the request that opened a pooled connection is not the request that later uses it. - HTTP/2 without TLS (h2c) through
golang.org/x/net/http2/h2c: the stream id is not read, so the index isunknown. - Stream ids assume clients number streams 1, 3, 5, … (every common client does); a client that skips ids gets indexes that count ids, not streams.
- fiber's status after an error is what fiber's default error handler would send (the
*fiber.Errorcode, else 500); a custom error handler may send something else. The status is not a join key. - gin and echo through their own
Run/Startwithout the server change get the middleware's context butunknownindexes (noConnContext). - arm64 with Go 1.17: the pure-Go probes' arguments are on the stack (no register ABI yet); untested.
Safety
- Every hook call is guarded: a panic inside the hook is recovered and counted, and after 5 the hook switches itself off for the process. A panic in your handler passes through untouched (the end of the request is reported from a
deferwithoutrecover). - Nothing is wrapped that the handler sees: the
ResponseWriteris passed on as it is (sohttp.Flusher,http.Hijacker,io.ReaderFromstay visible), and the request is the server's own, with only its context extended. The status is read fromnet/http's response after the handler. - The wrappers call exactly the function they replace with the same arguments and return its results;
RunisStartthenWait, asexec.Cmd.Runis. File descriptors are read withSyscallConn, neverFd()(which would switch the file to blocking mode). - While no tracer is attached, each hook point does one check (two atomic loads for the pure-Go probes, one call for the core library) and nothing else.
VBXTRACE=0in the environment switches the hook off at start.- Tested: every sample service runs with the hook failing on every call (chaos mode) and without the hook; the responses are byte-identical. Overhead has not been measured yet.
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. Reverting removes the ./vbxtrace directory, the go.mod lines and the wrapper calls; the service rebuilds as before.
Troubleshooting
- Are the probes there? For the pure-Go probes,
go tool nm <binary> | grep vbxtrace/internal/probe(unstripped), orstrings -a <binary> | grep vbxtracegoprobefor the marker (any binary). For the core library,readelf -n /usr/local/lib/vulnboxd/trace/libvbxtrace-x86_64.so. - Is the hook loaded? Log
vbxtrace.Status()at start:go,core, oroff(VBXTRACE=0, or switched off after errors).VBXTRACE_DEBUG=1prints why loading the core library failed. With the core backend,/opt/vbxtrace/libvbxtrace-*.soappears in/proc/<pid>/maps. - Requests show
request_index=unknown. The server is not started throughvbxtrace.ListenAndServe/vbxtrace.Server(noConnContext), or the connections were accepted before the sensor attached. - No
spawned/connected/openedfor a request. The call is not wrapped, or it gets a context that is not the request's (check that the handler passesr.Context()on). - Which links did a flow get? The hub shows each link's method; this package's are
hook:go-g2, labelled "hook · Go (vbxtrace)" on the Trace tab. - Build fails with "replacement directory ./vbxtrace does not exist". The Dockerfile runs
go mod downloadbefore copying the source; addCOPY vbxtrace ./vbxtracebefore it.