From a53af15dc7c5df3a4d2c4dffc4ddd5b060f7fb15 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 23 Sep 2026 21:43:11 -0500 Subject: [PATCH 1/2] feat(cni): populate the SRv6 source filter from fabric routes galactic-cni run now builds the uSID datapath's SRv6 ingress source allow-list from the routes the node already learns and keeps it current, so a node can accept tenant SRv6 traffic only from fabric peers once an operator enables audit or enforce mode. Nothing changes until then. - internal/srcfilter: reconciler turning main-table routes inside the SR domain prefixes (>= /64, excluding the node's own locator) into allow entries bound to the uplink slots their hops use, bonds and VLANs on bonds expanded to slaves; writes before deletes, marks the filter populated only after a clean pass, and keeps the previous list on any read failure or an empty route set - Target and SlotAssigner interfaces so other datapaths can reuse it behind a thin adapter; USIDTarget adapts srcfiltermap - attach.Watcher.Reevaluated triggers a pass after each debounced netlink re-evaluation, plus a 60 s resync that survives the watch loop - GALACTIC_CNI_SRV6_SOURCE_FILTER/_DOMAIN_PREFIXES/_SOURCE_BINDING/ _SOURCE_ALLOW_EXTRA; off by default, invalid config writes off - galactic_usid_src_filter_* metrics and a srv6-source-filter health service no probe depends on --- docs/cni/architecture.md | 32 ++ docs/cni/environment-variables.md | 24 + internal/config/cni.go | 20 + internal/installer/installer.go | 5 + internal/installer/srcfilter.go | 178 ++++++++ internal/installer/srcfilter_test.go | 95 ++++ internal/plumbing/ebpf/attach/watch.go | 31 +- internal/plumbing/ebpf/attach/watch_test.go | 32 ++ internal/plumbing/ebpf/metrics/collector.go | 104 ++++- .../plumbing/ebpf/metrics/srcfilter_test.go | 97 ++++ internal/srcfilter/desired.go | 193 ++++++++ internal/srcfilter/doc.go | 17 + internal/srcfilter/reconciler.go | 289 ++++++++++++ internal/srcfilter/reconciler_test.go | 424 ++++++++++++++++++ internal/srcfilter/settings.go | 163 +++++++ internal/srcfilter/settings_test.go | 82 ++++ internal/srcfilter/slots.go | 65 +++ internal/srcfilter/slots_test.go | 78 ++++ internal/srcfilter/target.go | 53 +++ internal/srcfilter/usidtarget.go | 110 +++++ 20 files changed, 2086 insertions(+), 6 deletions(-) create mode 100644 internal/installer/srcfilter.go create mode 100644 internal/installer/srcfilter_test.go create mode 100644 internal/plumbing/ebpf/metrics/srcfilter_test.go create mode 100644 internal/srcfilter/desired.go create mode 100644 internal/srcfilter/doc.go create mode 100644 internal/srcfilter/reconciler.go create mode 100644 internal/srcfilter/reconciler_test.go create mode 100644 internal/srcfilter/settings.go create mode 100644 internal/srcfilter/settings_test.go create mode 100644 internal/srcfilter/slots.go create mode 100644 internal/srcfilter/slots_test.go create mode 100644 internal/srcfilter/target.go create mode 100644 internal/srcfilter/usidtarget.go diff --git a/docs/cni/architecture.md b/docs/cni/architecture.md index 85757486b..b8198d6c5 100644 --- a/docs/cni/architecture.md +++ b/docs/cni/architecture.md @@ -211,6 +211,38 @@ is set in the entry's mask. | `src_filter_stats` | Per-CPU array (8) | Checked, allowed, denied by prefix, denied by interface, bypassed before first sync | | `src_filter_denied` | LRU hash (1024) | Denied source /64s with count, last interface, last reason and time, for triage | +#### Control plane + +`galactic-cni run` (the DaemonSet's long-running `credential-refresh` +container) owns the allow-list through `internal/srcfilter`. It is started only +when `GALACTIC_CNI_SRV6_SOURCE_FILTER` is `audit` or `enforce`; with `off`, or +an invalid configuration, the container writes mode `off` and starts nothing. + +- **Inputs.** Every main-table IPv6 route of any protocol that forwards: peer + locators arrive from FRR as BGP routes, egress shard SIDs as boot-protocol + routes. A route counts only if it lies inside a configured SR domain prefix, + is at least a /64 (so an aggregate never allows unassigned node IDs), and is + not inside this node's own locator from its `BGPRouter`. +- **Interface binding.** An entry's mask is the union of the slots of every + hop's link, a bond master or a VLAN on a bond counting as the bond's slaves. + Uplinks are what `attach.ResolveInterfaces` returns, each keeping its slot + for as long as it exists (at most 32). Loose binding, or a hop whose link is + unknown, accepts the entry on any interface. Static extra sources always do. +- **Apply.** Uplink slots first, then new and changed entries, then removals, + then the config with `populated` set and the generation bumped. `populated` + is set only after a pass with no error, and the configured mode is written + as soon as the reconciler starts. +- **Failure.** A pass that cannot read routes, links, uplinks or the node's + locator, or that finds no fabric route at all, changes nothing, so the last + allow-list stays in force. The outcome is reported on the + `srv6-source-filter` gRPC health service, which no probe checks. +- **Triggers.** Startup, every debounced re-evaluation of the attach watch loop + (`Watcher.Reevaluated`), and a 60 s resync that keeps running if the watch + loop dies. The resync also logs the most-denied sources at debug level. +- **Reuse.** The reconciler writes through the `srcfilter.Target` interface; + `USIDTarget` adapts `srcfiltermap`. `SlotAssigner` lets a datapath that owns + its own uplink slots (`KeepSlots`) reuse it unchanged. + --- ## Data flow diff --git a/docs/cni/environment-variables.md b/docs/cni/environment-variables.md index 55faa4c9e..cb29ea39f 100644 --- a/docs/cni/environment-variables.md +++ b/docs/cni/environment-variables.md @@ -59,6 +59,7 @@ they resolve only `LogFile`/`LogLevel` from `HostConf` — never `NodeName` or | DAN directory | `GALACTIC_CNI_DAN_DIR` env → `HostConf.DANDir` | `/run/kata-containers/dans-rs` | `galactic-cni init`, `galactic-tap` | | eBPF filter priority | `GALACTIC_CNI_EBPF_FILTER_PRIORITY` env (plain `os.Getenv`, no `HostConf`/conflist tier) | `1` | `galactic-cni init`/`run` | | Fabric MTU limits | `GALACTIC_CNI_TCP_MSS_CLAMP` env (plain `os.Getenv`, no `HostConf`/conflist tier) | `auto` | `galactic-cni run` | +| SRv6 source filter | `GALACTIC_CNI_SRV6_*` env (plain `os.Getenv`, `galactic-cni run` only) | `off` | `galactic-cni run` | `GALACTIC_CNI_*` env var names are shared as-is across every binary that resolves node-level settings — there's no per-binary prefix for these, since @@ -194,6 +195,29 @@ of 100; refusals are counted as `rate_limited`. **Type:** `auto`, `off`, or an MTU · **Default:** `auto` +## SRv6 ingress source filter + +Controls the uSID datapath's SRv6 ingress source filter: a node accepts SRv6 traffic for its tenant networks only from sources inside a fabric peer's locator, and only on the uplinks its route to that peer uses. `galactic-cni run` builds the allow-list from the node's main routing table and keeps it current. Read only by that container, with no conflist tier. + +| Variable | Values | Default | Effect | +| -------------------------------------- | ----------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- | +| `GALACTIC_CNI_SRV6_SOURCE_FILTER` | `off`, `audit`, `enforce` | `off` | `off` leaves traffic untouched and starts no reconciler. `audit` counts and records sources it would reject. `enforce` drops them. | +| `GALACTIC_CNI_SRV6_DOMAIN_PREFIXES` | comma-separated IPv6 prefixes | _(none)_ | The prefixes fabric locators are allocated from. Only routes inside them, and at least a /64, become allowed sources. Required unless `off`. | +| `GALACTIC_CNI_SRV6_SOURCE_BINDING` | `strict`, `loose` | `strict` | `strict` accepts a source only on the uplinks this node's route to it uses. `loose` accepts a known source on any uplink. | +| `GALACTIC_CNI_SRV6_SOURCE_ALLOW_EXTRA` | comma-separated IPv6 prefixes | _(none)_ | Extra sources allowed on any uplink, for senders with no route in the main table. | + +- An invalid value, or `audit`/`enforce` without domain prefixes, logs an error, writes `off` and reports the `srv6-source-filter` health service as not serving. The filter is never enforced on a configuration it could not read. +- The filter lets every packet through until the first complete sync, and a sync that cannot read routes, or finds no fabric route at all, keeps the previous allow-list rather than clearing it. +- Roll out with `audit` first and watch `galactic_usid_src_filter_packets_total{result=~"deny_.*"}` before switching to `enforce`. Debug logging lists the most-denied sources every minute. + +| Metric | Type | Meaning | +| ----------------------------------------- | ------- | ---------------------------------------------------------------------------------------------- | +| `galactic_usid_src_filter_packets_total` | counter | Decisions by `result`: `checked`, `allowed`, `deny_prefix`, `deny_iface`, `bypass_unpopulated` | +| `galactic_usid_src_filter_entries` | gauge | Allowed source prefixes | +| `galactic_usid_src_filter_mode` | gauge | 0 off, 1 audit, 2 enforce | +| `galactic_usid_src_filter_populated` | gauge | 1 once the allow-list reflects a complete sync | +| `galactic_usid_src_filter_denied_sources` | gauge | Distinct denied source /64s recorded for triage | + ## `GALACTIC_CNI_EGRESS_SHARD_SIDS` Comma-separated list of the `galactic-nat` shards' `Status.ShardSID`s this diff --git a/internal/config/cni.go b/internal/config/cni.go index b2f20690d..021a1bdd4 100644 --- a/internal/config/cni.go +++ b/internal/config/cni.go @@ -52,6 +52,26 @@ const ( // internal/plumbing/ebpf/mssclamp. EnvCNITCPMSSClamp = "GALACTIC_CNI_TCP_MSS_CLAMP" + // EnvCNISRv6SourceFilter sets the uSID datapath's SRv6 ingress source + // filter mode: off (the default), audit or enforce. Read only by + // galactic-cni run. + EnvCNISRv6SourceFilter = "GALACTIC_CNI_SRV6_SOURCE_FILTER" + + // EnvCNISRv6DomainPrefixes is a comma-separated list of the IPv6 prefixes + // the fabric's locators are allocated from. Only routes inside them become + // allowed sources. Required unless the source filter is off. + EnvCNISRv6DomainPrefixes = "GALACTIC_CNI_SRV6_DOMAIN_PREFIXES" + + // EnvCNISRv6SourceBinding is strict (the default), accepting a source only + // on the uplinks this node's route to it uses, or loose, accepting a known + // source on any uplink. + EnvCNISRv6SourceBinding = "GALACTIC_CNI_SRV6_SOURCE_BINDING" + + // EnvCNISRv6SourceAllowExtra is a comma-separated list of extra IPv6 + // source prefixes to allow on any uplink, for senders with no route in + // the main table. + EnvCNISRv6SourceAllowExtra = "GALACTIC_CNI_SRV6_SOURCE_ALLOW_EXTRA" + // EnvCNIEgressShardSIDs is a comma-separated list of every live egress // shard's SID: the fabric-wide membership a tenant VRF's egress routes need. // One SID per shard covers both address families -- a shard decides which diff --git a/internal/installer/installer.go b/internal/installer/installer.go index 695f480e8..907901f66 100644 --- a/internal/installer/installer.go +++ b/internal/installer/installer.go @@ -1165,6 +1165,9 @@ func NewMetrics() *metrics.Metrics { // replies to that guest's solicitations. This runs here, not from // galactic-tap's cmdAdd, because a guest's boot outlives that short-lived // process. It is independent of the eBPF datapath and runs regardless. +// 9. Keeps the SRv6 ingress source filter's allow-list in step with this +// node's routes when it is enabled, reporting on its own +// srcFilterHealthServiceName health service. func Run(ctx context.Context, grpcHealthPort, metricsPort int) error { slog.Info("Starting CNI installer run daemon", "grpcHealthPort", grpcHealthPort, "metricsPort", metricsPort) @@ -1233,6 +1236,8 @@ func Run(ctx context.Context, grpcHealthPort, metricsPort int) error { healthSrv.SetServingStatus(ebpfHealthServiceName, grpc_health_v1.HealthCheckResponse_SERVING) } + startSourceFilter(ctx, ebpfState, healthSrv) + go func() { if err := grpcSrv.Serve(lis); err != nil && !errors.Is(err, grpc.ErrServerStopped) { slog.Error("gRPC health server exited with error", "err", err) diff --git a/internal/installer/srcfilter.go b/internal/installer/srcfilter.go new file mode 100644 index 000000000..5733f8f60 --- /dev/null +++ b/internal/installer/srcfilter.go @@ -0,0 +1,178 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package installer + +import ( + "context" + "log/slog" + "net/netip" + "os" + "time" + + "github.com/vishvananda/netlink" + "google.golang.org/grpc/health" + "google.golang.org/grpc/health/grpc_health_v1" + + "go.datum.net/galactic/internal/plumbing/ebpf/attach" + "go.datum.net/galactic/internal/plumbing/ebpf/srcfiltermap" + "go.datum.net/galactic/internal/srcfilter" +) + +// srcFilterResyncInterval paces the source filter's periodic full pass, which +// heals drift no netlink event reports. A var so tests can shrink it. +var srcFilterResyncInterval = 60 * time.Second + +// srcFilterTopDenied is how many denied sources each periodic pass logs at +// debug level. +const srcFilterTopDenied = 5 + +// srcFilterHealthServiceName is the gRPC health service reporting whether the +// source filter's last pass succeeded. It is separate from +// ebpfHealthServiceName so a control-plane fault here never fails the +// datapath's own probes. +const srcFilterHealthServiceName = "srv6-source-filter" + +// startSourceFilter configures the uSID datapath's SRv6 ingress source filter +// from the environment and, unless it is off, starts a goroutine that keeps its +// allow-list in step with this node's routes until ctx is canceled. +// +// A pass runs at startup, after every debounced re-evaluation of st.watcher, +// and every srcFilterResyncInterval, so the filter keeps being maintained if +// the watch loop dies. Mode off, or a configuration error, writes mode off and +// starts nothing; a configuration error also reports the health service not +// serving. A nil st.objs means no datapath is loaded, and nothing happens. +func startSourceFilter(ctx context.Context, st ebpfDatapathState, healthSrv *health.Server) { + if st.objs == nil { + return + } + filter := srcfiltermap.NewFromObjects(st.objs) + target := srcfilter.USIDTarget{Filter: filter} + + settings, err := srcfilter.LoadSettings(os.Getenv) + if err != nil { + slog.Error("SRv6 source filter configuration is invalid; leaving the filter off", "err", err) + healthSrv.SetServingStatus(srcFilterHealthServiceName, grpc_health_v1.HealthCheckResponse_NOT_SERVING) + disableSourceFilter(target) + return + } + if settings.Mode == srcfilter.ModeOff { + disableSourceFilter(target) + return + } + + r, err := srcfilter.New(srcfilter.Options{ + Settings: settings, + Target: target, + Routes: srcfilter.MainTableRoutes, + Links: netlink.LinkList, + Uplinks: attach.ResolveInterfaces, + OwnLocator: ownLocatorFn(st), + }) + if err != nil { + slog.Error("Could not start the SRv6 source filter reconciler; leaving the filter off", "err", err) + healthSrv.SetServingStatus(srcFilterHealthServiceName, grpc_health_v1.HealthCheckResponse_NOT_SERVING) + disableSourceFilter(target) + return + } + + slog.Info("SRv6 source filter reconciler starting", "mode", settings.Mode.String(), + "binding", settings.Binding.String(), "domainPrefixes", settings.DomainPrefixes, + "extraSources", settings.ExtraSources) + healthSrv.SetServingStatus(srcFilterHealthServiceName, grpc_health_v1.HealthCheckResponse_NOT_SERVING) + go runSourceFilter(ctx, r, filter, st.watcher, healthSrv) +} + +// runSourceFilter drives r until ctx is canceled, publishing each pass's +// outcome on the health service. +func runSourceFilter( + ctx context.Context, r *srcfilter.Reconciler, filter *srcfiltermap.Filter, w *attach.Watcher, + healthSrv *health.Server, +) { + ticker := time.NewTicker(srcFilterResyncInterval) + defer ticker.Stop() + + var lastErr string + pass := func() { + lastErr = sourceFilterPass(ctx, r, healthSrv, lastErr) + } + + pass() + for { + select { + case <-ctx.Done(): + return + case <-w.Reevaluated(): + pass() + case <-ticker.C: + pass() + logTopDeniedSources(ctx, filter) + } + } +} + +// sourceFilterPass runs one pass and reports it. lastErr is the previous +// pass's error text, empty after a success; a repeated failure logs at debug +// rather than error. It returns this pass's error text. +func sourceFilterPass(ctx context.Context, r *srcfilter.Reconciler, healthSrv *health.Server, lastErr string) string { + res, err := r.Reconcile(ctx) + if err != nil { + healthSrv.SetServingStatus(srcFilterHealthServiceName, grpc_health_v1.HealthCheckResponse_NOT_SERVING) + level := slog.LevelError + if err.Error() == lastErr { + level = slog.LevelDebug + } + slog.Log(ctx, level, "SRv6 source filter pass failed; keeping the previous allow-list", + "err", err, "populated", res.State.Populated) + return err.Error() + } + + healthSrv.SetServingStatus(srcFilterHealthServiceName, grpc_health_v1.HealthCheckResponse_SERVING) + if lastErr != "" { + slog.Info("SRv6 source filter pass recovered") + } + if res.Changed { + slog.Info("SRv6 source filter allow-list updated", "entries", res.Entries, "added", res.Added, + "updated", res.Updated, "removed", res.Removed, "unbound", res.Unbound, "uplinks", res.SlotCount, + "mode", res.State.Mode.String(), "generation", res.State.Generation) + } + return "" +} + +// ownLocatorFn returns the lookup for this node's own locator, or nil when no +// Kubernetes client is available, in which case the own locator is not +// excluded. +func ownLocatorFn(st ebpfDatapathState) func(context.Context) (netip.Prefix, error) { + if st.k8sClient == nil { + slog.Warn("SRv6 source filter cannot exclude this node's own locator: no Kubernetes client") + return nil + } + return func(ctx context.Context) (netip.Prefix, error) { + return nodeLocatorPrefix(ctx, st.k8sClient, st.namespace, st.nodeName) + } +} + +// disableSourceFilter writes mode off, logging a failure. +func disableSourceFilter(target srcfilter.Target) { + if err := srcfilter.Disable(target); err != nil { + slog.Error("Could not turn the SRv6 source filter off", "err", err) + } +} + +// logTopDeniedSources logs the most-denied sources at debug level, for triage +// without turning source addresses into metric labels. +func logTopDeniedSources(ctx context.Context, filter *srcfiltermap.Filter) { + if !slog.Default().Enabled(ctx, slog.LevelDebug) { + return + } + denied, err := filter.DeniedSources() + if err != nil { + slog.Debug("Could not read SRv6 source filter denials", "err", err) + return + } + for _, d := range denied[:min(len(denied), srcFilterTopDenied)] { + slog.Debug("SRv6 source filter denied source", "prefix", d.Prefix.String(), "count", d.Count, + "lastIfindex", d.LastIfindex, "lastReason", d.LastReason.String()) + } +} diff --git a/internal/installer/srcfilter_test.go b/internal/installer/srcfilter_test.go new file mode 100644 index 000000000..baeff7a34 --- /dev/null +++ b/internal/installer/srcfilter_test.go @@ -0,0 +1,95 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package installer + +import ( + "context" + "errors" + "net" + "net/netip" + "testing" + + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" + "google.golang.org/grpc/health" + "google.golang.org/grpc/health/grpc_health_v1" + + "go.datum.net/galactic/internal/plumbing/ebpf/srcfiltermap" + "go.datum.net/galactic/internal/srcfilter" +) + +func srcFilterStatus(t *testing.T, h *health.Server) grpc_health_v1.HealthCheckResponse_ServingStatus { + t.Helper() + resp, err := h.Check(context.Background(), + &grpc_health_v1.HealthCheckRequest{Service: srcFilterHealthServiceName}) + if err != nil { + t.Fatalf("health check: %v", err) + } + return resp.GetStatus() +} + +func TestSourceFilterPassReportsHealth(t *testing.T) { + filter, _ := srcfiltermap.NewFake() + peer := netip.MustParsePrefix("2001:db8:0:2::/64") + routes := []netlink.Route{{ + Dst: &net.IPNet{IP: peer.Addr().AsSlice(), Mask: net.CIDRMask(64, 128)}, + LinkIndex: 1, + Table: unix.RT_TABLE_MAIN, + Type: unix.RTN_UNICAST, + }} + var routesErr error + + r, err := srcfilter.New(srcfilter.Options{ + Settings: srcfilter.Settings{ + Mode: srcfilter.ModeAudit, + DomainPrefixes: []netip.Prefix{netip.MustParsePrefix("2001:db8::/32")}, + }, + Target: srcfilter.USIDTarget{Filter: filter}, + Routes: func() ([]netlink.Route, error) { return routes, routesErr }, + Links: func() ([]netlink.Link, error) { + return []netlink.Link{&netlink.Device{LinkAttrs: netlink.LinkAttrs{Index: 1, Name: "uplink0"}}}, nil + }, + Uplinks: func() ([]string, error) { return []string{"uplink0"}, nil }, + }) + if err != nil { + t.Fatal(err) + } + + h := health.NewServer() + ctx := context.Background() + + lastErr := sourceFilterPass(ctx, r, h, "") + if lastErr != "" || srcFilterStatus(t, h) != grpc_health_v1.HealthCheckResponse_SERVING { + t.Fatalf("after success: lastErr %q, status %v", lastErr, srcFilterStatus(t, h)) + } + + routesErr = errors.New("netlink dump interrupted") + lastErr = sourceFilterPass(ctx, r, h, lastErr) + if lastErr == "" || srcFilterStatus(t, h) != grpc_health_v1.HealthCheckResponse_NOT_SERVING { + t.Fatalf("after failure: lastErr %q, status %v", lastErr, srcFilterStatus(t, h)) + } + entries, err := filter.ListAllow() + if err != nil || len(entries) != 1 { + t.Fatalf("allow-list after failure = %v, %v; want the previous entry kept", entries, err) + } + + routesErr = nil + if lastErr = sourceFilterPass(ctx, r, h, lastErr); lastErr != "" { + t.Fatalf("recovery pass failed: %s", lastErr) + } + if srcFilterStatus(t, h) != grpc_health_v1.HealthCheckResponse_SERVING { + t.Fatal("health did not recover") + } +} + +func TestStartSourceFilterWithoutDatapathIsNoOp(t *testing.T) { + t.Setenv("GALACTIC_CNI_SRV6_SOURCE_FILTER", "enforce") + h := health.NewServer() + startSourceFilter(context.Background(), ebpfDatapathState{}, h) + if _, err := h.Check(context.Background(), + &grpc_health_v1.HealthCheckRequest{Service: srcFilterHealthServiceName}); err == nil { + t.Error("health service registered with no datapath loaded") + } +} diff --git a/internal/plumbing/ebpf/attach/watch.go b/internal/plumbing/ebpf/attach/watch.go index 795ec566b..e8e27e654 100644 --- a/internal/plumbing/ebpf/attach/watch.go +++ b/internal/plumbing/ebpf/attach/watch.go @@ -70,8 +70,9 @@ var onReconcileDone = func() {} // and ask it to re-evaluate the attachment set out of band, without waiting for // the next netlink event or a container restart. type Watcher struct { - alive atomic.Bool - nudge chan struct{} + alive atomic.Bool + nudge chan struct{} + reevaluated chan struct{} // mu guards attached and onChange, and is held across every onChange call // so two calls never run at once or land out of order. @@ -84,7 +85,29 @@ type Watcher struct { // once the Watch loop it is passed to starts running, and dead again once that // loop exits for any reason. func newWatcher() *Watcher { - return &Watcher{nudge: make(chan struct{}, 1)} + return &Watcher{nudge: make(chan struct{}, 1), reevaluated: make(chan struct{}, 1)} +} + +// Reevaluated returns a channel that receives after every debounced +// re-evaluation, whether or not it changed anything or succeeded, so a consumer +// of the same link and route events can react without subscribing again. +// Signals coalesce: a consumer that falls behind sees one pending signal, not +// a backlog. A nil Watcher returns a nil channel, which never receives. +func (w *Watcher) Reevaluated() <-chan struct{} { + if w == nil { + return nil + } + return w.reevaluated +} + +func (w *Watcher) signalReevaluated() { + if w == nil { + return + } + select { + case w.reevaluated <- struct{}{}: + default: + } } // Alive reports whether the Watch loop this Watcher was passed to is still @@ -360,6 +383,7 @@ func Watch(ctx context.Context, program *ebpf.Program, initial []string, w *Watc next = nil case err != nil: slog.Warn("attach: re-evaluate interface set failed, keeping previous attachment", "err", err) + w.signalReevaluated() onReconcileDone() continue } @@ -381,6 +405,7 @@ func Watch(ctx context.Context, program *ebpf.Program, initial []string, w *Watc // held is judged against the new set rather than waiting out the // TTL. setWatchedUplinks(order) + w.signalReevaluated() onReconcileDone() } } diff --git a/internal/plumbing/ebpf/attach/watch_test.go b/internal/plumbing/ebpf/attach/watch_test.go index 906899af2..7f3b4b9f8 100644 --- a/internal/plumbing/ebpf/attach/watch_test.go +++ b/internal/plumbing/ebpf/attach/watch_test.go @@ -1096,3 +1096,35 @@ func TestWatch_PublishesHeldUplinksAfterResolvedOnes(t *testing.T) { t.Errorf("published sets = %v, want %v", published, want) } } + +// TestWatcher_ReevaluatedSignalsEveryPass covers Reevaluated receiving after a +// debounced re-evaluation, including one whose resolution failed, and a nil +// Watcher returning a channel that never receives. +func TestWatcher_ReevaluatedSignalsEveryPass(t *testing.T) { + withWatchTestDefaults(t) + resolveInterfacesFn = func() ([]string, error) { return nil, errors.New("no default route") } + + var nilWatcher *Watcher + if nilWatcher.Reevaluated() != nil { + t.Error("nil Watcher.Reevaluated() is non-nil") + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + w := newWatcher() + done := make(chan error, 1) + go func() { done <- Watch(ctx, &ebpf.Program{}, nil, w) }() + + for range 2 { + w.Reconcile() + select { + case <-w.Reevaluated(): + case <-time.After(5 * time.Second): + t.Fatal("Reevaluated did not receive after a nudge") + } + } + cancel() + if err := <-done; err != nil { + t.Fatalf("Watch: %v", err) + } +} diff --git a/internal/plumbing/ebpf/metrics/collector.go b/internal/plumbing/ebpf/metrics/collector.go index 7f81d9444..2b8b006af 100644 --- a/internal/plumbing/ebpf/metrics/collector.go +++ b/internal/plumbing/ebpf/metrics/collector.go @@ -12,6 +12,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "go.datum.net/galactic/internal/plumbing/ebpf/prog" + "go.datum.net/galactic/internal/plumbing/ebpf/srcfiltermap" "go.datum.net/galactic/internal/plumbing/ebpf/uformat" "go.datum.net/galactic/internal/plumbing/ebpf/usidmap" "go.datum.net/galactic/internal/plumbing/intf" @@ -26,9 +27,18 @@ type DropReasonsReader interface { Lookup(key, valueOut any) error } +// SourceFilterReader is the read side of the SRv6 ingress source filter that +// Collector needs. *srcfiltermap.Filter satisfies it. +type SourceFilterReader interface { + Stats() (srcfiltermap.Stats, error) + Config() (srcfiltermap.Config, error) + ListAllow() ([]srcfiltermap.Entry, error) + DeniedSources() ([]srcfiltermap.DeniedSource, error) +} + // Collector reads the uSID datapath's live map state at every scrape: -// per-Argument packet and byte counters, drops by reason, and Argument-space -// utilization per Block. +// per-Argument packet and byte counters, drops by reason, Argument-space +// utilization per Block, and the source filter's decisions and state. type Collector struct { vrf *usidmap.VRFTable locator *usidmap.LocatorTable @@ -53,6 +63,7 @@ type Collector struct { // hostOnlyPortDrops is nil unless set by WithHostOnlyPorts, in which case // the packets tp_deliver refused for a host-only port are collected too. hostOnlyPortDrops DropReasonsReader + srcFilter SourceFilterReader } // NewCollector builds a Collector from already-constructed tables and reader. @@ -66,6 +77,13 @@ func NewCollector( return &Collector{vrf: vrf, locator: locator, dropReasons: dropReasons, vpcAttribution: vpcAttribution} } +// WithSourceFilter makes c also report the source filter read through r, and +// returns c. +func (c *Collector) WithSourceFilter(r SourceFilterReader) *Collector { + c.srcFilter = r + return c +} + // NewCollectorFromObjects builds a Collector reading directly from a loaded // object set's maps. func NewCollectorFromObjects(objs *prog.UsidObjects) *Collector { @@ -77,7 +95,8 @@ func NewCollectorFromObjects(objs *prog.UsidObjects) *Collector { ).WithMSSClamp(objs.MssClampStats, objs.MssClampTable). WithPMTU(objs.PmtuStats, objs.EncapMtuTable). WithVRFTraffic(usidmap.NewVRFTrafficTable(usidmap.KernelCounterTable{Map: objs.VrfTrafficCounters})). - WithHostOnlyPorts(objs.HostOnlyPortDrops) + WithHostOnlyPorts(objs.HostOnlyPortDrops). + WithSourceFilter(srcfiltermap.NewFromObjects(objs)) } // WithVRFTraffic adds vrf_traffic_counters to c, so each VRF's per-direction @@ -209,6 +228,32 @@ var ( "design plan §2's Option 2 -- an exhaustion-alerting input.", []string{labelBlock}, nil, ) + srcFilterPacketsDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, "src_filter", "packets_total"), + "SRv6 ingress source filter decisions, by result: checked, allowed, deny_prefix, deny_iface "+ + "or bypass_unpopulated. Denials are also counted in audit mode, where the packet is still delivered.", + []string{labelResult}, nil, + ) + srcFilterEntriesDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, "src_filter", "entries"), + "Allowed source prefixes currently in the SRv6 ingress source filter.", + nil, nil, + ) + srcFilterModeDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, "src_filter", "mode"), + "SRv6 ingress source filter mode: 0 off, 1 audit, 2 enforce.", + nil, nil, + ) + srcFilterPopulatedDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, "src_filter", "populated"), + "1 once the source filter's allow-list reflects a complete sync; until then every packet bypasses it.", + nil, nil, + ) + srcFilterDeniedSourcesDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, "src_filter", "denied_sources"), + "Distinct source /64s the source filter has recorded as denied, bounded by the record's capacity.", + nil, nil, + ) ) // Describe implements prometheus.Collector. @@ -226,12 +271,18 @@ func (c *Collector) Describe(ch chan<- *prometheus.Desc) { ch <- pmtuDesc ch <- encapMTUDesc ch <- hostOnlyPortDropsDesc + ch <- srcFilterPacketsDesc + ch <- srcFilterEntriesDesc + ch <- srcFilterModeDesc + ch <- srcFilterPopulatedDesc + ch <- srcFilterDeniedSourcesDesc } // Collect implements prometheus.Collector. func (c *Collector) Collect(ch chan<- prometheus.Metric) { c.collectVRF(ch) c.collectDrops(ch) + c.collectSrcFilter(ch) c.collectMSSClamp(ch) c.collectPMTU(ch) c.collectHostOnlyPorts(ch) @@ -470,3 +521,50 @@ func (c *Collector) collectDrops(ch chan<- prometheus.Metric) { ch <- prometheus.MustNewConstMetric(dropsDesc, prometheus.CounterValue, float64(total), name) } } + +func (c *Collector) collectSrcFilter(ch chan<- prometheus.Metric) { + if c.srcFilter == nil { + return + } + + if st, err := c.srcFilter.Stats(); err != nil { + ch <- prometheus.NewInvalidMetric(srcFilterPacketsDesc, fmt.Errorf("read src_filter_stats: %w", err)) + } else { + for _, v := range []struct { + slot uint32 + count uint64 + }{ + {prog.SrcFilterStatChecked, st.Checked}, + {prog.SrcFilterStatAllowed, st.Allowed}, + {prog.SrcFilterStatDenyPrefix, st.DenyPrefix}, + {prog.SrcFilterStatDenyIface, st.DenyIface}, + {prog.SrcFilterStatBypassUnpopulated, st.BypassUnpopulated}, + } { + ch <- prometheus.MustNewConstMetric(srcFilterPacketsDesc, prometheus.CounterValue, + float64(v.count), prog.SrcFilterStatNames[v.slot]) + } + } + + if cfg, err := c.srcFilter.Config(); err != nil { + ch <- prometheus.NewInvalidMetric(srcFilterModeDesc, fmt.Errorf("read src_filter_config_table: %w", err)) + } else { + populated := 0.0 + if cfg.Populated { + populated = 1 + } + ch <- prometheus.MustNewConstMetric(srcFilterModeDesc, prometheus.GaugeValue, float64(cfg.Mode)) + ch <- prometheus.MustNewConstMetric(srcFilterPopulatedDesc, prometheus.GaugeValue, populated) + } + + if entries, err := c.srcFilter.ListAllow(); err != nil { + ch <- prometheus.NewInvalidMetric(srcFilterEntriesDesc, fmt.Errorf("list src_allow_table: %w", err)) + } else { + ch <- prometheus.MustNewConstMetric(srcFilterEntriesDesc, prometheus.GaugeValue, float64(len(entries))) + } + + if denied, err := c.srcFilter.DeniedSources(); err != nil { + ch <- prometheus.NewInvalidMetric(srcFilterDeniedSourcesDesc, fmt.Errorf("list src_filter_denied: %w", err)) + } else { + ch <- prometheus.MustNewConstMetric(srcFilterDeniedSourcesDesc, prometheus.GaugeValue, float64(len(denied))) + } +} diff --git a/internal/plumbing/ebpf/metrics/srcfilter_test.go b/internal/plumbing/ebpf/metrics/srcfilter_test.go new file mode 100644 index 000000000..6b9bc593b --- /dev/null +++ b/internal/plumbing/ebpf/metrics/srcfilter_test.go @@ -0,0 +1,97 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package metrics + +import ( + "maps" + "net/netip" + "strings" + "testing" + + "github.com/prometheus/client_golang/prometheus" + + "go.datum.net/galactic/internal/plumbing/ebpf/prog" + "go.datum.net/galactic/internal/plumbing/ebpf/srcfiltermap" + "go.datum.net/galactic/internal/plumbing/ebpf/usidmap" +) + +func TestCollectorSourceFilter(t *testing.T) { + filter, tables := srcfiltermap.NewFake() + if err := filter.SetConfig(srcfiltermap.Config{Mode: srcfiltermap.ModeAudit, Populated: true}); err != nil { + t.Fatal(err) + } + for _, p := range []string{"2001:db8:0:2::/64", "2001:db8:0:3::/64"} { + if err := filter.PutAllow(srcfiltermap.Entry{Prefix: netip.MustParsePrefix(p), AnyIface: true}); err != nil { + t.Fatal(err) + } + } + stats := map[uint32][]uint64{ + prog.SrcFilterStatChecked: {5, 5}, + prog.SrcFilterStatAllowed: {4, 3}, + prog.SrcFilterStatDenyPrefix: {1, 1}, + prog.SrcFilterStatDenyIface: {0, 1}, + prog.SrcFilterStatBypassUnpopulated: {2, 0}, + } + for slot, perCPU := range stats { + if err := tables.Stats.Put(slot, perCPU); err != nil { + t.Fatal(err) + } + } + if err := tables.Denied.Put(prog.UsidSrcDeniedKey{Prefix: [8]uint8{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 9}}, + prog.UsidSrcDeniedValue{Count: 3, LastReason: prog.SrcFilterStatDenyPrefix}); err != nil { + t.Fatal(err) + } + + c := NewCollector(usidmap.NewVRFTable(newFakeTable()), nil, nil, nil).WithSourceFilter(filter) + got := gatherSrcFilter(t, c) + want := map[string]float64{ + "galactic_usid_src_filter_packets_total/checked": 10, + "galactic_usid_src_filter_packets_total/allowed": 7, + "galactic_usid_src_filter_packets_total/deny_prefix": 2, + "galactic_usid_src_filter_packets_total/deny_iface": 1, + "galactic_usid_src_filter_packets_total/bypass_unpopulated": 2, + "galactic_usid_src_filter_entries": 2, + "galactic_usid_src_filter_mode": 1, + "galactic_usid_src_filter_populated": 1, + "galactic_usid_src_filter_denied_sources": 1, + } + if !maps.Equal(got, want) { + t.Errorf("source filter series:\n got %v\n want %v", got, want) + } +} + +// gatherSrcFilter registers c in a private registry and returns every +// galactic_usid_src_filter_* sample keyed by name, plus "/" for the +// labeled counter. +func gatherSrcFilter(t *testing.T, c prometheus.Collector) map[string]float64 { + t.Helper() + reg := prometheus.NewPedanticRegistry() + reg.MustRegister(c) + families, err := reg.Gather() + if err != nil { + t.Fatalf("gather: %v", err) + } + out := make(map[string]float64) + for _, mf := range families { + if !strings.HasPrefix(mf.GetName(), "galactic_usid_src_filter_") { + continue + } + for _, m := range mf.GetMetric() { + key := mf.GetName() + if r := labelValue(m, labelResult); r != "" { + key += "/" + r + } + out[key] = metricValue(m) + } + } + return out +} + +func TestCollectorWithoutSourceFilterEmitsNone(t *testing.T) { + c := NewCollector(usidmap.NewVRFTable(newFakeTable()), nil, nil, nil) + if got := gatherSrcFilter(t, c); len(got) != 0 { + t.Errorf("src filter series emitted without a source filter: %v", got) + } +} diff --git a/internal/srcfilter/desired.go b/internal/srcfilter/desired.go new file mode 100644 index 000000000..bd30883c3 --- /dev/null +++ b/internal/srcfilter/desired.go @@ -0,0 +1,193 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfilter + +import ( + "net" + "net/netip" + "slices" + + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" + + "go.datum.net/galactic/internal/plumbing/bond" +) + +const vlanLinkType = "vlan" + +// desiredInput is everything one pass computes its allow-list from. +type desiredInput struct { + routes []netlink.Route + links []netlink.Link + slots map[uint32]uint8 + ownLocator netip.Prefix + domain []netip.Prefix + minPrefixLen int + binding Binding + extra []netip.Prefix +} + +// desiredOutput is a pass's allow-list plus what it was built from. +type desiredOutput struct { + entries []Entry + // fromRoutes counts entries derived from at least one route. + fromRoutes int + // unbound counts route entries with a hop whose link is unknown, which + // are accepted on any interface rather than bound to none. + unbound int +} + +// computeDesired returns the allow-list for in, sorted by prefix, with +// duplicate prefixes merged. +// +// A route yields an entry when it is an IPv6 main-table route that forwards, +// its destination lies inside a domain prefix, is at least minPrefixLen long, +// and does not lie inside this node's own locator. Its interface mask is the +// union of every hop's link slots, a bond master or a VLAN on a bond counting +// as its slaves. Loose binding, or a hop with no usable link, accepts the +// prefix on any interface. Every extra prefix is accepted on any interface. +func computeDesired(in desiredInput) desiredOutput { + byIndex := make(map[int]netlink.Link, len(in.links)) + for _, l := range in.links { + byIndex[l.Attrs().Index] = l + } + + merged := make(map[netip.Prefix]*Entry) + fromRoute := make(map[netip.Prefix]bool) + merge := func(e Entry) { + cur, ok := merged[e.Prefix] + if !ok { + merged[e.Prefix] = &e + return + } + cur.IfaceMask |= e.IfaceMask + cur.AnyIface = cur.AnyIface || e.AnyIface + } + + var out desiredOutput + for i := range in.routes { + r := &in.routes[i] + p, ok := routePrefix(r) + if !ok || !in.eligible(p) { + continue + } + mask, bound := hopMask(r, byIndex, in.links, in.slots) + e := Entry{Prefix: p, IfaceMask: mask, AnyIface: in.binding == BindingLoose || !bound} + if !bound { + out.unbound++ + } + merge(e) + fromRoute[p] = true + } + for _, p := range in.extra { + merge(Entry{Prefix: p.Masked(), AnyIface: true}) + } + + out.entries = make([]Entry, 0, len(merged)) + for _, e := range merged { + out.entries = append(out.entries, *e) + } + slices.SortFunc(out.entries, func(a, b Entry) int { return a.Prefix.Compare(b.Prefix) }) + out.fromRoutes = len(fromRoute) + return out +} + +// eligible reports whether p is a fabric peer's prefix: inside a domain +// prefix, at least minPrefixLen long and not inside this node's own locator. +func (in desiredInput) eligible(p netip.Prefix) bool { + if p.Bits() < in.minPrefixLen { + return false + } + if in.ownLocator.IsValid() && contains(in.ownLocator, p) { + return false + } + for _, d := range in.domain { + if contains(d, p) { + return true + } + } + return false +} + +// contains reports whether inner lies entirely inside outer. +func contains(outer, inner netip.Prefix) bool { + return outer.Bits() <= inner.Bits() && outer.Contains(inner.Addr()) +} + +// routePrefix returns r's destination when r is an IPv6 main-table route that +// forwards somewhere. A discard or local route, a default route and an IPv4 +// route all return false. +func routePrefix(r *netlink.Route) (netip.Prefix, bool) { + if r.Table != unix.RT_TABLE_MAIN || r.Dst == nil { + return netip.Prefix{}, false + } + if r.Type != unix.RTN_UNICAST && r.Type != unix.RTN_UNSPEC { + return netip.Prefix{}, false + } + ones, bits := r.Dst.Mask.Size() + if bits != net.IPv6len*8 || ones == 0 { + return netip.Prefix{}, false + } + addr, ok := netip.AddrFromSlice(r.Dst.IP) + if !ok || !addr.Is6() || addr.Is4In6() || addr.IsLinkLocalUnicast() { + return netip.Prefix{}, false + } + return netip.PrefixFrom(addr, ones).Masked(), true +} + +// hopMask returns the union of the slots of every link r's hops leave through, +// and whether every hop named a link that could be resolved. +func hopMask( + r *netlink.Route, byIndex map[int]netlink.Link, all []netlink.Link, slots map[uint32]uint8, +) (uint32, bool) { + hops := make([]int, 0, 1+len(r.MultiPath)) + if len(r.MultiPath) > 0 { + for _, nh := range r.MultiPath { + hops = append(hops, nh.LinkIndex) + } + } else { + hops = append(hops, r.LinkIndex) + } + + var mask uint32 + for _, ifindex := range hops { + link, ok := byIndex[ifindex] + if ifindex <= 0 || !ok { + return 0, false + } + for _, idx := range ingressLinks(link, byIndex, all) { + if slot, ok := slots[uint32(idx)]; ok && int(slot) < MaxSlots { + mask |= 1 << slot + } + } + } + return mask, true +} + +// ingressLinks returns the ifindexes a packet routed out of link can arrive +// on: link itself, plus its slaves when link is a bond master, plus the slaves +// of the bond a VLAN link sits on. Receive classification on a bond happens on +// its slaves, so a slave's ifindex is what the datapath sees. +func ingressLinks(link netlink.Link, byIndex map[int]netlink.Link, all []netlink.Link) []int { + out := []int{link.Attrs().Index} + master := link + if !bond.IsMaster(master) { + if link.Type() != vlanLinkType { + return out + } + parent, ok := byIndex[link.Attrs().ParentIndex] + if !ok || !bond.IsMaster(parent) { + return out + } + master = parent + out = append(out, parent.Attrs().Index) + } + for _, l := range all { + if l.Attrs().MasterIndex == master.Attrs().Index { + out = append(out, l.Attrs().Index) + } + } + return out +} diff --git a/internal/srcfilter/doc.go b/internal/srcfilter/doc.go new file mode 100644 index 000000000..53b7076a0 --- /dev/null +++ b/internal/srcfilter/doc.go @@ -0,0 +1,17 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package srcfilter builds a node's SRv6 ingress source allow-list from the +// routes it already learns and keeps a datapath's source filter in step with +// it. +// +// Every fabric peer sources its SRv6 traffic from inside its own locator, and +// each node carries a route to every peer locator. A route inside the +// configured SR domain prefixes therefore names a legitimate source, and the +// links that route leaves through name the uplinks that source may arrive on. +// +// The package decides what to allow and when; it writes through the Target +// interface, so any datapath with an allow-list, uplink slots and a mode can +// reuse it behind a thin adapter. +package srcfilter diff --git a/internal/srcfilter/reconciler.go b/internal/srcfilter/reconciler.go new file mode 100644 index 000000000..65a6eeb37 --- /dev/null +++ b/internal/srcfilter/reconciler.go @@ -0,0 +1,289 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfilter + +import ( + "context" + "errors" + "fmt" + "log/slog" + "maps" + "net/netip" + "sync" + + "github.com/vishvananda/netlink" +) + +// ErrNoFabricRoutes means a pass found no route naming a fabric peer. A pass +// that finds none leaves the allow-list as it is rather than emptying it, since +// losing every route at once is far more often a routing daemon restarting than +// a node with no peers. +var ErrNoFabricRoutes = errors.New("no fabric peer routes inside the SR domain prefixes") + +// Options configures a Reconciler. +type Options struct { + Settings Settings + // MinPrefixLen is the shortest route that becomes an entry. + // DefaultMinPrefixLen when zero. + MinPrefixLen int + Target Target + // Slots assigns uplink slots. StableSlots when nil. + Slots SlotAssigner + // Routes lists the main table's IPv6 routes. + Routes func() ([]netlink.Route, error) + // Links lists every link on the host. + Links func() ([]netlink.Link, error) + // Uplinks returns the names of the interfaces the datapath is attached + // to. + Uplinks func() ([]string, error) + // OwnLocator returns this node's own locator, or the zero Prefix when it + // has none yet. Nil means none. + OwnLocator func(ctx context.Context) (netip.Prefix, error) +} + +// Result reports what one pass did. +type Result struct { + Entries int + Added int + Updated int + Removed int + Unbound int + Changed bool + State State + SlotCount int +} + +// Reconciler keeps a Target's allow-list, uplink slots and state in step with +// the host's routes. It is safe for concurrent use; passes are serialized. +type Reconciler struct { + opts Options + + mu sync.Mutex + state State + loaded bool +} + +// New returns a Reconciler for opts. It returns an error when a required +// field is missing or the mode is off, since an off filter needs no +// reconciler. +func New(opts Options) (*Reconciler, error) { + switch { + case opts.Target == nil: + return nil, errors.New("srcfilter: target is required") + case opts.Routes == nil || opts.Links == nil || opts.Uplinks == nil: + return nil, errors.New("srcfilter: routes, links and uplinks sources are required") + case opts.Settings.Mode == ModeOff: + return nil, errors.New("srcfilter: mode is off") + case len(opts.Settings.DomainPrefixes) == 0: + return nil, errors.New("srcfilter: at least one SR domain prefix is required") + } + if opts.MinPrefixLen == 0 { + opts.MinPrefixLen = DefaultMinPrefixLen + } + if opts.Slots == nil { + opts.Slots = StableSlots + } + if opts.OwnLocator == nil { + opts.OwnLocator = func(context.Context) (netip.Prefix, error) { return netip.Prefix{}, nil } + } + return &Reconciler{opts: opts}, nil +} + +// Reconcile runs one pass: it resolves uplinks, slots and routes, computes the +// allow-list and applies it, writing new and changed entries before removing +// stale ones. The Target is marked populated only after a pass completes with +// no error, and its generation is bumped whenever a pass changes anything. +// +// On the first pass the configured mode is written straight away, keeping +// whatever populated flag and allow-list the Target already holds, so a mode +// change takes effect even while routes cannot be read. +// +// Any failure to read inputs, and a pass that finds no fabric routes, returns +// an error without touching the allow-list, so the previous one stays in +// force. +func (r *Reconciler) Reconcile(ctx context.Context) (Result, error) { + r.mu.Lock() + defer r.mu.Unlock() + + if err := r.loadState(); err != nil { + return Result{}, err + } + + uplinkNames, err := r.opts.Uplinks() + if err != nil { + return Result{State: r.state}, fmt.Errorf("srcfilter: resolve uplinks: %w", err) + } + links, err := r.opts.Links() + if err != nil { + return Result{State: r.state}, fmt.Errorf("srcfilter: list links: %w", err) + } + uplinks, err := uplinkIndexes(uplinkNames, links) + if err != nil { + return Result{State: r.state}, err + } + currentSlots, err := r.opts.Target.UplinkSlots() + if err != nil { + return Result{State: r.state}, fmt.Errorf("srcfilter: read uplink slots: %w", err) + } + slots, err := r.opts.Slots(uplinks, currentSlots) + if err != nil { + return Result{State: r.state}, fmt.Errorf("srcfilter: assign uplink slots: %w", err) + } + own, err := r.opts.OwnLocator(ctx) + if err != nil { + return Result{State: r.state}, fmt.Errorf("srcfilter: resolve own locator: %w", err) + } + routes, err := r.opts.Routes() + if err != nil { + return Result{State: r.state}, fmt.Errorf("srcfilter: list routes: %w", err) + } + + desired := computeDesired(desiredInput{ + routes: routes, + links: links, + slots: slots, + ownLocator: own, + domain: r.opts.Settings.DomainPrefixes, + minPrefixLen: r.opts.MinPrefixLen, + binding: r.opts.Settings.Binding, + extra: r.opts.Settings.ExtraSources, + }) + res := Result{Entries: len(desired.entries), Unbound: desired.unbound, SlotCount: len(slots), State: r.state} + if desired.fromRoutes == 0 { + return res, fmt.Errorf("srcfilter: %w", ErrNoFabricRoutes) + } + + slotsChanged := !maps.Equal(slots, currentSlots) + if slotsChanged { + if err := r.opts.Target.SyncUplinkSlots(slots); err != nil { + return res, fmt.Errorf("srcfilter: sync uplink slots: %w", err) + } + } + if err := r.syncAllow(desired.entries, &res); err != nil { + return res, err + } + + res.Changed = slotsChanged || res.Added+res.Updated+res.Removed > 0 + if res.Changed || !r.state.Populated { + next := State{Mode: r.opts.Settings.Mode, Populated: true, Generation: r.state.Generation + 1} + if err := r.opts.Target.SetState(next); err != nil { + return res, fmt.Errorf("srcfilter: set state: %w", err) + } + r.state = next + } + res.State = r.state + return res, nil +} + +// loadState reads the Target's state once and writes the configured mode if +// it differs. +func (r *Reconciler) loadState() error { + if r.loaded { + return nil + } + st, err := r.opts.Target.State() + if err != nil { + return fmt.Errorf("srcfilter: read state: %w", err) + } + if st.Mode != r.opts.Settings.Mode { + prev := st.Mode + st.Mode = r.opts.Settings.Mode + st.Generation++ + if err := r.opts.Target.SetState(st); err != nil { + return fmt.Errorf("srcfilter: set mode %s: %w", st.Mode, err) + } + slog.Info("SRv6 source filter mode changed", "from", prev.String(), "to", st.Mode.String(), + "populated", st.Populated) + } + r.state, r.loaded = st, true + return nil +} + +// syncAllow makes the Target's allow-list exactly desired, writing before +// deleting. A failed write skips every delete, so the list only ever holds a +// superset of the old and new sets. +func (r *Reconciler) syncAllow(desired []Entry, res *Result) error { + current, err := r.opts.Target.ListAllow() + if err != nil { + return fmt.Errorf("srcfilter: list allow entries: %w", err) + } + have := make(map[netip.Prefix]Entry, len(current)) + for _, e := range current { + have[e.Prefix.Masked()] = e + } + want := make(map[netip.Prefix]struct{}, len(desired)) + + var errs []error + for _, e := range desired { + want[e.Prefix] = struct{}{} + old, ok := have[e.Prefix] + if ok && old.IfaceMask == e.IfaceMask && old.AnyIface == e.AnyIface { + continue + } + if err := r.opts.Target.PutAllow(e); err != nil { + errs = append(errs, fmt.Errorf("put %s: %w", e.Prefix, err)) + continue + } + if ok { + res.Updated++ + } else { + res.Added++ + } + } + if len(errs) > 0 { + return fmt.Errorf("srcfilter: write allow entries: %w", errors.Join(errs...)) + } + + for _, e := range current { + p := e.Prefix.Masked() + if _, ok := want[p]; ok { + continue + } + if err := r.opts.Target.DeleteAllow(p); err != nil { + errs = append(errs, fmt.Errorf("delete %s: %w", p, err)) + continue + } + res.Removed++ + } + if len(errs) > 0 { + return fmt.Errorf("srcfilter: remove stale allow entries: %w", errors.Join(errs...)) + } + return nil +} + +// uplinkIndexes resolves uplink names against links. A name with no link is +// skipped; none resolving is an error. +func uplinkIndexes(names []string, links []netlink.Link) ([]uint32, error) { + byName := make(map[string]int, len(links)) + for _, l := range links { + byName[l.Attrs().Name] = l.Attrs().Index + } + out := make([]uint32, 0, len(names)) + for _, n := range names { + if idx, ok := byName[n]; ok && idx > 0 { + out = append(out, uint32(idx)) + } + } + if len(out) == 0 { + return nil, fmt.Errorf("srcfilter: none of the uplinks %v exist on this host", names) + } + return out, nil +} + +// Disable writes mode off to target, keeping its generation moving. The +// allow-list is left as it is. +func Disable(target Target) error { + st, err := target.State() + if err != nil { + return fmt.Errorf("srcfilter: read state: %w", err) + } + if st.Mode == ModeOff && !st.Populated { + return nil + } + if err := target.SetState(State{Mode: ModeOff, Generation: st.Generation + 1}); err != nil { + return fmt.Errorf("srcfilter: set mode off: %w", err) + } + return nil +} diff --git a/internal/srcfilter/reconciler_test.go b/internal/srcfilter/reconciler_test.go new file mode 100644 index 000000000..504f27ebc --- /dev/null +++ b/internal/srcfilter/reconciler_test.go @@ -0,0 +1,424 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfilter + +import ( + "context" + "errors" + "net" + "net/netip" + "slices" + "testing" + + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" + + "go.datum.net/galactic/internal/plumbing/ebpf/srcfiltermap" +) + +const ( + idxEth0 = iota + 1 + idxEth1 + idxBond0 + idxEth2 + idxEth3 + idxVlan + idxMgmt +) + +var ( + domain = netip.MustParsePrefix("2001:db8::/32") + ownLocator = netip.MustParsePrefix("2001:db8:0:1::/64") + peerA = netip.MustParsePrefix("2001:db8:0:2::/64") + peerB = netip.MustParsePrefix("2001:db8:0:3::/64") + peerC = netip.MustParsePrefix("2001:db8:0:4::/64") + peerD = netip.MustParsePrefix("2001:db8:0:5::/64") + shard = netip.MustParsePrefix("2001:db8:0:6::/64") + unboundP = netip.MustParsePrefix("2001:db8:0:7::/64") + aggregate = netip.MustParsePrefix("2001:db8:1::/48") + discard = netip.MustParsePrefix("2001:db8:0:8::/64") + outside = netip.MustParsePrefix("2001:db9:0:1::/64") + extra = netip.MustParsePrefix("2001:db8:ffff:1::/64") +) + +func testLinks() []netlink.Link { + dev := func(idx int, name string, master int) netlink.Link { + return &netlink.Device{LinkAttrs: netlink.LinkAttrs{Index: idx, Name: name, MasterIndex: master}} + } + return []netlink.Link{ + dev(idxEth0, "eth0", 0), + dev(idxEth1, "eth1", 0), + &netlink.Bond{LinkAttrs: netlink.LinkAttrs{Index: idxBond0, Name: "bond0"}}, + dev(idxEth2, "eth2", idxBond0), + dev(idxEth3, "eth3", idxBond0), + &netlink.Vlan{LinkAttrs: netlink.LinkAttrs{Index: idxVlan, Name: "bond0.100", ParentIndex: idxBond0}}, + dev(idxMgmt, "mgmt", 0), + } +} + +var testUplinks = []string{"eth0", "eth1", "bond0", "eth2", "eth3", "bond0.100"} + +func ipnet(p netip.Prefix) *net.IPNet { + return &net.IPNet{IP: p.Addr().AsSlice(), Mask: net.CIDRMask(p.Bits(), 128)} +} + +func route(p netip.Prefix, link int, proto netlink.RouteProtocol) netlink.Route { + return netlink.Route{ + Dst: ipnet(p), LinkIndex: link, Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, Protocol: proto, + } +} + +func testRoutes() []netlink.Route { + multipath := route(peerB, 0, unix.RTPROT_BGP) + multipath.MultiPath = []*netlink.NexthopInfo{{LinkIndex: idxEth0}, {LinkIndex: idxEth1}} + blackhole := route(discard, 0, unix.RTPROT_BGP) + blackhole.Type = unix.RTN_BLACKHOLE + otherTable := route(peerA, idxMgmt, unix.RTPROT_BGP) + otherTable.Table = 100 + return []netlink.Route{ + route(peerA, idxEth0, unix.RTPROT_BGP), + multipath, + route(peerC, idxBond0, unix.RTPROT_BGP), + route(peerD, idxVlan, unix.RTPROT_BGP), + route(shard, idxEth1, unix.RTPROT_BOOT), + route(unboundP, 99, unix.RTPROT_BGP), + route(aggregate, idxEth0, unix.RTPROT_BGP), + route(ownLocator, idxEth0, unix.RTPROT_BGP), + blackhole, + route(outside, idxEth0, unix.RTPROT_BGP), + otherTable, + {Dst: nil, LinkIndex: idxMgmt, Table: unix.RT_TABLE_MAIN}, + } +} + +type fixture struct { + routes []netlink.Route + routesErr error + uplinks []string + filter *srcfiltermap.Filter + tables srcfiltermap.Tables + settings Settings +} + +func newFixture() *fixture { + f, t := srcfiltermap.NewFake() + return &fixture{ + routes: testRoutes(), + uplinks: testUplinks, + filter: f, + tables: t, + settings: Settings{ + Mode: ModeAudit, + DomainPrefixes: []netip.Prefix{domain}, + ExtraSources: []netip.Prefix{extra}, + }, + } +} + +func (fx *fixture) reconciler(t *testing.T) *Reconciler { + t.Helper() + r, err := New(Options{ + Settings: fx.settings, + Target: USIDTarget{Filter: fx.filter}, + Routes: func() ([]netlink.Route, error) { return fx.routes, fx.routesErr }, + Links: func() ([]netlink.Link, error) { return testLinks(), nil }, + Uplinks: func() ([]string, error) { return fx.uplinks, nil }, + OwnLocator: func(context.Context) (netip.Prefix, error) { + return ownLocator, nil + }, + }) + if err != nil { + t.Fatalf("New: %v", err) + } + return r +} + +func mask(t *testing.T, slots ...uint8) uint32 { + t.Helper() + m, err := srcfiltermap.IfaceMask(slots...) + if err != nil { + t.Fatal(err) + } + return m +} + +// Slots follow ifindex order: eth0 0, eth1 1, bond0 2, eth2 3, eth3 4, vlan 5. +func wantEntries(t *testing.T) []srcfiltermap.Entry { + return []srcfiltermap.Entry{ + {Prefix: peerA, IfaceMask: mask(t, 0)}, + {Prefix: peerB, IfaceMask: mask(t, 0, 1)}, + {Prefix: peerC, IfaceMask: mask(t, 2, 3, 4)}, + {Prefix: peerD, IfaceMask: mask(t, 2, 3, 4, 5)}, + {Prefix: shard, IfaceMask: mask(t, 1)}, + {Prefix: unboundP, AnyIface: true}, + {Prefix: extra, AnyIface: true}, + } +} + +func sortEntries(e []srcfiltermap.Entry) []srcfiltermap.Entry { + slices.SortFunc(e, func(a, b srcfiltermap.Entry) int { return a.Prefix.Compare(b.Prefix) }) + return e +} + +func assertAllow(t *testing.T, f *srcfiltermap.Filter, want []srcfiltermap.Entry) { + t.Helper() + got, err := f.ListAllow() + if err != nil { + t.Fatalf("ListAllow: %v", err) + } + if !slices.Equal(got, sortEntries(slices.Clone(want))) { + t.Errorf("allow-list:\n got %+v\n want %+v", got, sortEntries(want)) + } +} + +func assertConfig(t *testing.T, f *srcfiltermap.Filter, want srcfiltermap.Config) { + t.Helper() + got, err := f.Config() + if err != nil { + t.Fatalf("Config: %v", err) + } + if got != want { + t.Errorf("config = %+v, want %+v", got, want) + } +} + +func TestReconcileBuildsAllowList(t *testing.T) { + fx := newFixture() + res, err := fx.reconciler(t).Reconcile(context.Background()) + if err != nil { + t.Fatalf("Reconcile: %v", err) + } + assertAllow(t, fx.filter, wantEntries(t)) + assertConfig(t, fx.filter, srcfiltermap.Config{Mode: srcfiltermap.ModeAudit, Populated: true, Generation: 2}) + if res.Added != 7 || res.Unbound != 1 || !res.Changed || res.SlotCount != 6 { + t.Errorf("result = %+v", res) + } + + slots, err := fx.filter.UplinkSlots() + if err != nil { + t.Fatal(err) + } + want := map[uint32]uint8{idxEth0: 0, idxEth1: 1, idxBond0: 2, idxEth2: 3, idxEth3: 4, idxVlan: 5} + if len(slots) != len(want) { + t.Fatalf("slots = %v, want %v", slots, want) + } + for k, v := range want { + if slots[k] != v { + t.Errorf("slot[%d] = %d, want %d", k, slots[k], v) + } + } +} + +func TestReconcileNoOpKeepsGeneration(t *testing.T) { + fx := newFixture() + r := fx.reconciler(t) + if _, err := r.Reconcile(context.Background()); err != nil { + t.Fatal(err) + } + res, err := r.Reconcile(context.Background()) + if err != nil { + t.Fatal(err) + } + if res.Changed || res.Added+res.Updated+res.Removed != 0 { + t.Errorf("second pass changed something: %+v", res) + } + assertConfig(t, fx.filter, srcfiltermap.Config{Mode: srcfiltermap.ModeAudit, Populated: true, Generation: 2}) +} + +func TestReconcileRemovesWithdrawnRoute(t *testing.T) { + fx := newFixture() + r := fx.reconciler(t) + if _, err := r.Reconcile(context.Background()); err != nil { + t.Fatal(err) + } + fx.routes = slices.DeleteFunc(testRoutes(), func(rt netlink.Route) bool { + return rt.Dst != nil && rt.Dst.IP.Equal(peerA.Addr().AsSlice()) + }) + res, err := r.Reconcile(context.Background()) + if err != nil { + t.Fatal(err) + } + if res.Removed != 1 || !res.Changed { + t.Errorf("result = %+v", res) + } + assertAllow(t, fx.filter, wantEntries(t)[1:]) + assertConfig(t, fx.filter, srcfiltermap.Config{Mode: srcfiltermap.ModeAudit, Populated: true, Generation: 3}) +} + +func TestReconcileLooseBinding(t *testing.T) { + fx := newFixture() + fx.settings.Binding = BindingLoose + if _, err := fx.reconciler(t).Reconcile(context.Background()); err != nil { + t.Fatal(err) + } + want := wantEntries(t) + for i := range want { + want[i].AnyIface = true + } + assertAllow(t, fx.filter, want) +} + +func TestReconcileRouteListFailureKeepsAllowList(t *testing.T) { + fx := newFixture() + r := fx.reconciler(t) + if _, err := r.Reconcile(context.Background()); err != nil { + t.Fatal(err) + } + fx.routesErr = errors.New("netlink dump interrupted") + if _, err := r.Reconcile(context.Background()); err == nil { + t.Fatal("Reconcile succeeded with a failing route list") + } + assertAllow(t, fx.filter, wantEntries(t)) + assertConfig(t, fx.filter, srcfiltermap.Config{Mode: srcfiltermap.ModeAudit, Populated: true, Generation: 2}) +} + +func TestReconcileNoFabricRoutes(t *testing.T) { + tests := []struct { + name string + routes []netlink.Route + }{ + {"NoRoutes", nil}, + {"OnlyExcluded", []netlink.Route{ + route(aggregate, idxEth0, unix.RTPROT_BGP), + route(ownLocator, idxEth0, unix.RTPROT_BGP), + route(outside, idxEth0, unix.RTPROT_BGP), + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fx := newFixture() + fx.settings.Mode = ModeEnforce + fx.routes = tt.routes + _, err := fx.reconciler(t).Reconcile(context.Background()) + if !errors.Is(err, ErrNoFabricRoutes) { + t.Fatalf("err = %v, want ErrNoFabricRoutes", err) + } + assertAllow(t, fx.filter, nil) + assertConfig(t, fx.filter, srcfiltermap.Config{Mode: srcfiltermap.ModeEnforce, Generation: 1}) + }) + } +} + +func TestReconcileEmptyAfterPopulatedKeepsAllowList(t *testing.T) { + fx := newFixture() + r := fx.reconciler(t) + if _, err := r.Reconcile(context.Background()); err != nil { + t.Fatal(err) + } + fx.routes = nil + if _, err := r.Reconcile(context.Background()); !errors.Is(err, ErrNoFabricRoutes) { + t.Fatalf("err = %v, want ErrNoFabricRoutes", err) + } + assertAllow(t, fx.filter, wantEntries(t)) +} + +func TestReconcileWriteFailureSkipsDeletesAndPopulate(t *testing.T) { + fx := newFixture() + stale := srcfiltermap.Entry{Prefix: netip.MustParsePrefix("2001:db8:0:99::/64"), AnyIface: true} + if err := fx.filter.PutAllow(stale); err != nil { + t.Fatal(err) + } + fx.tables.Allow.(*srcfiltermap.FakeTable).PutErr = errors.New("map full") + + if _, err := fx.reconciler(t).Reconcile(context.Background()); err == nil { + t.Fatal("Reconcile succeeded with failing writes") + } + assertAllow(t, fx.filter, []srcfiltermap.Entry{stale}) + assertConfig(t, fx.filter, srcfiltermap.Config{Mode: srcfiltermap.ModeAudit, Generation: 1}) +} + +func TestReconcileAppliesModeBeforeFirstSync(t *testing.T) { + fx := newFixture() + if err := fx.filter.SetConfig(srcfiltermap.Config{ + Mode: srcfiltermap.ModeEnforce, Populated: true, Generation: 7, + }); err != nil { + t.Fatal(err) + } + fx.routesErr = errors.New("netlink dump interrupted") + if _, err := fx.reconciler(t).Reconcile(context.Background()); err == nil { + t.Fatal("Reconcile succeeded with a failing route list") + } + assertConfig(t, fx.filter, srcfiltermap.Config{Mode: srcfiltermap.ModeAudit, Populated: true, Generation: 8}) +} + +func TestReconcileTooManyUplinks(t *testing.T) { + fx := newFixture() + links := make([]netlink.Link, 0, MaxSlots+1) + names := make([]string, 0, MaxSlots+1) + for i := range MaxSlots + 1 { + name := "up" + string(rune('a'+i%26)) + string(rune('a'+i/26)) + links = append(links, &netlink.Device{LinkAttrs: netlink.LinkAttrs{Index: 100 + i, Name: name}}) + names = append(names, name) + } + r, err := New(Options{ + Settings: fx.settings, + Target: USIDTarget{Filter: fx.filter}, + Routes: func() ([]netlink.Route, error) { return fx.routes, nil }, + Links: func() ([]netlink.Link, error) { return links, nil }, + Uplinks: func() ([]string, error) { return names, nil }, + }) + if err != nil { + t.Fatal(err) + } + if _, err := r.Reconcile(context.Background()); err == nil { + t.Fatal("Reconcile succeeded with more uplinks than slots") + } + assertAllow(t, fx.filter, nil) +} + +func TestReconcileNoUplinkExists(t *testing.T) { + fx := newFixture() + fx.uplinks = []string{"gone0"} + if _, err := fx.reconciler(t).Reconcile(context.Background()); err == nil { + t.Fatal("Reconcile succeeded with no resolvable uplink") + } +} + +func TestNewRejectsIncompleteOptions(t *testing.T) { + f, _ := srcfiltermap.NewFake() + ok := Options{ + Settings: Settings{Mode: ModeAudit, DomainPrefixes: []netip.Prefix{domain}}, + Target: USIDTarget{Filter: f}, + Routes: func() ([]netlink.Route, error) { return nil, nil }, + Links: func() ([]netlink.Link, error) { return nil, nil }, + Uplinks: func() ([]string, error) { return nil, nil }, + } + tests := []struct { + name string + mutate func(*Options) + wantError bool + }{ + {"Valid", func(*Options) {}, false}, + {"NoTarget", func(o *Options) { o.Target = nil }, true}, + {"NoRoutes", func(o *Options) { o.Routes = nil }, true}, + {"ModeOff", func(o *Options) { o.Settings.Mode = ModeOff }, true}, + {"NoDomain", func(o *Options) { o.Settings.DomainPrefixes = nil }, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + o := ok + tt.mutate(&o) + if _, err := New(o); (err != nil) != tt.wantError { + t.Errorf("New() error = %v, wantError %v", err, tt.wantError) + } + }) + } +} + +func TestDisable(t *testing.T) { + f, _ := srcfiltermap.NewFake() + cfg := srcfiltermap.Config{Mode: srcfiltermap.ModeEnforce, Populated: true, Generation: 4} + if err := f.SetConfig(cfg); err != nil { + t.Fatal(err) + } + if err := Disable(USIDTarget{Filter: f}); err != nil { + t.Fatal(err) + } + assertConfig(t, f, srcfiltermap.Config{Mode: srcfiltermap.ModeOff, Generation: 5}) + if err := Disable(USIDTarget{Filter: f}); err != nil { + t.Fatal(err) + } + assertConfig(t, f, srcfiltermap.Config{Mode: srcfiltermap.ModeOff, Generation: 5}) +} diff --git a/internal/srcfilter/settings.go b/internal/srcfilter/settings.go new file mode 100644 index 000000000..f709df34e --- /dev/null +++ b/internal/srcfilter/settings.go @@ -0,0 +1,163 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfilter + +import ( + "errors" + "fmt" + "net/netip" + "strings" + + "go.datum.net/galactic/internal/config" +) + +const ( + modeNameOff = "off" + modeNameAudit = "audit" + modeNameEnforce = "enforce" + bindingNameStrict = "strict" + bindingNameLoose = "loose" +) + +// Mode selects how the datapath acts on a source the filter rejects. +type Mode uint32 + +const ( + // ModeOff disables the filter. + ModeOff Mode = iota + // ModeAudit counts and records rejected sources but still delivers them. + ModeAudit + // ModeEnforce drops rejected sources. + ModeEnforce +) + +// 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 returns the Mode named by s, case-insensitively. Empty means +// ModeOff. Any other unknown name is an error. +func ParseMode(s string) (Mode, error) { + s = strings.TrimSpace(s) + if s == "" { + return ModeOff, nil + } + for _, m := range []Mode{ModeOff, ModeAudit, ModeEnforce} { + if strings.EqualFold(s, m.String()) { + return m, nil + } + } + return ModeOff, fmt.Errorf("unknown source filter mode %q (want off, audit or enforce)", s) +} + +// Binding selects whether a source is tied to the uplinks its route uses. +type Binding uint32 + +const ( + // BindingStrict accepts a source only on the uplinks this node's route to + // it leaves through. + BindingStrict Binding = iota + // BindingLoose accepts a known source on any uplink. + BindingLoose +) + +// String returns the binding's configuration name. +func (b Binding) String() string { + if b == BindingLoose { + return bindingNameLoose + } + return bindingNameStrict +} + +// ParseBinding returns the Binding named by s, case-insensitively. Empty means +// BindingStrict. Any other unknown name is an error. +func ParseBinding(s string) (Binding, error) { + switch strings.ToLower(strings.TrimSpace(s)) { + case "", bindingNameStrict: + return BindingStrict, nil + case bindingNameLoose: + return BindingLoose, nil + default: + return BindingStrict, fmt.Errorf("unknown source binding %q (want strict or loose)", s) + } +} + +// DefaultMinPrefixLen is the shortest route a pass turns into an allow entry. +// A locator is a /64, so anything shorter is an aggregate that would also allow +// node IDs nobody holds. +const DefaultMinPrefixLen = 64 + +// Settings is the operator-facing source filter configuration. +type Settings struct { + Mode Mode + DomainPrefixes []netip.Prefix + Binding Binding + ExtraSources []netip.Prefix +} + +// LoadSettings reads Settings from the GALACTIC_CNI_SRV6_* variables through +// getenv. It returns an error for an unknown mode or binding, a malformed +// prefix, or audit or enforce mode with no SR domain prefixes. With mode off +// the other variables are not validated. +func LoadSettings(getenv func(string) string) (Settings, error) { + mode, err := ParseMode(getenv(config.EnvCNISRv6SourceFilter)) + if err != nil { + return Settings{}, fmt.Errorf("%s: %w", config.EnvCNISRv6SourceFilter, err) + } + if mode == ModeOff { + return Settings{Mode: ModeOff}, nil + } + + s := Settings{Mode: mode} + var errs []error + if s.Binding, err = ParseBinding(getenv(config.EnvCNISRv6SourceBinding)); err != nil { + errs = append(errs, fmt.Errorf("%s: %w", config.EnvCNISRv6SourceBinding, err)) + } + if s.DomainPrefixes, err = ParsePrefixList(getenv(config.EnvCNISRv6DomainPrefixes)); err != nil { + errs = append(errs, fmt.Errorf("%s: %w", config.EnvCNISRv6DomainPrefixes, err)) + } else if len(s.DomainPrefixes) == 0 { + errs = append(errs, fmt.Errorf("%s is required when %s is %s", + config.EnvCNISRv6DomainPrefixes, config.EnvCNISRv6SourceFilter, mode)) + } + if s.ExtraSources, err = ParsePrefixList(getenv(config.EnvCNISRv6SourceAllowExtra)); err != nil { + errs = append(errs, fmt.Errorf("%s: %w", config.EnvCNISRv6SourceAllowExtra, err)) + } + if len(errs) > 0 { + return Settings{}, errors.Join(errs...) + } + return s, nil +} + +// ParsePrefixList splits a comma-separated list of IPv6 prefixes, trimming +// whitespace and skipping blank entries, and returns each masked. An entry +// that is not an IPv6 prefix is an error. +func ParsePrefixList(raw string) ([]netip.Prefix, error) { + var out []netip.Prefix + for part := range strings.SplitSeq(raw, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + p, err := netip.ParsePrefix(part) + if err != nil { + return nil, fmt.Errorf("parse prefix %q: %w", part, err) + } + if !p.Addr().Is6() || p.Addr().Is4In6() { + return nil, fmt.Errorf("prefix %q is not IPv6", part) + } + out = append(out, p.Masked()) + } + return out, nil +} diff --git a/internal/srcfilter/settings_test.go b/internal/srcfilter/settings_test.go new file mode 100644 index 000000000..55d0ef15f --- /dev/null +++ b/internal/srcfilter/settings_test.go @@ -0,0 +1,82 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfilter + +import ( + "net/netip" + "slices" + "testing" + + "go.datum.net/galactic/internal/config" +) + +const testDomain = "2001:db8::/32" + +func TestLoadSettings(t *testing.T) { + tests := []struct { + name string + env map[string]string + want Settings + wantError bool + }{ + {"Unset", nil, Settings{Mode: ModeOff}, false}, + {"OffIgnoresRest", map[string]string{ + config.EnvCNISRv6SourceFilter: modeNameOff, + config.EnvCNISRv6SourceBinding: "bogus", + config.EnvCNISRv6DomainPrefixes: "nope", + }, Settings{Mode: ModeOff}, false}, + {"AUDIT", map[string]string{ + config.EnvCNISRv6SourceFilter: "AUDIT", + config.EnvCNISRv6DomainPrefixes: " 2001:db8::/32, ,fd00::1/48", + config.EnvCNISRv6SourceAllowExtra: "2001:db8:ffff::/48", + }, Settings{ + Mode: ModeAudit, + DomainPrefixes: []netip.Prefix{netip.MustParsePrefix(testDomain), netip.MustParsePrefix("fd00::/48")}, + ExtraSources: []netip.Prefix{netip.MustParsePrefix("2001:db8:ffff::/48")}, + }, false}, + {"EnforceLoose", map[string]string{ + config.EnvCNISRv6SourceFilter: modeNameEnforce, + config.EnvCNISRv6DomainPrefixes: testDomain, + config.EnvCNISRv6SourceBinding: bindingNameLoose, + }, Settings{ + Mode: ModeEnforce, + DomainPrefixes: []netip.Prefix{netip.MustParsePrefix(testDomain)}, + Binding: BindingLoose, + }, false}, + {"EnforceWithoutDomain", map[string]string{config.EnvCNISRv6SourceFilter: modeNameEnforce}, Settings{}, true}, + {"AuditWithoutDomain", map[string]string{config.EnvCNISRv6SourceFilter: modeNameAudit}, Settings{}, true}, + {"UnknownMode", map[string]string{config.EnvCNISRv6SourceFilter: "drop"}, Settings{}, true}, + {"UnknownBinding", map[string]string{ + config.EnvCNISRv6SourceFilter: modeNameAudit, + config.EnvCNISRv6DomainPrefixes: testDomain, + config.EnvCNISRv6SourceBinding: "tight", + }, Settings{}, true}, + {"IPv4Domain", map[string]string{ + config.EnvCNISRv6SourceFilter: modeNameAudit, + config.EnvCNISRv6DomainPrefixes: "10.0.0.0/8", + }, Settings{}, true}, + {"BadExtra", map[string]string{ + config.EnvCNISRv6SourceFilter: modeNameAudit, + config.EnvCNISRv6DomainPrefixes: testDomain, + config.EnvCNISRv6SourceAllowExtra: "2001:db8::1", + }, Settings{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := LoadSettings(func(k string) string { return tt.env[k] }) + if (err != nil) != tt.wantError { + t.Fatalf("LoadSettings() error = %v, wantError %v", err, tt.wantError) + } + if tt.wantError { + return + } + if got.Mode != tt.want.Mode || got.Binding != tt.want.Binding || + !slices.Equal(got.DomainPrefixes, tt.want.DomainPrefixes) || + !slices.Equal(got.ExtraSources, tt.want.ExtraSources) { + t.Errorf("LoadSettings() = %+v, want %+v", got, tt.want) + } + }) + } +} diff --git a/internal/srcfilter/slots.go b/internal/srcfilter/slots.go new file mode 100644 index 000000000..956cf3e87 --- /dev/null +++ b/internal/srcfilter/slots.go @@ -0,0 +1,65 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfilter + +import ( + "fmt" + "maps" + "slices" +) + +// StableSlots is a SlotAssigner that keeps every uplink still present on the +// slot it already holds and gives each new uplink the lowest free slot. A slot +// released in this same pass is reused only when no other is free, so an entry +// still naming the old uplink's bit is not briefly accepted on the new one. More +// than MaxSlots uplinks is an error. +func StableSlots(uplinks []uint32, current map[uint32]uint8) (map[uint32]uint8, error) { + want := make(map[uint32]struct{}, len(uplinks)) + for _, ifindex := range uplinks { + want[ifindex] = struct{}{} + } + if len(want) > MaxSlots { + return nil, fmt.Errorf("%d uplinks exceed the source filter's %d interface slots", len(want), MaxSlots) + } + + out := make(map[uint32]uint8, len(want)) + var used, released [MaxSlots]bool + for ifindex, slot := range current { + if int(slot) >= MaxSlots { + continue + } + if _, ok := want[ifindex]; ok && !used[slot] { + out[ifindex] = slot + used[slot] = true + continue + } + released[slot] = true + } + + pick := func() uint8 { + for _, avoidReleased := range []bool{true, false} { + for s := range MaxSlots { + if !used[s] && (!avoidReleased || !released[s]) { + used[s] = true + return uint8(s) + } + } + } + return MaxSlots + } + for _, ifindex := range slices.Sorted(maps.Keys(want)) { + if _, ok := out[ifindex]; ok { + continue + } + out[ifindex] = pick() + } + return out, nil +} + +// KeepSlots is a SlotAssigner for a datapath whose owner assigns uplink slots +// itself: it returns the Target's current assignment unchanged. +func KeepSlots(_ []uint32, current map[uint32]uint8) (map[uint32]uint8, error) { + return maps.Clone(current), nil +} diff --git a/internal/srcfilter/slots_test.go b/internal/srcfilter/slots_test.go new file mode 100644 index 000000000..60dac1bae --- /dev/null +++ b/internal/srcfilter/slots_test.go @@ -0,0 +1,78 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfilter + +import ( + "maps" + "testing" +) + +func TestStableSlots(t *testing.T) { + tests := []struct { + name string + uplinks []uint32 + current map[uint32]uint8 + want map[uint32]uint8 + wantError bool + }{ + {"Fresh", []uint32{7, 3}, nil, map[uint32]uint8{3: 0, 7: 1}, false}, + {"KeepsExisting", []uint32{3, 7}, map[uint32]uint8{7: 5}, map[uint32]uint8{7: 5, 3: 0}, false}, + {"AvoidsReleased", []uint32{9}, map[uint32]uint8{3: 0}, map[uint32]uint8{9: 1}, false}, + {"DropsRemoved", []uint32{3}, map[uint32]uint8{3: 2, 4: 0}, map[uint32]uint8{3: 2}, false}, + {"DuplicateUplink", []uint32{3, 3}, nil, map[uint32]uint8{3: 0}, false}, + {"TooMany", seq(MaxSlots + 1), nil, nil, true}, + {"Full", seq(MaxSlots), nil, nil, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := StableSlots(tt.uplinks, tt.current) + if (err != nil) != tt.wantError { + t.Fatalf("StableSlots() error = %v, wantError %v", err, tt.wantError) + } + if tt.want != nil && !maps.Equal(got, tt.want) { + t.Errorf("StableSlots() = %v, want %v", got, tt.want) + } + seen := map[uint8]bool{} + for _, s := range got { + if seen[s] || int(s) >= MaxSlots { + t.Errorf("slot %d duplicated or out of range in %v", s, got) + } + seen[s] = true + } + }) + } +} + +func TestStableSlotsReusesReleasedWhenFull(t *testing.T) { + current := map[uint32]uint8{} + for i := range uint32(MaxSlots) { + current[i+1] = uint8(i) + } + uplinks := seq(MaxSlots) + uplinks[0] = 1000 + got, err := StableSlots(uplinks, current) + if err != nil { + t.Fatal(err) + } + if got[1000] != 0 { + t.Errorf("new uplink got slot %d, want released slot 0", got[1000]) + } +} + +func TestKeepSlots(t *testing.T) { + cur := map[uint32]uint8{4: 2} + got, err := KeepSlots([]uint32{1, 2}, cur) + if err != nil || !maps.Equal(got, cur) { + t.Errorf("KeepSlots() = %v, %v", got, err) + } +} + +func seq(n int) []uint32 { + out := make([]uint32, n) + for i := range out { + out[i] = uint32(i + 1) + } + return out +} diff --git a/internal/srcfilter/target.go b/internal/srcfilter/target.go new file mode 100644 index 000000000..e6f1361ec --- /dev/null +++ b/internal/srcfilter/target.go @@ -0,0 +1,53 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfilter + +import "net/netip" + +// MaxSlots is the number of distinct uplinks an entry's interface mask can +// name. Valid slots are 0 through MaxSlots-1. +const MaxSlots = 32 + +// Entry is one allowed source prefix. +type Entry struct { + Prefix netip.Prefix + // IfaceMask has bit N set for every uplink assigned slot N. + IfaceMask uint32 + // AnyIface accepts the prefix on every interface, ignoring IfaceMask. + AnyIface bool +} + +// State is a filter's global state. +type State struct { + Mode Mode + // Populated reports that the allow-list reflects a complete sync. While + // false the datapath lets every packet through. + Populated bool + // Generation is a counter bumped on every applied change. + Generation uint64 +} + +// Target is a datapath's source filter as the Reconciler drives it. Every +// method must be safe to call again after a partial failure. +type Target interface { + // ListAllow returns every allow entry. + ListAllow() ([]Entry, error) + // PutAllow creates or overwrites the entry for e.Prefix. + PutAllow(e Entry) error + // DeleteAllow removes the entry for p. An absent entry is not an error. + DeleteAllow(p netip.Prefix) error + // UplinkSlots returns every ifindex-to-slot assignment. + UplinkSlots() (map[uint32]uint8, error) + // SyncUplinkSlots makes the slot assignments exactly slots. + SyncUplinkSlots(slots map[uint32]uint8) error + // State returns the filter's global state. + State() (State, error) + // SetState writes the filter's global state. + SetState(s State) error +} + +// SlotAssigner returns the ifindex-to-slot assignment for a pass, given the +// uplink ifindexes the pass resolved and the assignment the Target holds now. +type SlotAssigner func(uplinks []uint32, current map[uint32]uint8) (map[uint32]uint8, error) diff --git a/internal/srcfilter/usidtarget.go b/internal/srcfilter/usidtarget.go new file mode 100644 index 000000000..d096682b0 --- /dev/null +++ b/internal/srcfilter/usidtarget.go @@ -0,0 +1,110 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfilter + +import ( + "fmt" + "net/netip" + + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" + + "go.datum.net/galactic/internal/plumbing/ebpf/srcfiltermap" +) + +// USIDTarget adapts the uSID datapath's source filter maps to Target. +type USIDTarget struct { + Filter *srcfiltermap.Filter +} + +var _ Target = USIDTarget{} + +// ListAllow implements Target. +func (t USIDTarget) ListAllow() ([]Entry, error) { + in, err := t.Filter.ListAllow() + if err != nil { + return nil, err + } + out := make([]Entry, 0, len(in)) + for _, e := range in { + out = append(out, Entry{Prefix: e.Prefix, IfaceMask: e.IfaceMask, AnyIface: e.AnyIface}) + } + return out, nil +} + +// PutAllow implements Target. +func (t USIDTarget) PutAllow(e Entry) error { + return t.Filter.PutAllow(srcfiltermap.Entry{Prefix: e.Prefix, IfaceMask: e.IfaceMask, AnyIface: e.AnyIface}) +} + +// DeleteAllow implements Target. +func (t USIDTarget) DeleteAllow(p netip.Prefix) error { return t.Filter.DeleteAllow(p) } + +// UplinkSlots implements Target. +func (t USIDTarget) UplinkSlots() (map[uint32]uint8, error) { return t.Filter.UplinkSlots() } + +// SyncUplinkSlots implements Target. +func (t USIDTarget) SyncUplinkSlots(slots map[uint32]uint8) error { + return t.Filter.SyncUplinkSlots(slots) +} + +// State implements Target. +func (t USIDTarget) State() (State, error) { + c, err := t.Filter.Config() + if err != nil { + return State{}, err + } + m, err := fromMapMode(c.Mode) + if err != nil { + return State{}, err + } + return State{Mode: m, Populated: c.Populated, Generation: uint64(c.Generation)}, nil +} + +// SetState implements Target. The map holds a 32-bit generation, so the +// counter wraps there. +func (t USIDTarget) SetState(s State) error { + m, err := toMapMode(s.Mode) + if err != nil { + return err + } + return t.Filter.SetConfig(srcfiltermap.Config{ + Mode: m, + Populated: s.Populated, + Generation: uint32(s.Generation), //nolint:gosec // an opaque counter; wrapping is harmless + }) +} + +func toMapMode(m Mode) (srcfiltermap.Mode, error) { + switch m { + case ModeOff: + return srcfiltermap.ModeOff, nil + case ModeAudit: + return srcfiltermap.ModeAudit, nil + case ModeEnforce: + return srcfiltermap.ModeEnforce, nil + default: + return srcfiltermap.ModeOff, fmt.Errorf("srcfilter: invalid mode %s", m) + } +} + +func fromMapMode(m srcfiltermap.Mode) (Mode, error) { + switch m { + case srcfiltermap.ModeOff: + return ModeOff, nil + case srcfiltermap.ModeAudit: + return ModeAudit, nil + case srcfiltermap.ModeEnforce: + return ModeEnforce, nil + default: + return ModeOff, fmt.Errorf("srcfilter: datapath holds unknown mode %s", m) + } +} + +// MainTableRoutes lists every IPv6 route in the host's main routing table. +func MainTableRoutes() ([]netlink.Route, error) { + return netlink.RouteListFiltered(netlink.FAMILY_V6, + &netlink.Route{Table: unix.RT_TABLE_MAIN}, netlink.RT_FILTER_TABLE) +} From fc5856bb586580b9cb33a528af8f896688c1ebab Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 24 Sep 2026 08:36:37 -0500 Subject: [PATCH 2/2] feat(cni): allow only fabric-installed routes as SRv6 sources The source filter now takes an allow-list entry only from a route the fabric's own routing installed, and optionally only through a configured fabric peer, so a static or hand-added route can never widen the set of accepted SRv6 senders. - galactic-router tags its plain main-table routes (gateway and egress shard routes) with a dedicated kernel route protocol, 214, instead of the default boot protocol; a replace re-tags routes an older version installed, which happens when the router restarts and replays its RIB - the reconciler accepts only protocol bgp (the underlay) and 214 - GALACTIC_CNI_SRV6_FABRIC_NEXTHOPS optionally requires each counted hop to use a gateway inside the listed peer prefixes on an uplink; a route with no such hop is left out, and a pass left with none keeps the previous allow-list --- docs/cni/architecture.md | 20 +++-- docs/cni/environment-variables.md | 16 ++-- go.mod | 2 +- internal/config/cni.go | 8 ++ internal/installer/srcfilter.go | 12 ++- internal/installer/srcfilter_test.go | 1 + internal/srcfilter/desired.go | 107 ++++++++++++++++++++------ internal/srcfilter/reconciler.go | 39 +++++++--- internal/srcfilter/reconciler_test.go | 93 +++++++++++++++++++++- internal/srcfilter/settings.go | 6 ++ internal/srcfilter/settings_test.go | 17 +++- internal/srcfilter/usidtarget.go | 41 +++++++++- 12 files changed, 304 insertions(+), 58 deletions(-) diff --git a/docs/cni/architecture.md b/docs/cni/architecture.md index b8198d6c5..5e026f6f1 100644 --- a/docs/cni/architecture.md +++ b/docs/cni/architecture.md @@ -218,11 +218,21 @@ container) owns the allow-list through `internal/srcfilter`. It is started only when `GALACTIC_CNI_SRV6_SOURCE_FILTER` is `audit` or `enforce`; with `off`, or an invalid configuration, the container writes mode `off` and starts nothing. -- **Inputs.** Every main-table IPv6 route of any protocol that forwards: peer - locators arrive from FRR as BGP routes, egress shard SIDs as boot-protocol - routes. A route counts only if it lies inside a configured SR domain prefix, - is at least a /64 (so an aggregate never allows unassigned node IDs), and is - not inside this node's own locator from its `BGPRouter`. +- **Inputs.** Main-table IPv6 routes that forward and were installed by the + fabric's own routing: protocol `bgp` (FRR's underlay). The filter also considers + protocol 250 gateway and shard routes from the router's dedicated plain-route + table when their prefix does not overlap a specific main-table route. + Static, boot, kernel and other routes never count. Eligible prefixes lie + inside a configured SR domain, are at least a /64, and exclude this + node's own locator from its `BGPRouter`. +- **Fabric next hop.** When `GALACTIC_CNI_SRV6_FABRIC_NEXTHOPS` is set, only + hops whose gateway lies inside it and that leave through an uplink count, + and a route with no such hop is left out. Kernel routes carry the resolved, + directly connected gateway even for recursive or iBGP routes, so the list + names peer link and transit addresses (and `fe80::/10` for unnumbered + sessions), not loopbacks. The peer set lives in the underlay's own + configuration, which galactic does not read, so this is operator-supplied; + unset skips the check. - **Interface binding.** An entry's mask is the union of the slots of every hop's link, a bond master or a VLAN on a bond counting as the bond's slaves. Uplinks are what `attach.ResolveInterfaces` returns, each keeping its slot diff --git a/docs/cni/environment-variables.md b/docs/cni/environment-variables.md index cb29ea39f..af84d3224 100644 --- a/docs/cni/environment-variables.md +++ b/docs/cni/environment-variables.md @@ -197,17 +197,19 @@ of 100; refusals are counted as `rate_limited`. ## SRv6 ingress source filter -Controls the uSID datapath's SRv6 ingress source filter: a node accepts SRv6 traffic for its tenant networks only from sources inside a fabric peer's locator, and only on the uplinks its route to that peer uses. `galactic-cni run` builds the allow-list from the node's main routing table and keeps it current. Read only by that container, with no conflist tier. +Controls the uSID datapath's SRv6 ingress source filter: a node accepts SRv6 traffic for its tenant networks only from sources inside a fabric peer's locator, and only on the uplinks its route to that peer uses. `galactic-cni run` builds the allow-list from the fabric routes installed by underlay BGP in the main table or by `galactic-router` in its plain-route table and keeps it current. Static and other routes never become allowed sources. Read only by that container, with no conflist tier. -| Variable | Values | Default | Effect | -| -------------------------------------- | ----------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- | -| `GALACTIC_CNI_SRV6_SOURCE_FILTER` | `off`, `audit`, `enforce` | `off` | `off` leaves traffic untouched and starts no reconciler. `audit` counts and records sources it would reject. `enforce` drops them. | -| `GALACTIC_CNI_SRV6_DOMAIN_PREFIXES` | comma-separated IPv6 prefixes | _(none)_ | The prefixes fabric locators are allocated from. Only routes inside them, and at least a /64, become allowed sources. Required unless `off`. | -| `GALACTIC_CNI_SRV6_SOURCE_BINDING` | `strict`, `loose` | `strict` | `strict` accepts a source only on the uplinks this node's route to it uses. `loose` accepts a known source on any uplink. | -| `GALACTIC_CNI_SRV6_SOURCE_ALLOW_EXTRA` | comma-separated IPv6 prefixes | _(none)_ | Extra sources allowed on any uplink, for senders with no route in the main table. | +| Variable | Values | Default | Effect | +| -------------------------------------- | ----------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GALACTIC_CNI_SRV6_SOURCE_FILTER` | `off`, `audit`, `enforce` | `off` | `off` leaves traffic untouched and starts no reconciler. `audit` counts and records sources it would reject. `enforce` drops them. | +| `GALACTIC_CNI_SRV6_DOMAIN_PREFIXES` | comma-separated IPv6 prefixes | _(none)_ | The prefixes fabric locators are allocated from. Only routes inside them, and at least a /64, become allowed sources. Required unless `off`. | +| `GALACTIC_CNI_SRV6_SOURCE_BINDING` | `strict`, `loose` | `strict` | `strict` accepts a source only on the uplinks this node's route to it uses. `loose` accepts a known source on any uplink. | +| `GALACTIC_CNI_SRV6_SOURCE_ALLOW_EXTRA` | comma-separated IPv6 prefixes | _(none)_ | Extra sources allowed on any uplink, for senders with no route in the main table. | +| `GALACTIC_CNI_SRV6_FABRIC_NEXTHOPS` | comma-separated IPv6 prefixes | _(none)_ | Addresses of the fabric's BGP peers as route gateways: link and transit addresses, `fe80::/10` for unnumbered sessions. When set, a route counts only through a hop to one of them on an uplink. Unset skips the check. | - An invalid value, or `audit`/`enforce` without domain prefixes, logs an error, writes `off` and reports the `srv6-source-filter` health service as not serving. The filter is never enforced on a configuration it could not read. - The filter lets every packet through until the first complete sync, and a sync that cannot read routes, or finds no fabric route at all, keeps the previous allow-list rather than clearing it. +- A protocol 250 plain route contributes its uplinks only when its prefix has no overlap with a specific main-table route. This respects the kernel's preference for the underlay and avoids granting fallback interfaces for partially shadowed prefixes. - Roll out with `audit` first and watch `galactic_usid_src_filter_packets_total{result=~"deny_.*"}` before switching to `enforce`. Debug logging lists the most-denied sources every minute. | Metric | Type | Meaning | diff --git a/go.mod b/go.mod index 7d902bd44..3eec54be9 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/containernetworking/cni v1.3.1 github.com/containernetworking/plugins v1.9.1 github.com/coreos/go-iptables v0.8.0 + github.com/gaissmai/bart v0.26.1 github.com/go-logr/logr v1.4.4 github.com/google/uuid v1.6.0 github.com/k8snetworkplumbingwg/network-attachment-definition-client v1.7.7 @@ -72,7 +73,6 @@ require ( github.com/evanphx/json-patch/v5 v5.9.11 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect github.com/fxamacker/cbor/v2 v2.9.1 // indirect - github.com/gaissmai/bart v0.26.1 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-logr/zapr v1.3.0 // indirect github.com/go-openapi/jsonpointer v1.0.0 // indirect diff --git a/internal/config/cni.go b/internal/config/cni.go index 021a1bdd4..0ce8e5d40 100644 --- a/internal/config/cni.go +++ b/internal/config/cni.go @@ -72,6 +72,14 @@ const ( // the main table. EnvCNISRv6SourceAllowExtra = "GALACTIC_CNI_SRV6_SOURCE_ALLOW_EXTRA" + // EnvCNISRv6FabricNextHops is a comma-separated list of IPv6 prefixes + // holding the addresses of this fabric's BGP peers as they appear as route + // gateways: link and transit addresses, and fe80::/10 for unnumbered + // sessions. When set, a route becomes an allowed source only through a + // hop whose gateway lies inside it and that leaves through an uplink. + // Unset skips the next-hop check. + EnvCNISRv6FabricNextHops = "GALACTIC_CNI_SRV6_FABRIC_NEXTHOPS" + // EnvCNIEgressShardSIDs is a comma-separated list of every live egress // shard's SID: the fabric-wide membership a tenant VRF's egress routes need. // One SID per shard covers both address families -- a shard decides which diff --git a/internal/installer/srcfilter.go b/internal/installer/srcfilter.go index 5733f8f60..d86d1b62c 100644 --- a/internal/installer/srcfilter.go +++ b/internal/installer/srcfilter.go @@ -15,6 +15,7 @@ import ( "google.golang.org/grpc/health" "google.golang.org/grpc/health/grpc_health_v1" + "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/plumbing/ebpf/attach" "go.datum.net/galactic/internal/plumbing/ebpf/srcfiltermap" "go.datum.net/galactic/internal/srcfilter" @@ -65,7 +66,7 @@ func startSourceFilter(ctx context.Context, st ebpfDatapathState, healthSrv *hea r, err := srcfilter.New(srcfilter.Options{ Settings: settings, Target: target, - Routes: srcfilter.MainTableRoutes, + Routes: srcfilter.FabricRoutes, Links: netlink.LinkList, Uplinks: attach.ResolveInterfaces, OwnLocator: ownLocatorFn(st), @@ -79,7 +80,11 @@ func startSourceFilter(ctx context.Context, st ebpfDatapathState, healthSrv *hea slog.Info("SRv6 source filter reconciler starting", "mode", settings.Mode.String(), "binding", settings.Binding.String(), "domainPrefixes", settings.DomainPrefixes, - "extraSources", settings.ExtraSources) + "extraSources", settings.ExtraSources, "fabricNextHops", settings.FabricNextHops) + if len(settings.FabricNextHops) == 0 { + slog.Warn("SRv6 source filter next-hop check is off: routes from the fabric's routing are accepted " + + "whatever their gateway; set " + config.EnvCNISRv6FabricNextHops + " to require a fabric peer") + } healthSrv.SetServingStatus(srcFilterHealthServiceName, grpc_health_v1.HealthCheckResponse_NOT_SERVING) go runSourceFilter(ctx, r, filter, st.watcher, healthSrv) } @@ -134,7 +139,8 @@ func sourceFilterPass(ctx context.Context, r *srcfilter.Reconciler, healthSrv *h } if res.Changed { slog.Info("SRv6 source filter allow-list updated", "entries", res.Entries, "added", res.Added, - "updated", res.Updated, "removed", res.Removed, "unbound", res.Unbound, "uplinks", res.SlotCount, + "updated", res.Updated, "removed", res.Removed, "unbound", res.Unbound, + "foreignNextHop", res.ForeignNextHop, "uplinks", res.SlotCount, "mode", res.State.Mode.String(), "generation", res.State.Generation) } return "" diff --git a/internal/installer/srcfilter_test.go b/internal/installer/srcfilter_test.go index baeff7a34..dda54b449 100644 --- a/internal/installer/srcfilter_test.go +++ b/internal/installer/srcfilter_test.go @@ -38,6 +38,7 @@ func TestSourceFilterPassReportsHealth(t *testing.T) { LinkIndex: 1, Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, + Protocol: unix.RTPROT_BGP, }} var routesErr error diff --git a/internal/srcfilter/desired.go b/internal/srcfilter/desired.go index bd30883c3..27893e14c 100644 --- a/internal/srcfilter/desired.go +++ b/internal/srcfilter/desired.go @@ -13,6 +13,7 @@ import ( "golang.org/x/sys/unix" "go.datum.net/galactic/internal/plumbing/bond" + "go.datum.net/galactic/internal/plumbing/srv6" ) const vlanLinkType = "vlan" @@ -27,6 +28,11 @@ type desiredInput struct { minPrefixLen int binding Binding extra []netip.Prefix + // nextHops, when non-empty, are the only gateways a hop may use. + nextHops []netip.Prefix + // uplinks is the set of uplink ifindexes. A hop checked against nextHops + // must also leave through one of them. + uplinks map[int]bool } // desiredOutput is a pass's allow-list plus what it was built from. @@ -37,17 +43,25 @@ type desiredOutput struct { // unbound counts route entries with a hop whose link is unknown, which // are accepted on any interface rather than bound to none. unbound int + // foreignNextHop counts routes dropped because no hop's gateway is a + // fabric next hop. + foreignNextHop int } // computeDesired returns the allow-list for in, sorted by prefix, with // duplicate prefixes merged. // -// A route yields an entry when it is an IPv6 main-table route that forwards, -// its destination lies inside a domain prefix, is at least minPrefixLen long, -// and does not lie inside this node's own locator. Its interface mask is the -// union of every hop's link slots, a bond master or a VLAN on a bond counting -// as its slaves. Loose binding, or a hop with no usable link, accepts the -// prefix on any interface. Every extra prefix is accepted on any interface. +// A route yields an entry when it is an IPv6 fabric route that forwards, +// was installed by the fabric's routing (BGP or galactic-router), its +// destination lies inside a domain prefix, is at least minPrefixLen long, and +// does not lie inside this node's own locator. When nextHops is set, only hops +// whose gateway lies inside it and that leave through an uplink count, and a +// route with no such hop yields nothing. +// +// Its interface mask is the union of every counted hop's link slots, a bond +// master or a VLAN on a bond counting as its slaves. Loose binding, or a hop +// with no usable link, accepts the prefix on any interface. Every extra prefix +// is accepted on any interface. func computeDesired(in desiredInput) desiredOutput { byIndex := make(map[int]netlink.Link, len(in.links)) for _, l := range in.links { @@ -73,7 +87,11 @@ func computeDesired(in desiredInput) desiredOutput { if !ok || !in.eligible(p) { continue } - mask, bound := hopMask(r, byIndex, in.links, in.slots) + mask, bound, ok := in.hopMask(r, byIndex) + if !ok { + out.foreignNextHop++ + continue + } e := Entry{Prefix: p, IfaceMask: mask, AnyIface: in.binding == BindingLoose || !bound} if !bound { out.unbound++ @@ -116,16 +134,21 @@ func contains(outer, inner netip.Prefix) bool { return outer.Bits() <= inner.Bits() && outer.Contains(inner.Addr()) } -// routePrefix returns r's destination when r is an IPv6 main-table route that +// routePrefix returns r's destination when r is an IPv6 fabric route that // forwards somewhere. A discard or local route, a default route and an IPv4 // route all return false. func routePrefix(r *netlink.Route) (netip.Prefix, bool) { - if r.Table != unix.RT_TABLE_MAIN || r.Dst == nil { + if r.Dst == nil { return netip.Prefix{}, false } if r.Type != unix.RTN_UNICAST && r.Type != unix.RTN_UNSPEC { return netip.Prefix{}, false } + underlay := r.Table == unix.RT_TABLE_MAIN && r.Protocol == unix.RTPROT_BGP + plain := r.Table == int(srv6.PlainRouteTable) && r.Protocol == srv6.PlainRouteProtocol + if !underlay && !plain { + return netip.Prefix{}, false + } ones, bits := r.Dst.Mask.Size() if bits != net.IPv6len*8 || ones == 0 { return netip.Prefix{}, false @@ -137,33 +160,67 @@ func routePrefix(r *netlink.Route) (netip.Prefix, bool) { return netip.PrefixFrom(addr, ones).Masked(), true } -// hopMask returns the union of the slots of every link r's hops leave through, -// and whether every hop named a link that could be resolved. -func hopMask( - r *netlink.Route, byIndex map[int]netlink.Link, all []netlink.Link, slots map[uint32]uint8, -) (uint32, bool) { - hops := make([]int, 0, 1+len(r.MultiPath)) +// hopMask returns the union of the slots of every counted link r's hops leave +// through, whether every counted hop named a link that could be resolved, and +// whether any hop counted at all. Without nextHops every hop counts. +func (in desiredInput) hopMask(r *netlink.Route, byIndex map[int]netlink.Link) (uint32, bool, bool) { + type hop struct { + link int + gw net.IP + } + hops := make([]hop, 0, 1+len(r.MultiPath)) if len(r.MultiPath) > 0 { for _, nh := range r.MultiPath { - hops = append(hops, nh.LinkIndex) + hops = append(hops, hop{link: nh.LinkIndex, gw: nh.Gw}) } } else { - hops = append(hops, r.LinkIndex) + hops = append(hops, hop{link: r.LinkIndex, gw: r.Gw}) } - var mask uint32 - for _, ifindex := range hops { - link, ok := byIndex[ifindex] - if ifindex <= 0 || !ok { - return 0, false + var ( + mask uint32 + bound = true + counted bool + ) + for _, h := range hops { + if len(in.nextHops) > 0 && !in.fabricNextHop(h.link, h.gw) { + continue } - for _, idx := range ingressLinks(link, byIndex, all) { - if slot, ok := slots[uint32(idx)]; ok && int(slot) < MaxSlots { + counted = true + link, ok := byIndex[h.link] + if h.link <= 0 || !ok { + bound = false + continue + } + for _, idx := range ingressLinks(link, byIndex, in.links) { + if slot, ok := in.slots[uint32(idx)]; ok && int(slot) < MaxSlots { mask |= 1 << slot } } } - return mask, true + if !bound { + mask = 0 + } + return mask, bound, counted +} + +// fabricNextHop reports whether a hop through link to gw reaches a fabric BGP +// peer: gw lies inside a nextHops prefix and link is an uplink. +func (in desiredInput) fabricNextHop(link int, gw net.IP) bool { + if !in.uplinks[link] { + return false + } + addr, ok := netip.AddrFromSlice(gw) + if !ok { + return false + } + addr = addr.Unmap() + for _, p := range in.nextHops { + if p.Contains(addr) { + return true + } + } + return false } // ingressLinks returns the ifindexes a packet routed out of link can arrive diff --git a/internal/srcfilter/reconciler.go b/internal/srcfilter/reconciler.go index 65a6eeb37..757e3c8b5 100644 --- a/internal/srcfilter/reconciler.go +++ b/internal/srcfilter/reconciler.go @@ -31,7 +31,7 @@ type Options struct { Target Target // Slots assigns uplink slots. StableSlots when nil. Slots SlotAssigner - // Routes lists the main table's IPv6 routes. + // Routes lists the IPv6 routes consulted for fabric traffic. Routes func() ([]netlink.Route, error) // Links lists every link on the host. Links func() ([]netlink.Link, error) @@ -45,14 +45,17 @@ type Options struct { // Result reports what one pass did. type Result struct { - Entries int - Added int - Updated int - Removed int - Unbound int - Changed bool - State State - SlotCount int + Entries int + Added int + Updated int + Removed int + Unbound int + // ForeignNextHop counts in-domain fabric routes left out because no hop + // used a fabric next hop. + ForeignNextHop int + Changed bool + State State + SlotCount int } // Reconciler keeps a Target's allow-list, uplink slots and state in step with @@ -149,8 +152,16 @@ func (r *Reconciler) Reconcile(ctx context.Context) (Result, error) { minPrefixLen: r.opts.MinPrefixLen, binding: r.opts.Settings.Binding, extra: r.opts.Settings.ExtraSources, + nextHops: r.opts.Settings.FabricNextHops, + uplinks: uplinkSet(uplinks), }) - res := Result{Entries: len(desired.entries), Unbound: desired.unbound, SlotCount: len(slots), State: r.state} + res := Result{ + Entries: len(desired.entries), + Unbound: desired.unbound, + ForeignNextHop: desired.foreignNextHop, + SlotCount: len(slots), + State: r.state, + } if desired.fromRoutes == 0 { return res, fmt.Errorf("srcfilter: %w", ErrNoFabricRoutes) } @@ -253,6 +264,14 @@ func (r *Reconciler) syncAllow(desired []Entry, res *Result) error { return nil } +func uplinkSet(uplinks []uint32) map[int]bool { + out := make(map[int]bool, len(uplinks)) + for _, idx := range uplinks { + out[int(idx)] = true + } + return out +} + // uplinkIndexes resolves uplink names against links. A name with no link is // skipped; none resolving is an error. func uplinkIndexes(names []string, links []netlink.Link) ([]uint32, error) { diff --git a/internal/srcfilter/reconciler_test.go b/internal/srcfilter/reconciler_test.go index 504f27ebc..acea91cb2 100644 --- a/internal/srcfilter/reconciler_test.go +++ b/internal/srcfilter/reconciler_test.go @@ -16,6 +16,7 @@ import ( "golang.org/x/sys/unix" "go.datum.net/galactic/internal/plumbing/ebpf/srcfiltermap" + "go.datum.net/galactic/internal/plumbing/srv6" ) const ( @@ -41,6 +42,10 @@ var ( discard = netip.MustParsePrefix("2001:db8:0:8::/64") outside = netip.MustParsePrefix("2001:db9:0:1::/64") extra = netip.MustParsePrefix("2001:db8:ffff:1::/64") + staticP = netip.MustParsePrefix("2001:db8:0:9::/64") + bootP = netip.MustParsePrefix("2001:db8:0:a::/64") + kernelP = netip.MustParsePrefix("2001:db8:0:b::/64") + peerGw = net.ParseIP("fe80::1") ) func testLinks() []netlink.Link { @@ -66,13 +71,35 @@ func ipnet(p netip.Prefix) *net.IPNet { func route(p netip.Prefix, link int, proto netlink.RouteProtocol) netlink.Route { return netlink.Route{ - Dst: ipnet(p), LinkIndex: link, Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, Protocol: proto, + Dst: ipnet(p), Gw: peerGw, LinkIndex: link, Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, + Protocol: proto, + } +} + +func plainTestRoute(p netip.Prefix) netlink.Route { + r := route(p, idxEth1, srv6.PlainRouteProtocol) + r.Table = int(srv6.PlainRouteTable) + return r +} + +func TestPlainRoutePrecedence(t *testing.T) { + main := []netlink.Route{ + route(peerA, idxEth0, unix.RTPROT_STATIC), + route(netip.PrefixFrom(peerB.Addr(), 128), idxEth0, unix.RTPROT_BGP), + } + fallback := []netlink.Route{ + plainTestRoute(peerA), plainTestRoute(peerB), plainTestRoute(shard), + } + got := withUnshadowedPlainRoutes(main, fallback) + if len(got) != 3 || got[2].Dst.String() != shard.String() { + t.Fatalf("merged routes = %v, want both main routes and only the unshadowed shard fallback", got) } } func testRoutes() []netlink.Route { multipath := route(peerB, 0, unix.RTPROT_BGP) - multipath.MultiPath = []*netlink.NexthopInfo{{LinkIndex: idxEth0}, {LinkIndex: idxEth1}} + multipath.Gw = nil + multipath.MultiPath = []*netlink.NexthopInfo{{LinkIndex: idxEth0, Gw: peerGw}, {LinkIndex: idxEth1, Gw: peerGw}} blackhole := route(discard, 0, unix.RTPROT_BGP) blackhole.Type = unix.RTN_BLACKHOLE otherTable := route(peerA, idxMgmt, unix.RTPROT_BGP) @@ -82,7 +109,10 @@ func testRoutes() []netlink.Route { multipath, route(peerC, idxBond0, unix.RTPROT_BGP), route(peerD, idxVlan, unix.RTPROT_BGP), - route(shard, idxEth1, unix.RTPROT_BOOT), + plainTestRoute(shard), + route(staticP, idxEth0, unix.RTPROT_STATIC), + route(bootP, idxEth0, unix.RTPROT_BOOT), + route(kernelP, idxEth0, unix.RTPROT_KERNEL), route(unboundP, 99, unix.RTPROT_BGP), route(aggregate, idxEth0, unix.RTPROT_BGP), route(ownLocator, idxEth0, unix.RTPROT_BGP), @@ -422,3 +452,60 @@ func TestDisable(t *testing.T) { } assertConfig(t, f, srcfiltermap.Config{Mode: srcfiltermap.ModeOff, Generation: 5}) } + +func TestReconcileFabricNextHops(t *testing.T) { + transit := netip.MustParsePrefix("fd00:f::/64") + onTransit := net.ParseIP("fd00:f::1") + foreign := net.ParseIP("2001:db8:9::1") + + withGw := func(r netlink.Route, gw net.IP) netlink.Route { + r.Gw = gw + return r + } + multipath := route(peerB, 0, unix.RTPROT_BGP) + multipath.Gw = nil + multipath.MultiPath = []*netlink.NexthopInfo{ + {LinkIndex: idxEth0, Gw: onTransit}, + {LinkIndex: idxEth1, Gw: foreign}, + } + + fx := newFixture() + fx.settings.FabricNextHops = []netip.Prefix{transit} + fx.settings.ExtraSources = nil + fx.routes = []netlink.Route{ + withGw(route(peerA, idxEth0, unix.RTPROT_BGP), onTransit), + multipath, + withGw(route(peerC, idxMgmt, unix.RTPROT_BGP), onTransit), + withGw(route(peerD, idxEth0, unix.RTPROT_BGP), nil), + withGw(plainTestRoute(shard), onTransit), + withGw(route(unboundP, 99, unix.RTPROT_BGP), onTransit), + withGw(route(staticP, idxEth0, unix.RTPROT_STATIC), onTransit), + } + + res, err := fx.reconciler(t).Reconcile(context.Background()) + if err != nil { + t.Fatalf("Reconcile: %v", err) + } + assertAllow(t, fx.filter, []srcfiltermap.Entry{ + {Prefix: peerA, IfaceMask: mask(t, 0)}, + {Prefix: peerB, IfaceMask: mask(t, 0)}, + {Prefix: shard, IfaceMask: mask(t, 1)}, + }) + if res.ForeignNextHop != 3 { + t.Errorf("ForeignNextHop = %d, want 3 (mgmt link, no gateway, unknown link)", res.ForeignNextHop) + } +} + +func TestReconcileNoFabricNextHopKeepsAllowList(t *testing.T) { + fx := newFixture() + r := fx.reconciler(t) + if _, err := r.Reconcile(context.Background()); err != nil { + t.Fatal(err) + } + fx.settings.FabricNextHops = []netip.Prefix{netip.MustParsePrefix("fd00:dead::/64")} + r = fx.reconciler(t) + if _, err := r.Reconcile(context.Background()); !errors.Is(err, ErrNoFabricRoutes) { + t.Fatalf("err = %v, want ErrNoFabricRoutes", err) + } + assertAllow(t, fx.filter, wantEntries(t)) +} diff --git a/internal/srcfilter/settings.go b/internal/srcfilter/settings.go index f709df34e..b4686753a 100644 --- a/internal/srcfilter/settings.go +++ b/internal/srcfilter/settings.go @@ -105,6 +105,9 @@ type Settings struct { DomainPrefixes []netip.Prefix Binding Binding ExtraSources []netip.Prefix + // FabricNextHops, when set, are the only route gateways that count as a + // fabric BGP peer. Empty skips the next-hop check. + FabricNextHops []netip.Prefix } // LoadSettings reads Settings from the GALACTIC_CNI_SRV6_* variables through @@ -134,6 +137,9 @@ func LoadSettings(getenv func(string) string) (Settings, error) { if s.ExtraSources, err = ParsePrefixList(getenv(config.EnvCNISRv6SourceAllowExtra)); err != nil { errs = append(errs, fmt.Errorf("%s: %w", config.EnvCNISRv6SourceAllowExtra, err)) } + if s.FabricNextHops, err = ParsePrefixList(getenv(config.EnvCNISRv6FabricNextHops)); err != nil { + errs = append(errs, fmt.Errorf("%s: %w", config.EnvCNISRv6FabricNextHops, err)) + } if len(errs) > 0 { return Settings{}, errors.Join(errs...) } diff --git a/internal/srcfilter/settings_test.go b/internal/srcfilter/settings_test.go index 55d0ef15f..23f72bb09 100644 --- a/internal/srcfilter/settings_test.go +++ b/internal/srcfilter/settings_test.go @@ -57,6 +57,20 @@ func TestLoadSettings(t *testing.T) { config.EnvCNISRv6SourceFilter: modeNameAudit, config.EnvCNISRv6DomainPrefixes: "10.0.0.0/8", }, Settings{}, true}, + {"FabricNextHops", map[string]string{ + config.EnvCNISRv6SourceFilter: modeNameAudit, + config.EnvCNISRv6DomainPrefixes: testDomain, + config.EnvCNISRv6FabricNextHops: "fe80::/10,fd00:f::/64", + }, Settings{ + Mode: ModeAudit, + DomainPrefixes: []netip.Prefix{netip.MustParsePrefix(testDomain)}, + FabricNextHops: []netip.Prefix{netip.MustParsePrefix("fe80::/10"), netip.MustParsePrefix("fd00:f::/64")}, + }, false}, + {"BadFabricNextHops", map[string]string{ + config.EnvCNISRv6SourceFilter: modeNameAudit, + config.EnvCNISRv6DomainPrefixes: testDomain, + config.EnvCNISRv6FabricNextHops: "10.0.0.0/8", + }, Settings{}, true}, {"BadExtra", map[string]string{ config.EnvCNISRv6SourceFilter: modeNameAudit, config.EnvCNISRv6DomainPrefixes: testDomain, @@ -74,7 +88,8 @@ func TestLoadSettings(t *testing.T) { } if got.Mode != tt.want.Mode || got.Binding != tt.want.Binding || !slices.Equal(got.DomainPrefixes, tt.want.DomainPrefixes) || - !slices.Equal(got.ExtraSources, tt.want.ExtraSources) { + !slices.Equal(got.ExtraSources, tt.want.ExtraSources) || + !slices.Equal(got.FabricNextHops, tt.want.FabricNextHops) { t.Errorf("LoadSettings() = %+v, want %+v", got, tt.want) } }) diff --git a/internal/srcfilter/usidtarget.go b/internal/srcfilter/usidtarget.go index d096682b0..1b0d2e65e 100644 --- a/internal/srcfilter/usidtarget.go +++ b/internal/srcfilter/usidtarget.go @@ -8,10 +8,13 @@ import ( "fmt" "net/netip" + "github.com/gaissmai/bart" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" "go.datum.net/galactic/internal/plumbing/ebpf/srcfiltermap" + "go.datum.net/galactic/internal/plumbing/nldump" + "go.datum.net/galactic/internal/plumbing/srv6" ) // USIDTarget adapts the uSID datapath's source filter maps to Target. @@ -103,8 +106,40 @@ func fromMapMode(m srcfiltermap.Mode) (Mode, error) { } } -// MainTableRoutes lists every IPv6 route in the host's main routing table. -func MainTableRoutes() ([]netlink.Route, error) { - return netlink.RouteListFiltered(netlink.FAMILY_V6, +// FabricRoutes reads both tables consulted by the host's routing policy. +func FabricRoutes() ([]netlink.Route, error) { + main, err := nldump.RouteListFiltered(netlink.FAMILY_V6, &netlink.Route{Table: unix.RT_TABLE_MAIN}, netlink.RT_FILTER_TABLE) + if err != nil { + return nil, fmt.Errorf("list main-table routes: %w", err) + } + plain, err := nldump.RouteListFiltered(netlink.FAMILY_V6, + &netlink.Route{Table: int(srv6.PlainRouteTable), Protocol: srv6.PlainRouteProtocol}, + netlink.RT_FILTER_TABLE|netlink.RT_FILTER_PROTOCOL) + if err != nil { + return nil, fmt.Errorf("list plain routes: %w", err) + } + return withUnshadowedPlainRoutes(main, plain), nil +} + +// A specific main-table route takes precedence over the plain-route table. +// A partially shadowed fallback cannot grant its interface for the whole prefix. +func withUnshadowedPlainRoutes(main, plain []netlink.Route) []netlink.Route { + var specific bart.Lite + for _, r := range main { + if r.Dst == nil { + continue + } + bits, width := r.Dst.Mask.Size() + addr, ok := netip.AddrFromSlice(r.Dst.IP) + if ok && width == 128 && bits > 0 && r.Type != unix.RTN_THROW { + specific.Insert(netip.PrefixFrom(addr, bits).Masked()) + } + } + for _, r := range plain { + if p, ok := routePrefix(&r); ok && !specific.OverlapsPrefix(p) { + main = append(main, r) + } + } + return main }