.NET startup hook (D1)
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 ASP.NET Core services on Kestrel (minimal APIs, MVC, Razor Pages, gRPC, SignalR) and other .NET services where one thread-pool thread serves many requests in turn. It gets in compose-only: a read-only mount of the hook directory plus DOTNET_STARTUP_HOOKS, with the image and source left as they are. Raw TcpListener servers and trimmed or Native AOT apps (which cannot load startup hooks) use a small source change instead: one vendored C# file and one line.
Covers
| Versions | |
|---|---|
| .NET runtime (framework-dependent apps) | 6, 7, 8, 9, 10 — tested on each, glibc (Debian/Ubuntu images) and musl (Alpine) |
| Kestrel | HTTP/1.1, HTTP/2 (h2c and TLS), HTTP/3, WebSocket upgrades |
| Frameworks on Kestrel | minimal APIs, MVC / Web API controllers, Razor Pages, gRPC (Grpc.AspNetCore), SignalR, static files, anything built on ASP.NET Core hosting |
Raw socket servers (TcpListener, Socket.Accept*) | source change, .NET 6+ |
Trimmed (PublishTrimmed) and Native AOT (PublishAot) apps | source change (middleware), .NET 8+ for AOT web apps |
| x86_64, aarch64 | the core is picked by RuntimeInformation.ProcessArchitecture |
What the kernel links without this hook. Nothing useful, for most .NET services. ASP.NET Core runs every request on the shared thread pool, and an await can resume the request on a different thread. So a thread is never a request, and the kernel's "one live client socket per thread" rule does not apply. Only apps that spawn a process per connection, or run strictly one request at a time, are linked by the kernel alone.
Runtimes older than .NET 6 are not supported. The hook notices them and does nothing (see Safety).
How it gets in
From a registry (local development, or a build with network; the same release as the hook directory): NuGet: dotnet add package VbxTrace.Sources --version 1.0.0 (source change), or VbxTrace.StartupHook with DOTNET_STARTUP_HOOKS=<package>/tools/vbxtrace/dotnet/VbxTrace.StartupHook.dll; see Local development.
Compose-only (Kestrel apps, the default)
services:
<service>:
+ volumes:
+ - /usr/local/lib/vulnboxd/trace:/opt/vbxtrace:ro
+ environment:
+ DOTNET_STARTUP_HOOKS: /opt/vbxtrace/dotnet/VbxTrace.StartupHook.dllIf the service already sets DOTNET_STARTUP_HOOKS (for example for OpenTelemetry auto-instrumentation), the hub appends the path with : instead of replacing the value. Paths in the variable must be absolute. It works the same with dotnet app.dll, an apphost executable (./app) and single-file (not trimmed) apps, because the runtime reads the variable in every case.
To apply it by hand, add the two blocks above to the service in docker-compose.yml and recreate the container. No rebuild is needed.
The hub proposes this (template hooks/dotnet/d1/proposals/compose.toml) when it detects *.csproj, *.fsproj, *.vbproj, global.json or a solution file, a base image mcr.microsoft.com/dotnet/{aspnet,runtime,sdk}:{6..10}.*, or a command like dotnet <app>.dll. It does not propose it when the project sets PublishAot or PublishTrimmed.
Source change: raw TcpListener servers
A hand-written socket server is not ASP.NET Core, so there is no hosting event to listen to. The service marks each connection as a session itself (template proposals/source-tcplistener.toml, example proposals/tcplistener.diff):
Copy
/usr/local/lib/vulnboxd/trace/dotnet/vendor/VbxTrace.csinto the project asvendor/vbxtrace/VbxTrace.cs. The SDK compiles every.csbelow the project directory, so the project file needs no<Compile>item.Add
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>to the project file. The file calls the core through function pointers, which C# only allows in unsafe code.Add one line at the top of the per-connection handler:
csharpusing Vulnboxd.Trace; static async Task Handle(TcpClient client) { using var _ = VbxTrace.Session(client); // one session per connection, until the handler returns ... }Add the read-only mount (the core library lives there):
- /usr/local/lib/vulnboxd/trace:/opt/vbxtrace:ro.
VbxTrace.Session also accepts a Socket. A hand-written server that speaks a request/response protocol over one connection can mark each request instead, with using var r = VbxTrace.Request(socket, index, VbxProtocol.Http1); … r.End(status);.
Source change: trimmed and Native AOT ASP.NET Core apps
Trimmed and AOT apps are built with startup hooks switched off, so the runtime ignores DOTNET_STARTUP_HOOKS: no error, and no hook. For these, the hub proposes proposals/source-aspnetcore-aot.toml (example proposals/aspnetcore-aot.diff):
- Copy
VbxTrace.csandVbxTrace.AspNetCore.csfrom/usr/local/lib/vulnboxd/trace/dotnet/vendor/tovendor/vbxtrace/. - Add
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>. - In
Program.cs, addusing Vulnboxd.Trace;and putapp.UseVbxTrace();directly aftervar app = builder.Build();, before any other middleware. - Add the read-only mount.
Both files are trim- and AOT-safe: no reflection, only base class library and ASP.NET Core APIs. Define VBXTRACE_PUBLIC to make the API public if you vendor the files into a shared class library. Several vendored copies in one process (or a vendored copy plus the startup hook) agree on a single context and report every request once.
What it records
| Event | Emitted from | Join key |
|---|---|---|
request_begin | ASP.NET Core hosting's Microsoft.AspNetCore.Hosting.BeginRequest diagnostic event (startup hook), app.UseVbxTrace() (source change), VbxTrace.Session/Request (raw servers) | accepted socket's local port, peer address and port (HttpContext.Connection), request index, protocol |
request_end | …Hosting.EndRequest, or …Hosting.UnhandledException when the app threw. The status is HttpContext.Response.StatusCode (500 for a thrown request; 101 for a WebSocket after it closed; 0 for a raw session) | context id |
context_enter / context_exit | the request context's AsyncLocal change notification, on every thread that starts or stops running the request's code | the thread (pid, tid) |
spawned, connected, opened | only when the service calls VbxTrace.Spawned(process), VbxTrace.Connected(socket) or VbxTrace.Opened(handle) (optional, source change) | child pid / local port / pid + fd |
Request index. Kestrel numbers the requests of every connection itself, and puts the number in HttpContext.TraceIdentifier (<connection id>:<8 hex digits>):
- HTTP/1.x: the request count on the connection. Index 0 is the first request on the connection. On ASP.NET Core 6 the count starts one higher, and the hook corrects for that.
- HTTP/2: the stream id (client streams 1, 3, 5, …). The index is the stream's position in that sequence, so gRPC calls on one connection get 0, 1, 2, ….
- HTTP/3: stream id / 4.
Kestrel keeps this counter whether or not anything traces, so the index stays exact even when the sensor attaches in the middle of a keep-alive connection. When the identifier is not Kestrel's (another IServer, or a middleware that replaced it before the hook read it, which is rare because the hook reads it first), the hook sends VBX_REQUEST_INDEX_UNKNOWN instead of guessing.
Protocol. http1 for HTTP/1.x, websocket for an HTTP/1.1 WebSocket upgrade (one request for the whole socket, ending when it closes), http2, grpc (HTTP/2 with Content-Type: application/grpc*) and http3. A raw session is raw.
Process starts, file opens and outgoing connections are linked by the sensor through the thread windows, not by events from the hook. .NET makes each of these syscalls on the thread that runs the request's code, synchronously:
Process.Startforks there.FileStream/File.*open there.Socket.ConnectandConnectAsyncissueconnect(2)there before their firstawait.HttpClient, Npgsql, StackExchange.Redis and others go through these.
That thread is inside the request's context_enter … context_exit window at that moment, so the sensor joins the kernel's fork, openat or connect event on that thread to the request. This is an exact join: the runtime itself says which request's code was running on that thread. The D1 samples check it on every run. They record a marker on the thread that made each syscall and verify that it lies inside the right request's window.
Context following
The current request is an AsyncLocal<ulong> (the context id). .NET's ExecutionContext carries it through await, Task.Run, Task.Factory.StartNew, ThreadPool.QueueUserWorkItem, new Thread(...), timers, Parallel.* and IAsyncEnumerable. Nothing needs to be wrapped.
The hosting layer raises BeginRequest synchronously inside the request's own async flow, the same place ASP.NET Core sets Activity.Current. So the context the hook sets there is the request's from then on, including middleware, endpoint, filters, gRPC handler, SignalR hub method invocations, and response writing. At EndRequest the hook clears the context again, so the connection's next keep-alive request starts clean.
The AsyncLocal is created with a change handler, which the runtime calls on a thread whenever that thread's value changes. Typical causes:
- an
awaitcontinuation starts there; - a thread-pool work item carrying the request's context starts or finishes;
- the hook sets or clears the value.
The handler emits context_exit(old) and context_enter(new). That gives the sensor a per-thread window for every piece of every request, with no handoff needed. Work started with ExecutionContext.SuppressFlow() or UnsafeQueueUserWorkItem deliberately runs without the context, and is not attributed.
Known gaps
Work that captured a request's context outlives the request. Examples: a fire-and-forget
Task.Run, a timer, or a background loop created lazily during the first request (a connection multiplexer's reader loop). Its later syscalls stay attributed to that request. That is what the runtime says, and usually right: that request started the work. The .NET libraries themselves create their long-lived loops without flowing context.WebSockets over HTTP/2 (extended CONNECT, .NET 7+) are reported as
http2, notwebsocket.Kestrel connection handlers (
ListenOptions.UseConnectionHandler<T>, raw TCP inside Kestrel) raise no hosting events, so they are not covered. A connection handler can mark the session itself withusing var _ = VbxTrace.Request(connection.LocalEndPoint, connection.RemoteEndPoint, 0, VbxProtocol.Raw);(source change).SignalR: a WebSocket connection is one request for its whole life. The individual hub method calls inside it are not separate requests (they all link to the connection's request). Long polling and SSE transports are one request per poll.
Syscalls on other threads. A native library doing I/O on its own threads (for example a native SQLite build with a worker thread, which is rare) is not linked.
Runtimes older than .NET 6: the hook switches itself off (no events).
Trimmed / Native AOT apps ignore startup hooks: use the source change.
IIS / HTTP.sys (Windows only) and other
IServers: request boundaries work, but the index isVBX_REQUEST_INDEX_UNKNOWN.No method patching.
Process.Start, file opens and connects publish no diagnostics events. Wrapping them would mean patching framework methods at run time. That approach was evaluated and rejected:- MonoMod.RuntimeDetour (MIT) is large, rewrites JIT-compiled code, lags behind new runtimes, and conflicts with apps that use Harmony or MonoMod themselves.
- A hand-written jump patch breaks under tiered compilation and ReadyToRun code being replaced.
- A CLR profiler doing ReJIT takes the process's only profiler slot (APM agents and dotnet-monitor need it).
The thread windows give the same exact links without touching any framework code.
Safety
- Two assemblies, loaded from the read-only mount:
VbxTrace.StartupHook.dllis a trampoline built for netcoreapp3.0, so it loads into every runtime that has startup hooks. It returns at once whenVBXTRACE=0is set or the runtime is older than .NET 6. Otherwise it loadsVbxTrace.StartupHook.Impl.dll(.NET 6+).- A startup hook that throws would stop the service from starting, so the trampoline catches everything.
- Nothing is patched or wrapped:
- The hook subscribes to
DiagnosticListener"Microsoft.AspNetCore" and enables exactly three events (BeginRequest,EndRequest,UnhandledException). - It deliberately does not enable
HttpRequestInand installs noActivityListener. Either would make ASP.NET Core createActivityobjects, and anActivitymakesHttpClientadd atraceparentheader to outgoing requests, which would change the service's traffic. - Logging, headers and responses are unchanged.
- The hook subscribes to
- While no tracer is attached, the per-request cost is the hosting layer asking whether
BeginRequestis enabled. The hook answers with one call into the core (vbx_v1_enabled_mask, a memory read). No context is set, so the runtime's context switches carry no notification work. - Guards:
- Every callback and every call into the core is guarded.
- The
AsyncLocalchange handler catches everything (an exception there would terminate the process). - Nothing the hook does changes an argument, a return value, an exception or a status of the service.
- Off after 5 internal errors for the process. With
VBXTRACE_DEBUG=1the hook prints its state and errors to stderr, as lines starting withvbxtrace[dotnet]:. - Chaos test. With
VBXTRACE_CHAOS=1every event call into the core throws inside its guard. In this test mode the binding never switches off, so every guard stays exercised. The samples' responses are byte-identical with the hook failing, working, or absent. - Overhead has not been measured yet; that is a later 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.
- Compose-only: removing the
DOTNET_STARTUP_HOOKSentry (or the whole change) removes the hook completely, because the image was never touched. - Source change:
VBXTRACE=0turns the vendored code off as well. To remove it, revert the commit: deletevendor/vbxtrace/, theSession/UseVbxTraceline, andAllowUnsafeBlocksif nothing else needs it.
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?
grep vbxtrace /proc/<pid>/mapsinside the container (or via/proc/<host pid>/mapson the host) showslibvbxtrace-x86_64.soonce the hook is active. Run the service once withVBXTRACE_DEBUG=1: it printsvbxtrace[dotnet]: active (/opt/vbxtrace/…), or why not (off (VBXTRACE=0),off (libvbxtrace-x86_64.so not found)). - Which links did a flow get? The hub shows each link's method; this package's are
hook:D1. - No output at all with
VBXTRACE_DEBUG=1:- The startup hook did not run. Check that the variable reaches the process:
cat /proc/<pid>/environ | tr '\0' '\n' | grep DOTNET_STARTUP_HOOKS. - The path must be absolute and the file readable, which needs the mount.
- Trimmed / AOT apps ignore the variable: use the source change.
- The startup hook did not run. Check that the variable reaches the process:
- The service does not start, with "Startup hook assembly … failed to load": the path in
DOTNET_STARTUP_HOOKSis wrong (mount missing or misspelt). The hub's proposal always adds the mount together with the variable. - Requests appear but spawns do not link: the sensor must attach
context_enter/context_exit(the thread windows). The hook emits them only while those probes are attached. request_indexis unknown: the service runs on a server other than Kestrel, or replacesHttpContext.TraceIdentifiervery early.
For developers
- Sources:
hooks/dotnet/d1/src/. - Build:
hooks/dotnet/d1/build.shbuilds both DLLs intohooks/dotnet/d1/dotnet/(git-ignored). The harness runs it before staging. It uses the host's .NET SDK, ormcr.microsoft.com/dotnet/sdk:10.0through podman. - Samples:
hooks/run-samples.sh dotnetruns all six, each in events, chaos and baseline mode.
| Sample | What it covers |
|---|---|
minimal | Minimal API run in turn on .NET 6, 7, 8, 9 and 10: keep-alive indexes, 404, 500, Process.Start, FileStream, Socket.Connect / ConnectAsync, Task.Run, a second connection |
mvc | Controllers on .NET 9 |
grpc | Grpc.AspNetCore on .NET 8, three calls on one HTTP/2 connection |
signalr | Hub over WebSocket on .NET 10 Alpine (musl) |
tcplistener | Source change: raw server on .NET 8 Alpine |
aot | Source change: Native AOT on .NET 10 with UseVbxTrace() |