diff --git a/cmd/geneva-server/main.go b/cmd/geneva-server/main.go index 47d485c..ef51204 100644 --- a/cmd/geneva-server/main.go +++ b/cmd/geneva-server/main.go @@ -17,6 +17,7 @@ import ( "os" "strconv" "strings" + "time" "github.com/alexflint/go-arg" "github.com/getlantern/geneva-server/internal/adapter" @@ -51,28 +52,29 @@ func (m *markFlag) UnmarshalText(b []byte) error { // runCmd holds the flags for the run subcommand. type runCmd struct { - Mode string `arg:"--mode" default:"prod" help:"operating mode: prod or eval"` - Port uint16 `arg:"--port,required" help:"proxy TCP port to steer"` - OutQueue uint16 `arg:"--out-queue" default:"100" help:"NFQUEUE number for egress (outbound) packets"` - InQueue uint16 `arg:"--in-queue" default:"101" help:"NFQUEUE number for ingress (inbound) packets"` - QueueMaxLen uint32 `arg:"--queue-max-len" default:"65535" help:"maximum packets waiting in each NFQUEUE; overload is kernel fail-open"` - Mark markFlag `arg:"--mark" default:"0x67656e" help:"deprecated compatibility flag; reinjection now preserves the packet's exact routing mark"` - ReinjectBypassUID int64 `arg:"--reinject-bypass-uid" default:"-1" help:"dedicated Geneva socket UID excluded before output queueing"` - GenerationMarkNamespace markFlag `arg:"--generation-mark-namespace" default:"0x67000000" help:"must acknowledge the fleet-reserved Geneva conntrack namespace 0x67000000/0xfffff000"` - Table string `arg:"--table" default:"geneva_server" help:"dedicated nftables table name"` - ControlAddr string `arg:"--control-addr" default:"127.0.0.1:8092" help:"address for the control/health HTTP surface"` - Market string `arg:"--market" default:"unknown" help:"market label for the eval-mode canary pool"` - 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"` - 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; required in prod so controller-owned NIC offloads are durably restorable"` - 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"` - AdapterStateFile string `arg:"--adapter-state-file" default:"/var/lib/geneva-server/adapter-state.json" help:"durable local state for reconstructing live connection generations after restart"` - MaxGenerations int `arg:"--max-generations" default:"3" help:"maximum prepared/live immutable engine generations"` - MaxScopedGenerations int `arg:"--max-scoped-generations" help:"maximum handshake-scoped generations within the total generation budget (default: min(3, total))"` - MaxEveryPacketGenerations int `arg:"--max-every-packet-generations" help:"maximum every-packet generations within the total generation budget (default: min(2, total))"` + Mode string `arg:"--mode" default:"prod" help:"operating mode: prod or eval"` + Port uint16 `arg:"--port,required" help:"proxy TCP port to steer"` + OutQueue uint16 `arg:"--out-queue" default:"100" help:"NFQUEUE number for egress (outbound) packets"` + InQueue uint16 `arg:"--in-queue" default:"101" help:"NFQUEUE number for ingress (inbound) packets"` + QueueMaxLen uint32 `arg:"--queue-max-len" default:"65535" help:"maximum packets waiting in each NFQUEUE; overload is kernel fail-open"` + Mark markFlag `arg:"--mark" default:"0x67656e" help:"deprecated compatibility flag; reinjection now preserves the packet's exact routing mark"` + ReinjectBypassUID int64 `arg:"--reinject-bypass-uid" default:"-1" help:"dedicated Geneva socket UID excluded before output queueing"` + GenerationMarkNamespace markFlag `arg:"--generation-mark-namespace" default:"0x67000000" help:"must acknowledge the fleet-reserved Geneva conntrack namespace 0x67000000/0xfffff000"` + Table string `arg:"--table" default:"geneva_server" help:"dedicated nftables table name"` + ControlAddr string `arg:"--control-addr" default:"127.0.0.1:8092" help:"address for the control/health HTTP surface"` + Market string `arg:"--market" default:"unknown" help:"market label for the eval-mode canary pool"` + 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"` + 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; required in prod so controller-owned NIC offloads are durably restorable"` + 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"` + AdapterStateFile string `arg:"--adapter-state-file" default:"/var/lib/geneva-server/adapter-state.json" help:"durable local state for reconstructing live connection generations after restart"` + MaxGenerations int `arg:"--max-generations" default:"3" help:"maximum prepared/live immutable engine generations"` + MaxScopedGenerations int `arg:"--max-scoped-generations" help:"maximum handshake-scoped generations within the total generation budget (default: min(3, total))"` + MaxEveryPacketGenerations int `arg:"--max-every-packet-generations" help:"maximum every-packet generations within the total generation budget (default: min(2, total))"` + DrainIdleTimeout time.Duration `arg:"--drain-idle-timeout" default:"5m" help:"an ESTABLISHED connection idle this long no longer holds its generation's drain open (0 disables); flows killed on the path without a FIN otherwise stay in conntrack for days"` } // validateCmd holds the flags for the validate subcommand. @@ -207,6 +209,9 @@ func (o *runCmd) validate() error { if o.MaxEveryPacketGenerations < 1 || o.MaxEveryPacketGenerations > o.MaxGenerations { return fmt.Errorf("--max-every-packet-generations must be between 1 and --max-generations") } + if o.DrainIdleTimeout < 0 { + return errors.New("--drain-idle-timeout must not be negative") + } if o.Mode == "prod" && strings.TrimSpace(o.Iface) == "" { return errors.New("prod mode requires --iface so NIC offload ownership is durable and restorable") } diff --git a/cmd/geneva-server/run_linux.go b/cmd/geneva-server/run_linux.go index 3f80b8f..6a00d73 100644 --- a/cmd/geneva-server/run_linux.go +++ b/cmd/geneva-server/run_linux.go @@ -328,7 +328,7 @@ func steeringConfig(o *runCmd, fatal func(error)) steering.Config { ObserveInbound: o.ObserveInbound, StateFile: o.AdapterStateFile, - Connections: flowtrack.Counter{}, + Connections: flowtrack.Counter{IdleAfter: o.DrainIdleTimeout}, MaxGenerations: o.MaxGenerations, MaxScopedGenerations: o.MaxScopedGenerations, MaxEveryPacketGenerations: o.MaxEveryPacketGenerations, diff --git a/deploy/README.md b/deploy/README.md index 1dfa147..f998f79 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -219,7 +219,18 @@ high 20 bits is left alone and the connection is not steered. Drain/status read conntrack over netlink, filter by the full Geneva generation mask, then by original IPv4/TCP destination port. GC refuses an active -generation or any nonzero result. IDs are bounded to 1..4095 and cannot be +generation or any nonzero result. An ESTABLISHED flow idle longer than +`--drain-idle-timeout` (default 5m, 0 disables) no longer holds a drain open: +a connection the path killed without a FIN (a censor dropping it after the +handshake, a client that vanished) stays ESTABLISHED in conntrack for +`nf_conntrack_tcp_timeout_established`, five days by default. Idleness comes +from the entry's own timer, which restarts on every packet, so a live +connection holds the drain however long it lasts. A flow that is +retransmitting or has unacknowledged data runs on the much shorter +`nf_conntrack_tcp_timeout_max_retrans` / `_unacknowledged` timer instead, +which says nothing about idle time, so it keeps holding the drain until that +timer expires the entry. ID allocation still counts +every entry, idle or not, so an ID is never reused while one carries its mark. IDs are bounded to 1..4095 and cannot be changed in place; an ID becomes reusable only after zero-flow GC, so wraparound cannot bind an old conntrack entry to new DNA. Startup also reserves every live orphan ID found in the namespace. Restaging an absent rollback artifact takes a diff --git a/internal/flowtrack/counter_linux.go b/internal/flowtrack/counter_linux.go index 6aebfec..a06171a 100644 --- a/internal/flowtrack/counter_linux.go +++ b/internal/flowtrack/counter_linux.go @@ -7,6 +7,10 @@ package flowtrack import ( "context" "fmt" + "os" + "strconv" + "strings" + "time" ct "github.com/ti-mo/conntrack" "golang.org/x/sys/unix" @@ -15,7 +19,99 @@ import ( ) // Counter counts live, adapter-owned TCP flows. -type Counter struct{} +// +// IdleAfter, when positive, leaves out ESTABLISHED flows that have carried no +// packet for that long. A connection the path killed without a FIN or RST +// (a censor dropping a flow after its handshake, a client that vanished) +// stays ESTABLISHED in conntrack for nf_conntrack_tcp_timeout_established, +// five days by default, and would hold its generation's drain open for all of +// it. Idleness is read from conntrack itself: an entry's remaining timeout +// restarts at the established timeout on every packet, so a live connection +// keeps counting however long it lasts. +// +// While a flow retransmits or has data outstanding, the kernel re-arms its +// timer at the much shorter max-retrans or unacknowledged timeout instead. +// Such a timer says nothing about idle time, so the flow counts; if the path +// has killed it, that short timer removes the entry soon anyway. +type Counter struct { + IdleAfter time.Duration +} + +// establishedTimeoutPath is where the kernel exposes the timeout an +// ESTABLISHED TCP entry restarts at on every packet. maxRetransTimeoutPath and +// unacknowledgedTimeoutPath hold the shorter timeouts it restarts at instead +// while the flow retransmits or has unacknowledged data. +var ( + establishedTimeoutPath = "/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established" + maxRetransTimeoutPath = "/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_max_retrans" + unacknowledgedTimeoutPath = "/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_unacknowledged" +) + +// tcpConntrackEstablished is the kernel's TCP_CONNTRACK_ESTABLISHED state. +const tcpConntrackEstablished = 3 + +// liveness decides which dumped flows still hold a drain open. +type liveness struct { + idleAfter time.Duration + established time.Duration + // shortTimer is the longest timeout an ESTABLISHED entry can restart at + // while it retransmits or has unacknowledged data. A remaining timeout at + // or below it may have been re-armed by the latest packet. + shortTimer time.Duration +} + +// newLiveness reads the conntrack TCP timeouts. Without them idleness cannot +// be measured, so every flow counts: holding a drain open is the safe mistake. +func (c Counter) newLiveness() liveness { + if c.IdleAfter <= 0 { + return liveness{} + } + established, ok := readTimeout(establishedTimeoutPath) + if !ok { + return liveness{} + } + maxRetrans, ok := readTimeout(maxRetransTimeoutPath) + if !ok { + return liveness{} + } + unacknowledged, ok := readTimeout(unacknowledgedTimeoutPath) + if !ok { + return liveness{} + } + return liveness{ + idleAfter: c.IdleAfter, + established: established, + shortTimer: max(maxRetrans, unacknowledged), + } +} + +func readTimeout(path string) (time.Duration, bool) { + raw, err := os.ReadFile(path) + if err != nil { + return 0, false + } + seconds, err := strconv.ParseUint(strings.TrimSpace(string(raw)), 10, 32) + if err != nil || seconds == 0 { + return 0, false + } + return time.Duration(seconds) * time.Second, true +} + +// live reports whether a flow still counts toward a drain. +func (l liveness) live(flow ct.Flow) bool { + if l.idleAfter <= 0 || l.established <= 0 { + return true + } + tcp := flow.ProtoInfo.TCP + if tcp == nil || tcp.State != tcpConntrackEstablished { + return true + } + remaining := time.Duration(flow.Timeout) * time.Second + if remaining >= l.established || remaining <= l.shortTimer { + return true + } + return l.established-remaining < l.idleAfter +} // Conntrack's netlink dump does not accept a context. Keep lifecycle calls // bounded by running at most one dump at a time and allowing the caller to @@ -27,16 +123,19 @@ var dumpSlot = make(chan struct{}, 1) // Count returns flows whose full Geneva namespace+generation bits match id and // whose original tuple targeted the configured proxy port. Connmark bits // outside the adapter reservation are intentionally ignored. -func (Counter) Count(ctx context.Context, id uint32, port uint16) (int, error) { +func (c Counter) Count(ctx context.Context, id uint32, port uint16) (int, error) { mark, err := generation.Mark(id) if err != nil { return 0, err } - return count(ctx, ct.Filter{Mark: mark, Mask: generation.Mask}, port) + return count(ctx, ct.Filter{Mark: mark, Mask: generation.Mask}, port, c.newLiveness()) } // Counts returns one consistent namespace snapshot grouped by generation. // Startup uses it to find orphan marks without racing several separate dumps. +// It deliberately ignores IdleAfter: it decides which generation IDs are still +// in use, and an ID must not be handed to new DNA while any entry, idle or +// not, still carries its mark. func (Counter) Counts(ctx context.Context, port uint16) (map[uint32]int, error) { flows, err := dump(ctx, ct.Filter{Mark: generation.Namespace, Mask: 0xff000000}) if err != nil { @@ -59,14 +158,14 @@ func (Counter) Neutralize(ctx context.Context, port uint16) (int, error) { return updateNeutral(ctx, port) } -func count(ctx context.Context, filter ct.Filter, port uint16) (int, error) { +func count(ctx context.Context, filter ct.Filter, port uint16, alive liveness) (int, error) { flows, err := dump(ctx, filter) if err != nil { return 0, err } n := 0 for _, flow := range flows { - if adapterFlow(flow, port) { + if adapterFlow(flow, port) && alive.live(flow) { n++ } } diff --git a/internal/flowtrack/counter_linux_test.go b/internal/flowtrack/counter_linux_test.go index 20f7d61..accb50b 100644 --- a/internal/flowtrack/counter_linux_test.go +++ b/internal/flowtrack/counter_linux_test.go @@ -6,6 +6,7 @@ import ( "context" "errors" "net" + "os" "sync/atomic" "testing" "time" @@ -134,3 +135,87 @@ func TestNeutralMarkPreservesAllBitsOutsideReservation(t *testing.T) { } } } + +// A connection killed on the path without a FIN stays ESTABLISHED in conntrack +// for days; once idle past the drain idle timeout it stops holding the drain. +// Anything that has carried a packet recently, is not ESTABLISHED, or runs on +// the short retransmission or unacknowledged-data timer, counts. +func TestLivenessDropsIdleEstablishedFlows(t *testing.T) { + established := 432000 * time.Second + alive := liveness{idleAfter: 5 * time.Minute, established: established, shortTimer: 300 * time.Second} + flow := func(state uint8, idle time.Duration) ct.Flow { + return ct.Flow{ + Timeout: uint32((established - idle) / time.Second), + ProtoInfo: ct.ProtoInfo{TCP: &ct.ProtoInfoTCP{State: state}}, + } + } + withTimeout := func(state uint8, remaining time.Duration) ct.Flow { + return ct.Flow{ + Timeout: uint32(remaining / time.Second), + ProtoInfo: ct.ProtoInfo{TCP: &ct.ProtoInfoTCP{State: state}}, + } + } + cases := []struct { + name string + flow ct.Flow + want bool + }{ + {"active", flow(tcpConntrackEstablished, 10*time.Second), true}, + {"just under the idle timeout", flow(tcpConntrackEstablished, 5*time.Minute-time.Second), true}, + {"idle past the timeout", flow(tcpConntrackEstablished, 5*time.Minute), false}, + {"dead for hours", flow(tcpConntrackEstablished, 6*time.Hour), false}, + {"closing flows expire on their own timers", flow(7, 6*time.Hour), true}, + {"retransmitting or unacknowledged, just re-armed", withTimeout(tcpConntrackEstablished, 300*time.Second), true}, + {"retransmitting or unacknowledged, nearly expired", withTimeout(tcpConntrackEstablished, time.Second), true}, + {"established timer just above the short timer", withTimeout(tcpConntrackEstablished, 301*time.Second), false}, + {"no TCP protocol info", ct.Flow{Timeout: 10}, true}, + } + for _, tc := range cases { + if got := alive.live(tc.flow); got != tc.want { + t.Errorf("%s: live = %v, want %v", tc.name, got, tc.want) + } + } + if !(liveness{}).live(flow(tcpConntrackEstablished, 6*time.Hour)) { + t.Error("a disabled idle timeout must count every flow") + } +} + +// Without every conntrack TCP timeout, idleness cannot be measured and every +// flow counts. +func TestLivenessWithoutTimeoutsCountsEverything(t *testing.T) { + paths := []*string{&establishedTimeoutPath, &maxRetransTimeoutPath, &unacknowledgedTimeoutPath} + originals := make([]string, len(paths)) + for i, p := range paths { + originals[i] = *p + } + t.Cleanup(func() { + for i, p := range paths { + *p = originals[i] + } + }) + dir := t.TempDir() + write := func(name, value string) string { + path := dir + "/" + name + if err := os.WriteFile(path, []byte(value), 0o600); err != nil { + t.Fatal(err) + } + return path + } + established := write("established", "432000\n") + maxRetrans := write("max_retrans", "300\n") + unacknowledged := write("unacknowledged", "300\n") + missing := dir + "/missing" + + dead := ct.Flow{Timeout: 3600, ProtoInfo: ct.ProtoInfo{TCP: &ct.ProtoInfoTCP{State: tcpConntrackEstablished}}} + for i := range paths { + establishedTimeoutPath, maxRetransTimeoutPath, unacknowledgedTimeoutPath = established, maxRetrans, unacknowledged + *paths[i] = missing + if !(Counter{IdleAfter: time.Minute}).newLiveness().live(dead) { + t.Fatalf("an unreadable %s must count the flow", originals[i]) + } + } + establishedTimeoutPath, maxRetransTimeoutPath, unacknowledgedTimeoutPath = established, maxRetrans, unacknowledged + if (Counter{IdleAfter: time.Minute}).newLiveness().live(dead) { + t.Fatal("a flow idle for days must not count once the timeouts are known") + } +}