Skip to content

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
Go1.17–1.26 (tested in the official golang:1.17–1.26 images, cgo on and off, with and without the recording build)
Architecturesamd64 and arm64 (arm64 pure-Go probes: Go 1.18+)
Binariesstatic (CGO_ENABLED=0, scratch/distroless images) and dynamic; glibc and musl; stripped or not
net/httphttp.Server (HTTP/1.1, HTTP/2 over TLS, WebSocket upgrades), http.ServeMux
Routers on net/httpchi, gorilla/mux, echo v4, gin (adapter vbxgin for passing *gin.Context)
fasthttpany version with RequestCtx.ConnRequestNum (adapter vbxfasthttp)
fiberv2 (adapter vbxfiber)
gRPCgrpc-go 1.60+ (adapter vbxgrpc, unary and streaming)
Raw TCP serversvbxtrace.Session / vbxtrace.ConnRequest
Dependenciesthe 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:

  1. Copy the hook directory's go/vbxtrace (/usr/local/lib/vulnboxd/trace/go/vbxtrace on the vulnbox) into the service directory as ./vbxtrace, next to go.mod.

  2. In go.mod, require and replace it (and the adapter, if the framework needs one):

    diff
     require (
     	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/vbxgin

    Replaced local modules need no go.sum lines. If the service has a vendor/ directory, the module is also copied to vendor/vulnboxd.ctf.garden/vbxtrace and listed in vendor/modules.txt (# vulnboxd.ctf.garden/vbxtrace v0.0.0 => ./vbxtrace, ## explicit; go 1.17, and its two packages).

  3. If the Dockerfile copies go.mod and runs go mod download before copying the rest, it gets COPY vbxtrace ./vbxtrace before that step.

  4. 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 ​

FrameworkChange
net/http, chi, gorilla/muxhttp.ListenAndServe(addr, h) → vbxtrace.ListenAndServe(addr, h) (also ListenAndServeTLS, Serve, ServeTLS); a hand-built server: vbxtrace.Server(srv) before srv.ListenAndServe()
echoe.Start(addr) → vbxtrace.ListenAndServe(addr, e); or keep e.Start and set e.Server.ConnContext = vbxtrace.ConnContext plus e.Pre(echo.WrapMiddleware(vbxtrace.Middleware))
ginr.Run(addr) → vbxtrace.ListenAndServe(addr, r), and r.Use(vbxgin.Middleware())
fasthttpfasthttp.ListenAndServe(addr, h) → fasthttp.ListenAndServe(addr, vbxfasthttp.Handler(h))
fiber v2app.Use(vbxfiber.New()) first after fiber.New()
gRPCgrpc.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 ofUse
cmd.Run(), cmd.Start(), cmd.Output(), cmd.CombinedOutput()vbxtrace.Run(ctx, cmd), Start, Output, CombinedOutput
os.StartProcess(...)vbxtrace.StartProcess(ctx, ...)
net.Dial, (&net.Dialer{}).DialContextvbxtrace.DialContext(ctx, network, addr), or vbxtrace.Dialer{}
a driver's or http.Transport's dial functionvbxtrace.WrapDialContext(dial)
os.OpenFile, os.Open, os.Createvbxtrace.OpenFile(ctx, ...), Open, Create
a connection or file obtained elsewherevbxtrace.Connected(ctx, conn), vbxtrace.Opened(ctx, f, flag)

Example (the full proposal examples are in hooks/go/g2/proposals/*.diff):

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 ​

go
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 ​

EventEmitted fromJoin key
request_begin / request_endvbxtrace.Handler (installed by ListenAndServe/Server), vbxfasthttp.Handler, vbxfiber.New, vbxgrpc interceptors, Session, ConnRequest, Beginthe accepted connection's peer address and port, the request's index on it, the local port
spawnedRun, Start, Output, CombinedOutput, StartProcess, Spawnedthe child's pid
connectedDialContext, Dialer, WrapDialContext, Connectedthe connection's local port (TCP, connected UDP; unix sockets with transport unix)
openedOpenFile, Open, Create, Openedpid + fd; flags are what os.OpenFile passes to open(2) (the flag plus O_CLOEXEC)
handoffvbxtrace.Handoff(ctx)the two context ids

Request index. It is exact or it is unknown, never a guess:

  • net/http: ConnContext stamps each connection accepted while a tracer listens and counts its requests. Connections accepted before the tracer attached (or by a server without ConnContext) are reported with index unknown (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:noinline functions 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/vbxtrace is mounted): libvbxtrace-<arch>.so is loaded with dlopen and 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, so c.Value finds it in a *gin.Context (after vbxgin.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 .probes section. 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_total counts 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/sql pools 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 is unknown.
  • 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.Error code, else 500); a custom error handler may send something else. The status is not a join key.
  • gin and echo through their own Run/Start without the server change get the middleware's context but unknown indexes (no ConnContext).
  • 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 defer without recover).
  • Nothing is wrapped that the handler sees: the ResponseWriter is passed on as it is (so http.Flusher, http.Hijacker, io.ReaderFrom stay visible), and the request is the server's own, with only its context extended. The status is read from net/http's response after the handler.
  • The wrappers call exactly the function they replace with the same arguments and return its results; Run is Start then Wait, as exec.Cmd.Run is. File descriptors are read with SyscallConn, never Fd() (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=0 in 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), or strings -a <binary> | grep vbxtracegoprobe for 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, or off (VBXTRACE=0, or switched off after errors). VBXTRACE_DEBUG=1 prints why loading the core library failed. With the core backend, /opt/vbxtrace/libvbxtrace-*.so appears in /proc/<pid>/maps.
  • Requests show request_index=unknown. The server is not started through vbxtrace.ListenAndServe/vbxtrace.Server (no ConnContext), or the connections were accepted before the sensor attached.
  • No spawned/connected/opened for a request. The call is not wrapped, or it gets a context that is not the request's (check that the handler passes r.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 download before copying the source; add COPY vbxtrace ./vbxtrace before it.