Skip to content

Hook cheat sheet: Rust ​

How to add a vulnboxd runtime hook to a Rust service by hand. Find your setup in the table, then follow its block.

  • Without source access: only the compose file changes; redeploy. With source access: you change the code or Dockerfile and rebuild.
  • Hub automation says how much the hub's proposals do for you. Fully: approve the proposal in the hub; the block is the fallback when it failed. With conditions: the same, when the conditions listed hold. Partly: the hub pushes the compose part, the rest is yours. Not at all: everything is by hand.
  • /usr/local/lib/vulnboxd/trace is the hook directory vulnboxd installs on the vulnbox. Compose snippets mount it read-only at /opt/vbxtrace in the container.
  • How to check that the hook works and undo it is at the end of the page.
  • Runtime hooks explains what a hook does.

Rust ​

SetupUse this whenChangeHub automation
Add the vulnboxd hook to a Rust WebAssembly host (wasmtime / wasmer)Depends on wasmtime, wasmtime-wasi, wasmtime-wasi-http, wasmer or wasmer-wasix (in Cargo.toml), and only if a Cargo.toml file matches the pattern belowsource, rebuildnot at all
Rust hook for actix-web 4Depends on actix-web (in Cargo.toml)source, rebuildnot at all
Rust hook for axumDepends on axum (in Cargo.toml)source, rebuildnot at all
Rust hook for hyper 1 (own accept loop)Depends on hyper or hyper-util (in Cargo.toml)source, rebuildnot at all
Rust hook for poem 3Depends on poem (in Cargo.toml)source, rebuildnot at all
Rust hook for Rocket 0.5Depends on rocket (in Cargo.toml)source, rebuildnot at all
Rust hook for Salvo 1Depends on salvo (in Cargo.toml)source, rebuildnot at all
Rust hook for raw tokio TCP serverDepends on tokio (in Cargo.toml)source, rebuildnot at all
Rust hook for tonic gRPC serverDepends on tonic (in Cargo.toml)source, rebuildnot at all
Rust hook for warp 0.3 / hyper 0.14Depends on warp or hyper (in Cargo.toml)source, rebuildnot at all
Rust hook for glommio 0.9Depends on glommio (in Cargo.toml)source, rebuildnot at all
Rust hook for may coroutines / may_minihttpDepends on may or may_minihttp (in Cargo.toml)source, rebuildnot at all
Rust hook for monoio 0.2Depends on monoio (in Cargo.toml)source, rebuildnot at all
Rust hook for smol 2Depends on smol or async-executor (in Cargo.toml)source, rebuildnot at all
Rust hook for std threads (thread per connection)Started with cargosource, rebuildnot at all
Rust hook for tide 0.16 (async-std)Depends on tide (in Cargo.toml)source, rebuildnot at all

With source access ​

These change the service's code or Dockerfile, then it is rebuilt.

Add the vulnboxd hook to a Rust WebAssembly host (wasmtime / wasmer) ​

  • Use this when: Rust service that depends on wasmtime, wasmtime-wasi, wasmtime-wasi-http, wasmer or wasmer-wasix (in Cargo.toml), and only if a Cargo.toml file matches the pattern below.
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd's Rust hook into the host, wraps its hyper/axum service so each request has a context, carries that context into the guest call (spawn_blocking / spawn / bind), and swaps the host functions' std/tokio process, file and socket calls for the traced wrappers, so child processes, files and connections the guest causes through the host are linked to the request. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network (as for R1).
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = [the server integration the host uses: "hyper1" / "axum08" / ..., plus "tokio"] }; add "vendor/vbxtrace" to [workspace] exclude if there is a workspace.
  3. Request boundaries as for R1: hyper accept loop → vbxtrace_hook::Trace::with_conn(service, vbxtrace_hook::ConnInfo::from_tokio(&stream)); axum → vbxtrace_hook::axum::trace(app).
  4. The guest call: tokio::task::spawn_blocking(f) → vbxtrace_hook::tokio::spawn_blocking(f); tokio::spawn(fut) → vbxtrace_hook::tokio::spawn(fut); any other future that runs the guest → vbxtrace_hook::bind(fut). Async wasmtime (call_async on fibers) inside the request's task needs nothing.
  5. Host functions the guest imports (Linker::func_wrap / custom WASI hooks): std::process::Command spawn/status/output → spawn_traced/status_traced/output_traced (vbxtrace_hook::process::CommandExt); std::fs::{File::open, File::create, read, write, OpenOptions} → vbxtrace_hook::fs::*; std::net::TcpStream::connect → vbxtrace_hook::net::connect; tokio equivalents → vbxtrace_hook::tokio::{process, fs, net}.
  6. wasmtime-wasi's own filesystem and socket implementation cannot be wrapped without forking it: its files and sockets get no hook event (wasmtime-wasi may move file I/O to its own blocking tasks, which carry no context). What the host's own host functions do is exact; prefer custom host functions for effects that matter.
  7. Make sure the Dockerfile copies vendor/ before cargo build.

Example change on a sample service (hooks/wasm/x2/proposals/wasmtime-host.diff):

diff
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,3 +12,4 @@ http-body-util = "0.1"
 tokio = { version = "1", features = ["full"] }
 wasmtime = "25"
+vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["hyper1", "tokio"] }
--- a/src/main.rs
+++ b/src/main.rs
@@ -20,10 +20,11 @@ use wasmtime::{Caller, Engine, Linker, Module, Store};
+use vbxtrace_hook::process::CommandExt;
 
 fn host_run(_: Caller<'_, ()>) -> i32 {
-    match std::process::Command::new("/usr/bin/convert").spawn().and_then(|mut c| c.wait()) {
+    match std::process::Command::new("/usr/bin/convert").spawn_traced().and_then(|mut c| c.wait()) {
         Ok(s) if s.success() => 0,
         _ => -1,
     }
 }
 
 fn host_save(_: Caller<'_, ()>) -> i32 {
-    if std::fs::write("/data/out", "...").is_ok() { 0 } else { -1 }
+    if vbxtrace_hook::fs::write("/data/out", "...").is_ok() { 0 } else { -1 }
 }
@@ -60,7 +61,7 @@ async fn handler(host: Arc<Host>, req: Request<Incoming>) -> Result<Response<Full<Bytes>>, Infallible> {
     let work = move || host.handle(route);
-    let result = tokio::task::spawn_blocking(work).await;
+    let result = vbxtrace_hook::tokio::spawn_blocking(work).await;
@@ -80,9 +81,10 @@ async fn serve() {
         let (stream, _) = listener.accept().await.unwrap();
+        let conn = vbxtrace_hook::ConnInfo::from_tokio(&stream);
         let io = TokioIo::new(stream);
         let host = host.clone();
         tokio::spawn(async move {
             let svc = service_fn(move |req| handler(host.clone(), req));
+            let svc = vbxtrace_hook::Trace::with_conn(svc, conn);
             let _ = hyper::server::conn::http1::Builder::new().serve_connection(io, svc).await;
         });
--- a/Dockerfile
+++ b/Dockerfile
@@ -2,5 +2,6 @@ FROM rust:1-alpine AS build
 WORKDIR /app
 COPY Cargo.toml Cargo.lock ./
+COPY vendor ./vendor
 COPY src ./src
 RUN cargo build --release
Exact detection rules

Package X2 (WebAssembly hosts), proposal X2:wasmtime-host, defined in hooks/wasm/x2/proposals/wasmtime-host.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:
  • Command matches (regex): \bcargo\b
  • Dependency on: wasmtime, wasmtime-wasi, wasmtime-wasi-http, wasmer, wasmer-wasix
  • Files: Cargo.toml, Cargo.lock, *.wat, *.wasm, **/*.wit
  • Required: a Cargo.toml file matching (?m)^\s*(wasmtime|wasmer)[a-z-]*\s*=

Rust hook for actix-web 4 ​

  • Use this when: Rust service that depends on actix-web (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the actix-web 4 setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["actix-web4" (+ "tokio-process" / "tokio-fs" / "tokio-net" for what the service uses)] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. Add .wrap(vbxtrace_hook::actix::Trace) to the App (outermost wrap) and .on_connect(vbxtrace_hook::actix::on_connect) to the HttpServer (an existing on_connect callback f becomes on_connect(vbxtrace_hook::actix::on_connect_with(f))).
  4. Replace the calls whose effects should be linked: std::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (vbxtrace_hook::process::CommandExt); std::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::fs::*; TcpStream::connect → vbxtrace_hook::net::connect.
  5. Context into new work: actix_web::rt::spawn(fut) → actix_web::rt::spawn(vbxtrace_hook::bind(fut)); web::block(f) → web::block(vbxtrace_hook::thread::wrap(f)).
  6. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).

Example change on a sample service (hooks/rust/r1/proposals/actix-web.diff):

diff
# The source change the hub proposes for a service on actix-web (here: tests/offline/actix-web), after the hook
# directory was copied to vendor/vbxtrace. Apply with `patch -p1`.

diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -9,3 +9,4 @@
 
 [dependencies]
 actix-web = "4"
+vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["actix-web4"] }
diff -ruN a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -5,16 +5,18 @@
 //! A typical small CTF service, before the hook: what the proposal diff applies to.
 
 use actix_web::{get, web, App, HttpServer, Responder};
+use vbxtrace_hook::process::CommandExt;
 
 #[get("/run/{cmd}")]
 async fn run(cmd: web::Path<String>) -> impl Responder {
-    let out = std::process::Command::new("sh").arg("-c").arg(cmd.as_str()).output().unwrap();
+    let out = std::process::Command::new("sh").arg("-c").arg(cmd.as_str()).output_traced().unwrap();
     String::from_utf8_lossy(&out.stdout).into_owned()
 }
 
 #[actix_web::main]
 async fn main() -> std::io::Result<()> {
-    HttpServer::new(|| App::new().service(run))
+    HttpServer::new(|| App::new().wrap(vbxtrace_hook::actix::Trace).service(run))
+        .on_connect(vbxtrace_hook::actix::on_connect)
         .bind(("0.0.0.0", 8000))?
         .run()
         .await
Exact detection rules

Package R1 (Rust tokio crate), proposal R1:actix-web, defined in hooks/rust/r1/proposals/actix-web.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: actix-web
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for axum ​

  • Use this when: Rust service that depends on axum (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd's Rust hook into the service and wraps axum::serve's make service, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["axum07" or "axum08" (the axum the lockfile has), plus "tokio-process" / "tokio-fs" / "tokio-net" for what the service uses] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. Wrap the make service: axum::serve(listener, X) becomes axum::serve(listener, vbxtrace_hook::axum::trace(X)), whatever X is (a Router, into_make_service(), into_make_service_with_connect_info::<C>()).
  4. Replace the calls whose effects should be linked: tokio::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (use vbxtrace_hook::tokio::process::CommandExt); tokio::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::tokio::fs::*; tokio::net::TcpStream::connect → vbxtrace_hook::tokio::net::connect; std::process / std::fs / std::net likewise → vbxtrace_hook::{process::CommandExt, fs, net}.
  5. Context into new work: tokio::spawn → vbxtrace_hook::tokio::spawn, tokio::task::spawn_blocking → vbxtrace_hook::tokio::spawn_blocking, JoinSet::spawn → spawn_traced (vbxtrace_hook::tokio::JoinSetExt).
  6. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).

Example change on a sample service (hooks/rust/r1/proposals/axum.diff):

diff
# The source change the hub proposes for an axum service (here: tests/offline/axum), after the hook
# directory was copied to vendor/vbxtrace. Apply with `patch -p1`.

diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,3 +10,4 @@
 [dependencies]
 axum = "0.8"
 tokio = { version = "1", features = ["full"] }
+vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["axum08", "tokio-fs", "tokio-process"] }
diff -ruN a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -5,13 +5,14 @@
 //! A typical small CTF service, before the hook: what the proposal diff applies to.
 
 use axum::{extract::Path, routing::get, Router};
+use vbxtrace_hook::tokio::process::CommandExt;
 
 async fn note(Path(id): Path<String>) -> String {
-    tokio::fs::read_to_string(format!("/data/{id}")).await.unwrap_or_default()
+    vbxtrace_hook::tokio::fs::read_to_string(format!("/data/{id}")).await.unwrap_or_default()
 }
 
 async fn ping(Path(host): Path<String>) -> String {
-    let out = tokio::process::Command::new("ping").args(["-c1", &host]).output().await.unwrap();
+    let out = tokio::process::Command::new("ping").args(["-c1", &host]).output_traced().await.unwrap();
     String::from_utf8_lossy(&out.stdout).into_owned()
 }
 
@@ -21,5 +22,5 @@
         .route("/note/{id}", get(note))
         .route("/ping/{host}", get(ping));
     let listener = tokio::net::TcpListener::bind("0.0.0.0:8000").await.unwrap();
-    axum::serve(listener, app).await.unwrap();
+    axum::serve(listener, vbxtrace_hook::axum::trace(app)).await.unwrap();
 }
Exact detection rules

Package R1 (Rust tokio crate), proposal R1:axum, defined in hooks/rust/r1/proposals/axum.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: axum
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for hyper 1 (own accept loop) ​

  • Use this when: Rust service that depends on hyper or hyper-util (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the hyper 1 (own accept loop) setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["hyper1" (+ "tokio-process" / "tokio-fs")] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. In the accept loop: let conn = vbxtrace_hook::ConnInfo::from_tokio(&stream); before wrapping the stream, and serve vbxtrace_hook::Trace::with_conn(service, conn) instead of service (hyper's http1/http2/auto builders and TowerToHyperService all take it). warp 0.4 (hyper 1) is served the same way via warp::service.
  4. Replace the calls whose effects should be linked: tokio::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (use vbxtrace_hook::tokio::process::CommandExt; feature tokio-process); tokio::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::tokio::fs::* (tokio-fs); tokio::net::TcpStream::connect → vbxtrace_hook::tokio::net::connect (tokio-net); std::process / std::fs / std::net likewise → vbxtrace_hook::{process::CommandExt, fs, net}.
  5. Context into new work: tokio::spawn → vbxtrace_hook::tokio::spawn, tokio::task::spawn_blocking → vbxtrace_hook::tokio::spawn_blocking, JoinSet::spawn → spawn_traced (vbxtrace_hook::tokio::JoinSetExt).
  6. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).
Complete example: hyper/src/main.rs

hooks/rust/r1/samples/hyper/src/main.rs, with the hook added.

rust
//! The hyper 1 sample: an accept loop, `serve_connection` per connection, and handlers that use the
//! std wrappers (blocking calls inside async handlers, as small services do).

mod driver;

use std::convert::Infallible;

use bytes::Bytes;
use http_body_util::Full;
use hyper::service::service_fn;
use hyper::{Request, Response};
use hyper_util::rt::TokioIo;

#[cfg(feature = "hook")]
use vbxtrace_hook::process::CommandExt;

async fn handler(req: Request<hyper::body::Incoming>) -> Result<Response<Full<Bytes>>, Infallible> {
    let (status, body): (u16, String) = match req.uri().path() {
        "/hello" => (200, "hello\n".into()),
        "/spawn" => {
            // std's output(): the thread is marked as working for the request while it blocks.
            let mut cmd = std::process::Command::new("/bin/echo");
            cmd.arg("spawned");
            #[cfg(feature = "hook")]
            let out = cmd.output_traced().unwrap();
            #[cfg(not(feature = "hook"))]
            let out = cmd.output().unwrap();
            (200, String::from_utf8_lossy(&out.stdout).into_owned())
        }
        "/file" => {
            std::fs::write("/tmp/hyper-flag", "flag{sample}\n").unwrap();
            #[cfg(feature = "hook")]
            let s = vbxtrace_hook::fs::read_to_string("/tmp/hyper-flag").unwrap();
            #[cfg(not(feature = "hook"))]
            let s = std::fs::read_to_string("/tmp/hyper-flag").unwrap();
            (200, s)
        }
        "/connect" => {
            #[cfg(feature = "hook")]
            let s = vbxtrace_hook::net::connect("127.0.0.1:8081");
            #[cfg(not(feature = "hook"))]
            let s = std::net::TcpStream::connect("127.0.0.1:8081");
            drop(s.unwrap());
            (200, "connected\n".into())
        }
        _ => (404, "not found\n".into()),
    };
    Ok(Response::builder().status(status).body(Full::new(Bytes::from(body))).unwrap())
}

async fn serve() {
    let _side = tokio::net::TcpListener::bind("127.0.0.1:8081").await.unwrap();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await.unwrap();
    loop {
        let (stream, _) = listener.accept().await.unwrap();
        #[cfg(feature = "hook")]
        let conn = vbxtrace_hook::ConnInfo::from_tokio(&stream);
        let io = TokioIo::new(stream);
        tokio::spawn(async move {
            #[cfg(feature = "hook")]
            let svc = vbxtrace_hook::Trace::with_conn(service_fn(handler), conn);
            #[cfg(not(feature = "hook"))]
            let svc = service_fn(handler);
            let _ = hyper::server::conn::http1::Builder::new().serve_connection(io, svc).await;
        });
    }
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    match args.get(1).map(String::as_str) {
        Some("serve") => tokio::runtime::Runtime::new().unwrap().block_on(serve()),
        Some("drive") => driver::drive(&["/hello", "/missing"], &["/spawn", "/file", "/connect"]),
        Some("bench") => driver::bench(args[2].parse().unwrap(), "/hello"),
        _ => panic!("usage: sample serve | drive | bench N"),
    }
}
Exact detection rules

Package R1 (Rust tokio crate), proposal R1:hyper, defined in hooks/rust/r1/proposals/hyper.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: hyper, hyper-util
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for poem 3 ​

  • Use this when: Rust service that depends on poem (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the poem 3 setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["poem" (+ "tokio-process" / "tokio-fs" / "tokio-net")] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. Wrap the listener and add the middleware outermost: Server::new(vbxtrace_hook::poem::TracedListener(listener)).run(app.with(vbxtrace_hook::poem::Trace)) (use poem::EndpointExt).
  4. Replace the calls whose effects should be linked: tokio::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (use vbxtrace_hook::tokio::process::CommandExt; feature tokio-process); tokio::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::tokio::fs::* (tokio-fs); tokio::net::TcpStream::connect → vbxtrace_hook::tokio::net::connect (tokio-net); std::process / std::fs / std::net likewise → vbxtrace_hook::{process::CommandExt, fs, net}.
  5. Context into new work: tokio::spawn → vbxtrace_hook::tokio::spawn, tokio::task::spawn_blocking → vbxtrace_hook::tokio::spawn_blocking, JoinSet::spawn → spawn_traced (vbxtrace_hook::tokio::JoinSetExt).
  6. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).

Example change on a sample service (hooks/rust/r1/proposals/poem.diff):

diff
# The source change the hub proposes for a service on poem (here: tests/offline/poem), after the hook
# directory was copied to vendor/vbxtrace. Apply with `patch -p1`.

diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,3 +10,4 @@
 [dependencies]
 poem = "3"
 tokio = { version = "1", features = ["full"] }
+vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["poem", "tokio-fs"] }
diff -ruN a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -6,15 +6,15 @@
 
 use poem::listener::TcpListener;
 use poem::web::Path;
-use poem::{get, handler, Route, Server};
+use poem::{get, handler, EndpointExt, Route, Server};
 
 #[handler]
 async fn note(Path(id): Path<String>) -> String {
-    tokio::fs::read_to_string(format!("/data/{id}")).await.unwrap_or_default()
+    vbxtrace_hook::tokio::fs::read_to_string(format!("/data/{id}")).await.unwrap_or_default()
 }
 
 #[tokio::main]
 async fn main() -> Result<(), std::io::Error> {
-    let app = Route::new().at("/note/:id", get(note));
-    Server::new(TcpListener::bind("0.0.0.0:3000")).run(app).await
+    let app = Route::new().at("/note/:id", get(note)).with(vbxtrace_hook::poem::Trace);
+    Server::new(vbxtrace_hook::poem::TracedListener(TcpListener::bind("0.0.0.0:3000"))).run(app).await
 }
Exact detection rules

Package R1 (Rust tokio crate), proposal R1:poem, defined in hooks/rust/r1/proposals/poem.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: poem
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for Rocket 0.5 ​

  • Use this when: Rust service that depends on rocket (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the Rocket 0.5 setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["rocket05" (+ "tokio-process" / "tokio-fs" / "tokio-net")] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. Attach the fairing and wrap the routes: rocket::build().attach(vbxtrace_hook::rocket::Trace).mount(base, vbxtrace_hook::rocket::traced(routes![...])) for every mount.
  4. Optional, for exact request indexes: keep_alive = 0 (Rocket.toml, ROCKET_KEEP_ALIVE=0 or Config); with keep-alive on, requests are reported with an unknown index.
  5. Replace the calls whose effects should be linked: rocket::tokio::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (use vbxtrace_hook::tokio::process::CommandExt; feature tokio-process); tokio::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::tokio::fs::* (tokio-fs); tokio::net::TcpStream::connect → vbxtrace_hook::tokio::net::connect (tokio-net); std::process / std::fs / std::net likewise → vbxtrace_hook::{process::CommandExt, fs, net}.
  6. Context into new work: tokio::spawn → vbxtrace_hook::tokio::spawn, tokio::task::spawn_blocking → vbxtrace_hook::tokio::spawn_blocking, JoinSet::spawn → spawn_traced (vbxtrace_hook::tokio::JoinSetExt).
  7. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).

Example change on a sample service (hooks/rust/r1/proposals/rocket.diff):

diff
# The source change the hub proposes for a service on rocket (here: tests/offline/rocket), after the hook
# directory was copied to vendor/vbxtrace. Apply with `patch -p1`.

diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -9,3 +9,4 @@
 
 [dependencies]
 rocket = "0.5"
+vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["rocket05", "tokio-fs"] }
diff -ruN a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -8,10 +8,12 @@
 
 #[get("/note/<id>")]
 async fn note(id: &str) -> String {
-    rocket::tokio::fs::read_to_string(format!("/data/{id}")).await.unwrap_or_default()
+    vbxtrace_hook::tokio::fs::read_to_string(format!("/data/{id}")).await.unwrap_or_default()
 }
 
 #[launch]
 fn rocket() -> _ {
-    rocket::build().mount("/", routes![note])
+    rocket::build()
+        .attach(vbxtrace_hook::rocket::Trace)
+        .mount("/", vbxtrace_hook::rocket::traced(routes![note]))
 }
Exact detection rules

Package R1 (Rust tokio crate), proposal R1:rocket, defined in hooks/rust/r1/proposals/rocket.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: rocket
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for Salvo 1 ​

  • Use this when: Rust service that depends on salvo (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the Salvo 1 setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["salvo" (+ "tokio-process" / "tokio-fs" / "tokio-net")] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. Wrap the TCP acceptor and hoop the Service: Server::new(vbxtrace_hook::salvo::TracedAcceptor(acceptor)).serve(Service::new(router).hoop(vbxtrace_hook::salvo::Trace)).
  4. Replace the calls whose effects should be linked: tokio::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (use vbxtrace_hook::tokio::process::CommandExt; feature tokio-process); tokio::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::tokio::fs::* (tokio-fs); tokio::net::TcpStream::connect → vbxtrace_hook::tokio::net::connect (tokio-net); std::process / std::fs / std::net likewise → vbxtrace_hook::{process::CommandExt, fs, net}.
  5. Context into new work: tokio::spawn → vbxtrace_hook::tokio::spawn, tokio::task::spawn_blocking → vbxtrace_hook::tokio::spawn_blocking, JoinSet::spawn → spawn_traced (vbxtrace_hook::tokio::JoinSetExt).
  6. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).

Example change on a sample service (hooks/rust/r1/proposals/salvo.diff):

diff
# The source change the hub proposes for a service on salvo (here: tests/offline/salvo), after the hook
# directory was copied to vendor/vbxtrace. Apply with `patch -p1`.

diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,3 +10,4 @@
 [dependencies]
 salvo = "1"
 tokio = { version = "1", features = ["full"] }
+vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["salvo", "tokio-process"] }
diff -ruN a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -5,11 +5,12 @@
 //! A typical small CTF service, before the hook: what the proposal diff applies to.
 
 use salvo::prelude::*;
+use vbxtrace_hook::tokio::process::CommandExt;
 
 #[handler]
 async fn run(req: &mut Request) -> String {
     let cmd = req.param::<String>("cmd").unwrap_or_default();
-    let out = tokio::process::Command::new("sh").arg("-c").arg(cmd).output().await.unwrap();
+    let out = tokio::process::Command::new("sh").arg("-c").arg(cmd).output_traced().await.unwrap();
     String::from_utf8_lossy(&out.stdout).into_owned()
 }
 
@@ -17,5 +18,6 @@
 async fn main() {
     let router = Router::with_path("run/{cmd}").get(run);
     let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
-    Server::new(acceptor).serve(router).await;
+    let service = Service::new(router).hoop(vbxtrace_hook::salvo::Trace);
+    Server::new(vbxtrace_hook::salvo::TracedAcceptor(acceptor)).serve(service).await;
 }
Exact detection rules

Package R1 (Rust tokio crate), proposal R1:salvo, defined in hooks/rust/r1/proposals/salvo.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: salvo
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for raw tokio TCP server ​

  • Use this when: Rust service that depends on tokio (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the raw tokio TCP server setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["tokio-net" (+ "tokio-process" / "tokio-fs")] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. For each accepted socket: let conn = vbxtrace_hook::ConnInfo::from_tokio(&socket); then tokio::spawn(conn.session(handle(socket))) for one raw session per connection, or conn.begin(Protocol::Http1/Raw) per message with request.bind(fut).
  4. Replace the calls whose effects should be linked: tokio::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (use vbxtrace_hook::tokio::process::CommandExt; feature tokio-process); tokio::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::tokio::fs::* (tokio-fs); tokio::net::TcpStream::connect → vbxtrace_hook::tokio::net::connect (tokio-net); std::process / std::fs / std::net likewise → vbxtrace_hook::{process::CommandExt, fs, net}.
  5. Context into new work: tokio::spawn → vbxtrace_hook::tokio::spawn, tokio::task::spawn_blocking → vbxtrace_hook::tokio::spawn_blocking, JoinSet::spawn → spawn_traced (vbxtrace_hook::tokio::JoinSetExt).
  6. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).
Complete example: tokio-raw/src/main.rs

hooks/rust/r1/samples/tokio-raw/src/main.rs, with the hook added.

rust
//! The raw tokio sample: a hand-rolled line protocol server (it happens to speak just enough HTTP/1.1
//! for the shared driver) on `tokio::net::TcpListener`, a task per connection. Each connection is one
//! raw session: `ConnInfo::from_tokio(&socket).session(handler)`.

mod driver;

use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;

#[cfg(feature = "hook")]
use vbxtrace_hook::tokio::process::CommandExt;

async fn handle(path: &str) -> (u16, &'static str) {
    match path {
        "/hello" => (200, "hello\n"),
        "/spawn" => {
            let mut cmd = tokio::process::Command::new("/bin/true");
            #[cfg(feature = "hook")]
            cmd.status_traced().await.unwrap();
            #[cfg(not(feature = "hook"))]
            cmd.status().await.unwrap();
            (200, "spawned\n")
        }
        "/file" => {
            #[cfg(feature = "hook")]
            let f = vbxtrace_hook::tokio::fs::OpenOptions::new().append(true).create(true).open("/tmp/raw-log").await;
            #[cfg(not(feature = "hook"))]
            let f = tokio::fs::OpenOptions::new().append(true).create(true).open("/tmp/raw-log").await;
            f.unwrap().write_all(b"x\n").await.unwrap();
            (200, "appended\n")
        }
        "/connect" => {
            #[cfg(feature = "hook")]
            let s = vbxtrace_hook::tokio::net::connect("127.0.0.1:8081").await;
            #[cfg(not(feature = "hook"))]
            let s = tokio::net::TcpStream::connect("127.0.0.1:8081").await;
            drop(s.unwrap());
            (200, "connected\n")
        }
        _ => (404, "not found\n"),
    }
}

async fn session(sock: TcpStream) {
    let mut sock = BufReader::new(sock);
    loop {
        let mut line = String::new();
        if sock.read_line(&mut line).await.unwrap_or(0) == 0 {
            return;
        }
        let path = line.split_whitespace().nth(1).unwrap_or("").to_string();
        // the rest of the head
        loop {
            line.clear();
            if sock.read_line(&mut line).await.unwrap_or(0) == 0 || line == "\r\n" {
                break;
            }
        }
        let (status, body) = handle(&path).await;
        let resp = format!("HTTP/1.1 {status} X\r\nContent-Length: {}\r\n\r\n{body}", body.len());
        sock.get_mut().write_all(resp.as_bytes()).await.unwrap();
    }
}

async fn serve() {
    let _side = tokio::net::TcpListener::bind("127.0.0.1:8081").await.unwrap();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await.unwrap();
    loop {
        let (sock, _) = listener.accept().await.unwrap();
        // Connections are served one after the other so the sample's event order is fixed; a real
        // server would not await the task.
        #[cfg(feature = "hook")]
        let task = {
            let conn = vbxtrace_hook::ConnInfo::from_tokio(&sock);
            tokio::spawn(conn.session(session(sock)))
        };
        #[cfg(not(feature = "hook"))]
        let task = tokio::spawn(session(sock));
        task.await.unwrap();
    }
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    match args.get(1).map(String::as_str) {
        Some("serve") => tokio::runtime::Runtime::new().unwrap().block_on(serve()),
        Some("drive") => driver::drive(&["/hello", "/missing"], &["/spawn", "/file", "/connect"]),
        Some("bench") => driver::bench(args[2].parse().unwrap(), "/hello"),
        _ => panic!("usage: sample serve | drive | bench N"),
    }
}
Exact detection rules

Package R1 (Rust tokio crate), proposal R1:tokio-raw, defined in hooks/rust/r1/proposals/tokio-raw.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: tokio
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for tonic gRPC server ​

  • Use this when: Rust service that depends on tonic (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the tonic gRPC server setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["tonic" (+ "tokio-process" / "tokio-fs" / "tokio-net")] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. Serve through the hook's incoming stream and layer: let listener = tokio::net::TcpListener::bind(addr).await?; Server::builder().layer(vbxtrace_hook::tonic::TraceLayer)...serve_with_incoming(vbxtrace_hook::tonic::incoming(listener)) instead of .serve(addr). Builder tcp_nodelay/keepalive settings move to incoming(..).nodelay(..).
  4. Replace the calls whose effects should be linked: tokio::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (use vbxtrace_hook::tokio::process::CommandExt; feature tokio-process); tokio::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::tokio::fs::* (tokio-fs); tokio::net::TcpStream::connect → vbxtrace_hook::tokio::net::connect (tokio-net); std::process / std::fs / std::net likewise → vbxtrace_hook::{process::CommandExt, fs, net}.
  5. Context into new work: tokio::spawn → vbxtrace_hook::tokio::spawn, tokio::task::spawn_blocking → vbxtrace_hook::tokio::spawn_blocking, JoinSet::spawn → spawn_traced (vbxtrace_hook::tokio::JoinSetExt).
  6. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).

Example change on a sample service (hooks/rust/r1/proposals/tonic.diff):

diff
# The source change the hub proposes for a service on tonic (here: tests/offline/tonic), after the hook
# directory was copied to vendor/vbxtrace. Apply with `patch -p1`.

diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -11,3 +11,4 @@
 tonic = "0.14"
 tonic-health = "0.14"
 tokio = { version = "1", features = ["full"] }
+vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["tonic"] }
diff -ruN a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -9,9 +9,11 @@
 #[tokio::main]
 async fn main() {
     let (_reporter, health) = tonic_health::server::health_reporter();
+    let listener = tokio::net::TcpListener::bind("0.0.0.0:50051").await.unwrap();
     Server::builder()
+        .layer(vbxtrace_hook::tonic::TraceLayer)
         .add_service(health)
-        .serve("0.0.0.0:50051".parse().unwrap())
+        .serve_with_incoming(vbxtrace_hook::tonic::incoming(listener))
         .await
         .unwrap();
 }
Exact detection rules

Package R1 (Rust tokio crate), proposal R1:tonic, defined in hooks/rust/r1/proposals/tonic.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: tonic
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for warp 0.3 / hyper 0.14 ​

  • Use this when: Rust service that depends on warp or hyper (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the warp 0.3 / hyper 0.14 setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["hyper014" (+ "tokio-process" / "tokio-fs" / "tokio-net")] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. Serve per connection: warp::serve(routes).run(addr) becomes hyper::Server::bind(&addr).serve(make_service_fn(|conn: &AddrStream| { let svc = vbxtrace_hook::hyper014::trace(warp::service(routes.clone()), conn.local_addr(), conn.remote_addr()); async move { Ok::<_, Infallible>(svc) } })); add hyper = { version = "0.14", features = ["server", "tcp", "http1"] } if the service has no direct hyper dependency (warp already brings it). A hyper 0.14 make_service_fn wraps its per-connection service the same way.
  4. Replace the calls whose effects should be linked: tokio::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (use vbxtrace_hook::tokio::process::CommandExt; feature tokio-process); tokio::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::tokio::fs::* (tokio-fs); tokio::net::TcpStream::connect → vbxtrace_hook::tokio::net::connect (tokio-net); std::process / std::fs / std::net likewise → vbxtrace_hook::{process::CommandExt, fs, net}.
  5. Context into new work: tokio::spawn → vbxtrace_hook::tokio::spawn, tokio::task::spawn_blocking → vbxtrace_hook::tokio::spawn_blocking, JoinSet::spawn → spawn_traced (vbxtrace_hook::tokio::JoinSetExt).
  6. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).

Example change on a sample service (hooks/rust/r1/proposals/warp.diff):

diff
# The source change the hub proposes for a service on warp (here: tests/offline/warp), after the hook
# directory was copied to vendor/vbxtrace. Apply with `patch -p1`.

diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,3 +10,5 @@
 [dependencies]
 warp = "0.3"
 tokio = { version = "1", features = ["full"] }
+hyper = { version = "0.14", features = ["server", "tcp", "http1"] }
+vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["hyper014", "tokio-process"] }
diff -ruN a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -4,15 +4,21 @@
 
 //! A typical small CTF service, before the hook: what the proposal diff applies to.
 
+use hyper::server::conn::AddrStream;
+use vbxtrace_hook::tokio::process::CommandExt;
 use warp::Filter;
 
 async fn ping(host: String) -> Result<String, std::convert::Infallible> {
-    let out = tokio::process::Command::new("ping").args(["-c1", &host]).output().await.unwrap();
+    let out = tokio::process::Command::new("ping").args(["-c1", &host]).output_traced().await.unwrap();
     Ok(String::from_utf8_lossy(&out.stdout).into_owned())
 }
 
 #[tokio::main]
 async fn main() {
     let routes = warp::path!("ping" / String).and_then(ping);
-    warp::serve(routes).run(([0, 0, 0, 0], 8000)).await;
+    let make = hyper::service::make_service_fn(move |conn: &AddrStream| {
+        let svc = vbxtrace_hook::hyper014::trace(warp::service(routes.clone()), conn.local_addr(), conn.remote_addr());
+        async move { Ok::<_, std::convert::Infallible>(svc) }
+    });
+    hyper::Server::bind(&([0, 0, 0, 0], 8000).into()).serve(make).await.unwrap();
 }
Exact detection rules

Package R1 (Rust tokio crate), proposal R1:warp, defined in hooks/rust/r1/proposals/warp.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: warp, hyper
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for glommio 0.9 ​

  • Use this when: Rust service that depends on glommio (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the glommio 0.9 setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["glommio"] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. Per accepted glommio::net::TcpStream: ConnInfo::from_socket(&stream), conn.begin(..) + request.bind(fut) per message (or conn.session(fut)).
  4. io_uring operations are invisible to the sensor's syscall tracepoints, so wrap every file open and connect: DmaFile/BufferedFile::open/create → vbxtrace_hook::glommio::{dma_open, dma_create, buffered_open, buffered_create}; TcpStream::connect → vbxtrace_hook::glommio::connect; glommio::spawn_local → vbxtrace_hook::glommio::spawn_local.
  5. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).
Complete example: glommio/src/main.rs

hooks/rust/r2/samples/glommio/src/main.rs, with the hook added.

rust
//! The glommio sample: an accept loop on `glommio::net::TcpListener` in a local executor, a request
//! per HTTP/1.1 message, files and connects through glommio (io_uring: invisible to syscall
//! tracepoints, hence `opened` and `connected` from the hook).

mod driver;

use futures_lite::{AsyncReadExt, AsyncWriteExt};
use glommio::net::TcpStream;

async fn handle(path: &str) -> (u16, &'static str) {
    match path {
        "/hello" => (200, "hello\n"),
        "/file" => {
            #[cfg(feature = "hook")]
            let f = vbxtrace_hook::glommio::buffered_create("/tmp/glommio-file").await;
            #[cfg(not(feature = "hook"))]
            let f = glommio::io::BufferedFile::create("/tmp/glommio-file").await;
            f.unwrap().close().await.unwrap();
            (200, "created\n")
        }
        "/connect" => {
            let work = async {
                #[cfg(feature = "hook")]
                let s = vbxtrace_hook::glommio::connect("127.0.0.1:8081").await;
                #[cfg(not(feature = "hook"))]
                let s = TcpStream::connect("127.0.0.1:8081").await;
                drop(s.unwrap());
            };
            // in a task spawned for the request
            #[cfg(feature = "hook")]
            vbxtrace_hook::glommio::spawn_local(work).await;
            #[cfg(not(feature = "hook"))]
            glommio::spawn_local(work).await;
            (200, "connected\n")
        }
        _ => (404, "not found\n"),
    }
}

/// Reads one request head; None at EOF.
async fn read_head(sock: &mut TcpStream, pending: &mut Vec<u8>) -> Option<String> {
    loop {
        if let Some(i) = pending.windows(4).position(|w| w == b"\r\n\r\n") {
            let head: Vec<u8> = pending.drain(..i + 4).collect();
            return Some(String::from_utf8_lossy(&head).into_owned());
        }
        let mut buf = [0u8; 4096];
        match sock.read(&mut buf).await {
            Ok(0) | Err(_) => return None,
            Ok(n) => pending.extend_from_slice(&buf[..n]),
        }
    }
}

async fn connection(mut sock: TcpStream) {
    #[cfg(feature = "hook")]
    let conn = vbxtrace_hook::ConnInfo::from_socket(&sock);
    let mut pending = Vec::new();
    while let Some(head) = read_head(&mut sock, &mut pending).await {
        let path = head.split_whitespace().nth(1).unwrap_or("").to_string();
        #[cfg(feature = "hook")]
        let request = conn.begin(vbxtrace_hook::Protocol::Http1);
        #[cfg(feature = "hook")]
        let (status, body) = request.bind(handle(&path)).await;
        #[cfg(not(feature = "hook"))]
        let (status, body) = handle(&path).await;
        let resp = format!("HTTP/1.1 {status} X\r\nContent-Length: {}\r\n\r\n{body}", body.len());
        sock.write_all(resp.as_bytes()).await.unwrap();
        #[cfg(feature = "hook")]
        request.end(status);
    }
}

async fn serve() {
    let _side = std::net::TcpListener::bind("127.0.0.1:8081").unwrap();
    let listener = glommio::net::TcpListener::bind("127.0.0.1:8080").unwrap();
    loop {
        let sock = listener.accept().await.unwrap();
        glommio::spawn_local(connection(sock)).await;
    }
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    match args.get(1).map(String::as_str) {
        Some("serve") => {
            glommio::LocalExecutorBuilder::default().spawn(serve).unwrap().join().unwrap();
        }
        Some("drive") => driver::drive(&["/hello", "/missing"], &["/file", "/connect"]),
        Some("bench") => driver::bench(args[2].parse().unwrap(), "/hello"),
        _ => panic!("usage: sample serve | drive | bench N"),
    }
}
Exact detection rules

Package R2 (Rust other runtimes and threads), proposal R2:glommio, defined in hooks/rust/r2/proposals/glommio.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: glommio
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for may coroutines / may_minihttp ​

  • Use this when: Rust service that depends on may or may_minihttp (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the may coroutines / may_minihttp setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["may" ("may-minihttp" for may_minihttp)] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. may_minihttp: HttpServer(service).start(addr) → vbxtrace_hook::may::TracedServer(service).start(addr) (use may_minihttp::HttpServiceFactory); a factory f.start(addr) → vbxtrace_hook::may::Traced(f).start(addr). Raw may::net servers: ConnInfo::from_socket(&stream) and conn.begin(..) with with_context(..) inside the connection's coroutine.
  4. Replace the calls whose effects should be linked: std::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (vbxtrace_hook::process::CommandExt); std::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::fs::*; TcpStream::connect → vbxtrace_hook::net::connect. may::net::TcpStream::connect: call vbxtrace_hook::net::note_connected(&stream, Transport::Tcp) after it.
  5. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).
Complete example: may/src/main.rs

hooks/rust/r2/samples/may/src/main.rs, with the hook added.

rust
//! The may sample: a may_minihttp service in coroutines, `TracedServer` instead of `HttpServer`.

mod driver;

use std::io;

use may_minihttp::{HttpService, Request, Response};

#[cfg(feature = "hook")]
use vbxtrace_hook::process::CommandExt;

#[derive(Clone)]
struct Svc;

impl HttpService for Svc {
    fn call(&mut self, req: Request, rsp: &mut Response) -> io::Result<()> {
        match req.path() {
            "/hello" => rsp.body("hello\n"),
            "/spawn" => {
                let mut cmd = std::process::Command::new("/bin/true");
                #[cfg(feature = "hook")]
                cmd.status_traced()?;
                #[cfg(not(feature = "hook"))]
                cmd.status()?;
                rsp.body("spawned\n")
            }
            "/connect" => {
                // may's own TcpStream (a coroutine may move threads while it connects).
                let s = may::net::TcpStream::connect("127.0.0.1:8081")?;
                #[cfg(feature = "hook")]
                vbxtrace_hook::net::note_connected(&s, vbxtrace_hook::Transport::Tcp);
                drop(s);
                rsp.body("connected\n")
            }
            _ => {
                rsp.status_code(404, "Not Found");
                rsp.body("not found\n")
            }
        }
        Ok(())
    }
}

fn serve() {
    let _side = std::net::TcpListener::bind("127.0.0.1:8081").unwrap();
    #[cfg(feature = "hook")]
    let server = {
        use may_minihttp::HttpServiceFactory;
        vbxtrace_hook::may::TracedServer(Svc).start("127.0.0.1:8080").unwrap()
    };
    #[cfg(not(feature = "hook"))]
    let server = may_minihttp::HttpServer(Svc).start("127.0.0.1:8080").unwrap();
    server.join().unwrap();
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    match args.get(1).map(String::as_str) {
        Some("serve") => serve(),
        Some("drive") => driver::drive(&["/hello", "/missing"], &["/spawn", "/connect"]),
        Some("bench") => driver::bench(args[2].parse().unwrap(), "/hello"),
        _ => panic!("usage: sample serve | drive | bench N"),
    }
}
Exact detection rules

Package R2 (Rust other runtimes and threads), proposal R2:may, defined in hooks/rust/r2/proposals/may.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: may, may_minihttp
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for monoio 0.2 ​

  • Use this when: Rust service that depends on monoio (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the monoio 0.2 setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["monoio"] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. Per accepted monoio::net::TcpStream: ConnInfo::from_socket(&stream), conn.begin(..) + request.bind(fut) per message (or conn.session(fut)).
  4. io_uring operations are invisible to the sensor's syscall tracepoints, so wrap every file open and connect: monoio::fs::File::open/create/OpenOptions → vbxtrace_hook::monoio::{open, create, OpenOptions}; TcpStream::connect → vbxtrace_hook::monoio::connect; monoio::spawn → vbxtrace_hook::monoio::spawn.
  5. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).
Complete example: monoio/src/main.rs

hooks/rust/r2/samples/monoio/src/main.rs, with the hook added.

rust
//! The monoio sample: an accept loop on `monoio::net::TcpListener`, a request per HTTP/1.1 message,
//! files and connects through monoio (io_uring: invisible to syscall tracepoints, hence `opened` and
//! `connected` from the hook).

mod driver;

use monoio::io::{AsyncReadRent, AsyncWriteRentExt};
use monoio::net::TcpStream;

async fn handle(path: &str) -> (u16, &'static str) {
    match path {
        "/hello" => (200, "hello\n"),
        "/file" => {
            #[cfg(feature = "hook")]
            let f = vbxtrace_hook::monoio::create("/tmp/monoio-file").await;
            #[cfg(not(feature = "hook"))]
            let f = monoio::fs::File::create("/tmp/monoio-file").await;
            f.unwrap().close().await.unwrap();
            (200, "created\n")
        }
        "/connect" => {
            let work = async {
                #[cfg(feature = "hook")]
                let s = vbxtrace_hook::monoio::connect("127.0.0.1:8081").await;
                #[cfg(not(feature = "hook"))]
                let s = TcpStream::connect("127.0.0.1:8081").await;
                drop(s.unwrap());
            };
            // in a task spawned for the request
            #[cfg(feature = "hook")]
            vbxtrace_hook::monoio::spawn(work).await;
            #[cfg(not(feature = "hook"))]
            monoio::spawn(work).await;
            (200, "connected\n")
        }
        _ => (404, "not found\n"),
    }
}

/// Reads one request head; None at EOF.
async fn read_head(sock: &mut TcpStream, pending: &mut Vec<u8>) -> Option<String> {
    loop {
        if let Some(i) = pending.windows(4).position(|w| w == b"\r\n\r\n") {
            let head: Vec<u8> = pending.drain(..i + 4).collect();
            return Some(String::from_utf8_lossy(&head).into_owned());
        }
        let buf = vec![0u8; 4096];
        let (res, buf) = sock.read(buf).await;
        match res {
            Ok(0) | Err(_) => return None,
            Ok(n) => pending.extend_from_slice(&buf[..n]),
        }
    }
}

async fn connection(mut sock: TcpStream) {
    #[cfg(feature = "hook")]
    let conn = vbxtrace_hook::ConnInfo::from_socket(&sock);
    let mut pending = Vec::new();
    while let Some(head) = read_head(&mut sock, &mut pending).await {
        let path = head.split_whitespace().nth(1).unwrap_or("").to_string();
        #[cfg(feature = "hook")]
        let request = conn.begin(vbxtrace_hook::Protocol::Http1);
        #[cfg(feature = "hook")]
        let (status, body) = request.bind(handle(&path)).await;
        #[cfg(not(feature = "hook"))]
        let (status, body) = handle(&path).await;
        let resp = format!("HTTP/1.1 {status} X\r\nContent-Length: {}\r\n\r\n{body}", body.len());
        let (r, _) = sock.write_all(resp.into_bytes()).await;
        r.unwrap();
        #[cfg(feature = "hook")]
        request.end(status);
    }
}

async fn serve() {
    let _side = std::net::TcpListener::bind("127.0.0.1:8081").unwrap();
    let listener = monoio::net::TcpListener::bind("127.0.0.1:8080").unwrap();
    loop {
        let (sock, _) = listener.accept().await.unwrap();
        monoio::spawn(connection(sock)).await;
    }
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    match args.get(1).map(String::as_str) {
        Some("serve") => {
            // io_uring if the container allows it, else epoll (stderr says which).
            eprintln!("monoio driver: {}", if monoio::utils::detect_uring() { "io_uring" } else { "epoll" });
            let mut rt = monoio::RuntimeBuilder::<monoio::FusionDriver>::new().enable_all().build().unwrap();
            rt.block_on(serve())
        }
        Some("drive") => driver::drive(&["/hello", "/missing"], &["/file", "/connect"]),
        Some("bench") => driver::bench(args[2].parse().unwrap(), "/hello"),
        _ => panic!("usage: sample serve | drive | bench N"),
    }
}
Exact detection rules

Package R2 (Rust other runtimes and threads), proposal R2:monoio, defined in hooks/rust/r2/proposals/monoio.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: monoio
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for smol 2 ​

  • Use this when: Rust service that depends on smol or async-executor (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the smol 2 setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["smol"] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. Per accepted smol::net::TcpStream: let conn = vbxtrace_hook::ConnInfo::from_socket(&stream); conn.session(fut) or conn.begin(..) + request.bind(fut) per message.
  4. smol::spawn → vbxtrace_hook::smol::spawn; Executor::spawn(fut) → spawn(vbxtrace_hook::bind(fut)); smol::unblock → vbxtrace_hook::smol::unblock; TcpStream::connect → vbxtrace_hook::smol::connect.
  5. Replace the calls whose effects should be linked: std::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (vbxtrace_hook::process::CommandExt); std::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::fs::*; TcpStream::connect → vbxtrace_hook::net::connect.
  6. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).
Complete example: smol/src/main.rs

hooks/rust/r2/samples/smol/src/main.rs, with the hook added.

rust
//! The smol sample: an accept loop on `smol::net::TcpListener`, a task per connection, a request per
//! HTTP/1.1 message (`conn.begin` + `request.bind`).

mod driver;

use smol::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use smol::net::TcpStream;

#[cfg(feature = "hook")]
use vbxtrace_hook::process::CommandExt;

async fn handle(path: &str) -> (u16, &'static str) {
    match path {
        "/hello" => (200, "hello\n"),
        "/spawn" => {
            let work = || {
                let mut cmd = std::process::Command::new("/bin/true");
                #[cfg(feature = "hook")]
                cmd.status_traced().unwrap();
                #[cfg(not(feature = "hook"))]
                cmd.status().unwrap();
            };
            #[cfg(feature = "hook")]
            vbxtrace_hook::smol::unblock(work).await;
            #[cfg(not(feature = "hook"))]
            smol::unblock(work).await;
            (200, "spawned\n")
        }
        "/task" => {
            // A task spawned for the request keeps its context.
            let work = async {
                #[cfg(feature = "hook")]
                let s = vbxtrace_hook::smol::connect("127.0.0.1:8081").await;
                #[cfg(not(feature = "hook"))]
                let s = TcpStream::connect("127.0.0.1:8081").await;
                drop(s.unwrap());
            };
            #[cfg(feature = "hook")]
            vbxtrace_hook::smol::spawn(work).await;
            #[cfg(not(feature = "hook"))]
            smol::spawn(work).await;
            (200, "task\n")
        }
        _ => (404, "not found\n"),
    }
}

async fn connection(sock: TcpStream) {
    #[cfg(feature = "hook")]
    let conn = vbxtrace_hook::ConnInfo::from_socket(&sock);
    let mut sock = BufReader::new(sock);
    loop {
        let mut line = String::new();
        if sock.read_line(&mut line).await.unwrap_or(0) == 0 {
            return;
        }
        let path = line.split_whitespace().nth(1).unwrap_or("").to_string();
        loop {
            line.clear();
            if sock.read_line(&mut line).await.unwrap_or(0) == 0 || line == "\r\n" {
                break;
            }
        }
        #[cfg(feature = "hook")]
        let request = conn.begin(vbxtrace_hook::Protocol::Http1);
        #[cfg(feature = "hook")]
        let (status, body) = request.bind(handle(&path)).await;
        #[cfg(not(feature = "hook"))]
        let (status, body) = handle(&path).await;
        let resp = format!("HTTP/1.1 {status} X\r\nContent-Length: {}\r\n\r\n{body}", body.len());
        sock.get_mut().write_all(resp.as_bytes()).await.unwrap();
        #[cfg(feature = "hook")]
        request.end(status);
    }
}

async fn serve() {
    let _side = smol::net::TcpListener::bind("127.0.0.1:8081").await.unwrap();
    let listener = smol::net::TcpListener::bind("127.0.0.1:8080").await.unwrap();
    loop {
        let (sock, _) = listener.accept().await.unwrap();
        // One connection after the other so the event order is fixed.
        smol::spawn(connection(sock)).await;
    }
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    match args.get(1).map(String::as_str) {
        Some("serve") => smol::block_on(serve()),
        Some("drive") => driver::drive(&["/hello", "/missing"], &["/spawn", "/task"]),
        Some("bench") => driver::bench(args[2].parse().unwrap(), "/hello"),
        _ => panic!("usage: sample serve | drive | bench N"),
    }
}
Exact detection rules

Package R2 (Rust other runtimes and threads), proposal R2:smol, defined in hooks/rust/r2/proposals/smol.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: smol, async-executor
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for std threads (thread per connection) ​

  • Use this when: Rust service started with cargo.
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the std threads (thread per connection) setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = [none (std only)] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. Optional (the kernel already links thread-per-connection servers): per connection let conn = vbxtrace_hook::ConnInfo::from_socket(&stream); per message let request = conn.begin(Protocol::Http1); with_context(request.ctx(), || handle(..)); request.end(status).
  4. Replace the calls whose effects should be linked: std::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (vbxtrace_hook::process::CommandExt); std::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::fs::*; TcpStream::connect → vbxtrace_hook::net::connect.
  5. Helper threads: std::thread::spawn → vbxtrace_hook::thread::spawn; work handed to a pool → vbxtrace_hook::thread::wrap(f).
  6. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).
Complete example: std-threads/src/main.rs

hooks/rust/r2/samples/std-threads/src/main.rs, with the hook added.

rust
//! The std threads sample: `std::net::TcpListener`, a thread per connection, a hand-rolled HTTP/1.1
//! loop. The kernel links such threads exactly already; the hook adds request boundaries on keep-alive
//! connections and carries the context into helper threads.

mod driver;

use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;

#[cfg(feature = "hook")]
use vbxtrace_hook::process::CommandExt;

fn handle(path: &str) -> (u16, &'static str) {
    match path {
        "/hello" => (200, "hello\n"),
        "/spawn" => {
            let mut cmd = std::process::Command::new("/bin/true");
            #[cfg(feature = "hook")]
            cmd.status_traced().unwrap();
            #[cfg(not(feature = "hook"))]
            cmd.status().unwrap();
            (200, "spawned\n")
        }
        "/worker" => {
            // Work on a helper thread: thread::spawn carries the context (context_enter/exit).
            let work = || {
                #[cfg(feature = "hook")]
                vbxtrace_hook::fs::write("/tmp/std-worker", "x").unwrap();
                #[cfg(not(feature = "hook"))]
                std::fs::write("/tmp/std-worker", "x").unwrap();
            };
            #[cfg(feature = "hook")]
            vbxtrace_hook::thread::spawn(work).join().unwrap();
            #[cfg(not(feature = "hook"))]
            std::thread::spawn(work).join().unwrap();
            (200, "worked\n")
        }
        "/connect" => {
            #[cfg(feature = "hook")]
            let s = vbxtrace_hook::net::connect("127.0.0.1:8081");
            #[cfg(not(feature = "hook"))]
            let s = TcpStream::connect("127.0.0.1:8081");
            drop(s.unwrap());
            (200, "connected\n")
        }
        _ => (404, "not found\n"),
    }
}

fn connection(sock: TcpStream) {
    #[cfg(feature = "hook")]
    let conn = vbxtrace_hook::ConnInfo::from_socket(&sock);
    let mut sock = BufReader::new(sock);
    loop {
        let mut line = String::new();
        if sock.read_line(&mut line).unwrap_or(0) == 0 {
            return;
        }
        let path = line.split_whitespace().nth(1).unwrap_or("").to_string();
        loop {
            line.clear();
            if sock.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
                break;
            }
        }
        #[cfg(feature = "hook")]
        let request = conn.begin(vbxtrace_hook::Protocol::Http1);
        #[cfg(feature = "hook")]
        let (status, body) = vbxtrace_hook::with_context(request.ctx(), || handle(&path));
        #[cfg(not(feature = "hook"))]
        let (status, body) = handle(&path);
        let resp = format!("HTTP/1.1 {status} X\r\nContent-Length: {}\r\n\r\n{body}", body.len());
        sock.get_mut().write_all(resp.as_bytes()).unwrap();
        #[cfg(feature = "hook")]
        request.end(status);
    }
}

fn serve() {
    let _side = std::net::TcpListener::bind("127.0.0.1:8081").unwrap();
    let listener = std::net::TcpListener::bind("127.0.0.1:8080").unwrap();
    for sock in listener.incoming() {
        let sock = sock.unwrap();
        // Served one after the other so the event order is fixed; a real server would not join.
        std::thread::spawn(move || connection(sock)).join().unwrap();
    }
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    match args.get(1).map(String::as_str) {
        Some("serve") => serve(),
        Some("drive") => driver::drive(&["/hello", "/missing"], &["/spawn", "/worker", "/connect"]),
        Some("bench") => driver::bench(args[2].parse().unwrap(), "/hello"),
        _ => panic!("usage: sample serve | drive | bench N"),
    }
}
Exact detection rules

Package R2 (Rust other runtimes and threads), proposal R2:std-threads, defined in hooks/rust/r2/proposals/std-threads.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Rust hook for tide 0.16 (async-std) ​

  • Use this when: Rust service that depends on tide (in Cargo.toml).
  • Hub automation: not at all. The hub lists these steps with its proposal but changes nothing.
  • Check and undo: hook built into the service

Vendors vulnboxd Rust hook into the service and adds it to the tide 0.16 (async-std) setup, so the sensor links child processes, outgoing connections and opened files to the request that caused them. Builds offline.

Source change, then rebuild:

  1. Copy the hook directory's rust/ (on the vulnbox: /usr/local/lib/vulnboxd/trace/rust) to <service>/vendor/vbxtrace, so the build needs no network.
  2. Cargo.toml [dependencies]: vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["tide"] }. If the manifest has a [workspace] table, add "vendor/vbxtrace" to its exclude list.
  3. app.listen(addr) becomes app.listen(vbxtrace_hook::tide::TracedListener::bind(addr)).
  4. async_std::fs / net / task: vbxtrace_hook::async_std::{fs::*, connect, spawn, spawn_blocking}; child processes through the std wrappers inside vbxtrace_hook::async_std::spawn_blocking.
  5. Replace the calls whose effects should be linked: std::process::Command .spawn()/.status()/.output() → .spawn_traced()/.status_traced()/.output_traced() (vbxtrace_hook::process::CommandExt); std::fs::{read, read_to_string, write, File::open, File::create, OpenOptions} → vbxtrace_hook::fs::*; TcpStream::connect → vbxtrace_hook::net::connect.
  6. Make sure the Dockerfile copies vendor/ before cargo build (a COPY of only Cargo.toml/Cargo.lock/src for layer caching must add vendor/vbxtrace).

Example change on a sample service (hooks/rust/r2/proposals/tide.diff):

diff
# The source change the hub proposes for a service on tide (here: ../r1/tests/offline/tide), after the hook
# directory was copied to vendor/vbxtrace. Apply with `patch -p1`.

diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,3 +10,4 @@
 [dependencies]
 tide = "0.16"
 async-std = { version = "1", features = ["attributes"] }
+vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["tide"] }
diff -ruN a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -9,8 +9,8 @@
     let mut app = tide::new();
     app.at("/note/:id").get(|req: tide::Request<()>| async move {
         let id = req.param("id")?.to_string();
-        Ok(async_std::fs::read_to_string(format!("/data/{id}")).await.unwrap_or_default())
+        Ok(vbxtrace_hook::async_std::fs::read_to_string(format!("/data/{id}")).await.unwrap_or_default())
     });
-    app.listen("0.0.0.0:8080").await?;
+    app.listen(vbxtrace_hook::tide::TracedListener::bind("0.0.0.0:8080")).await?;
     Ok(())
 }
Exact detection rules

Package R2 (Rust other runtimes and threads), proposal R2:tide, defined in hooks/rust/r2/proposals/tide.toml.

  • Image matches (regex): ^(docker\.io/)?(library/)?rust:, ^(docker\.io/)?clux/muslrust, ^(docker\.io/)?lukemathwalker/cargo-chef
  • Command matches (regex): \bcargo\b
  • Dependency on: tide
  • Files: Cargo.toml, Cargo.lock, **/Cargo.toml

Check that it works, and undo ​

Each block links the variant it needs.

Hook built into the service ​

Check: After the rebuild, the binary carries the hook's probes (a count above 0):

sh
readelf -n <the built binary> | grep -c vbxtrace

The hub's Trace tab then shows links whose method starts with hook:.

Undo: Set VBXTRACE: "0" in the service's environment and restart it, or revert the change.