diff --git a/util/linuxfw/iptables_runner.go b/util/linuxfw/iptables_runner.go index ad983fb75..7dd1b7731 100644 --- a/util/linuxfw/iptables_runner.go +++ b/util/linuxfw/iptables_runner.go @@ -535,8 +535,9 @@ func (i *iptablesRunner) DelStatefulRule(tunname string) error { // AddConnmarkSaveRule adds conntrack marking rules to save and restore marks. // These rules run in mangle/PREROUTING (to restore marks from conntrack) and -// mangle/OUTPUT (to save marks to conntrack) before rp_filter checks, enabling -// proper routing table lookups for exit nodes and subnet routers. +// mangle/OUTPUT (to save marks to conntrack), so routing decisions for reply +// packets use the right table. Reverse path checks only see the restored mark +// if they're mark-aware (see NetfilterRunner.AddConnmarkSaveRule). func (i *iptablesRunner) AddConnmarkSaveRule() error { // Check if rules already exist (idempotency) for _, ipt := range i.getTables() { @@ -556,7 +557,8 @@ func (i *iptablesRunner) AddConnmarkSaveRule() error { } // mangle/PREROUTING: Restore mark from conntrack for ESTABLISHED/RELATED connections - // This runs BEFORE routing decision and rp_filter check + // This runs before the routing decision and the kernel's rp_filter check, + // though rp_filter only uses the mark with src_valid_mark=1. // The connmark check ensures we only restore when Tailscale has marked the connection, // preventing us from wiping mark bits set by other systems when ct mark is zero. for _, ipt := range i.getTables() { diff --git a/util/linuxfw/nftables_runner.go b/util/linuxfw/nftables_runner.go index bf6097d5c..9f1a2c47a 100644 --- a/util/linuxfw/nftables_runner.go +++ b/util/linuxfw/nftables_runner.go @@ -549,8 +549,10 @@ type NetfilterRunner interface { // AddConnmarkSaveRule adds conntrack marking rules to save marks from packets. // These rules run in mangle/PREROUTING and mangle/OUTPUT to mark connections - // and restore marks on reply packets before rp_filter checks, enabling proper - // routing table lookups for exit nodes and subnet routers. + // and restore marks on reply packets, so the routing decision for replies + // uses the right table. Reverse path checks only see the restored mark if + // they're mark-aware: netfilter checks that include the mark, or the + // kernel's rp_filter with net.ipv4.conf.*.src_valid_mark=1. AddConnmarkSaveRule() error // DelConnmarkSaveRule removes conntrack marking rules added by AddConnmarkSaveRule. @@ -2260,8 +2262,9 @@ func makeConnmarkSaveExprs() []expr.Any { // AddConnmarkSaveRule adds conntrack marking rules to save and restore marks. // These rules run in mangle/PREROUTING (to restore marks from conntrack) and -// mangle/OUTPUT (to save marks to conntrack) before rp_filter checks, enabling -// proper routing table lookups for exit nodes and subnet routers. +// mangle/OUTPUT (to save marks to conntrack), so routing decisions for reply +// packets use the right table. Reverse path checks only see the restored mark +// if they're mark-aware (see NetfilterRunner.AddConnmarkSaveRule). func (n *nftablesRunner) AddConnmarkSaveRule() error { conn := n.conn diff --git a/wgengine/router/osrouter/iprule_linux.go b/wgengine/router/osrouter/iprule_linux.go new file mode 100644 index 000000000..20e12afe3 --- /dev/null +++ b/wgengine/router/osrouter/iprule_linux.go @@ -0,0 +1,260 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !android + +package osrouter + +import ( + "encoding/binary" + "errors" + "fmt" + "net/netip" + + "github.com/mdlayher/netlink" + "golang.org/x/sys/unix" +) + +// This file is a minimal rtnetlink client for policy routing rules, used for +// the rp_filter underlay rules. It exists because those rules need selectors +// that github.com/tailscale/netlink doesn't support (uidrange, and the rule +// protocol, which marks the rules as ours) and the uidrange encoding in +// github.com/jsimonetti/rtnetlink is wrong (16-bit fields where the kernel's +// struct fib_rule_uid_range has 32-bit ones). + +// ruleProtocolTailscale is the rule protocol (FRA_PROTOCOL, like a route's +// RTPROT_*) we set on rules from this file so we can recognize them later +// regardless of their shape. 52 matches the Tailscale routing table and is +// unassigned in iproute2's rt_protos. Kernels before 4.17 ignore it. +const ruleProtocolTailscale = 52 + +// ipRule is a policy routing rule, limited to the fields we set. Decoding +// also records whether the kernel reported a protocol and whether the rule +// has any selector or action ipRule doesn't model. +type ipRule struct { + family addrFamily + priority uint32 + table uint32 + src netip.Addr // if valid, matches exactly this source address + invert bool // "not": invert the selectors + fwmark, fwmask uint32 // used when fwmask != 0 + suppressPrefixlen int32 // -1 for none + uidRange *[2]uint32 // inclusive [start, end]; nil for none + ipProto uint8 // IP protocol selector (unix.IPPROTO_*); 0 for none + sportRange *[2]uint16 // inclusive source port range; nil for none + protocol uint8 + + // Set by decoding only. + hasProtocol bool // the kernel reported FRA_PROTOCOL (kernel 4.17+) + other bool // has selectors or an action ipRule doesn't model +} + +func (f addrFamily) afInet() uint8 { + if f == v6 { + return unix.AF_INET6 + } + return unix.AF_INET +} + +// fibRuleHdrLen is sizeof(struct fib_rule_hdr). +const fibRuleHdrLen = 12 + +func (ru ipRule) marshal() ([]byte, error) { + hdr := make([]byte, fibRuleHdrLen) + hdr[0] = ru.family.afInet() + if ru.src.IsValid() { + hdr[2] = uint8(ru.src.BitLen()) // src_len + } + if ru.table < 256 { + hdr[4] = uint8(ru.table) + } else { + hdr[4] = unix.RT_TABLE_COMPAT + } + hdr[7] = unix.FR_ACT_TO_TBL + var flags uint32 + if ru.invert { + flags |= unix.FIB_RULE_INVERT + } + binary.NativeEndian.PutUint32(hdr[8:], flags) + + ae := netlink.NewAttributeEncoder() + ae.Uint32(unix.FRA_PRIORITY, ru.priority) + ae.Uint32(unix.FRA_TABLE, ru.table) + if ru.src.IsValid() { + ae.Bytes(unix.FRA_SRC, ru.src.AsSlice()) + } + if ru.fwmask != 0 { + ae.Uint32(unix.FRA_FWMARK, ru.fwmark) + ae.Uint32(unix.FRA_FWMASK, ru.fwmask) + } + if ru.suppressPrefixlen >= 0 { + ae.Uint32(unix.FRA_SUPPRESS_PREFIXLEN, uint32(ru.suppressPrefixlen)) + } + if ru.uidRange != nil { + b := make([]byte, 8) + binary.NativeEndian.PutUint32(b[0:], ru.uidRange[0]) + binary.NativeEndian.PutUint32(b[4:], ru.uidRange[1]) + ae.Bytes(unix.FRA_UID_RANGE, b) + } + if ru.ipProto != 0 { + ae.Uint8(unix.FRA_IP_PROTO, ru.ipProto) + } + if ru.sportRange != nil { + b := make([]byte, 4) // struct fib_rule_port_range + binary.NativeEndian.PutUint16(b[0:], ru.sportRange[0]) + binary.NativeEndian.PutUint16(b[2:], ru.sportRange[1]) + ae.Bytes(unix.FRA_SPORT_RANGE, b) + } + if ru.protocol != 0 { + ae.Uint8(unix.FRA_PROTOCOL, ru.protocol) + } + attrs, err := ae.Encode() + if err != nil { + return nil, err + } + return append(hdr, attrs...), nil +} + +func unmarshalIPRule(b []byte) (ipRule, error) { + ru := ipRule{suppressPrefixlen: -1} + if len(b) < fibRuleHdrLen { + return ru, fmt.Errorf("short fib_rule_hdr: %d bytes", len(b)) + } + switch b[0] { + case unix.AF_INET: + ru.family = v4 + case unix.AF_INET6: + ru.family = v6 + default: + return ru, fmt.Errorf("unexpected rule family %d", b[0]) + } + dstLen, srcLen, tos, table, action := b[1], b[2], b[3], b[4], b[7] + flags := binary.NativeEndian.Uint32(b[8:]) + ru.table = uint32(table) + ru.invert = flags&unix.FIB_RULE_INVERT != 0 + if dstLen != 0 || tos != 0 || action != unix.FR_ACT_TO_TBL { + ru.other = true + } + + ad, err := netlink.NewAttributeDecoder(b[fibRuleHdrLen:]) + if err != nil { + return ru, err + } + for ad.Next() { + switch ad.Type() { + case unix.FRA_PRIORITY: + ru.priority = ad.Uint32() + case unix.FRA_TABLE: + ru.table = ad.Uint32() + case unix.FRA_SRC: + a, ok := netip.AddrFromSlice(ad.Bytes()) + if !ok || int(srcLen) != a.BitLen() { + ru.other = true // a prefix, not a single address + continue + } + ru.src = a + case unix.FRA_FWMARK: + ru.fwmark = ad.Uint32() + case unix.FRA_FWMASK: + ru.fwmask = ad.Uint32() + case unix.FRA_SUPPRESS_PREFIXLEN: + if v := ad.Uint32(); v != 0xffffffff { + ru.suppressPrefixlen = int32(v) + } + case unix.FRA_SUPPRESS_IFGROUP: + if ad.Uint32() != 0xffffffff { + ru.other = true + } + case unix.FRA_UID_RANGE: + v := ad.Bytes() + if len(v) != 8 { + ru.other = true + continue + } + ru.uidRange = &[2]uint32{binary.NativeEndian.Uint32(v[0:]), binary.NativeEndian.Uint32(v[4:])} + case unix.FRA_IP_PROTO: + ru.ipProto = ad.Uint8() + case unix.FRA_SPORT_RANGE: + v := ad.Bytes() + if len(v) != 4 { + ru.other = true + continue + } + ru.sportRange = &[2]uint16{binary.NativeEndian.Uint16(v[0:]), binary.NativeEndian.Uint16(v[2:])} + case unix.FRA_PROTOCOL: + ru.protocol = ad.Uint8() + ru.hasProtocol = true + default: + // iif/oif names, dst, goto, realms, tunnel id, l3mdev, + // destination ports, dscp, and anything newer. + ru.other = true + } + } + if err := ad.Err(); err != nil { + return ru, err + } + // A fwmark selector without a mask is a full-mask match; normalize so + // callers can compare fwmask. + if ru.fwmark != 0 && ru.fwmask == 0 { + ru.fwmask = 0xffffffff + } + return ru, nil +} + +func ipRuleExec(typ netlink.HeaderType, flags netlink.HeaderFlags, data []byte) ([]netlink.Message, error) { + c, err := netlink.Dial(unix.NETLINK_ROUTE, nil) + if err != nil { + return nil, err + } + defer c.Close() + return c.Execute(netlink.Message{ + Header: netlink.Header{Type: typ, Flags: netlink.Request | flags}, + Data: data, + }) +} + +// addIPRule adds ru. It fails with EEXIST if an identical rule exists. +func addIPRule(ru ipRule) error { + b, err := ru.marshal() + if err != nil { + return err + } + _, err = ipRuleExec(unix.RTM_NEWRULE, netlink.Acknowledge|netlink.Create|netlink.Excl, b) + return err +} + +// delIPRule deletes the first rule matching every field set in ru. It fails +// with ENOENT if there is none. +func delIPRule(ru ipRule) error { + b, err := ru.marshal() + if err != nil { + return err + } + _, err = ipRuleExec(unix.RTM_DELRULE, netlink.Acknowledge, b) + return err +} + +// listIPRules returns all rules of the given family. Rules that fail to +// decode are skipped. +func listIPRules(f addrFamily) ([]ipRule, error) { + hdr := make([]byte, fibRuleHdrLen) + hdr[0] = f.afInet() + msgs, err := ipRuleExec(unix.RTM_GETRULE, netlink.Dump, hdr) + if err != nil { + return nil, err + } + var out []ipRule + var errs []error + for _, m := range msgs { + ru, err := unmarshalIPRule(m.Data) + if err != nil { + errs = append(errs, err) + continue + } + out = append(out, ru) + } + if len(out) == 0 && len(errs) > 0 { + return nil, errors.Join(errs...) + } + return out, nil +} diff --git a/wgengine/router/osrouter/router_linux.go b/wgengine/router/osrouter/router_linux.go index 6031a35b1..a2b38da4a 100644 --- a/wgengine/router/osrouter/router_linux.go +++ b/wgengine/router/osrouter/router_linux.go @@ -105,6 +105,38 @@ type linuxRouter struct { magicsockPortV4 uint16 magicsockPortV6 uint16 + // underlaySrcRules is the set of local underlay addresses for which we + // have installed a "from lookup main" ip rule so that strict + // reverse path filtering keeps working while using an exit node. See + // rpfilter_linux.go. + underlaySrcRules set.Set[underlayRule] + + // exitRouteV4 and exitRouteV6 are whether the current config routes + // 0.0.0.0/0 and ::/0 into table 52, i.e. whether we use an exit node. + // Set from the config at the start of Set, before routes change, so + // the underlay rules can be installed ahead of the default route. + exitRouteV4, exitRouteV6 bool + + // underlaySrcRulesCapped is whether the last reconcile hit + // maxUnderlaySrcRulesPerFamily; used to log only on transitions. + underlaySrcRulesCapped bool + + // underlayAddrs returns the host's candidate underlay source addresses. + // It defaults to reading the netmon interface state; tests override it + // before subscribeEvents, or later with mu held. Read with mu held. + underlayAddrs func() []netip.Addr + + // lastUnderlayErr is the last underlay rule error logged, so a + // persistent failure isn't logged on every network change. + lastUnderlayErr string + + // rpFilterStrictV4Seen is the IPv4 rp_filter mode the underlay rules + // were last computed with, which recheckRPFilter compares against. + rpFilterStrictV4Seen bool + + // rpFilterRecheckPending is whether a recheckRPFilter is scheduled. + rpFilterRecheckPending atomic.Bool + // ipRulesV6 is whether the base ip rules were last installed for IPv6 // too. Read without mu by onIPRuleDeleted. ipRulesV6 atomic.Bool @@ -133,8 +165,13 @@ type routerFixed struct { // default, interfaceV6UsableForTun. See #20447. interfaceV6Usable func() bool + // rpFilterStrictV4 reports whether the kernel's IPv4 rp_filter is in + // strict mode somewhere, gating the IPv4 underlay rules. Nil means the + // production default, which reads the sysctls. + rpFilterStrictV4 func() bool + // afterFunc, if non-nil, replaces time.AfterFunc for the router's rule - // restore timers. For tests. + // restore and rp_filter recheck timers. For tests. afterFunc func(time.Duration, func()) // ipRuleAvailable is whether the kernel was built with @@ -203,6 +240,10 @@ func newLinuxRouter(fixed routerFixed) *linuxRouter { if r.interfaceV6Usable == nil { r.interfaceV6Usable = func() bool { return interfaceV6UsableForTun(r.tunname) } } + if r.rpFilterStrictV4 == nil { + r.rpFilterStrictV4 = r.rpFilterStrictV4FromSysctl + } + r.underlayAddrs = r.underlayAddrsFromNetMon if r.useIPCommand() { r.ipRuleAvailable = (r.cmd.run("ip", "rule") == nil) } else { @@ -268,6 +309,9 @@ func (r *linuxRouter) subscribeEvents(bus *eventbus.Bus) { r.logf("updateMagicsockPort(port=%v, network=%s) failed: %v", pu.UDPPort, pu.EndpointNetwork, err) } }) + eventbus.SubscribeFunc(ec, func(netmon.ChangeDelta) { + r.onNetworkChange() + }) } // after runs f after d on the router's timer hook (routerFixed.afterFunc), @@ -446,6 +490,12 @@ func (r *linuxRouter) onIPRuleDeleted(family uint8, table uint8, priority uint32 if family == unix.AF_INET6 && !r.ipRulesV6.Load() { return } + if r.isUnderlayRulePriority(int(priority)) { + // rp_filter underlay rules are added and removed by us as + // addresses come and go, so don't run the full restore, which + // would feed back into ourselves. + return + } if r.ruleRestorePending.Swap(true) { // Another timer is already pending. return @@ -475,6 +525,9 @@ func (r *linuxRouter) Up() error { if err := r.addIPRules(); err != nil { return fmt.Errorf("adding IP rules: %w", err) } + // Remove rp_filter underlay source rules left by a previous instance + // that didn't shut down cleanly. Set installs fresh ones as needed. + r.sweepStaleUnderlaySrcRulesLocked() if err := r.upInterface(); err != nil { return fmt.Errorf("bringing interface up: %w", err) } @@ -496,6 +549,15 @@ func (r *linuxRouter) Close() error { r.logf("warning: failed to delete connmark rules: %v", err) } + // Remove the rp_filter underlay rules last, once the interface (and + // with it the exit node default route) and the base rules are gone, + // even if one of those steps fails. + defer func() { + if err := r.removeUnderlaySrcRulesLocked(); err != nil { + r.logf("warning: %v", err) + } + }() + if err := r.downInterface(); err != nil { return err } @@ -561,6 +623,16 @@ func (r *linuxRouter) Set(cfg *router.Config) error { errs = append(errs, err) } + // Install the rp_filter underlay rules (add only) before the exit node + // default route below, so replies to tailscaled's sockets are never + // dropped in between. Removals wait for the full reconcile after the + // routes have changed. This is best effort: a failure shouldn't fail + // Set or mark the router unhealthy. The full reconcile below retries, + // and logs. + r.exitRouteV4 = slices.Contains(cfg.Routes, tsaddr.AllIPv4()) || r.routes[tsaddr.AllIPv4()] + r.exitRouteV6 = slices.Contains(cfg.Routes, tsaddr.AllIPv6()) || r.routes[tsaddr.AllIPv6()] + r.updateUnderlaySrcRulesLocked(true) + newLocalRoutes, err := cidrDiff("localRoute", r.localRoutes, cfg.LocalRoutes, r.addThrowRoute, r.delThrowRoute, r.logf) if err != nil { errs = append(errs, err) @@ -615,6 +687,16 @@ func (r *linuxRouter) Set(cfg *router.Config) error { } } + // Keep strict rp_filter working for replies to tailscaled's own + // sockets while table 52 holds an exit-node default route. Runs after + // r.routes and r.addrs are updated, as it depends on both. + // Follow the default routes actually installed, not the desired + // config: if deleting one failed, it's still there and so must the + // rules be. + r.exitRouteV4 = r.routes[tsaddr.AllIPv4()] + r.exitRouteV6 = r.routes[tsaddr.AllIPv6()] + r.logUnderlayErrLocked(r.updateUnderlaySrcRulesLocked(false)) + // Ensure that the SNAT rule is added or removed as needed. switch { case cfg.SNATSubnetRoutes == r.snatSubnetRoutes: @@ -647,8 +729,11 @@ func (r *linuxRouter) Set(cfg *router.Config) error { r.updateStatefulFilteringWithDockerWarning(cfg) // Connmark rules for rp_filter compatibility. - // Always enabled when netfilter is ON to handle all rp_filter=1 scenarios - // (normal operation, exit nodes, subnet routers, and clients using exit nodes). + // Restoring the bypass mark on replies lets mark-aware reverse path + // checks (e.g. an nftables "fib saddr . mark . iif oif" rule) pass. The + // kernel's own rp_filter only consults the mark when + // src_valid_mark=1, which we deliberately don't set (see #19796); for + // that case, see the underlay source rules in rpfilter_linux.go. // Gate on r.netfilterMode (actual state) rather than cfg.NetfilterMode // (desired state) so we don't call into the runner when chain setup failed. netfilterOn := r.netfilterMode == netfilterOn @@ -2051,6 +2136,7 @@ func cleanUp(logf logger.Logf, interfaceName string) { linuxfw.NfTablesCleanUp(logf) } removeOrphanedAddrsForCleanup(logf, osCommandRunner{ambientCapNetAdmin: useAmbientCaps()}, interfaceName) + removeUnderlaySrcRulesForCleanup(logger.WithPrefix(logf, "router: ")) } // removeOrphanedAddrsForCleanup removes every Tailscale-range address from diff --git a/wgengine/router/osrouter/router_linux_test.go b/wgengine/router/osrouter/router_linux_test.go index 2be6951b6..11d16dfcb 100644 --- a/wgengine/router/osrouter/router_linux_test.go +++ b/wgengine/router/osrouter/router_linux_test.go @@ -49,6 +49,39 @@ ip rule add -6 pref 5210 fwmark 0x80000/0xff0000 table main ip rule add -6 pref 5230 fwmark 0x80000/0xff0000 table default ip rule add -6 pref 5250 fwmark 0x80000/0xff0000 type unreachable ip rule add -6 pref 5270 table 52 +` + // basicExitV4 is basic plus the rp_filter underlay source rules for the + // IPv4 addresses returned by testUnderlayAddrs, installed while an IPv4 + // exit route is present. + basicExitV4 := ` +ip rule add -4 pref 5210 fwmark 0x80000/0xff0000 table main +ip rule add -4 pref 5230 fwmark 0x80000/0xff0000 table default +ip rule add -4 pref 5250 fwmark 0x80000/0xff0000 type unreachable +ip rule add -4 pref 5255 not fwmark 0x80000/0xff0000 table 52 suppress_prefixlength 0 protocol 52 +ip rule add -4 pref 5260 from 10.1.2.3 uidrange 0-0 table main protocol 52 +ip rule add -4 pref 5260 from 192.168.1.5 uidrange 0-0 table main protocol 52 +ip rule add -4 pref 5270 table 52 +ip rule add -6 pref 5210 fwmark 0x80000/0xff0000 table main +ip rule add -6 pref 5230 fwmark 0x80000/0xff0000 table default +ip rule add -6 pref 5250 fwmark 0x80000/0xff0000 type unreachable +ip rule add -6 pref 5270 table 52 +` + // basicExitDual is basicExitV4 plus the IPv6 underlay source rules. + basicExitDual := ` +ip rule add -4 pref 5210 fwmark 0x80000/0xff0000 table main +ip rule add -4 pref 5230 fwmark 0x80000/0xff0000 table default +ip rule add -4 pref 5250 fwmark 0x80000/0xff0000 type unreachable +ip rule add -4 pref 5255 not fwmark 0x80000/0xff0000 table 52 suppress_prefixlength 0 protocol 52 +ip rule add -4 pref 5260 from 10.1.2.3 uidrange 0-0 table main protocol 52 +ip rule add -4 pref 5260 from 192.168.1.5 uidrange 0-0 table main protocol 52 +ip rule add -4 pref 5270 table 52 +ip rule add -6 pref 5210 fwmark 0x80000/0xff0000 table main +ip rule add -6 pref 5230 fwmark 0x80000/0xff0000 table default +ip rule add -6 pref 5250 fwmark 0x80000/0xff0000 type unreachable +ip rule add -6 pref 5255 not fwmark 0x80000/0xff0000 table 52 suppress_prefixlength 0 protocol 52 +ip rule add -6 pref 5260 from 2001:db8::5 uidrange 0-0 table main protocol 52 +ip rule add -6 pref 5260 from fe80::5 uidrange 0-0 table main protocol 52 +ip rule add -6 pref 5270 table 52 ` states := []struct { name string @@ -358,7 +391,7 @@ up ip addr add 100.101.102.104/10 dev tailscale0 ip route add 0.0.0.0/0 dev tailscale0 table 52 ip route add 100.100.100.100/32 dev tailscale0 table 52 -ip route add throw 10.0.0.0/8 table 52` + basic + +ip route add throw 10.0.0.0/8 table 52` + basicExitV4 + `v4/filter/FORWARD -j ts-forward v4/filter/INPUT -j ts-input v4/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000 @@ -395,7 +428,45 @@ ip addr add 100.101.102.104/10 dev tailscale0 ip route add 0.0.0.0/0 dev tailscale0 table 52 ip route add 100.100.100.100/32 dev tailscale0 table 52 ip route add throw 10.0.0.0/8 table 52 -ip route add throw 192.168.0.0/24 table 52` + basic, +ip route add throw 192.168.0.0/24 table 52` + basicExitV4, + }, + { + name: "exit-node-dual-stack-no-netfilter", + in: &Config{ + LocalAddrs: mustCIDRs("100.101.102.104/10", "fd7a:115c:a1e0::104/128"), + Routes: mustCIDRs("100.100.100.100/32", "0.0.0.0/0", "::/0"), + NetfilterMode: netfilterOff, + }, + want: ` +up +ip addr add 100.101.102.104/10 dev tailscale0 +ip addr add fd7a:115c:a1e0::104/128 dev tailscale0 +ip route add 0.0.0.0/0 dev tailscale0 table 52 +ip route add 100.100.100.100/32 dev tailscale0 table 52 +ip route add ::/0 dev tailscale0 table 52` + basicExitDual, + }, + { + name: "exit-node-v6-only-route", + in: &Config{ + LocalAddrs: mustCIDRs("100.101.102.104/10"), + Routes: mustCIDRs("::/0"), + NetfilterMode: netfilterOff, + }, + want: ` +up +ip addr add 100.101.102.104/10 dev tailscale0 +ip route add ::/0 dev tailscale0 table 52 +ip rule add -4 pref 5210 fwmark 0x80000/0xff0000 table main +ip rule add -4 pref 5230 fwmark 0x80000/0xff0000 table default +ip rule add -4 pref 5250 fwmark 0x80000/0xff0000 type unreachable +ip rule add -4 pref 5270 table 52 +ip rule add -6 pref 5210 fwmark 0x80000/0xff0000 table main +ip rule add -6 pref 5230 fwmark 0x80000/0xff0000 table default +ip rule add -6 pref 5250 fwmark 0x80000/0xff0000 type unreachable +ip rule add -6 pref 5255 not fwmark 0x80000/0xff0000 table 52 suppress_prefixlength 0 protocol 52 +ip rule add -6 pref 5260 from 2001:db8::5 uidrange 0-0 table main protocol 52 +ip rule add -6 pref 5260 from fe80::5 uidrange 0-0 table main protocol 52 +ip rule add -6 pref 5270 table 52`, }, { name: "subnet-routes-connmark-for-rp_filter", @@ -530,6 +601,8 @@ v6/nat/ts-postrouting -m mark --mark 0x40000/0xff0000 -j MASQUERADE // fake netfilter runner's HasIPV6 (noV6) is the authoritative v6 signal // here. See #20447. r.interfaceV6Usable = func() bool { return true } + r.underlayAddrs = func() []netip.Addr { return slices.Clone(testUnderlayAddrs) } + r.rpFilterStrictV4 = func() bool { return true } }) if err := router.Up(); err != nil { t.Fatalf("failed to up router: %v", err) @@ -1023,6 +1096,11 @@ type fakeOS struct { ips []string routes []string rules []string + // cmds logs every command run, in order. + cmds []string + // failRun, if non-nil, is consulted first by run; a non-nil error is + // returned as the command's result, without running it. + failRun func(args []string) error // This test tests on the router level, so we will not bother // with using iptables or nftables, chose the simpler one. nfr linuxfw.NetfilterRunner @@ -1083,6 +1161,12 @@ func (o *fakeOS) String() string { } func (o *fakeOS) run(args ...string) error { + o.cmds = append(o.cmds, strings.Join(args, " ")) + if o.failRun != nil { + if err := o.failRun(args); err != nil { + return err + } + } unexpected := func() error { o.t.Errorf("unexpected invocation %q", strings.Join(args, " ")) return errors.New("unrecognized invocation") @@ -1202,6 +1286,16 @@ func (o *fakeOS) output(args ...string) ([]byte, error) { return []byte(strings.Join(ret, "\n")), nil } + // "ip -4 route show table 52", as hasRoute runs it. + for _, fam := range []string{"ip -4 route show ", "ip -6 route show "} { + if def, ok := strings.CutPrefix(got, fam); ok { + if slices.Contains(o.routes, def) { + return []byte(def), nil + } + return nil, nil + } + } + want := "ip rule list priority 10000" if got != want { o.t.Errorf("unexpected command that wants output: %v", got) @@ -1698,6 +1792,12 @@ func newTestLinuxRouter(t *testing.T, configure ...func(*linuxRouter)) (*linuxRo // signal; don't consult the live /proc for the tun's IPv6 state. // See #20447. r.interfaceV6Usable = func() bool { return true } + // Don't let the host's real interface addresses leak into + // rp_filter underlay source rules; tests opt in with + // setTestUnderlayAddrs. + r.underlayAddrs = func() []netip.Addr { return nil } + // Don't depend on the host's rp_filter sysctls either. + r.rpFilterStrictV4 = func() bool { return true } } lr := newTestRouter(logger.Discard, "tailscale0", mon, fake, ht, bus, append([]func(*linuxRouter){defaults}, configure...)...) if err := lr.Up(); err != nil { @@ -2168,15 +2268,17 @@ func TestOnIPRuleDeletedFamily(t *testing.T) { // holding mu. // // A publisher floods the bus with events whose callbacks read those fields -// (RuleDeleted reads ipPolicyPrefBase without mu). If a future change -// subscribes earlier, or writes such a field after subscribing, the race -// detector reports it. It can only do so under -race; without it this is a -// smoke test. +// (RuleDeleted at our priority reads ipPolicyPrefBase and ipRuleAvailable +// without mu; ChangeDelta reads ipRuleAvailable under mu, which the +// constructor never takes). If a future change subscribes earlier, or +// writes such a field after subscribing, the race detector reports it. It +// can only do so under -race; without it this is a smoke test. func TestSubscribeEventsAfterInit(t *testing.T) { bus := eventbus.New() defer bus.Close() pubc := bus.Client("test-publisher") ruleDeleted := eventbus.Publish[netmon.RuleDeleted](pubc) + netChange := eventbus.Publish[netmon.ChangeDelta](pubc) stop := make(chan struct{}) var wg sync.WaitGroup @@ -2187,13 +2289,14 @@ func TestSubscribeEventsAfterInit(t *testing.T) { return default: } - // Just below our priority range, onIPRuleDeleted reads - // ipPolicyPrefBase and returns, without scheduling a - // restore that would run ip commands on the fake OS. + // At the underlay source rule priority, onIPRuleDeleted + // returns early (those deletions are our own), without + // running ip commands on the fake OS. ruleDeleted.Publish(netmon.RuleDeleted{ Table: uint8(mainRouteTable.Num), - Priority: uint32(defaultIPPolicyPrefBase - 1), + Priority: uint32(defaultIPPolicyPrefBase + underlaySrcRuleOffset), }) + netChange.Publish(netmon.ChangeDelta{}) } }) defer func() { diff --git a/wgengine/router/osrouter/rpfilter_linux.go b/wgengine/router/osrouter/rpfilter_linux.go new file mode 100644 index 000000000..d50820577 --- /dev/null +++ b/wgengine/router/osrouter/rpfilter_linux.go @@ -0,0 +1,821 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !android + +package osrouter + +import ( + "cmp" + "errors" + "fmt" + "net/netip" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "time" + + "golang.org/x/sys/unix" + "tailscale.com/envknob" + "tailscale.com/net/netmon" + "tailscale.com/tsconst" + "tailscale.com/util/clientmetric" + "tailscale.com/util/set" +) + +// Underlay rules keep strict reverse-path filtering (rp_filter=1, or a +// netfilter "fib saddr . iif oif" check) working while this node routes +// through an exit node, without touching net.ipv4.conf.*.src_valid_mark. +// +// The problem: with an exit node, table 52 holds a default route via the +// Tailscale interface, and the catch-all rule at ipPolicyPrefBase+70 sends +// every unmarked lookup there. When a reply to one of tailscaled's own +// (bypass-marked) sockets arrives on a physical interface, the kernel +// validates its source with a reverse lookup that has fwmark 0 (unless +// src_valid_mark=1), iif=lo, uid 0, daddr= and +// saddr=. That lookup falls into table 52, resolves to +// the Tailscale interface, mismatches the ingress interface, and the packet +// is dropped as a martian. See tailscale/tailscale#3310. +// +// Setting src_valid_mark=1 fixes that, but it is a host-global behavior +// change that breaks other fwmark users (TPROXY, Cilium L7, split-tunnel +// VPNs, multi-WAN PBR); see tailscale/tailscale#19796. +// +// Instead, per address family, we install +// +// : not fwmark lookup 52 suppress_prefixlength 0 +// : from A uidrange 0-0 lookup main +// +// with a base+60 rule for each underlay address A. +// +// The base+60 rule sends the reverse lookup (which carries saddr=A and uid +// 0) to the main table, where it finds the physical interface and passes. +// +// The base+55 rule runs first and consults table 52 without its default +// route. It keeps everything table 52 routes more specifically than the +// default on the Tailscale interface even for lookups from A: tailnet peers +// and subnet routes (so a peer can still reach the host's LAN address, and +// replies go back through the tunnel), and, with ExitNodeAllowLANAccess +// off, the LAN prefixes that table 52 claims so LAN traffic doesn't leak. +// Throw routes in table 52 (local routes) end the lookup there and fall +// through to the next rule, as before. It excludes bypass-marked packets, +// which must never use table 52. +// +// The base+55 rule also keeps the LAN block: a reply from a LAN host to one +// of tailscaled's own sockets fails reverse-path validation just like any +// other LAN packet, so with ExitNodeAllowLANAccess off and strict rp_filter +// those replies are still dropped, as they were before src_valid_mark. That +// includes magicsock's, so direct paths to peers on the LAN fall back to +// DERP. +// +// Mark-aware netfilter reverse-path checks (e.g. nftables "fib saddr . mark +// . iif oif") are covered by the connmark rules instead, when netfilter is +// on. +// +// The uidrange 0-0 selector limits the base+60 rule to lookups made as uid +// 0. The kernel's reverse-path lookups always are, so the fix works, but +// sockets of non-root processes bound to an underlay address (curl +// --interface, a torrent client) still use the exit node, as before. +// Sockets of root processes bound to an underlay address, and packets the +// kernel itself sends from it (ICMP errors, TCP resets, replies on inbound +// connections from root-owned sockets) use the physical interface. +// +// Unmarked lookups without an underlay source (normal outbound traffic, +// which gets the Tailscale source address) and forwarded traffic (foreign +// source addresses) match neither rule and are unaffected. +// +// The rules are an ip rule mechanism only, so they work in every netfilter +// mode, including "off" and "nodivert". They carry rule protocol +// ruleProtocolTailscale so we only ever remove our own rules. +// +// The rules are only installed for an address family while that family's +// default route (0.0.0.0/0 or ::/0) is in table 52, i.e. while using an exit +// node; that is the only configuration in which the catch-all hijacks +// reverse-path lookups for arbitrary Internet peers. The IPv4 rules are +// also only installed while the kernel's IPv4 rp_filter is strict on some +// interface (re-checked on every network change and Set); see +// rpFilterStrictV4FromSysctl. +// +// Limitations: the rules only exist while 0.0.0.0/0 or ::/0 is routed. Other +// table 52 routes that cover a peer, DERP or control address (an exit node +// split into 0.0.0.0/1 and 128.0.0.0/1, or an accepted subnet route such as +// 10.0.0.0/8) cause the same drop and aren't handled. Installing the rules +// for them wouldn't help either: the base+55 rule keeps those routes ahead +// of the base+60 rule, as it must for traffic that should use the tunnel. +// The reverse lookup for a reply to tailscaled from such an address is the +// same as for anything else from there. Telling them apart needs the +// packet's mark (src_valid_mark), or exceptions for the exact addresses +// tailscaled talks to. +// +// The rules send the reverse lookup to the main table. On +// multi-WAN / policy routing hosts whose underlay default route lives in +// another table (selected by fwmark or source rules), main may have no +// route to the peer, the lookup falls through to table 52 and the drop +// remains. Such setups (e.g. OpenWrt mwan3) usually have their own +// lower-priority "from lookup " rules that match first. +// Kernels before 4.10 ignore uidrange, so there the base+60 rule applies to +// all processes. Kernels before 4.17 don't store the rule protocol; there we +// recognize our rules by their exact shape instead. + +const ( + // underlaySuppressRuleOffset and underlaySrcRuleOffset are the + // priorities of the underlay rules relative to ipPolicyPrefBase. Both + // must be below the table 52 catch-all (offset 70), the suppress rule + // below the source rules, and both inside the ipPolicyPrefBase..+99 + // range that onIPRuleDeleted watches. + underlaySuppressRuleOffset = 55 + underlaySrcRuleOffset = 60 +) + +// kernelVersion returns the running kernel's major and minor version, or +// 0, 0 if unknown. +var kernelVersion = sync.OnceValues(func() (major, minor int) { + var u unix.Utsname + if err := unix.Uname(&u); err != nil { + return 0, 0 + } + rel := unix.ByteSliceToString(u.Release[:]) + maj, rest, _ := strings.Cut(rel, ".") + mnr, _, _ := strings.Cut(rest, ".") + major, _ = strconv.Atoi(maj) + minor, _ = strconv.Atoi(strings.TrimRightFunc(mnr, func(r rune) bool { return r < '0' || r > '9' })) + return major, minor +}) + +func kernelAtLeast(major, minor int) bool { + ma, mi := kernelVersion() + return ma > major || (ma == major && mi >= minor) +} + +// maxUnderlaySrcRulesPerFamily bounds how many underlay source rules we +// install per address family. Every rule is walked linearly on each policy +// routing lookup that reaches it, so hosts with very many local addresses +// (e.g. kube-proxy IPVS nodes) would otherwise pay a per-packet cost. +const maxUnderlaySrcRulesPerFamily = 128 + +// disableUnderlaySrcRules is a kill switch for the underlay rules, should +// they conflict with some host's policy routing setup. +var disableUnderlaySrcRules = envknob.RegisterBool("TS_DEBUG_DISABLE_RPFILTER_SRC_RULES") + +var ( + metricUnderlaySrcRules = clientmetric.NewGauge("router_linux_rpfilter_src_rules") + metricUnderlaySrcRulesCapped = clientmetric.NewGauge("router_linux_rpfilter_src_rules_capped") +) + +// underlayRule identifies one rule we manage: the source rule for src or, +// when src isn't set, the family's table 52 suppress rule. +type underlayRule struct { + fam addrFamily + src netip.Addr +} + +func (u underlayRule) isSuppress() bool { return !u.src.IsValid() } + +// rank orders rule kinds for adding: suppress, then source. +func (u underlayRule) rank() int { + if u.isSuppress() { + return 0 + } + return 1 +} + +func (u underlayRule) String() string { + if u.isSuppress() { + return fmt.Sprintf("v%d table %d suppress rule", u.fam, tailscaleRouteTable.Num) + } + return "source rule for " + u.src.String() +} + +// compareUnderlayRules orders suppress rules before source rules (the order +// to add them in), then by family and address. +func compareUnderlayRules(a, b underlayRule) int { + return cmp.Or( + cmp.Compare(a.rank(), b.rank()), + cmp.Compare(a.fam, b.fam), + a.src.Compare(b.src)) +} + +func (r *linuxRouter) underlaySrcRulePriority() int { + return r.ipPolicyPrefBase + underlaySrcRuleOffset +} + +func (r *linuxRouter) underlaySuppressRulePriority() int { + return r.ipPolicyPrefBase + underlaySuppressRuleOffset +} + +// isUnderlayRulePriority reports whether pri is one of the underlay rule +// priorities. +func (r *linuxRouter) isUnderlayRulePriority(pri int) bool { + return pri == r.underlaySrcRulePriority() || + pri == r.underlaySuppressRulePriority() +} + +// rpFilterStrictV4FromSysctl reports whether the kernel's strict IPv4 +// reverse path filter applies to any up, non-Tailscale interface. The +// effective mode of an interface is the larger of conf/all/rp_filter and +// conf//rp_filter, so 1 (strict) only applies when neither is 2 (loose). +func (r *linuxRouter) rpFilterStrictV4FromSysctl() bool { + read := func(dev string) int { + b, err := os.ReadFile(filepath.Join("/proc/sys/net/ipv4/conf", dev, "rp_filter")) + if err != nil { + return 0 + } + v, _ := strconv.Atoi(strings.TrimSpace(string(b))) + return v + } + all := read("all") + var st *netmon.State + if r.netMon != nil { + st = r.netMon.InterfaceState() + } + if st == nil { + return all == 1 + } + for name, ifc := range st.Interface { + if name == r.tunname || strings.HasPrefix(name, "tailscale") || !ifc.IsUp() || ifc.IsLoopback() { + continue + } + if max(all, read(name)) == 1 { + return true + } + } + return false +} + +// underlayAddrsFromNetMon returns the candidate underlay source addresses +// from the network monitor's current interface state. +func (r *linuxRouter) underlayAddrsFromNetMon() []netip.Addr { + if r.netMon == nil { + return nil + } + return underlayAddrsFromState(r.netMon.InterfaceState(), r.tunname) +} + +// underlayAddrsFromState returns the de-duplicated local unicast addresses +// on up, non-Tailscale interfaces in st, in priority order for +// maxUnderlaySrcRulesPerFamily: +// +// 1. all addresses on the default route interface, which is where +// tailscaled's bypass-marked sockets (WireGuard, DERP, control) source +// from and so where the replies that need fixing arrive; +// 2. then non-link-local addresses on other interfaces, interfaces with +// fewer such addresses first, so a handful of real NICs are never +// crowded out by an interface carrying hundreds of service VIPs (e.g. +// kube-proxy's kube-ipvs0 dummy, which holds every ClusterIP); +// 3. then link-local addresses on other interfaces, so the fe80:: +// addresses of many container veths can't crowd out another NIC's +// global addresses either; +// 4. ties broken by interface name, and addresses within an interface in +// address order, for determinism. +// +// Addresses on the loopback interface are included unless they are loopback +// addresses themselves: hosts commonly put service VIPs (anycast, BGP, +// keepalived) on lo, and replies to them face the same reverse-path check. +// Link-local addresses are included, as the Tailscale default route would +// otherwise capture reverse lookups for link-local peers too. +func underlayAddrsFromState(st *netmon.State, tunname string) []netip.Addr { + if st == nil { + return nil + } + type ifAddrs struct { + name string + isDefault bool + global []netip.Addr // not link-local + linkLocal []netip.Addr + } + var ifs []ifAddrs + for name, ifc := range st.Interface { + if name == tunname || strings.HasPrefix(name, "tailscale") { + continue + } + if !ifc.IsUp() { + // Addresses on down interfaces aren't usable as local + // destinations. + continue + } + ia := ifAddrs{name: name, isDefault: name == st.DefaultRouteInterface} + for _, pfx := range st.InterfaceIPs[name] { + a := pfx.Addr().WithZone("") + if !a.IsValid() || a.IsUnspecified() || a.IsLoopback() || a.IsMulticast() { + continue + } + if a.IsLinkLocalUnicast() { + ia.linkLocal = append(ia.linkLocal, a) + } else { + ia.global = append(ia.global, a) + } + } + if len(ia.global) == 0 && len(ia.linkLocal) == 0 { + continue + } + for _, as := range []*[]netip.Addr{&ia.global, &ia.linkLocal} { + slices.SortFunc(*as, netip.Addr.Compare) + *as = slices.Compact(*as) + } + ifs = append(ifs, ia) + } + slices.SortFunc(ifs, func(a, b ifAddrs) int { + if a.isDefault != b.isDefault { + if a.isDefault { + return -1 + } + return 1 + } + if c := len(a.global) - len(b.global); c != 0 { + return c + } + return strings.Compare(a.name, b.name) + }) + var out []netip.Addr + seen := set.Set[netip.Addr]{} + add := func(as []netip.Addr) { + for _, a := range as { + // The same address may be configured on more than one + // interface; keep its highest-priority occurrence. + if !seen.Contains(a) { + seen.Add(a) + out = append(out, a) + } + } + } + for _, ia := range ifs { + if ia.isDefault { + add(ia.global) + add(ia.linkLocal) + } + } + for _, ia := range ifs { + if !ia.isDefault { + add(ia.global) + } + } + for _, ia := range ifs { + if !ia.isDefault { + add(ia.linkLocal) + } + } + return out +} + +// desiredUnderlayRulesLocked returns the set of underlay rules that should +// currently be installed. +// +// r.mu must be held. +func (r *linuxRouter) desiredUnderlayRulesLocked() set.Set[underlayRule] { + want := set.Set[underlayRule]{} + if !r.ipRuleAvailable || r.closed.Load() || disableUnderlaySrcRules() || r.underlayAddrs == nil { + r.setUnderlaySrcRulesCappedLocked(false) + return want + } + // The kernel's IPv4 rp_filter is the only IPv4 check we know of that + // needs these rules (mark-aware netfilter checks are covered by the + // connmark rules), so skip them unless it's in strict mode: they make + // root sockets bound to an underlay address bypass the exit node, and + // hosts without the problem shouldn't get that. IPv6 has no kernel + // reverse path filter; its netfilter checks can't be detected + // reliably, so the IPv6 rules are always installed. + wantV4 := false + if r.exitRouteV4 && r.rpFilterStrictV4 != nil { + wantV4 = r.rpFilterStrictV4() + r.rpFilterStrictV4Seen = wantV4 + } + wantV6 := r.exitRouteV6 && r.getV6Available() + if !wantV4 && !wantV6 { + r.setUnderlaySrcRulesCappedLocked(false) + return want + } + + // Never install a rule for one of our own Tailscale addresses. + tsAddrs := set.Set[netip.Addr]{} + for p := range r.addrs { + tsAddrs.Add(p.Addr()) + } + + var n4, n6 int + capped := false + for _, a := range r.underlayAddrs() { + if tsAddrs.Contains(a) { + continue + } + switch { + case a.Is4() && wantV4: + if n4 >= maxUnderlaySrcRulesPerFamily { + capped = true + continue + } + n4++ + case a.Is6() && wantV6: + if n6 >= maxUnderlaySrcRulesPerFamily { + capped = true + continue + } + n6++ + default: + continue + } + want.Add(underlayRule{fam: familyOf(a), src: a}) + } + // A family's suppress rule exists whenever it has source rules. + if n4 > 0 { + want.Add(underlayRule{fam: v4}) + } + if n6 > 0 { + want.Add(underlayRule{fam: v6}) + } + r.setUnderlaySrcRulesCappedLocked(capped) + return want +} + +// setUnderlaySrcRulesCappedLocked records whether the per-family cap was hit, +// logging only on transitions to avoid spamming on every netmon change. +// +// r.mu must be held. +func (r *linuxRouter) setUnderlaySrcRulesCappedLocked(capped bool) { + if capped == r.underlaySrcRulesCapped { + return + } + r.underlaySrcRulesCapped = capped + if capped { + metricUnderlaySrcRulesCapped.Set(1) + } else { + metricUnderlaySrcRulesCapped.Set(0) + } + if capped { + r.logf("warning: more than %d local addresses per address family; only the first %d get rp_filter underlay source rules, replies to the rest may be dropped by strict reverse path filtering while using an exit node", maxUnderlaySrcRulesPerFamily, maxUnderlaySrcRulesPerFamily) + } +} + +// updateUnderlaySrcRulesLocked reconciles the installed underlay rules with +// the desired set. If addOnly, it only adds missing rules; Set uses that +// before it installs exit node routes, so the rules are in place before the +// default route that makes them necessary. +// +// Adds happen suppress rule first, then source rules; removals the +// reverse. That way a source rule never exists without its family's +// suppress rule, which would briefly cut tailnet traffic to the underlay +// addresses. +// +// r.mu must be held. +func (r *linuxRouter) updateUnderlaySrcRulesLocked(addOnly bool) error { + if r.underlaySrcRules == nil { + r.underlaySrcRules = set.Set[underlayRule]{} + } + want := r.desiredUnderlayRulesLocked() + + var errs []error + var added, removed int + if !addOnly { + stale := slices.SortedFunc(func(yield func(underlayRule) bool) { + for u := range r.underlaySrcRules { + if !want.Contains(u) && !yield(u) { + return + } + } + }, compareUnderlayRules) + for _, u := range slices.Backward(stale) { + if err := r.delUnderlayRule(u); err != nil { + // Keep tracking it so we retry on the next reconcile. + errs = append(errs, fmt.Errorf("deleting rp_filter %v: %w", u, err)) + continue + } + r.underlaySrcRules.Delete(u) + removed++ + } + } + for _, u := range slices.SortedFunc(want.All(), compareUnderlayRules) { + if r.underlaySrcRules.Contains(u) { + continue + } + if !u.isSuppress() && !r.underlaySrcRules.Contains(underlayRule{fam: u.fam}) { + // Its suppress rule failed to install; don't add a source + // rule without it. + continue + } + if err := r.addUnderlayRule(u); err != nil { + errs = append(errs, fmt.Errorf("adding rp_filter %v: %w", u, err)) + continue + } + r.underlaySrcRules.Add(u) + added++ + } + if added > 0 || removed > 0 { + r.logf("rp_filter underlay rules: +%d -%d, now %d", added, removed, len(r.underlaySrcRules)) + } + metricUnderlaySrcRules.Set(int64(len(r.underlaySrcRules))) + r.scheduleRPFilterRecheckLocked() + return errors.Join(errs...) +} + +// rpFilterRecheckInterval is how often, while an exit node's 0.0.0.0/0 is +// routed, we re-read the IPv4 rp_filter sysctls that gate the IPv4 rules. +const rpFilterRecheckInterval = 10 * time.Second + +// scheduleRPFilterRecheckLocked arranges for the IPv4 rp_filter mode to be +// read again after rpFilterRecheckInterval, while it gates rules we might +// need. A sysctl write raises no netlink event, so without this a switch to +// strict mode with the exit node already on would leave the IPv4 rules out +// until some unrelated network change or Set (review finding). +// +// r.mu must be held. +func (r *linuxRouter) scheduleRPFilterRecheckLocked() { + if !r.exitRouteV4 || !r.ipRuleAvailable || r.rpFilterStrictV4 == nil || + r.closed.Load() || disableUnderlaySrcRules() { + return + } + if r.rpFilterRecheckPending.Swap(true) { + return + } + r.after(rpFilterRecheckInterval, r.recheckRPFilter) +} + +// recheckRPFilter reconciles the underlay rules if the IPv4 rp_filter mode +// changed since they were last computed, and otherwise schedules the next +// check. Reading the sysctls is a handful of small /proc reads. +func (r *linuxRouter) recheckRPFilter() { + strict := r.rpFilterStrictV4() + r.mu.Lock() + defer r.mu.Unlock() + r.rpFilterRecheckPending.Store(false) + if r.closed.Load() || !r.exitRouteV4 { + return + } + if strict == r.rpFilterStrictV4Seen { + r.scheduleRPFilterRecheckLocked() + return + } + r.logf("IPv4 rp_filter is now %s; updating rp_filter underlay rules", map[bool]string{true: "strict", false: "not strict"}[strict]) + // This reschedules the next check. + r.logUnderlayErrLocked(r.updateUnderlaySrcRulesLocked(false)) +} + +// removeUnderlaySrcRulesLocked removes every underlay rule we are tracking, +// source rules first. +// +// r.mu must be held. +func (r *linuxRouter) removeUnderlaySrcRulesLocked() error { + var errs []error + for _, u := range slices.Backward(slices.SortedFunc(r.underlaySrcRules.All(), compareUnderlayRules)) { + if err := r.delUnderlayRule(u); err != nil { + // Keep tracking it so a later reconcile or Close retries + // (the next Up's sweep also catches it). + errs = append(errs, fmt.Errorf("deleting rp_filter %v: %w", u, err)) + continue + } + r.underlaySrcRules.Delete(u) + } + return errors.Join(errs...) +} + +// underlayNetlinkUsable reports whether we can manage underlay rules via +// netlink directly: always on a real system, even when the ip command is +// forced (TS_DEBUG_USE_IP_COMMAND), as the ip command adds identical rules. +// Not with the tests' fake command runner. +func (r *linuxRouter) underlayNetlinkUsable() bool { + _, ok := r.cmd.(osCommandRunner) + return ok +} + +// onNetworkChange is the netmon.ChangeDelta eventbus callback. It +// reconciles the underlay rules with the current interface state so they +// follow address changes (DHCP renewals, interfaces coming and going, IPv6 +// privacy address rotation). +func (r *linuxRouter) onNetworkChange() { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed.Load() { + return + } + // No snapshotV6Usable here: it reads /proc eagerly, while a reconcile + // calls getV6Available at most once, and only when ::/0 is routed. + r.logUnderlayErrLocked(r.updateUnderlaySrcRulesLocked(false)) +} + +// logUnderlayErrLocked logs err from a reconcile of the underlay rules, +// unless it's the same as the last one logged: a rule that can't be added +// is retried on every network change, which on a container host happens +// all the time. A nil err resets that, so a later failure logs again. +// +// r.mu must be held. +func (r *linuxRouter) logUnderlayErrLocked(err error) { + if err == nil { + r.lastUnderlayErr = "" + return + } + if msg := err.Error(); msg != r.lastUnderlayErr { + r.lastUnderlayErr = msg + r.logf("warning: rp_filter underlay rules: %v", err) + } +} + +// sweepStaleUnderlaySrcRulesLocked deletes underlay rules left behind by a +// previous tailscaled that exited without cleaning up (crash, SIGKILL). +// See isOurUnderlayRule for how they're recognized. +// +// It needs netlink; see underlayNetlinkUsable. +// +// r.mu must be held. +func (r *linuxRouter) sweepStaleUnderlaySrcRulesLocked() { + r.underlaySrcRules = set.Set[underlayRule]{} + if !r.ipRuleAvailable || !r.underlayNetlinkUsable() { + return + } + if n := sweepUnderlaySrcRules(r.logf, r.ipPolicyPrefBase); n > 0 { + r.logf("removed %d stale rp_filter underlay rule(s) left by a previous instance", n) + } +} + +// sweepUnderlaySrcRules deletes, via netlink, all of our underlay rules for +// priority base in both address families. It returns the number deleted. +func sweepUnderlaySrcRules(logf func(string, ...any), base int) int { + n := 0 + // Sweep both families regardless of current IPv6 availability so we + // also clean up after a previous run that had IPv6. + for _, family := range []addrFamily{v4, v6} { + rules, err := listIPRules(family) + if err != nil { + continue + } + for _, ru := range rules { + if !isOurUnderlayRule(ru, base) { + continue + } + if err := delIPRule(ru); err != nil && !errors.Is(err, errENOENT) { + logf("warning: deleting stale rp_filter underlay rule (pref %d, from %v): %v", ru.priority, ru.src, err) + continue + } + n++ + } + } + return n +} + +// removeUnderlaySrcRulesForCleanup removes leftover underlay rules from the +// router cleanup that tailscaled runs at every start (and for --cleanup), +// when no router is running. It only sweeps the priority base this host +// would use, determined the same way newLinuxRouter does. +func removeUnderlaySrcRulesForCleanup(logf func(string, ...any)) { + base := defaultIPPolicyPrefBase + if isMWAN3, err := checkOpenWRTUsingMWAN3(); err == nil && isMWAN3 { + base = mwan3IPPolicyPrefBase + } + if n := sweepUnderlaySrcRules(logf, base); n > 0 { + logf("removed %d stale rp_filter underlay rule(s) during cleanup", n) + } +} + +// isOurUnderlayRule reports whether ru is an underlay rule installed by +// tailscaled for priority base. On kernels that store the rule protocol +// (4.17+), that's exactly the rules at our priorities with protocol +// ruleProtocolTailscale, whatever their shape. On older kernels it falls +// back to the exact shape of the rules we install there. +func isOurUnderlayRule(ru ipRule, base int) bool { + return isOurUnderlayRuleFor(ru, base, kernelAtLeast(4, 10)) +} + +// isOurUnderlayRuleFor is isOurUnderlayRule for a kernel that does +// (uidRangeOK) or doesn't support uidrange selectors. +func isOurUnderlayRuleFor(ru ipRule, base int, uidRangeOK bool) bool { + src := int(ru.priority) == base+underlaySrcRuleOffset + sup := int(ru.priority) == base+underlaySuppressRuleOffset + if !src && !sup { + return false + } + if ru.hasProtocol { + return ru.protocol == ruleProtocolTailscale + } + if ru.other || ru.invert != sup || src && ru.suppressPrefixlen != -1 { + return false + } + // Our source rules carry uidrange 0-0, which kernels from 4.10 keep and + // older ones drop. + uidOK := ru.uidRange == nil + if uidRangeOK { + uidOK = ru.uidRange != nil && *ru.uidRange == [2]uint32{0, 0} + } + if src { + return ru.table == uint32(mainRouteTable.Num) && + ru.src.IsValid() && + ru.fwmask == 0 && + ru.ipProto == 0 && ru.sportRange == nil && + uidOK + } + return ru.table == uint32(tailscaleRouteTable.Num) && + !ru.src.IsValid() && + ru.fwmark == tsconst.LinuxBypassMarkNum && + ru.fwmask == tsconst.LinuxFwmarkMaskNum && + ru.suppressPrefixlen == 0 && + ru.ipProto == 0 && ru.sportRange == nil && + ru.uidRange == nil +} + +// isIPRuleNotFound reports whether err from 'ip rule del' means the rule +// didn't exist. iproute2 exits 2 (254 on some older versions) for any +// RTNETLINK error, including EPERM, so the exit code alone isn't enough; the +// real command runner includes iproute2's output in the error, which we +// match. The test fakeOS reports "not found" as exactly "exitcode:N". +func isIPRuleNotFound(err error) bool { + c := errCode(err) + if c != 2 && c != 254 { + return false + } + return strings.Contains(err.Error(), "No such file or directory") || + err.Error() == "exitcode:"+strconv.Itoa(c) +} + +func familyOf(a netip.Addr) addrFamily { + if a.Is6() { + return v6 + } + return v4 +} + +// underlayIPRule returns the kernel rule for u. +func (r *linuxRouter) underlayIPRule(u underlayRule) ipRule { + if u.isSuppress() { + return ipRule{ + family: u.fam, + priority: uint32(r.underlaySuppressRulePriority()), + table: uint32(tailscaleRouteTable.Num), + invert: true, + fwmark: tsconst.LinuxBypassMarkNum, + fwmask: tsconst.LinuxFwmarkMaskNum, + suppressPrefixlen: 0, + protocol: ruleProtocolTailscale, + } + } + return ipRule{ + family: u.fam, + priority: uint32(r.underlaySrcRulePriority()), + table: uint32(mainRouteTable.Num), + src: u.src, + suppressPrefixlen: -1, + uidRange: &[2]uint32{0, 0}, + protocol: ruleProtocolTailscale, + } +} + +// underlayIPCommandArgs returns the ip command for verb ("add" or "del") on +// u. It sets the rule protocol, so the netlink sweep recognizes these rules +// too; that needs iproute2 4.17 or later (busybox lacks it, and uidrange). +func (r *linuxRouter) underlayIPCommandArgs(verb string, u underlayRule) []string { + if u.isSuppress() { + mark := fmt.Sprintf("0x%x", tsconst.LinuxBypassMarkNum) + if r.fwmaskWorks() { + mark += "/" + tsconst.LinuxFwmarkMask + } + return []string{ + "ip", u.fam.dashArg(), + "rule", verb, + "pref", strconv.Itoa(r.underlaySuppressRulePriority()), + "not", "fwmark", mark, + "table", tailscaleRouteTable.ipCmdArg(), + "suppress_prefixlength", "0", + "protocol", strconv.Itoa(ruleProtocolTailscale), + } + } + return []string{ + "ip", u.fam.dashArg(), + "rule", verb, + "pref", strconv.Itoa(r.underlaySrcRulePriority()), + "from", u.src.String(), + "uidrange", "0-0", + "table", mainRouteTable.ipCmdArg(), + "protocol", strconv.Itoa(ruleProtocolTailscale), + } +} + +// addUnderlayRule installs u. An already existing identical rule is not an +// error. +func (r *linuxRouter) addUnderlayRule(u underlayRule) error { + if r.useIPCommand() { + err := r.cmd.run(r.underlayIPCommandArgs("add", u)...) + if err != nil && errCode(err) == 2 && strings.Contains(err.Error(), "File exists") { + return nil + } + return err + } + err := addIPRule(r.underlayIPRule(u)) + if errors.Is(err, errEEXIST) { + return nil + } + return err +} + +// delUnderlayRule removes u. A missing rule is not an error. +func (r *linuxRouter) delUnderlayRule(u underlayRule) error { + if r.useIPCommand() { + err := r.cmd.run(r.underlayIPCommandArgs("del", u)...) + if err == nil || isIPRuleNotFound(err) { + return nil + } + return err + } + err := delIPRule(r.underlayIPRule(u)) + if errors.Is(err, errENOENT) { + return nil + } + return err +} diff --git a/wgengine/router/osrouter/rpfilter_linux_test.go b/wgengine/router/osrouter/rpfilter_linux_test.go new file mode 100644 index 000000000..470f9e25b --- /dev/null +++ b/wgengine/router/osrouter/rpfilter_linux_test.go @@ -0,0 +1,1545 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !android + +package osrouter + +import ( + "encoding/binary" + "errors" + "fmt" + "net" + "net/netip" + "os" + "os/exec" + "reflect" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "syscall" + "testing" + "time" + + mdnetlink "github.com/mdlayher/netlink" + "github.com/tailscale/netlink" + "go4.org/netipx" + "golang.org/x/sys/unix" + "tailscale.com/envknob" + "tailscale.com/net/netmon" + "tailscale.com/tstest" + "tailscale.com/types/logger" + "tailscale.com/util/eventbus" + "tailscale.com/util/set" + "tailscale.com/wgengine/router" +) + +// testUnderlayAddrs is a fixed underlay address set used by fake-OS router +// tests so results don't depend on the host's interfaces. It deliberately +// includes one of the test configs' Tailscale addresses, which must never get +// a rule. +var testUnderlayAddrs = []netip.Addr{ + netip.MustParseAddr("10.1.2.3"), + netip.MustParseAddr("100.101.102.104"), // a Tailscale LocalAddr in tests; excluded + netip.MustParseAddr("192.168.1.5"), + netip.MustParseAddr("2001:db8::5"), + netip.MustParseAddr("fe80::5"), +} + +func setTestUnderlayAddrs(r *linuxRouter, addrs []netip.Addr) { + r.mu.Lock() + defer r.mu.Unlock() + r.underlayAddrs = func() []netip.Addr { return slices.Clone(addrs) } +} + +// testUnderlayPri and testSuppressPri are the underlay rule priorities for +// routers using the default ipPolicyPrefBase, as newTestLinuxRouter does. +const ( + testUnderlayPri = defaultIPPolicyPrefBase + underlaySrcRuleOffset + testSuppressPri = defaultIPPolicyPrefBase + underlaySuppressRuleOffset +) + +// underlayRules returns the fake OS's rules at the underlay rule priorities. +func underlayRules(fake *fakeOS) []string { + var out []string + for _, ru := range fake.rules { + if strings.Contains(ru, fmt.Sprintf(" pref %d ", testUnderlayPri)) || + strings.Contains(ru, fmt.Sprintf(" pref %d ", testSuppressPri)) { + out = append(out, ru) + } + } + return out +} + +// underlaySrcRuleCount counts the fake OS's underlay source rules for the +// family given as "-4" or "-6". +func underlaySrcRuleCount(fake *fakeOS, fam string) int { + n := 0 + for _, ru := range underlayRules(fake) { + if strings.HasPrefix(ru, fam+" ") && strings.Contains(ru, " from ") { + n++ + } + } + return n +} + +// wantUnderlayRules returns the fake OS rules expected for underlay source +// addresses addrs: one source rule each, plus the suppress rule for each +// family that has any. +func wantUnderlayRules(addrs ...string) []string { + var out []string + fams := set.Set[string]{} + for _, a := range addrs { + fam := "-4" + if strings.Contains(a, ":") { + fam = "-6" + } + fams.Add(fam) + out = append(out, fmt.Sprintf("%s pref %d from %s uidrange 0-0 table main protocol 52", fam, testUnderlayPri, a)) + } + for fam := range fams { + out = append(out, fmt.Sprintf("%s pref %d not fwmark 0x80000/0xff0000 table 52 suppress_prefixlength 0 protocol 52", fam, testSuppressPri)) + } + slices.Sort(out) + return out +} + +func checkUnderlayRules(t *testing.T, fake *fakeOS, want ...string) { + t.Helper() + got := underlayRules(fake) + w := strings.Split(adjustFwmask(t, strings.Join(wantUnderlayRules(want...), "\n")), "\n") + if len(want) == 0 { + w = nil + } + if !slices.Equal(got, w) { + t.Fatalf("underlay source rules:\n got %q\nwant %q", got, w) + } +} + +func exitConfig(routes ...string) *router.Config { + return &router.Config{ + LocalAddrs: mustCIDRs("100.101.102.104/10"), + Routes: mustCIDRs(routes...), + NetfilterMode: netfilterOff, + } +} + +func TestUnderlayAddrsFromState(t *testing.T) { + const up = net.FlagUp + ifc := func(name string, flags net.Flags) netmon.Interface { + return netmon.Interface{Interface: &net.Interface{Name: name, Flags: flags}} + } + st := &netmon.State{ + DefaultRouteInterface: "eth0", + Interface: map[string]netmon.Interface{ + "eth0": ifc("eth0", up), + "lo": ifc("lo", up|net.FlagLoopback), + "tailscale0": ifc("tailscale0", up), + "ts-custom": ifc("ts-custom", up), + "docker0": ifc("docker0", 0), // down + "wg0": ifc("wg0", up), + "kube-ipvs0": ifc("kube-ipvs0", up), + "empty0": ifc("empty0", up), + }, + InterfaceIPs: map[string][]netip.Prefix{ + "eth0": { + netip.MustParsePrefix("fe80::5/64"), + netip.MustParsePrefix("192.168.1.5/24"), + netip.MustParsePrefix("2001:db8::5/64"), + netip.MustParsePrefix("192.168.1.5/24"), // dup + }, + "lo": { + netip.MustParsePrefix("127.0.0.1/8"), + netip.MustParsePrefix("::1/128"), + netip.MustParsePrefix("10.9.9.9/32"), // service VIP on lo + }, + "tailscale0": {netip.MustParsePrefix("100.64.0.1/32")}, + "ts-custom": {netip.MustParsePrefix("100.64.0.2/32")}, + "docker0": {netip.MustParsePrefix("172.17.0.1/16")}, + "wg0": {netip.MustParsePrefix("10.200.0.2/32")}, + "kube-ipvs0": { + netip.MustParsePrefix("10.96.0.1/32"), + netip.MustParsePrefix("10.96.0.10/32"), + netip.MustParsePrefix("10.200.0.2/32"), // also on wg0; keep first + }, + }, + } + got := underlayAddrsFromState(st, "ts-custom") + want := []netip.Addr{ + // Default route interface first. + netip.MustParseAddr("192.168.1.5"), + netip.MustParseAddr("2001:db8::5"), + netip.MustParseAddr("fe80::5"), + // Then by address count (1 each), then name. + netip.MustParseAddr("10.9.9.9"), // lo + netip.MustParseAddr("10.200.0.2"), // wg0 + // Then the many-address interface, minus the dup already listed. + netip.MustParseAddr("10.96.0.1"), + netip.MustParseAddr("10.96.0.10"), + } + if !slices.Equal(got, want) { + t.Errorf("underlayAddrsFromState:\n got %v\nwant %v", got, want) + } + if got := underlayAddrsFromState(nil, "tailscale0"); got != nil { + t.Errorf("nil state: got %v, want nil", got) + } +} + +// TestUnderlaySrcRulesCapKeepsPrimary is a regression test for the cap +// filling up with service VIPs (numerically lower than the NIC address) on a +// kube-proxy IPVS node and leaving the address tailscaled actually uses +// without a rule. +func TestUnderlaySrcRulesCapKeepsPrimary(t *testing.T) { + const up = net.FlagUp + ifc := func(name string) netmon.Interface { + return netmon.Interface{Interface: &net.Interface{Name: name, Flags: up}} + } + var vips []netip.Prefix + a := netip.MustParseAddr("10.96.0.1") + for range 3 * maxUnderlaySrcRulesPerFamily { + vips = append(vips, netip.PrefixFrom(a, 32)) + a = a.Next() + } + st := &netmon.State{ + DefaultRouteInterface: "eth0", + Interface: map[string]netmon.Interface{ + "eth0": ifc("eth0"), + "eth1": ifc("eth1"), + "kube-ipvs0": ifc("kube-ipvs0"), + }, + InterfaceIPs: map[string][]netip.Prefix{ + "eth0": {netip.MustParsePrefix("192.168.1.5/24")}, + "eth1": {netip.MustParsePrefix("172.16.0.5/24")}, + "kube-ipvs0": vips, + }, + } + lr, fake := newTestLinuxRouter(t) + setTestUnderlayAddrs(lr, underlayAddrsFromState(st, "tailscale0")) + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatal(err) + } + rules := underlayRules(fake) + if n := underlaySrcRuleCount(fake, "-4"); n != maxUnderlaySrcRulesPerFamily { + t.Fatalf("got %d source rules, want %d", n, maxUnderlaySrcRulesPerFamily) + } + for _, want := range wantUnderlayRules("192.168.1.5", "172.16.0.5") { + if !slices.Contains(rules, want) { + t.Errorf("missing %q; cap crowded out a NIC address", want) + } + } +} + +func TestUnderlaySrcRulesNilAddrFunc(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + lr.mu.Lock() + lr.underlayAddrs = nil + lr.mu.Unlock() + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake) +} + +// TestUnderlaySrcRulesLifecycle walks the rules through exit node on/off, +// per-family gating, address changes, and Close. +func TestUnderlaySrcRulesLifecycle(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + addrs := []netip.Addr{ + netip.MustParseAddr("192.168.1.5"), + netip.MustParseAddr("2001:db8::5"), + } + setTestUnderlayAddrs(lr, addrs) + + // No exit node: no rules. + if err := lr.Set(exitConfig("100.100.100.100/32", "192.168.16.0/24")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake) + + // IPv4 exit route only. + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake, "192.168.1.5") + + // Dual-stack exit routes. + if err := lr.Set(exitConfig("0.0.0.0/0", "::/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake, "192.168.1.5", "2001:db8::5") + + // DHCP renumbering plus a new IPv6 privacy address: rules follow + // on the next network change without a Set. + setTestUnderlayAddrs(lr, []netip.Addr{ + netip.MustParseAddr("192.168.1.77"), + netip.MustParseAddr("2001:db8::5"), + netip.MustParseAddr("2001:db8::abcd"), + }) + lr.onNetworkChange() + checkUnderlayRules(t, fake, "192.168.1.77", "2001:db8::5", "2001:db8::abcd") + + // Idempotent: repeated changes and Sets with no difference don't + // re-add (fakeOS fails the test on a duplicate add). + lr.onNetworkChange() + if err := lr.Set(exitConfig("0.0.0.0/0", "::/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake, "192.168.1.77", "2001:db8::5", "2001:db8::abcd") + + // Exit node off: everything removed. + if err := lr.Set(exitConfig("100.100.100.100/32")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake) + + // Back on, then Close removes them. + if err := lr.Set(exitConfig("0.0.0.0/0", "::/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake, "192.168.1.77", "2001:db8::5", "2001:db8::abcd") + if err := lr.Close(); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake) + + // Network changes after Close are ignored. + lr.onNetworkChange() + checkUnderlayRules(t, fake) +} + +func TestUnderlaySrcRulesNilConfigRemoves(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + setTestUnderlayAddrs(lr, []netip.Addr{netip.MustParseAddr("192.168.1.5")}) + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake, "192.168.1.5") + if err := lr.Set(nil); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake) +} + +func TestUnderlaySrcRulesSkipV6WhenUnavailable(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + fake.nfr.(*fakeIPTablesRunner).noV6 = true + setTestUnderlayAddrs(lr, []netip.Addr{ + netip.MustParseAddr("192.168.1.5"), + netip.MustParseAddr("2001:db8::5"), + }) + if err := lr.Set(exitConfig("0.0.0.0/0", "::/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake, "192.168.1.5") +} + +func TestUnderlaySrcRulesExcludeTailscaleAddrs(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + setTestUnderlayAddrs(lr, []netip.Addr{ + netip.MustParseAddr("100.101.102.104"), // our Tailscale address + netip.MustParseAddr("100.72.1.1"), // carrier-grade NAT underlay; keep + }) + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake, "100.72.1.1") +} + +func TestUnderlaySrcRulesCap(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + var addrs []netip.Addr + a := netip.MustParseAddr("10.0.0.1") + for range maxUnderlaySrcRulesPerFamily + 10 { + addrs = append(addrs, a) + a = a.Next() + } + addrs = append(addrs, netip.MustParseAddr("2001:db8::5")) + setTestUnderlayAddrs(lr, addrs) + if err := lr.Set(exitConfig("0.0.0.0/0", "::/0")); err != nil { + t.Fatal(err) + } + n4, n6 := underlaySrcRuleCount(fake, "-4"), underlaySrcRuleCount(fake, "-6") + if n4 != maxUnderlaySrcRulesPerFamily || n6 != 1 { + t.Errorf("got %d v4 and %d v6 rules; want %d and 1", n4, n6, maxUnderlaySrcRulesPerFamily) + } + if !lr.underlaySrcRulesCapped { + t.Error("underlaySrcRulesCapped = false; want true") + } +} + +// TestUnderlaySrcRulesInRestoreRange ensures the rule priority is inside the +// range onIPRuleDeleted reacts to and below the table 52 catch-all. +func TestUnderlaySrcRulesInRestoreRange(t *testing.T) { + for _, base := range []int{defaultIPPolicyPrefBase, mwan3IPPolicyPrefBase} { + r := &linuxRouter{routerFixed: routerFixed{ipPolicyPrefBase: base}} + pri := r.underlaySrcRulePriority() + if pri < base || pri >= base+100 { + t.Errorf("base %d: priority %d outside onIPRuleDeleted range", base, pri) + } + for _, ru := range append(slices.Clone(baseIPRules), ubntIPRules...) { + if ru.Table == tailscaleRouteTable.Num && pri >= base+ru.Priority { + t.Errorf("base %d: priority %d not below table 52 rule at %d", base, pri, base+ru.Priority) + } + } + } +} + +func TestIsOurUnderlayRule(t *testing.T) { + base := defaultIPPolicyPrefBase + r := &linuxRouter{routerFixed: routerFixed{ipPolicyPrefBase: base}} + // srcRule and supRule are ours as listed by a kernel without rule + // protocol support (pre-4.17), so only their shape identifies them. + noProto := func(u underlayRule) func() ipRule { + return func() ipRule { + ru := r.underlayIPRule(u) + ru.protocol = 0 + return ru + } + } + srcRule := noProto(underlayRule{fam: v4, src: netip.MustParseAddr("192.168.1.5")}) + supRule := noProto(underlayRule{fam: v6}) + mod := func(ru ipRule, f func(*ipRule)) ipRule { f(&ru); return ru } + noUID := func(ru *ipRule) { ru.uidRange = nil } + // An administrator's "ip rule add pref 5260 from 192.0.2.50 lookup main". + admin := ipRule{family: v4, priority: uint32(base + underlaySrcRuleOffset), table: uint32(mainRouteTable.Num), src: netip.MustParseAddr("192.0.2.50"), suppressPrefixlen: -1} + + tests := []struct { + name string + ru ipRule + // want is the result on kernels 4.10-4.16 (uidrange, no rule + // protocol) and wantPre410 on older ones. Rules with a protocol + // are only reported by 4.17+, where both agree. + want, wantPre410 bool + }{ + // Kernel 4.17+: the protocol decides, whatever the shape. + {"protocol-ours", mod(srcRule(), func(ru *ipRule) { ru.hasProtocol = true; ru.protocol = ruleProtocolTailscale }), true, true}, + {"protocol-ours-odd-shape", mod(srcRule(), func(ru *ipRule) { ru.hasProtocol = true; ru.protocol = ruleProtocolTailscale; ru.other = true }), true, true}, + {"protocol-ours-suppress", mod(supRule(), func(ru *ipRule) { ru.hasProtocol = true; ru.protocol = ruleProtocolTailscale }), true, true}, + {"protocol-admin-same-shape", mod(srcRule(), func(ru *ipRule) { ru.hasProtocol = true; ru.protocol = 0 }), false, false}, + {"protocol-other-daemon", mod(srcRule(), func(ru *ipRule) { ru.hasProtocol = true; ru.protocol = 186 }), false, false}, + {"protocol-ours-other-priority", mod(srcRule(), func(ru *ipRule) { ru.hasProtocol = true; ru.protocol = ruleProtocolTailscale; ru.priority++ }), false, false}, + + // Older kernels: exact shape. Our source rule has uidrange 0-0 + // from 4.10, and none before (the kernel drops it). + {"shape-src", srcRule(), true, false}, + {"shape-src-no-uidrange", mod(srcRule(), noUID), false, true}, + {"shape-admin-rule (review finding 4)", admin, false, true}, + {"shape-src-v6", mod(srcRule(), func(ru *ipRule) { ru.family = v6; ru.src = netip.MustParseAddr("2001:db8::5") }), true, false}, + {"shape-src-other-uidrange", mod(srcRule(), func(ru *ipRule) { ru.uidRange = &[2]uint32{1000, 1000} }), false, false}, + {"shape-src-other-table", mod(srcRule(), func(ru *ipRule) { ru.table = 100 }), false, false}, + {"shape-src-no-src", mod(srcRule(), func(ru *ipRule) { ru.src = netip.Addr{} }), false, false}, + {"shape-src-invert", mod(srcRule(), func(ru *ipRule) { ru.invert = true }), false, false}, + {"shape-src-fwmark", mod(srcRule(), func(ru *ipRule) { ru.fwmark, ru.fwmask = 1, 1 }), false, false}, + {"shape-src-suppress", mod(srcRule(), func(ru *ipRule) { ru.suppressPrefixlen = 0 }), false, false}, + {"shape-src-ipproto", mod(srcRule(), func(ru *ipRule) { ru.ipProto = unix.IPPROTO_TCP }), false, false}, + {"shape-src-other-selectors", mod(srcRule(), func(ru *ipRule) { ru.other = true }), false, false}, + {"shape-other-priority", mod(srcRule(), func(ru *ipRule) { ru.priority = 5261 }), false, false}, + {"shape-suppress", supRule(), true, true}, + {"shape-suppress-no-invert", mod(supRule(), func(ru *ipRule) { ru.invert = false }), false, false}, + {"shape-suppress-other-mark", mod(supRule(), func(ru *ipRule) { ru.fwmark = 0x40000 }), false, false}, + {"shape-suppress-other-prefixlen", mod(supRule(), func(ru *ipRule) { ru.suppressPrefixlen = 8 }), false, false}, + {"shape-suppress-other-table", mod(supRule(), func(ru *ipRule) { ru.table = 254 }), false, false}, + {"shape-suppress-with-src", mod(supRule(), func(ru *ipRule) { ru.src = netip.MustParseAddr("2001:db8::5") }), false, false}, + } + for _, tt := range tests { + if got := isOurUnderlayRuleFor(tt.ru, base, true); got != tt.want { + t.Errorf("%s (kernel 4.10-4.16): got %v, want %v", tt.name, got, tt.want) + } + if got := isOurUnderlayRuleFor(tt.ru, base, false); got != tt.wantPre410 { + t.Errorf("%s (kernel < 4.10): got %v, want %v", tt.name, got, tt.wantPre410) + } + } +} + +// TestIPRuleMarshalRoundTrip checks that our rules survive encoding to the +// kernel's wire format and back, including uidrange's 32-bit fields. +func TestIPRuleMarshalRoundTrip(t *testing.T) { + r := &linuxRouter{routerFixed: routerFixed{ipPolicyPrefBase: defaultIPPolicyPrefBase}} + for _, u := range []underlayRule{ + {fam: v4, src: netip.MustParseAddr("192.168.1.5")}, + {fam: v6, src: netip.MustParseAddr("2001:db8::5")}, + {fam: v4}, + {fam: v6}, + } { + want := r.underlayIPRule(u) + b, err := want.marshal() + if err != nil { + t.Fatalf("%v: marshal: %v", u, err) + } + got, err := unmarshalIPRule(b) + if err != nil { + t.Fatalf("%v: unmarshal: %v", u, err) + } + want.hasProtocol = true // set by decoding when the protocol is present + if !reflect.DeepEqual(got, want) { + t.Errorf("%v: round trip:\n got %+v\nwant %+v", u, got, want) + } + if !isOurUnderlayRule(got, defaultIPPolicyPrefBase) { + t.Errorf("%v: decoded rule not recognized as ours", u) + } + } + // A kernel-format uidrange with values above 16 bits decodes intact. + big := r.underlayIPRule(underlayRule{fam: v4, src: netip.MustParseAddr("10.0.0.1")}) + big.uidRange = &[2]uint32{70000, 4000000000} + b, _ := big.marshal() + got, err := unmarshalIPRule(b) + if err != nil || got.uidRange == nil || *got.uidRange != [2]uint32{70000, 4000000000} { + t.Errorf("large uidrange round trip: %+v, %v", got.uidRange, err) + } +} + +// netnsChildEnv marks the re-executed test process running inside a private +// network namespace. +const netnsChildEnv = "TS_TEST_RPFILTER_NETNS_CHILD" + +// TestUnderlaySrcRulesKernel is an end-to-end test against the real kernel. +// It re-executes itself in a fresh network namespace (so nothing touches the +// host's rules), builds a minimal exit-node topology with strict rp_filter, +// and uses the kernel's own input route lookup (RTM_GETROUTE with iif, which +// runs fib_validate_source) to verify replies to tailscaled's sockets are no +// longer rejected as martians. It also checks outbound traffic still uses the +// exit node, rules follow address changes, and stale rules are swept. +func TestUnderlaySrcRulesKernel(t *testing.T) { + if os.Getenv(netnsChildEnv) == "" { + tstest.RequireRoot(t) + cmd := exec.Command(os.Args[0], "-test.run=^TestUnderlaySrcRulesKernel$", "-test.v") + cmd.Env = append(os.Environ(), netnsChildEnv+"=1") + cmd.SysProcAttr = &syscall.SysProcAttr{Cloneflags: unix.CLONE_NEWNET} + out, err := cmd.CombinedOutput() + if err != nil { + if errors.Is(err, syscall.EPERM) { + t.Skipf("can't create network namespace: %v", err) + } + t.Fatalf("netns child failed: %v\n%s", err, out) + } + t.Logf("netns child output:\n%s", out) + return + } + underlayRulesKernelChild(t) +} + +func underlayRulesKernelChild(t *testing.T) { + var ( + local4 = netip.MustParseAddr("172.31.0.44") + local6 = netip.MustParseAddr("2001:db8:1::44") + gw4 = netip.MustParseAddr("172.31.0.1") + gw6 = netip.MustParseAddr("2001:db8:1::1") + remote4 = netip.MustParseAddr("1.2.3.4") // exit node / DERP underlay + remote6 = netip.MustParseAddr("2001:db8:ffff::1234") // ditto, IPv6 + ) + mustSysctl := func(k, v string) { + t.Helper() + if err := writeSysctl(k, v); err != nil { + t.Fatal(err) + } + } + + // Underlay "NIC": a dummy interface with a default route in main. + lo, err := netlink.LinkByName("lo") + if err != nil { + t.Fatal(err) + } + if err := netlink.LinkSetUp(lo); err != nil { + t.Fatal(err) + } + ul := &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: "ul0"}} + if err := netlink.LinkAdd(ul); err != nil { + t.Skipf("can't create dummy link (no dummy module?): %v", err) + } + mustSysctl("net.ipv6.conf.ul0.disable_ipv6", "0") + mustSysctl("net.ipv6.conf.ul0.accept_dad", "0") + if err := netlink.LinkSetUp(ul); err != nil { + t.Fatal(err) + } + for _, p := range []string{"172.31.0.44/20", "2001:db8:1::44/64"} { + if err := netlink.AddrAdd(ul, &netlink.Addr{IPNet: netipx.PrefixIPNet(netip.MustParsePrefix(p))}); err != nil { + t.Fatal(err) + } + } + for _, gw := range []netip.Addr{gw4, gw6} { + if err := netlink.RouteAdd(&netlink.Route{LinkIndex: ul.Attrs().Index, Gw: gw.AsSlice()}); err != nil { + t.Fatalf("default via %v: %v", gw, err) + } + } + // A network behind this node (like a container bridge), which ipnlocal + // passes as a local (throw) route. + lan0 := &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: "lan0"}} + if err := netlink.LinkAdd(lan0); err != nil { + t.Fatal(err) + } + if err := netlink.LinkSetUp(lan0); err != nil { + t.Fatal(err) + } + if err := netlink.AddrAdd(lan0, &netlink.Addr{IPNet: netipx.PrefixIPNet(netip.MustParsePrefix("192.168.5.1/24"))}); err != nil { + t.Fatal(err) + } + mustSysctl("net.ipv4.ip_forward", "1") + // Strict reverse path filtering; src_valid_mark left at its default of 0. + for _, k := range []string{"all", "default", "ul0", "lan0"} { + mustSysctl("net.ipv4.conf."+k+".rp_filter", "1") + mustSysctl("net.ipv4.conf."+k+".src_valid_mark", "0") + } + + // A real router on a real TUN, with the real netmon. + tunDev := createTestTUN(t) + defer tunDev.Close() + bus := eventbus.New() + defer bus.Close() + mon, err := netmon.New(bus, logger.Discard) + if err != nil { + t.Fatal(err) + } + mon.Start() + defer mon.Close() + // Count rule restores so we can detect restore feedback loops. + var restores atomic.Int32 + logf := func(format string, args ...any) { + if strings.Contains(format, "deleted ip rules; restoring") { + restores.Add(1) + } + t.Logf(format, args...) + } + tunName, err := tunDev.Name() + if err != nil { + t.Fatal(err) + } + // Capture the router's timers instead of letting them run on the wall + // clock, so the assertions below can run them and wait for them rather + // than sleep. + var timers routerTimers + lr := newTestRouter(logf, tunName, mon, osCommandRunner{}, nil, bus, func(r *linuxRouter) { + r.nfr = NewFakeOS(t).nfr // netfilter isn't under test + r.interfaceV6Usable = func() bool { return true } + r.afterFunc = timers.afterFunc + }) + + // Stale rules from a "crashed" previous instance, to be swept by Up, + // and an administrator's look-alike rules at our priority and at the + // mwan3 base's priority, which must survive every sweep. + stale := []underlayRule{{fam: v4, src: netip.MustParseAddr("192.0.2.99")}, {fam: v4}} + for _, u := range stale { + if err := addIPRule(lr.underlayIPRule(u)); err != nil { + t.Fatal(err) + } + } + admin := []ipRule{ + {family: v4, priority: uint32(lr.underlaySrcRulePriority()), table: uint32(mainRouteTable.Num), src: netip.MustParseAddr("192.0.2.50"), suppressPrefixlen: -1}, + {family: v4, priority: uint32(mwan3IPPolicyPrefBase + underlaySrcRuleOffset), table: uint32(mainRouteTable.Num), src: netip.MustParseAddr("192.0.2.51"), suppressPrefixlen: -1}, + } + for _, ru := range admin { + if err := addIPRule(ru); err != nil { + t.Fatal(err) + } + } + // Leftovers installed with the ip command (TS_DEBUG_USE_IP_COMMAND), + // which must be swept too (review finding: they lacked the protocol). + for _, u := range []underlayRule{ + {fam: v4, src: netip.MustParseAddr("192.0.2.98")}, + {fam: v6}, + } { + if err := (osCommandRunner{}).run(lr.underlayIPCommandArgs("add", u)...); err != nil { + t.Fatalf("ip rule add for %v: %v", u, err) + } + } + checkAdminRules := func(when string) { + t.Helper() + rules, err := listIPRules(v4) + if err != nil { + t.Fatal(err) + } + for _, want := range admin { + if !slices.ContainsFunc(rules, func(ru ipRule) bool { return ru.priority == want.priority && ru.src == want.src }) { + t.Fatalf("%s: administrator's rule (pref %d from %v) was deleted", when, want.priority, want.src) + } + } + } + if err := lr.Up(); err != nil { + t.Fatal(err) + } + defer lr.Close() + if got, sup := kernelUnderlayRules(t, lr), kernelSuppressRules(t, lr); len(got) != 0 || len(sup) != 0 { + t.Fatalf("after Up, stale rules not swept: %v %v", got, sup) + } + checkAdminRules("after Up's sweep") + + // replyPasses reports whether a reply from remote4 to local4 arriving + // on ul0 passes the kernel's input route lookup and source validation. + replyPasses := func() error { + _, err := netlink.RouteGetWithOptions(local4.AsSlice(), &netlink.RouteGetOptions{Iif: "ul0", SrcAddr: remote4.AsSlice()}) + return err + } + // routeDev returns the output interface for dst from src (src may be + // invalid for an unbound socket). + routeDev := func(dst, src netip.Addr) string { + t.Helper() + var opts *netlink.RouteGetOptions + if src.IsValid() { + opts = &netlink.RouteGetOptions{SrcAddr: src.AsSlice()} + } + rs, err := netlink.RouteGetWithOptions(dst.AsSlice(), opts) + if err != nil || len(rs) == 0 { + return fmt.Sprintf("error(%v)", err) + } + l, err := netlink.LinkByIndex(rs[0].LinkIndex) + if err != nil { + return fmt.Sprintf("error(%v)", err) + } + return l.Attrs().Name + } + + cfg := &router.Config{ + LocalAddrs: mustCIDRs("100.101.102.104/32", "fd7a:115c:a1e0::104/128"), + Routes: mustCIDRs("100.64.0.0/10", "fd7a:115c:a1e0::/48", "0.0.0.0/0", "::/0"), + NetfilterMode: netfilterOff, + } + noExit := &router.Config{ + LocalAddrs: cfg.LocalAddrs, + Routes: mustCIDRs("100.64.0.0/10", "fd7a:115c:a1e0::/48"), + NetfilterMode: netfilterOff, + } + // With ExitNodeAllowLANAccess off, ipnlocal adds the LAN prefixes to + // Routes; with it on, to LocalRoutes (throw routes). + lan := mustCIDRs("172.31.0.0/20", "2001:db8:1::/64") + cfgLANBlocked := &router.Config{ + LocalAddrs: cfg.LocalAddrs, + Routes: append(slices.Clone(cfg.Routes), lan...), + LocalRoutes: mustCIDRs("192.168.5.0/24"), // the network behind us + NetfilterMode: netfilterOff, + } + cfgLANAllowed := &router.Config{ + LocalAddrs: cfg.LocalAddrs, + Routes: cfg.Routes, + LocalRoutes: append(slices.Clone(lan), netip.MustParsePrefix("192.168.5.0/24")), + NetfilterMode: netfilterOff, + } + + // Install the exit node routes with the address source disabled + // first, to prove the topology reproduces #3310. + setTestUnderlayAddrs(lr, nil) + if err := lr.Set(cfg); err != nil { + t.Fatal(err) + } + if got := kernelUnderlayRules(t, lr); len(got) != 0 { + t.Fatalf("unexpected rules with address source disabled: %v", got) + } + if err := replyPasses(); !errors.Is(err, unix.EINVAL) { + t.Fatalf("without underlay rules: reply validation = %v; want EINVAL (martian), topology doesn't reproduce #3310", err) + } + + // Now with the real netmon-backed address source. + lr.mu.Lock() + lr.underlayAddrs = lr.underlayAddrsFromNetMon + lr.mu.Unlock() + lr.onNetworkChange() + got := kernelUnderlayRules(t, lr) + if !slices.Contains(got, local4) || !slices.Contains(got, local6) { + t.Fatalf("underlay rules = %v; want %v and %v", got, local4, local6) + } + if sup := kernelSuppressRules(t, lr); !slices.Equal(sup, []addrFamily{v4, v6}) { + t.Fatalf("suppress rules for families %v; want v4 and v6", sup) + } + for _, a := range got { + if a == netip.MustParseAddr("100.101.102.104") || a == netip.MustParseAddr("fd7a:115c:a1e0::104") { + t.Fatalf("rule installed for Tailscale address %v", a) + } + } + if err := replyPasses(); err != nil { + t.Fatalf("with underlay rules: reply validation failed: %v", err) + } + // Outbound from unbound sockets and from the Tailscale address still + // goes via the exit node; only underlay-sourced lookups use main. + for _, tc := range []struct { + dst, src netip.Addr + want string + }{ + {remote4, netip.Addr{}, tunName}, + {remote4, netip.MustParseAddr("100.101.102.104"), tunName}, + {remote4, local4, "ul0"}, + {remote6, netip.Addr{}, tunName}, + {remote6, netip.MustParseAddr("fd7a:115c:a1e0::104"), tunName}, + {remote6, local6, "ul0"}, + } { + if got := routeDev(tc.dst, tc.src); got != tc.want { + t.Errorf("route to %v from %v: dev %s, want %s", tc.dst, tc.src, got, tc.want) + } + } + + // Tailnet peers keep reaching the underlay addresses through the + // tunnel: inbound passes strict rp_filter on the Tailscale interface, + // and replies go back through it (review finding: without the table + // 52 suppress rule, both went to the physical interface). + peer4 := netip.MustParseAddr("100.64.0.2") + peer6 := netip.MustParseAddr("fd7a:115c:a1e0::2") + for _, tc := range []struct{ peer, local netip.Addr }{{peer4, local4}, {peer6, local6}} { + if _, err := kernelRouteGet(tc.local, tc.peer, tunName, -1); err != nil { + t.Errorf("tailnet peer %v -> %v arriving on %s: rejected: %v", tc.peer, tc.local, tunName, err) + } + if got, err := kernelRouteGet(tc.peer, tc.local, "", 0); got != tunName { + t.Errorf("reply %v -> %v: dev %q (%v), want %s", tc.local, tc.peer, got, err, tunName) + } + } + + // Only lookups as uid 0 (which the kernel's reverse-path check uses) + // match the source rules: a non-root socket bound to an underlay + // address still goes through the exit node. + for _, tc := range []struct { + dst, src netip.Addr + uid int + want string + }{ + {remote4, local4, 0, "ul0"}, + {remote4, local4, 65534, tunName}, + {remote6, local6, 0, "ul0"}, + {remote6, local6, 65534, tunName}, + } { + if got, err := kernelRouteGet(tc.dst, tc.src, "", tc.uid); got != tc.want { + t.Errorf("route to %v from %v as uid %d: dev %q (%v), want %s", tc.dst, tc.src, tc.uid, got, err, tc.want) + } + } + + // LAN traffic with ExitNodeAllowLANAccess off stays blocked as before: + // table 52 claims the LAN prefix, so a LAN host's packet to an underlay + // address fails reverse-path validation and the reply would go into the + // tunnel. With it on (throw routes), the LAN works. + lanHost4 := netip.MustParseAddr("172.31.0.9") + if err := lr.Set(cfgLANBlocked); err != nil { + t.Fatal(err) + } + if _, err := kernelRouteGet(local4, lanHost4, "ul0", -1); !errors.Is(err, unix.EINVAL) { + t.Errorf("LAN blocked: LAN host packet passed reverse-path validation (%v); want EINVAL", err) + } + if got, _ := kernelRouteGet(lanHost4, local4, "", 0); got != tunName { + t.Errorf("LAN blocked: reply to LAN host via %q; want %s", got, tunName) + } + if err := replyPasses(); err != nil { + t.Errorf("LAN blocked: reply from exit node rejected: %v", err) + } + if err := lr.Set(cfgLANAllowed); err != nil { + t.Fatal(err) + } + if _, err := kernelRouteGet(local4, lanHost4, "ul0", -1); err != nil { + t.Errorf("LAN allowed: LAN host packet rejected: %v", err) + } + if got, _ := kernelRouteGet(lanHost4, local4, "", 0); got != "ul0" { + t.Errorf("LAN allowed: reply to LAN host via %q; want ul0", got) + } + if err := lr.Set(cfg); err != nil { + t.Fatal(err) + } + + // Known limitation, pinned: an accepted subnet route in table 52 that + // covers an Internet remote (a DERP or control server, say) is more + // specific than ::/0 or 0.0.0.0/0, so the suppress rule sends the + // reverse path lookup to the tunnel and the remote's replies fail + // strict rp_filter. + cfgSubnet := &router.Config{ + LocalAddrs: cfg.LocalAddrs, + Routes: append(slices.Clone(cfg.Routes), netip.PrefixFrom(remote4, 24).Masked()), + NetfilterMode: netfilterOff, + } + if err := lr.Set(cfgSubnet); err != nil { + t.Fatal(err) + } + if _, err := kernelRouteGet(local4, remote4, "ul0", -1); !errors.Is(err, unix.EINVAL) { + t.Errorf("subnet route covering %v: reply validation = %v; want EINVAL (known limitation; update the commit message if fixed)", remote4, err) + } + if err := lr.Set(cfg); err != nil { + t.Fatal(err) + } + if err := replyPasses(); err != nil { + t.Fatalf("after dropping the subnet route: reply validation failed: %v", err) + } + + // Address changes are followed via netmon without a Set. + newAddr := netip.MustParseAddr("172.31.0.45") + if err := netlink.AddrAdd(ul, &netlink.Addr{IPNet: netipx.PrefixIPNet(netip.PrefixFrom(newAddr, 20))}); err != nil { + t.Fatal(err) + } + waitFor(t, "rule for added address", func() bool { + return slices.Contains(kernelUnderlayRules(t, lr), newAddr) + }) + if err := netlink.AddrDel(ul, &netlink.Addr{IPNet: netipx.PrefixIPNet(netip.PrefixFrom(newAddr, 20))}); err != nil { + t.Fatal(err) + } + waitFor(t, "rule removal for deleted address", func() bool { + return !slices.Contains(kernelUnderlayRules(t, lr), newAddr) + }) + + // Same for a carrier-grade NAT underlay address, which is in the + // Tailscale CGNAT range but not on the Tailscale interface (review + // finding: netmon ignored it, so no rule appeared). + cgnat := netip.MustParsePrefix("100.72.1.1/24") + if err := netlink.AddrAdd(ul, &netlink.Addr{IPNet: netipx.PrefixIPNet(cgnat)}); err != nil { + t.Fatal(err) + } + waitFor(t, "rule for added CGNAT underlay address", func() bool { + return slices.Contains(kernelUnderlayRules(t, lr), cgnat.Addr()) + }) + if err := netlink.AddrDel(ul, &netlink.Addr{IPNet: netipx.PrefixIPNet(cgnat)}); err != nil { + t.Fatal(err) + } + waitFor(t, "rule removal for deleted CGNAT underlay address", func() bool { + return !slices.Contains(kernelUnderlayRules(t, lr), cgnat.Addr()) + }) + + // Our own add/remove churn above must not have triggered the + // "somebody deleted ip rules" restore path. quiesce runs everything + // the router scheduled and waits for every event the bus has for it, + // so a non-zero count is a real feedback loop, not work in flight. + quiesce(t, lr, bus, &timers) + if n := restores.Load(); n != 0 { + t.Fatalf("%d rule restores triggered by our own rule churn; want 0", n) + } + + // With a loose (or no) kernel rp_filter, the IPv4 rules aren't needed + // and aren't installed; IPv6 has no kernel rp_filter, so its stay. + // A sysctl write raises no event: the router's periodic recheck (run + // here by draining its timers, with no Set or network change) is what + // notices, in both directions. + for _, k := range []string{"all", "ul0", "lan0"} { + mustSysctl("net.ipv4.conf."+k+".rp_filter", "2") + } + waitForTimers(t, &timers, "IPv4 rules removed after rp_filter went loose", func() bool { + return !slices.ContainsFunc(kernelUnderlayRules(t, lr), netip.Addr.Is4) + }) + if got := kernelUnderlayRules(t, lr); !slices.Contains(got, local6) { + t.Fatalf("with loose rp_filter: rules for %v; want IPv6 only", got) + } + if got := kernelSuppressRules(t, lr); !slices.Equal(got, []addrFamily{v6}) { + t.Fatalf("with loose rp_filter: suppress rules for %v; want v6 only", got) + } + for _, k := range []string{"all", "ul0", "lan0"} { + mustSysctl("net.ipv4.conf."+k+".rp_filter", "1") + } + waitForTimers(t, &timers, "IPv4 rules back after rp_filter went strict", func() bool { + return slices.Contains(kernelUnderlayRules(t, lr), local4) + }) + if err := replyPasses(); err != nil { + t.Fatalf("back to strict rp_filter: reply validation failed: %v", err) + } + + // Exit node off: rules removed. + if err := lr.Set(noExit); err != nil { + t.Fatal(err) + } + if got, sup := kernelUnderlayRules(t, lr), kernelSuppressRules(t, lr); len(got) != 0 || len(sup) != 0 { + t.Fatalf("after exit node off: rules %v %v remain", got, sup) + } + + // Close removes them too. + if err := lr.Set(cfg); err != nil { + t.Fatal(err) + } + if len(kernelUnderlayRules(t, lr)) == 0 { + t.Fatal("rules not re-installed") + } + if err := lr.Close(); err != nil { + t.Fatal(err) + } + if got, sup := kernelUnderlayRules(t, lr), kernelSuppressRules(t, lr); len(got) != 0 || len(sup) != 0 { + t.Fatalf("after Close: rules %v %v remain", got, sup) + } + + // The cleanup tailscaled runs at every start removes our leftovers + // but not the administrator's rules, including the one at the mwan3 + // base's priority on this non-mwan3 host. + for _, u := range stale { + if err := addIPRule(lr.underlayIPRule(u)); err != nil { + t.Fatal(err) + } + } + removeUnderlaySrcRulesForCleanup(t.Logf) + if got, sup := kernelUnderlayRules(t, lr), kernelSuppressRules(t, lr); len(got) != 0 || len(sup) != 0 { + t.Fatalf("after cleanup: rules %v %v remain", got, sup) + } + checkAdminRules("after cleanup") +} + +// kernelUnderlayRules lists the source addresses of our underlay source +// rules currently installed in the kernel. +func kernelUnderlayRules(t *testing.T, lr *linuxRouter) []netip.Addr { + t.Helper() + var out []netip.Addr + for _, fam := range []addrFamily{v4, v6} { + rules, err := listIPRules(fam) + if err != nil { + t.Fatal(err) + } + for _, ru := range rules { + if isOurUnderlayRule(ru, lr.ipPolicyPrefBase) && int(ru.priority) == lr.underlaySrcRulePriority() && !slices.Contains(out, ru.src) { + out = append(out, ru.src) + } + } + } + slices.SortFunc(out, netip.Addr.Compare) + return out +} + +// kernelSuppressRules lists the families that have our table 52 suppress +// rule installed in the kernel. +func kernelSuppressRules(t *testing.T, lr *linuxRouter) []addrFamily { + t.Helper() + var out []addrFamily + for _, fam := range []addrFamily{v4, v6} { + rules, err := listIPRules(fam) + if err != nil { + t.Fatal(err) + } + for _, ru := range rules { + if isOurUnderlayRule(ru, lr.ipPolicyPrefBase) && int(ru.priority) == lr.underlaySuppressRulePriority() && !slices.Contains(out, fam) { + out = append(out, fam) + } + } + } + return out +} + +// kernelRouteGet asks the kernel, like 'ip route get', for the route to dst +// from src, returning the output interface name. If iif is set it does an +// input lookup as if the packet arrived on iif, which includes reverse-path +// source validation (EINVAL for a martian). If uid >= 0, the lookup is made +// as that uid. (The netlink package we use elsewhere can't set the uid.) +func kernelRouteGet(dst, src netip.Addr, iif string, uid int) (string, error) { + return kernelRouteGetPorts(dst, src, iif, uid, 0, 0, 0) +} + +// kernelRouteGetPorts is kernelRouteGet for a flow with the given IP +// protocol and ports (as 'ip route get ... ipproto P sport S dport D'). +func kernelRouteGetPorts(dst, src netip.Addr, iif string, uid int, ipProto uint8, sport, dport uint16) (string, error) { + hdr := make([]byte, 12) // struct rtmsg + if dst.Is4() { + hdr[0] = unix.AF_INET + } else { + hdr[0] = unix.AF_INET6 + } + hdr[1] = uint8(dst.BitLen()) + ae := mdnetlink.NewAttributeEncoder() + ae.Bytes(unix.RTA_DST, dst.AsSlice()) + if src.IsValid() { + hdr[2] = uint8(src.BitLen()) + ae.Bytes(unix.RTA_SRC, src.AsSlice()) + } + if iif != "" { + l, err := netlink.LinkByName(iif) + if err != nil { + return "", err + } + ae.Uint32(unix.RTA_IIF, uint32(l.Attrs().Index)) + } + if uid >= 0 { + ae.Uint32(unix.RTA_UID, uint32(uid)) + } + if ipProto != 0 { + ae.Uint8(unix.RTA_IP_PROTO, ipProto) + // Unlike rule port ranges, route query ports are __be16. + ae.Bytes(unix.RTA_SPORT, binary.BigEndian.AppendUint16(nil, sport)) + ae.Bytes(unix.RTA_DPORT, binary.BigEndian.AppendUint16(nil, dport)) + } + attrs, err := ae.Encode() + if err != nil { + return "", err + } + c, err := mdnetlink.Dial(unix.NETLINK_ROUTE, nil) + if err != nil { + return "", err + } + defer c.Close() + msgs, err := c.Execute(mdnetlink.Message{ + Header: mdnetlink.Header{Type: unix.RTM_GETROUTE, Flags: mdnetlink.Request}, + Data: append(hdr, attrs...), + }) + if err != nil { + return "", err + } + if len(msgs) == 0 || len(msgs[0].Data) < 12 { + return "", errors.New("no route returned") + } + ad, err := mdnetlink.NewAttributeDecoder(msgs[0].Data[12:]) + if err != nil { + return "", err + } + for ad.Next() { + if ad.Type() == unix.RTA_OIF { + l, err := netlink.LinkByIndex(int(ad.Uint32())) + if err != nil { + return "", err + } + return l.Attrs().Name, nil + } + } + return "", errors.New("route has no output interface") +} + +// waitFor polls cond until it holds. The interval is a poll of real kernel +// state, which nothing in this test can be notified about; it isn't a wait +// for one of the router's own timers, which routerTimers makes deterministic. +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + waitForPoll(t, what, cond) +} + +func waitForPoll(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(50 * time.Millisecond) + } +} + +// waitForTimers is waitFor for a condition that the router's own timers +// bring about: it drains them on every pass, so what the router scheduled +// runs instead of waiting out its delay on the wall clock. +func waitForTimers(t *testing.T, timers *routerTimers, what string, cond func() bool) { + t.Helper() + waitForPoll(t, what, func() bool { + timers.drain() + return cond() + }) +} + +// routerTimers records the timers a router schedules through +// routerFixed.afterFunc instead of arming them on the wall clock, so a test +// runs them exactly when it needs their effect. A func that reschedules +// itself (a recheck) stays queued for the next drain, which is what the +// router would do in production. +type routerTimers struct { + mu sync.Mutex + pending []func() +} + +func (rt *routerTimers) afterFunc(_ time.Duration, f func()) { + rt.mu.Lock() + defer rt.mu.Unlock() + rt.pending = append(rt.pending, f) +} + +// len reports how many funcs are scheduled and not yet run. +func (rt *routerTimers) len() int { + rt.mu.Lock() + defer rt.mu.Unlock() + return len(rt.pending) +} + +// drain runs every func scheduled so far, once each, on the calling +// goroutine. +func (rt *routerTimers) drain() { + rt.mu.Lock() + pending := rt.pending + rt.pending = nil + rt.mu.Unlock() + for _, f := range pending { + f() + } +} + +// quiesce settles lr before assertions that count what it did: it runs every +// timer lr has scheduled, and waits until the bus has delivered +// every event published so far to lr's callbacks. What remains in flight +// after that is only a netlink event the kernel hasn't delivered yet, which +// waitFor's polling bounds; the wall-clock sleeps this replaced bounded +// nothing and cost seconds apiece. +func quiesce(t *testing.T, lr *linuxRouter, bus *eventbus.Bus, timers *routerTimers) { + t.Helper() + dbg := bus.Debugger() + waitForTimers(t, timers, "router to quiesce", func() bool { + return len(dbg.PublishQueue()) == 0 && len(dbg.SubscribeQueue(lr.eventClient)) == 0 + }) +} + +func TestUnderlaySrcRulesKillSwitch(t *testing.T) { + // envknob.Setenv isn't synchronized with readers of the knob, so set + // it before the router (and its goroutines) exist, and reset it only + // after the router is closed. t.Cleanup runs last-registered first, + // so register the reset before creating the router. + envknob.Setenv("TS_DEBUG_DISABLE_RPFILTER_SRC_RULES", "true") + t.Cleanup(func() { envknob.Setenv("TS_DEBUG_DISABLE_RPFILTER_SRC_RULES", "") }) + + lr, fake := newTestLinuxRouter(t) + setTestUnderlayAddrs(lr, []netip.Addr{netip.MustParseAddr("192.168.1.5")}) + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake) + lr.onNetworkChange() + checkUnderlayRules(t, fake) +} + +func TestIsIPRuleNotFound(t *testing.T) { + // realErr runs a shell through the production osCommandRunner so the + // error has exactly the shape (wrapped *exec.ExitError plus iproute2's + // output) that 'ip rule del' failures have in production. + realErr := func(code int, msg string) error { + return osCommandRunner{}.run("sh", "-c", fmt.Sprintf("echo %q >&2; exit %d", msg, code)) + } + tests := []struct { + name string + err error + want bool + }{ + {"nil", nil, false}, + {"fake-not-found", errors.New("exitcode:2"), true}, + {"fake-not-found-old-iproute2", errors.New("exitcode:254"), true}, + {"real-not-found", realErr(2, "RTNETLINK answers: No such file or directory"), true}, + {"real-not-found-old-iproute2", realErr(254, "RTNETLINK answers: No such file or directory"), true}, + {"real-eperm", realErr(2, "RTNETLINK answers: Operation not permitted"), false}, + {"real-other-code", realErr(1, "RTNETLINK answers: No such file or directory"), false}, + {"fake-other-code", errors.New("exitcode:1"), false}, + {"unrelated", errors.New("boom"), false}, + } + for _, tt := range tests { + if got := isIPRuleNotFound(tt.err); got != tt.want { + t.Errorf("%s: got %v, want %v (err: %v)", tt.name, got, tt.want, tt.err) + } + } +} + +// TestUnderlaySrcRulesBeforeExitRoute checks that enabling an exit node +// installs the underlay rules before the default route, so there is no +// window in which replies to tailscaled's sockets are dropped, and that +// disabling it removes them after the route. +func TestUnderlaySrcRulesBeforeExitRoute(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + setTestUnderlayAddrs(lr, []netip.Addr{netip.MustParseAddr("192.168.1.5")}) + idx := func(prefix string) int { + t.Helper() + i := slices.IndexFunc(fake.cmds, func(c string) bool { return strings.HasPrefix(c, prefix) }) + if i < 0 { + t.Fatalf("no %q command; ran %q", prefix, fake.cmds) + } + return i + } + fake.cmds = nil + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatal(err) + } + sup := idx("ip -4 rule add pref 5255 ") + src := idx("ip -4 rule add pref 5260 ") + route := idx("ip route add 0.0.0.0/0 ") + if !(sup < src && src < route) { + t.Errorf("enable order: suppress rule %d, source rule %d, default route %d; want rules first, suppress before source", sup, src, route) + } + + fake.cmds = nil + if err := lr.Set(exitConfig("100.100.100.100/32")); err != nil { + t.Fatal(err) + } + route = idx("ip route del 0.0.0.0/0 ") + src = idx("ip -4 rule del pref 5260 ") + sup = idx("ip -4 rule del pref 5255 ") + if !(route < src && src < sup) { + t.Errorf("disable order: default route %d, source rule %d, suppress rule %d; want route first, source before suppress", route, src, sup) + } +} + +// TestUnderlaySrcRulesFailures covers the reconcile's failure paths: a +// failed suppress rule add skips its source rules without failing Set, a +// failed delete stays tracked and is retried, and "File exists" from the ip +// command counts as success. +func TestUnderlaySrcRulesFailures(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + setTestUnderlayAddrs(lr, []netip.Addr{netip.MustParseAddr("192.168.1.5")}) + realErr := func(code int, msg string) error { + return osCommandRunner{}.run("sh", "-c", fmt.Sprintf("echo %q >&2; exit %d", msg, code)) + } + + // Suppress rule add fails: no source rule either, and Set succeeds + // (the rules are best effort and mustn't mark the router unhealthy). + fake.failRun = func(args []string) error { + if strings.Contains(strings.Join(args, " "), "rule add pref 5255") { + return realErr(2, "RTNETLINK answers: Operation not permitted") + } + return nil + } + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatalf("Set failed because of an rp_filter rule: %v", err) + } + checkUnderlayRules(t, fake) + + // Once it works, the next reconcile installs both. + fake.failRun = nil + lr.onNetworkChange() + checkUnderlayRules(t, fake, "192.168.1.5") + + // Delete fails: the rule stays tracked and is retried. + fake.failRun = func(args []string) error { + if strings.Contains(strings.Join(args, " "), "rule del pref 5260") { + return realErr(2, "RTNETLINK answers: Operation not permitted") + } + return nil + } + if err := lr.Set(exitConfig("100.100.100.100/32")); err != nil { + t.Fatalf("Set failed because of an rp_filter rule: %v", err) + } + if !lr.underlaySrcRules.Contains(underlayRule{fam: v4, src: netip.MustParseAddr("192.168.1.5")}) { + t.Fatal("source rule whose delete failed is no longer tracked") + } + if got := underlaySrcRuleCount(fake, "-4"); got != 1 { + t.Fatalf("source rules after failed delete: %d, want 1", got) + } + // The suppress rule stays too: it's removed after its source rules. + fake.failRun = nil + lr.onNetworkChange() + checkUnderlayRules(t, fake) + + // "File exists" from 'ip rule add' (e.g. left by a previous run in + // ip command mode) counts as installed. + fake.failRun = func(args []string) error { + if strings.Contains(strings.Join(args, " "), "rule add pref 5260") { + return realErr(2, "RTNETLINK answers: File exists") + } + return nil + } + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatal(err) + } + if !lr.underlaySrcRules.Contains(underlayRule{fam: v4, src: netip.MustParseAddr("192.168.1.5")}) { + t.Error(`source rule not tracked after "File exists"`) + } +} + +// TestUnderlayRulesFollowInstalledRoutes checks that the rules stay while +// the exit node default route does, even when the config no longer has it +// because deleting it failed. +func TestUnderlayRulesFollowInstalledRoutes(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + setTestUnderlayAddrs(lr, []netip.Addr{netip.MustParseAddr("192.168.1.5")}) + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake, "192.168.1.5") + fake.failRun = func(args []string) error { + if strings.HasPrefix(strings.Join(args, " "), "ip route del 0.0.0.0/0") { + return errors.New("exitcode:1") + } + return nil + } + lr.Set(exitConfig("100.100.100.100/32")) // fails to remove the default route + if !lr.routes[netip.MustParsePrefix("0.0.0.0/0")] { + t.Fatal("test setup: default route delete didn't fail") + } + checkUnderlayRules(t, fake, "192.168.1.5") + fake.failRun = nil + if err := lr.Set(exitConfig("100.100.100.100/32")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake) +} + +// TestUnderlayRulesRemovedLastOnClose checks that Close removes the rules +// after taking the interface (and so the exit node default route) down. +func TestUnderlayRulesRemovedLastOnClose(t *testing.T) { + lr, fake := newTestLinuxRouter(t) + setTestUnderlayAddrs(lr, []netip.Addr{netip.MustParseAddr("192.168.1.5")}) + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatal(err) + } + fake.cmds = nil + if err := lr.Close(); err != nil { + t.Fatal(err) + } + down := slices.Index(fake.cmds, "ip link set dev tailscale0 down") + del := slices.IndexFunc(fake.cmds, func(c string) bool { return strings.HasPrefix(c, "ip -4 rule del pref 5260 ") }) + if down < 0 || del < 0 || del < down { + t.Errorf("Close: interface down at %d, rule removal at %d; want removal after down; ran %q", down, del, fake.cmds) + } + checkUnderlayRules(t, fake) +} + +// TestUnderlayAddrsLinkLocalLast is a regression test for the per-family cap +// filling up with the fe80:: addresses of many container veths and leaving +// another NIC's global addresses without rules. +func TestUnderlayAddrsLinkLocalLast(t *testing.T) { + ifc := func(name string) netmon.Interface { + return netmon.Interface{Interface: &net.Interface{Name: name, Flags: net.FlagUp}} + } + st := &netmon.State{ + DefaultRouteInterface: "eth0", + Interface: map[string]netmon.Interface{"eth0": ifc("eth0"), "eth1": ifc("eth1")}, + InterfaceIPs: map[string][]netip.Prefix{ + "eth0": {netip.MustParsePrefix("192.168.1.5/24"), netip.MustParsePrefix("2001:db8::5/64"), netip.MustParsePrefix("fe80::5/64")}, + "eth1": {netip.MustParsePrefix("10.0.0.5/24"), netip.MustParsePrefix("2001:db8:1::5/64"), netip.MustParsePrefix("fe80::6/64")}, + }, + } + ll := netip.MustParseAddr("fe80::1:0") + for i := range maxUnderlaySrcRulesPerFamily + 2 { + name := fmt.Sprintf("veth%03d", i) + st.Interface[name] = ifc(name) + st.InterfaceIPs[name] = []netip.Prefix{netip.PrefixFrom(ll, 64)} + ll = ll.Next() + } + lr, fake := newTestLinuxRouter(t) + setTestUnderlayAddrs(lr, underlayAddrsFromState(st, "tailscale0")) + if err := lr.Set(exitConfig("0.0.0.0/0", "::/0")); err != nil { + t.Fatal(err) + } + rules := underlayRules(fake) + for _, a := range []string{"192.168.1.5", "2001:db8::5", "fe80::5", "10.0.0.5", "2001:db8:1::5"} { + if w := wantUnderlayRules(a)[0]; !slices.ContainsFunc(rules, func(r string) bool { return strings.Contains(r, " from "+a+" ") }) { + t.Errorf("no rule for %s (want %q); veth link-locals crowded it out", a, w) + } + } + if n := underlaySrcRuleCount(fake, "-6"); n != maxUnderlaySrcRulesPerFamily { + t.Errorf("got %d IPv6 source rules, want the cap %d", n, maxUnderlaySrcRulesPerFamily) + } +} + +// TestUnderlayRulesNeedStrictRPFilter checks that the IPv4 rules are only +// installed while the kernel's IPv4 rp_filter is strict, so hosts without +// the problem don't get the behavior change for root sockets bound to an +// underlay address. IPv6 has no kernel rp_filter; its rules stay. +func TestUnderlayRulesNeedStrictRPFilter(t *testing.T) { + var strict atomic.Bool + lr, fake := newTestLinuxRouter(t, func(r *linuxRouter) { + r.rpFilterStrictV4 = strict.Load + }) + setTestUnderlayAddrs(lr, []netip.Addr{netip.MustParseAddr("192.168.1.5"), netip.MustParseAddr("2001:db8::5")}) + if err := lr.Set(exitConfig("0.0.0.0/0", "::/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake, "2001:db8::5") + strict.Store(true) + lr.onNetworkChange() + checkUnderlayRules(t, fake, "192.168.1.5", "2001:db8::5") + strict.Store(false) + lr.onNetworkChange() + checkUnderlayRules(t, fake, "2001:db8::5") +} + +// TestRPFilterRecheck checks that a change of the IPv4 rp_filter mode is +// picked up while an exit node is in use without any Set or network change, +// since a sysctl write raises no event (review finding: switching to strict +// mode left the IPv4 rules out until something unrelated happened). +func TestRPFilterRecheck(t *testing.T) { + var strict atomic.Bool + var timers routerTimers + var reads atomic.Int32 + lr, fake := newTestLinuxRouter(t, func(r *linuxRouter) { + r.rpFilterStrictV4 = func() bool { reads.Add(1); return strict.Load() } + r.afterFunc = timers.afterFunc + }) + setTestUnderlayAddrs(lr, []netip.Addr{netip.MustParseAddr("192.168.1.5"), netip.MustParseAddr("2001:db8::5")}) + + // No exit node: nothing to gate, so nothing is scheduled. + if err := lr.Set(exitConfig()); err != nil { + t.Fatal(err) + } + if n := timers.len(); n != 0 { + t.Fatalf("%d timers scheduled without an exit node; want 0", n) + } + + if err := lr.Set(exitConfig("0.0.0.0/0", "::/0")); err != nil { + t.Fatal(err) + } + checkUnderlayRules(t, fake, "2001:db8::5") + if n := timers.len(); n != 1 { + t.Fatalf("%d rechecks scheduled with an exit node; want 1", n) + } + + // Unchanged: the recheck only reads the sysctls and schedules the next. + reads.Store(0) + timers.drain() + checkUnderlayRules(t, fake, "2001:db8::5") + if n, r := timers.len(), reads.Load(); n != 1 || r != 1 { + t.Fatalf("after an unchanged recheck: %d timers, %d sysctl reads; want 1 and 1", n, r) + } + + // Strict, with no Set or network change: the next recheck adds the + // IPv4 rules, and loose again removes them. + strict.Store(true) + timers.drain() + checkUnderlayRules(t, fake, "192.168.1.5", "2001:db8::5") + strict.Store(false) + timers.drain() + checkUnderlayRules(t, fake, "2001:db8::5") + + // Exit node off: the pending recheck finds nothing to do and stops. + if err := lr.Set(exitConfig()); err != nil { + t.Fatal(err) + } + timers.drain() + if n := timers.len(); n != 0 { + t.Fatalf("%d timers still scheduled after the exit node went away; want 0", n) + } +} + +// TestRPFilterStrictV4FromSysctl checks the sysctl reading against the +// host: the result must match a direct computation of max(all, iface) == 1. +func TestRPFilterStrictV4FromSysctl(t *testing.T) { + lr, _ := newTestLinuxRouter(t) + read := func(dev string) int { + b, err := os.ReadFile("/proc/sys/net/ipv4/conf/" + dev + "/rp_filter") + if err != nil { + return 0 + } + v, _ := strconv.Atoi(strings.TrimSpace(string(b))) + return v + } + want := false + for name, ifc := range lr.netMon.InterfaceState().Interface { + if !ifc.IsUp() || ifc.IsLoopback() || strings.HasPrefix(name, "tailscale") { + continue + } + if max(read("all"), read(name)) == 1 { + want = true + } + } + if got := lr.rpFilterStrictV4FromSysctl(); got != want { + t.Errorf("rpFilterStrictV4FromSysctl = %v, want %v", got, want) + } +} + +// TestUnderlayErrorLoggedOnce checks that a rule that keeps failing to add +// is logged once, not on every network change. +func TestUnderlayErrorLoggedOnce(t *testing.T) { + var mu sync.Mutex + var warnings int + lr, fake := newTestLinuxRouter(t, func(r *linuxRouter) { + r.logf = func(format string, args ...any) { + if strings.Contains(format, "warning: rp_filter underlay rules") { + mu.Lock() + warnings++ + mu.Unlock() + } + } + }) + setTestUnderlayAddrs(lr, []netip.Addr{netip.MustParseAddr("192.168.1.5")}) + fake.failRun = func(args []string) error { + if strings.Contains(strings.Join(args, " "), "rule add pref 5255") { + return errors.New("exitcode:1") + } + return nil + } + if err := lr.Set(exitConfig("0.0.0.0/0")); err != nil { + t.Fatal(err) + } + for range 5 { + lr.onNetworkChange() + } + mu.Lock() + got := warnings + mu.Unlock() + if got != 1 { + t.Errorf("persistent failure logged %d times, want 1", got) + } + // Once it works, a new failure is logged again. + fake.failRun = nil + lr.onNetworkChange() + fake.failRun = func(args []string) error { + if strings.Contains(strings.Join(args, " "), "rule del pref 5260") { + return errors.New("exitcode:1") + } + return nil + } + lr.Set(exitConfig("100.100.100.100/32")) + mu.Lock() + got = warnings + mu.Unlock() + if got != 2 { + t.Errorf("after recovery and a new failure: logged %d times, want 2", got) + } +} diff --git a/wgengine/router/osrouter/rpfilter_netfilter_linux_test.go b/wgengine/router/osrouter/rpfilter_netfilter_linux_test.go new file mode 100644 index 000000000..f36cfba9a --- /dev/null +++ b/wgengine/router/osrouter/rpfilter_netfilter_linux_test.go @@ -0,0 +1,498 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !android + +package osrouter + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "net" + "net/netip" + "os" + "os/exec" + "regexp" + "slices" + "strconv" + "syscall" + "testing" + "time" + + "github.com/tailscale/netlink" + "go4.org/netipx" + "golang.org/x/sys/unix" + "tailscale.com/net/netmon" + "tailscale.com/tstest" + "tailscale.com/types/logger" + "tailscale.com/util/eventbus" + "tailscale.com/wgengine/router" +) + +// netfilterChildEnv marks a re-executed TestUnderlaySrcRulesNetfilter* +// process running inside a private network namespace. +const netfilterChildEnv = "TS_TEST_RPFILTER_NETFILTER_CHILD" + +// runNetfilterTest runs child in a private network namespace, as root, with +// the nft command available, re-executing the test binary for it. +func runNetfilterTest(t *testing.T, child func(*testing.T)) { + if os.Getenv(netfilterChildEnv) == "" { + tstest.RequireRoot(t) + if _, err := exec.LookPath("nft"); err != nil { + t.Skip("no nft command") + } + cmd := exec.Command(os.Args[0], "-test.run=^"+t.Name()+"$", "-test.v") + cmd.Env = append(os.Environ(), netfilterChildEnv+"=1") + cmd.SysProcAttr = &syscall.SysProcAttr{Cloneflags: unix.CLONE_NEWNET} + out, err := cmd.CombinedOutput() + if err != nil { + if errors.Is(err, syscall.EPERM) { + t.Skipf("can't create network namespace: %v", err) + } + t.Fatalf("netns child failed: %v\n%s", err, out) + } + t.Logf("netns child output:\n%s", out) + return + } + child(t) +} + +// TestUnderlaySrcRulesNetfilterV6 checks, with real packets against the real +// kernel, that the IPv6 underlay rules let replies to an underlay address +// through a netfilter reverse path filter while an exit node's ::/0 is in +// table 52. +// +// IPv6 has no kernel rp_filter, so IPv6's reverse path checks are netfilter +// ones, like firewalld's default IPv6_rpfilter: nftables "fib saddr . iif oif +// missing drop". That lookup runs through the ip rules as uid 0, so without +// our rules it finds table 52's ::/0 via the Tailscale interface, not the +// interface the reply came in on, and drops it. TestUnderlaySrcRulesKernel +// checks the IPv6 rules' routing decisions but stubs netfilter out; this is +// the end-to-end check for IPv6 that its replyPasses is for IPv4. +func TestUnderlaySrcRulesNetfilterV6(t *testing.T) { + runNetfilterTest(t, func(t *testing.T) { + e := newNetfilterRPFEnv(t, v6) + defer e.close() + + // The filter itself works: with only main's default route, a + // reply from the Internet arriving on ul0 is fine. + if !e.sendReply() { + t.Fatal("before using an exit node: reply dropped; the rpfilter rule is broken") + } + + // Exit node on, address source disabled so there are no underlay + // rules: the filter's lookup finds ::/0 via the Tailscale + // interface and the reply is dropped. This is the bug, for IPv6. + setTestUnderlayAddrs(e.lr, nil) + e.set(e.cfg) + if got := kernelUnderlayRules(t, e.lr); len(got) != 0 { + t.Fatalf("unexpected rules with address source disabled: %v", got) + } + if e.sendReply() { + t.Fatal("exit node on, no underlay rules: reply passed; the topology doesn't reproduce the bug for IPv6") + } + + // With the rules, the same reply passes. + e.useNetMonAddrs() + if !e.sendReply() { + t.Fatal("exit node on, with underlay rules: reply dropped") + } + + e.checkExitNodeOff() + }) +} + +// TestUnderlaySrcRulesNetfilterV4 is TestUnderlaySrcRulesNetfilterV6 for +// IPv4: the same netfilter reverse path check, with IPv4 replies. +// +// Unlike the IPv6 rules, the IPv4 rules are only installed while the +// kernel's IPv4 rp_filter is strict, so with a netfilter check alone (kernel +// rp_filter loose) the reply is still dropped. That is pinned here as a known +// limitation, so that a change to it is deliberate. Once rp_filter is strict +// the rules are installed (by the router's periodic recheck, with no Set or +// network change), and they satisfy the netfilter check and the kernel's +// strict rp_filter together. +func TestUnderlaySrcRulesNetfilterV4(t *testing.T) { + runNetfilterTest(t, func(t *testing.T) { + e := newNetfilterRPFEnv(t, v4) + defer e.close() + rpFilter := func(mode string) { + t.Helper() + for _, k := range []string{"all", "default", "ul0"} { + e.sysctl("net.ipv4.conf."+k+".rp_filter", mode) + } + } + + rpFilter("2") // loose: only the netfilter check is strict + if !e.sendReply() { + t.Fatal("before using an exit node: reply dropped; the rpfilter rule is broken") + } + + // Exit node on with a loose kernel rp_filter: no IPv4 rules, and + // the netfilter check drops the reply. + e.useNetMonAddrs() + e.set(e.cfg) + if got := kernelUnderlayRules(t, e.lr); slices.ContainsFunc(got, netip.Addr.Is4) { + t.Fatalf("IPv4 rules %v with loose rp_filter; want none", got) + } + if e.sendReply() { + t.Fatal("loose rp_filter, netfilter check: reply passed without IPv4 rules; " + + "if the IPv4 rules are now installed regardless of rp_filter, turn this into a pass and update the commit message") + } + + // Strict: the recheck installs the rules, and the reply passes + // both the netfilter check and the kernel's rp_filter. + rpFilter("1") + waitForTimers(t, &e.timers, "IPv4 rules after rp_filter went strict", func() bool { + return slices.Contains(kernelUnderlayRules(t, e.lr), e.local) + }) + if !e.sendReply() { + t.Fatal("strict rp_filter, with underlay rules: reply dropped") + } + + e.checkExitNodeOff() + }) +} + +// netfilterRPFEnv is a network namespace set up for the netfilter reverse +// path tests: an underlay NIC ul0 with one address of a family and a +// default route, an nftables reverse path filter on it, a socket on that +// address, and a router on a real TUN. Replies are injected with AF_PACKET +// on ulp, the other end of ul0's veth pair, so they arrive on ul0 as if from +// the network, and go through netfilter and the input path. +type netfilterRPFEnv struct { + t *testing.T + fam addrFamily + local, remote netip.Addr + lr *linuxRouter + timers routerTimers + cfg, noExit *router.Config + + pc *net.UDPConn + inj *ethInjector + seq int + closers []func() +} + +const ( + nfListenPort = 41641 // the reply's destination: one of our sockets + nfRemotePort = 3478 +) + +func newNetfilterRPFEnv(t *testing.T, fam addrFamily) *netfilterRPFEnv { + e := &netfilterRPFEnv{t: t, fam: fam} + var prefix netip.Prefix + var gw netip.Addr + if fam == v4 { + prefix = netip.MustParsePrefix("172.31.0.44/20") + gw = netip.MustParseAddr("172.31.0.1") + e.remote = netip.MustParseAddr("1.2.3.4") // exit node / DERP underlay + } else { + prefix = netip.MustParsePrefix("2001:db8:1::44/64") + gw = netip.MustParseAddr("2001:db8:1::1") + e.remote = netip.MustParseAddr("2001:db8:ffff::1234") + } + e.local = prefix.Addr() + + lo, err := netlink.LinkByName("lo") + if err != nil { + t.Fatal(err) + } + if err := netlink.LinkSetUp(lo); err != nil { + t.Fatal(err) + } + veth := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: "ul0"}, PeerName: "ulp"} + if err := netlink.LinkAdd(veth); err != nil { + t.Skipf("can't create veth pair (no veth module?): %v", err) + } + ul, err := netlink.LinkByName("ul0") + if err != nil { + t.Fatal(err) + } + ulp, err := netlink.LinkByName("ulp") + if err != nil { + t.Fatal(err) + } + // ulp is only a wire: keep it out of IPv6 (and so out of netmon's + // underlay addresses and the routing table). It never gets an IPv4 + // address. + e.sysctl("net.ipv6.conf.ulp.disable_ipv6", "1") + e.sysctl("net.ipv6.conf.ul0.disable_ipv6", "0") + e.sysctl("net.ipv6.conf.ul0.accept_dad", "0") + for _, l := range []netlink.Link{ul, ulp} { + if err := netlink.LinkSetUp(l); err != nil { + t.Fatal(err) + } + } + if err := netlink.AddrAdd(ul, &netlink.Addr{IPNet: netipx.PrefixIPNet(prefix)}); err != nil { + t.Fatal(err) + } + if err := netlink.RouteAdd(&netlink.Route{LinkIndex: ul.Attrs().Index, Gw: gw.AsSlice()}); err != nil { + t.Fatalf("default via %v: %v", gw, err) + } + + // A reverse path filter like firewalld's IPv6_rpfilter, for this + // family, scoped to the test's replies. The second counter shows the + // packets that got through it. + nfproto := map[addrFamily]string{v4: "ipv4", v6: "ipv6"}[fam] + cmd := exec.Command("nft", "-f", "-") + cmd.Stdin = bytes.NewReader(fmt.Appendf(nil, ` +table inet rpftest { + chain pre { + type filter hook prerouting priority raw; policy accept; + iifname "ul0" meta nfproto %[1]s udp dport %[2]d fib saddr . iif oif missing counter drop comment "rpf-drop" + iifname "ul0" meta nfproto %[1]s udp dport %[2]d counter comment "rpf-pass" + } +} +`, nfproto, nfListenPort)) + if out, err := cmd.CombinedOutput(); err != nil { + t.Skipf("can't install nftables fib rule (no nf_tables / nft_fib?): %v\n%s", err, out) + } + + network := map[addrFamily]string{v4: "udp4", v6: "udp6"}[fam] + e.pc, err = net.ListenUDP(network, &net.UDPAddr{IP: e.local.AsSlice(), Port: nfListenPort}) + if err != nil { + t.Fatal(err) + } + e.closers = append(e.closers, func() { e.pc.Close() }) + e.inj, err = newEthInjector(ulp, ul.Attrs().HardwareAddr) + if err != nil { + t.Fatal(err) + } + e.closers = append(e.closers, func() { e.inj.Close() }) + + tunDev := createTestTUN(t) + e.closers = append(e.closers, func() { tunDev.Close() }) + bus := eventbus.New() + e.closers = append(e.closers, bus.Close) + mon, err := netmon.New(bus, logger.Discard) + if err != nil { + t.Fatal(err) + } + mon.Start() + e.closers = append(e.closers, func() { mon.Close() }) + tunName, err := tunDev.Name() + if err != nil { + t.Fatal(err) + } + e.lr = newTestRouter(t.Logf, tunName, mon, osCommandRunner{}, nil, bus, func(r *linuxRouter) { + r.nfr = NewFakeOS(t).nfr // the router's own netfilter isn't under test + r.interfaceV6Usable = func() bool { return true } + r.afterFunc = e.timers.afterFunc + }) + if err := e.lr.Up(); err != nil { + t.Fatal(err) + } + e.closers = append(e.closers, func() { e.lr.Close() }) + // The address source stays off until useNetMonAddrs. + setTestUnderlayAddrs(e.lr, nil) + + e.cfg = &router.Config{ + LocalAddrs: mustCIDRs("100.101.102.104/32", "fd7a:115c:a1e0::104/128"), + Routes: mustCIDRs("100.64.0.0/10", "fd7a:115c:a1e0::/48", "0.0.0.0/0", "::/0"), + NetfilterMode: netfilterOff, + } + e.noExit = &router.Config{ + LocalAddrs: e.cfg.LocalAddrs, + Routes: mustCIDRs("100.64.0.0/10", "fd7a:115c:a1e0::/48"), + NetfilterMode: netfilterOff, + } + return e +} + +func (e *netfilterRPFEnv) close() { + for _, f := range slices.Backward(e.closers) { + f() + } +} + +func (e *netfilterRPFEnv) sysctl(k, v string) { + e.t.Helper() + if err := writeSysctl(k, v); err != nil { + e.t.Fatal(err) + } +} + +func (e *netfilterRPFEnv) set(cfg *router.Config) { + e.t.Helper() + if err := e.lr.Set(cfg); err != nil { + e.t.Fatal(err) + } +} + +// useNetMonAddrs switches the router's address source to the real netmon +// state and reconciles, which installs rules for ul0's address if they're +// wanted. +func (e *netfilterRPFEnv) useNetMonAddrs() { + e.lr.mu.Lock() + e.lr.underlayAddrs = e.lr.underlayAddrsFromNetMon + e.lr.mu.Unlock() + e.lr.onNetworkChange() +} + +func (e *netfilterRPFEnv) counter(name string) int { + e.t.Helper() + out, err := exec.Command("nft", "list", "chain", "inet", "rpftest", "pre").CombinedOutput() + if err != nil { + e.t.Fatalf("nft list: %v\n%s", err, out) + } + m := regexp.MustCompile(`counter packets (\d+) bytes \d+ .*comment "` + name + `"`).FindSubmatch(out) + if m == nil { + e.t.Fatalf("no %q counter in:\n%s", name, out) + } + n, _ := strconv.Atoi(string(m[1])) + return n +} + +// sendReply injects a reply from e.remote to our socket and reports whether +// netfilter passed it or dropped it, having waited for the kernel to account +// for it one way or the other. A passed reply must also reach the socket. +func (e *netfilterRPFEnv) sendReply() (passed bool) { + t := e.t + t.Helper() + e.seq++ + drops, passes := e.counter("rpf-drop"), e.counter("rpf-pass") + payload := fmt.Appendf(nil, "reply %d", e.seq) + if err := e.inj.sendUDP(e.remote, e.local, nfRemotePort, nfListenPort, payload); err != nil { + t.Fatal(err) + } + waitFor(t, fmt.Sprintf("reply %d to be filtered", e.seq), func() bool { + return e.counter("rpf-drop") > drops || e.counter("rpf-pass") > passes + }) + if e.counter("rpf-drop") > drops { + return false + } + e.pc.SetReadDeadline(time.Now().Add(5 * time.Second)) + buf := make([]byte, 64) + n, from, err := e.pc.ReadFromUDPAddrPort(buf) + if err != nil { + t.Fatalf("reply %d passed netfilter but wasn't delivered: %v", e.seq, err) + } + if got := string(buf[:n]); got != string(payload) || from.Addr().Unmap() != e.remote { + t.Fatalf("socket got %q from %v; want %q from %v", got, from, payload, e.remote) + } + return true +} + +// checkExitNodeOff checks that with the exit node off the rules go, and with +// table 52 no longer claiming the default route the reply still passes. +func (e *netfilterRPFEnv) checkExitNodeOff() { + t := e.t + t.Helper() + e.set(e.noExit) + if got := kernelUnderlayRules(t, e.lr); len(got) != 0 { + t.Fatalf("after exit node off: rules %v remain", got) + } + if !e.sendReply() { + t.Fatal("after exit node off: reply dropped") + } +} + +// ethInjector writes Ethernet frames out of a link with AF_PACKET. Written +// to one end of a veth pair, they arrive on the other end as received +// traffic, going through netfilter and the input path like a packet from +// the network. +type ethInjector struct { + fd int + srcMAC net.HardwareAddr + dstMAC net.HardwareAddr + ifidx int +} + +func newEthInjector(out netlink.Link, dstMAC net.HardwareAddr) (*ethInjector, error) { + fd, err := unix.Socket(unix.AF_PACKET, unix.SOCK_RAW, 0) + if err != nil { + return nil, fmt.Errorf("AF_PACKET socket: %w", err) + } + return ðInjector{ + fd: fd, + srcMAC: out.Attrs().HardwareAddr, + dstMAC: dstMAC, + ifidx: out.Attrs().Index, + }, nil +} + +func (e *ethInjector) Close() error { return unix.Close(e.fd) } + +// sendUDP injects a UDP packet from src:sport to dst:dport, over IPv4 or +// IPv6 according to the addresses. +func (e *ethInjector) sendUDP(src, dst netip.Addr, sport, dport uint16, payload []byte) error { + const ethLen, udpLen = 14, 8 + ipLen, etherType := 40, uint16(unix.ETH_P_IPV6) + if src.Is4() { + ipLen, etherType = 20, unix.ETH_P_IP + } + frame := make([]byte, ethLen+ipLen+udpLen+len(payload)) + + copy(frame[0:6], e.dstMAC) + copy(frame[6:12], e.srcMAC) + binary.BigEndian.PutUint16(frame[12:14], etherType) + + ip, udp := frame[ethLen:ethLen+ipLen], frame[ethLen+ipLen:] + binary.BigEndian.PutUint16(udp[0:2], sport) + binary.BigEndian.PutUint16(udp[2:4], dport) + binary.BigEndian.PutUint16(udp[4:6], uint16(udpLen+len(payload))) + copy(udp[udpLen:], payload) + + if src.Is4() { + ip[0] = 4<<4 | 5 // version 4, 20-byte header + binary.BigEndian.PutUint16(ip[2:4], uint16(ipLen+udpLen+len(payload))) + ip[8] = 64 // TTL + ip[9] = unix.IPPROTO_UDP + s4, d4 := src.As4(), dst.As4() + copy(ip[12:16], s4[:]) + copy(ip[16:20], d4[:]) + binary.BigEndian.PutUint16(ip[10:12], inetChecksum(0, ip)) + // The UDP checksum is optional for IPv4; zero means none. + } else { + ip[0] = 6 << 4 // version 6, traffic class 0, flow label 0 + binary.BigEndian.PutUint16(ip[4:6], uint16(udpLen+len(payload))) + ip[6] = unix.IPPROTO_UDP + ip[7] = 64 // hop limit + s16, d16 := src.As16(), dst.As16() + copy(ip[8:24], s16[:]) + copy(ip[24:40], d16[:]) + // Mandatory for IPv6 (RFC 8200 section 8.1), over a + // pseudo-header of the addresses, length and protocol. + sum := inetSum(inetSum(0, s16[:]), d16[:]) + uint32(len(udp)) + unix.IPPROTO_UDP + cs := inetChecksum(sum, udp) + if cs == 0 { + cs = 0xffff // 0 means "no checksum", which IPv6 forbids + } + binary.BigEndian.PutUint16(udp[6:8], cs) + } + + sa := &unix.SockaddrLinklayer{ + Ifindex: e.ifidx, + Protocol: htons(etherType), + Halen: 6, + } + copy(sa.Addr[:], e.dstMAC) + return unix.Sendto(e.fd, frame, 0, sa) +} + +// inetSum adds b to the running one's complement sum, as 16-bit words. +func inetSum(sum uint32, b []byte) uint32 { + for len(b) >= 2 { + sum += uint32(binary.BigEndian.Uint16(b)) + b = b[2:] + } + if len(b) == 1 { + sum += uint32(b[0]) << 8 + } + return sum +} + +// inetChecksum returns the Internet checksum (RFC 1071) of b, starting from +// the partial sum sum. +func inetChecksum(sum uint32, b []byte) uint16 { + sum = inetSum(sum, b) + for sum>>16 != 0 { + sum = sum&0xffff + sum>>16 + } + return ^uint16(sum) +} + +func htons(v uint16) uint16 { return v<<8 | v>>8 }