diff --git a/internal/capture/filter.go b/internal/capture/filter.go index 6c210de..a3cd618 100644 --- a/internal/capture/filter.go +++ b/internal/capture/filter.go @@ -30,30 +30,40 @@ type Filter struct { // game traffic and control-plane traffic included. Rejecting these keywords // outright is the only honest behaviour available to us; go-pcap gives no // signal we could surface instead. +// +// The same applies to the non-protocol qualifiers go-pcap ignores: portrange +// compiles to an unconditional keep (so "tcp port 1 or portrange 1-65535" +// captured everything), less and greater are silently treated as a port test, +// and broadcast and multicast are ignored entirely. var unsupportedProtocolKeywords = map[string]struct{}{ - "aarp": {}, - "ah": {}, - "atalk": {}, - "decnet": {}, - "decnett": {}, - "esp": {}, - "fddi": {}, - "icmp": {}, - "icmp6": {}, - "igmp": {}, - "igrp": {}, - "ipx": {}, - "iso": {}, - "lat": {}, - "modpl": {}, - "morpc": {}, - "netbeui": {}, - "pim": {}, - "sca": {}, - "stp": {}, - "tr": {}, - "vrrp": {}, - "wlan": {}, + "aarp": {}, + "ah": {}, + "atalk": {}, + "broadcast": {}, + "decnet": {}, + "decnett": {}, + "esp": {}, + "fddi": {}, + "greater": {}, + "icmp": {}, + "icmp6": {}, + "igmp": {}, + "igrp": {}, + "ipx": {}, + "iso": {}, + "lat": {}, + "less": {}, + "modpl": {}, + "morpc": {}, + "multicast": {}, + "netbeui": {}, + "pim": {}, + "portrange": {}, + "sca": {}, + "stp": {}, + "tr": {}, + "vrrp": {}, + "wlan": {}, } // CompileFilter validates and compiles a BPF filter expression. @@ -92,6 +102,9 @@ func CompileFilter(expr string) (*Filter, error) { if !testsPacketContents(instructions) { return nil, fmt.Errorf("invalid filter: %q compiled to a program with no packet test, so it would not restrict the capture at all", expr) } + if !canDrop(instructions) { + return nil, fmt.Errorf("invalid filter: %q compiled to a program that keeps every packet, so it would not restrict the capture at all", expr) + } return &Filter{ instructions: instructions, @@ -133,6 +146,48 @@ func testsPacketContents(prog []bpf.Instruction) bool { return false } +// canDrop reports whether some packet can reach a drop verdict: a RetConstant +// returning 0 that is reachable from instruction 0 along some execution path. +// A RetA is treated as able to drop, since its value depends on the packet. +// The walk is a structural backstop for any future qualifier go-pcap ignores +// inside an "or", where the program can keep every packet even though it +// contains conditional branches (see testsPacketContents). +func canDrop(prog []bpf.Instruction) bool { + if len(prog) == 0 { + return false + } + visited := make([]bool, len(prog)) + stack := []int{0} + for len(stack) > 0 { + i := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if i < 0 || i >= len(prog) || visited[i] { + continue + } + visited[i] = true + + var next []int + switch ins := prog[i].(type) { + case bpf.JumpIf: + next = []int{i + 1 + int(ins.SkipTrue), i + 1 + int(ins.SkipFalse)} + case bpf.JumpIfX: + next = []int{i + 1 + int(ins.SkipTrue), i + 1 + int(ins.SkipFalse)} + case bpf.Jump: + next = []int{i + 1 + int(ins.Skip)} + case bpf.RetConstant: + if ins.Val == 0 { + return true + } + case bpf.RetA: + return true + default: + next = []int{i + 1} + } + stack = append(stack, next...) + } + return false +} + // Expression returns the original filter expression string. func (f *Filter) Expression() string { return f.expr diff --git a/internal/capture/filter_test.go b/internal/capture/filter_test.go index 55f3356..9302b38 100644 --- a/internal/capture/filter_test.go +++ b/internal/capture/filter_test.go @@ -147,3 +147,40 @@ func TestCompileFilter_CompiledProgramDiscriminates(t *testing.T) { t.Error("compiled program has no conditional branch; it would match every packet") } } + +// TestCompileFilterRejectsIgnoredQualifiers pins the qualifiers go-pcap parses +// but does not implement: portrange compiles to an unconditional keep, less and +// greater are silently read as port tests, and broadcast is ignored. Each must +// be refused rather than captured as if it had filtered. +func TestCompileFilterRejectsIgnoredQualifiers(t *testing.T) { + tests := []string{ + "tcp port 25565 or portrange 1-65535", + "portrange 1-2", + "tcp port 1 or less 100", + "tcp port 1 or greater 1", + "tcp port 1 or ip broadcast", + } + for _, expr := range tests { + t.Run(expr, func(t *testing.T) { + f, err := CompileFilter(expr) + if err == nil { + t.Fatalf("CompileFilter(%q) succeeded; want a rejection", expr) + } + if f != nil { + t.Error("CompileFilter returned non-nil Filter after error") + } + }) + } +} + +// TestCanDropFindsReachableDrop checks that a normal port filter has a reachable +// drop verdict, so the program-level backstop in CompileFilter accepts it. +func TestCanDropFindsReachableDrop(t *testing.T) { + f, err := CompileFilter("tcp port 25565") + if err != nil { + t.Fatalf("CompileFilter(\"tcp port 25565\") failed: %v", err) + } + if !canDrop(f.Instructions()) { + t.Error("canDrop reported no reachable drop for a restricting filter") + } +} diff --git a/internal/capture/writer.go b/internal/capture/writer.go index 9acf279..1bd8eb9 100644 --- a/internal/capture/writer.go +++ b/internal/capture/writer.go @@ -143,7 +143,10 @@ func NewWriter(filePath string, maxDurationSeconds int64, maxSizeBytes int64, sn // containment check, and a cleaned path also can't carry a redundant // ".." that would otherwise resolve outside whatever directory the // caller intended. - file, err := os.Create(filepath.Clean(filePath)) + // The file is created owner-only (0600) while the capture runs; callers + // widen the mode after finalizing if needed. O_NOFOLLOW means a symlink + // planted at the path is never followed. + file, err := os.OpenFile(filepath.Clean(filePath), os.O_WRONLY|os.O_CREATE|os.O_TRUNC|syscall.O_NOFOLLOW, 0o600) if err != nil { return nil, fmt.Errorf("create capture file %s: %w", filePath, err) } diff --git a/internal/capture/writer_test.go b/internal/capture/writer_test.go index 4f8c24b..78c8747 100644 --- a/internal/capture/writer_test.go +++ b/internal/capture/writer_test.go @@ -14,6 +14,56 @@ import ( const testFilter = "udp port 25565" +// TestNewWriterCreatesOwnerOnlyFile checks that the capture file is created +// with mode 0600 while the capture runs. +func TestNewWriterCreatesOwnerOnlyFile(t *testing.T) { + path := t.TempDir() + "/owner_only.pcapng" + + w, err := NewWriter(path, 300, 1000000, 65535, testFilter) + if err != nil { + t.Fatalf("NewWriter failed: %v", err) + } + if err := w.Close(); err != nil { + t.Fatalf("Close failed: %v", err) + } + + info, err := os.Stat(path) + if err != nil { + t.Fatalf("stat capture file: %v", err) + } + if perm := info.Mode().Perm(); perm != 0o600 { + t.Errorf("capture file perm = %o; want 600", perm) + } +} + +// TestNewWriterRefusesSymlink checks that a symlink planted at the capture path +// is never followed: NewWriter must fail and must not write through it. +func TestNewWriterRefusesSymlink(t *testing.T) { + dir := t.TempDir() + victim := dir + "/victim.txt" + if err := os.WriteFile(victim, []byte("keep"), 0o600); err != nil { + t.Fatalf("write victim: %v", err) + } + link := dir + "/planted.pcapng" + if err := os.Symlink(victim, link); err != nil { + t.Fatalf("symlink: %v", err) + } + + w, err := NewWriter(link, 300, 1000000, 65535, testFilter) + if err == nil { + _ = w.Close() + t.Fatal("NewWriter followed a planted symlink; want error") + } + + got, readErr := os.ReadFile(victim) + if readErr != nil { + t.Fatalf("read victim: %v", readErr) + } + if string(got) != "keep" { + t.Errorf("symlink target was modified: %q", got) + } +} + // TestWriter_NormalStop tests that a normal stop produces a valid file // openable via gopacket's own reader, and that counters are accurate. func TestWriter_NormalStop(t *testing.T) { diff --git a/internal/httpserver/handlers.go b/internal/httpserver/handlers.go index eea5abf..b08fbb4 100644 --- a/internal/httpserver/handlers.go +++ b/internal/httpserver/handlers.go @@ -313,6 +313,11 @@ func validCaptureID(id string) bool { return captureIDPattern.MatchString(id) } +// maxControlBody bounds the JSON body of a start or stop control request. +// Control requests are small JSON, so anything larger is refused rather than +// decoded. +const maxControlBody = 64 << 10 + // captureFilePath returns the on-disk path for a capture's PCAPNG file. // // Every caller of this method has already rejected id with validCaptureID @@ -427,6 +432,7 @@ func (s *Server) HandleStart(w http.ResponseWriter, r *http.Request) { return } + r.Body = http.MaxBytesReader(w, r.Body, maxControlBody) var req startRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "invalid request body", http.StatusBadRequest) @@ -729,6 +735,9 @@ func (s *Server) HandleStop(w http.ResponseWriter, r *http.Request) { return } + if r.Body != nil { + r.Body = http.MaxBytesReader(w, r.Body, maxControlBody) + } var req stopRequest // The body is optional. A client that builds the request without an // explicit ContentLength sends it chunked (ContentLength == -1), so test @@ -859,6 +868,14 @@ func (s *Server) HandleDownload(w http.ResponseWriter, r *http.Request) { http.Error(w, "capture id required", http.StatusBadRequest) return } + // A caller that sends identity headers gets the same identity check as the + // bound route. This mirrors HandleDelete. + if hasControlIdentity(r) { + r.SetPathValue("serverUID", r.Header.Get("X-Gameplane-Server-UID")) + r.SetPathValue("captureUID", r.Header.Get("X-Gameplane-Capture-UID")) + s.HandleBoundDownload(w, r) + return + } s.mu.Lock() running := s.captureBusyLocked(id) diff --git a/specs.md b/specs.md index 4e1d4a0..b4aa6ad 100644 --- a/specs.md +++ b/specs.md @@ -114,9 +114,9 @@ Single Go module; packages organized by responsibility (capture, httpserver, aut **`internal/capture/afpacket.go`**: Establishes AF_PACKET socket via gopacket/afpacket.TPacket with MMap'd kernel buffers. Compiles the filter and prepares its BPF VM before opening the socket, retains kernel filtering, and checks every received frame against the same program before snaplen truncation or output. Reads packets via blocking poll (respecting context cancellation) and writes to PCAPNG writer. Manages socket lifecycle (Create, Start, Stop, Close) and enforces hard size/duration limits. -**`internal/capture/filter.go`**: Compiles BPF filter expressions via github.com/packetcap/go-pcap/filter into bytecode instructions. Validates filter syntax before capture starts (defense-in-depth, complementing API-tier validation). +**`internal/capture/filter.go`**: Compiles BPF filter expressions via github.com/packetcap/go-pcap/filter into bytecode instructions. Validates filter syntax before capture starts (defense-in-depth, complementing API-tier validation). Rejects the protocol and non-protocol qualifiers go-pcap parses but does not implement (`portrange`, `less`, `greater`, `broadcast`, `multicast`, and the unsupported protocol keywords), since go-pcap compiles them to a keep-everything program or silently reads them as a port test. A program with no reachable drop verdict (`canDrop`) is also rejected, as a structural backstop for any future qualifier go-pcap ignores inside an `or`. -**`internal/capture/writer.go`**: Writes captured packets to PCAPNG files via gopacket/pcapgo.NgWriter. Enforces hard size and duration limits (stops immediately when either is reached). Detects disk-full conditions (`ENOSPC`) and stops the capture, marking it `failed`/`disk_full` — the partial file is kept, not deleted, and stays downloadable (see "Edge Cases" below for the verified behavior; this line described intended, not implemented, behavior). Produces valid PCAPNG files readable by `tcpdump`, Wireshark, and other third-party tools. +**`internal/capture/writer.go`**: Writes captured packets to PCAPNG files via gopacket/pcapgo.NgWriter. Enforces hard size and duration limits (stops immediately when either is reached). Detects disk-full conditions (`ENOSPC`) and stops the capture, marking it `failed`/`disk_full` — the partial file is kept, not deleted, and stays downloadable (see "Edge Cases" below for the verified behavior; this line described intended, not implemented, behavior). Produces valid PCAPNG files readable by `tcpdump`, Wireshark, and other third-party tools. The capture file is created with mode `0600` (owner-only) and opened with `O_NOFOLLOW`, so a symlink planted at the path is never followed; callers may widen the mode after finalization. **`internal/httpserver/handlers.go`**: Implements six HTTP endpoints exposed on `:9091`: `POST /captures/{id}/start`, `POST /captures/{id}/stop`, `GET /captures/{id}/status`, `GET /captures/{id}/file`, `DELETE /captures/{id}`, and `GET /healthz` (see Endpoints below for the full table). Validates requests, marshals capture state, and streams completed files to authenticated clients. `HandleStart` also enforces the volume budget (F-187): before opening a packet source, it sums the bytes of every retained `capture-*.pcapng` file already on `captureDataDir` (`retainedCaptureBytes`) and refuses the start with `507 Insufficient Storage` if that total plus the requested `maxSizeBytes` would exceed `Server.budgetBytes`. A file already deleted (expired, in this system, means deleted by the operator's retention reconciler, or removed by `HandleDelete` when the API deletes its CR — F-261) is simply absent from that sum. `budgetBytes` of `0` disables the check.