Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
- **Strings from tenants and the network are cleaned.** Container names and images, a tenant's interface names, LLDP and NIC strings, the ASN feed's network owner, netns names and congestion names are cut to 256 bytes (16 for interface and congestion names) at a UTF-8 boundary. Invalid UTF-8 and control characters (C0, DEL, C1) become U+FFFD. Each is cleaned once, where it enters, not per row.
- **Per-namespace caps.** `-maxDumpBytes` (default 256 MiB) and `-maxRecordsPerNetns` (default 262144) bound one namespace's dump per poll: packets past the byte cap are drained undecoded, and records past the record cap are dropped before decode. `-maxNetns` (default 4096) bounds the namespaces tracked. At the cap, tracked namespaces keep their slots, and new ones wait for a freed slot, first come, first served. Alert on `xtcp_netns_dropped_total`. Drops are counted in `xtcp_dump_dropped_total{reason}` and `xtcp_netns_dropped_total`, with one log line per truncated dump or short reconcile. `0` turns a cap off; the matching env vars are `MAX_DUMP_BYTES`, `MAX_RECORDS_PER_NETNS` and `MAX_NETNS`. The caps are startup-only: `ConfigService.Set` keeps the running values. No healthy host should reach the defaults; a host that does now loses that namespace's excess rows, where it used to collect them all ([polling and batching](docs/polling-and-batching.md#per-namespace-caps)).
- **Socket-count gate, reconcile limits, per-owner quota.** Before each poll xtcp2 reads each namespace's sockstat (an fd opened in the namespace; `pread`, or io_uring batches with `-ioUring`) and, when the total is over `-maxRecordsPerPoll` (default 1,048,576), degrades only the namespaces over their fair share: first TIME_WAIT/SYN_RECV are not asked for, then one of K port shards is dumped per poll. `-maxNetnsPerOwner` (default 64) caps namespaces tracked per owner (the container runtime's cgroup), `-maxNetnsAddsPerReconcile` (256) the adds per reconcile, and `-reconcileTimeout` (1s) the namespace scan; a timed-out scan deletes nothing. New metrics `xtcp_poll_sockets`, `xtcp_poll_degraded_total{level}` and `xtcp_reconcile_incomplete_total{reason}`; `xtcp_netns_dropped_total` gains `reason`. `0` turns each off; all are startup-only. Each tracked namespace now holds four fds (was two: sockstat and `ip_local_port_range` are new), and xtcp2 warns at startup when `RLIMIT_NOFILE` can't cover them ([polling and batching](docs/polling-and-batching.md#socket-count-gate), [network namespaces](docs/network-namespaces.md#configuration)). The analysis behind an upstream all-namespace dump is in [docs/kernel](docs/kernel/inet-diag-all-netns.md).
- **Fuzzing in CI.** `fuzz-all` (dev shell) finds every Go fuzz target with `go test -list` and fuzzes each in turn: 10 s per target on each PR, 2 min nightly (`.github/workflows/fuzz.yml`), with crashers uploaded as an artifact. Two new fuzzers cover tenant-reachable paths: `FuzzDockerProjection` (a Docker inspect body to a container's name and image) and `FuzzRowFromProto` (an S3 envelope through Parquet and back). `FuzzClean` now also checks idempotence and the fast path. The first run found `/ip/vrf/show/NAME` returning 500 for a name that is no VRF; it is now a 404. Docker API response bodies are now capped per endpoint, and an oversized `/events` line no longer stalls container-metadata refresh.
- **Fuzzing in CI.** `fuzz-all` (dev shell) finds every Go fuzz target with `go test -list` and fuzzes each in turn: 10 s per target on each PR, 2 min nightly (`.github/workflows/fuzz.yml`), with crashers uploaded as an artifact. Two new fuzzers cover tenant-reachable paths: `FuzzDockerProjection` (a Docker inspect body to a container's name and image) and `FuzzRowFromProto` (an S3 envelope through Parquet and back). `FuzzClean` now also checks idempotence and the fast path. The first run found `/ip/vrf/show/NAME` returning 500 for a name that is no VRF; it is now a 404. Docker container list and inspect bodies are now streamed, keeping only the fields used: memory stays bounded however large a container's labels are, a container whose entry passes 4 MiB is skipped and logged (never the whole list), each request has a 10 s timeout, and an oversized `/events` line no longer stalls container-metadata refresh. Limits: [Docker API limits](docs/design-metadata-enrichment.md#docker-api-limits).
- **Vulnerability check.** `checks.govulncheck` runs govulncheck against a pinned snapshot of the Go vulnerability database, with no tags and with every flavor tag, and fails on a reachable finding not in its accepted list. One is accepted: GO-2026-6859 in `net/http`, fixed in go1.27.4, until the toolchain moves. `nix run .#govulncheck-fresh` checks against the live database and runs `go mod verify`; `nix build .#sbom-<binary>` writes a CycloneDX SBOM for any binary package.

## 0.2.1 (2026-11)
Expand Down
27 changes: 27 additions & 0 deletions docs/design-metadata-enrichment.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,33 @@ usable routes count (up, not reject, not on `lo`: every host has the kernel's
bridge) is replaced by the physical NICs under its `lower_*` sysfs links, since
those carry the NIC attributes and the LLDP neighbours.

### Docker API limits

Docker's list and inspect bodies carry tenant-chosen data (image labels, the
container name), so `pkg/dockermeta` streams them (`jsonwalk.go`): it keeps only
Id, Name, Image, `State.Pid` and `NetworkSettings.SandboxKey`, and validates and
discards everything else, labels included, without buffering it. Memory is about
37 KiB per body whatever its size. The limits bound CPU and are constants:

| Constant | Value | Applies to | Over the limit |
|---|---|---|---|
| `maxInspectBody` | 4 MiB | one `GET /containers/{id}/json` | that container is skipped (logged) |
| `maxListEntry` | 4 MiB | one container's entry in `GET /containers/json` | that entry is dropped (logged); the list still builds |
| `maxIDRaw` | 4 KiB | `Id`, `SandboxKey` (set by the daemon) | that container is skipped (logged) |
| `maxTextRaw` | 4 KiB | `Name`, `Image` | cut; `strpolicy.Clean` then cuts to 256 bytes |
| `maxVersionBody` | 64 KiB | `GET /version` | version negotiation falls back to unversioned paths |
| `requestTimeout` | 10 s | every list, inspect and version request | the request fails: a skipped container, or a failed re-list that keeps the previous index |
| `maxDrain` | 64 KiB | the unread rest of any body | the connection is closed instead of reused |

Measured on a host with 31 containers: inspect bodies are 6.8–13.7 KB (labels at
most 638 B) and the list is about 2.5 KB per container, so 4 MiB is about 300×
the largest. The list has no total limit on purpose: a total would let a few
padded containers fail every re-list for the whole host. A tenant can make
its own container unattributed by padding its image labels past 4 MiB, and
nothing more; each walk costs about 27 ms at that size. `/events` is a stream
and has no timeout; a line over 1 MiB ends it and the index falls back to
re-listing.

## 3. Config: flags / env / config protobuf

Precedence: **defaults < flags < env < `XTCP_CONFIG_JSON`** (`cmd/xtcp2/xtcp2.go`).
Expand Down
1 change: 1 addition & 0 deletions docs/security-hardening/focused-container-hardening.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ Author and publish this as the reference `docker-compose`/OCI config (none exist
| C2 | **(code)** Cap the number of tracked namespaces (`-maxNetns`), oldest-idle eviction, counter. | Bounded goroutines, sockets and memory. |
| C3 | **(code)** Explicit, metered S3 queue depth and total buffered bytes; when full, drop oldest with a counter rather than grow. | Memory bound under S3 outage. |
| C4 | **(code)** String policy in `rowFromProto` and the JSON/line marshallers for every tenant- or host-influenced string column (`container_name`, `container_image`, `label`, `*_lldp_chassis_name`, congestion-control name): max length (e.g. 256), valid UTF-8, control characters replaced. Same policy in log lines. | Keeps Parquet objects and logs predictable; stops log injection. |
| C5 | **(code)** Docker API bodies streamed, not buffered: list and inspect keep only the projected fields and skip the rest (labels) unbuffered; per-container limits (`maxInspectBody`, `maxListEntry`, 4 MiB), a 10 s `requestTimeout`, a bounded drain. Values and rationale: [Docker API limits](../design-metadata-enrichment.md#docker-api-limits). | A tenant's image labels can cost at most its own container's attribution, never another's, and never collector memory. |

### D. Build and supply chain

Expand Down
2 changes: 1 addition & 1 deletion docs/security-hardening/focused-implementation-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ Non-blocking shortfalls found while implementing F1; none blocks R1.
| Fix `RegisterIOWQMaxWorkers` signature in the giouring fork | giouring PR |
| Upstream RFC for an all-namespace inet_diag dump, only after the VM numbers and a lore.kernel.org search | F2 follow-up |
| Add the scrubbed F0.5 Parquet rows as `FuzzRowFromProto` seeds once F0.5 is captured | FP-7 follow-up |
| ~~Cap `dockermeta.getJSON`'s body~~ done in #312: per-endpoint caps (`/version` 64 KiB, `/containers/json` 32 MiB, inspect 1 MiB; over the cap the container is skipped or the re-list fails), and `drainClose` now discards at most 64 KiB: an `/events` line over the scanner's 1 MiB used to block the refresh goroutine draining the endless stream | — |
| ~~Cap `dockermeta.getJSON`'s body~~ done in #312 as focused design C5, a walk rather than a cap: a whole-body cap let a tenant image pad its labels to hide its container (inspect) or freeze the host's index (list). `jsonwalk.go` keeps only the projected fields and skips the rest unbuffered, with encoding/json's accept/reject (`FuzzDockerProjection`, `FuzzDecodeIDs` are differential). Limits: 4 MiB per inspect and per list entry, no list total, 10 s per request, 64 KiB drain ([Docker API limits](../design-metadata-enrichment.md#docker-api-limits)). The drain fix: an `/events` line over 1 MiB used to block the refresh goroutine draining the endless stream | — |
| Re-tune the three caps' defaults from the F0.6 baseline (≥ 10× p99) | F0.6 |
| The F2 gate's 1 M-socket synthetic netns run | after FP-6 |

Expand Down
76 changes: 56 additions & 20 deletions pkg/dockermeta/dockermeta.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,16 @@ const relistInterval = 30 * time.Second
// back to a re-list) after it errors or closes.
const eventsRetryDelay = time.Second

// Response body caps. The daemon is trusted, but container names, images and
// labels in its bodies are the tenant's choice, so each read is bounded.
// Response body bounds. The list and inspect bodies carry tenant-chosen
// labels, so they are walked, not capped (see jsonwalk.go).
const (
// maxVersionBody caps GET /version, a few hundred bytes in practice.
// maxVersionBody caps GET /version, a few hundred bytes and no tenant
// data, so a plain cap is safe.
maxVersionBody = 64 << 10
// maxListBody caps GET /containers/json: one summary per running
// container, labels included (a few KB each), so it scales with the host.
maxListBody = 32 << 20
// maxInspectBody caps GET /containers/{id}/json for one container.
maxInspectBody = 1 << 20
// requestTimeout bounds one list, inspect or version request, so a body
// that trickles in cannot stall the refresh goroutine. Not /events,
// which is a stream by design.
requestTimeout = 10 * time.Second
// maxDrain caps how much of an unread body drainClose discards for
// connection reuse; past it the connection is closed instead. /events
// never ends, so an unbounded drain there would block forever.
Expand Down Expand Up @@ -240,11 +240,6 @@ func splitVersion(s string) []int {
return out
}

// containerRef is one entry of GET /containers/json.
type containerRef struct {
ID string `json:"Id"`
}

// inspect is the subset of GET /containers/{id}/json we decode.
type inspect struct {
ID string `json:"Id"`
Expand All @@ -266,16 +261,25 @@ type inspect struct {
// per-container inspect failures are skipped so one bad container can't sink
// the whole index.
func (ix *Index) build(ctx context.Context) (map[uint64]Container, error) {
var refs []containerRef
if err := getJSON(ctx, ix.client, ix.baseURL+"/containers/json", maxListBody, &refs); err != nil {
var ids []string
dropped := 0
err := walkJSON(ctx, ix.client, ix.baseURL+"/containers/json", func(r io.Reader) error {
var err error
ids, dropped, err = decodeIDs(r, noLimit, maxListEntry)
return err
})
if err != nil {
return nil, fmt.Errorf("list containers: %w", err)
}
m := make(map[uint64]Container, len(refs))
for _, ref := range refs {
if ref.ID == "" {
if dropped > 0 {
log.Printf("dockermeta: list: %d container(s) skipped: entry over %d bytes or Id over %d", dropped, maxListEntry, maxIDRaw)
}
m := make(map[uint64]Container, len(ids))
for _, id := range ids {
if id == "" {
continue
}
if c, ok := ix.inspect(ctx, ref.ID); ok {
if c, ok := ix.inspect(ctx, id); ok {
m[c.NetnsInode] = c
}
}
Expand All @@ -287,7 +291,17 @@ func (ix *Index) build(ctx context.Context) (map[uint64]Container, error) {
// (host network), or an unresolvable inode.
func (ix *Index) inspect(ctx context.Context, id string) (Container, bool) {
var in inspect
if err := getJSON(ctx, ix.client, ix.baseURL+"/containers/"+id+"/json", maxInspectBody, &in); err != nil {
err := walkJSON(ctx, ix.client, ix.baseURL+"/containers/"+id+"/json", func(r io.Reader) error {
var err error
in, err = decodeInspect(r, maxInspectBody)
return err
})
if err != nil {
// A size refusal is worth seeing: it is the one skip a body's
// content can force. Other errors (gone, malformed) stay quiet.
if errors.Is(err, errBodyTooLarge) || errors.Is(err, errFieldTooLong) {
log.Printf("dockermeta: inspect %.12s skipped: %v", id, err)
}
return Container{}, false
}
return project(in, ix.stat)
Expand Down Expand Up @@ -425,10 +439,32 @@ func (ix *Index) rebuild(ctx context.Context) {
ix.snapshot.Store(&m)
}

// walkJSON does a GET and hands a 2xx body to decode. A non-2xx status is an
// error without reading the body.
func walkJSON(ctx context.Context, client *http.Client, url string, decode func(io.Reader) error) error {
ctx, cancel := context.WithTimeout(ctx, requestTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer drainClose(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("GET %s: status %d", url, resp.StatusCode)
}
return decode(resp.Body)
}

// getJSON does a GET and decodes the JSON body into v. A non-2xx status, a
// body over limit bytes (errBodyTooLarge) or a decode error is returned so
// callers can skip/fall back.
func getJSON(ctx context.Context, client *http.Client, url string, limit int64, v any) error {
ctx, cancel := context.WithTimeout(ctx, requestTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
Expand Down
18 changes: 9 additions & 9 deletions pkg/dockermeta/dockermeta_fuzz_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package dockermeta

import (
"encoding/json"
"errors"
"os"
"path/filepath"
Expand Down Expand Up @@ -191,15 +190,15 @@ func TestDockerProjectionJSON(t *testing.T) {
if err != nil {
t.Fatalf("%s: %v", tc.name, err)
}
var in inspect
if err := json.Unmarshal(data, &in); err != nil {
in, err := checkInspectParity(t, data)
if err != nil {
if !tc.expected.unmarshalErr {
t.Fatalf("%s: unmarshal: %v", tc.description, err)
t.Fatalf("%s: decode: %v", tc.description, err)
}
return
}
if tc.expected.unmarshalErr {
t.Fatalf("%s: unmarshal succeeded, expected an error", tc.description)
t.Fatalf("%s: decode succeeded, expected an error", tc.description)
}
c, ok := project(in, fakeStat)
got := projectionWant{ok: ok, name: c.Name, image: c.Image, pid: c.Pid}
Expand All @@ -213,10 +212,11 @@ func TestDockerProjectionJSON(t *testing.T) {
}
}

// FuzzDockerProjection feeds arbitrary inspect bodies through json.Unmarshal
// FuzzDockerProjection feeds arbitrary inspect bodies through decodeInspect
// and project. The Docker daemon is trusted, but the container name and image
// are the tenant's choice, so whatever they hold must come out as bounded,
// valid UTF-8 without control runes.
// valid UTF-8 without control runes. decodeInspect must also accept and
// project exactly what encoding/json would (checkInspectParity).
//
// go test -run '^$' -fuzz '^FuzzDockerProjection$' -fuzztime=30s ./pkg/dockermeta/
func FuzzDockerProjection(f *testing.F) {
Expand All @@ -229,8 +229,8 @@ func FuzzDockerProjection(f *testing.F) {
f.Add(data)
}
f.Fuzz(func(t *testing.T, data []byte) {
var in inspect
if err := json.Unmarshal(data, &in); err != nil {
in, err := checkInspectParity(t, data)
if err != nil {
return
}
c, ok := project(in, fuzzStat)
Expand Down
Loading