diff --git a/ipn/ipnlocal/local.go b/ipn/ipnlocal/local.go index 200bf4d32..72e2d6465 100644 --- a/ipn/ipnlocal/local.go +++ b/ipn/ipnlocal/local.go @@ -7029,9 +7029,15 @@ func (b *LocalBackend) routerConfigLocked(cfg *wgcfg.Config, prefs ipn.PrefsView } for vip := range vipServiceIPs { if (vip.Is4() && v4) || (vip.Is6() && v6) { - rs.Routes = append(rs.Routes, netip.PrefixFrom(vip, vip.BitLen())) + p := netip.PrefixFrom(vip, vip.BitLen()) + rs.Routes = append(rs.Routes, p) + rs.ServiceAddrs = append(rs.ServiceAddrs, p) } } + // The loop above fills rs.ServiceAddrs in map iteration order, which + // varies between calls. Sort it, because router.Config.Equal compares + // slices in order. + slices.SortFunc(rs.ServiceAddrs, netip.Prefix.Compare) // Get any extra Routes an extension may want installed. if extensionRoutesFx, ok := b.extHost.hooks.ExtraRouterConfigRoutes.GetOk(); ok { diff --git a/ipn/ipnlocal/local_test.go b/ipn/ipnlocal/local_test.go index 0c40e11ad..2e4d6aad8 100644 --- a/ipn/ipnlocal/local_test.go +++ b/ipn/ipnlocal/local_test.go @@ -10331,6 +10331,63 @@ func TestRouteAllDisabled(t *testing.T) { } } +// TestRouterConfigServiceAddrs verifies that routerConfigLocked reports the +// addresses of the Services this node hosts as ServiceAddrs, sorted, and only +// for the IP families the node has an address in. +func TestRouterConfigServiceAddrs(t *testing.T) { + pp := netip.MustParsePrefix + svcIPMapJSON, err := json.Marshal(tailcfg.ServiceIPMappings{ + "svc:a": []netip.Addr{netip.MustParseAddr("100.99.1.2"), netip.MustParseAddr("fd7a:115c:a1e0::9902")}, + "svc:b": []netip.Addr{netip.MustParseAddr("100.99.1.1"), netip.MustParseAddr("fd7a:115c:a1e0::9901")}, + }) + if err != nil { + t.Fatal(err) + } + tests := []struct { + name string + addrs []netip.Prefix + want []netip.Prefix + }{ + { + name: "dual_stack", + addrs: []netip.Prefix{pp("100.64.1.1/32"), pp("fd7a:115c:a1e0::1/128")}, + want: []netip.Prefix{ + pp("100.99.1.1/32"), pp("100.99.1.2/32"), + pp("fd7a:115c:a1e0::9901/128"), pp("fd7a:115c:a1e0::9902/128"), + }, + }, + { + name: "v4_only", + addrs: []netip.Prefix{pp("100.64.1.1/32")}, + want: []netip.Prefix{pp("100.99.1.1/32"), pp("100.99.1.2/32")}, + }, + { + name: "no_addrs", + addrs: nil, + want: nil, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + lb := newTestLocalBackend(t) + nm := &netmap.NetworkMap{ + SelfNode: (&tailcfg.Node{ + Name: "test-node", + Addresses: tt.addrs, + CapMap: tailcfg.NodeCapMap{ + nodecap.ServiceHost: []tailcfg.RawMessage{tailcfg.RawMessage(svcIPMapJSON)}, + }, + }).View(), + } + lb.currentNode().SetNetMap(nm) + rcfg := lb.routerConfigLocked(&wgcfg.Config{Addresses: tt.addrs}, new(ipn.Prefs).View(), nm) + if !slices.Equal(rcfg.ServiceAddrs, tt.want) { + t.Errorf("ServiceAddrs = %v; want %v", rcfg.ServiceAddrs, tt.want) + } + }) + } +} + // TestAdvertiseRoute_InvalidPrefix tests that AdvertiseRoute rejects routes // with non-address bits set in the prefix. func TestAdvertiseRoute_InvalidPrefix(t *testing.T) { diff --git a/wgengine/router/osrouter/router_linux.go b/wgengine/router/osrouter/router_linux.go index 0d235723d..1e8bfa7ef 100644 --- a/wgengine/router/osrouter/router_linux.go +++ b/wgengine/router/osrouter/router_linux.go @@ -493,21 +493,37 @@ func (r *linuxRouter) Set(cfg *router.Config) error { // isn't desired and that we don't already track (prevAddrs). Like cidrDiff, // this trusts cfg.LocalAddrs to be authoritative. See #19974. // + // The sweep leaves cfg.ServiceAddrs alone. An operator serving a Tailscale + // Service in TUN mode may assign its addresses to the tunnel interface. + // The sweep is also skipped while cfg.LocalAddrs is empty, such as after + // "tailscale down". That config carries no ServiceAddrs, so the sweep + // could not tell a Service address from a stale one. The next Set with + // addresses runs the sweep again. + // // TODO(bcreane): a late orphan with no config change -- IPv6 becoming // available, or an external re-add -- isn't caught here; re-run this sweep on // netmon.ChangeDelta to handle it. See tailscale/corp#43882. wantAddrs := set.SetOf(cfg.LocalAddrs) - if r.lastScanAddrs == nil || !r.lastScanAddrs.Equal(wantAddrs) { + if len(cfg.LocalAddrs) == 0 { + r.lastScanAddrs = nil + } else if r.lastScanAddrs == nil || !r.lastScanAddrs.Equal(wantAddrs) { if ifaceAddrs, err := r.tailscaleInterfaceAddrs(); err != nil { r.logf("router: enumerating interface addresses failed, skipping orphan cleanup: %v", err) } else { r.lastScanAddrs = wantAddrs kernelAddrs := r.deletableAddrs(ifaceAddrs) + serviceAddrs := make(set.Set[netip.Addr], len(cfg.ServiceAddrs)) + for _, p := range cfg.ServiceAddrs { + serviceAddrs.Add(p.Addr()) + } var removed []netip.Prefix for p := range orphanedAddrs(kernelAddrs, cfg.LocalAddrs) { if prevAddrs[p] { continue // an address we were tracking; cidrDiff already handled it } + if serviceAddrs.Contains(p.Addr()) { + continue // assigned by the operator for a Service; not ours to remove + } if err := r.delAddress(p); err != nil { r.logf("router: removing stale address %v from %s failed: %v", p, r.tunname, err) errs = append(errs, err) diff --git a/wgengine/router/osrouter/router_linux_test.go b/wgengine/router/osrouter/router_linux_test.go index efa2bd358..78efb2cbe 100644 --- a/wgengine/router/osrouter/router_linux_test.go +++ b/wgengine/router/osrouter/router_linux_test.go @@ -1782,6 +1782,89 @@ func TestSetInstallsLoopbackRuleForExistingAddr(t *testing.T) { } } +// TestSetKeepsServiceAddrs verifies that the orphan sweep does not remove +// Service addresses an operator assigned to the tunnel interface for a Service +// served in TUN mode. The sweep still removes other stale addresses. +func TestSetKeepsServiceAddrs(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + + const ( + vip4 = "100.99.1.1/32 dev tailscale0" + vip6 = "fd7a:115c:a1e0::9901/128 dev tailscale0" + orphan = "100.64.0.99/32 dev tailscale0" + ) + fake.ips = []string{vip4, vip6, orphan} + slices.Sort(fake.ips) + + up := func(localAddr string) *Config { + return &Config{ + LocalAddrs: mustCIDRs(localAddr), + ServiceAddrs: mustCIDRs("100.99.1.1/32", "fd7a:115c:a1e0::9901/128"), + NetfilterMode: netfilterOff, + } + } + checkVIPs := func(step string) { + t.Helper() + for _, vip := range []string{vip4, vip6} { + if !slices.Contains(fake.ips, vip) { + t.Errorf("%s: Service addr %q was removed; ips=%q", step, vip, fake.ips) + } + } + } + + if err := lr.Set(up("100.64.0.1/32")); err != nil { + t.Fatalf("Set up: %v", err) + } + checkVIPs("up") + if slices.Contains(fake.ips, orphan) { + t.Errorf("orphan %q was not removed; ips=%q", orphan, fake.ips) + } + + // "tailscale down" sends an empty config with no ServiceAddrs. + if err := lr.Set(&Config{NetfilterMode: netfilterOff}); err != nil { + t.Fatalf("Set down: %v", err) + } + checkVIPs("down") + + // A LocalAddrs change triggers a new sweep. + if err := lr.Set(up("100.64.0.2/32")); err != nil { + t.Fatalf("Set up with new addr: %v", err) + } + checkVIPs("up with new addr") +} + +// TestSetOrphanScanAfterDown verifies that an orphan that appears while the +// router has no addresses stays in place until the next Set with addresses, +// and is removed then even if LocalAddrs is the same as before the down. +func TestSetOrphanScanAfterDown(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + + const orphan = "100.64.0.99/32 dev tailscale0" + up := &Config{ + LocalAddrs: mustCIDRs("100.64.0.1/32"), + NetfilterMode: netfilterOff, + } + if err := lr.Set(up); err != nil { + t.Fatalf("Set up: %v", err) + } + + fake.ips = append(fake.ips, orphan) + slices.Sort(fake.ips) + if err := lr.Set(&Config{NetfilterMode: netfilterOff}); err != nil { + t.Fatalf("Set down: %v", err) + } + if !slices.Contains(fake.ips, orphan) { + t.Errorf("orphan removed while down; ips=%q", fake.ips) + } + + if err := lr.Set(up); err != nil { + t.Fatalf("Set up again: %v", err) + } + if slices.Contains(fake.ips, orphan) { + t.Errorf("orphan not removed on the Set after down; ips=%q", fake.ips) + } +} + // TestSetOrphanScanGatedByAddrChange verifies the interface is scanned for // orphans on the first Set and when LocalAddrs changes, but not for route-only // updates -- so a subnet router churning routes doesn't pay for a scan on every diff --git a/wgengine/router/router.go b/wgengine/router/router.go index a253590ca..9f4a3f160 100644 --- a/wgengine/router/router.go +++ b/wgengine/router/router.go @@ -131,6 +131,13 @@ type Config struct { // flow logging and is otherwise ignored. SubnetRoutes []netip.Prefix + // ServiceAddrs are the addresses of the Tailscale Services (VIP + // services) this node hosts. The router does not assign them to the + // tunnel interface. Only Linux uses them: an operator serving a + // Service in TUN mode may assign them to the tunnel interface, and + // the router must not remove them as stale addresses. + ServiceAddrs []netip.Prefix + // SNATSubnetRoutes enables SNAT for traffic to local subnets. // Implemented on Linux (iptables/nftables) and FreeBSD (PF). SNATSubnetRoutes bool @@ -161,5 +168,6 @@ func (c *Config) Clone() *Config { c2.Routes = slices.Clone(c.Routes) c2.LocalRoutes = slices.Clone(c.LocalRoutes) c2.SubnetRoutes = slices.Clone(c.SubnetRoutes) + c2.ServiceAddrs = slices.Clone(c.ServiceAddrs) return &c2 } diff --git a/wgengine/router/router_test.go b/wgengine/router/router_test.go index e6b415586..af0de6177 100644 --- a/wgengine/router/router_test.go +++ b/wgengine/router/router_test.go @@ -14,7 +14,7 @@ import ( func TestConfigEqual(t *testing.T) { testedFields := []string{ "LocalAddrs", "Routes", "LocalRoutes", "NewMTU", - "SubnetRoutes", "SNATSubnetRoutes", "StatefulFiltering", + "SubnetRoutes", "ServiceAddrs", "SNATSubnetRoutes", "StatefulFiltering", "NetfilterMode", "NetfilterKind", "RemoveCGNATDropRule", } configType := reflect.TypeFor[Config]() @@ -106,6 +106,16 @@ func TestConfigEqual(t *testing.T) { true, }, + { + &Config{ServiceAddrs: nets("100.99.1.1/32")}, + &Config{ServiceAddrs: nets("100.99.1.2/32")}, + false, + }, + { + &Config{ServiceAddrs: nets("100.99.1.1/32")}, + &Config{ServiceAddrs: nets("100.99.1.1/32")}, + true, + }, { &Config{SNATSubnetRoutes: false}, &Config{SNATSubnetRoutes: true},