From c5b4de74862a73e44bab515fd082e7c6ed9605f8 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 23 Sep 2026 21:18:24 -0500 Subject: [PATCH] feat(nat): verify SRv6 sources before NAT gateway forwarding Add an SRv6 source filter to the egress translation datapath as defence-in-depth. Before either forward leg, nat_ingress can check that an encapsulated tenant packet's outer source is a well-formed tenant SID (End.DT46, non-zero Argument, zero padding) and, once the allow-list is populated, that it falls inside a known fabric prefix and arrives on an uplink that prefix is bound to. Key changes: - New maps only (nat_src_allow LPM trie, nat_uplink_slot, nat_src_filter_config, nat_src_filter_stats, nat_src_denied LRU), so upgrading keeps every existing pinned map, including the session table - Modes off (default, one array read), audit (count, forward everything) and enforce (drop); the allow-list checks stay bypassed until the control plane marks a full sync - natsrcfiltermap: typed API plus an in-memory fake for the allow-list, uplink slots, mode and sync state, counters and denied sources - galactic-nat sets the mode from GALACTIC_NAT_SRV6_SOURCE_FILTER, numbers its uplinks into slots, and exports decision metrics Populating the allow-list from fabric routes is left to a shared reconciler in a follow-up. --- cmd/galactic-nat/metrics.go | 61 +++ cmd/galactic-nat/nat.go | 7 + cmd/galactic-nat/srcfilter.go | 64 +++ cmd/galactic-nat/srcfilter_test.go | 80 ++++ docs/nat/configuration.md | 35 +- internal/config/nat.go | 30 ++ internal/config/nat_srcfilter_test.go | 39 ++ internal/plumbing/ebpf/natprog/doc.go | 2 +- internal/plumbing/ebpf/natprog/nat.c | 241 +++++++++- .../ebpf/natprog/nat_srcfilter_test.go | 339 ++++++++++++++ internal/plumbing/ebpf/natprog/srcfilter.go | 47 ++ internal/plumbing/ebpf/natsrcfiltermap/doc.go | 27 ++ .../plumbing/ebpf/natsrcfiltermap/fake.go | 173 ++++++++ .../plumbing/ebpf/natsrcfiltermap/filter.go | 414 ++++++++++++++++++ .../ebpf/natsrcfiltermap/filter_test.go | 277 ++++++++++++ .../ebpf/natsrcfiltermap/kernel_test.go | 104 +++++ .../plumbing/ebpf/natsrcfiltermap/table.go | 51 +++ 17 files changed, 1984 insertions(+), 7 deletions(-) create mode 100644 cmd/galactic-nat/srcfilter.go create mode 100644 cmd/galactic-nat/srcfilter_test.go create mode 100644 internal/config/nat_srcfilter_test.go create mode 100644 internal/plumbing/ebpf/natprog/nat_srcfilter_test.go create mode 100644 internal/plumbing/ebpf/natprog/srcfilter.go create mode 100644 internal/plumbing/ebpf/natsrcfiltermap/doc.go create mode 100644 internal/plumbing/ebpf/natsrcfiltermap/fake.go create mode 100644 internal/plumbing/ebpf/natsrcfiltermap/filter.go create mode 100644 internal/plumbing/ebpf/natsrcfiltermap/filter_test.go create mode 100644 internal/plumbing/ebpf/natsrcfiltermap/kernel_test.go create mode 100644 internal/plumbing/ebpf/natsrcfiltermap/table.go diff --git a/cmd/galactic-nat/metrics.go b/cmd/galactic-nat/metrics.go index 12b50042e..e731fa14f 100644 --- a/cmd/galactic-nat/metrics.go +++ b/cmd/galactic-nat/metrics.go @@ -17,6 +17,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/natmap" "go.datum.net/galactic/internal/plumbing/ebpf/natprog" + "go.datum.net/galactic/internal/plumbing/ebpf/natsrcfiltermap" ) const metricsNamespace = "galactic_nat" @@ -40,6 +41,7 @@ var trafficLabels = []string{labelFamily, "direction", "action"} // scoped to what the map layer exposes read access to, the connection table // being entirely datapath-owned and so observability-only. type natCollector struct { + srcFilter *natsrcfiltermap.Filter connTable *natmap.ConnTable connMaxEntries uint32 dropReasons natmap.DropReasonsReader @@ -78,6 +80,7 @@ func newNatCollector(objs *natprog.NatObjects) *natCollector { claims: objs.NatClaims, neighFallbacks: objs.NeighFallbacks, shardConfig: natmap.NewShardConfigTable(natmap.KernelTable{Map: objs.ShardConfigTable}), + srcFilter: natsrcfiltermap.NewKernelFilter(objs), } } @@ -177,6 +180,23 @@ var ( "Packets dropped by this shard's datapath, by reason (drop_reasons map).", []string{"reason"}, nil, ) + srcFilterDecisionsDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "srv6_source_filter", "decisions_total"), + "SRv6 source filter decisions on encapsulated tenant packets, by decision. Denials are counted "+ + "in audit mode too, where the packet is still forwarded.", + []string{"decision"}, nil, + ) + srcFilterStateDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "srv6_source_filter", "populated"), + "1 once the SRv6 source filter's allow-list has completed a full sync, else 0, labelled with "+ + "the filter's mode.", + []string{"mode"}, nil, + ) + srcFilterAllowEntriesDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "srv6_source_filter", "allow_entries"), + "Current number of prefixes in the SRv6 source filter's allow-list.", + nil, nil, + ) ) // Describe implements prometheus.Collector. @@ -194,6 +214,9 @@ func (c *natCollector) Describe(ch chan<- *prometheus.Desc) { ch <- sessionCreatesDesc ch <- claimProbesDesc ch <- neighFallbacksDesc + ch <- srcFilterDecisionsDesc + ch <- srcFilterStateDesc + ch <- srcFilterAllowEntriesDesc } // Collect implements prometheus.Collector. @@ -204,6 +227,7 @@ func (c *natCollector) Collect(ch chan<- prometheus.Metric) { c.collectTraffic(ch) c.collectClaims(ch) c.collectNeighFallbacks(ch) + c.collectSrcFilter(ch) } // collectNeighFallbacks reports the return packets passed to the kernel for @@ -430,4 +454,41 @@ func (c *natCollector) collectClaims(ch chan<- prometheus.Metric) { f.label, p.label) } } + +} +func (c *natCollector) collectSrcFilter(ch chan<- prometheus.Metric) { + if c.srcFilter == nil { + return + } + + if stats, err := c.srcFilter.Stats(); err != nil { + ch <- prometheus.NewInvalidMetric(srcFilterDecisionsDesc, fmt.Errorf("read source filter stats: %w", err)) + } else { + for decision, value := range map[string]uint64{ + natprog.SrcStatNames[natprog.SrcStatChecked]: stats.Checked, + natprog.SrcStatNames[natprog.SrcStatAllowed]: stats.Allowed, + natprog.SrcStatNames[natprog.SrcStatDenyPrefix]: stats.DenyPrefix, + natprog.SrcStatNames[natprog.SrcStatDenyInterface]: stats.DenyInterface, + natprog.SrcStatNames[natprog.SrcStatDenyStructure]: stats.DenyStructure, + natprog.SrcStatNames[natprog.SrcStatBypassUnpopulated]: stats.BypassUnpopulated, + } { + ch <- prometheus.MustNewConstMetric(srcFilterDecisionsDesc, prometheus.CounterValue, float64(value), decision) + } + } + + if cfg, err := c.srcFilter.Config(); err != nil { + ch <- prometheus.NewInvalidMetric(srcFilterStateDesc, fmt.Errorf("read source filter config: %w", err)) + } else { + populated := 0.0 + if cfg.Populated { + populated = 1 + } + ch <- prometheus.MustNewConstMetric(srcFilterStateDesc, prometheus.GaugeValue, populated, cfg.Mode.String()) + } + + if entries, err := c.srcFilter.ListAllow(); err != nil { + ch <- prometheus.NewInvalidMetric(srcFilterAllowEntriesDesc, fmt.Errorf("list source filter allow-list: %w", err)) + } else { + ch <- prometheus.MustNewConstMetric(srcFilterAllowEntriesDesc, prometheus.GaugeValue, float64(len(entries))) + } } diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index 24d63a6a9..a82326e9d 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -24,6 +24,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/natattach" "go.datum.net/galactic/internal/plumbing/ebpf/natmap" "go.datum.net/galactic/internal/plumbing/ebpf/natprog" + "go.datum.net/galactic/internal/plumbing/ebpf/natsrcfiltermap" "go.datum.net/galactic/internal/plumbing/ebpf/xdpattach" "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" @@ -322,6 +323,11 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, return nil, fmt.Errorf("load egress translation eBPF datapath: %w", err) } + if err := setupSourceFilter(cfg.SRv6SourceFilter, uplinks, natsrcfiltermap.NewKernelFilter(objs)); err != nil { + _ = objs.Close() + return nil, fmt.Errorf("configure SRv6 source filter: %w", err) + } + // Before the attach, not after: the dispatcher tail-calls into these, and a // packet arriving at an empty slot passes through untranslated. if err := natattach.PopulateProgArray(objs); err != nil { @@ -381,6 +387,7 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, "interfaces", uplinks, "autoDetected", len(cfg.UplinkInterfaces) == 0, "xdpAttach", cfg.XDPAttach, + "srv6SourceFilter", cfg.SRv6SourceFilter, ) d.attached = true diff --git a/cmd/galactic-nat/srcfilter.go b/cmd/galactic-nat/srcfilter.go new file mode 100644 index 000000000..afdcd6ebe --- /dev/null +++ b/cmd/galactic-nat/srcfilter.go @@ -0,0 +1,64 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "fmt" + + "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/plumbing/ebpf/natprog" + "go.datum.net/galactic/internal/plumbing/ebpf/natsrcfiltermap" +) + +// setupSourceFilter writes the SRv6 source filter's mode and numbers this +// shard's uplinks into slots, in configuration order, so allow-list entries +// can bind a prefix to the uplinks it is reachable through. It leaves the +// allow-list and its populated flag to their own reconciler, so until that +// has run the datapath applies only its structural source checks. +func setupSourceFilter(configuredMode string, uplinks []string, filter *natsrcfiltermap.Filter) error { + mode, err := natsrcfiltermap.ParseMode(configuredMode) + if err != nil { + return err + } + if mode == natsrcfiltermap.ModeOff { + return filter.SetMode(mode) + } + slots, err := uplinkSlots(uplinks, linkIndexByName) + if err != nil { + return err + } + if err := filter.SyncUplinkSlots(slots); err != nil { + return err + } + return filter.SetMode(mode) +} + +// uplinkSlots assigns slot N to the Nth interface in ifaces, keyed by the +// ifindex ifindexOf resolves it to. It returns an error when an interface does +// not resolve or there are more interfaces than slots. +func uplinkSlots(ifaces []string, ifindexOf func(string) (int, error)) (map[uint32]uint8, error) { + if len(ifaces) > int(natprog.SrcFilterMaxSlot)+1 { + return nil, fmt.Errorf("%d uplink interfaces exceed the source filter's %d slots", + len(ifaces), int(natprog.SrcFilterMaxSlot)+1) + } + slots := make(map[uint32]uint8, len(ifaces)) + for i, name := range ifaces { + ifindex, err := ifindexOf(name) + if err != nil { + return nil, fmt.Errorf("resolve uplink interface %q: %w", name, err) + } + slots[uint32(ifindex)] = uint8(i) + } + return slots, nil +} + +func linkIndexByName(name string) (int, error) { + link, err := netlink.LinkByName(name) + if err != nil { + return 0, err + } + return link.Attrs().Index, nil +} diff --git a/cmd/galactic-nat/srcfilter_test.go b/cmd/galactic-nat/srcfilter_test.go new file mode 100644 index 000000000..ae90f246c --- /dev/null +++ b/cmd/galactic-nat/srcfilter_test.go @@ -0,0 +1,80 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "errors" + "fmt" + "reflect" + "testing" + + "go.datum.net/galactic/internal/plumbing/ebpf/natsrcfiltermap" +) + +const ( + testUplinkA = "eth1" + testUplinkB = "eth0" +) + +func fakeIfindex(indexes map[string]int) func(string) (int, error) { + return func(name string) (int, error) { + if i, ok := indexes[name]; ok { + return i, nil + } + return 0, errors.New("link not found") + } +} + +func TestUplinkSlots(t *testing.T) { + many := make([]string, 33) + for i := range many { + many[i] = fmt.Sprintf("eth%d", i) + } + tests := []struct { + name string + ifaces []string + want map[uint32]uint8 + wantError bool + }{ + {"ConfigurationOrder", []string{testUplinkA, testUplinkB}, map[uint32]uint8{3: 0, 2: 1}, false}, + {"Unresolvable", []string{testUplinkA, "missing"}, nil, true}, + {"TooMany", many, nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := uplinkSlots(tt.ifaces, fakeIfindex(map[string]int{testUplinkB: 2, testUplinkA: 3})) + if (err != nil) != tt.wantError { + t.Fatalf("uplinkSlots error = %v, wantError = %v", err, tt.wantError) + } + if !tt.wantError && !reflect.DeepEqual(got, tt.want) { + t.Errorf("uplinkSlots = %v, want %v", got, tt.want) + } + }) + } +} + +func TestSetupSourceFilterRejectsUnknownMode(t *testing.T) { + filter, fakes := natsrcfiltermap.NewFakeFilter() + if err := setupSourceFilter("strict", nil, filter); err == nil { + t.Fatal("setupSourceFilter succeeded with an unknown mode, want error") + } + if fakes.Config.Len() != 0 || fakes.UplinkSlots.Len() != 0 { + t.Error("setupSourceFilter wrote state before rejecting its mode") + } +} + +func TestSetupSourceFilterOffSkipsUplinkResolution(t *testing.T) { + filter, _ := natsrcfiltermap.NewFakeFilter() + if err := filter.SetMode(natsrcfiltermap.ModeEnforce); err != nil { + t.Fatal(err) + } + if err := setupSourceFilter("off", []string{"missing-test-interface"}, filter); err != nil { + t.Fatal(err) + } + cfg, err := filter.Config() + if err != nil || cfg.Mode != natsrcfiltermap.ModeOff { + t.Fatalf("config = %+v, %v, want off", cfg, err) + } +} diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index fed611a87..a452c6392 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -18,6 +18,7 @@ Logging takes `--log-level` (`LOG_LEVEL`), without the `GALACTIC_NAT` prefix and | Uplink interfaces | `GALACTIC_NAT_UPLINK_INTERFACES` | `--nat-uplink-interfaces` | auto-detected | No | | XDP attach mode | `GALACTIC_NAT_XDP_ATTACH` | `--nat-xdp-attach` | `direct` | No | | Datapath enabled | `GALACTIC_NAT_DATAPATH_ENABLED` | `--nat-datapath-enabled` | `true` | No | +| SRv6 source filter | `GALACTIC_NAT_SRV6_SOURCE_FILTER` | — | `off` | No | | Echo responder | `GALACTIC_NAT_ECHO_RESPONDER` | `--nat-echo-responder` | `false` | No | | Procfs sysctl root | `GALACTIC_NAT_PROC_SYS_PATH` | `--nat-proc-sys-path` | `/proc/sys` | No | | Metrics port | `GALACTIC_NAT_METRICS_PORT` | `--metrics-port` | `9182` | No | @@ -197,6 +198,32 @@ node where something else already turned forwarding on passes with the default too. SELinux policy on an enforcing node can still refuse the write, and the shard then says so at startup. +**`GALACTIC_NAT_SRV6_SOURCE_FILTER`** +The datapath's SRv6 source filter mode: `off`, `audit` or `enforce`. +Environment-only. Before a tenant's encapsulated packet reaches either +forward leg, the filter checks its outer source: + +- It must be a well-formed tenant SID: Function End.DT46, a non-zero + Argument and zero padding. The reply is re-encapsulated toward exactly + that address, so nothing that fails this could have been answered. +- Once the allow-list is populated, it must fall inside an allowed fabric + prefix and arrive on an uplink that prefix is bound to. Until then these + two checks are bypassed and counted as such. + +| Mode | Behaviour | +| --------- | ------------------------------------------------------------------------- | +| `off` | No check; the datapath behaves exactly as without the filter. | +| `audit` | Every decision is counted and denied sources are recorded; nothing drops. | +| `enforce` | Packets whose source fails a check are dropped. | + +`galactic-nat` numbers the resolved startup uplinks into slots in order, for allow-list entries to +bind to. Nothing populates the allow-list yet, so today `audit` and +`enforce` apply only the structural check. Decisions are exported as +`galactic_nat_srv6_source_filter_decisions_total{decision}`, with +`galactic_nat_srv6_source_filter_populated{mode}` and +`galactic_nat_srv6_source_filter_allow_entries` alongside. Roll out with +`audit` first and move to `enforce` once the denials are understood. + ### Capabilities and host requirements `galactic-nat` runs `hostNetwork: true` and needs: @@ -499,9 +526,11 @@ knowing before you rely on this component in production: deployment needs its own redistribution/border design for this. - **IPv4 is out of scope.** `nat.c` rejects non-IPv6 inner packets outright; there is no IPv4 masquerade path. -- **No anti-spoofing / trust boundary on ingress to a shard.** The - datapath trusts fabric-internal traffic; this deserves its own security - pass before carrying untrusted traffic. +- **Source filtering is structural only until its allow-list is + populated.** `GALACTIC_NAT_SRV6_SOURCE_FILTER` checks that an + encapsulated packet's source is a well-formed tenant SID; the fabric-peer + allow-list and uplink binding it also supports are not yet populated by + anything in this repo. The filter is `off` by default. - **A shard node's netfilter rules never see tenant egress.** Both directions are claimed in XDP and leave from the driver, so nothing a shard translates traverses `PREROUTING`, `FORWARD`, or connection diff --git a/internal/config/nat.go b/internal/config/nat.go index 7e18e0b46..bda8b97ab 100644 --- a/internal/config/nat.go +++ b/internal/config/nat.go @@ -7,6 +7,7 @@ package config import ( "errors" "fmt" + "strings" "github.com/spf13/pflag" "github.com/spf13/viper" @@ -107,6 +108,22 @@ const ( NATXDPAttachChain = "chain" ) +const ( + // EnvNATSRv6SourceFilter selects the datapath's SRv6 source filter mode: + // off, audit or enforce. Optional, defaulting to off, which leaves the + // datapath's behaviour unchanged. audit counts every decision without + // dropping; enforce drops encapsulated tenant packets whose outer source + // fails the check. + EnvNATSRv6SourceFilter = "GALACTIC_NAT_SRV6_SOURCE_FILTER" +) + +// SRv6 source filter modes accepted by EnvNATSRv6SourceFilter. +const ( + NATSRv6SourceFilterOff = "off" + NATSRv6SourceFilterAudit = "audit" + NATSRv6SourceFilterEnforce = "enforce" +) + // --- NATConfig --------------------------------------------------------- // NATConfig resolves galactic-nat configuration with three-tier precedence: @@ -142,6 +159,10 @@ type NATConfig struct { // ProcSysPath is EnvNATProcSysPath. ProcSysPath string + + // SRv6SourceFilter is the source filter mode, one of the + // NATSRv6SourceFilter* values, normalised to lower case. + SRv6SourceFilter string } // NewNATConfig creates a config resolver reading the GALACTIC_NAT @@ -160,6 +181,7 @@ func NewNATConfig() *NATConfig { v.SetDefault("datapath_enabled", true) v.SetDefault("echo_responder", false) v.SetDefault("proc_sys_path", DefaultProcSysPath) + v.SetDefault("srv6_source_filter", NATSRv6SourceFilterOff) cfg := &NATConfig{ v: v, @@ -201,6 +223,7 @@ func (c *NATConfig) readFields() { c.NodeName = c.v.GetString(KeyNodeName) c.MetricsPort = c.v.GetInt(KeyMetricsPort) c.GRPCHealthPort = c.v.GetInt(KeyGRPCHealthPort) + c.SRv6SourceFilter = strings.ToLower(strings.TrimSpace(c.v.GetString("srv6_source_filter"))) c.UplinkInterfaces = splitCommaList(c.v.GetString("uplink_interfaces")) c.XDPAttach = c.v.GetString("xdp_attach") c.XDPAttachDeprecated = c.XDPAttach == NATXDPAttachChain @@ -217,6 +240,13 @@ func (c *NATConfig) Validate() error { if c.NodeName == "" { return fmt.Errorf("node name is required (use --node-name flag or %s env var)", EnvNATNodeName) } + switch c.SRv6SourceFilter { + case NATSRv6SourceFilterOff, NATSRv6SourceFilterAudit, NATSRv6SourceFilterEnforce: + default: + return fmt.Errorf("SRv6 source filter mode %q must be %s, %s or %s (%s env var)", + c.SRv6SourceFilter, NATSRv6SourceFilterOff, NATSRv6SourceFilterAudit, + NATSRv6SourceFilterEnforce, EnvNATSRv6SourceFilter) + } if c.MetricsPort < 1 || c.MetricsPort > 65535 { return errors.New("metrics port must be between 1 and 65535") } diff --git a/internal/config/nat_srcfilter_test.go b/internal/config/nat_srcfilter_test.go new file mode 100644 index 000000000..c63ad6806 --- /dev/null +++ b/internal/config/nat_srcfilter_test.go @@ -0,0 +1,39 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package config + +import "testing" + +func TestNATConfigSRv6SourceFilter(t *testing.T) { + tests := []struct { + name string + value string + set bool + want string + wantError bool + }{ + {"DefaultOff", "", false, NATSRv6SourceFilterOff, false}, + {"Audit", "audit", true, NATSRv6SourceFilterAudit, false}, + {"EnforceNormalised", " Enforce ", true, NATSRv6SourceFilterEnforce, false}, + {"Unknown", "strict", true, "strict", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Setenv(EnvNATNodeName, testNATNodeName) + t.Setenv(EnvNATUplinkInterfaces, testNATIface) + if tt.set { + t.Setenv(EnvNATSRv6SourceFilter, tt.value) + } + + cfg := NewNATConfig() + if cfg.SRv6SourceFilter != tt.want { + t.Errorf("SRv6SourceFilter = %q, want %q", cfg.SRv6SourceFilter, tt.want) + } + if err := cfg.Validate(); (err != nil) != tt.wantError { + t.Errorf("Validate() error = %v, wantError = %v", err, tt.wantError) + } + }) + } +} diff --git a/internal/plumbing/ebpf/natprog/doc.go b/internal/plumbing/ebpf/natprog/doc.go index 7992b85c9..bcfd4db53 100644 --- a/internal/plumbing/ebpf/natprog/doc.go +++ b/internal/plumbing/ebpf/natprog/doc.go @@ -86,4 +86,4 @@ const ( // within their packed structs, so they are genuinely 2-byte aligned despite the // packed attribute. // -//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -Wno-address-of-packed-member -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type conn_key -type conn_value -type shard_config -type nat_traffic_counter Nat nat.c +//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -Wno-address-of-packed-member -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type conn_key -type conn_value -type shard_config -type nat_traffic_counter -type src_allow_key -type src_allow_value -type src_filter_config -type src_denied_key -type src_denied_value Nat nat.c diff --git a/internal/plumbing/ebpf/natprog/nat.c b/internal/plumbing/ebpf/natprog/nat.c index 1796b7032..296a817e4 100644 --- a/internal/plumbing/ebpf/natprog/nat.c +++ b/internal/plumbing/ebpf/natprog/nat.c @@ -100,6 +100,7 @@ // the family: inside nat64_prefix, or inside 64:ff9b::/96 when // NAT_SHARD_FLAG_WKP is set -> nat64_forward, otherwise nat66_forward; // or the _icmp_ leaf of the same family for an inner ICMPv6 packet. +// The source filter, when on, runs first; see its section below. // 4. IPv4 destination equal to shard_pub_addr4 is a reply from the IPv4 // internet -> nat64_return; for ICMPv4, nat64_icmp_error for an error // type and nat64_icmp_return for anything else. @@ -144,9 +145,34 @@ // // There is no tenant-identity check beyond the Argument itself. A forged // Argument misdirects only the forger's own isolation bucket, never a -// legitimate tenant's, but this program trusts that only fabric-internal -// traffic reaches it at all. The trust boundary is a separate security -// question, not something this file resolves. +// legitimate tenant's. +// +// --------------------------------------------------------------------- +// SRv6 source filtering. +// --------------------------------------------------------------------- +// +// Before either forward leg, the dispatcher can verify the outer source of an +// encapsulated tenant packet, as a second check alongside the underlay's own +// isolation. nat_src_filter_config selects the mode: off (the default, a +// single array read and no other change), audit (count every decision, +// forward everything), or enforce (drop what fails). +// +// The source must first be a well-formed tenant SID: Function End.DT46, a +// non-zero Argument, and zero padding. The return leg re-encapsulates toward +// that exact address, so a source that fails this could never receive a reply +// and loses nothing by being refused. This part needs no control-plane state +// and applies from the moment the mode leaves off. +// +// Once the control plane marks the allow-list populated, the source must also +// fall inside a prefix in nat_src_allow, and arrive on an uplink that prefix is +// bound to: nat_uplink_slot maps an ingress ifindex to a slot, and the entry's +// iface_mask names the slots it is reachable through. Until the first +// complete sync the prefix and interface checks are bypassed and counted as +// such, so a control plane that has not run yet cannot black-hole egress. +// +// Denied sources are recorded by locator (their top 64 bits) in an LRU for +// triage. None of this state shares a map with the translation paths, so +// adding it leaves every existing pinned map as it was. #include #define SEC(name) __attribute__((section(name), used)) @@ -515,6 +541,76 @@ enum nat_drop_reason { DROP_REASON_NAT_COUNT = 27, }; +// Source filter modes, stored in src_filter_config.mode. The array's zero +// value is off, so a datapath whose control plane never writes the map +// behaves exactly as it did before the filter existed. +#define NAT_SRC_FILTER_OFF 0 +#define NAT_SRC_FILTER_AUDIT 1 +#define NAT_SRC_FILTER_ENFORCE 2 + +// src_allow_value.flags. ANY_IFACE accepts the prefix on every uplink, for a +// peer whose reachability is not tied to one link. +#define NAT_SRC_ALLOW_ANY_IFACE 0x1 + +// nat_uplink_slot values index a 32-bit mask, so slots run 0-31. +#define NAT_SRC_MAX_SLOT 31 + +// uFMT 48+16 field constants, matching internal/plumbing/ebpf/uformat. +#define NAT_USID_FUNCTION_END_DT46 0xE + +// Indices into nat_src_filter_stats. The map is sized NAT_SRC_STAT_SLOTS rather +// than to the count in use, so a later counter is an append that leaves the +// pinned map's layout, and so every other pinned map, untouched. +enum nat_src_stat { + NAT_SRC_STAT_CHECKED = 0, + NAT_SRC_STAT_ALLOWED = 1, + NAT_SRC_STAT_DENY_PREFIX = 2, + NAT_SRC_STAT_DENY_IFACE = 3, + NAT_SRC_STAT_DENY_STRUCTURE = 4, + NAT_SRC_STAT_BYPASS_UNPOPULATED = 5, + NAT_SRC_STAT_COUNT = 6, + NAT_SRC_STAT_SLOTS = 16, +}; + +// struct src_allow_key is nat_src_allow's LPM key: prefixlen in bits, then the +// address in network order. +struct src_allow_key { + __u32 prefixlen; + __u8 addr[16]; +}; + +// struct src_allow_value binds an allowed prefix to the uplinks it may arrive +// on: bit N of iface_mask is uplink slot N. +struct src_allow_value { + __u32 iface_mask; + __u32 flags; +}; + +// struct src_filter_config is nat_src_filter_config's single entry. populated +// is set once the control plane has completed a full sync of nat_src_allow; +// generation is the control plane's own sync counter, exposed for +// observability and never read by the datapath. +struct src_filter_config { + __u32 mode; + __u32 populated; + __u64 generation; +}; + +// struct src_denied_key is a denied source's locator: its top 64 bits, Block +// and Node-ID, which identify the sending node whatever its Argument. +struct src_denied_key { + __u8 locator[8]; +}; + +// struct src_denied_value records the most recent denial for one locator. +// packets is approximate under concurrent updates from several CPUs. +struct src_denied_value { + __u64 packets; + __u64 last_seen_ns; + __u32 last_reason; + __u32 last_ifindex; +}; + // --------------------------------------------------------------------- // Maps. // --------------------------------------------------------------------- @@ -684,6 +780,41 @@ struct { __type(key, __u32); __type(value, struct icmp_bucket); } icmp_rate_bucket SEC(".maps"); +struct { + __uint(type, BPF_MAP_TYPE_LPM_TRIE); + __uint(max_entries, 4096); + __uint(map_flags, BPF_F_NO_PREALLOC); + __type(key, struct src_allow_key); + __type(value, struct src_allow_value); +} nat_src_allow SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, NAT_SRC_MAX_SLOT + 1); + __type(key, __u32); + __type(value, __u32); +} nat_uplink_slot SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 1); + __type(key, __u32); + __type(value, struct src_filter_config); +} nat_src_filter_config SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); + __uint(max_entries, NAT_SRC_STAT_SLOTS); + __type(key, __u32); + __type(value, __u64); +} nat_src_filter_stats SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_LRU_HASH); + __uint(max_entries, 1024); + __type(key, struct src_denied_key); + __type(value, struct src_denied_value); +} nat_src_denied SEC(".maps"); static NAT_ALWAYS_INLINE void count_drop(__u32 reason) { @@ -721,6 +852,101 @@ static NAT_ALWAYS_INLINE int take_icmp_token(void) return 1; } +static NAT_ALWAYS_INLINE void count_src_stat(__u32 stat) +{ + __u64 *counter = bpf_map_lookup_elem(&nat_src_filter_stats, &stat); + if (counter) + *counter += 1; +} + +static NAT_ALWAYS_INLINE void record_src_denied(const __u8 saddr[16], __u32 reason, __u32 ifindex) +{ + struct src_denied_key key; + __builtin_memcpy(key.locator, saddr, sizeof(key.locator)); + + __u64 now = bpf_ktime_get_ns(); + struct src_denied_value *seen = bpf_map_lookup_elem(&nat_src_denied, &key); + if (seen) { + seen->packets += 1; + seen->last_seen_ns = now; + seen->last_reason = reason; + seen->last_ifindex = ifindex; + return; + } + + struct src_denied_value fresh = { + .packets = 1, + .last_seen_ns = now, + .last_reason = reason, + .last_ifindex = ifindex, + }; + bpf_map_update_elem(&nat_src_denied, &key, &fresh, BPF_ANY); +} + +// src_well_formed reports whether saddr is a tenant SID a reply can be +// re-encapsulated toward: Function End.DT46, a non-zero Argument, and a zero +// padding tail. +static NAT_ALWAYS_INLINE int src_well_formed(const __u8 saddr[16]) +{ + if ((saddr[8] >> 4) != NAT_USID_FUNCTION_END_DT46) + return 0; + if ((saddr[8] & 0x0F) == 0 && saddr[9] == 0) + return 0; + for (int i = 10; i < 16; i++) { + if (saddr[i] != 0) + return 0; + } + return 1; +} + +// src_filter_check classifies one encapsulated packet's outer source, counts +// the decision, and returns the stat index it landed on. Callers treat +// NAT_SRC_STAT_ALLOWED and NAT_SRC_STAT_BYPASS_UNPOPULATED as a pass and every +// other value as a denial. +static NAT_ALWAYS_INLINE __u32 src_filter_check(struct xdp_md *ctx, const __u8 saddr[16], + const struct src_filter_config *fcfg) +{ + __u32 verdict; + + count_src_stat(NAT_SRC_STAT_CHECKED); + + if (!src_well_formed(saddr)) { + verdict = NAT_SRC_STAT_DENY_STRUCTURE; + goto denied; + } + + if (!fcfg->populated) { + count_src_stat(NAT_SRC_STAT_BYPASS_UNPOPULATED); + return NAT_SRC_STAT_BYPASS_UNPOPULATED; + } + + struct src_allow_key key; + key.prefixlen = 128; + __builtin_memcpy(key.addr, saddr, sizeof(key.addr)); + struct src_allow_value *allow = bpf_map_lookup_elem(&nat_src_allow, &key); + if (!allow) { + verdict = NAT_SRC_STAT_DENY_PREFIX; + goto denied; + } + + if (!(allow->flags & NAT_SRC_ALLOW_ANY_IFACE)) { + __u32 ifindex = ctx->ingress_ifindex; + __u32 *slot = bpf_map_lookup_elem(&nat_uplink_slot, &ifindex); + if (!slot || *slot > NAT_SRC_MAX_SLOT || !(allow->iface_mask & (1u << *slot))) { + verdict = NAT_SRC_STAT_DENY_IFACE; + goto denied; + } + } + + count_src_stat(NAT_SRC_STAT_ALLOWED); + return NAT_SRC_STAT_ALLOWED; + +denied: + count_src_stat(verdict); + record_src_denied(saddr, verdict, ctx->ingress_ifindex); + return verdict; +} + static NAT_ALWAYS_INLINE int addr6_eq(const __u8 a[16], const __u8 b[16]) { for (int i = 0; i < 16; i++) { @@ -3097,6 +3323,15 @@ int nat_ingress(struct xdp_md *ctx) } if (locator_matches(ip6->daddr, cfg->shard_sid) && ip6->nexthdr == NAT_IPPROTO_IPV6) { + __u32 fcfg_key = 0; + struct src_filter_config *fcfg = bpf_map_lookup_elem(&nat_src_filter_config, &fcfg_key); + if (fcfg && fcfg->mode != NAT_SRC_FILTER_OFF) { + __u32 verdict = src_filter_check(ctx, ip6->saddr, fcfg); + if (verdict != NAT_SRC_STAT_ALLOWED && verdict != NAT_SRC_STAT_BYPASS_UNPOPULATED && + fcfg->mode == NAT_SRC_FILTER_ENFORCE) + return XDP_DROP; + } + struct nat_ip6hdr *inner = (void *) (ip6 + 1); if ((void *) (inner + 1) > data_end) { count_drop(DROP_REASON_NAT66_MALFORMED_FORWARD); diff --git a/internal/plumbing/ebpf/natprog/nat_srcfilter_test.go b/internal/plumbing/ebpf/natprog/nat_srcfilter_test.go new file mode 100644 index 000000000..a308f22fa --- /dev/null +++ b/internal/plumbing/ebpf/natprog/nat_srcfilter_test.go @@ -0,0 +1,339 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package natprog + +import ( + "net/netip" + "testing" +) + +// loIfindex is the ingress interface a BPF_PROG_TEST_RUN reports when no +// context is supplied: the loopback device of the caller's network namespace. +const loIfindex uint32 = 1 + +var ( + srcTestShardSID = netip.MustParseAddr("fc00:1:2::1") + srcTestShardPub = netip.MustParseAddr("2001:db8:9999::1") + // srcTestTenantSID is a well-formed tenant SID: Block fc00:3:4, Node-ID 5, + // Function End.DT46, Argument 0x123. + srcTestTenantSID = netip.MustParseAddr("fc00:3:4:5:e123::") + srcTestBackend = netip.MustParseAddr("fd20:60::5") + srcTestDest = netip.MustParseAddr("2001:db8:9998::1") +) + +// srcTestTenantBlock is the /48 covering srcTestTenantSID. +const srcTestTenantBlock = "fc00:3:4::/48" + +// loadSrcFilterObjects loads the datapath with a NAT66 shard configured and +// the source filter in mode. populated arms the allow-list checks. +func loadSrcFilterObjects(t *testing.T, mode uint32, populated bool) *NatObjects { + t.Helper() + objs := loadObjects(t) + if err := objs.ShardConfigTable.Put(uint32(0), NatShardConfig{ + ShardSid: srcTestShardSID.As16(), ShardPubAddr6: srcTestShardPub.As16(), ServesV6: 1, + }); err != nil { + t.Fatalf("populate shard_config_table: %v", err) + } + cfg := NatSrcFilterConfig{Mode: mode} + if populated { + cfg.Populated = 1 + } + if err := objs.NatSrcFilterConfig.Put(uint32(0), cfg); err != nil { + t.Fatalf("populate nat_src_filter_config: %v", err) + } + return objs +} + +func putAllow(t *testing.T, objs *NatObjects, prefix string, mask, flags uint32) { + t.Helper() + p := netip.MustParsePrefix(prefix) + key := NatSrcAllowKey{Prefixlen: uint32(p.Bits()), Addr: p.Addr().As16()} + if err := objs.NatSrcAllow.Put(key, NatSrcAllowValue{IfaceMask: mask, Flags: flags}); err != nil { + t.Fatalf("populate nat_src_allow %s: %v", prefix, err) + } +} + +func putUplinkSlot(t *testing.T, objs *NatObjects, ifindex uint32, slot uint32) { + t.Helper() + if err := objs.NatUplinkSlot.Put(ifindex, slot); err != nil { + t.Fatalf("populate nat_uplink_slot: %v", err) + } +} + +// encappedFromSource builds a tenant egress packet toward the shard SID with +// outer source src. +func encappedFromSource(t *testing.T, src netip.Addr) []byte { + t.Helper() + dst := srcTestShardSID.As16() + dst[8] = (dst[8] & 0xF0) | 0x01 + dst[9] = 0x23 + return buildEncappedUDPPacket(t, netip.AddrFrom16(dst), src, srcTestBackend, srcTestDest, []byte("egress")) +} + +func connCount(t *testing.T, objs *NatObjects) int { + t.Helper() + var ( + key NatConnKey + value NatConnValue + n int + ) + it := objs.NatConnTable.Iterate() + for it.Next(&key, &value) { + n++ + } + if err := it.Err(); err != nil { + t.Fatalf("iterate nat_conn_table: %v", err) + } + return n +} + +func srcStat(t *testing.T, objs *NatObjects, index uint32) uint64 { + t.Helper() + return sumPerCPU(t, objs.NatSrcFilterStats, index) +} + +func deniedCount(t *testing.T, objs *NatObjects) int { + t.Helper() + var ( + key NatSrcDeniedKey + value NatSrcDeniedValue + n int + ) + it := objs.NatSrcDenied.Iterate() + for it.Next(&key, &value) { + n++ + } + if err := it.Err(); err != nil { + t.Fatalf("iterate nat_src_denied: %v", err) + } + return n +} + +// assertForwarded checks that a packet reached a forward leg: the leg claims a +// session row before it resolves a next hop, so a row exists whatever the +// host's routes make of the verdict. +func assertForwarded(t *testing.T, objs *NatObjects, ret uint32) { + t.Helper() + assertLeftFromDatapath(t, ret) + if n := connCount(t, objs); n == 0 { + t.Fatalf("no session row after the packet: it never reached a forward leg") + } +} + +// assertDenied checks that a packet was dropped by the source filter before +// any forward leg ran. +func assertDenied(t *testing.T, objs *NatObjects, ret uint32) { + t.Helper() + if ret != xdpDrop { + t.Fatalf("verdict = %d, want XDP_DROP (%d)", ret, xdpDrop) + } + if n := connCount(t, objs); n != 0 { + t.Fatalf("%d session rows after a denied packet, want 0", n) + } +} + +func TestSrcFilter_OffIsNoOp(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + if err := objs.ShardConfigTable.Put(uint32(0), NatShardConfig{ + ShardSid: srcTestShardSID.As16(), ShardPubAddr6: srcTestShardPub.As16(), ServesV6: 1, + }); err != nil { + t.Fatalf("populate shard_config_table: %v", err) + } + + ret, _, err := objs.NatIngress.Test(encappedFromSource(t, netip.MustParseAddr("fc00:3:4::a1b2"))) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + assertForwarded(t, objs, ret) + if got := srcStat(t, objs, SrcStatChecked); got != 0 { + t.Errorf("checked = %d with the filter off, want 0", got) + } +} + +func TestSrcFilter_AuditCountsAndForwards(t *testing.T) { + tests := []struct { + name string + populated bool + src netip.Addr + wantStat uint32 + wantDeny bool + }{ + {"StructureUnpopulated", false, netip.MustParseAddr("fc00:3:4::a1b2"), SrcStatDenyStructure, true}, + {"UnknownPrefix", true, srcTestTenantSID, SrcStatDenyPrefix, true}, + {"BypassUnpopulated", false, srcTestTenantSID, SrcStatBypassUnpopulated, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + requireRoot(t) + objs := loadSrcFilterObjects(t, SrcFilterModeAudit, tt.populated) + + ret, _, err := objs.NatIngress.Test(encappedFromSource(t, tt.src)) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + assertForwarded(t, objs, ret) + if got := srcStat(t, objs, SrcStatChecked); got != 1 { + t.Errorf("checked = %d, want 1", got) + } + if got := srcStat(t, objs, tt.wantStat); got != 1 { + t.Errorf("%s = %d, want 1", SrcStatNames[tt.wantStat], got) + } + wantDenied := 0 + if tt.wantDeny { + wantDenied = 1 + } + if got := deniedCount(t, objs); got != wantDenied { + t.Errorf("denied-source entries = %d, want %d", got, wantDenied) + } + }) + } +} + +func TestSrcFilter_EnforceDeniesStructure(t *testing.T) { + tests := []struct { + name string + src string + }{ + {"FunctionNotEndDT46", "fc00:3:4:5:f123::"}, + {"FunctionZero", "fc00:3:4:5:123::"}, + {"ArgumentZero", "fc00:3:4:5:e000::"}, + {"PaddingSet", "fc00:3:4:5:e123::1"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + requireRoot(t) + objs := loadSrcFilterObjects(t, SrcFilterModeEnforce, false) + + ret, _, err := objs.NatIngress.Test(encappedFromSource(t, netip.MustParseAddr(tt.src))) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + assertDenied(t, objs, ret) + if got := srcStat(t, objs, SrcStatDenyStructure); got != 1 { + t.Errorf("deny_structure = %d, want 1", got) + } + }) + } +} + +func TestSrcFilter_EnforceAllowList(t *testing.T) { + tests := []struct { + name string + allowPrefix string + allowMask uint32 + allowFlags uint32 + slotLo *uint32 + wantAllowed bool + wantStat uint32 + }{ + {"UnknownPrefix", "fc00:9::/48", 1, 0, ptr(0), false, SrcStatDenyPrefix}, + {"MatchingSlot", srcTestTenantBlock, 1 << 2, 0, ptr(2), true, SrcStatAllowed}, + {"LongerPrefix", "fc00:3:4:5::/64", 1, 0, ptr(0), true, SrcStatAllowed}, + {"WrongSlot", srcTestTenantBlock, 1 << 0, 0, ptr(3), false, SrcStatDenyInterface}, + {"UnslottedInterface", srcTestTenantBlock, 1, 0, nil, false, SrcStatDenyInterface}, + {"AnyInterface", srcTestTenantBlock, 0, SrcAllowFlagAnyInterface, nil, true, SrcStatAllowed}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + requireRoot(t) + objs := loadSrcFilterObjects(t, SrcFilterModeEnforce, true) + putAllow(t, objs, tt.allowPrefix, tt.allowMask, tt.allowFlags) + if tt.slotLo != nil { + putUplinkSlot(t, objs, loIfindex, *tt.slotLo) + } + + ret, _, err := objs.NatIngress.Test(encappedFromSource(t, srcTestTenantSID)) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + if tt.wantAllowed { + assertForwarded(t, objs, ret) + if got := deniedCount(t, objs); got != 0 { + t.Errorf("denied-source entries = %d, want 0", got) + } + } else { + assertDenied(t, objs, ret) + assertDeniedRecord(t, objs, tt.wantStat) + } + if got := srcStat(t, objs, tt.wantStat); got != 1 { + t.Errorf("%s = %d, want 1", SrcStatNames[tt.wantStat], got) + } + }) + } +} + +func TestSrcFilter_EnforceUnpopulatedBypassesAllowList(t *testing.T) { + requireRoot(t) + objs := loadSrcFilterObjects(t, SrcFilterModeEnforce, false) + + ret, _, err := objs.NatIngress.Test(encappedFromSource(t, srcTestTenantSID)) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + assertForwarded(t, objs, ret) + if got := srcStat(t, objs, SrcStatBypassUnpopulated); got != 1 { + t.Errorf("bypass_unpopulated = %d, want 1", got) + } + if got := srcStat(t, objs, SrcStatAllowed); got != 0 { + t.Errorf("allowed = %d, want 0: a bypass is not an allow", got) + } +} + +func TestSrcFilter_NonShardTrafficUntouched(t *testing.T) { + requireRoot(t) + objs := loadSrcFilterObjects(t, SrcFilterModeEnforce, true) + + unclaimed := buildUDPPacket(t, netip.MustParseAddr("2001:db8::9999"), + netip.MustParseAddr("2001:db8:ffff::1"), 5000, 443, []byte("hi")) + ret, out, err := objs.NatIngress.Test(unclaimed) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + if ret != xdpPass { + t.Errorf("unclaimed verdict = %d, want XDP_PASS (%d)", ret, xdpPass) + } + if string(out) != string(unclaimed) { + t.Errorf("unclaimed packet mutated") + } + + otherNode := buildEncappedUDPPacket(t, netip.MustParseAddr("fc00:1:3:0:e123::"), + netip.MustParseAddr("fc00:9::1"), srcTestBackend, srcTestDest, []byte("x")) + ret, _, err = objs.NatIngress.Test(otherNode) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + if ret != xdpPass { + t.Errorf("other-locator verdict = %d, want XDP_PASS (%d)", ret, xdpPass) + } + + reply := buildUDPPacket(t, srcTestShardPub, srcTestDest, 443, 40000, []byte("r")) + if _, _, err := objs.NatIngress.Test(reply); err != nil { + t.Fatalf("program test-run: %v", err) + } + + if got := srcStat(t, objs, SrcStatChecked); got != 0 { + t.Errorf("checked = %d, want 0: only traffic to the shard SID is filtered", got) + } +} + +func assertDeniedRecord(t *testing.T, objs *NatObjects, wantReason uint32) { + t.Helper() + var key NatSrcDeniedKey + copy(key.Locator[:], srcTestTenantSID.AsSlice()[:8]) + var value NatSrcDeniedValue + if err := objs.NatSrcDenied.Lookup(key, &value); err != nil { + t.Fatalf("lookup nat_src_denied for the source locator: %v", err) + } + if value.Packets != 1 || value.LastReason != wantReason || value.LastIfindex != loIfindex { + t.Errorf("denied record = %+v, want 1 packet, reason %d, ifindex %d", + value, wantReason, loIfindex) + } + if value.LastSeenNs == 0 { + t.Errorf("denied record has no timestamp") + } +} + +func ptr(v uint32) *uint32 { return &v } diff --git a/internal/plumbing/ebpf/natprog/srcfilter.go b/internal/plumbing/ebpf/natprog/srcfilter.go new file mode 100644 index 000000000..6c34d9491 --- /dev/null +++ b/internal/plumbing/ebpf/natprog/srcfilter.go @@ -0,0 +1,47 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package natprog + +// Source filter modes, mirroring the datapath's NAT_SRC_FILTER_* values in +// src_filter_config.mode. Zero is off, so an unwritten config map leaves the +// dispatcher's behaviour unchanged. +const ( + SrcFilterModeOff uint32 = 0 + SrcFilterModeAudit uint32 = 1 + SrcFilterModeEnforce uint32 = 2 +) + +// SrcAllowFlagAnyInterface mirrors NAT_SRC_ALLOW_ANY_IFACE: an allow-list entry +// carrying it is accepted on every uplink, whatever its interface mask. +const SrcAllowFlagAnyInterface uint32 = 0x1 + +// SrcFilterMaxSlot is the highest uplink slot nat_uplink_slot may hold, each +// slot being one bit of a 32-bit interface mask. +const SrcFilterMaxSlot uint8 = 31 + +// Indices into nat_src_filter_stats, mirroring the datapath's nat_src_stat +// enum. SrcStatSlots is the map's size, deliberately larger than SrcStatCount +// so a later counter is an append rather than a map layout change. +const ( + SrcStatChecked uint32 = 0 + SrcStatAllowed uint32 = 1 + SrcStatDenyPrefix uint32 = 2 + SrcStatDenyInterface uint32 = 3 + SrcStatDenyStructure uint32 = 4 + SrcStatBypassUnpopulated uint32 = 5 + SrcStatCount uint32 = 6 + SrcStatSlots uint32 = 16 +) + +// SrcStatNames maps each SrcStat* index to a short, stable, metrics-friendly +// name. +var SrcStatNames = map[uint32]string{ + SrcStatChecked: "checked", + SrcStatAllowed: "allowed", + SrcStatDenyPrefix: "deny_prefix", + SrcStatDenyInterface: "deny_interface", + SrcStatDenyStructure: "deny_structure", + SrcStatBypassUnpopulated: "bypass_unpopulated", +} diff --git a/internal/plumbing/ebpf/natsrcfiltermap/doc.go b/internal/plumbing/ebpf/natsrcfiltermap/doc.go new file mode 100644 index 000000000..bc6dcdf49 --- /dev/null +++ b/internal/plumbing/ebpf/natsrcfiltermap/doc.go @@ -0,0 +1,27 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package natsrcfiltermap is the typed control-plane API for the egress +// translation datapath's SRv6 source filter: the allow-list of fabric source +// prefixes and the uplinks each is reachable through, the uplink slot +// numbering those bindings refer to, the filter's mode and sync state, and its +// read-only decision counters and denied-source record. +// +// # Who writes what +// +// The process that owns a shard writes the mode and its own uplink slots at +// startup. The allow-list, and the populated flag that arms it, belong to a +// reconciler that derives peer prefixes from fabric routes: it writes entries +// with PutAllow and DeleteAllow, then calls MarkPopulated once a full sync has +// landed. Until MarkPopulated runs, the datapath applies only its structural +// source checks and counts every other decision as a bypass, so an allow-list +// that has not been built yet cannot drop traffic. +// +// # Testability +// +// Filter is written against the Table and PerCPUReader interfaces rather than +// loaded maps. NewKernelFilter adapts a loaded object set; NewFakeFilter +// returns one backed by in-memory tables, for tests in this package and in +// callers such as the reconciler. +package natsrcfiltermap diff --git a/internal/plumbing/ebpf/natsrcfiltermap/fake.go b/internal/plumbing/ebpf/natsrcfiltermap/fake.go new file mode 100644 index 000000000..94eee61ff --- /dev/null +++ b/internal/plumbing/ebpf/natsrcfiltermap/fake.go @@ -0,0 +1,173 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package natsrcfiltermap + +import ( + "reflect" + "sync" + + "github.com/cilium/ebpf" +) + +// FakeTable is an in-memory Table with *ebpf.Map's copy-in/copy-out +// semantics, for tests that need no kernel or root. Keys must be comparable +// values. Iteration follows insertion order. +type FakeTable struct { + mu sync.Mutex + entries map[any]any + order []any +} + +// NewFakeTable returns an empty FakeTable. +func NewFakeTable() *FakeTable { + return &FakeTable{entries: make(map[any]any)} +} + +// Put stores value at key. +func (f *FakeTable) Put(key, value any) error { + f.mu.Lock() + defer f.mu.Unlock() + if _, exists := f.entries[key]; !exists { + f.order = append(f.order, key) + } + f.entries[key] = value + return nil +} + +// Lookup copies the value at key into valueOut, or returns +// ebpf.ErrKeyNotExist. +func (f *FakeTable) Lookup(key, valueOut any) error { + f.mu.Lock() + defer f.mu.Unlock() + v, ok := f.entries[key] + if !ok { + return ebpf.ErrKeyNotExist + } + reflect.ValueOf(valueOut).Elem().Set(reflect.ValueOf(v)) + return nil +} + +// Delete removes key, or returns ebpf.ErrKeyNotExist. +func (f *FakeTable) Delete(key any) error { + f.mu.Lock() + defer f.mu.Unlock() + if _, ok := f.entries[key]; !ok { + return ebpf.ErrKeyNotExist + } + delete(f.entries, key) + for i, k := range f.order { + if k == key { + f.order = append(f.order[:i], f.order[i+1:]...) + break + } + } + return nil +} + +// Len returns the number of entries. +func (f *FakeTable) Len() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.order) +} + +// Iterate returns an Iterator over a snapshot of the entries. +func (f *FakeTable) Iterate() Iterator { + f.mu.Lock() + defer f.mu.Unlock() + keys := append([]any(nil), f.order...) + values := make([]any, len(keys)) + for i, k := range keys { + values[i] = f.entries[k] + } + return &fakeIterator{keys: keys, values: values, idx: -1} +} + +type fakeIterator struct { + keys []any + values []any + idx int +} + +func (it *fakeIterator) Next(keyOut, valueOut any) bool { + it.idx++ + if it.idx >= len(it.keys) { + return false + } + reflect.ValueOf(keyOut).Elem().Set(reflect.ValueOf(it.keys[it.idx])) + reflect.ValueOf(valueOut).Elem().Set(reflect.ValueOf(it.values[it.idx])) + return true +} + +func (it *fakeIterator) Err() error { return nil } + +// FakePerCPU is an in-memory PerCPUReader: a fixed per-CPU slice per uint32 +// index, zero-filled for any index not set. +type FakePerCPU struct { + mu sync.Mutex + CPUs int + values map[uint32][]uint64 +} + +// NewFakePerCPU returns a FakePerCPU reporting cpus values per index. +func NewFakePerCPU(cpus int) *FakePerCPU { + return &FakePerCPU{CPUs: cpus, values: make(map[uint32][]uint64)} +} + +// Set stores perCPU at index. +func (f *FakePerCPU) Set(index uint32, perCPU ...uint64) { + f.mu.Lock() + defer f.mu.Unlock() + f.values[index] = append([]uint64(nil), perCPU...) +} + +// Lookup copies index's per-CPU values into valueOut, a *[]uint64. +func (f *FakePerCPU) Lookup(key, valueOut any) error { + f.mu.Lock() + defer f.mu.Unlock() + out, ok := valueOut.(*[]uint64) + if !ok { + return ebpf.ErrNotSupported + } + index, ok := key.(uint32) + if !ok { + return ebpf.ErrNotSupported + } + v, ok := f.values[index] + if !ok { + v = make([]uint64, f.CPUs) + } + *out = append([]uint64(nil), v...) + return nil +} + +// FakeTables holds the in-memory maps behind a fake Filter, for assertions +// and for seeding datapath-owned state such as counters and denials. +type FakeTables struct { + Allow *FakeTable + UplinkSlots *FakeTable + Config *FakeTable + Stats *FakePerCPU + Denied *FakeTable +} + +// NewFakeFilter returns a Filter backed by fresh in-memory maps, and those +// maps. +func NewFakeFilter() (*Filter, *FakeTables) { + fakes := &FakeTables{ + Allow: NewFakeTable(), + UplinkSlots: NewFakeTable(), + Config: NewFakeTable(), + Stats: NewFakePerCPU(2), + Denied: NewFakeTable(), + } + return NewFilter(Tables{ + Allow: fakes.Allow, + UplinkSlots: fakes.UplinkSlots, + Config: fakes.Config, + Stats: fakes.Stats, + Denied: fakes.Denied, + }), fakes +} diff --git a/internal/plumbing/ebpf/natsrcfiltermap/filter.go b/internal/plumbing/ebpf/natsrcfiltermap/filter.go new file mode 100644 index 000000000..251c968a6 --- /dev/null +++ b/internal/plumbing/ebpf/natsrcfiltermap/filter.go @@ -0,0 +1,414 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package natsrcfiltermap + +import ( + "errors" + "fmt" + "net/netip" + "sort" + "strings" + "sync" + "time" + + "github.com/cilium/ebpf" + + "go.datum.net/galactic/internal/plumbing/ebpf/natprog" +) + +// configKey is nat_src_filter_config's single fixed key. +const configKey uint32 = 0 + +// Configuration names of each Mode. +const ( + modeNameOff = "off" + modeNameAudit = "audit" + modeNameEnforce = "enforce" +) + +// Mode is the source filter's operating mode. +type Mode uint32 + +const ( + // ModeOff leaves the dispatcher's behaviour unchanged. + ModeOff = Mode(natprog.SrcFilterModeOff) + // ModeAudit counts every decision and forwards everything. + ModeAudit = Mode(natprog.SrcFilterModeAudit) + // ModeEnforce drops every packet whose source fails a check. + ModeEnforce = Mode(natprog.SrcFilterModeEnforce) +) + +// String returns the mode's configuration name. +func (m Mode) String() string { + switch m { + case ModeOff: + return modeNameOff + case ModeAudit: + return modeNameAudit + case ModeEnforce: + return modeNameEnforce + default: + return fmt.Sprintf("unknown(%d)", uint32(m)) + } +} + +// ParseMode parses off, audit or enforce, case-insensitively. An empty string +// is off. Any other value is an error. +func ParseMode(s string) (Mode, error) { + switch strings.ToLower(strings.TrimSpace(s)) { + case "", modeNameOff: + return ModeOff, nil + case modeNameAudit: + return ModeAudit, nil + case modeNameEnforce: + return ModeEnforce, nil + default: + return ModeOff, fmt.Errorf("unknown SRv6 source filter mode %q (want off, audit or enforce)", s) + } +} + +// Binding is the set of uplinks an allowed prefix may arrive on. +type Binding struct { + // Slots holds one bit per uplink slot, bit N being slot N. + Slots uint32 + + // AnyInterface accepts the prefix on every uplink, ignoring Slots. + AnyInterface bool +} + +// SlotMask returns the interface mask naming each slot in slots. It returns an +// error for a slot above natprog.SrcFilterMaxSlot. +func SlotMask(slots ...uint8) (uint32, error) { + var mask uint32 + for _, s := range slots { + if s > natprog.SrcFilterMaxSlot { + return 0, fmt.Errorf("uplink slot %d out of range [0,%d]", s, natprog.SrcFilterMaxSlot) + } + mask |= 1 << s + } + return mask, nil +} + +// AllowEntry is one allow-list entry. +type AllowEntry struct { + Prefix netip.Prefix + Binding Binding +} + +// Config is nat_src_filter_config's decoded state. +type Config struct { + Mode Mode + Populated bool + Generation uint64 +} + +// Stats is the per-CPU summed value of every decision counter. +type Stats struct { + Checked uint64 + Allowed uint64 + DenyPrefix uint64 + DenyInterface uint64 + DenyStructure uint64 + BypassUnpopulated uint64 +} + +// DeniedSource is one entry of the denied-source record: the sending +// locator, the top 64 bits of the source, and its most recent denial. +type DeniedSource struct { + Locator netip.Prefix + Packets uint64 + LastSeen time.Duration + LastReason string + LastIfindex uint32 +} + +// Tables names the maps a Filter operates on. +type Tables struct { + Allow Table + UplinkSlots Table + Config Table + Stats PerCPUReader + Denied Table +} + +// Filter is the typed API over the source filter's maps. Its methods are safe +// for concurrent use. +type Filter struct { + mu sync.Mutex + t Tables +} + +// NewFilter returns a Filter over tables. +func NewFilter(tables Tables) *Filter { + return &Filter{t: tables} +} + +// NewKernelFilter returns a Filter over a loaded object set's maps. +func NewKernelFilter(objs *natprog.NatObjects) *Filter { + return NewFilter(Tables{ + Allow: KernelTable{Map: objs.NatSrcAllow}, + UplinkSlots: KernelTable{Map: objs.NatUplinkSlot}, + Config: KernelTable{Map: objs.NatSrcFilterConfig}, + Stats: objs.NatSrcFilterStats, + Denied: KernelTable{Map: objs.NatSrcDenied}, + }) +} + +// allowKey validates prefix and encodes it as an LPM key. The prefix must be a +// native IPv6 prefix; host bits below its length are masked off. +func allowKey(prefix netip.Prefix) (natprog.NatSrcAllowKey, error) { + if !prefix.IsValid() || !prefix.Addr().Is6() || prefix.Addr().Is4In6() { + return natprog.NatSrcAllowKey{}, fmt.Errorf("allow prefix %s is not a native IPv6 prefix", prefix) + } + masked := prefix.Masked() + return natprog.NatSrcAllowKey{ + Prefixlen: uint32(masked.Bits()), + Addr: masked.Addr().As16(), + }, nil +} + +// PutAllow creates or replaces the allow-list entry for prefix. It returns an +// error if prefix is not a native IPv6 prefix, or if binding names no uplink +// and does not accept any. +func (f *Filter) PutAllow(prefix netip.Prefix, binding Binding) error { + key, err := allowKey(prefix) + if err != nil { + return fmt.Errorf("natsrcfiltermap: put allow: %w", err) + } + if binding.Slots == 0 && !binding.AnyInterface { + return fmt.Errorf("natsrcfiltermap: put allow %s: binding names no uplink", prefix) + } + value := natprog.NatSrcAllowValue{IfaceMask: binding.Slots} + if binding.AnyInterface { + value.Flags |= natprog.SrcAllowFlagAnyInterface + } + if err := f.t.Allow.Put(key, value); err != nil { + return fmt.Errorf("natsrcfiltermap: put allow %s: %w", prefix, err) + } + return nil +} + +// DeleteAllow removes the allow-list entry for prefix. Deleting an absent +// entry is not an error. +func (f *Filter) DeleteAllow(prefix netip.Prefix) error { + key, err := allowKey(prefix) + if err != nil { + return fmt.Errorf("natsrcfiltermap: delete allow: %w", err) + } + if err := f.t.Allow.Delete(key); err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { + return fmt.Errorf("natsrcfiltermap: delete allow %s: %w", prefix, err) + } + return nil +} + +// ListAllow returns every allow-list entry, sorted by prefix. +func (f *Filter) ListAllow() ([]AllowEntry, error) { + var ( + key natprog.NatSrcAllowKey + value natprog.NatSrcAllowValue + entries []AllowEntry + ) + it := f.t.Allow.Iterate() + for it.Next(&key, &value) { + entries = append(entries, AllowEntry{ + Prefix: netip.PrefixFrom(netip.AddrFrom16(key.Addr), int(key.Prefixlen)), + Binding: Binding{ + Slots: value.IfaceMask, + AnyInterface: value.Flags&natprog.SrcAllowFlagAnyInterface != 0, + }, + }) + } + if err := it.Err(); err != nil { + return nil, fmt.Errorf("natsrcfiltermap: list allow: %w", err) + } + sort.Slice(entries, func(i, j int) bool { + return entries[i].Prefix.String() < entries[j].Prefix.String() + }) + return entries, nil +} + +// SyncUplinkSlots makes nat_uplink_slot hold exactly slots, keyed by ifindex: +// every entry is written and any ifindex not in slots is removed. It returns an +// error for a zero ifindex or a slot above natprog.SrcFilterMaxSlot, before +// writing anything. +func (f *Filter) SyncUplinkSlots(slots map[uint32]uint8) error { + for ifindex, slot := range slots { + if ifindex == 0 { + return errors.New("natsrcfiltermap: sync uplink slots: ifindex 0 is not an interface") + } + if slot > natprog.SrcFilterMaxSlot { + return fmt.Errorf("natsrcfiltermap: sync uplink slots: ifindex %d slot %d out of range [0,%d]", + ifindex, slot, natprog.SrcFilterMaxSlot) + } + } + + f.mu.Lock() + defer f.mu.Unlock() + + current, err := f.uplinkSlots() + if err != nil { + return fmt.Errorf("natsrcfiltermap: sync uplink slots: %w", err) + } + for ifindex, slot := range slots { + if err := f.t.UplinkSlots.Put(ifindex, uint32(slot)); err != nil { + return fmt.Errorf("natsrcfiltermap: sync uplink slots: put ifindex %d: %w", ifindex, err) + } + } + for ifindex := range current { + if _, keep := slots[ifindex]; keep { + continue + } + if err := f.t.UplinkSlots.Delete(ifindex); err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { + return fmt.Errorf("natsrcfiltermap: sync uplink slots: delete ifindex %d: %w", ifindex, err) + } + } + return nil +} + +// UplinkSlots returns every ifindex-to-slot entry. +func (f *Filter) UplinkSlots() (map[uint32]uint8, error) { + slots, err := f.uplinkSlots() + if err != nil { + return nil, fmt.Errorf("natsrcfiltermap: uplink slots: %w", err) + } + return slots, nil +} + +func (f *Filter) uplinkSlots() (map[uint32]uint8, error) { + var ifindex, slot uint32 + out := make(map[uint32]uint8) + it := f.t.UplinkSlots.Iterate() + for it.Next(&ifindex, &slot) { + out[ifindex] = uint8(slot) + } + if err := it.Err(); err != nil { + return nil, err + } + return out, nil +} + +// Config returns the filter's current mode and sync state. An unwritten +// config reads as off and unpopulated. +func (f *Filter) Config() (Config, error) { + raw, err := f.readConfig() + if err != nil { + return Config{}, fmt.Errorf("natsrcfiltermap: config: %w", err) + } + return Config{ + Mode: Mode(raw.Mode), + Populated: raw.Populated != 0, + Generation: raw.Generation, + }, nil +} + +func (f *Filter) readConfig() (natprog.NatSrcFilterConfig, error) { + var raw natprog.NatSrcFilterConfig + if err := f.t.Config.Lookup(configKey, &raw); err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { + return natprog.NatSrcFilterConfig{}, err + } + return raw, nil +} + +// updateConfig applies mutate to the current config and writes it back. The +// datapath only reads this map, so a read-modify-write under f.mu is the only +// writer. +func (f *Filter) updateConfig(mutate func(*natprog.NatSrcFilterConfig)) error { + f.mu.Lock() + defer f.mu.Unlock() + raw, err := f.readConfig() + if err != nil { + return err + } + mutate(&raw) + return f.t.Config.Put(configKey, raw) +} + +// SetMode sets the filter's mode, leaving its sync state as it is. It returns +// an error for a mode other than ModeOff, ModeAudit or ModeEnforce. +func (f *Filter) SetMode(mode Mode) error { + if mode != ModeOff && mode != ModeAudit && mode != ModeEnforce { + return fmt.Errorf("natsrcfiltermap: set mode: unknown mode %d", uint32(mode)) + } + if err := f.updateConfig(func(c *natprog.NatSrcFilterConfig) { c.Mode = uint32(mode) }); err != nil { + return fmt.Errorf("natsrcfiltermap: set mode: %w", err) + } + return nil +} + +// MarkPopulated records that a full allow-list sync has landed, arming the +// prefix and interface checks, and stores generation as that sync's +// identifier. +func (f *Filter) MarkPopulated(generation uint64) error { + err := f.updateConfig(func(c *natprog.NatSrcFilterConfig) { + c.Populated = 1 + c.Generation = generation + }) + if err != nil { + return fmt.Errorf("natsrcfiltermap: mark populated: %w", err) + } + return nil +} + +// MarkUnpopulated disarms the prefix and interface checks, returning the filter +// to its structural checks alone. +func (f *Filter) MarkUnpopulated() error { + if err := f.updateConfig(func(c *natprog.NatSrcFilterConfig) { c.Populated = 0 }); err != nil { + return fmt.Errorf("natsrcfiltermap: mark unpopulated: %w", err) + } + return nil +} + +// Stats returns every decision counter, summed across CPUs. +func (f *Filter) Stats() (Stats, error) { + var totals [natprog.SrcStatCount]uint64 + for i := range natprog.SrcStatCount { + var perCPU []uint64 + if err := f.t.Stats.Lookup(i, &perCPU); err != nil { + return Stats{}, fmt.Errorf("natsrcfiltermap: stats: lookup[%d]: %w", i, err) + } + for _, v := range perCPU { + totals[i] += v + } + } + return Stats{ + Checked: totals[natprog.SrcStatChecked], + Allowed: totals[natprog.SrcStatAllowed], + DenyPrefix: totals[natprog.SrcStatDenyPrefix], + DenyInterface: totals[natprog.SrcStatDenyInterface], + DenyStructure: totals[natprog.SrcStatDenyStructure], + BypassUnpopulated: totals[natprog.SrcStatBypassUnpopulated], + }, nil +} + +// Denied returns the denied-source record, most recent first. LastSeen is the +// kernel's monotonic clock at the denial, not wall time. +func (f *Filter) Denied() ([]DeniedSource, error) { + var ( + key natprog.NatSrcDeniedKey + value natprog.NatSrcDeniedValue + out []DeniedSource + ) + it := f.t.Denied.Iterate() + for it.Next(&key, &value) { + var addr [16]byte + copy(addr[:8], key.Locator[:]) + reason := natprog.SrcStatNames[value.LastReason] + if reason == "" { + reason = fmt.Sprintf("unknown_%d", value.LastReason) + } + out = append(out, DeniedSource{ + Locator: netip.PrefixFrom(netip.AddrFrom16(addr), 64), + Packets: value.Packets, + LastSeen: time.Duration(value.LastSeenNs), + LastReason: reason, + LastIfindex: value.LastIfindex, + }) + } + if err := it.Err(); err != nil { + return nil, fmt.Errorf("natsrcfiltermap: denied: %w", err) + } + sort.Slice(out, func(i, j int) bool { return out[i].LastSeen > out[j].LastSeen }) + return out, nil +} diff --git a/internal/plumbing/ebpf/natsrcfiltermap/filter_test.go b/internal/plumbing/ebpf/natsrcfiltermap/filter_test.go new file mode 100644 index 000000000..a80236d5d --- /dev/null +++ b/internal/plumbing/ebpf/natsrcfiltermap/filter_test.go @@ -0,0 +1,277 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package natsrcfiltermap + +import ( + "net/netip" + "reflect" + "testing" + "time" + + "go.datum.net/galactic/internal/plumbing/ebpf/natprog" +) + +func TestParseMode(t *testing.T) { + tests := []struct { + name string + input string + want Mode + wantError bool + }{ + {"Empty", "", ModeOff, false}, + {"Off", modeNameOff, ModeOff, false}, + {"Audit", modeNameAudit, ModeAudit, false}, + {"EnforceMixedCase", " Enforce ", ModeEnforce, false}, + {"Unknown", "strict", ModeOff, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := ParseMode(tt.input) + if (err != nil) != tt.wantError { + t.Fatalf("ParseMode(%q) error = %v, wantError = %v", tt.input, err, tt.wantError) + } + if got != tt.want { + t.Errorf("ParseMode(%q) = %v, want %v", tt.input, got, tt.want) + } + if !tt.wantError { + if back, _ := ParseMode(got.String()); back != got { + t.Errorf("ParseMode(%q.String()) = %v, want %v", got, back, got) + } + } + }) + } +} + +func TestSlotMask(t *testing.T) { + tests := []struct { + name string + slots []uint8 + want uint32 + wantError bool + }{ + {"None", nil, 0, false}, + {"FirstAndLast", []uint8{0, 31}, 1 | 1<<31, false}, + {"OutOfRange", []uint8{32}, 0, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := SlotMask(tt.slots...) + if (err != nil) != tt.wantError { + t.Fatalf("SlotMask(%v) error = %v, wantError = %v", tt.slots, err, tt.wantError) + } + if got != tt.want { + t.Errorf("SlotMask(%v) = %#x, want %#x", tt.slots, got, tt.want) + } + }) + } +} + +func TestPutAllowEncodesAndMasks(t *testing.T) { + f, fakes := NewFakeFilter() + + if err := f.PutAllow(netip.MustParsePrefix("fc00:0:0:1:ffff::/64"), Binding{Slots: 0b101}); err != nil { + t.Fatalf("PutAllow: %v", err) + } + if err := f.PutAllow(netip.MustParsePrefix("fc00:0:1::/48"), Binding{AnyInterface: true}); err != nil { + t.Fatalf("PutAllow: %v", err) + } + + var value natprog.NatSrcAllowValue + key := natprog.NatSrcAllowKey{Prefixlen: 64, Addr: netip.MustParseAddr("fc00:0:0:1::").As16()} + if err := fakes.Allow.Lookup(key, &value); err != nil { + t.Fatalf("masked key not stored: %v", err) + } + if value.IfaceMask != 0b101 || value.Flags != 0 { + t.Errorf("value = %+v, want mask 0b101 and no flags", value) + } + + got, err := f.ListAllow() + if err != nil { + t.Fatalf("ListAllow: %v", err) + } + want := []AllowEntry{ + {Prefix: netip.MustParsePrefix("fc00:0:0:1::/64"), Binding: Binding{Slots: 0b101}}, + {Prefix: netip.MustParsePrefix("fc00:0:1::/48"), Binding: Binding{AnyInterface: true}}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("ListAllow = %+v, want %+v", got, want) + } +} + +func TestPutAllowRejects(t *testing.T) { + tests := []struct { + name string + prefix netip.Prefix + binding Binding + }{ + {"IPv4Prefix", netip.MustParsePrefix("192.0.2.0/24"), Binding{AnyInterface: true}}, + {"MappedPrefix", netip.MustParsePrefix("::ffff:192.0.2.0/120"), Binding{AnyInterface: true}}, + {"InvalidPrefix", netip.Prefix{}, Binding{AnyInterface: true}}, + {"NoUplink", netip.MustParsePrefix("fc00::/48"), Binding{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, fakes := NewFakeFilter() + if err := f.PutAllow(tt.prefix, tt.binding); err == nil { + t.Errorf("PutAllow(%s, %+v) succeeded, want error", tt.prefix, tt.binding) + } + if fakes.Allow.Len() != 0 { + t.Errorf("rejected entry was written") + } + }) + } +} + +func TestDeleteAllowToleratesAbsent(t *testing.T) { + f, fakes := NewFakeFilter() + prefix := netip.MustParsePrefix("fc00:0:0:1::/64") + + if err := f.DeleteAllow(prefix); err != nil { + t.Fatalf("DeleteAllow(absent): %v", err) + } + if err := f.PutAllow(prefix, Binding{Slots: 1}); err != nil { + t.Fatalf("PutAllow: %v", err) + } + if err := f.DeleteAllow(prefix); err != nil { + t.Fatalf("DeleteAllow: %v", err) + } + if fakes.Allow.Len() != 0 { + t.Errorf("entry survived DeleteAllow") + } +} + +func TestSyncUplinkSlots(t *testing.T) { + f, _ := NewFakeFilter() + + if err := f.SyncUplinkSlots(map[uint32]uint8{2: 0, 3: 1, 7: 2}); err != nil { + t.Fatalf("SyncUplinkSlots: %v", err) + } + if err := f.SyncUplinkSlots(map[uint32]uint8{3: 0, 9: 1}); err != nil { + t.Fatalf("SyncUplinkSlots: %v", err) + } + got, err := f.UplinkSlots() + if err != nil { + t.Fatalf("UplinkSlots: %v", err) + } + want := map[uint32]uint8{3: 0, 9: 1} + if !reflect.DeepEqual(got, want) { + t.Errorf("UplinkSlots = %v, want %v", got, want) + } +} + +func TestSyncUplinkSlotsRejectsBeforeWriting(t *testing.T) { + tests := []struct { + name string + slots map[uint32]uint8 + }{ + {"ZeroIfindex", map[uint32]uint8{0: 0, 2: 1}}, + {"SlotOutOfRange", map[uint32]uint8{2: 32}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, fakes := NewFakeFilter() + if err := f.SyncUplinkSlots(tt.slots); err == nil { + t.Errorf("SyncUplinkSlots(%v) succeeded, want error", tt.slots) + } + if fakes.UplinkSlots.Len() != 0 { + t.Errorf("rejected sync wrote entries") + } + }) + } +} + +func TestConfigModeAndPopulated(t *testing.T) { + f, _ := NewFakeFilter() + + cfg, err := f.Config() + if err != nil { + t.Fatalf("Config: %v", err) + } + if cfg != (Config{}) { + t.Errorf("unwritten Config = %+v, want zero (off, unpopulated)", cfg) + } + + if err := f.MarkPopulated(7); err != nil { + t.Fatalf("MarkPopulated: %v", err) + } + if err := f.SetMode(ModeEnforce); err != nil { + t.Fatalf("SetMode: %v", err) + } + cfg, err = f.Config() + if err != nil { + t.Fatalf("Config: %v", err) + } + if want := (Config{Mode: ModeEnforce, Populated: true, Generation: 7}); cfg != want { + t.Errorf("Config = %+v, want %+v", cfg, want) + } + + if err := f.MarkUnpopulated(); err != nil { + t.Fatalf("MarkUnpopulated: %v", err) + } + cfg, err = f.Config() + if err != nil { + t.Fatalf("Config: %v", err) + } + if want := (Config{Mode: ModeEnforce, Generation: 7}); cfg != want { + t.Errorf("Config after MarkUnpopulated = %+v, want %+v", cfg, want) + } + + if err := f.SetMode(Mode(9)); err == nil { + t.Errorf("SetMode(9) succeeded, want error") + } +} + +func TestStatsSumsAcrossCPUs(t *testing.T) { + f, fakes := NewFakeFilter() + fakes.Stats.Set(natprog.SrcStatChecked, 4, 6) + fakes.Stats.Set(natprog.SrcStatAllowed, 3, 1) + fakes.Stats.Set(natprog.SrcStatDenyPrefix, 1, 0) + fakes.Stats.Set(natprog.SrcStatDenyInterface, 0, 2) + fakes.Stats.Set(natprog.SrcStatDenyStructure, 1, 1) + fakes.Stats.Set(natprog.SrcStatBypassUnpopulated, 0, 0) + + got, err := f.Stats() + if err != nil { + t.Fatalf("Stats: %v", err) + } + want := Stats{Checked: 10, Allowed: 4, DenyPrefix: 1, DenyInterface: 2, DenyStructure: 2} + if got != want { + t.Errorf("Stats = %+v, want %+v", got, want) + } +} + +func TestDeniedDecodesMostRecentFirst(t *testing.T) { + f, fakes := NewFakeFilter() + + older := natprog.NatSrcDeniedKey{} + copy(older.Locator[:], netip.MustParseAddr("fc00:0:0:1::").AsSlice()[:8]) + newer := natprog.NatSrcDeniedKey{} + copy(newer.Locator[:], netip.MustParseAddr("fc00:0:0:2::").AsSlice()[:8]) + + _ = fakes.Denied.Put(older, natprog.NatSrcDeniedValue{ + Packets: 3, LastSeenNs: 100, LastReason: natprog.SrcStatDenyPrefix, LastIfindex: 2, + }) + _ = fakes.Denied.Put(newer, natprog.NatSrcDeniedValue{ + Packets: 1, LastSeenNs: 200, LastReason: natprog.SrcStatDenyInterface, LastIfindex: 4, + }) + + got, err := f.Denied() + if err != nil { + t.Fatalf("Denied: %v", err) + } + want := []DeniedSource{ + { + Locator: netip.MustParsePrefix("fc00:0:0:2::/64"), Packets: 1, + LastSeen: 200 * time.Nanosecond, LastReason: "deny_interface", LastIfindex: 4, + }, + { + Locator: netip.MustParsePrefix("fc00:0:0:1::/64"), Packets: 3, + LastSeen: 100 * time.Nanosecond, LastReason: "deny_prefix", LastIfindex: 2, + }, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("Denied = %+v, want %+v", got, want) + } +} diff --git a/internal/plumbing/ebpf/natsrcfiltermap/kernel_test.go b/internal/plumbing/ebpf/natsrcfiltermap/kernel_test.go new file mode 100644 index 000000000..b07bc0955 --- /dev/null +++ b/internal/plumbing/ebpf/natsrcfiltermap/kernel_test.go @@ -0,0 +1,104 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package natsrcfiltermap + +import ( + "net/netip" + "os" + "reflect" + "testing" + + "github.com/cilium/ebpf/rlimit" + + "go.datum.net/galactic/internal/plumbing/ebpf/natprog" +) + +func requireRoot(t *testing.T) { + t.Helper() + if os.Geteuid() != 0 { + t.Skip("test requires root (CAP_BPF) to load BPF maps; re-run via sudo") + } + if err := rlimit.RemoveMemlock(); err != nil { + t.Fatalf("rlimit.RemoveMemlock: %v", err) + } +} + +// TestKernelFilterRoundTrip drives every Filter operation against the real +// maps, which the fake cannot vouch for: LPM key encoding, trie iteration, and +// per-CPU reads. +func TestKernelFilterRoundTrip(t *testing.T) { + requireRoot(t) + + var objs natprog.NatObjects + if err := natprog.LoadNatObjects(&objs, nil); err != nil { + t.Fatalf("load objects: %v", err) + } + t.Cleanup(func() { _ = objs.Close() }) + f := NewKernelFilter(&objs) + + if err := f.PutAllow(netip.MustParsePrefix("fc00:3:4::/48"), Binding{Slots: 0b11}); err != nil { + t.Fatalf("PutAllow: %v", err) + } + if err := f.PutAllow(netip.MustParsePrefix("fc00:3:5:1::/64"), Binding{AnyInterface: true}); err != nil { + t.Fatalf("PutAllow: %v", err) + } + if err := f.DeleteAllow(netip.MustParsePrefix("fc00:9::/48")); err != nil { + t.Fatalf("DeleteAllow(absent): %v", err) + } + entries, err := f.ListAllow() + if err != nil { + t.Fatalf("ListAllow: %v", err) + } + wantEntries := []AllowEntry{ + {Prefix: netip.MustParsePrefix("fc00:3:4::/48"), Binding: Binding{Slots: 0b11}}, + {Prefix: netip.MustParsePrefix("fc00:3:5:1::/64"), Binding: Binding{AnyInterface: true}}, + } + if !reflect.DeepEqual(entries, wantEntries) { + t.Errorf("ListAllow = %+v, want %+v", entries, wantEntries) + } + + if err := f.SyncUplinkSlots(map[uint32]uint8{2: 0, 5: 1}); err != nil { + t.Fatalf("SyncUplinkSlots: %v", err) + } + if err := f.SyncUplinkSlots(map[uint32]uint8{5: 0}); err != nil { + t.Fatalf("SyncUplinkSlots: %v", err) + } + slots, err := f.UplinkSlots() + if err != nil { + t.Fatalf("UplinkSlots: %v", err) + } + if want := map[uint32]uint8{5: 0}; !reflect.DeepEqual(slots, want) { + t.Errorf("UplinkSlots = %v, want %v", slots, want) + } + + if err := f.SetMode(ModeAudit); err != nil { + t.Fatalf("SetMode: %v", err) + } + if err := f.MarkPopulated(3); err != nil { + t.Fatalf("MarkPopulated: %v", err) + } + cfg, err := f.Config() + if err != nil { + t.Fatalf("Config: %v", err) + } + if want := (Config{Mode: ModeAudit, Populated: true, Generation: 3}); cfg != want { + t.Errorf("Config = %+v, want %+v", cfg, want) + } + + stats, err := f.Stats() + if err != nil { + t.Fatalf("Stats: %v", err) + } + if stats != (Stats{}) { + t.Errorf("Stats on a fresh map = %+v, want zero", stats) + } + denied, err := f.Denied() + if err != nil { + t.Fatalf("Denied: %v", err) + } + if len(denied) != 0 { + t.Errorf("Denied on a fresh map = %+v, want none", denied) + } +} diff --git a/internal/plumbing/ebpf/natsrcfiltermap/table.go b/internal/plumbing/ebpf/natsrcfiltermap/table.go new file mode 100644 index 000000000..fe472b075 --- /dev/null +++ b/internal/plumbing/ebpf/natsrcfiltermap/table.go @@ -0,0 +1,51 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package natsrcfiltermap + +import "github.com/cilium/ebpf" + +// Table is the map-operation surface Filter is written against. A loaded +// *ebpf.Map satisfies it through KernelTable. +type Table interface { + // Put creates or overwrites the entry at key with value. + Put(key, value any) error + + // Lookup reads the entry at key into valueOut, returning an error matching + // ebpf.ErrKeyNotExist when key is absent. + Lookup(key, valueOut any) error + + // Delete removes the entry at key, returning an error matching + // ebpf.ErrKeyNotExist when key is absent. + Delete(key any) error + + // Iterate returns an Iterator over every entry, in unspecified order. + Iterate() Iterator +} + +// Iterator matches *ebpf.MapIterator's Next/Err method set. +type Iterator interface { + // Next decodes the next pair into keyOut and valueOut and reports whether + // one was available. + Next(keyOut, valueOut any) bool + + // Err returns the first error encountered during iteration. + Err() error +} + +// PerCPUReader reads one per-CPU array slot into a slice with one value per +// CPU. A loaded per-CPU *ebpf.Map satisfies it directly. +type PerCPUReader interface { + Lookup(key, valueOut any) error +} + +// KernelTable adapts a loaded map to Table. +type KernelTable struct { + Map *ebpf.Map +} + +func (k KernelTable) Put(key, value any) error { return k.Map.Put(key, value) } +func (k KernelTable) Lookup(key, valueOut any) error { return k.Map.Lookup(key, valueOut) } +func (k KernelTable) Delete(key any) error { return k.Map.Delete(key) } +func (k KernelTable) Iterate() Iterator { return k.Map.Iterate() }