mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-06 23:36:34 +09:00
wgengine/router/osrouter: repair rp_filter rules other processes delete
Other software deletes ip rules it doesn't own: systemd-networkd with ManageForeignRoutingPolicyRules, or an administrator's "ip rule flush". Deletions at the rp_filter underlay rule priorities are mostly the router's own, so it ignored them, and an underlay rule deleted by someone else stayed missing until the next change to the rules. On a deletion at an underlay priority, look for tracked rules missing from the kernel 250ms later and re-add them. That only ever adds, so it can't feed back into itself. Repairs are rate limited like the base rule restore, but only repairs that find something missing count, so the router's own churn doesn't use up the budget. A family whose rules can't be listed only has its own rules counted as missing. When the base rules are restored after a flush, the underlay rules are re-added too, and source and port rules left without their family's suppress rule by a failed re-add are removed rather than left to cut tailnet traffic to the underlay addresses. Repairs need netlink. Updates #3310 Signed-off-by: Mike O'Driscoll <mikeo@tailscale.com>
This commit is contained in:
5 files changed
+571
-15
No files matched your search
@@ -126,6 +126,10 @@ type linuxRouter struct {
|
||||
// before subscribeEvents, or later with mu held. Read with mu held.
|
||||
underlayAddrs func() []netip.Addr
|
||||
|
||||
// underlaySrcRepairPending is whether a repair of externally deleted
|
||||
// underlay source rules is scheduled.
|
||||
underlaySrcRepairPending atomic.Bool
|
||||
|
||||
// netChangePending is whether an underlay source rule reconcile for a
|
||||
// network change is queued but hasn't yet acquired mu.
|
||||
netChangePending atomic.Bool
|
||||
@@ -185,7 +189,7 @@ type routerFixed struct {
|
||||
rpFilterStrictV4 func() bool
|
||||
|
||||
// afterFunc, if non-nil, replaces time.AfterFunc for the router's rule
|
||||
// restore and rp_filter recheck timers. For tests.
|
||||
// restore and repair timers. For tests.
|
||||
afterFunc func(time.Duration, func())
|
||||
|
||||
// ipRuleAvailable is whether the kernel was built with
|
||||
@@ -196,9 +200,11 @@ type routerFixed struct {
|
||||
// installed. Zero means defaultIPPolicyPrefBase.
|
||||
ipPolicyPrefBase int
|
||||
|
||||
// ipRuleFixLimiter rate limits restores of the base ip rules, so we
|
||||
// ipRuleFixLimiter rate limits restores of the base ip rules, and
|
||||
// underlayRepairLimiter repairs of the rp_filter underlay rules, so we
|
||||
// don't get into a high-speed fight with another process deleting them.
|
||||
ipRuleFixLimiter *rate.Limiter
|
||||
ipRuleFixLimiter *rate.Limiter
|
||||
underlayRepairLimiter *rate.Limiter
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -247,6 +253,9 @@ func newLinuxRouter(fixed routerFixed) *linuxRouter {
|
||||
if fixed.ipRuleFixLimiter == nil {
|
||||
fixed.ipRuleFixLimiter = rate.NewLimiter(rate.Every(5*time.Second), 10)
|
||||
}
|
||||
if fixed.underlayRepairLimiter == nil {
|
||||
fixed.underlayRepairLimiter = rate.NewLimiter(rate.Every(5*time.Second), 10)
|
||||
}
|
||||
r := &linuxRouter{
|
||||
routerFixed: fixed,
|
||||
netfilterMode: netfilterOff,
|
||||
@@ -507,9 +516,13 @@ func (r *linuxRouter) onIPRuleDeleted(family uint8, table uint8, priority uint32
|
||||
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.
|
||||
// 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). Instead do an
|
||||
// add-only repair in case another process deleted one of ours.
|
||||
// An external flush (systemd-networkd) also deletes the base
|
||||
// rules, whose events run the full restore below.
|
||||
r.scheduleUnderlaySrcRuleRepair()
|
||||
return
|
||||
}
|
||||
if r.ruleRestorePending.Swap(true) {
|
||||
@@ -528,6 +541,7 @@ func (r *linuxRouter) onIPRuleDeleted(family uint8, table uint8, priority uint32
|
||||
if r.ruleRestorePending.Swap(false) && !r.closed.Load() {
|
||||
r.logf("somebody (likely systemd-networkd) deleted ip rules; restoring Tailscale's")
|
||||
r.justAddIPRules()
|
||||
r.restoreUnderlaySrcRules()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2294,8 +2294,8 @@ func TestSubscribeEventsAfterInit(t *testing.T) {
|
||||
default:
|
||||
}
|
||||
// At the underlay source rule priority, onIPRuleDeleted
|
||||
// returns early (those deletions are our own), without
|
||||
// running ip commands on the fake OS.
|
||||
// takes the add-only repair path, which never runs ip
|
||||
// commands on the fake OS.
|
||||
ruleDeleted.Publish(netmon.RuleDeleted{
|
||||
Table: uint8(mainRouteTable.Num),
|
||||
Priority: uint32(defaultIPPolicyPrefBase + underlaySrcRuleOffset),
|
||||
|
||||
@@ -565,6 +565,21 @@ func (r *linuxRouter) updateUnderlaySrcRulesLocked(addOnly bool) error {
|
||||
r.underlaySrcRules.Add(u)
|
||||
added++
|
||||
}
|
||||
// Never leave source or port rules installed without their family's
|
||||
// suppress rule (for example after its re-add failed in a repair):
|
||||
// they'd send tailnet traffic to the underlay addresses out the
|
||||
// physical interface. Even in addOnly mode.
|
||||
for _, u := range slices.Backward(slices.SortedFunc(r.underlaySrcRules.All(), compareUnderlayRules)) {
|
||||
if u.isSuppress() || r.underlaySrcRules.Contains(underlayRule{fam: u.fam}) {
|
||||
continue
|
||||
}
|
||||
if err := r.delUnderlayRule(u); err != nil {
|
||||
errs = append(errs, fmt.Errorf("deleting rp_filter %v without its suppress rule: %w", u, err))
|
||||
continue
|
||||
}
|
||||
r.underlaySrcRules.Delete(u)
|
||||
removed++
|
||||
}
|
||||
if added > 0 || removed > 0 {
|
||||
r.logf("rp_filter underlay rules: +%d -%d, now %d", added, removed, len(r.underlaySrcRules))
|
||||
}
|
||||
@@ -633,6 +648,34 @@ func (r *linuxRouter) removeUnderlaySrcRulesLocked() error {
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// restoreUnderlaySrcRules re-installs underlay rules after some other
|
||||
// process (typically systemd-networkd) deleted ip rules in our priority range.
|
||||
// We can't tell which of ours were deleted, so re-add everything we track.
|
||||
//
|
||||
// With netlink the re-add is idempotent (EEXIST is ignored), so this never
|
||||
// deletes anything: deleting would emit RTM_DELRULE and feed back into
|
||||
// onIPRuleDeleted. The ip command can't distinguish "exists" reliably
|
||||
// enough, so there we delete and re-add; deletions at our priorities only
|
||||
// schedule an add-only repair (which needs netlink, so not with the tests'
|
||||
// fake runner), so that doesn't loop either.
|
||||
func (r *linuxRouter) restoreUnderlaySrcRules() {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.closed.Load() || !r.ipRuleAvailable {
|
||||
return
|
||||
}
|
||||
if r.underlayNetlinkUsable() {
|
||||
r.reAddUnderlaySrcRulesLocked(slices.Collect(r.underlaySrcRules.All()))
|
||||
} else {
|
||||
if err := r.removeUnderlaySrcRulesLocked(); err != nil {
|
||||
r.logf("restoring rp_filter underlay rules: %v", err)
|
||||
}
|
||||
}
|
||||
if err := r.updateUnderlaySrcRulesLocked(false); err != nil {
|
||||
r.logf("restoring rp_filter underlay rules: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -642,6 +685,171 @@ func (r *linuxRouter) underlayNetlinkUsable() bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
// reAddUnderlaySrcRulesLocked re-adds, via netlink, the given tracked
|
||||
// underlay rules, suppress rules first. It never deletes, so it emits no
|
||||
// RTM_DELRULE and can't feed back into onIPRuleDeleted. Rules that already
|
||||
// exist are left alone (EEXIST). It returns how many rules were actually
|
||||
// missing, and whether any re-add failed (the failed rules are no longer
|
||||
// tracked).
|
||||
//
|
||||
// r.mu must be held.
|
||||
func (r *linuxRouter) reAddUnderlaySrcRulesLocked(rules []underlayRule) (n int, failed bool) {
|
||||
slices.SortFunc(rules, compareUnderlayRules)
|
||||
for _, u := range rules {
|
||||
err := addIPRule(r.underlayIPRule(u))
|
||||
switch {
|
||||
case err == nil:
|
||||
n++
|
||||
case errors.Is(err, errEEXIST):
|
||||
default:
|
||||
r.logf("restoring rp_filter %v: %v", u, err)
|
||||
// Forget it so the next reconcile retries the add.
|
||||
r.underlaySrcRules.Delete(u)
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
return n, failed
|
||||
}
|
||||
|
||||
// missingUnderlayRulesLocked returns the tracked underlay rules that aren't
|
||||
// in the kernel.
|
||||
//
|
||||
// r.mu must be held.
|
||||
func (r *linuxRouter) missingUnderlayRulesLocked() []underlayRule {
|
||||
return r.missingUnderlayRules(listIPRules)
|
||||
}
|
||||
|
||||
// missingUnderlayRules is missingUnderlayRulesLocked with the kernel's rule
|
||||
// listing passed in. It lists only the families it tracks rules for. If it
|
||||
// can't list a family's rules, it reports that family's tracked rules as
|
||||
// missing (re-adding is idempotent), but not the other family's: a host
|
||||
// whose IPv6 rule dump fails (ipv6.disable=1) mustn't have every IPv4 repair
|
||||
// re-add every rule and spend a rate limit token doing it.
|
||||
func (r *linuxRouter) missingUnderlayRules(list func(addrFamily) ([]ipRule, error)) []underlayRule {
|
||||
var missing []underlayRule
|
||||
for _, fam := range []addrFamily{v4, v6} {
|
||||
var tracked []underlayRule
|
||||
for u := range r.underlaySrcRules {
|
||||
if u.fam == fam {
|
||||
tracked = append(tracked, u)
|
||||
}
|
||||
}
|
||||
if len(tracked) == 0 {
|
||||
continue
|
||||
}
|
||||
rules, err := list(fam)
|
||||
if err != nil {
|
||||
missing = append(missing, tracked...)
|
||||
continue
|
||||
}
|
||||
installed := set.Set[underlayRule]{}
|
||||
for _, ru := range rules {
|
||||
if u, ok := r.underlayRuleOf(ru); ok {
|
||||
installed.Add(u)
|
||||
}
|
||||
}
|
||||
for _, u := range tracked {
|
||||
if !installed.Contains(u) {
|
||||
missing = append(missing, u)
|
||||
}
|
||||
}
|
||||
}
|
||||
return missing
|
||||
}
|
||||
|
||||
// underlayRuleOf returns which of our underlay rules the kernel rule ru is,
|
||||
// if any.
|
||||
func (r *linuxRouter) underlayRuleOf(ru ipRule) (underlayRule, bool) {
|
||||
if !isOurUnderlayRule(ru, r.ipPolicyPrefBase) {
|
||||
return underlayRule{}, false
|
||||
}
|
||||
u := underlayRule{fam: ru.family, src: ru.src}
|
||||
switch int(ru.priority) {
|
||||
case r.underlaySuppressRulePriority():
|
||||
u.src = netip.Addr{}
|
||||
case r.underlayPortRulePriority():
|
||||
if ru.sportRange == nil {
|
||||
return underlayRule{}, false
|
||||
}
|
||||
u.port = ru.sportRange[0]
|
||||
}
|
||||
return u, true
|
||||
}
|
||||
|
||||
// underlaySrcRepairDelay is how long after a deletion at our priorities we
|
||||
// check for missing underlay rules, batching bursts of deletions.
|
||||
const underlaySrcRepairDelay = 250 * time.Millisecond
|
||||
|
||||
// scheduleUnderlaySrcRuleRepair is called when a rule at an underlay rule
|
||||
// priority is deleted. Most such deletions are our own (address removed,
|
||||
// exit node turned off), but another process may have deleted one of ours
|
||||
// without touching the base rules, in which case nothing else would notice.
|
||||
// After a short delay we re-add any tracked rule that is missing. Since that
|
||||
// only ever adds, it can't cause further deletion events.
|
||||
//
|
||||
// It needs netlink; see underlayNetlinkUsable.
|
||||
func (r *linuxRouter) scheduleUnderlaySrcRuleRepair() {
|
||||
if !r.ipRuleAvailable || !r.underlayNetlinkUsable() || r.closed.Load() {
|
||||
return
|
||||
}
|
||||
if r.underlaySrcRepairPending.Swap(true) {
|
||||
return
|
||||
}
|
||||
r.after(underlaySrcRepairDelay, r.repairUnderlaySrcRules)
|
||||
}
|
||||
|
||||
// underlayRepairWait reports how long to wait before re-adding missing
|
||||
// underlay rules, or 0 to re-add them now. Like the base rule restore,
|
||||
// repairs are rate limited so we don't get into a high-speed fight with
|
||||
// another process deleting our rules. Only repairs that actually find
|
||||
// rules missing count: most deletions at our priorities are our own, and
|
||||
// they mustn't use up the budget for real ones.
|
||||
func (r *linuxRouter) underlayRepairWait(missing int) time.Duration {
|
||||
lim := r.underlayRepairLimiter
|
||||
if missing == 0 || lim == nil {
|
||||
return 0
|
||||
}
|
||||
rr := lim.Reserve()
|
||||
if d := rr.Delay(); d > 0 {
|
||||
// Don't hold the reservation: we come back after d and take a
|
||||
// token then.
|
||||
rr.Cancel()
|
||||
return d
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (r *linuxRouter) repairUnderlaySrcRules() {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.closed.Load() {
|
||||
r.underlaySrcRepairPending.Store(false)
|
||||
return
|
||||
}
|
||||
missing := r.missingUnderlayRulesLocked()
|
||||
if d := r.underlayRepairWait(len(missing)); d > 0 {
|
||||
// Keep the repair pending, so deletions meanwhile don't schedule
|
||||
// more, and come back when the rate limit allows.
|
||||
r.after(d, r.repairUnderlaySrcRules)
|
||||
return
|
||||
}
|
||||
r.underlaySrcRepairPending.Store(false)
|
||||
if len(missing) == 0 {
|
||||
return
|
||||
}
|
||||
n, failed := r.reAddUnderlaySrcRulesLocked(missing)
|
||||
if n > 0 {
|
||||
r.logf("re-added %d rp_filter underlay rule(s) deleted by another process", n)
|
||||
}
|
||||
if failed {
|
||||
// Retry, and remove any source rules left without their
|
||||
// suppress rule.
|
||||
if err := r.updateUnderlaySrcRulesLocked(false); err != nil {
|
||||
r.logf("repairing rp_filter underlay rules: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// queueNetworkChange is the netmon.ChangeDelta eventbus callback. It must
|
||||
// return quickly: the router's eventbus client delivers events one at a
|
||||
// time, so blocking here (on r.mu behind a long Set, then on netlink
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
"github.com/tailscale/netlink"
|
||||
"go4.org/netipx"
|
||||
"golang.org/x/sys/unix"
|
||||
"golang.org/x/time/rate"
|
||||
"tailscale.com/envknob"
|
||||
"tailscale.com/net/netmon"
|
||||
"tailscale.com/tstest"
|
||||
@@ -369,6 +370,32 @@ func TestUnderlaySrcRulesCap(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnderlaySrcRulesRestore checks that rules deleted by another process
|
||||
// (e.g. systemd-networkd flushing foreign rules) are re-installed, and that
|
||||
// restoring while they still exist doesn't duplicate them.
|
||||
func TestUnderlaySrcRulesRestore(t *testing.T) {
|
||||
lr, fake := newTestLinuxRouter(t)
|
||||
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", "2001:db8::5")
|
||||
|
||||
// Restore with everything present: no duplicates.
|
||||
lr.restoreUnderlaySrcRules()
|
||||
checkUnderlayRules(t, fake, "192.168.1.5", "2001:db8::5")
|
||||
|
||||
// External flush of one rule.
|
||||
fake.rules = slices.DeleteFunc(fake.rules, func(s string) bool {
|
||||
return strings.Contains(s, "from 192.168.1.5 ")
|
||||
})
|
||||
lr.restoreUnderlaySrcRules()
|
||||
checkUnderlayRules(t, fake, "192.168.1.5", "2001:db8::5")
|
||||
}
|
||||
|
||||
// TestUnderlaySrcRulesInRestoreRange ensures the rule priority is inside the
|
||||
// range onIPRuleDeleted reacts to and below the table 52 catch-all.
|
||||
func TestUnderlaySrcRulesInRestoreRange(t *testing.T) {
|
||||
@@ -606,24 +633,31 @@ func underlayRulesKernelChild(t *testing.T) {
|
||||
mon.Start()
|
||||
defer mon.Close()
|
||||
// Count rule restores so we can detect restore feedback loops.
|
||||
var restores atomic.Int32
|
||||
var restores, repairs atomic.Int32
|
||||
logf := func(format string, args ...any) {
|
||||
if strings.Contains(format, "deleted ip rules; restoring") {
|
||||
restores.Add(1)
|
||||
}
|
||||
if strings.Contains(format, "rp_filter underlay rule(s) deleted by another process") {
|
||||
repairs.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.
|
||||
// Capture the router's restore and repair 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 }
|
||||
// A repair budget that never refills, enough for the test's few
|
||||
// genuine external deletions only: if our own rule churn spent
|
||||
// it, the later repairs would never happen.
|
||||
r.underlayRepairLimiter = rate.NewLimiter(rate.Every(time.Hour), 5)
|
||||
r.afterFunc = timers.afterFunc
|
||||
})
|
||||
|
||||
@@ -983,6 +1017,38 @@ func underlayRulesKernelChild(t *testing.T) {
|
||||
if n := restores.Load(); n != 0 {
|
||||
t.Fatalf("%d rule restores triggered by our own rule churn; want 0", n)
|
||||
}
|
||||
if n := repairs.Load(); n != 0 {
|
||||
t.Fatalf("%d rule repairs re-added rules after our own churn; want 0", n)
|
||||
}
|
||||
|
||||
// Our own rule churn mustn't use up the repair budget (review finding):
|
||||
// toggle the exit node a dozen times (each removes and re-adds our
|
||||
// rules), then check an external deletion is still repaired promptly.
|
||||
for range 12 {
|
||||
if err := lr.Set(noExit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := lr.Set(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor(t, "rules back after exit node toggle", func() bool {
|
||||
return slices.Contains(kernelUnderlayRules(t, lr), local4)
|
||||
})
|
||||
}
|
||||
quiesce(t, lr, bus, &timers)
|
||||
restoresBefore, repairsBefore := restores.Load(), repairs.Load()
|
||||
if err := delIPRule(lr.underlayIPRule(underlayRule{fam: v4, src: local4})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitForTimers(t, &timers, "external deletion after our own churn repaired (churn used up the rate limit?)", func() bool {
|
||||
return slices.Contains(kernelUnderlayRules(t, lr), local4)
|
||||
})
|
||||
quiesce(t, lr, bus, &timers)
|
||||
if r, p := restores.Load()-restoresBefore, repairs.Load()-repairsBefore; r != 0 || p != 1 {
|
||||
t.Fatalf("after churn and one external delete: %d restores, %d repairs; want 0 and 1", r, p)
|
||||
}
|
||||
restores.Store(0)
|
||||
repairs.Store(0)
|
||||
|
||||
// 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.
|
||||
@@ -1010,6 +1076,99 @@ func underlayRulesKernelChild(t *testing.T) {
|
||||
if err := replyPasses(); err != nil {
|
||||
t.Fatalf("back to strict rp_filter: reply validation failed: %v", err)
|
||||
}
|
||||
quiesce(t, lr, bus, &timers)
|
||||
restores.Store(0)
|
||||
repairs.Store(0)
|
||||
|
||||
// A lone external deletion of just one underlay rule (base rules
|
||||
// untouched, so no full restore) is repaired by the add-only path.
|
||||
if err := delIPRule(lr.underlayIPRule(underlayRule{fam: v6, src: local6})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitForTimers(t, &timers, "repair after lone external delete", func() bool {
|
||||
return slices.Contains(kernelUnderlayRules(t, lr), local6)
|
||||
})
|
||||
quiesce(t, lr, bus, &timers)
|
||||
if r, p := restores.Load(), repairs.Load(); r != 0 || p != 1 {
|
||||
t.Fatalf("after lone delete: %d restores, %d repairs; want 0 and 1", r, p)
|
||||
}
|
||||
|
||||
// The same for the magicsock port rule, whose deletion event carries
|
||||
// attributes newer kernels added (FRA_SPORT_MASK, from 6.15): netmon
|
||||
// must still parse it, or the rule is never repaired (review finding).
|
||||
lr.mu.Lock()
|
||||
portRule := underlayRule{fam: v4, src: local4, port: lr.underlayMagicsockPortV4}
|
||||
lr.mu.Unlock()
|
||||
// Other addresses (lan0's) have port rules too, so look for this one.
|
||||
hasPortRule := func() bool {
|
||||
t.Helper()
|
||||
rules, err := listIPRules(v4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return slices.ContainsFunc(rules, func(ru ipRule) bool {
|
||||
u, ok := lr.underlayRuleOf(ru)
|
||||
return ok && u == portRule
|
||||
})
|
||||
}
|
||||
if portRule.port == 0 || !hasPortRule() {
|
||||
t.Fatalf("no port rule %v installed to delete", portRule)
|
||||
}
|
||||
restores.Store(0)
|
||||
repairs.Store(0)
|
||||
if err := delIPRule(lr.underlayIPRule(portRule)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if hasPortRule() {
|
||||
t.Fatalf("port rule %v still there after deleting it", portRule)
|
||||
}
|
||||
waitForTimers(t, &timers, "repair after external port rule delete", hasPortRule)
|
||||
quiesce(t, lr, bus, &timers)
|
||||
if r, p := restores.Load(), repairs.Load(); r != 0 || p != 1 {
|
||||
t.Fatalf("after port rule delete: %d restores, %d repairs; want 0 and 1", r, p)
|
||||
}
|
||||
|
||||
// An external flush (as systemd-networkd's
|
||||
// ManageForeignRoutingPolicyRules does) removes the base rules and the
|
||||
// underlay source rules; both are repaired.
|
||||
catchAll := netlink.NewRule()
|
||||
catchAll.Priority = lr.ipPolicyPrefBase + 70
|
||||
catchAll.Family = netlink.FAMILY_V4
|
||||
catchAll.Table = tailscaleRouteTable.Num
|
||||
if err := netlink.RuleDel(catchAll); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
catchAll6 := *catchAll
|
||||
catchAll6.Family = netlink.FAMILY_V6
|
||||
if err := netlink.RuleDel(&catchAll6); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, u := range []underlayRule{{fam: v4, src: local4}, {fam: v4}} {
|
||||
if err := delIPRule(lr.underlayIPRule(u)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// The add-only repair (underlay rules) and the full restore (base
|
||||
// rules, including the table 52 catch-all) run on separate timers;
|
||||
// wait for both.
|
||||
waitForTimers(t, &timers, "restore after external flush", func() bool {
|
||||
return slices.Contains(kernelUnderlayRules(t, lr), local4) &&
|
||||
slices.Contains(kernelSuppressRules(t, lr), v4) &&
|
||||
routeDev(remote4, netip.Addr{}) == tunName &&
|
||||
routeDev(remote6, netip.Addr{}) == tunName
|
||||
})
|
||||
if err := replyPasses(); err != nil {
|
||||
t.Fatalf("after restore: reply validation failed: %v", err)
|
||||
}
|
||||
for _, dst := range []netip.Addr{remote4, remote6} {
|
||||
if got := routeDev(dst, netip.Addr{}); got != tunName {
|
||||
t.Fatalf("after restore: route to %v via %s, want %s (catch-all not restored?)", dst, got, tunName)
|
||||
}
|
||||
}
|
||||
quiesce(t, lr, bus, &timers)
|
||||
if n := restores.Load(); n != 1 {
|
||||
t.Fatalf("got %d rule restores after one external flush; want exactly 1 (feedback loop?)", n)
|
||||
}
|
||||
|
||||
// Exit node off: rules removed.
|
||||
if err := lr.Set(noExit); err != nil {
|
||||
@@ -1215,8 +1374,8 @@ func waitForTimers(t *testing.T, timers *routerTimers, what string, cond func()
|
||||
// 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.
|
||||
// itself (a repair the rate limiter deferred) stays queued for the next
|
||||
// drain, which is what the router would do in production.
|
||||
type routerTimers struct {
|
||||
mu sync.Mutex
|
||||
pending []func()
|
||||
@@ -1248,7 +1407,7 @@ func (rt *routerTimers) drain() {
|
||||
}
|
||||
|
||||
// quiesce settles lr before assertions that count what it did: it runs every
|
||||
// timer lr has scheduled, and waits until the bus has delivered
|
||||
// restore or repair 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
|
||||
@@ -1562,6 +1721,37 @@ func TestUnderlayRulesRemovedLastOnClose(t *testing.T) {
|
||||
checkUnderlayRules(t, fake)
|
||||
}
|
||||
|
||||
// TestUnderlayRulesNeedSuppressRule checks that if a family's suppress rule
|
||||
// is lost and can't be re-added (as after a failed repair), its source rules
|
||||
// are removed rather than left in place, where they'd cut tailnet traffic
|
||||
// to the underlay addresses.
|
||||
func TestUnderlayRulesNeedSuppressRule(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")
|
||||
// As reAddUnderlaySrcRulesLocked does when the re-add fails.
|
||||
lr.mu.Lock()
|
||||
lr.underlaySrcRules.Delete(underlayRule{fam: v4})
|
||||
lr.mu.Unlock()
|
||||
fake.rules = slices.DeleteFunc(fake.rules, func(r string) bool { return strings.Contains(r, " pref 5255 ") })
|
||||
fake.failRun = func(args []string) error {
|
||||
if strings.Contains(strings.Join(args, " "), "rule add pref 5255") {
|
||||
return errors.New("exitcode:1")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
lr.onNetworkChange()
|
||||
if n := underlaySrcRuleCount(fake, "-4"); n != 0 {
|
||||
t.Errorf("%d source rules left without their suppress rule", n)
|
||||
}
|
||||
fake.failRun = nil
|
||||
lr.onNetworkChange()
|
||||
checkUnderlayRules(t, fake, "192.168.1.5")
|
||||
}
|
||||
|
||||
// TestUnderlayPortRuleWithoutNetfilter checks that the magicsock port rule
|
||||
// follows the port even when the netfilter magicsock rule fails (review
|
||||
// finding: the port was only recorded after netfilter succeeded, so no
|
||||
@@ -1623,6 +1813,52 @@ func TestUnderlayAddrsLinkLocalLast(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnderlayRepairRateLimited checks that re-adding underlay rules that
|
||||
// another process keeps deleting is rate limited, like the base rule
|
||||
// restore, and that repairs which find nothing missing (our own deletions)
|
||||
// don't use up the budget (review findings).
|
||||
func TestUnderlayRepairRateLimited(t *testing.T) {
|
||||
r := &linuxRouter{routerFixed: routerFixed{underlayRepairLimiter: rate.NewLimiter(rate.Every(5*time.Second), 3)}}
|
||||
// Our own deletions: nothing missing, no tokens used.
|
||||
for range 20 {
|
||||
if d := r.underlayRepairWait(0); d != 0 {
|
||||
t.Fatalf("repair with nothing missing waits %v, want 0", d)
|
||||
}
|
||||
}
|
||||
if tok := r.underlayRepairLimiter.Tokens(); tok < 2.9 {
|
||||
t.Fatalf("repairs with nothing missing used tokens: %.1f left of 3", tok)
|
||||
}
|
||||
// Real external deletions: the burst goes through, then it waits.
|
||||
for i := range 3 {
|
||||
if d := r.underlayRepairWait(1); d != 0 {
|
||||
t.Fatalf("repair %d within the burst waits %v, want 0", i, d)
|
||||
}
|
||||
}
|
||||
d := r.underlayRepairWait(1)
|
||||
if d < 4*time.Second {
|
||||
t.Fatalf("repair beyond the burst waits %v, want about 5s", d)
|
||||
}
|
||||
// Waiting didn't take a token: asking again gives the same wait.
|
||||
if d2 := r.underlayRepairWait(1); d2 < d-time.Second {
|
||||
t.Errorf("second wait %v much shorter than first %v; the first held a reservation", d2, d)
|
||||
}
|
||||
|
||||
// Scheduling isn't limited, but coalesces while a repair is pending.
|
||||
var scheduled int
|
||||
r2 := &linuxRouter{
|
||||
routerFixed: routerFixed{
|
||||
ipRuleAvailable: true,
|
||||
cmd: osCommandRunner{},
|
||||
afterFunc: func(time.Duration, func()) { scheduled++ },
|
||||
},
|
||||
}
|
||||
r2.scheduleUnderlaySrcRuleRepair()
|
||||
r2.scheduleUnderlaySrcRuleRepair()
|
||||
if scheduled != 1 {
|
||||
t.Errorf("scheduled %d repairs while one was pending, want 1", scheduled)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -1808,3 +2044,79 @@ func TestUnderlayErrorLoggedOnce(t *testing.T) {
|
||||
t.Errorf("after recovery and a new failure: logged %d times, want 2", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMissingUnderlayRules checks that a family whose rules can't be listed
|
||||
// only counts its own tracked rules as missing, and that a family with no
|
||||
// tracked rules isn't listed at all (review finding: an IPv6 dump failure,
|
||||
// as on ipv6.disable=1 hosts, made every repair re-add every IPv4 rule too).
|
||||
func TestMissingUnderlayRules(t *testing.T) {
|
||||
r := &linuxRouter{routerFixed: routerFixed{ipPolicyPrefBase: defaultIPPolicyPrefBase}}
|
||||
src4 := underlayRule{fam: v4, src: netip.MustParseAddr("192.168.1.5")}
|
||||
sup4 := underlayRule{fam: v4}
|
||||
src6 := underlayRule{fam: v6, src: netip.MustParseAddr("2001:db8::5")}
|
||||
sup6 := underlayRule{fam: v6}
|
||||
kernel := func(us ...underlayRule) []ipRule {
|
||||
var out []ipRule
|
||||
for _, u := range us {
|
||||
out = append(out, r.underlayIPRule(u))
|
||||
}
|
||||
return out
|
||||
}
|
||||
errV6 := errors.New("listing IPv6 rules: address family not supported")
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
tracked []underlayRule
|
||||
list map[addrFamily]func() ([]ipRule, error)
|
||||
want []underlayRule
|
||||
}{
|
||||
{
|
||||
name: "v6-dump-fails-v4-only",
|
||||
tracked: []underlayRule{src4, sup4},
|
||||
list: map[addrFamily]func() ([]ipRule, error){
|
||||
v4: func() ([]ipRule, error) { return kernel(src4, sup4), nil },
|
||||
// Not tracked, so not listed (a call here fails the test).
|
||||
},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "v6-dump-fails-both-tracked",
|
||||
tracked: []underlayRule{src4, sup4, src6, sup6},
|
||||
list: map[addrFamily]func() ([]ipRule, error){
|
||||
v4: func() ([]ipRule, error) { return kernel(src4, sup4), nil },
|
||||
v6: func() ([]ipRule, error) { return nil, errV6 },
|
||||
},
|
||||
want: []underlayRule{src6, sup6},
|
||||
},
|
||||
{
|
||||
name: "one-v4-missing",
|
||||
tracked: []underlayRule{src4, sup4, src6, sup6},
|
||||
list: map[addrFamily]func() ([]ipRule, error){
|
||||
v4: func() ([]ipRule, error) { return kernel(sup4), nil },
|
||||
v6: func() ([]ipRule, error) { return kernel(src6, sup6), nil },
|
||||
},
|
||||
want: []underlayRule{src4},
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r.underlaySrcRules = set.Of(tt.tracked...)
|
||||
got := r.missingUnderlayRules(func(fam addrFamily) ([]ipRule, error) {
|
||||
f, ok := tt.list[fam]
|
||||
if !ok {
|
||||
t.Fatalf("listed family %v, which has no tracked rules", fam)
|
||||
}
|
||||
return f()
|
||||
})
|
||||
sortRules := func(us []underlayRule) {
|
||||
slices.SortFunc(us, func(a, b underlayRule) int {
|
||||
return strings.Compare(fmt.Sprint(a), fmt.Sprint(b))
|
||||
})
|
||||
}
|
||||
sortRules(got)
|
||||
sortRules(tt.want)
|
||||
if !slices.Equal(got, tt.want) {
|
||||
t.Errorf("missing = %v; want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,7 @@ func TestUnderlaySrcRulesNetfilterV6(t *testing.T) {
|
||||
t.Fatal("exit node on, with underlay rules: reply dropped")
|
||||
}
|
||||
|
||||
e.checkRuleDeleteAndRepair()
|
||||
e.checkExitNodeOff()
|
||||
})
|
||||
}
|
||||
@@ -152,6 +153,7 @@ func TestUnderlaySrcRulesNetfilterV4(t *testing.T) {
|
||||
t.Fatal("strict rp_filter, with underlay rules: reply dropped")
|
||||
}
|
||||
|
||||
e.checkRuleDeleteAndRepair()
|
||||
e.checkExitNodeOff()
|
||||
})
|
||||
}
|
||||
@@ -376,6 +378,26 @@ func (e *netfilterRPFEnv) sendReply() (passed bool) {
|
||||
return true
|
||||
}
|
||||
|
||||
// checkRuleDeleteAndRepair checks that it's the source rule for e.local that
|
||||
// lets the reply through: with just that one deleted (as another process
|
||||
// might) the reply is dropped again, until the router repairs it.
|
||||
func (e *netfilterRPFEnv) checkRuleDeleteAndRepair() {
|
||||
t := e.t
|
||||
t.Helper()
|
||||
if err := delIPRule(e.lr.underlayIPRule(underlayRule{fam: e.fam, src: e.local})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e.sendReply() {
|
||||
t.Fatal("source rule deleted: reply passed; the rule isn't what lets it through")
|
||||
}
|
||||
waitForTimers(t, &e.timers, "repair of the deleted source rule", func() bool {
|
||||
return slices.Contains(kernelUnderlayRules(t, e.lr), e.local)
|
||||
})
|
||||
if !e.sendReply() {
|
||||
t.Fatal("after repair: reply dropped")
|
||||
}
|
||||
}
|
||||
|
||||
// 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() {
|
||||
|
||||
Reference in new issue
Block a user