diff --git a/internal/nftables/compiler.go b/internal/nftables/compiler.go index a86c5b5..47dc59d 100644 --- a/internal/nftables/compiler.go +++ b/internal/nftables/compiler.go @@ -469,6 +469,14 @@ func (c *Compiler) compileOneRule(state *FirewallState, tag, srcSpec, dstSpec, p for _, src := range c.zoneSpecs(srcSpec) { for _, srcAddr := range splitAddrs(src.Addr) { + if action == config.RuleDNAT || action == config.RuleRedirect { + if dnatSkipsIntrazone(srcSpec, src.Zone, dstSpec) { + continue + } + if err := c.compileDNATAccept(state, tag, src.Zone, srcAddr, dstSpec, proto, dports, sports, action, fwZone, section); err != nil { + return err + } + } for _, od := range splitAddrs(origDest) { if action == config.RuleDNAT || action == config.RuleRedirect { if err := c.compileDNATRule(state, tag, src.Zone, srcAddr, od, dstSpec, proto, dports, action, logLevel); err != nil { @@ -495,6 +503,42 @@ func (c *Compiler) compileOneRule(state *FirewallState, tag, srcSpec, dstSpec, p return nil } +// dnatSkipsIntrazone mirrors shorewall: a zone list or all!x source never pairs a zone with itself unless marked "+". +func dnatSkipsIntrazone(srcSpec, srcZone, dstSpec string) bool { + zones, _, _ := strings.Cut(srcSpec, ":") + wild := isZoneExclusion(srcSpec) || strings.Contains(zones, ",") + dstZone, _, _ := strings.Cut(dstSpec, ":") + return wild && !strings.Contains(zones, "+!") && srcZone == dstZone +} + +// compileDNATAccept emits the filter ACCEPT implied by DNAT/REDIRECT (shorewall's DNAT-/REDIRECT- omit it) for the translated flow. +func (c *Compiler) compileDNATAccept(state *FirewallState, tag, srcZone, srcAddr, dstSpec, proto string, + dports, sports config.PortSpec, action config.RuleAction, fwZone string, section config.RuleSection) error { + parts := strings.SplitN(dstSpec, ":", 3) + if len(parts) < 2 { + return fmt.Errorf("DNAT dest must be zone:address or zone:address:port") + } + dstZone, dstAddr := parts[0], parts[1] + if action == config.RuleRedirect { + dstZone, dstAddr = fwZone, "" + } + if len(parts) == 3 { + dports = config.PortSpec{parts[2]} + } + chain := c.selectChain(srcZone, dstZone, fwZone) + n := len(state.Rules[chain]) + if err := c.compileZonePair(state, tag, srcZone, srcAddr, dstZone, dstAddr, "", proto, + dports, sports, config.RuleAccept, "", fwZone, section); err != nil { + return err + } + for i := n; i < len(state.Rules[chain]); i++ { + e := state.Rules[chain][i].Exprs + last := len(e) - 1 + state.Rules[chain][i].Exprs = append(append(e[:last:last], matchCtBits(expr.CtKeySTATUS, ctStatusDNAT)...), e[last]) + } + return nil +} + // specCount is how many zone/address combinations compileOneRule expands src and dst into. func (c *Compiler) specCount(srcSpec, dstSpec, origDest string, action config.RuleAction) int { count := func(spec string) (n int) { @@ -1645,13 +1689,18 @@ const ( ctStateRelated = 4 ctStateNew = 8 ctStateUntracked = 64 + ctStatusDNAT = 32 ) func matchCtState(stateMask uint32) []expr.Any { + return matchCtBits(expr.CtKeySTATE, stateMask) +} + +func matchCtBits(key expr.CtKey, stateMask uint32) []expr.Any { stateBytes := make([]byte, 4) binary.NativeEndian.PutUint32(stateBytes, stateMask) return []expr.Any{ - &expr.Ct{Key: expr.CtKeySTATE, Register: 1}, + &expr.Ct{Key: key, Register: 1}, &expr.Bitwise{ SourceRegister: 1, DestRegister: 1, diff --git a/internal/nftables/compiler_test.go b/internal/nftables/compiler_test.go index 7be75de..6a08203 100644 --- a/internal/nftables/compiler_test.go +++ b/internal/nftables/compiler_test.go @@ -1627,7 +1627,7 @@ func TestCompile_QueueRedirMatchKernelReadback(t *testing.T) { for _, rules := range state.Rules { for _, r := range rules { w, ok := want[r.Tag] - if !ok { + if !ok || r.Chain != "prerouting" && r.Tag == "rule:3" { continue } if got := r.Exprs[len(r.Exprs)-1]; !reflect.DeepEqual(got, w) { @@ -1918,12 +1918,46 @@ func TestCompile_CommaZoneLists(t *testing.T) { { name: "dnat source list", rule: config.Rule{Action: config.RuleDNAT, Source: "net,lan", Dest: "svr:192.0.2.10", Proto: "tcp", DPort: config.PortSpec{"80"}}, - want: map[string][]string{"prerouting": {"iif=eth0", "iif=eth1"}}, + want: map[string][]string{"prerouting": {"iif=eth0", "iif=eth1"}, + "forward": {"iif=eth0 oif=eth2 daddr=192.0.2.10", "iif=eth1 oif=eth2 daddr=192.0.2.10"}}, + }, + { + name: "dnat source list skips the target zone", + rule: config.Rule{Action: config.RuleDNAT, Source: "net,svr", Dest: "svr:192.0.2.10", Proto: "tcp", DPort: config.PortSpec{"80"}}, + want: map[string][]string{"prerouting": {"iif=eth0"}, "forward": {"iif=eth0 oif=eth2 daddr=192.0.2.10"}}, + }, + { + name: "dnat lone source zone may equal the target zone", + rule: config.Rule{Action: config.RuleDNAT, Source: "svr", Dest: "svr:192.0.2.10", Proto: "tcp", DPort: config.PortSpec{"80"}}, + want: map[string][]string{"prerouting": {"iif=eth2"}, "forward": {"iif=eth2 oif=eth2 daddr=192.0.2.10"}}, + }, + { + name: "dnat exclusion source skips the target zone", + rule: config.Rule{Action: config.RuleDNAT, Source: "all!fw,anycast", Dest: "svr:192.0.2.10", Proto: "tcp", DPort: config.PortSpec{"80"}}, + want: map[string][]string{"prerouting": {"iif=eth1", "iif=eth0"}, + "forward": {"iif=eth1 oif=eth2 daddr=192.0.2.10", "iif=eth0 oif=eth2 daddr=192.0.2.10"}}, + }, + { + name: "dnat intrazone exclusion source keeps the target zone", + rule: config.Rule{Action: config.RuleDNAT, Source: "all+!fw,anycast,lan", Dest: "svr:192.0.2.10", Proto: "tcp", DPort: config.PortSpec{"80"}}, + want: map[string][]string{"prerouting": {"iif=eth0", "iif=eth2"}, + "forward": {"iif=eth0 oif=eth2 daddr=192.0.2.10", "iif=eth2 oif=eth2 daddr=192.0.2.10"}}, + }, + { + name: "dnat to fw accepts in input", + rule: config.Rule{Action: config.RuleDNAT, Source: "net", Dest: "fw:192.0.2.1", Proto: "tcp", DPort: config.PortSpec{"80"}}, + want: map[string][]string{"prerouting": {"iif=eth0"}, "input": {"iif=eth0 daddr=192.0.2.1"}}, + }, + { + name: "redirect accepts in input without daddr", + rule: config.Rule{Action: config.RuleRedirect, Source: "lan", Dest: "fw:192.0.2.1:3128", Proto: "tcp", DPort: config.PortSpec{"80"}}, + want: map[string][]string{"prerouting": {"iif=eth1"}, "input": {"iif=eth1"}}, }, { name: "dnat source address list", rule: config.Rule{Action: config.RuleDNAT, Source: "net:192.0.2.5,198.51.100.5", Dest: "svr:192.0.2.10", Proto: "tcp", DPort: config.PortSpec{"80"}}, - want: map[string][]string{"prerouting": {"iif=eth0 saddr=192.0.2.5", "iif=eth0 saddr=198.51.100.5"}}, + want: map[string][]string{"prerouting": {"iif=eth0 saddr=192.0.2.5", "iif=eth0 saddr=198.51.100.5"}, + "forward": {"iif=eth0 oif=eth2 saddr=192.0.2.5 daddr=192.0.2.10", "iif=eth0 oif=eth2 saddr=198.51.100.5 daddr=192.0.2.10"}}, }, { name: "negated address list stays one AND-ed rule", @@ -1958,17 +1992,20 @@ func TestCompile_CommaZoneLists(t *testing.T) { { name: "dnat origdest", rule: config.Rule{Action: config.RuleDNAT, Source: "net", Dest: "svr:192.0.2.17", Proto: "tcp", DPort: config.PortSpec{"80"}, OrigDest: "203.0.113.5"}, - want: map[string][]string{"prerouting": {"iif=eth0 daddr=203.0.113.5"}}, + want: map[string][]string{"prerouting": {"iif=eth0 daddr=203.0.113.5"}, + "forward": {"iif=eth0 oif=eth2 daddr=192.0.2.17"}}, }, { name: "dnat origdest list", rule: config.Rule{Action: config.RuleDNAT, Source: "net", Dest: "svr:192.0.2.17", Proto: "tcp", DPort: config.PortSpec{"80"}, OrigDest: "203.0.113.5,203.0.113.6"}, - want: map[string][]string{"prerouting": {"iif=eth0 daddr=203.0.113.5", "iif=eth0 daddr=203.0.113.6"}}, + want: map[string][]string{"prerouting": {"iif=eth0 daddr=203.0.113.5", "iif=eth0 daddr=203.0.113.6"}, + "forward": {"iif=eth0 oif=eth2 daddr=192.0.2.17"}}, }, { name: "dnat negated origdest list", rule: config.Rule{Action: config.RuleDNAT, Source: "net", Dest: "svr:192.0.2.17", Proto: "tcp", DPort: config.PortSpec{"80"}, OrigDest: "!203.0.113.5,203.0.113.6"}, - want: map[string][]string{"prerouting": {"iif=eth0 !daddr=203.0.113.5 !daddr=203.0.113.6"}}, + want: map[string][]string{"prerouting": {"iif=eth0 !daddr=203.0.113.5 !daddr=203.0.113.6"}, + "forward": {"iif=eth0 oif=eth2 daddr=192.0.2.17"}}, }, { name: "accept origdest", @@ -2217,6 +2254,45 @@ func TestCompile_DNATGetsNoRuleExtras(t *testing.T) { } } +func TestCompile_DNATImpliedAccept(t *testing.T) { + state, err := NewCompiler(listCfg(func(c *config.Config) { + c.Zones["svr"] = config.Zone{Type: config.ZoneIP} + c.Interfaces = append(c.Interfaces, config.Interface{Zone: "svr", Interface: "eth2"}) + c.Rules = []config.Rule{{Action: config.RuleDNAT, Source: "net", Dest: "svr:192.0.2.17:8080", Proto: "tcp", DPort: config.PortSpec{"80"}}} + })).Compile() + if err != nil { + t.Fatalf("Compile() error: %v", err) + } + fwd := taggedRules(state, "forward", "rule:0") + if len(fwd) != 1 { + t.Fatalf("got %d forward accepts, want 1", len(fwd)) + } + want := append(append(append(append(append(matchIfaceName(true, "eth0"), matchIfaceName(false, "eth2")...), + mustExprs(t)(matchDestCIDR("192.0.2.17"))...), mustExprs(t)(l4Exprs("tcp", "8080"))...), + matchCtBits(expr.CtKeySTATUS, ctStatusDNAT)...), &expr.Verdict{Kind: expr.VerdictAccept}) + if !reflect.DeepEqual(fwd[0].Exprs, want) { + t.Errorf("forward accept = %#v, want %#v", fwd[0].Exprs, want) + } +} + +func mustExprs(t *testing.T) func([]expr.Any, error) []expr.Any { + return func(e []expr.Any, err error) []expr.Any { + t.Helper() + if err != nil { + t.Fatal(err) + } + return e + } +} + +func l4Exprs(proto, port string) ([]expr.Any, error) { + m, err := l4Matches(proto, config.PortSpec{port}, nil) + if err != nil { + return nil, err + } + return m[0].exprs, nil +} + func TestCompile_CommaZoneListLimitErrors(t *testing.T) { for _, r := range []config.Rule{ {Action: config.RuleAccept, Source: "net", Dest: "fw,lan", RateLimit: "10/sec:5"},