wgengine/router/osrouter,util/linuxfw: add rp_filter source rules

With an exit node, table 52's default route makes strict reverse path
filtering drop replies to tailscaled's own sockets: the kernel checks a
reply's source with a reverse lookup, as uid 0 from the underlay
address, which finds the default route via the Tailscale interface
rather than the one the reply arrived on (#3310). The reverted
src_valid_mark=1 workaround fixed that for the whole host and broke
every other fwmark user (#19796).

Instead, while 0.0.0.0/0 or ::/0 is routed into table 52, install per
address family:

	pref base+55: not fwmark <bypass> lookup 52 suppress_prefixlength 0
	pref base+60: from A uidrange 0-0 lookup main

with a base+60 rule for each underlay address A. base+60 sends the
reverse lookup to the main table, and base+55 keeps table 52's tailnet
and LAN routes ahead of it, so tailnet peers still reach A through the
tunnel and ExitNodeAllowLANAccess=false still blocks the LAN. IPv6,
which has no kernel rp_filter, gets its rules whenever ::/0 is routed.
The IPv4 rules only exist while rp_filter is strict somewhere, re-read
every 10s while an exit node is in use since a sysctl write raises no
event.

The rules are added before the exit node's default route and removed
after it is gone, and in Close. They follow netmon's interface state,
for at most 128 addresses per family and never for our own Tailscale
addresses. They carry rule protocol 52; Up and tailscaled's startup
cleanup sweep away any a previous instance left. They don't use
netfilter, so they work in every netfilter mode.
TS_DEBUG_DISABLE_RPFILTER_SRC_RULES=true turns them off. The router
ignores deletions at their priorities instead of restoring the base
rules, since those deletions are its own.

linuxfw documents that the connmark rules only help reverse path checks
that are mark-aware.

Follow-ups cover replies from LAN peers to the magicsock port with LAN
access off, and rules other processes delete. Not covered, and pinned
by tests: remotes that a more specific table 52 route covers, such as
an accepted subnet route, and IPv4 netfilter reverse path checks
without a strict kernel rp_filter. Nor are hosts whose underlay default
route is not in main.

Behavior change: while an exit node is in use, sockets of root
processes bound to an underlay address, and packets the kernel itself
sends from one, leave by the physical interface rather than the exit
node; non-root processes are unaffected. That holds for IPv6 on every
host and for IPv4 where rp_filter is strict. Hosts that ran a release
with the reverted change keep src_valid_mark=1 until reboot or reset.

RELNOTE: Linux: exit nodes no longer set src_valid_mark=1; root sockets
bound to a physical interface's address now bypass the exit node.

Updates #3310
Updates #19796

Signed-off-by: Mike O'Driscoll <[email protected]>
This commit is contained in:
Mike O'Driscoll committed 2026-11-23 11:39:16 -05:00
1 parent 7a263537c7
commit 1aad7a1386
8 files changed
+3338 -20

No files matched your search

+5 -3
View File
@@ -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() {
+7 -4
View File
@@ -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
+260
View File
@@ -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
}
+89 -3
View File
@@ -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 <addr> 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
+113 -10
View File
@@ -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 <routeDef> 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() {
+821
View File
@@ -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=<remote peer/DERP/control IP> and
// saddr=<our underlay address>. 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
//
// <base+55>: not fwmark <bypass> lookup 52 suppress_prefixlength 0
// <base+60>: 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 <src> lookup <table>" 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/<if>/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
}
File diff suppressed because it is too large. Load diff
@@ -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 &ethInjector{
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 }