util/linuxfw: remove connmark rules in firewall cleanup (#22417)

The iptables and nftables cleanups didn't remove the connmark rules
from the mangle tables, so they were left behind by --cleanup and
after an unclean exit followed by a switch to another firewall mode.

AddConnmarkSaveRule created mangle/OUTPUT with type filter, which
iptables-nft can't add rules to. Create it with type route, as
iptables-nft does, and at startup delete the old filter-type chain
if nothing else uses it.

Updates #22363

Change-Id: I7b64e8e9894773f1dd88384c3339106603db15ae
Signed-off-by: Nikolaos Gkarlis <[email protected]>
This commit is contained in:
Nick Garlis authored and GitHub committed 2026-12-03 17:39:29 -08:00
1 parent c069cc6561
commit 85095d76d9
4 files changed
+200 -32

No files matched your search

+4
View File
@@ -233,5 +233,9 @@ func clearRules(proto iptables.Protocol, logf logger.Logf) error {
errs = append(errs, err)
}
if err := delConnmarkRules(ipt); err != nil {
errs = append(errs, err)
}
return errors.Join(errs...)
}
+37 -31
View File
@@ -598,40 +598,46 @@ func (i *iptablesRunner) AddConnmarkSaveRule() error {
// DelConnmarkSaveRule removes conntrack marking rules added by AddConnmarkSaveRule.
func (i *iptablesRunner) DelConnmarkSaveRule() error {
for _, ipt := range i.getTables() {
// Delete PREROUTING rule
args := []string{
"-m", "conntrack",
"--ctstate", "ESTABLISHED,RELATED",
"-m", "connmark",
"!", "--mark", "0x0/" + fwmarkMask,
"-j", "CONNMARK",
"--restore-mark",
"--nfmask", fwmarkMask,
"--ctmask", fwmarkMask,
}
if err := ipt.Delete("mangle", "PREROUTING", args...); err != nil {
if !isNotExistError(err) {
return fmt.Errorf("deleting connmark rule in mangle/PREROUTING: %w", err)
}
// Rule doesn't exist - this is fine for idempotency
if err := delConnmarkRules(ipt); err != nil {
return err
}
}
return nil
}
// Delete OUTPUT rule
args = []string{
"-m", "conntrack",
"--ctstate", "NEW",
"-m", "mark",
"!", "--mark", "0x0/" + fwmarkMask,
"-j", "CONNMARK",
"--save-mark",
"--nfmask", fwmarkMask,
"--ctmask", fwmarkMask,
// delConnmarkRules removes the rules added by AddConnmarkSaveRule from ipt.
func delConnmarkRules(ipt iptablesInterface) error {
// Delete PREROUTING rule
args := []string{
"-m", "conntrack",
"--ctstate", "ESTABLISHED,RELATED",
"-m", "connmark",
"!", "--mark", "0x0/" + fwmarkMask,
"-j", "CONNMARK",
"--restore-mark",
"--nfmask", fwmarkMask,
"--ctmask", fwmarkMask,
}
if err := ipt.Delete("mangle", "PREROUTING", args...); err != nil {
if !isNotExistError(err) {
return fmt.Errorf("deleting connmark rule in mangle/PREROUTING: %w", err)
}
if err := ipt.Delete("mangle", "OUTPUT", args...); err != nil {
if !isNotExistError(err) {
return fmt.Errorf("deleting connmark rule in mangle/OUTPUT: %w", err)
}
// Rule doesn't exist - this is fine for idempotency
}
// Delete OUTPUT rule
args = []string{
"-m", "conntrack",
"--ctstate", "NEW",
"-m", "mark",
"!", "--mark", "0x0/" + fwmarkMask,
"-j", "CONNMARK",
"--save-mark",
"--nfmask", fwmarkMask,
"--ctmask", fwmarkMask,
}
if err := ipt.Delete("mangle", "OUTPUT", args...); err != nil {
if !isNotExistError(err) {
return fmt.Errorf("deleting connmark rule in mangle/OUTPUT: %w", err)
}
}
return nil
+76 -1
View File
@@ -2322,7 +2322,7 @@ func (n *nftablesRunner) AddConnmarkSaveRule() error {
outputChain = conn.AddChain(&nftables.Chain{
Name: "OUTPUT",
Table: mangleTable,
Type: nftables.ChainTypeFilter,
Type: nftables.ChainTypeRoute,
Hooknum: nftables.ChainHookOutput,
Priority: nftables.ChainPriorityMangle,
})
@@ -2413,6 +2413,77 @@ func cleanupChain(logf logger.Logf, conn *nftables.Conn, table *nftables.Table,
}
}
// cleanupConnmarkRules removes the rules added by AddConnmarkSaveRule from
// table. Errors are logged.
func cleanupConnmarkRules(logf logger.Logf, conn *nftables.Conn, table *nftables.Table) {
for chainName, tag := range map[string]string{
"PREROUTING": "ts-connmark-restore",
"OUTPUT": "ts-connmark-save",
} {
chain, err := getChainFromTable(conn, table, chainName)
if err != nil {
continue
}
rules, err := conn.GetRules(table, chain)
if err != nil {
logf("cleanup: list rules of chain %s: %s", chainName, err)
continue
}
for _, rule := range rules {
if string(rule.UserData) == tag {
if err := conn.DelRule(rule); err != nil {
logf("cleanup: delete rule in chain %s: %s", chainName, err)
}
}
}
}
if err := conn.Flush(); err != nil {
logf("cleanup: flush delete connmark rules: %s", err)
}
}
// cleanupIncompatibleMangleOutputChain deletes the OUTPUT chain of an ip or
// ip6 mangle table if it looks like the one AddConnmarkSaveRule used to create:
// of type filter, with an accept policy, and holding no rules but Tailscale's.
// iptables-nft creates it with type route, and can't add rules to it
// otherwise. A filter chain holding other rules, or with another policy, may
// not be Tailscale's, so it's kept and a warning is logged. Errors are logged.
func cleanupIncompatibleMangleOutputChain(logf logger.Logf, conn *nftables.Conn, table *nftables.Table) {
if table.Family != nftables.TableFamilyIPv4 && table.Family != nftables.TableFamilyIPv6 {
return
}
chain, err := getChainFromTable(conn, table, "OUTPUT")
if err != nil {
if !errors.Is(err, errorChainNotFound{table.Name, "OUTPUT"}) {
logf("cleanup: get mangle OUTPUT chain: %s", err)
}
return
}
if chain.Type != nftables.ChainTypeFilter {
return
}
rules, err := conn.GetRules(table, chain)
if err != nil {
logf("cleanup: list rules of mangle OUTPUT chain: %s", err)
return
}
ours := chain.Policy != nil && *chain.Policy == nftables.ChainPolicyAccept
for _, rule := range rules {
if string(rule.UserData) != "ts-connmark-save" {
ours = false
}
}
if !ours {
logf("cleanup: mangle OUTPUT chain has type filter, which iptables-nft can't add rules to; recreate it with type route")
return
}
conn.FlushChain(chain)
conn.DelChain(chain)
if err := conn.Flush(); err != nil {
logf("cleanup: delete mangle OUTPUT chain: %s", err)
}
}
// NfTablesCleanUp removes all Tailscale added nftables rules.
// Any errors that occur are logged to the provided logf.
func NfTablesCleanUp(logf logger.Logf) {
@@ -2442,6 +2513,10 @@ func NfTablesCleanUp(logf logger.Logf) {
if table.Name == "nat" {
cleanupChain(logf, conn, table, "POSTROUTING", chainNamePostrouting)
}
if table.Name == "mangle" {
cleanupConnmarkRules(logf, conn, table)
cleanupIncompatibleMangleOutputChain(logf, conn, table)
}
}
}
+83
View File
@@ -1258,6 +1258,9 @@ func TestNFTAddAndDelConnmarkRules(t *testing.T) {
if prerouting4After == nil || output4After == nil {
t.Fatal("IPv4 mangle chains not created")
}
if output4After.Type != nftables.ChainTypeRoute {
t.Errorf("IPv4 OUTPUT chain type = %q, want %q", output4After.Type, nftables.ChainTypeRoute)
}
prerouting4Rules, err := conn.GetRules(prerouting4After.Table, prerouting4After)
if err != nil {
@@ -1358,6 +1361,86 @@ func TestNFTAddAndDelConnmarkRules(t *testing.T) {
}
}
func TestCleanupConnmarkRules(t *testing.T) {
conn := newSysConn(t)
runner := newFakeNftablesRunnerWithConn(t, conn, true)
if err := runner.AddConnmarkSaveRule(); err != nil {
t.Fatalf("AddConnmarkSaveRule() failed: %v", err)
}
for _, fam := range []nftables.TableFamily{nftables.TableFamilyIPv4, nftables.TableFamilyIPv6} {
cleanupConnmarkRules(t.Logf, conn, &nftables.Table{Family: fam, Name: "mangle"})
chains, err := conn.ListChainsOfTableFamily(fam)
if err != nil {
t.Fatal(err)
}
for _, ch := range chains {
if ch.Table.Name != "mangle" {
continue
}
rules, err := conn.GetRules(ch.Table, ch)
if err != nil {
t.Fatal(err)
}
if len(rules) != 0 {
t.Errorf("family %v chain %s: got %d rules after cleanup, want 0", fam, ch.Name, len(rules))
}
}
}
}
// TestCleanupIncompatibleMangleOutputChain checks that the cleanup deletes a
// mangle/OUTPUT chain of type filter as AddConnmarkSaveRule used to create it,
// and keeps any other.
func TestCleanupIncompatibleMangleOutputChain(t *testing.T) {
polAccept, polDrop := nftables.ChainPolicyAccept, nftables.ChainPolicyDrop
tests := []struct {
name string
typ nftables.ChainType
policy *nftables.ChainPolicy
ourRule bool
otherRule bool
wantDeleted bool
}{
{"filter, empty", nftables.ChainTypeFilter, &polAccept, false, false, true},
{"filter with our rule", nftables.ChainTypeFilter, &polAccept, true, false, true},
{"filter with another rule", nftables.ChainTypeFilter, &polAccept, true, true, false},
{"filter with drop policy", nftables.ChainTypeFilter, &polDrop, true, false, false},
{"route", nftables.ChainTypeRoute, &polAccept, true, false, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
conn := newSysConn(t)
mangle := conn.AddTable(&nftables.Table{Family: nftables.TableFamilyIPv4, Name: "mangle"})
ch := conn.AddChain(&nftables.Chain{
Name: "OUTPUT",
Table: mangle,
Type: tt.typ,
Hooknum: nftables.ChainHookOutput,
Priority: nftables.ChainPriorityMangle,
Policy: tt.policy,
})
if tt.ourRule {
conn.AddRule(&nftables.Rule{Table: mangle, Chain: ch, Exprs: makeConnmarkSaveExprs(), UserData: []byte("ts-connmark-save")})
}
if tt.otherRule {
conn.AddRule(&nftables.Rule{Table: mangle, Chain: ch, Exprs: []expr.Any{&expr.Verdict{Kind: expr.VerdictAccept}}})
}
if err := conn.Flush(); err != nil {
t.Fatal(err)
}
cleanupIncompatibleMangleOutputChain(t.Logf, conn, mangle)
_, err := getChainFromTable(conn, mangle, "OUTPUT")
if deleted := errors.Is(err, errorChainNotFound{"mangle", "OUTPUT"}); deleted != tt.wantDeleted {
t.Errorf("deleted = %v (err %v), want %v", deleted, err, tt.wantDeleted)
}
})
}
}
// TestMakeConnmarkRestoreExprs tests the nftables expressions for restoring
// marks from conntrack. This is a regression test that ensures the byte encoding
// doesn't change unexpectedly.