11 Commits

Author SHA1 Message Date
benvin 1e32bde555 Merge pull request 'Emit the implied ACCEPT for DNAT and REDIRECT rules' (#29) from benvin/dnat-implied-accept into main
ci/woodpecker/tag/release Pipeline was successful
Reviewed-on: #29
2026-10-04 15:28:05 +11:00
unkin-agent 87be6bc6af Merge remote-tracking branch 'origin/main' into benvin/dnat-implied-accept
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
# Conflicts:
#	internal/nftables/compiler.go
#	internal/nftables/compiler_test.go
2026-10-04 15:22:41 +11:00
benvin 599c483cd8 Merge pull request 'Accept DHCP on dhcp interfaces as shorewall does' (#27) from benvin/dhcp-option into main
Reviewed-on: #27
2026-10-04 15:21:51 +11:00
benvin 110b109d97 Merge pull request 'Include firewall zone in all/any rule expansion' (#28) from benvin/all-includes-fw into main
Reviewed-on: #28
2026-10-04 15:21:24 +11:00
unkin-agent ac63f65f2f Keep rule extras off the DNAT implied accept, expand all/any DNAT sources and match SPORT
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-10-04 15:12:29 +11:00
unkin-agent e3130b6c3b Expand all/any firewall pairs per zone and dedupe fw
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-10-04 15:10:49 +11:00
unkin-agent df9326330a Count firewall-expanded all/any specs for limiter guard
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-10-04 15:08:48 +11:00
unkin-agent b29ed2446e Emit the implied ACCEPT for DNAT and REDIRECT rules
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-10-04 15:08:11 +11:00
unkin-agent 0551120eec Scope DHCP accept rules to IPv4
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-10-04 15:07:41 +11:00
unkin-agent ff4c9b63e8 Include firewall zone in all/any rule expansion
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-10-04 15:06:24 +11:00
unkin-agent e48e9079bd Accept DHCP on dhcp interfaces as shorewall does
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-10-04 15:06:11 +11:00
2 changed files with 487 additions and 89 deletions
+158 -66
View File
@@ -126,40 +126,23 @@ func (c *Compiler) compileDHCP(state *FirewallState) {
continue
}
name := iface.PhysicalName()
// Allow DHCPv4 client traffic (bootpc:68 → bootps:67)
state.Rules["input"] = append(state.Rules["input"], ManagedRule{
Chain: "input",
Exprs: append(append(append(
matchIfaceName(true, name),
matchProtoNum(unix.IPPROTO_UDP)...),
matchSPort(68)...),
matchDPort(67)...,
),
Tag: fmt.Sprintf("dhcp:in:%s", iface.Interface),
})
// Allow DHCPv4 server → client replies
state.Rules["input"] = append(state.Rules["input"], ManagedRule{
Chain: "input",
Exprs: append(append(append(append(
matchIfaceName(true, name),
matchProtoNum(unix.IPPROTO_UDP)...),
matchSPort(67)...),
matchDPort(68)...),
&expr.Verdict{Kind: expr.VerdictAccept},
),
Tag: fmt.Sprintf("dhcp:reply:%s", iface.Interface),
})
state.Rules["output"] = append(state.Rules["output"], ManagedRule{
Chain: "output",
Exprs: append(append(append(append(
matchIfaceName(false, name),
matchProtoNum(unix.IPPROTO_UDP)...),
matchSPort(68)...),
matchDPort(67)...),
&expr.Verdict{Kind: expr.VerdictAccept},
),
Tag: fmt.Sprintf("dhcp:out:%s", iface.Interface),
})
dhcp := func(chain, dir string, ifaceMatch []expr.Any) {
state.Rules[chain] = append(state.Rules[chain], ManagedRule{
Chain: chain,
Exprs: append(append(append(append(ifaceMatch,
matchNFProto(unix.NFPROTO_IPV4)...),
matchProtoNum(unix.IPPROTO_UDP)...),
matchDPortRange(67, 68)...),
&expr.Verdict{Kind: expr.VerdictAccept}),
Tag: fmt.Sprintf("dhcp:%s:%s", dir, iface.Interface),
})
}
// shorewall: udp dport 67:68 both ways between fw and iface, forwarded back out a bridge
dhcp("input", "in", matchIfaceName(true, name))
dhcp("output", "out", matchIfaceName(false, name))
if iface.Options.Bridge {
dhcp("forward", "fwd", append(matchIfaceName(true, name), matchIfaceName(false, name)...))
}
}
}
@@ -381,7 +364,7 @@ func (c *Compiler) compileRules(state *FirewallState) error {
if err != nil {
return fmt.Errorf("rule[%d]: %w", i, err)
}
if len(matches)*c.specCount(rule.Source, rule.Dest, rule.OrigDest, rule.Action) > 1 {
if len(matches)*c.specCount(rule.Source, rule.Dest, rule.OrigDest, fwZone, rule.Action) > 1 {
return fmt.Errorf("rule[%d]: ratelimit/connlimit cannot be combined with proto, port, zone or address lists (each expanded rule would get its own limiter)", i)
}
}
@@ -467,26 +450,32 @@ func (c *Compiler) compileOneRule(state *FirewallState, tag, srcSpec, dstSpec, p
dports, sports config.PortSpec, action config.RuleAction, logLevel string,
dnatDest, origDest string, fwZone string, section config.RuleSection) error {
for _, src := range c.zoneSpecs(srcSpec) {
for _, srcAddr := range splitAddrs(src.Addr) {
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 {
if action == config.RuleDNAT || action == config.RuleRedirect {
for _, src := range c.dnatSourceSpecs(srcSpec, fwZone) {
if dnatSkipsIntrazone(srcSpec, src.Zone, dstSpec) {
continue
}
for _, srcAddr := range splitAddrs(src.Addr) {
if err := c.compileDNATAccept(state, tag+":accept", src.Zone, srcAddr, dstSpec, proto, dports, sports, action, fwZone, section); err != nil {
return err
}
for _, od := range splitAddrs(origDest) {
if err := c.compileDNATRule(state, tag, src.Zone, srcAddr, od, dstSpec, proto, dports, sports, action, logLevel); err != nil {
return err
}
continue
}
for _, dst := range c.zoneSpecs(dstSpec) {
// Exclusion expansion never pairs fw with itself, and pairs a zone with itself only for "all+".
if src.Zone == dst.Zone && (isZoneExclusion(srcSpec) || isZoneExclusion(dstSpec)) &&
(src.Zone == fwZone || !strings.Contains(srcSpec, "+!") && !strings.Contains(dstSpec, "+!")) {
continue
}
for _, dstAddr := range splitAddrs(dst.Addr) {
if err := c.compileZonePair(state, tag, src.Zone, srcAddr, dst.Zone, dstAddr, od, proto,
dports, sports, action, logLevel, fwZone, section); err != nil {
return err
}
}
}
return nil
}
for _, p := range c.zonePairs(srcSpec, dstSpec, fwZone) {
src, dst := p[0], p[1]
for _, srcAddr := range splitAddrs(src.Addr) {
for _, od := range splitAddrs(origDest) {
for _, dstAddr := range splitAddrs(dst.Addr) {
if err := c.compileZonePair(state, tag, src.Zone, srcAddr, dst.Zone, dstAddr, od, proto,
dports, sports, action, logLevel, fwZone, section); err != nil {
return err
}
}
}
@@ -495,19 +484,93 @@ func (c *Compiler) compileOneRule(state *FirewallState, tag, srcSpec, dstSpec, p
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) {
for _, z := range c.zoneSpecs(spec) {
n += len(splitAddrs(z.Addr))
// dnatSourceSpecs hooks DNAT per source zone like shorewall: all/any expand to every zone but fw (prerouting never sees fw traffic).
func (c *Compiler) dnatSourceSpecs(spec, fwZone string) []config.ZoneSpec {
zone, addr := splitZoneSpec(spec)
base, _, _ := strings.Cut(zone, "!")
if base = strings.TrimSuffix(base, "+"); base != "all" && base != "any" {
return c.zoneSpecs(spec)
}
var out []config.ZoneSpec
for _, z := range c.expandZoneRef(zone) {
if z != fwZone {
out = append(out, config.ZoneSpec{Zone: z, Addr: addr})
}
return n
}
n := count(srcSpec) * len(splitAddrs(origDest))
return out
}
// dnatSkipsIntrazone mirrors shorewall: a zone list or all/any source never pairs a zone with itself unless marked "+".
func dnatSkipsIntrazone(srcSpec, srcZone, dstSpec string) bool {
zones, _, _ := strings.Cut(srcSpec, ":")
base, _, _ := strings.Cut(zones, "!")
wild := base == "all" || base == "any" || strings.Contains(base, ",")
dstZone, _, _ := strings.Cut(dstSpec, ":")
return wild && 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, fwZone string, action config.RuleAction) int {
n := 0
if action == config.RuleDNAT || action == config.RuleRedirect {
return n
for _, src := range c.dnatSourceSpecs(srcSpec, fwZone) {
n += len(splitAddrs(src.Addr))
}
return n * len(splitAddrs(origDest))
}
return n * count(dstSpec)
for _, p := range c.zonePairs(srcSpec, dstSpec, fwZone) {
n += len(splitAddrs(p[0].Addr)) * len(splitAddrs(p[1].Addr))
}
return n * len(splitAddrs(origDest))
}
// zonePairs is the src/dst zone expansion of a non-DNAT rule, with fw added beside all/any.
func (c *Compiler) zonePairs(srcSpec, dstSpec, fwZone string) [][2]config.ZoneSpec {
srcs, srcGlobal := withFirewall(c.zoneSpecs(srcSpec), fwZone)
dsts, dstGlobal := withFirewall(c.zoneSpecs(dstSpec), fwZone)
var out [][2]config.ZoneSpec
for _, src := range srcs {
for _, dst := range dsts {
if src.Zone == fwZone && dst.Zone == fwZone && (srcGlobal || dstGlobal) {
continue
}
// Exclusion expansion never pairs fw with itself, and pairs a zone with itself only for "all+".
if src.Zone == dst.Zone && (isZoneExclusion(srcSpec) || isZoneExclusion(dstSpec)) &&
(src.Zone == fwZone || !strings.Contains(srcSpec, "+!") && !strings.Contains(dstSpec, "+!")) {
continue
}
out = append(out, [2]config.ZoneSpec{src, dst})
}
}
return out
}
// zoneSpecs expands a comma zone list; "all"/"any" stay global and "all!x,y" becomes every zone but x and y.
@@ -526,6 +589,26 @@ func (c *Compiler) zoneSpecs(spec string) []config.ZoneSpec {
return out
}
// withFirewall adds the firewall zone beside a global all/any spec, which otherwise only reaches forward.
func withFirewall(specs []config.ZoneSpec, fwZone string) ([]config.ZoneSpec, bool) {
out, global := specs, false
for _, s := range specs {
if fwZone != "" && isGlobalZone(s.Zone) {
global = true
if fw := (config.ZoneSpec{Zone: fwZone, Addr: s.Addr}); !slices.Contains(out, fw) {
out = append(out, fw)
}
}
}
return out, global
}
func isGlobalZone(spec string) bool {
zone, _ := splitZoneSpec(spec)
base := strings.TrimSuffix(zone, "+")
return base == "all" || base == "any"
}
func isZoneExclusion(spec string) bool {
base, _, ok := strings.Cut(spec, "!")
base = strings.TrimSuffix(base, "+")
@@ -595,7 +678,7 @@ func (c *Compiler) compileZonePair(state *FirewallState, tag, srcZone, srcAddr,
}
func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr, origDest, dstSpec, proto string,
dports config.PortSpec, action config.RuleAction, logLevel string) error {
dports, sports config.PortSpec, action config.RuleAction, logLevel string) error {
chain := "prerouting"
parts := strings.SplitN(dstSpec, ":", 3)
@@ -623,7 +706,7 @@ func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr,
}
}
matches, err := l4Matches(proto, dports, nil)
matches, err := l4Matches(proto, dports, sports)
if err != nil {
return err
}
@@ -1554,10 +1637,14 @@ func matchOrigDest(addr string) ([]expr.Any, error) {
if err != nil {
return nil, err
}
return append([]expr.Any{
return append(matchNFProto(proto), dst...), nil
}
func matchNFProto(proto byte) []expr.Any {
return []expr.Any{
&expr.Meta{Key: expr.MetaKeyNFPROTO, Register: 1},
&expr.Cmp{Op: expr.CmpOpEq, Register: 1, Data: []byte{proto}},
}, dst...), nil
}
}
func matchAddrCIDR(cidr string, isSrc bool) ([]expr.Any, error) {
@@ -1645,13 +1732,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,
+329 -23
View File
@@ -1013,38 +1013,84 @@ func TestCompile_DHCP(t *testing.T) {
Zones: map[string]config.Zone{
"fw": {Type: config.ZoneFirewall},
"net": {Type: config.ZoneIP},
"loc": {Type: config.ZoneIP},
},
Interfaces: []config.Interface{
{Zone: "net", Interface: "eth0", Options: config.InterfaceOptions{DHCP: true}},
{Zone: "loc", Interface: "br0", Options: config.InterfaceOptions{DHCP: true, Bridge: true}},
},
Policy: []config.Policy{
{Source: "all", Dest: "all", Action: config.PolicyDrop},
},
PortGroups: make(map[string]config.PortGroup),
}
c := NewCompiler(cfg)
state, err := c.Compile()
state, err := NewCompiler(cfg).Compile()
if err != nil {
t.Fatalf("Compile() error: %v", err)
}
foundIn := false
foundOut := false
for _, r := range state.Rules["input"] {
if r.Tag == "dhcp:in:eth0" || r.Tag == "dhcp:reply:eth0" {
foundIn = true
find := func(chain, tag string) *ManagedRule {
for i, r := range state.Rules[chain] {
if r.Tag == tag {
return &state.Rules[chain][i]
}
}
return nil
}
for _, want := range []struct{ chain, tag, iif, oif string }{
{"input", "dhcp:in:eth0", "eth0", ""},
{"output", "dhcp:out:eth0", "", "eth0"},
{"input", "dhcp:in:br0", "br0", ""},
{"output", "dhcp:out:br0", "", "br0"},
{"forward", "dhcp:fwd:br0", "br0", "br0"},
} {
r := find(want.chain, want.tag)
if r == nil {
t.Errorf("%s: no rule %s", want.chain, want.tag)
continue
}
metas := map[expr.MetaKey][]byte{}
for i := 0; i+1 < len(r.Exprs); i++ {
if m, ok := r.Exprs[i].(*expr.Meta); ok {
if c, ok := r.Exprs[i+1].(*expr.Cmp); ok && c.Op == expr.CmpOpEq {
metas[m.Key] = c.Data
}
}
}
if got := metas[expr.MetaKeyNFPROTO]; !bytes.Equal(got, []byte{unix.NFPROTO_IPV4}) {
t.Errorf("%s: nfproto %v, want ipv4 guard", want.tag, got)
}
if got := metas[expr.MetaKeyL4PROTO]; !bytes.Equal(got, []byte{unix.IPPROTO_UDP}) {
t.Errorf("%s: l4proto %v, want udp", want.tag, got)
}
for key, name := range map[expr.MetaKey]string{expr.MetaKeyIIFNAME: want.iif, expr.MetaKeyOIFNAME: want.oif} {
got, ok := metas[key]
if name == "" {
if ok {
t.Errorf("%s: unexpected meta %v match %q", want.tag, key, got)
}
} else if string(got) != name+"\x00" {
t.Errorf("%s: meta %v %q, want %q", want.tag, key, got, name)
}
}
v, ok := r.Exprs[len(r.Exprs)-1].(*expr.Verdict)
if !ok || v.Kind != expr.VerdictAccept {
t.Errorf("%s: last expr %#v, want accept verdict", want.tag, r.Exprs[len(r.Exprs)-1])
}
var lo, hi []byte
for _, e := range r.Exprs {
if c, ok := e.(*expr.Cmp); ok && c.Op == expr.CmpOpGte {
lo = c.Data
} else if ok && c.Op == expr.CmpOpLte {
hi = c.Data
}
}
if !bytes.Equal(lo, []byte{0, 67}) || !bytes.Equal(hi, []byte{0, 68}) {
t.Errorf("%s: dport range %v-%v, want 67-68", want.tag, lo, hi)
}
}
for _, r := range state.Rules["output"] {
if r.Tag == "dhcp:out:eth0" {
foundOut = true
}
}
if !foundIn {
t.Error("no DHCP input rule found for eth0")
}
if !foundOut {
t.Error("no DHCP output rule found for eth0")
if find("forward", "dhcp:fwd:eth0") != nil {
t.Error("non-bridge eth0 must not forward DHCP")
}
}
@@ -1918,12 +1964,58 @@ 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 all source expands per zone and skips fw and the target zone",
rule: config.Rule{Action: config.RuleDNAT, Source: "all", Dest: "svr:192.0.2.10", Proto: "tcp", DPort: config.PortSpec{"80"}},
want: map[string][]string{"prerouting": {"iif=eth3", "iif=eth1", "iif=eth0"},
"forward": {"iif=eth3 oif=eth2 daddr=192.0.2.10", "iif=eth1 oif=eth2 daddr=192.0.2.10", "iif=eth0 oif=eth2 daddr=192.0.2.10"}},
},
{
name: "dnat any+ source keeps the target zone",
rule: config.Rule{Action: config.RuleDNAT, Source: "any+", Dest: "svr:192.0.2.10", Proto: "tcp", DPort: config.PortSpec{"80"}},
want: map[string][]string{"prerouting": {"iif=eth3", "iif=eth1", "iif=eth0", "iif=eth2"},
"forward": {"iif=eth3 oif=eth2 daddr=192.0.2.10", "iif=eth1 oif=eth2 daddr=192.0.2.10", "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 +2050,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",
@@ -2019,7 +2114,7 @@ func TestCompile_CommaZoneLists(t *testing.T) {
got := map[string][]string{}
for chain, rules := range state.Rules {
for _, r := range rules {
if r.Tag == tag {
if r.Tag == tag || r.Tag == tag+":accept" {
got[chain] = append(got[chain], describeRule(r))
}
}
@@ -2217,11 +2312,116 @@ 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:accept")
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"))...),
dnatStatusExprs...), &expr.Verdict{Kind: expr.VerdictAccept})
if !reflect.DeepEqual(fwd[0].Exprs, want) {
t.Errorf("forward accept = %#v, want %#v", fwd[0].Exprs, want)
}
}
// IPS_DST_NAT = 1<<5, hard-coded so a wrong ctStatusDNAT or ct key fails here.
var dnatStatusExprs = []expr.Any{
&expr.Ct{Key: expr.CtKeySTATUS, Register: 1},
&expr.Bitwise{SourceRegister: 1, DestRegister: 1, Len: 4, Mask: binary.NativeEndian.AppendUint32(nil, 32), Xor: []byte{0, 0, 0, 0}},
&expr.Cmp{Op: expr.CmpOpNeq, Register: 1, Data: []byte{0, 0, 0, 0}},
}
func TestCompile_DNATImpliedAcceptGetsNoRuleExtras(t *testing.T) {
compile := func(r config.Rule) *FirewallState {
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{r}
})).Compile()
if err != nil {
t.Fatalf("Compile() error: %v", err)
}
return state
}
plain := config.Rule{Action: config.RuleDNAT, Source: "net", Dest: "svr:192.0.2.17", Proto: "tcp", DPort: config.PortSpec{"80"}}
extras := plain
extras.RateLimit, extras.Mark, extras.User = "10/sec:5", "0x1", "root"
want, got := compile(plain), compile(extras)
if len(taggedRules(got, "forward", "rule:0:accept")) != 1 {
t.Fatalf("want one forward accept, got %v", got.Rules["forward"])
}
if !reflect.DeepEqual(got.Rules, want.Rules) {
t.Errorf("ratelimit/mark/user changed the DNAT rules:\ngot %#v\nwant %#v", got.Rules, want.Rules)
}
}
func TestCompile_DNATMatchesSport(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", Proto: "tcp",
DPort: config.PortSpec{"80"}, SPort: config.PortSpec{"1024"}}}
})).Compile()
if err != nil {
t.Fatalf("Compile() error: %v", err)
}
m, err := l4Matches("tcp", config.PortSpec{"80"}, config.PortSpec{"1024"})
if err != nil {
t.Fatal(err)
}
for _, r := range append(taggedRules(state, "prerouting", "rule:0"), taggedRules(state, "forward", "rule:0:accept")...) {
if !containsExprs(r.Exprs, m[0].exprs) {
t.Errorf("%s rule lacks the sport match: %#v", r.Chain, r.Exprs)
}
}
}
func containsExprs(haystack, needle []expr.Any) bool {
for i := 0; i+len(needle) <= len(haystack); i++ {
if reflect.DeepEqual(haystack[i:i+len(needle)], needle) {
return true
}
}
return false
}
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"},
{Action: config.RuleAccept, Source: "net,lan", Dest: "fw", ConnLimit: "10"},
{Action: config.RuleAccept, Source: "net", Dest: "fw:192.0.2.1,198.51.100.1", RateLimit: "10/sec"},
{Action: config.RuleDNAT, Source: "net,lan", Dest: "fw:192.0.2.1", RateLimit: "10/sec"},
{Action: config.RuleAccept, Source: "all", Dest: "all", RateLimit: "10/sec"},
{Action: config.RuleAccept, Source: "net", Dest: "all", ConnLimit: "10"},
{Action: config.RuleAccept, Source: "all", Dest: "net", RateLimit: "10/sec"},
{Action: config.RuleAccept, Source: "net,all", Dest: "fw", RateLimit: "10/sec"},
} {
t.Run(r.Source+">"+r.Dest, func(t *testing.T) {
cfg := &config.Config{
@@ -2799,3 +2999,109 @@ func TestCompile_ConntrackHelperZones(t *testing.T) {
})
}
}
func TestCompile_AllIncludesFirewallMatches(t *testing.T) {
cases := []struct {
name string
rule config.Rule
want map[string][]string
}{
{
name: "all address kept on added fw rules",
rule: config.Rule{Action: config.RuleAccept, Source: "all:192.0.2.5", Dest: "all"},
want: map[string][]string{"input": {"saddr=192.0.2.5"}, "output": {"saddr=192.0.2.5"}, "forward": {"saddr=192.0.2.5"}},
},
{
name: "dnat with all source skips fw",
rule: config.Rule{Action: config.RuleDNAT, Source: "all", Dest: "fw:192.0.2.10", Proto: "tcp", DPort: config.PortSpec{"80"}},
want: map[string][]string{"prerouting": {"iif=eth0"}},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cfg := &config.Config{
Settings: config.Settings{TableName: "test", AddressFamily: config.FamilyINET},
Zones: map[string]config.Zone{"fw": {Type: config.ZoneFirewall}, "net": {Type: config.ZoneIP}},
Interfaces: []config.Interface{{Zone: "net", Interface: "eth0"}},
Rules: []config.Rule{tc.rule},
PortGroups: map[string]config.PortGroup{},
}
state := mustCompile(t, cfg)
got := map[string][]string{}
for _, chain := range []string{"prerouting", "input", "output", "forward"} {
for _, r := range taggedRules(state, chain, "rule:0") {
got[chain] = append(got[chain], describeRule(r))
}
}
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("rules = %q, want %q", got, tc.want)
}
})
}
}
func TestCompile_AllIncludesFirewall(t *testing.T) {
cases := []struct {
src, dst string
want map[string]int
}{
{"all", "all", map[string]int{"input": 1, "output": 1, "forward": 1}},
{"net", "all", map[string]int{"input": 1, "output": 0, "forward": 1}},
{"all", "net", map[string]int{"input": 0, "output": 1, "forward": 1}},
{"all", "fw", map[string]int{"input": 1, "output": 0, "forward": 0}},
{"all:192.0.2.0/24", "fw", map[string]int{"input": 1, "output": 0, "forward": 0}},
{"all!fw", "all!fw", map[string]int{"input": 0, "output": 0, "forward": 2}},
{"all+", "all", map[string]int{"input": 1, "output": 1, "forward": 1}},
{"net,all", "fw", map[string]int{"input": 2, "output": 0, "forward": 0}},
{"fw,all", "net", map[string]int{"input": 0, "output": 1, "forward": 1}},
}
for _, tc := range cases {
t.Run(tc.src+"->"+tc.dst, func(t *testing.T) {
cfg := &config.Config{
Settings: config.Settings{TableName: "test", AddressFamily: config.FamilyINET},
Zones: map[string]config.Zone{
"fw": {Type: config.ZoneFirewall},
"net": {Type: config.ZoneIP},
"loc": {Type: config.ZoneIP},
},
Interfaces: []config.Interface{{Zone: "net", Interface: "eth0"}, {Zone: "loc", Interface: "eth1"}},
Rules: []config.Rule{
{Action: config.RuleAccept, Source: tc.src, Dest: tc.dst, Proto: "icmp", DPort: config.PortSpec{"8"}},
},
PortGroups: map[string]config.PortGroup{},
}
state, err := NewCompiler(cfg).Compile()
if err != nil {
t.Fatalf("Compile() error: %v", err)
}
for chain, want := range tc.want {
got := 0
for _, r := range state.Rules[chain] {
if r.Tag == "rule:0" {
got++
}
}
if got != want {
t.Errorf("%s: got %d rule:0 entries, want %d", chain, got, want)
}
}
})
}
}
func TestSpecCount_CommaAllMatchesExpansion(t *testing.T) {
c := NewCompiler(&config.Config{
Zones: map[string]config.Zone{"fw": {Type: config.ZoneFirewall}, "net": {Type: config.ZoneIP}},
})
for _, tc := range []struct {
src, dst string
want int
}{
{"net,all", "fw", 2},
{"fw,all", "net", 2},
} {
if got := c.specCount(tc.src, tc.dst, "", "fw", config.RuleAccept); got != tc.want {
t.Errorf("specCount(%s, %s) = %d, want %d", tc.src, tc.dst, got, tc.want)
}
}
}