diff --git a/.gitignore b/.gitignore index b7f3b4e..30659a1 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,6 @@ profile.cov # goreleaser output dist/ + +# Written by bench/run.sh before each condition; the mount target, not source. +bench/strategy.dna diff --git a/.mise/config.toml b/.mise/config.toml index 5c8303a..7092b5b 100644 --- a/.mise/config.toml +++ b/.mise/config.toml @@ -38,6 +38,14 @@ run = "golangci-lint run ./..." description = "go vet over the module" run = "make vet" +[tasks.bench] +description = "engine microbenchmarks (per-packet cost, no kernel in the loop)" +run = "make bench" + +[tasks."bench:e2e"] +description = "data-plane benchmark over docker: throughput + sidecar CPU per GiB" +run = "make bench-e2e" + [tasks.e2e] description = "full docker-networking e2e (needs docker + a netfilter-capable kernel)" run = "make e2e" diff --git a/Makefile b/Makefile index 6084f37..073e3b8 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo none) LDFLAGS := -s -w -X main.version=$(VERSION) -X main.commit=$(COMMIT) -.PHONY: build test test-race vet lint e2e docker package clean +.PHONY: build test test-race bench bench-e2e vet lint e2e docker package clean build: CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o bin/geneva-server ./cmd/geneva-server @@ -23,6 +23,17 @@ vet: lint: golangci-lint run ./... +# Per-packet cost of the engine, with no kernel in the loop. The fastest signal +# when changing the hot path; run bench-e2e for the number that includes NFQUEUE. +bench: + go test ./internal/engine/ ./internal/nfqueue/ -run '^$$' -bench . -benchmem + +# Full data-plane benchmark over docker networking: throughput and sidecar CPU +# per GiB across every sidecar state. Args: GiB per condition, concurrent +# streams. +bench-e2e: + ./bench/run.sh $(GIB) $(STREAMS) + # Full e2e over docker networking (requires docker + a netfilter-capable kernel). e2e: ./e2e/run.sh diff --git a/bench/Dockerfile.bulk b/bench/Dockerfile.bulk new file mode 100644 index 0000000..8010616 --- /dev/null +++ b/bench/Dockerfile.bulk @@ -0,0 +1,16 @@ +# Benchmark-only image: the bulk load generator plus the tooling the runner uses +# to drive the control API and read the sidecar's counters. +FROM golang:1.25-bookworm AS builder +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 go build -trimpath -o /out/bulk ./bench/bulk + +FROM debian:bookworm-slim +RUN set -ex \ + && apt-get update \ + && apt-get install -y --no-install-recommends curl jq ethtool ca-certificates \ + && rm -rf /var/lib/apt/lists/* +COPY --from=builder /out/bulk /usr/local/bin/bulk +ENTRYPOINT ["/usr/local/bin/bulk"] diff --git a/bench/bulk/main.go b/bench/bulk/main.go new file mode 100644 index 0000000..9891f17 --- /dev/null +++ b/bench/bulk/main.go @@ -0,0 +1,136 @@ +// Command bulk is the load generator for the sidecar benchmark. It is both the +// server and the client so that a single image covers both ends, and it streams +// from a reused buffer rather than materializing the payload: the benchmark +// moves gigabytes, and a payload held in memory would measure the allocator. +// +// It deliberately speaks plain HTTP. The sidecar only ever manipulates outer +// IPv4/TCP headers, so wrapping the stream in TLS would add proxy-side crypto +// cost to every number without changing a single packet the sidecar sees. +package main + +import ( + "crypto/rand" + "flag" + "fmt" + "io" + "log" + "net/http" + "os" + "strconv" + "sync" + "time" +) + +const chunkSize = 256 << 10 + +func main() { + serve := flag.String("serve", "", "serve bulk data on this address (e.g. :8080)") + get := flag.String("get", "", "fetch bulk data from this base URL (e.g. http://server:8080)") + bytes := flag.Int64("bytes", 2<<30, "bytes to transfer per stream") + streams := flag.Int("streams", 1, "concurrent streams") + flag.Parse() + + switch { + case *serve != "": + runServer(*serve) + case *get != "": + if err := runClient(*get, *bytes, *streams); err != nil { + // Exit non-zero rather than printing a throughput figure: a + // half-finished transfer that reports a number is how a broken + // condition gets recorded as a benchmark result. + log.Fatal(err) + } + default: + log.Fatal("one of -serve or -get is required") + } +} + +func runServer(addr string) { + // Random rather than zeros: a NIC or a virtual link that compresses or + // dedupes would otherwise flatter the benchmark. + chunk := make([]byte, chunkSize) + if _, err := rand.Read(chunk); err != nil { + log.Fatal(err) + } + + mux := http.NewServeMux() + mux.HandleFunc("/bulk", func(w http.ResponseWriter, r *http.Request) { + n, err := strconv.ParseInt(r.URL.Query().Get("bytes"), 10, 64) + if err != nil || n < 0 { + http.Error(w, "bad bytes", http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Length", strconv.FormatInt(n, 10)) + for n > 0 { + c := int64(len(chunk)) + if n < c { + c = n + } + if _, err := w.Write(chunk[:c]); err != nil { + return + } + n -= c + } + }) + mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("ok")) + }) + + log.Printf("bulk server listening on %s", addr) + srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second} + log.Fatal(srv.ListenAndServe()) +} + +// runClient reports MB/s on stdout as a bare number, so the runner can read it +// without parsing prose. Any stream that fails, returns a non-200, or comes up +// short is an error: the number would be meaningless and the runner cannot tell +// a slow condition from a broken one. +func runClient(base string, n int64, streams int) error { + client := &http.Client{Timeout: 30 * time.Minute} + url := fmt.Sprintf("%s/bulk?bytes=%d", base, n) + + var wg sync.WaitGroup + got := make([]int64, streams) + errs := make([]error, streams) + start := time.Now() + for i := range streams { + wg.Add(1) + go func(i int) { + defer wg.Done() + resp, err := client.Get(url) + if err != nil { + errs[i] = fmt.Errorf("stream %d: %w", i, err) + return + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + errs[i] = fmt.Errorf("stream %d: HTTP %d", i, resp.StatusCode) + return + } + c, err := io.Copy(io.Discard, resp.Body) + got[i] = c + if err != nil { + errs[i] = fmt.Errorf("stream %d: after %d bytes: %w", i, c, err) + } + }(i) + } + wg.Wait() + elapsed := time.Since(start) + + for _, err := range errs { + if err != nil { + return err + } + } + var total int64 + for _, c := range got { + total += c + } + if want := n * int64(streams); total != want { + return fmt.Errorf("short transfer: got %d of %d bytes", total, want) + } + mbps := float64(total) / (1 << 20) / elapsed.Seconds() + _, _ = fmt.Fprintf(os.Stdout, "%.2f\n", mbps) + return nil +} diff --git a/bench/docker-compose.yml b/bench/docker-compose.yml new file mode 100644 index 0000000..cb2ad3e --- /dev/null +++ b/bench/docker-compose.yml @@ -0,0 +1,64 @@ +# Benchmark topology. Mirrors e2e/docker-compose.yml, with the echo server +# replaced by a streaming bulk server and the sidecar's arguments driven from +# the environment so the runner can sweep modes without editing this file. +# +# server — the "proxy": bulk data on :8080, and owner of the network namespace +# sidecar — geneva-server sharing the server's netns, steering :8080 +# client — pulls bulk data across the bridge; the load generator +# probe — on-demand container in the server's netns for nft/ethtool state +name: geneva-bench + +services: + server: + build: + context: .. + dockerfile: bench/Dockerfile.bulk + image: geneva-bench/bulk:latest + command: ["-serve", ":8080"] + healthcheck: + test: ["CMD", "curl", "-fsS", "http://localhost:8080/healthz"] + interval: "1s" + timeout: "2s" + retries: 30 + + sidecar: + build: + context: .. + dockerfile: Dockerfile + image: geneva-bench/sidecar:latest + network_mode: "service:server" + cap_add: + - NET_ADMIN + - NET_RAW + depends_on: + server: + condition: service_healthy + volumes: + - ./strategy.dna:/strategy.dna:ro + command: + - "run" + - "--mode=${GENEVA_MODE:-eval}" + - "--market=RU" + - "--port=8080" + - "--iface=eth0" + - "--control-addr=0.0.0.0:8092" + # Always a file, never a flag toggle: the runner rewrites strategy.dna + # between conditions, and an empty file is exactly the pass-through case. + - "--strategy-file=/strategy.dna" + # Debug-only, and only ever in this harness: the profile is what tells us + # whether a cost is in the engine or in the plumbing around it. + - "--pprof-addr=0.0.0.0:6060" + + client: + image: geneva-bench/bulk:latest + depends_on: + server: + condition: service_healthy + profiles: ["tools"] + entrypoint: ["sleep", "infinity"] + + probe: + image: geneva-bench/sidecar:latest + network_mode: "service:server" + profiles: ["tools"] + entrypoint: ["sleep", "infinity"] diff --git a/bench/run.sh b/bench/run.sh new file mode 100755 index 0000000..3f18479 --- /dev/null +++ b/bench/run.sh @@ -0,0 +1,160 @@ +#!/usr/bin/env bash +# Sidecar data-plane benchmark. +# +# Answers one question: what does steering cost per packet, and how much of that +# cost survives when the strategy cannot possibly match the traffic? It sweeps +# the sidecar's states (absent, pass-through, handshake-only, tamper-everything) +# in both modes and prints a table. +# +# The headline column is CPU-SEC/GiB, not MiB/s. A docker bridge has no link +# ceiling, so throughput here says more about the host than about the sidecar, +# while CPU per byte moved is the quantity that decides whether a 1-vCPU VPS can +# carry a strategy at line rate. +# +# Units are binary throughout — GiB and MiB/s — because that is what the byte +# counts actually are. +# +# Usage: bench/run.sh [GiB per condition] [streams] +# KEEP=1 bench/run.sh # leave the stack up for inspection +set -euo pipefail + +cd "$(dirname "$0")" +# The compose mount needs the file to exist before the sidecar starts; it is +# rewritten per condition and deliberately not tracked. +: > strategy.dna +COMPOSE=(docker compose -f docker-compose.yml) +source ../scripts/harness-lib.sh +GIB="${1:-2}" +STREAMS="${2:-1}" +BYTES=$(( GIB * (1 << 30) / STREAMS )) + +HANDSHAKE='[TCP:flags:S]-duplicate-| \/' +# One packet in, one packet out, on every data packet: the common manipulation, +# and the one the in-queue modified verdict is meant to make cheap. +TAMPER_ALL='[TCP:flags:PA]-tamper{TCP:window:replace:100}-| \/' +# Two packets out on every data packet: the worst case, since the extra packet +# has to reach the wire through the raw socket. +DUP_ALL='[TCP:flags:PA]-duplicate-| \/' + +results=() + +# SIDECAR_EXPECTED says whether a sidecar should be answering. While it is "1", +# telemetry that cannot be collected aborts the run instead of reading as zero: +# a stopped sidecar reporting 0 CPU and 0 packets looks exactly like the ideal +# result, and a stale container left by an interrupted run silently produced a +# wrong baseline row once already. +SIDECAR_EXPECTED=0 + +# sidecar_cpu prints the sidecar's cumulative CPU seconds (utime+stime of PID 1, +# which is geneva-server itself), or 0 when no sidecar is expected to be running. +sidecar_cpu() { + local ticks hz + if ! ticks=$("${COMPOSE[@]}" exec -T sidecar awk '{print $14+$15}' /proc/1/stat 2>/dev/null); then + [[ "$SIDECAR_EXPECTED" == "1" ]] && { echo "cannot read sidecar CPU while a sidecar is expected" >&2; exit 1; } + ticks=0 + fi + hz=$(getconf CLK_TCK) + awk -v t="${ticks:-0}" -v hz="$hz" 'BEGIN{printf "%.3f", t/hz}' +} + +# packets_in prints the engine's cumulative packet count, or 0 when no sidecar +# is expected to be running. +packets_in() { + local out + if ! out=$("${COMPOSE[@]}" exec -T client sh -c \ + 'curl -fsS http://server:8092/healthz | jq -r .engine.packets_in' 2>/dev/null); then + [[ "$SIDECAR_EXPECTED" == "1" ]] && { echo "cannot read the sidecar health surface while a sidecar is expected" >&2; exit 1; } + out=0 + fi + echo "${out:-0}" +} + +# measure runs one condition and appends a table row: label, MiB/s, sidecar CPU +# seconds per GiB, and nanoseconds of sidecar CPU per steered packet. +measure() { + local label="$1" + local cpu0 cpu1 pkt0 pkt1 mbps cpu_s + cpu0=$(sidecar_cpu); pkt0=$(packets_in) + mbps=$("${COMPOSE[@]}" exec -T client /usr/local/bin/bulk \ + -get http://server:8080 -bytes "$BYTES" -streams "$STREAMS" | tail -1) + cpu1=$(sidecar_cpu); pkt1=$(packets_in) + + cpu_s=$(awk -v a="$cpu0" -v b="$cpu1" 'BEGIN{printf "%.3f", b-a}') + local per_gb ns_pkt pkts + per_gb=$(awk -v c="$cpu_s" -v g="$GIB" 'BEGIN{printf "%.3f", (g>0)?c/g:0}') + pkts=$(( pkt1 - pkt0 )) + ns_pkt=$(awk -v c="$cpu_s" -v p="$pkts" 'BEGIN{printf "%.0f", (p>0)?c*1e9/p:0}') + printf ' %-26s %8s MiB/s cpu %6ss %6s s/GiB %9s pkts %5s ns/pkt\n' \ + "$label" "$mbps" "$cpu_s" "$per_gb" "$pkts" "$ns_pkt" + results+=("$(printf '%-26s|%8s|%7s|%9s|%6s' "$label" "$mbps" "$per_gb" "$pkts" "$ns_pkt")") +} + +# put installs a strategy over the control API on a running sidecar. +put() { + "${COMPOSE[@]}" exec -T client sh -c \ + "curl -fsS -X PUT --data-binary '$1' http://server:8092/strategy >/dev/null" +} + +start_sidecar() { + local mode="$1" dna="$2" + printf '%s' "$dna" > strategy.dna + GENEVA_MODE="$mode" "${COMPOSE[@]}" up -d --no-deps sidecar >/dev/null + if ! wait_healthy client; then + echo "sidecar control surface never came up" >&2 + "${COMPOSE[@]}" logs sidecar | tail -20 >&2 + exit 1 + fi + SIDECAR_EXPECTED=1 +} + +# stop_sidecar takes the sidecar down and stops expecting telemetry from it. +stop_sidecar() { + SIDECAR_EXPECTED=0 + "${COMPOSE[@]}" stop -t 10 sidecar >/dev/null +} + +# Start from a torn-down stack. An interrupted run can leave the server's +# network namespace de-offloaded (an older sidecar build never restored the NIC), +# and on a veth pair that alone costs several times the throughput — enough to +# make every row in the table wrong in the same direction. +"${COMPOSE[@]}" --profile tools down -v --remove-orphans >/dev/null 2>&1 || true + +step "Build images and start the bulk server (no sidecar yet)" +# The sidecar image is built here rather than on first use: start_sidecar brings +# it up per condition without --build, and a stale image would silently +# benchmark the previous commit. +"${COMPOSE[@]}" build server sidecar >/dev/null +"${COMPOSE[@]}" up -d server >/dev/null +"${COMPOSE[@]}" --profile tools up -d client >/dev/null + +# Remove, not stop: a sidecar left behind by an interrupted run would still be +# steering, and the baseline row would silently measure the old build. +"${COMPOSE[@]}" rm -sf sidecar >/dev/null 2>&1 || true + +step "Baseline: $GIB GiB over $STREAMS stream(s), sidecar absent" +measure "no-sidecar" + +# eval boots with no strategy at all: the state a test box sits in until the GA +# brain assigns it a candidate. It is the case that must cost nothing. +step "mode=eval" +start_sidecar eval "" +measure "eval/no-strategy" +put "$HANDSHAKE"; measure "eval/handshake-only" +put "$TAMPER_ALL"; measure "eval/tamper-every-packet" +put "$DUP_ALL"; measure "eval/duplicate-every-packet" +stop_sidecar + +# prod refuses to boot without a strategy, so it starts on the handshake one. +# The last row is the rollback path: PUT "" must take the box back off the data +# path rather than leaving it steering packets it no longer manipulates. +step "mode=prod" +start_sidecar prod "$HANDSHAKE" +measure "prod/handshake-only" +put "$TAMPER_ALL"; measure "prod/tamper-every-packet" +put "$DUP_ALL"; measure "prod/duplicate-every-packet" +put ""; measure "prod/rolled-back-to-empty" +stop_sidecar + +step "Summary" +printf '%-26s|%8s|%7s|%9s|%6s\n' "CONDITION" "MiB/s" "CPU s/GiB" "PACKETS" "ns/pkt" +printf '%s\n' "${results[@]}" diff --git a/cmd/geneva-server/main.go b/cmd/geneva-server/main.go index 3bd8c33..658a4fe 100644 --- a/cmd/geneva-server/main.go +++ b/cmd/geneva-server/main.go @@ -61,8 +61,11 @@ type runCmd struct { CanaryCapacity int `arg:"--canary-capacity" default:"64" help:"distinct values captured per field in eval mode"` NFTPath string `arg:"--nft" default:"nft" help:"path to the nft binary"` NoNFT bool `arg:"--no-nft" help:"do not program nftables rules (rules managed externally)"` + CensorCounters bool `arg:"--censor-counters" default:"true" help:"classify inbound packets with nftables counters, so the censor-reachability signal does not depend on steering inbound through userspace"` + ObserveInbound bool `arg:"--observe-inbound" help:"eval mode only: keep inbound packets flowing through userspace for the censor-reachability signal, at a round trip per inbound packet"` Iface string `arg:"--iface" help:"steered interface; NIC offloads are disabled on it so NFQUEUE yields MTU-sized, checksummed packets (strongly recommended)"` EthtoolPath string `arg:"--ethtool" default:"ethtool" help:"path to the ethtool binary (used with --iface)"` + PprofAddr string `arg:"--pprof-addr" help:"debug only: serve net/http/pprof on this address; never enable on a box carrying client traffic"` } // validateCmd holds the flags for the validate subcommand. @@ -144,24 +147,51 @@ func (o *runCmd) resolveStrategy() (string, error) { if o.Strategy != "" && o.StrategyFile != "" { return "", fmt.Errorf("--strategy and --strategy-file are mutually exclusive") } + dna := strings.TrimSpace(o.Strategy) if o.StrategyFile != "" { b, err := os.ReadFile(o.StrategyFile) if err != nil { return "", fmt.Errorf("read strategy file: %w", err) } // Tolerate a trailing newline in an operator-managed file. - return strings.TrimSpace(string(b)), nil + dna = strings.TrimSpace(string(b)) } - if o.Strategy == "" && o.Mode == "prod" { - return "", fmt.Errorf("prod mode requires --strategy or --strategy-file") + // Checked against the resolved DNA, not against the flags: an empty + // strategy file passed --strategy-file used to satisfy the flag check and + // boot prod in pass-through. That now also means no steering at all, so a + // truncated file would take a prod box off the data path silently. + if dna == "" && o.Mode == "prod" { + return "", fmt.Errorf("prod mode requires a non-empty strategy (--strategy or --strategy-file)") } - return strings.TrimSpace(o.Strategy), nil + return dna, nil } func (o *runCmd) validate() error { if o.Mode != "prod" && o.Mode != "eval" { return fmt.Errorf("invalid --mode %q (want prod or eval)", o.Mode) } + if o.ObserveInbound && o.Mode == "prod" { + // Refused rather than warned about, because the cost lands on real + // users and the benefit does not need their traffic. + // + // Observing inbound means a userspace round trip for every inbound + // packet, whether or not the strategy can act on one. Measured on a + // 1-vCPU box: free where clients download (the inbound direction is + // only stretch-ACKs) but -40% where they upload, and a prod box does + // not get to choose which its users do. What it buys is the + // censor-reachability signal, which is an inference from a + // SYN-to-data ratio — and an eval box, which carries no client + // traffic, produces that same signal for nothing. + // + // A prod box that genuinely needs inbound packets in userspace has a + // precise way to ask: give its strategy an inbound tree. Steering then + // follows the strategy, and the packets are queued because something + // actually acts on them rather than because a flag was set. An inbound + // pass-through tree is spelled `\/ [TCP:flags:A*]-send-|`. + return fmt.Errorf("--observe-inbound is not available in prod mode: it costs a userspace round trip " + + "per inbound packet (measured up to -40%% on upload-heavy traffic) for a signal an eval box " + + "provides for free; to steer inbound on a prod box, give the strategy an inbound tree") + } if o.OutQueue == o.InQueue { return fmt.Errorf("--out-queue and --in-queue must differ") } diff --git a/cmd/geneva-server/main_test.go b/cmd/geneva-server/main_test.go index 8546bd4..89890c2 100644 --- a/cmd/geneva-server/main_test.go +++ b/cmd/geneva-server/main_test.go @@ -58,3 +58,27 @@ func TestValidateRequiresNonZeroMark(t *testing.T) { } } } + +// TestObserveInboundRefusedInProd pins the mode gate. Observing inbound costs a +// userspace round trip per inbound packet — measured free on download-heavy +// traffic but -40% on upload-heavy, and a prod box does not get to choose which +// its users generate — in exchange for a signal an eval box produces for free. +// A prod box that needs inbound packets in userspace asks for them precisely, by +// giving its strategy an inbound tree. +func TestObserveInboundRefusedInProd(t *testing.T) { + base := func(mode string, observe bool) *runCmd { + return &runCmd{ + Mode: mode, Port: 443, OutQueue: 100, InQueue: 101, + Mark: 0x67656e, ObserveInbound: observe, + } + } + if err := base("prod", true).validate(); err == nil { + t.Error("validate accepted --observe-inbound in prod mode") + } + if err := base("eval", true).validate(); err != nil { + t.Errorf("validate rejected --observe-inbound in eval mode: %v", err) + } + if err := base("prod", false).validate(); err != nil { + t.Errorf("validate rejected prod without the flag: %v", err) + } +} diff --git a/cmd/geneva-server/run_linux.go b/cmd/geneva-server/run_linux.go index 52912d5..9a3adff 100644 --- a/cmd/geneva-server/run_linux.go +++ b/cmd/geneva-server/run_linux.go @@ -8,6 +8,7 @@ import ( "fmt" "log/slog" "net/http" + "net/http/pprof" "os" "os/signal" "syscall" @@ -17,13 +18,14 @@ import ( "github.com/getlantern/geneva-server/internal/censor" "github.com/getlantern/geneva-server/internal/control" "github.com/getlantern/geneva-server/internal/engine" - "github.com/getlantern/geneva-server/internal/netdev" "github.com/getlantern/geneva-server/internal/nfqueue" "github.com/getlantern/geneva-server/internal/nftables" + "github.com/getlantern/geneva-server/internal/steering" "github.com/getlantern/geneva-server/internal/telemetry" ) -// slogLogger adapts slog to the runtime's Debugf/Errorf logger. +// slogLogger adapts slog to the printf-style loggers the runtime and the +// steering controller want; one adapter satisfies both interfaces. type slogLogger struct{ l *slog.Logger } // Debugf checks the level before formatting. The runtime's debug path is the @@ -36,8 +38,17 @@ func (s slogLogger) Debugf(f string, a ...any) { s.l.Debug(fmt.Sprintf(f, a...)) } +// Infof formats unconditionally: its callers log lifecycle events, not +// per-packet ones. +func (s slogLogger) Infof(f string, a ...any) { s.l.Info(fmt.Sprintf(f, a...)) } func (s slogLogger) Errorf(f string, a ...any) { s.l.Error(fmt.Sprintf(f, a...)) } +// censorReadInterval is how often the kernel classification counters are read. +// One nft invocation per read, feeding a metric exported on a much slower +// cadence, so this only has to be quick enough that two consecutive /healthz +// calls do not return the same numbers. +const censorReadInterval = 2 * time.Second + func runServer(o *runCmd) error { ctx := context.Background() started := time.Now() @@ -61,53 +72,64 @@ func runServer(o *runCmd) error { observers = append(observers, pool) } - // The inbound censor classifier runs in both modes: a prod box's IP gets - // burned the same way a test box's does, and the fleet-wide burn rate is - // what sizes the clean-IP budget for exploration. - censorObs := censor.New() - observers = append(observers, censorObs) - observer := nfqueue.Observers(observers...) - // Signals cancel the root context so cleanup (nft teardown) always runs. ctx, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM) defer stop() - // Disable NIC offloads on the steered interface so NFQUEUE yields real, - // MTU-sized, fully-checksummed packets that reinjection can put back on the - // wire intact. - if o.Iface != "" { - summary, err := netdev.DisableOffload(ctx, o.EthtoolPath, o.Iface) - if err != nil { - return err - } - log.Info("NIC offloads adjusted", "iface", o.Iface, "result", summary) - } + // The controller owns both halves of "what reaches userspace": the NIC's + // offload state and the steering rules. It installs rules only for the + // packets the strategy's triggers can match, and nothing at all when the + // strategy can match nothing — which is what keeps an unassigned eval box + // and a rolled-back prod box off the data path entirely. + ctrl := steering.New(eng, steering.Config{ + Mode: o.Mode, + NFT: nftables.Config{ + Table: o.Table, + Port: o.Port, + OutQueue: o.OutQueue, + InQueue: o.InQueue, + Mark: uint32(o.Mark), + NFTPath: o.NFTPath, + Censor: o.CensorCounters, + }, + EthtoolPath: o.EthtoolPath, + Iface: o.Iface, + NoNFT: o.NoNFT, - // Program the steering rules. They are torn down on any exit path. - nft := nftables.New(nftables.Config{ - Table: o.Table, - Port: o.Port, - OutQueue: o.OutQueue, - InQueue: o.InQueue, - Mark: uint32(o.Mark), - NFTPath: o.NFTPath, - }) - if !o.NoNFT { - if err := nft.Install(ctx); err != nil { - return err + ObserveInbound: o.ObserveInbound, + }, slogLogger{l: log}) + if err := ctrl.Start(ctx); err != nil { + return err + } + defer func() { + // Use a fresh context: the root one is already cancelled at shutdown. + rmCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := ctrl.Close(rmCtx); err != nil { + log.Error("steering teardown failed", "err", err) } - log.Info("nftables steering installed", "table", o.Table, "port", o.Port) - defer func() { - // Use a fresh context: the root one is already cancelled at shutdown. - rmCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if err := nft.Remove(rmCtx); err != nil { - log.Error("nftables teardown failed", "err", err) - } else { - log.Info("nftables steering removed") - } - }() + }() + + // The inbound censor classifier runs in both modes: a prod box's IP gets + // burned the same way a test box's does, and the fleet-wide burn rate is + // what sizes the clean-IP budget for exploration. + // + // Where those counts come from is the interesting part. Steering is scoped + // to what the strategy can act on, so an outbound-only strategy delivers no + // inbound packet to userspace, and a classifier fed by NFQUEUE would see + // nothing at all. The kernel counters classify what arrives without queueing + // any of it, which is both the complete answer and the free one. The + // userspace classifier stays as the fallback for a box that turns them off, + // where it sees whatever the strategy happened to steer. + var censorSrc censor.Source + if o.CensorCounters { + censorSrc = censor.NewKernelSource(ctrl.CensorCounts, censorReadInterval) + } else { + obs := censor.New() + observers = append(observers, obs) + censorSrc = obs } + observer := nfqueue.Observers(observers...) // NFQUEUE runtime. rt, err := nfqueue.New(eng, nfqueue.Config{ @@ -121,6 +143,32 @@ func runServer(o *runCmd) error { return err } + // Profiling is opt-in and separate from the control surface: it is a + // benchmarking tool, and the control surface is unauthenticated on a box + // that carries traffic. The handlers are registered on a mux of our own + // rather than through the package's blank-import side effect, so nothing is + // reachable unless this flag is set. + if o.PprofAddr != "" { + pprofMux := http.NewServeMux() + pprofMux.HandleFunc("/debug/pprof/", pprof.Index) + pprofMux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) + pprofMux.HandleFunc("/debug/pprof/profile", pprof.Profile) + pprofMux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) + pprofMux.HandleFunc("/debug/pprof/trace", pprof.Trace) + pprofSrv := &http.Server{Addr: o.PprofAddr, Handler: pprofMux, ReadHeaderTimeout: 5 * time.Second} + go func() { + log.Warn("pprof enabled", "addr", o.PprofAddr) + if err := pprofSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Error("pprof listener failed", "err", err) + } + }() + defer func() { + shCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _ = pprofSrv.Shutdown(shCtx) + }() + } + // Metric export is opt-in: with no OTLP endpoint configured there is no // collector on the box to export to, so the provider is never built. if telemetry.Enabled() { @@ -133,7 +181,7 @@ func runServer(o *runCmd) error { Mode: o.Mode, Market: o.Market, Engine: eng, - Censor: censorObs, + Censor: censorSrc, Started: started, Verdicts: func() telemetry.Verdicts { s := rt.Snapshot() @@ -154,18 +202,22 @@ func runServer(o *runCmd) error { } // Control/health surface. - ctrl := control.New(control.Providers{ + api := control.New(control.Providers{ Mode: o.Mode, Version: version, Commit: commit, Engine: eng, Canary: pool, Verdicts: func() any { return rt.Snapshot() }, - InboundTCP: func() any { return censorObs.Snapshot() }, + InboundTCP: func() any { return censorSrc.Snapshot() }, + // A strategy change is not just an engine swap: it can put the box on + // or take it off the data path, so it has to go through the controller. + Apply: ctrl.Apply, + Steering: func() any { return ctrl.State() }, }) httpSrv := &http.Server{ Addr: o.ControlAddr, - Handler: ctrl.Handler(), + Handler: api.Handler(), ReadHeaderTimeout: 5 * time.Second, // Bound the whole request read: strategy uploads call io.ReadAll, so a // slow client must not be able to hold a handler open indefinitely. diff --git a/deploy/README.md b/deploy/README.md index 295cd3b..7a6c6ed 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -36,6 +36,9 @@ sidecar run `ethtool -K` to turn the offloads off, so NFQUEUE yields real, MTU-sized, fully-checksummed packets. Always set it to the interface carrying the proxy's traffic. +The offloads come down only while something is actually being steered, and go +back up when it stops — a sidecar with no strategy leaves the NIC alone. + ## Modes - **prod** — the assigned strategy on a fleet box: @@ -154,8 +157,123 @@ Mirror the `lantern-box` provisioning flow: 3. `systemctl enable --now geneva-server.service`. `enable` alone would leave the sidecar stopped until the next boot. -In eval mode the strategy file is optional: the sidecar starts in pass-through -until the GA brain assigns a candidate over `PUT /strategy`. +In eval mode the strategy file is optional: the sidecar starts with no strategy, +steering nothing at all, until the GA brain assigns a candidate over +`PUT /strategy`. + +The nftables rules are runtime-owned: the sidecar programs its table from the +loaded strategy and deletes it on stop, so provisioning must **not** install +steering rules itself. + +## What gets steered + +Steering follows the strategy, because the NFQUEUE round trip — not the +manipulation — is what the sidecar costs. Measured on a 1-vCPU box running +vless+REALITY, queueing every packet on the proxy's port cost 76% of a bulk +transfer's throughput *with no strategy loaded*, while a strategy that duplicated +every data packet cost only ~4% more than that. + +A Geneva strategy hands back any packet its triggers do not match, byte for byte. +So the rules are narrowed to what can match: + +| Strategy | Steered | +| --- | --- | +| no strategy (eval boot, or `PUT ""`) | nothing: no table, no rules, offloads untouched | +| triggers on TCP flags, e.g. `[TCP:flags:S]` | only those flag combinations, per direction | +| an outbound-only forest | outbound only; inbound stays in the kernel | +| a trigger nftables cannot express (`TCP:load`, `IP:ttl`, options) | everything on the port, in that direction | + +`GET /healthz` reports this under `steering`, which is where to look first when a +box is unexpectedly fast or slow: + +```json +"steering": {"steering": true, "outbound": "flags&0xff==0x02", "inbound": "none", "offloads_disabled": true} +``` -The nftables rules are runtime-owned: the sidecar creates its table on start and -deletes it on stop, so provisioning must **not** install steering rules itself. +### Cost of a strategy that touches every packet + +A strategy whose triggers match bulk data cannot be scoped away — those packets +genuinely have to reach userspace. What the sidecar does about it is spend as +little as possible per packet: one `recvmsg` per batch of packets rather than +per packet, accept verdicts batched into one message per batch, rewritten +packets replaced in the queue rather than dropped and reinjected through a raw +socket (which also skips a second trip through netfilter), and no allocation per +packet on the hot path. + +Two counters on `/healthz` say when the box is losing packets rather than +manipulating them: + +| Counter | Meaning | +| --- | --- | +| `verdicts.overruns` | the netlink socket buffer overflowed; those packets bypassed the strategy (the rules' `bypass` flag accepted them, so the proxy kept serving) | +| `verdicts.truncated` | the kernel copied only part of a packet, so it was accepted unmodified rather than manipulated as a fragment | + +Both should be zero. A nonzero `overruns` means the strategy cannot keep up with +the packet rate on this box; a nonzero `truncated` means the copy length is too +small for its traffic. + +### The censor signal comes from nftables counters + +Steering follows the strategy, so an outbound-only strategy delivers no inbound +packet to userspace — and the censor-reachability signal, the inbound +SYN-to-data ratio that estimates whether a box's IP has been burned, is about +inbound packets. Left there, scoping would have bought throughput by going +blind. + +So the classification happens in the kernel instead. Whenever the sidecar has a +table, it also installs named counters and a chain that sorts arriving packets +into them — RST, SYN, FIN, data, ack_only, in that precedence, each rule +returning so every packet lands in exactly one — and reads the counters once per +export interval. **No packet is queued for the signal**, and it works the same in +prod and eval, with or without an inbound tree in the strategy. On by default; +`--censor-counters=false` falls back to the userspace classifier, which only sees +what the strategy already steers. + +Two things the kernel path cannot count, and reports as zero: + +- `undecodable` — a decode failure cannot happen to a packet nobody decodes. +- `fragment` — a non-initial fragment carries no TCP header to match a port + against, so counting them would mean counting every fragment on the box for + every port. + +And one approximation: nftables cannot subtract one header field from another, so +"carries a payload" is `meta length > 80` rather than +`ip length - ihl*4 - dataoffset*4 > 0`. A pure ACK with 32 bytes of options is 72 +bytes, so the threshold is safe; the failure mode is a data segment with fewer +than ~28 payload bytes counting as `ack_only`, which proxy traffic does not +produce. + +The counters ride along with a table that exists for steering. They never keep +one alive on their own, so **a box with no strategy reports no censor signal** — +it also has nothing of ours in the kernel, which is the trade that makes an +unconfigured sidecar free. A box that should be reporting a burn rate is a box +that should have a strategy. + +### `--observe-inbound` (eval mode only) + +With the counters above providing the censor signal, this flag no longer has +anything to do with it. What it still buys is *packets* in userspace rather than +counts — which only the eval-mode canary pool wants, since that captures real +header field values for the GA brain to mutate against. Prod has no canary pool +at all, so in prod the flag would pay for something nothing reads: it is refused +outright at startup rather than warned about. + +**What it costs, if you are wondering why prod may not have it.** One round trip +per *inbound* packet, so it tracks the inbound packet rate, not the byte rate — +which makes it almost free or ruinous depending on which way the box's bulk +traffic runs, and a prod box does not get to choose which its users generate: + +| Workload | without | with | | +| --- | --- | --- | --- | +| download-heavy, handshake-only strategy | 105.1 MB/s | 105.0 MB/s | free | +| download-heavy, strategy tampering every data packet | 36.6 MB/s | 33.3 MB/s | −9% | +| **upload-heavy, handshake-only strategy** | **79.3 MB/s** | **47.4 MB/s** | **−40%** | + +Measured on a 1-vCPU box (route `d711a4df`, vless+REALITY). A download's inbound +direction is nothing but stretch-ACKs — 18.9k inbound packets across 900 MB, one +per ~33 outbound data packets — so observing it is free. An upload's inbound +direction is the bulk stream, and then every packet pays. + +An eval box carries no client traffic at all, so turning it on there costs +nothing worth counting — which is the other half of the argument for the mode +gate: the box that can afford the signal is the box that produces it for free. diff --git a/e2e/run.sh b/e2e/run.sh index 0238426..a408abf 100755 --- a/e2e/run.sh +++ b/e2e/run.sh @@ -14,17 +14,7 @@ set -euo pipefail cd "$(dirname "$0")" COMPOSE=(docker compose -f docker-compose.yml) - -pass() { printf ' \033[32mPASS\033[0m %s\n' "$1"; } -fail() { printf ' \033[31mFAIL\033[0m %s\n' "$1"; exit 1; } -step() { printf '\n\033[1m==> %s\033[0m\n' "$1"; } - -cleanup() { - if [[ "${KEEP:-0}" != "1" ]]; then - "${COMPOSE[@]}" --profile tools down -v --remove-orphans >/dev/null 2>&1 || true - fi -} -trap cleanup EXIT +source ../scripts/harness-lib.sh step "Build and start server + sidecar" "${COMPOSE[@]}" up -d --build server sidecar @@ -32,13 +22,7 @@ step "Build and start server + sidecar" # Wait for the control surface (proves the sidecar came up and installed rules). step "Wait for the control/health surface" -for i in $(seq 1 30); do - if "${COMPOSE[@]}" exec -T tester curl -fsS http://server:8092/healthz >/dev/null 2>&1; then - break - fi - [[ $i -eq 30 ]] && fail "control surface never became healthy" - sleep 1 -done +wait_healthy tester || fail "control surface never became healthy" mode=$("${COMPOSE[@]}" exec -T tester curl -fsS http://server:8092/healthz | jq -r .mode) [[ "$mode" == "prod" ]] && pass "control surface healthy (mode=$mode)" || fail "unexpected mode: $mode" @@ -62,23 +46,39 @@ fails=$(echo "$health" | jq '.verdicts.inject_fails') [[ "$rei" -gt 0 ]] && pass "packets were reinjected ($rei)" || fail "no reinjection occurred" [[ "$fails" -eq 0 ]] && pass "zero reinjection failures" || fail "$fails reinjection failures" -step "Inbound TCP classification (the censor-reachability signal)" +# The strategy under test is outbound-only, and nothing inbound is steered for +# it: no --observe-inbound, no inbound tree. The counts come from nftables +# counters that classify what arrives in the kernel, which is the only reason +# this signal survives steering being scoped to the strategy. +step "Inbound TCP classification from kernel counters (the censor-reachability signal)" +health=$("${COMPOSE[@]}" exec -T tester curl -fsS http://server:8092/healthz) echo "$health" | jq '.inbound_tcp' syn=$(echo "$health" | jq '.inbound_tcp.events.syn') data=$(echo "$health" | jq '.inbound_tcp.events.data') -undec=$(echo "$health" | jq '.inbound_tcp.events.undecodable') -# The tester completed a real 1 MiB transfer, so the uncensored baseline is -# syns followed by data. A burned box is the same shape with data at zero. -[[ "$syn" -gt 0 ]] && pass "inbound SYNs classified ($syn)" || fail "no inbound SYNs classified" -[[ "$data" -gt 0 ]] && pass "inbound data segments classified ($data)" || fail "no inbound data classified" -[[ "$undec" -eq 0 ]] && pass "every inbound packet was decodable" || fail "$undec inbound packets undecodable" +# The tester completed a real 1 MiB transfer, so the uncensored baseline is syns +# followed by data. A burned box is the same shape with data at zero. +[[ "$syn" -gt 0 ]] && pass "inbound SYNs counted in the kernel ($syn)" || fail "no inbound SYNs counted" +[[ "$data" -gt 0 ]] && pass "inbound data segments counted in the kernel ($data)" || fail "no inbound data counted" +# And the point of doing it in the kernel: none of those packets was queued. +inpkts=$("${COMPOSE[@]}" exec -T sidecar nft list table inet geneva_server | grep -cE "tcp dport 8080 .*queue" || true) +[[ "$inpkts" -eq 0 ]] && pass "no inbound queue rule: the signal cost no userspace round trip" \ + || fail "inbound packets are being queued after all" -step "2. Steering is scoped to the proxy port only" +step "2. Steering is scoped to the proxy port and to what the strategy can match" ruleset=$("${COMPOSE[@]}" exec -T sidecar nft list table inet geneva_server) echo "$ruleset" echo "$ruleset" | grep -q "tcp sport 8080" && pass "egress steering scoped to sport 8080" || fail "missing egress rule" -echo "$ruleset" | grep -q "tcp dport 8080" && pass "ingress steering scoped to dport 8080" || fail "missing ingress rule" echo "$ruleset" | grep -q "9090" && fail "ruleset unexpectedly references port 9090" || pass "unrelated port 9090 not steered" +# The strategy is outbound-only, so nothing inbound may be queued — the counters +# handle inbound without taking a packet out of the kernel. +echo "$ruleset" | grep -qE "tcp dport 8080 .*queue" && fail "inbound queue rule installed for an outbound-only strategy" \ + || pass "no inbound steering for an outbound-only strategy" +echo "$ruleset" | grep -q "jump censor_in" && pass "inbound classified by the counter chain instead" \ + || fail "missing the censor classification jump" +# And the egress rule must carry the flag match, or bulk data is still being +# queued for a strategy that only fires on PSH|ACK. +echo "$ruleset" | grep -q "tcp flags" && pass "egress steering narrowed to the strategy's flags" \ + || fail "egress rule not narrowed to the strategy's trigger flags" "${COMPOSE[@]}" exec -T tester sh -c 'curl -fsS http://server:9090/healthz' >/dev/null \ && pass "unrelated :9090 service still serves normally" \ || fail ":9090 service broke" @@ -94,7 +94,24 @@ got=$("${COMPOSE[@]}" exec -T tester sh -c 'curl -fsS http://server:8092/strateg && pass "service still serves after the in-place swap" \ || fail "service broke after strategy swap" -step "3. Clean teardown leaves no stale rules" +step "3. An empty strategy takes the box off the data path entirely" +"${COMPOSE[@]}" exec -T tester sh -c 'curl -fsS -X PUT --data-binary "" http://server:8092/strategy' >/dev/null \ + && pass "PUT of an empty strategy accepted" \ + || fail "PUT of an empty strategy rejected" +if "${COMPOSE[@]}" exec -T sidecar nft list table inet geneva_server >/dev/null 2>&1; then + fail "steering table still present with a strategy that can match nothing" +else + pass "steering table removed: no packet takes the round trip" +fi +steering=$("${COMPOSE[@]}" exec -T tester curl -fsS http://server:8092/healthz | jq -r .steering.steering) +[[ "$steering" == "false" ]] && pass "health surface reports steering=false" || fail "health surface reports steering=$steering" +"${COMPOSE[@]}" exec -T tester sh -c 'curl -fsS http://server:8080/healthz' >/dev/null \ + && pass "service still serves with the sidecar idle" \ + || fail "service broke after the strategy was withdrawn" +# Put a strategy back, so the teardown check below exercises a live table. +"${COMPOSE[@]}" exec -T tester sh -c "curl -fsS -X PUT --data-binary '$newdna' http://server:8092/strategy" >/dev/null + +step "4. Clean teardown leaves no stale rules" "${COMPOSE[@]}" stop -t 10 sidecar >/dev/null "${COMPOSE[@]}" logs sidecar 2>&1 | grep -q "nftables steering removed" \ && pass "sidecar logged rule teardown on shutdown" \ diff --git a/go.mod b/go.mod index cfd2905..34ae3ad 100644 --- a/go.mod +++ b/go.mod @@ -4,10 +4,10 @@ go 1.25.0 require ( github.com/alexflint/go-arg v1.6.1 - github.com/florianl/go-nfqueue/v2 v2.1.0 - github.com/getlantern/geneva v0.0.0-20260828121546-e4b88d19a7b3 + github.com/getlantern/geneva v0.0.0-20260901121220-c04e0fa29f63 github.com/getlantern/semconv v0.0.0-20260831125104-59924138100b github.com/gopacket/gopacket v1.7.1 + github.com/mdlayher/netlink v1.9.0 go.opentelemetry.io/otel v1.46.0 go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.46.0 go.opentelemetry.io/otel/metric v1.46.0 @@ -25,7 +25,6 @@ require ( github.com/google/go-cmp v0.7.0 // indirect github.com/google/uuid v1.6.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect - github.com/mdlayher/netlink v1.9.0 // indirect github.com/mdlayher/socket v0.5.1 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/otel/trace v1.46.0 // indirect diff --git a/go.sum b/go.sum index b2883b6..d2fbc4b 100644 --- a/go.sum +++ b/go.sum @@ -7,10 +7,8 @@ github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F9 github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/florianl/go-nfqueue/v2 v2.1.0 h1:Fywt30TY/evxyDySpXjxQ1jsRW7nQbLpOhELqpr4068= -github.com/florianl/go-nfqueue/v2 v2.1.0/go.mod h1:8PKUM5rYoVFO5IZV1bifx4/b0jHAglKkHXr9PRwzi4Y= -github.com/getlantern/geneva v0.0.0-20260828121546-e4b88d19a7b3 h1:nFZptUuU9qIy+JS64rTHQfR4AjrvN1XFNX5Il/vpDDs= -github.com/getlantern/geneva v0.0.0-20260828121546-e4b88d19a7b3/go.mod h1:+qFYj07mr5wkT1gpxHX6tJiGTb9j6RF17A1OOdLR7Sg= +github.com/getlantern/geneva v0.0.0-20260901121220-c04e0fa29f63 h1:UDd4QL7Xbr7Hn6nGq0gPlHtA7sNlblMhZHe9f5TcIiQ= +github.com/getlantern/geneva v0.0.0-20260901121220-c04e0fa29f63/go.mod h1:+qFYj07mr5wkT1gpxHX6tJiGTb9j6RF17A1OOdLR7Sg= github.com/getlantern/semconv v0.0.0-20260831125104-59924138100b h1:B86mZ37rhiKZgmjMAh69Rxc87GpudiUdiX9QPOv9GUc= github.com/getlantern/semconv v0.0.0-20260831125104-59924138100b/go.mod h1:GkPT5P9JoOTIRXRmFWxYgu1hhXgTFFTNc2hoG7WQc3g= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -28,8 +26,6 @@ github.com/gopacket/gopacket v1.7.1 h1:1C7/wrJ5HyiEAYDtStJHQk4rV0ChpanZDV9+3Ov3g github.com/gopacket/gopacket v1.7.1/go.mod h1:QKowPlTLrQU2rqV5C5I14Aoaid3l8da3kbddibc/Wgk= github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY= -github.com/jsimonetti/rtnetlink/v2 v2.2.0 h1:/KfZ310gOAFrXXol5VwnFEt+ucldD/0dsSRZwpHCP9w= -github.com/jsimonetti/rtnetlink/v2 v2.2.0/go.mod h1:lbjDHxC+5RJ08lzPeA90Ls2pEoId3F08MoEMlhfHxeI= github.com/mdlayher/netlink v1.9.0 h1:G8+GLq2x3v4D4MVIqDdNUhTUC7TKiCy/6MDkmItfKco= github.com/mdlayher/netlink v1.9.0/go.mod h1:YBnl5BXsCoRuwBjKKlZ+aYmEoq0r12FDA/3JC+94KDg= github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos= diff --git a/internal/censor/kernel.go b/internal/censor/kernel.go new file mode 100644 index 0000000..ccf9ce7 --- /dev/null +++ b/internal/censor/kernel.go @@ -0,0 +1,148 @@ +package censor + +import ( + "context" + "sync" + "time" +) + +// Source is where the inbound TCP counts come from. Two implementations exist +// and only one is active on a box: +// +// - Observer, which classifies packets that NFQUEUE delivered to userspace. +// It only ever sees what the strategy already asked to be steered. +// - KernelSource, which reads nftables counters that classified the packets in +// the kernel. It sees every inbound packet on the proxy's port whether or +// not the strategy touches inbound, and costs no userspace round trip. +type Source interface { + Count(e Event) uint64 + Snapshot() Snapshot +} + +// KernelSource exposes nftables classification counters as censor events. +// +// This is what lets the burn signal survive steering being scoped to what a +// strategy can act on. An outbound-only strategy steers no inbound packets, so +// the userspace classifier sees nothing and the signal goes dark — while the +// kernel can count what arrives for free, and does. +type KernelSource struct { + read func(context.Context) (map[string]uint64, error) + ttl time.Duration + + mu sync.Mutex + // total is the monotonic count exported for each event. The kernel's + // counters are objects inside the sidecar's table, so they reset whenever + // the table is rebuilt — which a strategy change does. Accumulating deltas + // here keeps the exported series monotonic across those rebuilds, so a + // rollout does not look like a counter going backwards. + total [eventCount]uint64 + // lastRaw is the previous reading, to difference against. + lastRaw [eventCount]uint64 + lastRead time.Time + // reading marks a read in flight, so concurrent callers return the + // last-known totals instead of queueing behind the nft subprocess. + reading bool + // reads and readErrors are for diagnosis: a source that cannot read is + // reporting stale numbers, and Reads is how a test proves that happened. + reads, readErrors uint64 +} + +// NewKernelSource returns a source that reads counts through read, no more often +// than once per ttl. read is called with a short-lived context by whichever +// goroutine asks for a count. +// +// A ttl of zero or less reads on every call. That is not what a box wants — one +// nft invocation per event per metric export — but it is what a test wants, and +// silently substituting a default would make the caching untestable. +func NewKernelSource(read func(context.Context) (map[string]uint64, error), ttl time.Duration) *KernelSource { + return &KernelSource{read: read, ttl: ttl} +} + +// eventByName maps the kernel counter names back to events. The kernel counters +// are named for the events, so this is the identity for those it can classify; +// fragment and undecodable have no kernel equivalent and stay at zero. +var eventByName = func() map[string]Event { + m := make(map[string]Event, eventCount) + for e := Event(0); e < eventCount; e++ { + m[e.String()] = e + } + return m +}() + +// refresh reads the counters if the cached values are older than the TTL. +// Failures leave the previous totals in place: stale counts are a better answer +// than zeroes, which would read as "the censor stopped". +// +// The read itself — a fork+exec of nft — runs outside the lock: Count feeds the +// metric callback and Snapshot feeds /healthz, and neither may stall behind a +// slow subprocess. One caller reads; everyone else gets the last-known totals. +func (k *KernelSource) refresh() { + k.mu.Lock() + if k.reading || (k.ttl > 0 && !k.lastRead.IsZero() && time.Since(k.lastRead) < k.ttl) { + k.mu.Unlock() + return + } + k.reading = true + k.mu.Unlock() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + raw, err := k.read(ctx) + cancel() + + k.mu.Lock() + defer k.mu.Unlock() + k.reading = false + k.lastRead = time.Now() + k.reads++ + if err != nil { + k.readErrors++ + return + } + for name, v := range raw { + e, ok := eventByName[name] + if !ok { + continue + } + switch { + case v >= k.lastRaw[e]: + k.total[e] += v - k.lastRaw[e] + default: + // The counter went backwards, so the table was rebuilt and the + // counter started over: everything it holds now is new. + k.total[e] += v + } + k.lastRaw[e] = v + } +} + +// Count returns the accumulated count for one event. +func (k *KernelSource) Count(e Event) uint64 { + k.refresh() + k.mu.Lock() + defer k.mu.Unlock() + if e < 0 || e >= eventCount { + return 0 + } + return k.total[e] +} + +// Snapshot returns all accumulated counts. +func (k *KernelSource) Snapshot() Snapshot { + k.refresh() + k.mu.Lock() + defer k.mu.Unlock() + s := Snapshot{Events: make(map[string]uint64, eventCount)} + for e := Event(0); e < eventCount; e++ { + s.Events[e.String()] = k.total[e] + } + return s +} + +// Reads reports how many times the counters have been read and how many of +// those failed. A source whose reads fail is reporting stale numbers, and this +// is what makes that observable. +func (k *KernelSource) Reads() (total, failed uint64) { + k.mu.Lock() + defer k.mu.Unlock() + return k.reads, k.readErrors +} diff --git a/internal/censor/kernel_test.go b/internal/censor/kernel_test.go new file mode 100644 index 0000000..ea1c35b --- /dev/null +++ b/internal/censor/kernel_test.go @@ -0,0 +1,98 @@ +package censor + +import ( + "context" + "errors" + "testing" + "time" +) + +func TestKernelSourceCounts(t *testing.T) { + raw := map[string]uint64{"syn": 5, "data": 100, "rst": 1} + k := NewKernelSource(func(context.Context) (map[string]uint64, error) { return raw, nil }, -1) + + if got := k.Count(EventSYN); got != 5 { + t.Errorf("syn = %d, want 5", got) + } + snap := k.Snapshot() + if snap.Events["data"] != 100 || snap.Events["rst"] != 1 { + t.Errorf("snapshot = %v", snap.Events) + } + // Every event is present, so a zero reads as zero rather than as a missing + // series — the same contract the userspace observer has. + for _, want := range []string{"syn", "rst", "fin", "data", "ack_only", "fragment", "undecodable"} { + if _, ok := snap.Events[want]; !ok { + t.Errorf("event %q missing from snapshot", want) + } + } +} + +// TestKernelSourceAccumulatesAcrossResets is the property that makes these +// counters usable as a metric: the kernel's counters are objects inside the +// sidecar's table, so a strategy change rebuilds the table and restarts them +// from zero. The exported series must not go backwards when that happens. +func TestKernelSourceAccumulatesAcrossResets(t *testing.T) { + var raw map[string]uint64 + k := NewKernelSource(func(context.Context) (map[string]uint64, error) { return raw, nil }, -1) + + raw = map[string]uint64{"syn": 10} + if got := k.Count(EventSYN); got != 10 { + t.Fatalf("first read = %d, want 10", got) + } + raw = map[string]uint64{"syn": 25} + if got := k.Count(EventSYN); got != 25 { + t.Fatalf("after growth = %d, want 25", got) + } + // Table rebuilt: the counter starts over at 3, and everything it holds is + // new traffic. + raw = map[string]uint64{"syn": 3} + if got := k.Count(EventSYN); got != 28 { + t.Errorf("after a reset = %d, want 28", got) + } + raw = map[string]uint64{"syn": 4} + if got := k.Count(EventSYN); got != 29 { + t.Errorf("after the reset, growth = %d, want 29", got) + } +} + +// TestKernelSourceKeepsCountsOnReadFailure pins that a failed read reports the +// last known counts rather than zeroes: zeroes would read as "the censor +// stopped", which is the opposite of "we cannot see". +func TestKernelSourceKeepsCountsOnReadFailure(t *testing.T) { + fail := false + k := NewKernelSource(func(context.Context) (map[string]uint64, error) { + if fail { + return nil, errors.New("nft went away") + } + return map[string]uint64{"syn": 7}, nil + }, -1) + + if got := k.Count(EventSYN); got != 7 { + t.Fatalf("first read = %d, want 7", got) + } + fail = true + if got := k.Count(EventSYN); got != 7 { + t.Errorf("after a failed read = %d, want the last known 7", got) + } + if _, failed := k.Reads(); failed == 0 { + t.Error("failed read not counted") + } +} + +// TestKernelSourceCachesReads keeps the read off the per-call path: Count is +// called once per event per metric export, and each read is an nft invocation. +func TestKernelSourceCachesReads(t *testing.T) { + var reads int + k := NewKernelSource(func(context.Context) (map[string]uint64, error) { + reads++ + return map[string]uint64{"syn": 1}, nil + }, time.Hour) + + for range 10 { + k.Count(EventSYN) + k.Snapshot() + } + if reads != 1 { + t.Errorf("read %d times, want 1 within the TTL", reads) + } +} diff --git a/internal/censor/observer.go b/internal/censor/observer.go index 1733559..2c43a8d 100644 --- a/internal/censor/observer.go +++ b/internal/censor/observer.go @@ -58,6 +58,14 @@ const ( eventCount ) +// KernelEvents are the events the nftables classification chain can sort +// packets into, in classification precedence order. It is the single list the +// kernel-side counter names and rules derive from (see internal/nftables), so +// adding or renaming an event cannot leave the two sides silently disagreeing. +// EventFragment and EventUndecodable have no kernel equivalent: a fragment +// carries no TCP header to match, and nothing the kernel counts is decoded. +var KernelEvents = []Event{EventRST, EventSYN, EventFIN, EventData, EventACKOnly} + func (e Event) String() string { switch e { case EventRST: diff --git a/internal/control/server.go b/internal/control/server.go index 8959653..13a435c 100644 --- a/internal/control/server.go +++ b/internal/control/server.go @@ -17,6 +17,7 @@ package control import ( + "context" "encoding/json" "errors" "io" @@ -42,6 +43,16 @@ type Providers struct { // InboundTCP returns the inbound TCP event counts (JSON-marshalable), the // box-side censor-reachability signal. It may be nil. InboundTCP func() any + // Apply installs a strategy end to end: it reprograms the kernel's steering + // for what the new strategy can match and then swaps the engine. PUT goes + // through it rather than straight to the engine, because a strategy change + // can put the box on or take it off the data path. It is required for PUT: + // a caller that forgets to wire it gets a loud 503, never a silent + // engine-only swap that leaves the kernel steering for the old strategy. + Apply func(ctx context.Context, dna string) error + // Steering returns what the box is currently steering (JSON-marshalable). + // It may be nil. + Steering func() any } // Server is the HTTP control surface. @@ -79,6 +90,10 @@ type healthResp struct { // read on a box with no collector configured — during an e2e run, or when // an operator is on the box asking whether its IP has been burned. InboundTCP any `json:"inbound_tcp,omitempty"` + // Steering says whether the box is on the data path at all, and for which + // packets. A sidecar with no strategy steers nothing, and an operator + // looking at a slow box needs to be able to tell that from here. + Steering any `json:"steering,omitempty"` } func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { @@ -97,20 +112,30 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { if s.p.InboundTCP != nil { resp.InboundTCP = s.p.InboundTCP() } + if s.p.Steering != nil { + resp.Steering = s.p.Steering() + } writeJSON(w, http.StatusOK, resp) } // handleStrategy serves GET (current DNA) and PUT (assign/replace the strategy). // PUT validates the DNA before installing it, and the swap is atomic, so the new -// strategy applies to the next packet with no restart. This works in both modes: -// the swap is strategy-content-only (the queues, nftables rules, reinjector, and -// offload setup are untouched). The write endpoint is unauthenticated, so the -// control address must stay on a private interface (see deploy/README.md). +// strategy applies to the next packet with no restart. This works in both modes. +// +// The swap is not strategy-content-only: steering is scoped to what the strategy +// can match, so installing one can widen, narrow, or remove the kernel's rules +// (see internal/steering). PUT of an empty strategy takes the box off the data +// path completely. The write endpoint is unauthenticated, so the control address +// must stay on a private interface (see deploy/README.md). func (s *Server) handleStrategy(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: writeJSON(w, http.StatusOK, map[string]string{"strategy": s.p.Engine.DNA()}) case http.MethodPut: + if s.p.Apply == nil { + writeError(w, http.StatusServiceUnavailable, "strategy updates are not wired up") + return + } // MaxBytesReader returns an error once the limit is exceeded, so an oversized // body is rejected rather than silently truncated (as io.LimitReader would). r.Body = http.MaxBytesReader(w, r.Body, 1<<20) @@ -127,8 +152,15 @@ func (s *Server) handleStrategy(w http.ResponseWriter, r *http.Request) { // Tolerate a trailing newline or surrounding whitespace (common when the // body is piped from a file), which would otherwise fail validation. dna := strings.TrimSpace(string(body)) - if err := s.p.Engine.SetStrategy(dna); err != nil { - writeError(w, http.StatusBadRequest, "invalid strategy: "+err.Error()) + if err := s.p.Apply(r.Context(), dna); err != nil { + // Only a strategy the client got wrong is the client's fault. A + // failure to program the kernel for a valid one is ours, and a 400 + // there would send the caller off fixing a DNA that is fine. + if errors.Is(err, engine.ErrInvalidStrategy) { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + writeError(w, http.StatusInternalServerError, "apply strategy: "+err.Error()) return } writeJSON(w, http.StatusOK, map[string]string{"strategy": s.p.Engine.DNA()}) diff --git a/internal/control/server_test.go b/internal/control/server_test.go index fde5188..8f82b56 100644 --- a/internal/control/server_test.go +++ b/internal/control/server_test.go @@ -1,6 +1,7 @@ package control import ( + "context" "encoding/json" "net/http" "net/http/httptest" @@ -25,6 +26,9 @@ func newTestServer(t *testing.T, mode, dna string, withCanary bool) *httptest.Se Version: "test", Engine: eng, Verdicts: func() any { return map[string]int{"accepted": 0} }, + // Engine-only apply: these tests exercise the HTTP surface, not the + // kernel-reprogramming half a real box wires in. + Apply: func(_ context.Context, dna string) error { return eng.SetStrategy(dna) }, } if withCanary { p.Canary = canary.NewPool("RU", 16) diff --git a/internal/engine/bench_test.go b/internal/engine/bench_test.go new file mode 100644 index 0000000..e51ba3c --- /dev/null +++ b/internal/engine/bench_test.go @@ -0,0 +1,88 @@ +package engine + +import ( + "fmt" + "testing" + + "github.com/getlantern/geneva/strategy" + "github.com/gopacket/gopacket" + "github.com/gopacket/gopacket/layers" + + "github.com/getlantern/geneva-server/internal/testutil" +) + +// The per-packet cost of the engine is what NFQUEUE steering multiplies by the +// packet rate, so it is the number to watch: at 1 Gbps with 1500-byte frames a +// box sees ~83k packets/s per direction, and every microsecond of per-packet +// work is 8.3% of a core. +// +// The cases are chosen to separate the three costs that make up Process: +// the private copy, the gopacket decode, and the strategy application. A +// pass-through engine pays the first two and nothing else, which is why an +// unconfigured sidecar is not free. +func BenchmarkProcess(b *testing.B) { + data := testutil.BuildTCP(b, 1, testutil.TCPFlags{ACK: true, PSH: true}, make([]byte, 1460)) + syn := testutil.BuildTCP(b, 1, testutil.TCPFlags{SYN: true}, nil) + + cases := []struct { + name string + dna string + raw []byte + }{ + // What an eval box runs before the brain assigns it anything, and what + // a rolled-back prod box runs after PUT "". + {"passthrough/data1460", "", data}, + {"passthrough/syn", "", syn}, + // A realistic prod shape: the trigger cannot match a data packet, so + // every byte of bulk traffic is decoded for nothing. + {"handshake-trigger/data1460", `[TCP:flags:S]-duplicate-| \/`, data}, + {"handshake-trigger/syn", `[TCP:flags:S]-duplicate-| \/`, syn}, + // The common manipulation: one packet in, one packet out, every data + // packet rewritten. This is the shape the in-queue modified verdict + // makes cheap. + {"tamper-data/data1460", `[TCP:flags:PA]-tamper{TCP:window:replace:100}-| \/`, data}, + // Worst case: the trigger matches every data packet and the action + // duplicates it, so a second packet has to reach the wire somehow. + {"duplicate-data/data1460", `[TCP:flags:PA]-duplicate-| \/`, data}, + } + for _, c := range cases { + b.Run(c.name, func(b *testing.B) { + e := mustEngine(b, c.dna) + // A reused scratch, as the NFQUEUE runtime does: one per queue + // goroutine. Benchmarking with nil would measure an allocator the + // hot path does not touch. + scratch := &Scratch{} + b.SetBytes(int64(len(c.raw))) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if _, err := e.Process(c.raw, strategy.DirectionOutbound, scratch); err != nil { + b.Fatal(err) + } + } + }) + } +} + +// BenchmarkDecode isolates the gopacket half of Process. Anything Process costs +// beyond this is the copy plus the strategy itself. +func BenchmarkDecode(b *testing.B) { + for _, size := range []int{0, 1460} { + raw := testutil.BuildTCP(b, 1, testutil.TCPFlags{ACK: true, PSH: true}, make([]byte, size)) + b.Run(fmt.Sprintf("payload%d", size), func(b *testing.B) { + b.SetBytes(int64(len(raw))) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + buf := make([]byte, len(raw)) + copy(buf, raw) + // The same decode options Process uses, so this measures the + // hot path's decode rather than gopacket's eager default. + pkt := gopacket.NewPacket(buf, layers.LayerTypeIPv4, gopacket.DecodeOptions{Lazy: true, NoCopy: true}) + if pkt.ErrorLayer() != nil { + b.Fatal("decode failed") + } + } + }) + } +} diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 11d69df..130af03 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -14,6 +14,7 @@ package engine import ( + "bytes" "errors" "fmt" "sync" @@ -63,6 +64,9 @@ type Result struct { // Packets holds the serialized replacement packets, in order. It is empty // for a dropped packet and holds exactly the input bytes for an unchanged // packet. Each entry is a complete IPv4 packet ready for reinjection. + // + // The entries alias the Scratch passed to Process and are only valid until + // the next Process call with that Scratch. Packets [][]byte } @@ -145,16 +149,22 @@ func New(dna string) (*Engine, error) { return e, nil } +// ErrInvalidStrategy marks a strategy the caller supplied as unparseable or +// invalid. The control surface uses it to tell a client error (a bad PUT body, +// worth a 4xx) from an infrastructure failure applying a valid strategy (a +// 5xx); anything that rejects a DNA on its content should wrap it. +var ErrInvalidStrategy = errors.New("invalid strategy") + // SetStrategy parses, validates, and atomically installs a new strategy. It is // safe to call concurrently with Process; in-flight packets finish against the // previous strategy and subsequent packets use the new one. func (e *Engine) SetStrategy(dna string) error { s, err := geneva.NewStrategy(dna) if err != nil { - return fmt.Errorf("parse strategy: %w", err) + return fmt.Errorf("%w: parse: %w", ErrInvalidStrategy, err) } if err := geneva.Validate(s); err != nil { - return fmt.Errorf("validate strategy: %w", err) + return fmt.Errorf("%w: validate: %w", ErrInvalidStrategy, err) } e.mu.Lock() // The initial load from New is not a swap, so the counter reads as the @@ -179,7 +189,14 @@ func (e *Engine) DNA() string { // Process decodes a raw IPv4 packet, applies the current strategy for the given // direction, and returns the verdict and replacement packets. raw must begin at // the IPv4 header, exactly as NFQUEUE delivers it. -func (e *Engine) Process(raw []byte, dir strategy.Direction) (Result, error) { +// +// scratch carries the per-packet working memory. It may be nil, in which case +// Process allocates; the NFQUEUE runtime passes one per queue goroutine, which +// is what keeps the hot path from allocating a fresh 1500-byte buffer, a decode +// copy and an output slice for every packet on the wire. A CPU profile of a +// tamper-every-packet strategy spent ~30% of its time in the garbage collector +// and the scheduler feeding it. +func (e *Engine) Process(raw []byte, dir strategy.Direction, scratch *Scratch) (Result, error) { e.Stats.PacketsIn.Add(1) e.Stats.BytesIn.Add(uint64(len(raw))) @@ -187,12 +204,21 @@ func (e *Engine) Process(raw []byte, dir strategy.Direction) (Result, error) { if l == nil { return Result{}, errors.New("engine has no strategy") } + if scratch == nil { + scratch = &Scratch{} + } - // Decode a private copy: gopacket packets alias their input buffer and the - // tamper actions mutate layers in place. - buf := make([]byte, len(raw)) + // Decode a private copy: the tamper actions mutate the decoded layers in + // place, and raw is the kernel's buffer, which classify still needs + // unmodified to tell "unchanged" from "tampered". + // + // NoCopy is what makes the copy above the only one: without it gopacket + // takes a second copy of the same bytes. Lazy defers decoding a layer until + // a trigger or action actually reads it, which for a strategy that only + // looks at TCP flags means the payload is never touched. + buf := scratch.packet(len(raw)) copy(buf, raw) - pkt := gopacket.NewPacket(buf, layers.LayerTypeIPv4, gopacket.Default) + pkt := gopacket.NewPacket(buf, layers.LayerTypeIPv4, gopacket.DecodeOptions{Lazy: true, NoCopy: true}) if errLayer := pkt.ErrorLayer(); errLayer != nil { e.Stats.Errors.Add(1) return Result{}, fmt.Errorf("decode packet: %w", errLayer.Error()) @@ -204,25 +230,63 @@ func (e *Engine) Process(raw []byte, dir strategy.Direction) (Result, error) { return Result{}, fmt.Errorf("apply strategy: %w", err) } - res := classify(raw, out) + res := classify(raw, out, scratch) e.record(res) return res, nil } -func classify(raw []byte, out []gopacket.Packet) Result { +// Scratch is one packet's worth of reusable working memory, owned by a single +// goroutine. The NFQUEUE runtime keeps one per queue, since each queue's +// callback is serialized on one goroutine. +// +// The Result returned by Process aliases this memory: its Packets stay valid +// only until the next Process call with the same Scratch. That is exactly the +// lifetime the runtime needs — it issues the verdict, which copies into the +// netlink message, before reading another packet. +type Scratch struct { + buf []byte + pkts [][]byte +} + +// packet returns a buffer of exactly n bytes, growing the backing array only +// when a packet is larger than anything seen before. +func (s *Scratch) packet(n int) []byte { + if cap(s.buf) < n { + // Round up to the next MTU-ish size so a run of slightly larger packets + // does not reallocate on each one. + s.buf = make([]byte, n, max(n, 2048)) + } + return s.buf[:n] +} + +// outputs returns a zero-length slice with room for n packets. +func (s *Scratch) outputs(n int) [][]byte { + if cap(s.pkts) < n { + s.pkts = make([][]byte, 0, max(n, 4)) + } + return s.pkts[:0] +} + +// classify decides the outcome and collects the serialized output packets. +// +// The output bytes are not copied: they are either the scratch buffer the packet +// was decoded into or buffers the geneva library allocated while serializing, +// and both outlive the caller's verdict. See Scratch for the lifetime contract. +func classify(raw []byte, out []gopacket.Packet, scratch *Scratch) Result { switch len(out) { case 0: return Result{Outcome: OutcomeDropped} case 1: data := out[0].Data() - if bytesEqual(raw, data) { - return Result{Outcome: OutcomeUnchanged, Packets: [][]byte{cloneBytes(data)}} + outcome := OutcomeTampered + if bytes.Equal(raw, data) { + outcome = OutcomeUnchanged } - return Result{Outcome: OutcomeTampered, Packets: [][]byte{cloneBytes(data)}} + return Result{Outcome: outcome, Packets: append(scratch.outputs(1), data)} default: - packets := make([][]byte, 0, len(out)) + packets := scratch.outputs(len(out)) for _, p := range out { - packets = append(packets, cloneBytes(p.Data())) + packets = append(packets, p.Data()) } return Result{Outcome: OutcomeExpanded, Packets: packets} } @@ -247,21 +311,3 @@ func (e *Engine) record(r Result) { // Snapshot returns a value copy of the cumulative stats with overhead ratios. func (e *Engine) Snapshot() Snapshot { return e.Stats.snapshot() } - -func cloneBytes(b []byte) []byte { - c := make([]byte, len(b)) - copy(c, b) - return c -} - -func bytesEqual(a, b []byte) bool { - if len(a) != len(b) { - return false - } - for i := range a { - if a[i] != b[i] { - return false - } - } - return true -} diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go index d37c0c2..034c4a4 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -1,51 +1,18 @@ package engine import ( + "bytes" "encoding/binary" "testing" "github.com/getlantern/geneva/strategy" "github.com/gopacket/gopacket" "github.com/gopacket/gopacket/layers" -) -// buildTCP builds a serialized IPv4/TCP packet with a valid checksum and length. -func buildTCP(t *testing.T, seq uint32, flags tcpFlags, payload []byte) []byte { - t.Helper() - ip := &layers.IPv4{ - Version: 4, - IHL: 5, - TTL: 64, - Id: 1234, - Protocol: layers.IPProtocolTCP, - SrcIP: []byte{10, 0, 0, 1}, - DstIP: []byte{10, 0, 0, 2}, - } - tcp := &layers.TCP{ - SrcPort: 8080, - DstPort: 44000, - Seq: seq, - Window: 65535, - SYN: flags.syn, - ACK: flags.ack, - PSH: flags.psh, - RST: flags.rst, - FIN: flags.fin, - } - if err := tcp.SetNetworkLayerForChecksum(ip); err != nil { - t.Fatalf("set network layer: %v", err) - } - buf := gopacket.NewSerializeBuffer() - opts := gopacket.SerializeOptions{ComputeChecksums: true, FixLengths: true} - if err := gopacket.SerializeLayers(buf, opts, ip, tcp, gopacket.Payload(payload)); err != nil { - t.Fatalf("serialize: %v", err) - } - return buf.Bytes() -} - -type tcpFlags struct{ syn, ack, psh, rst, fin bool } + "github.com/getlantern/geneva-server/internal/testutil" +) -func mustEngine(t *testing.T, dna string) *Engine { +func mustEngine(t testing.TB, dna string) *Engine { t.Helper() e, err := New(dna) if err != nil { @@ -117,23 +84,23 @@ func ones(b []byte) uint16 { func TestUnchanged_EmptyStrategy(t *testing.T) { e := mustEngine(t, "") - raw := buildTCP(t, 1000, tcpFlags{psh: true, ack: true}, []byte("hello world")) - res, err := e.Process(raw, strategy.DirectionOutbound) + raw := testutil.BuildTCP(t, 1000, testutil.TCPFlags{PSH: true, ACK: true}, []byte("hello world")) + res, err := e.Process(raw, strategy.DirectionOutbound, nil) if err != nil { t.Fatal(err) } if res.Outcome != OutcomeUnchanged { t.Fatalf("outcome = %v, want unchanged", res.Outcome) } - if len(res.Packets) != 1 || !bytesEqual(res.Packets[0], raw) { + if len(res.Packets) != 1 || !bytes.Equal(res.Packets[0], raw) { t.Fatalf("packet altered by empty strategy") } } func TestUnchanged_PassthroughTree(t *testing.T) { e := mustEngine(t, `[TCP:flags:PA]-| \/`) - raw := buildTCP(t, 1000, tcpFlags{psh: true, ack: true}, []byte("hello")) - res, err := e.Process(raw, strategy.DirectionOutbound) + raw := testutil.BuildTCP(t, 1000, testutil.TCPFlags{PSH: true, ACK: true}, []byte("hello")) + res, err := e.Process(raw, strategy.DirectionOutbound, nil) if err != nil { t.Fatal(err) } @@ -144,8 +111,8 @@ func TestUnchanged_PassthroughTree(t *testing.T) { func TestDropped(t *testing.T) { e := mustEngine(t, `[TCP:flags:R]-drop-| \/`) - raw := buildTCP(t, 1000, tcpFlags{rst: true}, nil) - res, err := e.Process(raw, strategy.DirectionOutbound) + raw := testutil.BuildTCP(t, 1000, testutil.TCPFlags{RST: true}, nil) + res, err := e.Process(raw, strategy.DirectionOutbound, nil) if err != nil { t.Fatal(err) } @@ -162,8 +129,8 @@ func TestDropped(t *testing.T) { func TestDuplicated(t *testing.T) { e := mustEngine(t, `[TCP:flags:PA]-duplicate-| \/`) - raw := buildTCP(t, 5000, tcpFlags{psh: true, ack: true}, []byte("payload")) - res, err := e.Process(raw, strategy.DirectionOutbound) + raw := testutil.BuildTCP(t, 5000, testutil.TCPFlags{PSH: true, ACK: true}, []byte("payload")) + res, err := e.Process(raw, strategy.DirectionOutbound, nil) if err != nil { t.Fatal(err) } @@ -184,8 +151,8 @@ func TestDuplicated(t *testing.T) { func TestTampered_Flags(t *testing.T) { e := mustEngine(t, `[TCP:flags:S]-tamper{TCP:flags:replace:SA}-| \/`) - raw := buildTCP(t, 42, tcpFlags{syn: true}, nil) - res, err := e.Process(raw, strategy.DirectionOutbound) + raw := testutil.BuildTCP(t, 42, testutil.TCPFlags{SYN: true}, nil) + res, err := e.Process(raw, strategy.DirectionOutbound, nil) if err != nil { t.Fatal(err) } @@ -201,8 +168,8 @@ func TestTampered_Flags(t *testing.T) { func TestTampered_TTL(t *testing.T) { e := mustEngine(t, `[TCP:flags:PA]-tamper{IP:ttl:replace:5}-| \/`) - raw := buildTCP(t, 42, tcpFlags{psh: true, ack: true}, []byte("data")) - res, err := e.Process(raw, strategy.DirectionOutbound) + raw := testutil.BuildTCP(t, 42, testutil.TCPFlags{PSH: true, ACK: true}, []byte("data")) + res, err := e.Process(raw, strategy.DirectionOutbound, nil) if err != nil { t.Fatal(err) } @@ -216,8 +183,8 @@ func TestTampered_TTL(t *testing.T) { func TestFragmented(t *testing.T) { e := mustEngine(t, `[TCP:flags:PA]-fragment{TCP:8:true}-| \/`) payload := []byte("0123456789ABCDEF") // 16 bytes - raw := buildTCP(t, 7000, tcpFlags{psh: true, ack: true}, payload) - res, err := e.Process(raw, strategy.DirectionOutbound) + raw := testutil.BuildTCP(t, 7000, testutil.TCPFlags{PSH: true, ACK: true}, payload) + res, err := e.Process(raw, strategy.DirectionOutbound, nil) if err != nil { t.Fatal(err) } @@ -254,8 +221,8 @@ func TestInboundBranchingRejectedAtParse(t *testing.T) { func TestOverheadMetrics(t *testing.T) { e := mustEngine(t, `[TCP:flags:PA]-duplicate-| \/`) - raw := buildTCP(t, 1, tcpFlags{psh: true, ack: true}, []byte("abcdefgh")) - if _, err := e.Process(raw, strategy.DirectionOutbound); err != nil { + raw := testutil.BuildTCP(t, 1, testutil.TCPFlags{PSH: true, ACK: true}, []byte("abcdefgh")) + if _, err := e.Process(raw, strategy.DirectionOutbound, nil); err != nil { t.Fatal(err) } snap := e.Snapshot() diff --git a/internal/netdev/offload.go b/internal/netdev/offload.go index 2692369..ce5aaf0 100644 --- a/internal/netdev/offload.go +++ b/internal/netdev/offload.go @@ -24,7 +24,109 @@ import ( // keep packets MTU-sized; checksum/scatter-gather offloads keep checksums real. var offloadFeatures = []string{"gso", "tso", "gro", "gre", "tx", "rx", "sg", "lro", "ufo"} -// DisableOffload turns off segmentation and checksum offloads on iface. +// restoreOrder re-enables features in dependency order. Segmentation offloads +// require scatter-gather and tx checksumming, so restoring in the disable order +// makes the kernel reject `tso on` and `gso on` as unsupported and silently +// leaves them off. +var restoreOrder = []string{"sg", "tx", "rx", "gso", "tso", "gro", "gre", "lro", "ufo"} + +// ethtoolNames maps the short feature names used with `ethtool -K` to the long +// names `ethtool -k` reports state under. Only the features whose state we need +// to read are listed; anything absent is simply attempted blind. +var ethtoolNames = map[string]string{ + "gso": "generic-segmentation-offload", + "tso": "tcp-segmentation-offload", + "gro": "generic-receive-offload", + "lro": "large-receive-offload", + "sg": "scatter-gather", + "tx": "tx-checksumming", + "rx": "rx-checksumming", + "ufo": "udp-fragmentation-offload", +} + +// readFeatures returns which of the offload features are currently on, keyed by +// short name. A feature the driver reports as "[fixed]" is reported by its +// current value and cannot be changed either way, which is what Disable needs +// to know. Features it cannot determine are simply absent from the map. +func readFeatures(ctx context.Context, ethtoolPath, iface string) map[string]bool { + out, err := exec.CommandContext(ctx, ethtoolPath, "-k", iface).Output() + if err != nil { + return nil + } + long := make(map[string]bool, len(ethtoolNames)) + for line := range strings.SplitSeq(string(out), "\n") { + name, value, found := strings.Cut(strings.TrimSpace(line), ":") + if !found { + continue + } + value = strings.TrimSpace(value) + on := strings.HasPrefix(value, "on") + fixed := strings.Contains(value, "[fixed]") + // A fixed feature is unchangeable: record its value so Disable skips it + // when it is already off and Restore never tries to set it. + if fixed && !on { + long[name] = false + continue + } + long[name] = on + } + state := make(map[string]bool, len(ethtoolNames)) + for short, name := range ethtoolNames { + if v, ok := long[name]; ok { + state[short] = v + } + } + return state +} + +// Disabled records the features Disable actually turned off on an interface, so +// Restore can put back exactly those and nothing else. +type Disabled struct { + ethtoolPath string + iface string + features []string + skipped []string +} + +// Summary describes what changed, for logging. +func (d *Disabled) Summary() string { + if d == nil { + return "unchanged=[all]" + } + return fmt.Sprintf("disabled=[%s] unchanged=[%s]", + strings.Join(d.features, " "), strings.Join(d.skipped, " ")) +} + +// Restore re-enables the features Disable turned off. Failures are collected +// rather than returned on the first one: a partial restore is better than +// stopping halfway, and the caller logs rather than aborts — the sidecar is on +// its way out by the time this runs. +func (d *Disabled) Restore(ctx context.Context) error { + if d == nil || len(d.features) == 0 { + return nil + } + want := make(map[string]bool, len(d.features)) + for _, f := range d.features { + want[f] = true + } + var failed []string + for _, f := range restoreOrder { + if !want[f] { + continue + } + if err := exec.CommandContext(ctx, d.ethtoolPath, "-K", d.iface, f, "on").Run(); err != nil { + failed = append(failed, f) + } + } + d.features = nil + if len(failed) > 0 { + return fmt.Errorf("could not re-enable offloads on %s: %s", d.iface, strings.Join(failed, " ")) + } + return nil +} + +// Disable turns off segmentation and checksum offloads on iface and returns +// what it changed. // // Individual features that cannot be changed are reported in the returned // summary rather than as an error: some virtual interfaces expose a subset as @@ -33,24 +135,33 @@ var offloadFeatures = []string{"gso", "tso", "gro", "gre", "tx", "rx", "sg", "lr // interface, and no feature changeable at all — because each of them means // NFQUEUE would go on receiving GSO/checksum-offloaded packets that cannot be // reinjected intact. -func DisableOffload(ctx context.Context, ethtoolPath, iface string) (string, error) { +func Disable(ctx context.Context, ethtoolPath, iface string) (*Disabled, error) { if ethtoolPath == "" { ethtoolPath = "ethtool" } if _, err := exec.LookPath(ethtoolPath); err != nil { - return "", fmt.Errorf("ethtool not found (needed to disable NIC offloads on %s): %w", iface, err) + return nil, fmt.Errorf("ethtool not found (needed to disable NIC offloads on %s): %w", iface, err) } // A missing interface is a hard error, not a "feature unchanged": otherwise a // typo in --iface would silently leave every offload on. if _, err := os.Stat("/sys/class/net/" + iface); err != nil { - return "", fmt.Errorf("interface %q not found: %w", iface, err) + return nil, fmt.Errorf("interface %q not found: %w", iface, err) } + + // Read the current state first. A feature that is already off, or that the + // driver reports as fixed, must not be recorded as something we turned off: + // Restore would then try to switch it back on and fail. veth reports lro + // exactly that way. + state := readFeatures(ctx, ethtoolPath, iface) + var ok, skipped []string for _, f := range offloadFeatures { - cmd := exec.CommandContext(ctx, ethtoolPath, "-K", iface, f, "off") - if out, err := cmd.CombinedOutput(); err != nil { + if on, known := state[f]; known && !on { + skipped = append(skipped, f) + continue + } + if err := exec.CommandContext(ctx, ethtoolPath, "-K", iface, f, "off").Run(); err != nil { // Feature fixed/unsupported on this interface; not fatal on its own. - _ = out skipped = append(skipped, f) continue } @@ -60,8 +171,8 @@ func DisableOffload(ctx context.Context, ethtoolPath, iface string) (string, err // context cancellation, an interface that rejects every request) — surface it // rather than letting NFQUEUE receive GSO/checksum-offloaded packets. if len(ok) == 0 { - return "", fmt.Errorf("failed to disable any offload on %q (check CAP_NET_ADMIN); attempted: %s", + return nil, fmt.Errorf("failed to disable any offload on %q (check CAP_NET_ADMIN); attempted: %s", iface, strings.Join(offloadFeatures, " ")) } - return fmt.Sprintf("disabled=[%s] unchanged=[%s]", strings.Join(ok, " "), strings.Join(skipped, " ")), nil + return &Disabled{ethtoolPath: ethtoolPath, iface: iface, features: ok, skipped: skipped}, nil } diff --git a/internal/nfqueue/queue_linux.go b/internal/nfqueue/queue_linux.go new file mode 100644 index 0000000..38bfbd6 --- /dev/null +++ b/internal/nfqueue/queue_linux.go @@ -0,0 +1,457 @@ +//go:build linux + +package nfqueue + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "syscall" + "time" + + "github.com/mdlayher/netlink" + "golang.org/x/sys/unix" +) + +// This file is the sidecar's netlink hot path. +// +// It exists because the generic Go netlink stack is far too expensive per +// packet. A CPU profile of a tamper-every-packet strategy put 41% of the +// sidecar's time in syscalls and ~30% in the garbage collector and the +// scheduler feeding it, against under 10% in the Geneva engine. The cause was +// not the engine or even NFQUEUE: mdlayher/netlink's Receive allocates a fresh +// page-sized buffer per call, does a MSG_PEEK recvmsg to size the message, then +// a second recvmsg to read it, then allocates again to parse it. That is two +// syscalls and several allocations for every packet, before any work happens. +// +// So the setup — dial, bind, copy mode, queue length — still goes through +// mdlayher/netlink, where it is readable and runs once. The per-packet path +// takes the raw fd and does the minimum: +// +// - One recvmsg into a reusable buffer, which returns however many packets +// the kernel has queued rather than exactly one. +// - Parsing in place. A packet's payload is a subslice of the read buffer, +// valid until the next read, which is precisely the window in which the +// verdict is issued. +// - Accept verdicts batched to one syscall per read. NFQNL_MSG_VERDICT_BATCH +// verdicts every packet id up to the one given, and ids increase +// monotonically, so a run of accepts collapses into a single message. The +// batch is flushed before any individual verdict for a later id, or a +// batch would swallow a packet meant to be dropped or rewritten. +// - Verdict messages marshalled into a reusable buffer. +// +// The result is one syscall per read plus one per manipulated packet, instead +// of three or more per packet, and no per-packet allocation at all. + +// Netlink and nfnetlink constants. The generic framing values are aliased from +// x/sys/unix, which is the authoritative source; the NFQNL_* message, attribute +// and verdict values are spelled out because x/sys does not export them. +const ( + nfnlSubsysQueue = unix.NFNL_SUBSYS_QUEUE + + nfqnlMsgPacket = 0 + nfqnlMsgVerdict = 1 + nfqnlMsgConfig = 2 + nfqnlMsgVerdictBatch = 3 + + // Packet attributes. + nfqaPacketHdr = 1 + nfqaVerdictHdr = 2 + nfqaPayload = 10 + nfqaCapLen = 13 + + // Config attributes and commands. + nfqaCfgCmd = 1 + nfqaCfgParams = 2 + nfqaCfgQueueMaxLen = 3 + nfqaCfgMask = 4 + nfqaCfgFlags = 5 + + nfqnlCfgCmdBind = 1 + nfqnlCfgCmdUnbind = 2 + nfqnlCfgCmdPfBind = 3 + nfqnlCfgCmdPfUnbind = 4 + + // Copy modes. + nfqnlCopyPacket = 2 + + // Verdicts, from netfilter.h. + nfDrop = 0 + nfAccept = 1 + + nlmsgHdrLen = unix.NLMSG_HDRLEN + nfgenmsgLen = 4 + nlaHdrLen = unix.NLA_HDRLEN + nlmsgAlignTo = unix.NLMSG_ALIGNTO + + // readBufSize holds many MTU-sized packets, or one 64 KB packet from an + // interface whose offloads are still on, in a single read. + readBufSize = 256 << 10 + + // maxQueueLen is how many packets the kernel will hold for this queue + // before dropping (and, with the bypass flag on the rules, accepting) them. + maxQueueLen = 0xffff + + // rcvBufSize is the socket buffer. NFQUEUE reports ENOBUFS and drops + // packets when this fills, and a burst plus a slow strategy is exactly how + // that happens. + rcvBufSize = 4 << 20 +) + +// ErrTruncated reports a packet the kernel copied only part of. It is a +// configuration error (copy length too small), and the only safe response is to +// accept the packet unmodified rather than reinject a fragment of it. +var ErrTruncated = errors.New("kernel truncated the captured packet") + +// queue is one bound NFQUEUE and its verdict channel. +type queue struct { + con *netlink.Conn + rc syscall.RawConn + num uint16 + family uint8 + + rbuf []byte + vbuf []byte + + // pendingAccept is the highest packet id accepted but not yet verdicted, + // held back so a run of accepts can go out as one batch message. + pendingAccept uint32 + hasPending bool + + // send writes a marshalled netlink message. A field rather than a method so + // the batching and marshalling can be tested without a kernel. + send func([]byte) error +} + +// openQueue dials netlink, binds queue num, and configures copy mode. +func openQueue(num uint16, maxPacketLen uint32, maxQueueLen uint32) (*queue, error) { + con, err := netlink.Dial(unix.NETLINK_NETFILTER, nil) + if err != nil { + return nil, fmt.Errorf("dial netlink: %w", err) + } + q := &queue{ + con: con, + num: num, + // AF_INET, matching an engine and reinjector that are IPv4-only. The + // kernel does not read this field for the messages it is sent with here + // — the queue bind and the verdicts — which is why v0.0.1 worked with it + // left at zero. Set explicitly all the same: an implicit AF_UNSPEC in an + // IPv4-only sidecar reads as an oversight rather than a decision. + family: unix.AF_INET, + rbuf: make([]byte, readBufSize), + vbuf: make([]byte, 0, 4096), + } + if err := con.SetReadBuffer(rcvBufSize); err != nil { + // Not fatal: a smaller buffer means ENOBUFS under burst, which is + // counted and logged, not a failure to run. + _ = err + } + rc, err := con.SyscallConn() + if err != nil { + _ = con.Close() + return nil, fmt.Errorf("raw netlink conn: %w", err) + } + q.rc = rc + q.send = q.writeRaw + + // The same sequence libnetfilter_queue performs: drop any stale handler for + // the family, bind the family, bind the queue, then set copy mode and depth. + steps := []struct { + what string + resid uint16 + attrs []netlink.Attribute + }{ + {"unbind family", 0, []netlink.Attribute{{Type: nfqaCfgCmd, Data: cfgCmd(nfqnlCfgCmdPfUnbind, q.family)}}}, + {"bind family", 0, []netlink.Attribute{{Type: nfqaCfgCmd, Data: cfgCmd(nfqnlCfgCmdPfBind, q.family)}}}, + {"bind queue", num, []netlink.Attribute{{Type: nfqaCfgCmd, Data: cfgCmd(nfqnlCfgCmdBind, q.family)}}}, + {"set copy mode", num, []netlink.Attribute{{Type: nfqaCfgParams, Data: cfgParams(maxPacketLen)}}}, + {"set queue length", num, []netlink.Attribute{{Type: nfqaCfgQueueMaxLen, Data: be32(maxQueueLen)}}}, + } + for _, s := range steps { + if err := q.config(s.resid, s.attrs); err != nil { + _ = con.Close() + return nil, fmt.Errorf("%s: %w", s.what, err) + } + } + return q, nil +} + +// config sends one NFQNL_MSG_CONFIG message. Setup only — this is the path that +// may allocate freely. +func (q *queue) config(resid uint16, attrs []netlink.Attribute) error { + data, err := netlink.MarshalAttributes(attrs) + if err != nil { + return err + } + body := make([]byte, 0, nfgenmsgLen+len(data)) + body = append(body, q.family, unix.NFNETLINK_V0, 0, 0) + binary.BigEndian.PutUint16(body[2:4], resid) + body = append(body, data...) + + _, err = q.con.Send(netlink.Message{ + Header: netlink.Header{ + Type: netlink.HeaderType((nfnlSubsysQueue << 8) | nfqnlMsgConfig), + Flags: netlink.Request | netlink.Acknowledge, + }, + Data: body, + }) + if err != nil { + return err + } + // Read the ack so a failure surfaces here rather than as a mystery later. + if _, err := q.con.Receive(); err != nil { + return err + } + return nil +} + +// Close releases the queue. It does not send an explicit unbind: the kernel +// drops the binding when the socket closes, and an unbind here would have to +// read its own ack off a socket a reader may still be draining — which +// deadlocked shutdown until the container was killed. +func (q *queue) Close() error { + return q.con.Close() +} + +// interrupt unblocks a reader parked in recvmsg by putting the read deadline in +// the past. Cancelling the context alone does not do it: the read is waiting on +// socket readiness inside the runtime poller, not on the context. +func (q *queue) interrupt() { + _ = q.con.SetReadDeadline(time.Now().Add(-time.Second)) +} + +// packet is one queued packet: its id and its bytes. The payload aliases the +// queue's read buffer and is only valid until the next read. +type packet struct { + id uint32 + payload []byte + // truncated is set when the kernel copied less than the packet's real + // length, which makes the payload unsafe to manipulate or reinject. + truncated bool +} + +// read performs one recvmsg and calls fn for every packet it returned, in +// order. Any accept verdicts fn defers are flushed before read returns, so no +// packet is ever left waiting on the next read. +func (q *queue) read(ctx context.Context, fn func(packet) error) error { + n, err := q.recvmsg() + if err != nil { + return err + } + if err := forEachPacket(ctx, q.rbuf[:n], fn); err != nil { + return err + } + return q.flush() +} + +// forEachPacket walks the netlink messages in one read and calls fn for each +// NFQNL_MSG_PACKET among them, in order. +// +// Neither messages nor attributes are padded at the end of a buffer, so every +// step is clamped to what is left: stepping by the aligned length walks off the +// end of the last one, which is exactly how this crashed the first time it met +// a real kernel. +func forEachPacket(ctx context.Context, b []byte, fn func(packet) error) error { + for len(b) >= nlmsgHdrLen { + msgLen := int(binary.LittleEndian.Uint32(b[0:4])) + msgType := binary.LittleEndian.Uint16(b[4:6]) + if msgLen < nlmsgHdrLen || msgLen > len(b) { + return fmt.Errorf("malformed netlink message: len %d in %d bytes", msgLen, len(b)) + } + if msgType == uint16((nfnlSubsysQueue<<8)|nfqnlMsgPacket) { + p, err := parsePacket(b[nlmsgHdrLen:msgLen]) + if err != nil { + return err + } + if err := fn(p); err != nil { + return err + } + } + b = b[min(nlmsgAlign(msgLen), len(b)):] + if ctx.Err() != nil { + return nil + } + } + return nil +} + +// recvmsg reads once into the reusable buffer, waiting for readiness through +// the runtime poller rather than blocking a thread. +func (q *queue) recvmsg() (int, error) { + var n int + var rerr error + err := q.rc.Read(func(fd uintptr) bool { + var flags int + n, _, flags, _, rerr = unix.Recvmsg(int(fd), q.rbuf, nil, 0) + if rerr == unix.EAGAIN || rerr == unix.EWOULDBLOCK { + return false // not ready; wait and try again + } + if rerr == nil && flags&unix.MSG_TRUNC != 0 { + rerr = fmt.Errorf("netlink message longer than the %d-byte read buffer", len(q.rbuf)) + } + return true + }) + if err != nil { + return 0, err + } + if rerr != nil { + return 0, rerr + } + return n, nil +} + +// parsePacket extracts the id and payload from one NFQNL_MSG_PACKET body. +func parsePacket(body []byte) (packet, error) { + if len(body) < nfgenmsgLen { + return packet{}, errors.New("nfnetlink message shorter than its header") + } + var p packet + var capLen uint32 + attrs := body[nfgenmsgLen:] + for len(attrs) >= nlaHdrLen { + alen := int(binary.LittleEndian.Uint16(attrs[0:2])) + atype := binary.LittleEndian.Uint16(attrs[2:4]) & 0x3fff // strip nested/byte-order bits + if alen < nlaHdrLen || alen > len(attrs) { + return packet{}, fmt.Errorf("malformed netlink attribute: len %d in %d bytes", alen, len(attrs)) + } + data := attrs[nlaHdrLen:alen] + switch atype { + case nfqaPacketHdr: + if len(data) < 4 { + return packet{}, errors.New("short nfqnl_msg_packet_hdr") + } + p.id = binary.BigEndian.Uint32(data[0:4]) + case nfqaPayload: + p.payload = data + case nfqaCapLen: + if len(data) >= 4 { + capLen = binary.BigEndian.Uint32(data[0:4]) + } + } + // The kernel does not pad the last attribute in a message, so the + // aligned step can point past the end: advance to exactly the end + // rather than overrunning it. + step := min(nlmsgAlign(alen), len(attrs)) + attrs = attrs[step:] + } + // NFQA_CAP_LEN is only present when the kernel copied less than the whole + // packet, which is the copy-length case: the bytes we hold are a prefix, so + // any manipulation of them would put a corrupt packet on the wire. + if capLen != 0 && int(capLen) > len(p.payload) { + p.truncated = true + } + return p, nil +} + +// accept defers an accept verdict into the current batch. +func (q *queue) accept(id uint32) { + // Ids increase monotonically, so keeping the highest is enough: the batch + // verdict covers every id below it. + if !q.hasPending || id > q.pendingAccept { + q.pendingAccept = id + } + q.hasPending = true +} + +// flush emits the pending batch accept, if any. +func (q *queue) flush() error { + if !q.hasPending { + return nil + } + id := q.pendingAccept + q.hasPending = false + return q.sendVerdict(nfqnlMsgVerdictBatch, id, nfAccept, nil) +} + +// verdict issues an immediate verdict for one packet, flushing any deferred +// accepts first. Without that flush a batch message would verdict this packet's +// id as well, overriding the decision being made here. +func (q *queue) verdict(id uint32, v int, replacement []byte) error { + if q.hasPending && q.pendingAccept < id { + if err := q.flush(); err != nil { + return err + } + } + q.hasPending = false + return q.sendVerdict(nfqnlMsgVerdict, id, v, replacement) +} + +// sendVerdict marshals into the reusable verdict buffer and writes it. +func (q *queue) sendVerdict(msgType int, id uint32, v int, replacement []byte) error { + return q.send(q.marshalVerdict(msgType, id, v, replacement)) +} + +// marshalVerdict builds a verdict message in the reusable buffer. +func (q *queue) marshalVerdict(msgType int, id uint32, v int, replacement []byte) []byte { + total := nlmsgHdrLen + nfgenmsgLen + nlaHdrLen + 8 + if replacement != nil { + total += nlaHdrLen + nlmsgAlign(len(replacement)) + } + if cap(q.vbuf) < total { + q.vbuf = make([]byte, 0, total*2) + } + b := q.vbuf[:total] + // Every other byte of the message is written below, so only the fields that + // must be zero are cleared: sequence and port id, plus the alignment tail + // after a replacement payload. Clearing the whole buffer would double the + // memory traffic of the marshal for a full-size replaced packet. + clear(b[8:16]) + + binary.LittleEndian.PutUint32(b[0:4], uint32(total)) + binary.LittleEndian.PutUint16(b[4:6], uint16((nfnlSubsysQueue<<8)|msgType)) + binary.LittleEndian.PutUint16(b[6:8], uint16(netlink.Request)) + // Sequence and port id stay zero: the kernel does not correlate verdicts, + // and nothing reads an ack for them. + + off := nlmsgHdrLen + b[off] = q.family + b[off+1] = unix.NFNETLINK_V0 + binary.BigEndian.PutUint16(b[off+2:off+4], q.num) + off += nfgenmsgLen + + // struct nfqnl_msg_verdict_hdr { __be32 verdict; __be32 id; } + binary.LittleEndian.PutUint16(b[off:off+2], uint16(nlaHdrLen+8)) + binary.LittleEndian.PutUint16(b[off+2:off+4], nfqaVerdictHdr) + binary.BigEndian.PutUint32(b[off+4:off+8], uint32(v)) + binary.BigEndian.PutUint32(b[off+8:off+12], id) + off += nlaHdrLen + 8 + + if replacement != nil { + binary.LittleEndian.PutUint16(b[off:off+2], uint16(nlaHdrLen+len(replacement))) + binary.LittleEndian.PutUint16(b[off+2:off+4], nfqaPayload) + copy(b[off+nlaHdrLen:], replacement) + clear(b[off+nlaHdrLen+len(replacement):]) + } + return b +} + +// writeRaw sends one marshalled message, waiting for writability through the +// runtime poller rather than blocking a thread. +func (q *queue) writeRaw(b []byte) error { + var werr error + err := q.rc.Write(func(fd uintptr) bool { + werr = unix.Sendmsg(int(fd), b, nil, &unix.SockaddrNetlink{Family: unix.AF_NETLINK}, 0) + if werr == unix.EAGAIN || werr == unix.EWOULDBLOCK { + return false + } + return true + }) + if err != nil { + return err + } + return werr +} + +func nlmsgAlign(n int) int { return (n + nlmsgAlignTo - 1) & ^(nlmsgAlignTo - 1) } + +func cfgCmd(cmd, family uint8) []byte { return []byte{cmd, 0, 0, family} } + +func cfgParams(maxPacketLen uint32) []byte { + b := make([]byte, 5) + binary.BigEndian.PutUint32(b[0:4], maxPacketLen) + b[4] = nfqnlCopyPacket + return b +} + +func be32(v uint32) []byte { return binary.BigEndian.AppendUint32(nil, v) } diff --git a/internal/nfqueue/queue_linux_test.go b/internal/nfqueue/queue_linux_test.go new file mode 100644 index 0000000..dfa36ed --- /dev/null +++ b/internal/nfqueue/queue_linux_test.go @@ -0,0 +1,342 @@ +//go:build linux + +package nfqueue + +import ( + "context" + "encoding/binary" + "testing" + + "github.com/mdlayher/netlink" + "golang.org/x/sys/unix" +) + +// buildPacketBody assembles an NFQNL_MSG_PACKET body the way the kernel does, +// so the parser is tested against the wire format rather than against itself. +func buildPacketBody(id uint32, payload []byte, capLen uint32) []byte { + b := []byte{unix.AF_INET, unix.NFNETLINK_V0, 0, 0} // nfgenmsg; res_id big-endian + + // struct nfqnl_msg_packet_hdr { __be32 packet_id; __be16 hw_protocol; __u8 hook; } + hdr := make([]byte, 8) + binary.BigEndian.PutUint32(hdr[0:4], id) + b = append(b, attr(nfqaPacketHdr, hdr)...) + + if capLen != 0 { + cl := make([]byte, 4) + binary.BigEndian.PutUint32(cl, capLen) + b = append(b, attr(nfqaCapLen, cl)...) + } + // Payload last, as the kernel sends it. + b = append(b, attr(nfqaPayload, payload)...) + return b +} + +func attr(typ uint16, data []byte) []byte { + out := make([]byte, nlmsgAlign(nlaHdrLen+len(data))) + binary.LittleEndian.PutUint16(out[0:2], uint16(nlaHdrLen+len(data))) + binary.LittleEndian.PutUint16(out[2:4], typ) + copy(out[nlaHdrLen:], data) + return out +} + +func TestParsePacket(t *testing.T) { + payload := []byte{0x45, 0x00, 0x00, 0x28, 0xde, 0xad, 0xbe, 0xef} + + t.Run("id and payload", func(t *testing.T) { + p, err := parsePacket(buildPacketBody(0x01020304, payload, 0)) + if err != nil { + t.Fatalf("parsePacket: %v", err) + } + if p.id != 0x01020304 { + t.Errorf("id = %#x, want %#x", p.id, 0x01020304) + } + if string(p.payload) != string(payload) { + t.Errorf("payload = % x, want % x", p.payload, payload) + } + if p.truncated { + t.Error("packet reported truncated with no NFQA_CAP_LEN") + } + }) + + t.Run("payload aliases the buffer", func(t *testing.T) { + // The whole point of the fast path: no copy per packet. If this ever + // starts copying, the allocation cost comes back. + body := buildPacketBody(1, payload, 0) + p, err := parsePacket(body) + if err != nil { + t.Fatalf("parsePacket: %v", err) + } + body[len(body)-1] = 0x99 + if p.payload[len(p.payload)-1] != 0x99 { + t.Error("payload was copied out of the read buffer") + } + }) + + t.Run("truncated capture is flagged", func(t *testing.T) { + // The kernel copied 8 bytes of a 1500-byte packet: manipulating that + // prefix would put a corrupt packet on the wire. + p, err := parsePacket(buildPacketBody(7, payload, 1500)) + if err != nil { + t.Fatalf("parsePacket: %v", err) + } + if !p.truncated { + t.Error("short capture not flagged as truncated") + } + }) + + t.Run("full-length capture is not flagged", func(t *testing.T) { + p, err := parsePacket(buildPacketBody(7, payload, uint32(len(payload)))) + if err != nil { + t.Fatalf("parsePacket: %v", err) + } + if p.truncated { + t.Error("full capture flagged as truncated") + } + }) + + t.Run("unpadded final attribute", func(t *testing.T) { + // The kernel pads attributes to 4 bytes except the last one in a + // message, where the padding is simply absent. Stepping over it by the + // aligned length walks off the end of the buffer — which is exactly + // what crashed the first version of this parser against a real kernel. + odd := []byte{0x45, 0x00, 0x00, 0x25, 0x01} // 5 bytes: attr len 9, aligned 12 + body := buildPacketBody(3, odd, 0) + body = body[:len(body)-3] // drop the trailing pad the helper added + p, err := parsePacket(body) + if err != nil { + t.Fatalf("parsePacket: %v", err) + } + if string(p.payload) != string(odd) { + t.Errorf("payload = % x, want % x", p.payload, odd) + } + }) + + t.Run("malformed attribute rejected", func(t *testing.T) { + body := buildPacketBody(1, payload, 0) + // Claim an attribute longer than the buffer. + binary.LittleEndian.PutUint16(body[4:6], 0xffff) + if _, err := parsePacket(body); err == nil { + t.Error("oversized attribute accepted") + } + }) + + t.Run("short message rejected", func(t *testing.T) { + if _, err := parsePacket([]byte{0x02}); err == nil { + t.Error("truncated nfgenmsg accepted") + } + }) +} + +// wrapMsg puts a body in a netlink message header of the given type. +func wrapMsg(msgType uint16, body []byte) []byte { + b := make([]byte, nlmsgHdrLen+len(body)) + binary.LittleEndian.PutUint32(b[0:4], uint32(len(b))) + binary.LittleEndian.PutUint16(b[4:6], msgType) + copy(b[nlmsgHdrLen:], body) + return b +} + +func TestForEachPacket(t *testing.T) { + ctx := context.Background() + packetType := uint16((nfnlSubsysQueue << 8) | nfqnlMsgPacket) + + t.Run("several packets in one read", func(t *testing.T) { + // The point of the fast path: one syscall can return many packets. + var buf []byte + for _, id := range []uint32{10, 11, 12} { + msg := wrapMsg(packetType, buildPacketBody(id, []byte{0x45, 0, 0, 0x28}, 0)) + buf = append(buf, msg...) + buf = append(buf, make([]byte, nlmsgAlign(len(msg))-len(msg))...) + } + var ids []uint32 + if err := forEachPacket(ctx, buf, func(p packet) error { + ids = append(ids, p.id) + return nil + }); err != nil { + t.Fatalf("forEachPacket: %v", err) + } + if len(ids) != 3 || ids[0] != 10 || ids[1] != 11 || ids[2] != 12 { + t.Errorf("ids = %v, want [10 11 12]", ids) + } + }) + + t.Run("unpadded final message", func(t *testing.T) { + // A message whose length is not a multiple of 4 and which sits at the + // end of the buffer: the aligned step would run past it. + body := buildPacketBody(1, []byte{0x45, 0x00, 0x00, 0x25, 0x01}, 0) + body = body[:len(body)-3] + var seen int + if err := forEachPacket(ctx, wrapMsg(packetType, body), func(packet) error { + seen++ + return nil + }); err != nil { + t.Fatalf("forEachPacket: %v", err) + } + if seen != 1 { + t.Errorf("saw %d packets, want 1", seen) + } + }) + + t.Run("non-packet messages are skipped", func(t *testing.T) { + buf := wrapMsg(uint16(netlink.Error), []byte{0, 0, 0, 0}) + if err := forEachPacket(ctx, buf, func(packet) error { + t.Error("callback ran for a non-packet message") + return nil + }); err != nil { + t.Fatalf("forEachPacket: %v", err) + } + }) + + t.Run("lying message length rejected", func(t *testing.T) { + buf := wrapMsg(packetType, buildPacketBody(1, []byte{0x45}, 0)) + binary.LittleEndian.PutUint32(buf[0:4], uint32(len(buf)+64)) + if err := forEachPacket(ctx, buf, func(packet) error { return nil }); err == nil { + t.Error("message longer than the buffer accepted") + } + }) +} + +func TestMarshalVerdict(t *testing.T) { + q := &queue{num: 100, family: unix.AF_INET} + + t.Run("plain verdict", func(t *testing.T) { + b := q.marshalVerdict(nfqnlMsgVerdict, 0x11223344, nfAccept, nil) + if got := int(binary.LittleEndian.Uint32(b[0:4])); got != len(b) { + t.Errorf("nlmsg_len = %d, want %d", got, len(b)) + } + if got, want := binary.LittleEndian.Uint16(b[4:6]), uint16((nfnlSubsysQueue<<8)|nfqnlMsgVerdict); got != want { + t.Errorf("nlmsg_type = %#x, want %#x", got, want) + } + if got, want := binary.LittleEndian.Uint16(b[6:8]), uint16(netlink.Request); got != want { + t.Errorf("nlmsg_flags = %#x, want %#x", got, want) + } + // nfgenmsg: res_id carries the queue number, big-endian. + if got := binary.BigEndian.Uint16(b[nlmsgHdrLen+2 : nlmsgHdrLen+4]); got != 100 { + t.Errorf("res_id = %d, want 100", got) + } + off := nlmsgHdrLen + nfgenmsgLen + if got, want := binary.LittleEndian.Uint16(b[off+2:off+4]), uint16(nfqaVerdictHdr); got != want { + t.Errorf("attr type = %d, want %d", got, want) + } + if got := binary.BigEndian.Uint32(b[off+4 : off+8]); got != nfAccept { + t.Errorf("verdict = %d, want %d", got, nfAccept) + } + if got := binary.BigEndian.Uint32(b[off+8 : off+12]); got != 0x11223344 { + t.Errorf("id = %#x, want %#x", got, 0x11223344) + } + }) + + t.Run("verdict with replacement packet", func(t *testing.T) { + replacement := []byte{1, 2, 3, 4, 5} + b := q.marshalVerdict(nfqnlMsgVerdict, 9, nfAccept, replacement) + off := nlmsgHdrLen + nfgenmsgLen + nlaHdrLen + 8 + if got, want := binary.LittleEndian.Uint16(b[off+2:off+4]), uint16(nfqaPayload); got != want { + t.Errorf("payload attr type = %d, want %d", got, want) + } + if got, want := int(binary.LittleEndian.Uint16(b[off:off+2])), nlaHdrLen+len(replacement); got != want { + t.Errorf("payload attr len = %d, want %d", got, want) + } + if got := string(b[off+nlaHdrLen : off+nlaHdrLen+len(replacement)]); got != string(replacement) { + t.Errorf("payload = % x, want % x", got, replacement) + } + }) + + t.Run("buffer is reused across calls", func(t *testing.T) { + q := &queue{num: 1} + first := q.marshalVerdict(nfqnlMsgVerdict, 1, nfAccept, nil) + second := q.marshalVerdict(nfqnlMsgVerdict, 2, nfAccept, nil) + if &first[0] != &second[0] { + t.Error("verdict buffer reallocated between calls") + } + // Stale bytes from a longer previous message must not survive. + long := q.marshalVerdict(nfqnlMsgVerdict, 3, nfAccept, []byte{9, 9, 9, 9}) + short := q.marshalVerdict(nfqnlMsgVerdict, 4, nfAccept, nil) + if len(short) >= len(long) { + t.Fatalf("expected the short message to be shorter: %d vs %d", len(short), len(long)) + } + if got := int(binary.LittleEndian.Uint32(short[0:4])); got != len(short) { + t.Errorf("nlmsg_len = %d, want %d after reuse", got, len(short)) + } + }) +} + +// TestVerdictBatching is the correctness half of the syscall optimization: a +// batch verdict applies to every packet id up to the one it names, so a +// deferred run of accepts must be flushed before an individual verdict for a +// later packet — otherwise the batch would accept a packet that was meant to be +// dropped or rewritten. +func TestVerdictBatching(t *testing.T) { + type msg struct { + typ int + id uint32 + v int + } + var sent []msg + newQueue := func() *queue { + q := &queue{num: 100} + q.send = func(b []byte) error { + off := nlmsgHdrLen + nfgenmsgLen + sent = append(sent, msg{ + typ: int(binary.LittleEndian.Uint16(b[4:6]) & 0xff), + v: int(binary.BigEndian.Uint32(b[off+4 : off+8])), + id: binary.BigEndian.Uint32(b[off+8 : off+12]), + }) + return nil + } + return q + } + + t.Run("a run of accepts becomes one batch message", func(t *testing.T) { + sent = nil + q := newQueue() + q.accept(1) + q.accept(2) + q.accept(3) + if len(sent) != 0 { + t.Fatalf("accepts sent eagerly: %+v", sent) + } + if err := q.flush(); err != nil { + t.Fatalf("flush: %v", err) + } + if len(sent) != 1 { + t.Fatalf("got %d messages, want 1: %+v", len(sent), sent) + } + if sent[0].typ != nfqnlMsgVerdictBatch || sent[0].id != 3 || sent[0].v != nfAccept { + t.Errorf("got %+v, want batch accept of id 3", sent[0]) + } + }) + + t.Run("pending accepts flush before a later drop", func(t *testing.T) { + sent = nil + q := newQueue() + q.accept(1) + q.accept(2) + if err := q.verdict(3, nfDrop, nil); err != nil { + t.Fatalf("verdict: %v", err) + } + if len(sent) != 2 { + t.Fatalf("got %d messages, want 2: %+v", len(sent), sent) + } + if sent[0].typ != nfqnlMsgVerdictBatch || sent[0].id != 2 { + t.Errorf("first message = %+v, want batch accept of id 2", sent[0]) + } + if sent[1].typ != nfqnlMsgVerdict || sent[1].id != 3 || sent[1].v != nfDrop { + t.Errorf("second message = %+v, want drop of id 3", sent[1]) + } + }) + + t.Run("nothing is sent twice", func(t *testing.T) { + sent = nil + q := newQueue() + q.accept(5) + if err := q.verdict(6, nfAccept, []byte{1, 2, 3}); err != nil { + t.Fatalf("verdict: %v", err) + } + if err := q.flush(); err != nil { + t.Fatalf("flush: %v", err) + } + if len(sent) != 2 { + t.Errorf("got %d messages, want 2 (batch for 5, mod-accept for 6): %+v", len(sent), sent) + } + }) +} diff --git a/internal/nfqueue/runtime.go b/internal/nfqueue/runtime.go index 5c887c3..f9b5799 100644 --- a/internal/nfqueue/runtime.go +++ b/internal/nfqueue/runtime.go @@ -9,11 +9,24 @@ // nftables rules send egress to the out-queue and ingress to the in-queue, so // each callback knows its direction unambiguously. // -// Outbound packets can fan out (duplicate/fragment) or change size (tamper), so -// a matched outbound packet is dropped in the queue and its replacements are -// reinjected through the raw socket. Inbound is single-in/single-out (branching -// is rejected at parse time), so it is handled entirely with the in-queue -// verdict: accept, drop, or overwrite-and-accept. +// Verdicts are issued in the queue wherever the queue can express them, because +// syscalls are what this package costs. A CPU profile of a tamper-every-packet +// strategy put 41% of the sidecar's time in syscalls and under 10% in the Geneva +// engine, so the useful optimizations are all about doing fewer of them: +// +// - Unchanged: a bare accept. +// - One packet out (tamper, the common manipulation): overwrite-and-accept in +// the queue. No raw socket, and — because the packet resumes where it was +// queued instead of being injected at the top of the stack — no second trip +// through netfilter and no routing lookup. +// - More than one packet out (duplicate/fragment): all but the last are +// injected through the raw socket, and the last replaces the queued packet. +// Injecting the earlier ones first preserves the order the strategy chose, +// since the overwritten packet is only released once this callback returns. +// - Dropped: a bare drop. +// +// Inbound is single-in/single-out (branching is rejected at parse time), so it +// never needs the raw socket at all. package nfqueue import ( @@ -21,11 +34,13 @@ import ( "errors" "fmt" "os" + "sync" "sync/atomic" - nfq "github.com/florianl/go-nfqueue/v2" - "github.com/getlantern/geneva-server/internal/engine" "github.com/getlantern/geneva/strategy" + "golang.org/x/sys/unix" + + "github.com/getlantern/geneva-server/internal/engine" ) // Observer is notified of every packet before manipulation, for eval-mode canary @@ -58,12 +73,37 @@ type Config struct { } // Stats counts verdicts and reinjection outcomes. +// +// The counters are per mechanism, not per intent, and a manipulated packet +// therefore lands in different ones depending on how it reached the wire: +// +// - Modified: replaced in the queue by an overwrite-and-accept verdict. This +// is the normal path for a strategy that produces one packet. +// - Reinjected + Dropped: put on the wire through the raw socket while the +// queued original was dropped. This is the normal path for the extra packets +// of a fan-out strategy, and the fallback path when an overwrite verdict is +// refused. +// +// So "how many packets did the strategy change" is Modified plus the fan-out +// share of Reinjected, and neither counter alone answers it. They are kept +// per-mechanism deliberately: a packet counted in both would make Accepted + +// Dropped + Modified stop reconciling with PacketsIn, which is what makes a +// bypassed or lost packet visible. type Stats struct { Accepted atomic.Uint64 Dropped atomic.Uint64 Modified atomic.Uint64 Reinjected atomic.Uint64 InjectFails atomic.Uint64 + // Overruns counts socket-buffer overflows. The packets lost to one were + // accepted by the queue rules' bypass flag, so the proxy kept serving — + // they simply never reached the strategy. + Overruns atomic.Uint64 + // Truncated counts packets the kernel copied only part of. They are + // accepted unmodified, since manipulating a prefix would put a corrupt + // packet on the wire, and a nonzero count means the copy length is too + // small for the traffic on this box. + Truncated atomic.Uint64 } // Snapshot is a value copy of Stats. @@ -73,6 +113,8 @@ type Snapshot struct { Modified uint64 `json:"modified"` Reinjected uint64 `json:"reinjected"` InjectFails uint64 `json:"inject_fails"` + Overruns uint64 `json:"overruns"` + Truncated uint64 `json:"truncated"` } // Runtime binds the engine to the two queues and the reinjector. @@ -108,106 +150,152 @@ func (rt *Runtime) Snapshot() Snapshot { Modified: rt.Stats.Modified.Load(), Reinjected: rt.Stats.Reinjected.Load(), InjectFails: rt.Stats.InjectFails.Load(), + Overruns: rt.Stats.Overruns.Load(), + Truncated: rt.Stats.Truncated.Load(), } } -// Run opens both queues, registers the callbacks, and blocks until ctx is -// cancelled. It always releases the queues and the raw socket before returning. +// Run opens both queues and pumps them until ctx is cancelled. It always +// releases the queues and the raw socket before returning. +// +// One goroutine per queue, and one read buffer and one Scratch per goroutine: +// each queue is processed strictly in order, which is what lets the verdict +// batching hold accepts back safely and lets the engine reuse its working +// memory without synchronization. func (rt *Runtime) Run(ctx context.Context) error { - outQ, err := rt.open(rt.cfg.OutQueue) + outQ, err := openQueue(rt.cfg.OutQueue, rt.cfg.MaxPacketLen, maxQueueLen) if err != nil { return fmt.Errorf("open out-queue %d: %w", rt.cfg.OutQueue, err) } defer func() { _ = outQ.Close() }() - inQ, err := rt.open(rt.cfg.InQueue) + inQ, err := openQueue(rt.cfg.InQueue, rt.cfg.MaxPacketLen, maxQueueLen) if err != nil { return fmt.Errorf("open in-queue %d: %w", rt.cfg.InQueue, err) } defer func() { _ = inQ.Close() }() defer func() { _ = rt.reinjector.Close() }() - if err := outQ.RegisterWithErrorFunc(ctx, rt.hook(outQ, strategy.DirectionOutbound), rt.errHook); err != nil { - return fmt.Errorf("register out-queue: %w", err) - } - if err := inQ.RegisterWithErrorFunc(ctx, rt.hook(inQ, strategy.DirectionInbound), rt.errHook); err != nil { - return fmt.Errorf("register in-queue: %w", err) - } - - <-ctx.Done() - return ctx.Err() -} + // A context of our own, cancelled the moment either pump gives up. Without + // it, one pump failing would leave the other looping: interrupt makes its + // read return a deadline error, which pump treats as the ordinary idle-queue + // case and retries — against a deadline still in the past, so it spins and + // wg.Wait below never returns. + pumpCtx, stopPumps := context.WithCancel(ctx) + defer stopPumps() -func (rt *Runtime) open(queue uint16) (*nfq.Nfqueue, error) { - return nfq.Open(&nfq.Config{ - NfQueue: queue, - MaxPacketLen: rt.cfg.MaxPacketLen, - MaxQueueLen: 0xffff, - Copymode: nfq.NfQnlCopyPacket, - }) -} + errs := make(chan error, 2) + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); errs <- rt.pump(pumpCtx, outQ, strategy.DirectionOutbound) }() + go func() { defer wg.Done(); errs <- rt.pump(pumpCtx, inQ, strategy.DirectionInbound) }() -func (rt *Runtime) errHook(e error) int { - // A read timeout is expected and not fatal — log it quietly. Everything else - // is logged at error level. Either way the queue stays open. - if errors.Is(e, os.ErrDeadlineExceeded) { - rt.log.Debugf("nfqueue read timeout: %v", e) - } else { - rt.log.Errorf("nfqueue error: %v", e) + var runErr error + select { + case <-ctx.Done(): + runErr = ctx.Err() + case runErr = <-errs: } - return 0 + stopPumps() + + // Wake both readers and wait for them before the deferred Close runs. A + // reader still draining the socket would swallow teardown traffic and leave + // shutdown hanging until something killed the process. + outQ.interrupt() + inQ.interrupt() + wg.Wait() + return runErr } -func (rt *Runtime) hook(q *nfq.Nfqueue, dir strategy.Direction) nfq.HookFunc { - return func(a nfq.Attribute) int { - if a.PacketID == nil { - return 0 +// pump reads one queue until the context is cancelled. +func (rt *Runtime) pump(ctx context.Context, q *queue, dir strategy.Direction) error { + scratch := &engine.Scratch{} + handle := func(p packet) error { + rt.handle(q, dir, p, scratch) + return nil + } + for { + if err := ctx.Err(); err != nil { + return err } - id := *a.PacketID - if a.Payload == nil || len(*a.Payload) == 0 { - // Counted like any other accept: this path is indistinguishable from - // a pass-through as far as the flow is concerned, and leaving it out - // makes the verdict counters undercount what was actually accepted. - rt.accept(q, id) - return 0 + err := q.read(ctx, handle) + switch { + case err == nil: + case errors.Is(err, unix.ENOBUFS): + // The socket buffer overflowed and the kernel dropped packets. + // Those packets were accepted by the bypass flag, so the proxy is + // unharmed; the strategy simply did not see them. + rt.Stats.Overruns.Add(1) + rt.log.Errorf("nfqueue socket overrun: packets bypassed the strategy") + case errors.Is(err, unix.EAGAIN), errors.Is(err, os.ErrDeadlineExceeded): + // Expected on an idle queue. + rt.log.Debugf("nfqueue read: %v", err) + case ctx.Err() != nil: + return ctx.Err() + default: + return fmt.Errorf("read %s queue: %w", dir, err) } - raw := *a.Payload + } +} - if rt.cfg.Observer != nil { - rt.cfg.Observer.Observe(raw, dir) - } +// handle runs one packet through the engine and issues its verdict. +func (rt *Runtime) handle(q *queue, dir strategy.Direction, p packet, scratch *engine.Scratch) { + if p.truncated { + // Fail open: a prefix of a packet cannot be manipulated or reinjected. + rt.Stats.Truncated.Add(1) + rt.accept(q, p.id) + return + } + if len(p.payload) == 0 { + // Counted like any other accept: this path is indistinguishable from a + // pass-through as far as the flow is concerned, and leaving it out + // makes the verdict counters undercount what was actually accepted. + rt.accept(q, p.id) + return + } - res, err := rt.eng.Process(raw, dir) - if err != nil { - // Fail open: a strategy or decode error must never black-hole the - // proxy's traffic. - rt.log.Errorf("process %s packet: %v", dir, err) - rt.accept(q, id) - return 0 - } + if rt.cfg.Observer != nil { + rt.cfg.Observer.Observe(p.payload, dir) + } - if dir == strategy.DirectionOutbound { - rt.verdictOutbound(q, id, res) - } else { - rt.verdictInbound(q, id, res) - } - return 0 + res, err := rt.eng.Process(p.payload, dir, scratch) + if err != nil { + // Fail open: a strategy or decode error must never black-hole the + // proxy's traffic. + rt.log.Errorf("process %s packet: %v", dir, err) + rt.accept(q, p.id) + return + } + + if dir == strategy.DirectionOutbound { + rt.verdictOutbound(q, p.id, res) + } else { + rt.verdictInbound(q, p.id, res) } } -// verdictOutbound: unchanged packets are accepted as-is; everything else drops -// the original and reinjects the replacement packets (possibly none, for a drop). +// verdictOutbound issues the outbound verdict, using the queue itself for +// everything but the extra packets a fan-out strategy produces. // -// If a strategy produced replacement packets but every reinjection failed, the -// original is accepted instead of dropped: dropping it would black-hole the -// flow, and failing open keeps the proxy serving. -func (rt *Runtime) verdictOutbound(q *nfq.Nfqueue, id uint32, res engine.Result) { +// If a strategy produced replacement packets but none of them could be +// delivered, the original is accepted instead of dropped: dropping it would +// black-hole the flow, and failing open keeps the proxy serving. +func (rt *Runtime) verdictOutbound(q *queue, id uint32, res engine.Result) { if res.Outcome == engine.OutcomeUnchanged { rt.accept(q, id) return } + if len(res.Packets) == 0 { + rt.drop(q, id) + return + } + + // Everything except the last replacement goes out through the raw socket, + // in order; the last one replaces the queued packet. + extras := res.Packets[:len(res.Packets)-1] + last := res.Packets[len(res.Packets)-1] injected := 0 - for _, p := range res.Packets { + for _, p := range extras { if err := rt.reinjector.Inject(p); err != nil { rt.log.Errorf("reinject: %v", err) rt.Stats.InjectFails.Add(1) @@ -216,26 +304,42 @@ func (rt *Runtime) verdictOutbound(q *nfq.Nfqueue, id uint32, res engine.Result) injected++ rt.Stats.Reinjected.Add(1) } - if len(res.Packets) > 0 && injected == 0 { - rt.log.Errorf("all %d replacement packets failed to reinject; accepting original to avoid black-hole", len(res.Packets)) - rt.accept(q, id) + if err := q.verdict(id, nfAccept, last); err != nil { + // The queued packet could not be replaced. Fall back to the older path + // — inject the replacement and drop the original — so a kernel that + // rejects the modified verdict still applies the strategy. + rt.log.Errorf("mod-accept outbound: %v", err) + if err := rt.reinjector.Inject(last); err != nil { + rt.log.Errorf("reinject after mod-accept failure: %v", err) + rt.Stats.InjectFails.Add(1) + if injected == 0 { + rt.log.Errorf("no replacement packet reached the wire; accepting original to avoid black-hole") + rt.accept(q, id) + return + } + } else { + // Counted as a reinjection rather than a modification: the packet + // reached the wire through the raw socket, and the original is + // dropped just below. See the Stats doc for why these stay + // per-mechanism instead of both being incremented. + rt.Stats.Reinjected.Add(1) + } + rt.drop(q, id) return } - _ = q.SetVerdict(id, nfq.NfDrop) - rt.Stats.Dropped.Add(1) + rt.Stats.Modified.Add(1) } // verdictInbound handles the single-in/single-out inbound path with in-queue // verdicts only — no reinjection. -func (rt *Runtime) verdictInbound(q *nfq.Nfqueue, id uint32, res engine.Result) { +func (rt *Runtime) verdictInbound(q *queue, id uint32, res engine.Result) { switch res.Outcome { case engine.OutcomeUnchanged: rt.accept(q, id) case engine.OutcomeDropped: - _ = q.SetVerdict(id, nfq.NfDrop) - rt.Stats.Dropped.Add(1) + rt.drop(q, id) case engine.OutcomeTampered: - if err := q.SetVerdictWithOption(id, nfq.NfAccept, nfq.WithAlteredPacket(res.Packets[0])); err != nil { + if err := q.verdict(id, nfAccept, res.Packets[0]); err != nil { rt.log.Errorf("mod-accept inbound: %v", err) rt.accept(q, id) return @@ -250,7 +354,16 @@ func (rt *Runtime) verdictInbound(q *nfq.Nfqueue, id uint32, res engine.Result) } } -func (rt *Runtime) accept(q *nfq.Nfqueue, id uint32) { - _ = q.SetVerdict(id, nfq.NfAccept) +// accept defers the accept into the queue's batch; it is flushed at the end of +// the read, or ahead of any individual verdict for a later packet. +func (rt *Runtime) accept(q *queue, id uint32) { + q.accept(id) rt.Stats.Accepted.Add(1) } + +func (rt *Runtime) drop(q *queue, id uint32) { + if err := q.verdict(id, nfDrop, nil); err != nil { + rt.log.Errorf("drop verdict: %v", err) + } + rt.Stats.Dropped.Add(1) +} diff --git a/internal/nftables/counters.go b/internal/nftables/counters.go new file mode 100644 index 0000000..8be3d68 --- /dev/null +++ b/internal/nftables/counters.go @@ -0,0 +1,64 @@ +package nftables + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os/exec" +) + +// ReadCounters returns the packet counts of the table's named counters, keyed by +// counter name. +// +// The counters are read out of the kernel rather than accumulated in userspace +// because that is the whole point of them: the classification happens in +// nftables, no packet takes a userspace round trip, and this call happens once +// per metric export interval instead of once per packet. +// +// A missing table is not an error — an idle sidecar has no table, and its +// counters simply do not exist yet — so the result is empty in that case. +func (m *Manager) ReadCounters(ctx context.Context) (map[string]uint64, error) { + cmd := exec.CommandContext(ctx, m.cfg.NFTPath, "-j", "list", "counters", "table", "inet", m.cfg.Table) + out, err := cmd.Output() + if err != nil { + if isMissingTableOutput(err) { + return map[string]uint64{}, nil + } + return nil, fmt.Errorf("%s -j list counters: %w", m.cfg.NFTPath, err) + } + return parseCounters(out) +} + +// counterList is the shape of `nft -j list counters`: a list of objects, each +// carrying at most one of the keys we care about. +type counterList struct { + Nftables []struct { + Counter *struct { + Name string `json:"name"` + Packets uint64 `json:"packets"` + } `json:"counter"` + } `json:"nftables"` +} + +func parseCounters(out []byte) (map[string]uint64, error) { + var list counterList + if err := json.Unmarshal(out, &list); err != nil { + return nil, fmt.Errorf("parse nft counter json: %w", err) + } + counts := make(map[string]uint64, len(list.Nftables)) + for _, entry := range list.Nftables { + if entry.Counter == nil { + continue // metainfo and anything else nft chooses to emit + } + counts[entry.Counter.Name] = entry.Counter.Packets + } + return counts, nil +} + +// isMissingTableOutput reports whether an nft failure was "no such table". The +// message goes to stderr, which exec.Cmd.Output captures into ExitError.Stderr. +func isMissingTableOutput(err error) bool { + var exitErr *exec.ExitError + return errors.As(err, &exitErr) && missingTableMessage(string(exitErr.Stderr)) +} diff --git a/internal/nftables/counters_test.go b/internal/nftables/counters_test.go new file mode 100644 index 0000000..8970018 --- /dev/null +++ b/internal/nftables/counters_test.go @@ -0,0 +1,100 @@ +package nftables + +import ( + "strings" + "testing" +) + +// nftCounterJSON is real `nft -j list counters` output, kept verbatim so the +// parser is tested against the format the binary actually emits — including the +// metainfo entry that carries no counter. +const nftCounterJSON = `{"nftables": [{"metainfo": {"version": "1.0.6", "release_name": "Lester Gooch #5", "json_schema_version": 1}}, ` + + `{"counter": {"family": "inet", "name": "rst", "table": "geneva_server", "handle": 3, "packets": 7, "bytes": 420}}, ` + + `{"counter": {"family": "inet", "name": "syn", "table": "geneva_server", "handle": 4, "packets": 12, "bytes": 720}}, ` + + `{"counter": {"family": "inet", "name": "data", "table": "geneva_server", "handle": 6, "packets": 3400, "bytes": 4964000}}]}` + +func TestParseCounters(t *testing.T) { + counts, err := parseCounters([]byte(nftCounterJSON)) + if err != nil { + t.Fatalf("parseCounters: %v", err) + } + for name, want := range map[string]uint64{"rst": 7, "syn": 12, "data": 3400} { + if counts[name] != want { + t.Errorf("%s = %d, want %d", name, counts[name], want) + } + } + if _, ok := counts["metainfo"]; ok { + t.Error("metainfo entry parsed as a counter") + } + if len(counts) != 3 { + t.Errorf("got %d counters, want 3: %v", len(counts), counts) + } +} + +func TestParseCountersRejectsGarbage(t *testing.T) { + if _, err := parseCounters([]byte("not json")); err == nil { + t.Error("garbage accepted") + } +} + +// TestCensorRulesetShape pins the classification chain: the counters exist, the +// jump is installed, precedence is the order the userspace classifier uses, and +// every rule returns so a packet lands in exactly one bucket. +func TestCensorRulesetShape(t *testing.T) { + m := New(Config{ + Table: "geneva_censor", Port: 8080, OutQueue: 100, InQueue: 101, Mark: 0x67656e, + Outbound: Selector{Flags: []FlagMatch{{Mask: 0xff, Value: 0x02}}}, + Censor: true, + }) + rs := m.Ruleset() + + for _, c := range CensorCounters { + if !strings.Contains(rs, "counter "+c+" {}") { + t.Errorf("counter %q not declared:\n%s", c, rs) + } + } + if !strings.Contains(rs, "jump "+censorChain) { + t.Errorf("classification jump missing:\n%s", rs) + } + + // Precedence: a RST is a RST even though it also has ACK set, so the order + // of the rules is what makes the buckets disjoint. + order := []string{`name "rst"`, `name "syn"`, `name "fin"`, `name "data"`, `name "ack_only"`} + at := -1 + for _, want := range order { + i := strings.Index(rs, want) + if i < 0 { + t.Fatalf("rule %s missing:\n%s", want, rs) + } + if i < at { + t.Errorf("rule %s is out of precedence order:\n%s", want, rs) + } + at = i + } + // Every counter rule must return, or a packet would fall through and be + // counted twice. + for _, line := range strings.Split(rs, "\n") { + if strings.Contains(line, "counter name") && !strings.Contains(line, "return") { + t.Errorf("counter rule does not return: %q", strings.TrimSpace(line)) + } + } + // And the counters must never queue anything: that is the entire point. + for _, line := range strings.Split(rs, "\n") { + if strings.Contains(line, "counter name") && strings.Contains(line, "queue") { + t.Errorf("counter rule queues a packet: %q", strings.TrimSpace(line)) + } + } +} + +// TestCensorCountersNeverKeepATableAlive pins that counting rides along with a +// table that exists for steering and never keeps one alive on its own — a box +// with no strategy has nothing of ours in the kernel. +func TestCensorCountersNeverKeepATableAlive(t *testing.T) { + m := New(Config{Table: "geneva_idle_censor", Port: 8080, OutQueue: 100, InQueue: 101, Mark: 0x67656e, Censor: true}) + if !m.Idle() { + t.Error("a censor-only manager is not idle") + } + if rs := m.Ruleset(); rs != "" { + t.Errorf("censor counters produced a ruleset with nothing to steer:\n%s", rs) + } +} diff --git a/internal/nftables/manager.go b/internal/nftables/manager.go index 3789885..13332f6 100644 --- a/internal/nftables/manager.go +++ b/internal/nftables/manager.go @@ -7,7 +7,12 @@ // it owns atomically, and the table name is disjoint from any other subsystem's. // // The steering is scoped to one TCP port in each direction — the proxy's -// listening port — and to IPv4. The table family is `inet`, which sees both +// listening port — to IPv4, and, when the loaded strategy allows it, to the +// TCP flag combinations that strategy's triggers can actually match. A packet +// no trigger can match is passed through byte-for-byte by the engine, so +// leaving it in the kernel reaches the same result without the round trip; see +// internal/steering. A direction whose forest is empty gets no rule at all, +// which is what makes an unconfigured sidecar free. The table family is `inet`, which sees both // address families, so the queue rules match `meta nfproto ipv4` explicitly: // the engine and the reinjector are IPv4-only, so queueing IPv6 would spend // userspace round trips on packets the engine can only fail open on. Reinjected @@ -22,6 +27,8 @@ import ( "fmt" "os/exec" "strings" + + "github.com/getlantern/geneva-server/internal/censor" ) // Config describes the steering rules to program. @@ -31,6 +38,14 @@ type Config struct { // Port is the proxy's TCP listening port. Egress is matched by source port, // ingress by destination port. Port uint16 + // Outbound and Inbound narrow each direction to the packets the loaded + // strategy can act on. A zero Selector steers nothing in that direction. + Outbound Selector + Inbound Selector + // Censor adds the inbound classification counters: named counters and a + // chain that sorts arriving packets into them without queueing any of them. + // See censorRules. + Censor bool // OutQueue receives egress (outbound) packets; InQueue receives ingress. OutQueue uint16 InQueue uint16 @@ -41,6 +56,129 @@ type Config struct { NFTPath string } +// Selector narrows a direction's steering to the packets a strategy can match. +// +// It is derived from the strategy's triggers (see internal/steering), not +// configured by hand: Any means "the strategy has a trigger nftables cannot +// express, queue everything", a non-empty Flags means "queue only these flag +// combinations", and the zero value means "this direction can match nothing, so +// steer none of it". +type Selector struct { + Any bool + Flags []FlagMatch +} + +// Empty reports whether this direction needs no rule at all. +func (s Selector) Empty() bool { return !s.Any && len(s.Flags) == 0 } + +// FlagMatch matches the packets for which `tcp flags & Mask == Value`. +type FlagMatch struct { + Mask uint8 + Value uint8 +} + +// nftFlagNames are the bits of the TCP flags byte in nftables' spelling. +var nftFlagNames = []struct { + bit uint8 + name string +}{ + {0x01, "fin"}, + {0x02, "syn"}, + {0x04, "rst"}, + {0x08, "psh"}, + {0x10, "ack"}, + {0x20, "urg"}, + {0x40, "ecn"}, + {0x80, "cwr"}, +} + +// flagExpr renders one FlagMatch as an nftables match expression. +func flagExpr(m FlagMatch) string { + if m.Mask == 0xff { + // Equality over the whole byte: nft compares the masked value against + // the named set, and an empty set is spelled "0x0". + return fmt.Sprintf("tcp flags & 0xff == %s", flagNames(m.Value)) + } + return fmt.Sprintf("tcp flags & %s == %s", flagNames(m.Mask), flagNames(m.Value)) +} + +// flagNames spells a flags bitmask the way nft accepts it on both sides of a +// comparison: a pipe-joined list of flag names, or a literal for the empty set. +// A multi-flag list is parenthesized — without the parentheses nft parses the +// bare pipes with its own operator precedence and installs a different match +// than the one written (`flags & syn|ack` becomes `(flags & syn)|ack`). +func flagNames(bits uint8) string { + if bits == 0 { + return "0x0" + } + var names []string + for _, f := range nftFlagNames { + if bits&f.bit != 0 { + names = append(names, f.name) + } + } + if len(names) > 1 { + return "(" + strings.Join(names, "|") + ")" + } + return names[0] +} + +// CensorCounters are the named nftables counters the classification chain sorts +// inbound packets into. The names are the censor event names — derived from the +// censor package's own list rather than respelled here, so nothing has to +// translate between the kernel's view and the metric's and the two cannot +// drift apart. +// +// Counters live in the sidecar's own table, so these names cannot collide with +// anything else on the box. +var CensorCounters = func() []string { + names := make([]string, len(censor.KernelEvents)) + for i, e := range censor.KernelEvents { + names[i] = e.String() + } + return names +}() + +// censorDataMinLength is the packet length above which an inbound TCP packet is +// counted as carrying data. +// +// nftables cannot subtract one header field from another, so "has a payload" +// cannot be expressed exactly — it would be +// `ip length - ihl*4 - dataoffset*4 > 0`. A pure ACK is 40 bytes of headers +// plus options, and 32 bytes of options (timestamps, SACK) is the realistic +// worst case, so anything above 80 bytes carries payload. The failure mode is a +// data segment with fewer than ~28 payload bytes counting as ack_only, which +// does not happen in proxy traffic: a TLS record is far larger. +const censorDataMinLength = 80 + +// censorRules renders the classification chain. Order is precedence, and each +// rule returns, so every packet lands in exactly one counter — the same +// property the userspace classifier has, and what makes a ratio between two +// counters mean what it appears to mean. +// +// Two of the userspace classifier's buckets have no kernel equivalent and stay +// at zero here. `undecodable` is a decode failure, which cannot happen to a +// packet nobody decodes. `fragment` would need a rule with no port match, since +// a non-initial fragment carries no TCP header to match a port against, and +// counting every fragment on the box for every port is worse than not counting +// it. +func censorRules() []string { + return []string{ + "chain " + censorChain + " {", + "\t\ttcp flags & rst == rst counter name \"rst\" return", + // A listening port never receives a SYN-ACK, so an inbound SYN without + // ACK is a client opening a connection. + "\t\ttcp flags & (syn|ack) == syn counter name \"syn\" return", + "\t\ttcp flags & fin == fin counter name \"fin\" return", + fmt.Sprintf("\t\tmeta length > %d counter name \"data\" return", censorDataMinLength), + "\t\tcounter name \"ack_only\" return", + "\t}", + } +} + +// censorChain is the regular (non-base) chain the input chain jumps into. +const censorChain = "censor_in" + // Manager owns the lifecycle of the steering table. type Manager struct { cfg Config @@ -59,29 +197,88 @@ func New(cfg Config) *Manager { // Ruleset returns the nft script that Install applies. Exposed so the exact // rules can be inspected and asserted in tests without touching the kernel. +// +// A direction with an empty Selector contributes no queue rule. When both are +// empty the ruleset is empty too, and Install removes the table instead of +// programming one. func (m *Manager) Ruleset() string { + if m.Idle() { + return "" + } var b strings.Builder fmt.Fprintf(&b, "table inet %s {\n", m.cfg.Table) + if m.cfg.Censor { + for _, c := range CensorCounters { + fmt.Fprintf(&b, "\tcounter %s {}\n", c) + } + for _, line := range censorRules() { + fmt.Fprintf(&b, "\t%s\n", line) + } + } // Egress (outbound): the proxy sends from Port toward the client/censor. fmt.Fprintf(&b, "\tchain output {\n") fmt.Fprintf(&b, "\t\ttype filter hook output priority 0; policy accept;\n") fmt.Fprintf(&b, "\t\tmeta mark %#x accept\n", m.cfg.Mark) - fmt.Fprintf(&b, "\t\tmeta nfproto ipv4 meta l4proto tcp tcp sport %d queue num %d bypass\n", m.cfg.Port, m.cfg.OutQueue) + for _, rule := range queueRules(m.cfg.Outbound, "sport", m.cfg.Port, m.cfg.OutQueue) { + fmt.Fprintf(&b, "\t\t%s\n", rule) + } fmt.Fprintf(&b, "\t}\n") // Ingress (inbound): packets arriving for the proxy's Port. fmt.Fprintf(&b, "\tchain input {\n") fmt.Fprintf(&b, "\t\ttype filter hook input priority 0; policy accept;\n") - fmt.Fprintf(&b, "\t\tmeta nfproto ipv4 meta l4proto tcp tcp dport %d queue num %d bypass\n", m.cfg.Port, m.cfg.InQueue) + if m.cfg.Censor { + // Counted before anything else in the chain, so the counts describe what + // arrived rather than what survived the strategy. Counting changes no + // verdict: the chain returns without one. + fmt.Fprintf(&b, "\t\tmeta nfproto ipv4 meta l4proto tcp tcp dport %d jump %s\n", m.cfg.Port, censorChain) + } + for _, rule := range queueRules(m.cfg.Inbound, "dport", m.cfg.Port, m.cfg.InQueue) { + fmt.Fprintf(&b, "\t\t%s\n", rule) + } fmt.Fprintf(&b, "\t}\n") fmt.Fprintf(&b, "}\n") return b.String() } +// Idle reports whether the configured selectors steer nothing, in which case no +// table should exist at all. +// +// The censor counters do not make a table non-idle. They ride along with a table +// that exists for steering; they never keep one alive on their own, because a +// box with no strategy is supposed to have nothing of ours in the kernel at all. +func (m *Manager) Idle() bool { + return m.cfg.Outbound.Empty() && m.cfg.Inbound.Empty() +} + +// queueRules renders the queue rules for one direction: one per flag match, or +// a single unconditional rule when the selector is Any. +func queueRules(sel Selector, portKeyword string, port, queue uint16) []string { + base := fmt.Sprintf("meta nfproto ipv4 meta l4proto tcp tcp %s %d", portKeyword, port) + verdict := fmt.Sprintf("queue num %d bypass", queue) + switch { + case sel.Empty(): + return nil + case sel.Any: + return []string{fmt.Sprintf("%s %s", base, verdict)} + default: + rules := make([]string, 0, len(sel.Flags)) + for _, f := range sel.Flags { + rules = append(rules, fmt.Sprintf("%s %s %s", base, flagExpr(f), verdict)) + } + return rules + } +} + // Install programs the steering table. Any pre-existing table of the same name // (left by a prior crash) is removed first, so Install is idempotent and never // stacks duplicate rules. func (m *Manager) Install(ctx context.Context) error { _ = m.Remove(ctx) // best-effort: clear a stale table from a previous run + if m.Idle() { + // Nothing can match, so there is nothing to steer: leaving the table + // absent is what keeps an unconfigured sidecar off the data path. + return nil + } if err := m.run(ctx, m.Ruleset()); err != nil { return fmt.Errorf("install nftables rules: %w", err) } @@ -109,7 +306,12 @@ func (m *Manager) run(ctx context.Context, script string) error { return nil } -func isMissingTable(err error) bool { - s := err.Error() +func isMissingTable(err error) bool { return missingTableMessage(err.Error()) } + +// missingTableMessage reports whether an nft error message means "no such +// table". Shared by the two call paths that see the message differently: run +// wraps CombinedOutput into the error string, ReadCounters gets it on +// ExitError.Stderr. +func missingTableMessage(s string) bool { return strings.Contains(s, "No such file or directory") || strings.Contains(s, "does not exist") } diff --git a/internal/nftables/manager_test.go b/internal/nftables/manager_test.go index f6404c2..af8aa4e 100644 --- a/internal/nftables/manager_test.go +++ b/internal/nftables/manager_test.go @@ -6,10 +6,19 @@ import ( "os/exec" "strings" "testing" + + "github.com/getlantern/geneva-server/internal/testutil" ) +// anySel is the widest selector: a strategy whose triggers cannot be expressed +// in nftables, so every packet on the port must be queued. +var anySel = Selector{Any: true} + func TestRulesetScoping(t *testing.T) { - m := New(Config{Table: "geneva_test", Port: 8080, OutQueue: 100, InQueue: 101, Mark: 0x67656e}) + m := New(Config{ + Table: "geneva_test", Port: 8080, OutQueue: 100, InQueue: 101, Mark: 0x67656e, + Outbound: anySel, Inbound: anySel, + }) rs := m.Ruleset() // The steering must be scoped to exactly the proxy's TCP port in each @@ -52,7 +61,10 @@ func TestInstallRemoveLifecycle(t *testing.T) { t.Skip("nft not installed") } ctx := context.Background() - m := New(Config{Table: "geneva_lifecycle_test", Port: 18080, OutQueue: 200, InQueue: 201, Mark: 0x67656e}) + m := New(Config{ + Table: "geneva_lifecycle_test", Port: 18080, OutQueue: 200, InQueue: 201, Mark: 0x67656e, + Outbound: anySel, Inbound: anySel, + }) t.Cleanup(func() { _ = m.Remove(ctx) }) if err := m.Install(ctx); err != nil { @@ -62,13 +74,13 @@ func TestInstallRemoveLifecycle(t *testing.T) { if err := m.Install(ctx); err != nil { t.Fatalf("second install: %v", err) } - if !tableExists(t, "geneva_lifecycle_test") { + if !testutil.TableExists(t, "geneva_lifecycle_test") { t.Fatal("table absent after install") } if err := m.Remove(ctx); err != nil { t.Fatalf("remove: %v", err) } - if tableExists(t, "geneva_lifecycle_test") { + if testutil.TableExists(t, "geneva_lifecycle_test") { t.Fatal("table present after remove: stale rules leaked") } // Remove on an absent table is a no-op, not an error. @@ -77,11 +89,86 @@ func TestInstallRemoveLifecycle(t *testing.T) { } } -func tableExists(t *testing.T, name string) bool { - t.Helper() - out, err := exec.Command("nft", "list", "tables", "inet").CombinedOutput() - if err != nil { - t.Fatalf("nft list tables: %v: %s", err, out) +// TestIdleSelectorsProgramNothing pins the property that makes an unconfigured +// sidecar free: with nothing to match, there is no table at all. A sidecar that +// installed rules and passed packets through would still pay the NFQUEUE round +// trip for every one of them, which measured as a 76% throughput loss on a +// 1-vCPU box. +func TestIdleSelectorsProgramNothing(t *testing.T) { + m := New(Config{Table: "geneva_idle", Port: 8080, OutQueue: 100, InQueue: 101, Mark: 0x67656e}) + if !m.Idle() { + t.Error("manager with no selectors is not idle") + } + if rs := m.Ruleset(); rs != "" { + t.Errorf("idle manager produced a ruleset:\n%s", rs) + } +} + +// TestRulesetFlagScoping is the optimization proper: a strategy that only +// triggers on handshake packets must leave bulk data in the kernel. +func TestRulesetFlagScoping(t *testing.T) { + m := New(Config{ + Table: "geneva_flags", Port: 8080, OutQueue: 100, InQueue: 101, Mark: 0x67656e, + // Exact SYN (the common handshake trigger) plus a wildcard RST. + Outbound: Selector{Flags: []FlagMatch{{Mask: 0xff, Value: 0x02}}}, + Inbound: Selector{Flags: []FlagMatch{{Mask: 0x04, Value: 0x04}}}, + }) + rs := m.Ruleset() + + wants := []string{ + "tcp sport 8080 tcp flags & 0xff == syn queue num 100 bypass", + "tcp dport 8080 tcp flags & rst == rst queue num 101 bypass", + } + for _, w := range wants { + if !strings.Contains(rs, w) { + t.Errorf("ruleset missing %q\n---\n%s", w, rs) + } + } + // No unconditional queue rule may survive scoping, or bulk data is still + // taking the round trip. + for _, line := range strings.Split(rs, "\n") { + if strings.Contains(line, "queue num") && !strings.Contains(line, "tcp flags") { + t.Errorf("unscoped queue rule survived: %q", strings.TrimSpace(line)) + } + } +} + +// TestRulesetMultiFlagParenthesized pins that multi-flag sets are rendered in +// parentheses. Bare pipes parse under nft's own operator precedence, so +// `tcp flags & syn|ack == syn|ack` installs cleanly as a completely different +// match — a wildcard multi-flag trigger like SA* would silently mis-scope. +func TestRulesetMultiFlagParenthesized(t *testing.T) { + m := New(Config{ + Table: "geneva_multi", Port: 8080, OutQueue: 100, InQueue: 101, Mark: 0x67656e, + // A wildcard SYN+ACK trigger and an exact PSH+ACK one. + Outbound: Selector{Flags: []FlagMatch{{Mask: 0x12, Value: 0x12}}}, + Inbound: Selector{Flags: []FlagMatch{{Mask: 0xff, Value: 0x18}}}, + }) + rs := m.Ruleset() + wants := []string{ + "tcp flags & (syn|ack) == (syn|ack)", + "tcp flags & 0xff == (psh|ack)", + } + for _, w := range wants { + if !strings.Contains(rs, w) { + t.Errorf("ruleset missing %q\n---\n%s", w, rs) + } + } +} + +// TestRulesetOneDirection covers an outbound-only strategy: the inbound chain +// must exist (it is where the reinjection guard and policy live) but carry no +// queue rule. +func TestRulesetOneDirection(t *testing.T) { + m := New(Config{ + Table: "geneva_one", Port: 8080, OutQueue: 100, InQueue: 101, Mark: 0x67656e, + Outbound: Selector{Any: true}, + }) + rs := m.Ruleset() + if strings.Contains(rs, "dport") { + t.Errorf("inbound queue rule emitted for an outbound-only strategy:\n%s", rs) + } + if !strings.Contains(rs, "sport 8080") { + t.Errorf("outbound queue rule missing:\n%s", rs) } - return strings.Contains(string(out), "table inet "+name) } diff --git a/internal/steering/controller.go b/internal/steering/controller.go new file mode 100644 index 0000000..463fc90 --- /dev/null +++ b/internal/steering/controller.go @@ -0,0 +1,335 @@ +//go:build linux + +package steering + +import ( + "context" + "fmt" + "sync" + + "github.com/getlantern/geneva" + + "github.com/getlantern/geneva-server/internal/engine" + "github.com/getlantern/geneva-server/internal/netdev" + "github.com/getlantern/geneva-server/internal/nftables" +) + +// Logger is the minimal logging surface the controller needs. +type Logger interface { + Infof(format string, args ...any) + Errorf(format string, args ...any) +} + +type nopLogger struct{} + +func (nopLogger) Infof(string, ...any) {} +func (nopLogger) Errorf(string, ...any) {} + +// Config describes the box the controller steers on. +type Config struct { + // Mode is GenevaModeProd or GenevaModeEval, spelled as the flag spells it. + // The controller needs it because one behaviour is mode-gated: see + // ObserveInbound. + Mode string + // NFT is the base kernel-programming config: table, port, queues, mark, nft + // path, and whether the censor classification counters ride along. The + // selectors are owned by the controller — whatever is set here is replaced + // with the loaded strategy's scope on every program. + NFT nftables.Config + EthtoolPath string + // Iface is the interface whose offloads are torn down while steering is + // active. Empty leaves the NIC alone, which is only correct where something + // else guarantees MTU-sized, checksummed packets (a test harness). + Iface string + // NoNFT skips programming the kernel entirely, for a box where the rules are + // managed out of band. + NoNFT bool + // ObserveInbound keeps every inbound packet flowing through userspace while + // a strategy is loaded, even when that strategy's triggers cannot act on + // inbound traffic at all. Honoured in eval mode only. + // + // It buys the censor-reachability signal (internal/censor), whose + // inbound-SYN-to-inbound-data ratio is the only estimate we have of a box's + // IP being burned. What it costs is one round trip per inbound packet, + // which makes it almost free or very expensive depending on which way the + // box's bulk traffic runs: measured on a 1-vCPU box, a download-heavy + // workload lost nothing at all (its inbound direction is stretch-ACKs, one + // packet per ~33 outbound), while an upload-heavy one lost 40%. Off by + // default for that reason; deploy/README.md has the numbers. + ObserveInbound bool +} + +// Controller owns the relationship between the loaded strategy and the kernel: +// it installs steering only for the packets the strategy can act on, and takes +// the box off the data path entirely when it can act on nothing. +// +// This is the piece that makes an unconfigured sidecar free. An eval box boots +// with no strategy and a prod box can be rolled back to none, and in both cases +// the right answer is not "queue everything and pass it through" — it is no +// queue at all. +type Controller struct { + cfg Config + eng *engine.Engine + log Logger + + // mu serializes reconciles. A strategy swap is a control-plane event + // measured in seconds, so a mutex costs nothing and keeps the kernel state, + // the offload state and the engine's strategy from interleaving. + mu sync.Mutex + scope Scope + nft *nftables.Manager + offloads *netdev.Disabled +} + +// New returns a controller for eng. Nothing is programmed until Apply runs. +func New(eng *engine.Engine, cfg Config, log Logger) *Controller { + if log == nil { + log = nopLogger{} + } + return &Controller{cfg: cfg, eng: eng, log: log} +} + +// State is the health surface's view of what the box is actually steering. +type State struct { + // Steering is false when no rule is installed, i.e. the sidecar is running + // but not on the data path. + Steering bool `json:"steering"` + // Outbound and Inbound describe each direction: "none", "all", or the flag + // matches being queued. + Outbound string `json:"outbound"` + Inbound string `json:"inbound"` + // OffloadsDisabled reports whether the NIC is currently de-offloaded. + OffloadsDisabled bool `json:"offloads_disabled"` +} + +// State snapshots the controller for /healthz. +func (c *Controller) State() State { + c.mu.Lock() + defer c.mu.Unlock() + return State{ + Steering: !c.scope.Idle(), + Outbound: describe(c.scope.Outbound), + Inbound: describe(c.scope.Inbound), + OffloadsDisabled: c.offloads != nil, + } +} + +// Start brings the kernel in line with the strategy the engine already holds. +// +// It exists separately from Apply because the initial strategy is loaded by +// engine.New: re-installing it here would count as a hot swap in the metrics, +// and `geneva.strategy_swaps` is the signal a rollout landed. Start therefore +// programs the kernel and records the scope without touching the engine. +func (c *Controller) Start(ctx context.Context) error { + dna := c.eng.DNA() + parsed, err := geneva.NewStrategy(dna) + if err != nil { + return fmt.Errorf("parse strategy: %w", err) + } + desired := c.widen(Of(parsed)) + + c.mu.Lock() + defer c.mu.Unlock() + if desired.Idle() { + // Program the idle scope rather than just recording it: an unclean exit + // (SIGKILL, an OOM, a crash) leaves the table behind, and a table with a + // reader attached is not the harmless orphan a table without one is — + // the runtime is about to open its queues, and those stale rules would + // put a box with no strategy right back on the data path. + if err := c.program(ctx, desired); err != nil { + return err + } + c.scope = desired + c.log.Infof("no steering installed: strategy can match nothing; box is off the data path") + return nil + } + if err := c.ensureOffloadsDown(ctx); err != nil { + return err + } + if err := c.program(ctx, desired); err != nil { + // The offloads are already down and the caller registers no teardown + // for a Start that failed, so put the NIC back here or it stays + // de-offloaded until the box is rebuilt. + c.restoreOffloads(ctx) + return err + } + c.scope = desired + c.log.Infof("steering installed: outbound=%s inbound=%s", + describe(desired.Outbound), describe(desired.Inbound)) + return nil +} + +// Apply parses dna, brings the kernel in line with what it can act on, and +// installs it in the engine. +// +// Ordering is deliberate and each step is a correctness requirement rather than +// tidiness: +// +// - Offloads come down before any rule goes up. NFQUEUE delivers packets from +// a point where segmentation is still pending, so a queue that opens while +// GSO is on hands the engine super-segments that cannot be reinjected. +// - Rules are programmed before the engine swaps. Both the old and the new +// strategy are valid, so whichever runs during the swap window is fine; +// what must not happen is packets arriving for a strategy that has not +// loaded, or a strategy loading with nothing to feed it. +// - Offloads go back up only after the rules are gone, and only when nothing +// is being steered any more. +func (c *Controller) Apply(ctx context.Context, dna string) error { + parsed, err := geneva.NewStrategy(dna) + if err != nil { + return fmt.Errorf("%w: parse: %w", engine.ErrInvalidStrategy, err) + } + if err := geneva.Validate(parsed); err != nil { + return fmt.Errorf("%w: validate: %w", engine.ErrInvalidStrategy, err) + } + desired := c.widen(Of(parsed)) + + c.mu.Lock() + defer c.mu.Unlock() + + if !desired.Idle() { + if err := c.ensureOffloadsDown(ctx); err != nil { + return err + } + } + if err := c.program(ctx, desired); err != nil { + return err + } + if err := c.eng.SetStrategy(dna); err != nil { + return err + } + c.scope = desired + if desired.Idle() { + c.restoreOffloads(ctx) + c.log.Infof("steering removed: strategy can match nothing; box is off the data path") + } else { + c.log.Infof("steering installed: outbound=%s inbound=%s", + describe(desired.Outbound), describe(desired.Inbound)) + } + return nil +} + +// Close removes every rule and restores the NIC. Safe to call more than once. +func (c *Controller) Close(ctx context.Context) error { + c.mu.Lock() + defer c.mu.Unlock() + steering := !c.scope.Idle() + err := c.program(ctx, Scope{}) + c.scope = Scope{} + c.restoreOffloads(ctx) + if err != nil { + return err + } + if steering { + // Logged unconditionally on the way out: "did the table actually go + // away" is the first question after any crash loop or rollback, and the + // journal is where it gets answered. + c.log.Infof("nftables steering removed") + } + return nil +} + +// widen applies the observation floor: on an eval box with ObserveInbound set, a +// strategy that is doing anything at all also keeps inbound traffic visible to +// the censor classifier. +// +// Two things it deliberately will not do. An idle strategy is left idle — a box +// with nothing to apply stays off the data path, which is the whole point of +// scoping. And in prod mode the floor is never applied, even if the flag +// somehow arrives set: the cost is a userspace round trip per inbound packet +// (measured free on download-heavy traffic but -40% on upload-heavy, and a prod +// box does not get to choose which its users generate) in exchange for a signal +// an eval box produces for free. main.go refuses the combination at startup; +// this is the second lock, for a Controller built by something other than the +// CLI. A prod box that needs inbound packets in userspace asks precisely, by +// giving its strategy an inbound tree. +func (c *Controller) widen(sc Scope) Scope { + if !c.cfg.ObserveInbound || c.cfg.Mode != modeEval || sc.Idle() { + return sc + } + sc.Inbound = nftables.Selector{Any: true} + return sc +} + +// modeEval is the eval-mode spelling shared with the CLI and the API. Kept +// local rather than imported so this package does not depend on the command. +const modeEval = "eval" + +// program makes the kernel match desired, replacing the table wholesale. An +// idle scope removes it. +func (c *Controller) program(ctx context.Context, desired Scope) error { + if c.cfg.NoNFT { + return nil + } + cfg := c.cfg.NFT + cfg.Outbound, cfg.Inbound = desired.Outbound, desired.Inbound + c.nft = nftables.New(cfg) + // Install removes any existing table first and programs nothing when the + // scope is idle, so this one call covers install, replace and remove. + return c.nft.Install(ctx) +} + +func (c *Controller) ensureOffloadsDown(ctx context.Context) error { + if c.cfg.Iface == "" || c.offloads != nil { + return nil + } + d, err := netdev.Disable(ctx, c.cfg.EthtoolPath, c.cfg.Iface) + if err != nil { + return err + } + c.offloads = d + c.log.Infof("NIC offloads adjusted: iface=%s %s", c.cfg.Iface, d.Summary()) + return nil +} + +// restoreOffloads puts the NIC back. A failure is logged, not returned: the +// strategy change itself succeeded, and refusing it because a checksum offload +// would not come back on would be the wrong trade. +func (c *Controller) restoreOffloads(ctx context.Context) { + if c.offloads == nil { + return + } + if err := c.offloads.Restore(ctx); err != nil { + c.log.Errorf("restore NIC offloads: %v", err) + } else { + c.log.Infof("NIC offloads restored on %s", c.cfg.Iface) + } + c.offloads = nil +} + +// CensorCounts reads the kernel classification counters. It is the read half of +// Config.NFT.Censor, handed to censor.NewKernelSource. +// +// The manager is rebuilt on every program call, so this takes the current one +// under the lock rather than caching a pointer. With an idle scope no table +// exists and there is nothing to read: empty counts are the correct answer for +// a box that is not steering, and answering without forking nft is what keeps +// an idle box's telemetry free. +func (c *Controller) CensorCounts(ctx context.Context) (map[string]uint64, error) { + c.mu.Lock() + nft, idle := c.nft, c.scope.Idle() + c.mu.Unlock() + if nft == nil || idle { + return map[string]uint64{}, nil + } + return nft.ReadCounters(ctx) +} + +// describe renders a selector for logs and the health surface. +func describe(sel nftables.Selector) string { + switch { + case sel.Any: + return "all" + case sel.Empty(): + return "none" + default: + out := "" + for i, f := range sel.Flags { + if i > 0 { + out += "," + } + out += fmt.Sprintf("flags&%#02x==%#02x", f.Mask, f.Value) + } + return out + } +} diff --git a/internal/steering/controller_linux_test.go b/internal/steering/controller_linux_test.go new file mode 100644 index 0000000..f8d1649 --- /dev/null +++ b/internal/steering/controller_linux_test.go @@ -0,0 +1,106 @@ +//go:build linux + +package steering + +import ( + "context" + "os" + "os/exec" + "testing" + + "github.com/getlantern/geneva-server/internal/engine" + "github.com/getlantern/geneva-server/internal/nftables" + "github.com/getlantern/geneva-server/internal/testutil" +) + +// TestObservationFloorIsEvalOnly is the controller-side half of the mode gate. +// main.go refuses the flag in prod mode; this is the second lock, for a +// Controller built by something other than the CLI. Widening inbound to +// everything on a prod box is exactly the cost scoping exists to avoid. +func TestObservationFloorIsEvalOnly(t *testing.T) { + // An outbound-only strategy: nothing asks for inbound, so inbound is + // steered only if the observation floor widens it. + handshake := mustScope(t, `[TCP:flags:S]-duplicate-| \/`) + + cases := []struct { + mode string + observe bool + wantInbound bool + }{ + {mode: "eval", observe: true, wantInbound: true}, + {mode: "eval", observe: false, wantInbound: false}, + {mode: "prod", observe: true, wantInbound: false}, + {mode: "prod", observe: false, wantInbound: false}, + } + for _, c := range cases { + ctrl := New(nil, Config{Mode: c.mode, ObserveInbound: c.observe}, nil) + got := ctrl.widen(handshake) + if got.Inbound.Any != c.wantInbound { + t.Errorf("mode=%s observe=%v: inbound steered = %v, want %v", + c.mode, c.observe, got.Inbound.Any, c.wantInbound) + } + // Widening must never touch the outbound side. + if len(got.Outbound.Flags) != 1 || got.Outbound.Any { + t.Errorf("mode=%s observe=%v: outbound selector altered: %+v", c.mode, c.observe, got.Outbound) + } + } +} + +// TestObservationFloorLeavesIdleIdle pins the other half: a box with no strategy +// stays off the data path even in eval mode with observation asked for. +func TestObservationFloorLeavesIdleIdle(t *testing.T) { + ctrl := New(nil, Config{Mode: "eval", ObserveInbound: true}, nil) + if got := ctrl.widen(mustScope(t, "")); !got.Idle() { + t.Errorf("idle strategy widened to %+v", got) + } +} + +// TestStartClearsStaleTableWhenIdle covers the unclean-restart case: a table +// left behind by a SIGKILL or a crash, followed by a start with no strategy. +// +// A leftover table with no reader is harmless (the rules carry `bypass`), but +// this process is about to open its queues — so the stale rules would put a box +// with no strategy straight back on the data path, which is the one thing the +// scoping is supposed to guarantee cannot happen. +// +// Requires root and nft, and self-skips otherwise, like the nftables lifecycle +// test. +func TestStartClearsStaleTableWhenIdle(t *testing.T) { + if os.Geteuid() != 0 { + t.Skip("requires root") + } + if _, err := exec.LookPath("nft"); err != nil { + t.Skip("nft not installed") + } + ctx := context.Background() + const table = "geneva_stale_test" + + // Leave a table behind, exactly as a killed sidecar would. + stale := nftables.New(nftables.Config{ + Table: table, Port: 18081, OutQueue: 300, InQueue: 301, Mark: 0x67656e, + Outbound: nftables.Selector{Any: true}, Inbound: nftables.Selector{Any: true}, + }) + if err := stale.Install(ctx); err != nil { + t.Fatalf("install stale table: %v", err) + } + t.Cleanup(func() { _ = stale.Remove(ctx) }) + if !testutil.TableExists(t, table) { + t.Fatal("stale table absent after install") + } + + // Start with no strategy. Iface is empty so the NIC is left alone. + eng, err := engine.New("") + if err != nil { + t.Fatalf("engine.New: %v", err) + } + ctrl := New(eng, Config{Mode: "eval", NFT: nftables.Config{Table: table, Port: 18081, OutQueue: 300, InQueue: 301, Mark: 0x67656e}}, nil) + if err := ctrl.Start(ctx); err != nil { + t.Fatalf("Start: %v", err) + } + if testutil.TableExists(t, table) { + t.Error("stale table survived a start with no strategy: the box is steering with nothing to apply") + } + if st := ctrl.State(); st.Steering { + t.Errorf("State reports steering with no strategy: %+v", st) + } +} diff --git a/internal/steering/scope.go b/internal/steering/scope.go new file mode 100644 index 0000000..897bf0e --- /dev/null +++ b/internal/steering/scope.go @@ -0,0 +1,146 @@ +// Package steering decides which packets have to reach userspace and keeps the +// kernel's view in sync with the loaded strategy. +// +// The sidecar's cost is not the strategy — it is the NFQUEUE round trip. Every +// steered packet is copied to userspace, decoded, handed to the engine and +// verdicted, and on a small VPS that dominates the box's CPU: measured on a +// 1-vCPU staging box, a bulk transfer fell from 105 MB/s to 25 MB/s with the +// sidecar running and *no strategy at all*, while a strategy that duplicated +// every data packet cost only ~4 MB/s beyond that. +// +// The fix is to queue only what a strategy could possibly act on. A Geneva +// strategy is a list of (trigger, action tree) pairs, and a packet that matches +// no trigger comes back out byte-for-byte — so filtering those packets in the +// kernel is not an approximation, it is the same result reached without the +// round trip. Most real strategies trigger on TCP flags (the handshake), which +// nftables can match directly, so bulk data never leaves the kernel at all. +// +// Scoping is also what makes an empty strategy free: no trees means nothing can +// match, which means no rules, which means no steering. +package steering + +import ( + "strconv" + "strings" + + "github.com/getlantern/geneva/actions" + "github.com/getlantern/geneva/strategy" + + "github.com/getlantern/geneva-server/internal/nftables" +) + +// Scope is the per-direction description of what a strategy can act on. It is +// expressed in the selectors nftables programs, so deriving a scope and +// programming the kernel share one vocabulary. +type Scope struct { + Outbound nftables.Selector + Inbound nftables.Selector +} + +// Idle reports whether the strategy can act on nothing at all, in which case no +// steering rules are needed and the sidecar has no effect on the box. +func (s Scope) Idle() bool { return s.Outbound.Empty() && s.Inbound.Empty() } + +// tcpFlagBits maps Geneva's flag letters to the bits of the TCP flags byte, in +// nftables' order. Geneva also understands 'N' (the NS bit), which lives in the +// reserved nibble rather than the flags byte, so a trigger naming it cannot be +// expressed as a flags match and falls back to Any. +var tcpFlagBits = map[rune]uint8{ + 'F': 0x01, // fin + 'S': 0x02, // syn + 'R': 0x04, // rst + 'P': 0x08, // psh + 'A': 0x10, // ack + 'U': 0x20, // urg + 'E': 0x40, // ecn + 'C': 0x80, // cwr +} + +// Of derives the scope of a parsed strategy. A nil strategy, or one with no +// action trees, yields a scope that steers nothing. +func Of(s *strategy.Strategy) Scope { + if s == nil { + return Scope{} + } + return Scope{ + Outbound: selectorOf(s.Outbound), + Inbound: selectorOf(s.Inbound), + } +} + +func selectorOf(f strategy.Forest) nftables.Selector { + var sel nftables.Selector + for _, tree := range f { + if tree == nil || tree.Trigger == nil { + continue + } + m, ok := flagMatchOf(tree) + if !ok { + // One unexpressible trigger widens the whole direction: the kernel + // cannot decide what this forest cares about, so it must ask. + return nftables.Selector{Any: true} + } + sel.Flags = append(sel.Flags, m) + } + return sel +} + +// flagMatchOf reduces one action tree's trigger to a flags match, reporting +// false when it cannot be expressed. +// +// The trigger's value is read back out of its String() form. That is the DNA +// serialization every strategy already round-trips through — it is the wire +// format, not a debug rendering — and the upstream trigger types keep their +// value field private. +func flagMatchOf(tree *actions.ActionTree) (nftables.FlagMatch, bool) { + t := tree.Trigger + if t.Protocol() != "TCP" || t.Field() != "flags" { + return nftables.FlagMatch{}, false + } + value, ok := triggerValue(t.String()) + if !ok { + return nftables.FlagMatch{}, false + } + + wildcard := strings.HasSuffix(value, "*") + value = strings.TrimSuffix(value, "*") + if value == "" { + return nftables.FlagMatch{}, false + } + + var want uint8 + for _, c := range value { + bit, ok := tcpFlagBits[c] + if !ok { + return nftables.FlagMatch{}, false + } + want |= bit + } + if wildcard { + // "these bits set, others free" + return nftables.FlagMatch{Mask: want, Value: want}, true + } + // Exact equality over the whole flags byte. Geneva's non-wildcard flags + // match is equality, not "contains": `[TCP:flags:S]` does not fire on a + // SYN-ACK. + return nftables.FlagMatch{Mask: 0xff, Value: want}, true +} + +// triggerValue extracts the value from a serialized trigger, i.e. "S" from +// "[TCP:flags:S]" and "S" from "[TCP:flags:S:3]" (the trailing field is gas). +func triggerValue(s string) (string, bool) { + s = strings.TrimSuffix(strings.TrimPrefix(s, "["), "]") + parts := strings.SplitN(s, ":", 3) + if len(parts) != 3 { + return "", false + } + value := parts[2] + // Gas is a trailing ":". Flag values never contain a colon themselves, + // so splitting from the right is unambiguous for the fields we reduce. + if i := strings.LastIndex(value, ":"); i >= 0 { + if _, err := strconv.Atoi(value[i+1:]); err == nil { + value = value[:i] + } + } + return value, true +} diff --git a/internal/steering/scope_test.go b/internal/steering/scope_test.go new file mode 100644 index 0000000..f6398ee --- /dev/null +++ b/internal/steering/scope_test.go @@ -0,0 +1,178 @@ +package steering + +import ( + "testing" + + "github.com/getlantern/geneva" + "github.com/getlantern/geneva/strategy" + + "github.com/getlantern/geneva-server/internal/engine" + "github.com/getlantern/geneva-server/internal/nftables" + "github.com/getlantern/geneva-server/internal/testutil" +) + +func mustScope(t *testing.T, dna string) Scope { + t.Helper() + s, err := geneva.NewStrategy(dna) + if err != nil { + t.Fatalf("parse %q: %v", dna, err) + } + return Of(s) +} + +func TestScopeOf(t *testing.T) { + cases := []struct { + name string + dna string + outbound nftables.Selector + inbound nftables.Selector + }{ + { + // The state an eval box boots in and the state a rollback leaves a + // prod box in. Nothing may be steered. + name: "empty", + }, + { + name: "handshake outbound", + dna: `[TCP:flags:S]-duplicate-| \/`, + outbound: nftables.Selector{Flags: []nftables.FlagMatch{{Mask: 0xff, Value: 0x02}}}, + }, + { + // Geneva's non-wildcard flags trigger is equality, so the mask + // covers the whole byte: [TCP:flags:S] must not fire on SYN-ACK. + name: "handshake with gas", + dna: `[TCP:flags:S:3]-duplicate-| \/`, + outbound: nftables.Selector{Flags: []nftables.FlagMatch{{Mask: 0xff, Value: 0x02}}}, + }, + { + name: "wildcard is a subset match", + dna: `[TCP:flags:S*]-duplicate-| \/`, + outbound: nftables.Selector{Flags: []nftables.FlagMatch{{Mask: 0x02, Value: 0x02}}}, + }, + { + name: "inbound only", + dna: `\/ [TCP:flags:R]-drop-|`, + inbound: nftables.Selector{Flags: []nftables.FlagMatch{{Mask: 0xff, Value: 0x04}}}, + }, + { + // A payload trigger cannot be expressed in nftables, so the whole + // direction widens to everything rather than guessing. + name: "payload trigger widens to any", + dna: `[TCP:load:GET]-duplicate-| \/`, + outbound: nftables.Selector{Any: true}, + }, + { + name: "ip trigger widens to any", + dna: `[IP:ttl:64]-duplicate-| \/`, + outbound: nftables.Selector{Any: true}, + }, + { + // One unexpressible trigger poisons its direction even when a + // sibling tree is narrow: the kernel cannot tell them apart. + name: "mixed forest widens to any", + dna: `[TCP:flags:S]-duplicate-|[TCP:load:GET]-drop-| \/`, + outbound: nftables.Selector{Any: true}, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := mustScope(t, c.dna) + assertSelector(t, "outbound", got.Outbound, c.outbound) + assertSelector(t, "inbound", got.Inbound, c.inbound) + wantIdle := c.outbound.Empty() && c.inbound.Empty() + if got.Idle() != wantIdle { + t.Errorf("Idle() = %v, want %v", got.Idle(), wantIdle) + } + }) + } +} + +func assertSelector(t *testing.T, dir string, got, want nftables.Selector) { + t.Helper() + if got.Any != want.Any { + t.Errorf("%s Any = %v, want %v", dir, got.Any, want.Any) + } + if len(got.Flags) != len(want.Flags) { + t.Fatalf("%s flags = %+v, want %+v", dir, got.Flags, want.Flags) + } + for i := range want.Flags { + if got.Flags[i] != want.Flags[i] { + t.Errorf("%s flags[%d] = %+v, want %+v", dir, i, got.Flags[i], want.Flags[i]) + } + } +} + +// TestScopeNeverNarrowerThanStrategy is the invariant the whole optimization +// rests on: a packet the kernel filters out must be a packet the engine would +// have handed back byte-for-byte anyway. If this test can find a packet that the +// selector rejects but the strategy modifies, scoping is silently dropping +// manipulations and the strategy is not being applied. +func TestScopeNeverNarrowerThanStrategy(t *testing.T) { + dnas := []string{ + "", + `[TCP:flags:S]-duplicate-| \/`, + `[TCP:flags:S*]-duplicate-| \/`, + `[TCP:flags:SA]-tamper{TCP:flags:replace:R}-| \/`, + `[TCP:flags:PA]-duplicate-| \/`, + `[TCP:flags:F*]-drop-| \/`, + `[TCP:flags:S]-duplicate-|[TCP:flags:R]-drop-| \/`, + `[TCP:load:GET]-duplicate-| \/`, + `\/ [TCP:flags:R]-drop-|`, + } + packets := []struct { + name string + flags uint8 + raw []byte + }{ + {"syn", 0x02, testutil.BuildTCP(t, 1, testutil.TCPFlags{SYN: true}, nil)}, + {"syn-ack", 0x12, testutil.BuildTCP(t, 1, testutil.TCPFlags{SYN: true, ACK: true}, nil)}, + {"ack", 0x10, testutil.BuildTCP(t, 1, testutil.TCPFlags{ACK: true}, nil)}, + {"psh-ack-data", 0x18, testutil.BuildTCP(t, 1, testutil.TCPFlags{PSH: true, ACK: true}, []byte("GET"))}, + {"rst", 0x04, testutil.BuildTCP(t, 1, testutil.TCPFlags{RST: true}, nil)}, + {"fin-ack", 0x11, testutil.BuildTCP(t, 1, testutil.TCPFlags{FIN: true, ACK: true}, nil)}, + } + + for _, dna := range dnas { + for _, dir := range []strategy.Direction{strategy.DirectionOutbound, strategy.DirectionInbound} { + sc := mustScope(t, dna) + sel := sc.Outbound + if dir == strategy.DirectionInbound { + sel = sc.Inbound + } + for _, p := range packets { + if selectorMatches(sel, p.flags) { + continue // the kernel would queue it; nothing to prove + } + // A fresh engine per packet: triggers consume gas, and a + // shared engine would let one case mask another. + e, err := engine.New(dna) + if err != nil { + t.Fatalf("engine.New(%q): %v", dna, err) + } + res, err := e.Process(p.raw, dir, nil) + if err != nil { + t.Fatalf("dna=%q %s %s: Process: %v", dna, dir, p.name, err) + } + if res.Outcome != engine.OutcomeUnchanged { + t.Errorf("dna=%q %s %s: filtered by scope but engine returned %s — scoping would drop this manipulation", + dna, dir, p.name, res.Outcome) + } + } + } + } +} + +// selectorMatches mirrors what the nftables rules do, so the test compares the +// kernel's decision against the engine's rather than against itself. +func selectorMatches(sel nftables.Selector, flags uint8) bool { + if sel.Any { + return true + } + for _, f := range sel.Flags { + if flags&f.Mask == f.Value { + return true + } + } + return false +} diff --git a/internal/telemetry/metrics.go b/internal/telemetry/metrics.go index bce30b3..018df01 100644 --- a/internal/telemetry/metrics.go +++ b/internal/telemetry/metrics.go @@ -38,8 +38,10 @@ type Providers struct { Market string // Engine is required. Engine *engine.Engine - // Censor is the inbound TCP observer. Nil disables the censor metric. - Censor *censor.Observer + // Censor is where the inbound TCP counts come from — the kernel's + // classification counters on a box that has them, the userspace classifier + // otherwise. Nil disables the censor metric. + Censor censor.Source // Verdicts reads the runtime's counters. Nil disables the verdict metrics // (the runtime is not up yet, or this is a non-Linux build). Verdicts func() Verdicts diff --git a/internal/testutil/testutil.go b/internal/testutil/testutil.go new file mode 100644 index 0000000..cb371f1 --- /dev/null +++ b/internal/testutil/testutil.go @@ -0,0 +1,61 @@ +// Package testutil holds test helpers shared by the packages that build +// packets for the engine and program nftables. It is imported only from tests. +package testutil + +import ( + "os/exec" + "strings" + "testing" + + "github.com/gopacket/gopacket" + "github.com/gopacket/gopacket/layers" +) + +// TCPFlags selects the flag bits BuildTCP sets on the packet. +type TCPFlags struct{ SYN, ACK, PSH, RST, FIN bool } + +// BuildTCP builds a serialized IPv4/TCP packet with a valid checksum and length. +func BuildTCP(t testing.TB, seq uint32, flags TCPFlags, payload []byte) []byte { + t.Helper() + ip := &layers.IPv4{ + Version: 4, + IHL: 5, + TTL: 64, + Id: 1234, + Protocol: layers.IPProtocolTCP, + SrcIP: []byte{10, 0, 0, 1}, + DstIP: []byte{10, 0, 0, 2}, + } + tcp := &layers.TCP{ + SrcPort: 8080, + DstPort: 44000, + Seq: seq, + Window: 65535, + SYN: flags.SYN, + ACK: flags.ACK, + PSH: flags.PSH, + RST: flags.RST, + FIN: flags.FIN, + } + if err := tcp.SetNetworkLayerForChecksum(ip); err != nil { + t.Fatalf("set network layer: %v", err) + } + buf := gopacket.NewSerializeBuffer() + opts := gopacket.SerializeOptions{ComputeChecksums: true, FixLengths: true} + if err := gopacket.SerializeLayers(buf, opts, ip, tcp, gopacket.Payload(payload)); err != nil { + t.Fatalf("serialize: %v", err) + } + return buf.Bytes() +} + +// TableExists reports whether an inet nftables table of the given name is +// currently installed. It shells out to nft, so callers must already have +// established that nft is present and the test may touch the kernel. +func TableExists(t testing.TB, name string) bool { + t.Helper() + out, err := exec.Command("nft", "list", "tables", "inet").CombinedOutput() + if err != nil { + t.Fatalf("nft list tables: %v: %s", err, out) + } + return strings.Contains(string(out), "table inet "+name) +} diff --git a/scripts/harness-lib.sh b/scripts/harness-lib.sh new file mode 100644 index 0000000..d1d66e2 --- /dev/null +++ b/scripts/harness-lib.sh @@ -0,0 +1,28 @@ +# Shared helpers for the docker-compose harnesses (e2e/run.sh, bench/run.sh). +# Source after setting COMPOSE to the compose invocation array; sourcing +# installs the KEEP-aware teardown trap. + +step() { printf '\n\033[1m==> %s\033[0m\n' "$1"; } +pass() { printf ' \033[32mPASS\033[0m %s\n' "$1"; } +fail() { printf ' \033[31mFAIL\033[0m %s\n' "$1"; exit 1; } + +harness_cleanup() { + if [[ "${KEEP:-0}" != "1" ]]; then + "${COMPOSE[@]}" --profile tools down -v --remove-orphans >/dev/null 2>&1 || true + fi +} +trap harness_cleanup EXIT + +# wait_healthy polls the sidecar control surface from inside the +# given container for up to 30 seconds. Returns non-zero if it never comes up, +# so the caller decides how loudly to fail. +wait_healthy() { + local via="$1" + for _ in $(seq 1 30); do + if "${COMPOSE[@]}" exec -T "$via" curl -fsS http://server:8092/healthz >/dev/null 2>&1; then + return 0 + fi + sleep 1 + done + return 1 +}