Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c557c4b78a | |||
| 9a7d1ab35b | |||
| 445d14c61e | |||
| 63c46fec81 | |||
| 5238886c6e | |||
| 532bd80a8a | |||
| 036021d726 | |||
| ff5a52b9e2 | |||
| 44e1ba852e | |||
| 34cf6dc9ab | |||
| b5be665902 |
@@ -3,19 +3,18 @@ module git.unkin.net/unkin/tomswall
|
||||
go 1.23
|
||||
|
||||
require (
|
||||
github.com/google/nftables v0.2.0
|
||||
github.com/mdlayher/netlink v1.7.2
|
||||
github.com/google/nftables v0.3.0
|
||||
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42
|
||||
github.com/spf13/cobra v1.8.1
|
||||
golang.org/x/sys v0.18.0
|
||||
golang.org/x/sys v0.28.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/google/go-cmp v0.6.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/josharian/native v1.1.0 // indirect
|
||||
github.com/mdlayher/socket v0.5.1 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
golang.org/x/net v0.23.0 // indirect
|
||||
golang.org/x/net v0.33.0 // indirect
|
||||
golang.org/x/sync v0.6.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/nftables v0.2.0 h1:PbJwaBmbVLzpeldoeUKGkE2RjstrjPKMl6oLrfEJ6/8=
|
||||
github.com/google/nftables v0.2.0/go.mod h1:Beg6V6zZ3oEn0JuiUQ4wqwuyqqzasOltcoXPtgLbFp4=
|
||||
github.com/google/nftables v0.3.0 h1:bkyZ0cbpVeMHXOrtlFc8ISmfVqq5gPJukoYieyVmITg=
|
||||
github.com/google/nftables v0.3.0/go.mod h1:BCp9FsrbF1Fn/Yu6CLUc9GGZFw/+hsxfluNXXmxBfRM=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLA=
|
||||
github.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
|
||||
github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/g=
|
||||
github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw=
|
||||
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42 h1:A1Cq6Ysb0GM0tpKMbdCXCIfBclan4oHk1Jb+Hrejirg=
|
||||
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42/go.mod h1:BB4YCPDOzfy7FniQ/lxuYQ3dgmM2cZumHbK8RpTjN2o=
|
||||
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
|
||||
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
@@ -16,14 +14,14 @@ github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
|
||||
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/vishvananda/netns v0.0.0-20180720170159-13995c7128cc h1:R83G5ikgLMxrBvLh22JhdfI8K6YXEPHx5P03Uu3DRs4=
|
||||
github.com/vishvananda/netns v0.0.0-20180720170159-13995c7128cc/go.mod h1:ZjcWmFBXmLKZu9Nxj3WKYEafiSqer2rnvPr0en9UNpI=
|
||||
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
|
||||
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||
github.com/vishvananda/netns v0.0.4 h1:Oeaw1EM2JMxD51g9uhtC0D7erkIjgmj8+JZc26m1YX8=
|
||||
github.com/vishvananda/netns v0.0.4/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
|
||||
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
+155
-49
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -205,16 +206,81 @@ func (c *Compiler) compileBlrules(state *FirewallState) error {
|
||||
}
|
||||
if err := c.compileOneRule(state, tag, rule.Source, rule.Dest,
|
||||
rule.Proto, rule.DPort, rule.SPort,
|
||||
action, rule.Log, "", fwZone, ""); err != nil {
|
||||
action, rule.Log, "", "", fwZone, ""); err != nil {
|
||||
return fmt.Errorf("blrule[%d]: %w", i, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// helperProtos is each kernel helper's default transport, used when an entry gives no proto.
|
||||
var helperProtos = map[string]string{
|
||||
"amanda": "udp", "ftp": "tcp", "irc": "tcp", "netbios-ns": "udp", "pptp": "tcp",
|
||||
"Q.931": "tcp", "RAS": "udp", "sane": "tcp", "sip": "udp", "snmp": "udp", "tftp": "udp",
|
||||
}
|
||||
|
||||
// compileHelper declares a ct helper object per (helper, proto) and assigns it
|
||||
// after conntrack (-200) has created the entry; a raw-priority assignment is a no-op.
|
||||
func (c *Compiler) compileHelper(state *FirewallState, tag string, ct config.ConntrackRule) error {
|
||||
if ct.Source != "" || ct.Dest != "" {
|
||||
slog.Warn("conntrack helper source/dest not supported, assigning globally", "rule", tag, "helper", ct.Helper)
|
||||
}
|
||||
chains := []string{"helper_prerouting", "helper_output"}
|
||||
switch ct.Chain {
|
||||
case config.ConntrackPrerouting:
|
||||
chains = chains[:1]
|
||||
case config.ConntrackOutput:
|
||||
chains = chains[1:]
|
||||
}
|
||||
|
||||
proto := ct.Proto
|
||||
if proto == "" {
|
||||
if proto = helperProtos[ct.Helper]; proto == "" {
|
||||
return fmt.Errorf("proto required for helper %q", ct.Helper)
|
||||
}
|
||||
}
|
||||
for _, p := range strings.Split(proto, ",") {
|
||||
p = strings.TrimSpace(p)
|
||||
n, err := protoNumber(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := ct.Helper
|
||||
if p != helperProtos[ct.Helper] {
|
||||
name += "-" + p
|
||||
}
|
||||
if !slices.ContainsFunc(state.Helpers, func(h Helper) bool { return h.Name == name }) {
|
||||
state.Helpers = append(state.Helpers, Helper{Name: name,
|
||||
Helper: expr.CtHelper{Name: ct.Helper, L3Proto: unix.NFPROTO_INET, L4Proto: n}})
|
||||
}
|
||||
|
||||
matches, err := l4Matches(p, ct.DPort, ct.SPort)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, chain := range chains {
|
||||
for _, m := range matches {
|
||||
state.Rules[chain] = append(state.Rules[chain], ManagedRule{
|
||||
Chain: chain,
|
||||
Exprs: append(append([]expr.Any{}, m.exprs...),
|
||||
&expr.Objref{Type: unix.NFT_OBJECT_CT_HELPER, Name: name}),
|
||||
Tag: tag + ":" + chain,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Compiler) compileConntrack(state *FirewallState) error {
|
||||
for i, ct := range c.cfg.Conntrack {
|
||||
tag := fmt.Sprintf("conntrack:%d", i)
|
||||
if ct.Action == config.ConntrackHelper {
|
||||
if err := c.compileHelper(state, tag, ct); err != nil {
|
||||
return fmt.Errorf("conntrack[%d]: %w", i, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
chains := []string{"prerouting"}
|
||||
switch ct.Chain {
|
||||
@@ -236,8 +302,6 @@ func (c *Compiler) compileConntrack(state *FirewallState) error {
|
||||
switch ct.Action {
|
||||
case config.ConntrackNoTrack:
|
||||
exprs = append(exprs, &expr.Notrack{})
|
||||
case config.ConntrackHelper:
|
||||
continue
|
||||
case config.ConntrackDrop:
|
||||
exprs = append(exprs, &expr.Verdict{Kind: expr.VerdictDrop})
|
||||
}
|
||||
@@ -276,14 +340,14 @@ func (c *Compiler) compileRules(state *FirewallState) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("rule[%d]: %w", i, err)
|
||||
}
|
||||
if len(matches)*specCount(rule.Source, rule.Dest, rule.Action) > 1 {
|
||||
if len(matches)*specCount(rule.Source, rule.Dest, rule.OrigDest, 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)
|
||||
}
|
||||
}
|
||||
|
||||
if err := c.compileOneRule(state, tag, rule.Source, rule.Dest,
|
||||
proto, dports, sport,
|
||||
rule.Action, rule.Log, rule.Dest, fwZone, rule.Section); err != nil {
|
||||
rule.Action, rule.Log, rule.Dest, rule.OrigDest, fwZone, rule.Section); err != nil {
|
||||
return fmt.Errorf("rule[%d]: %w", i, err)
|
||||
}
|
||||
|
||||
@@ -360,22 +424,24 @@ func (c *Compiler) applyChainExtras(state *FirewallState, chain, tag string, rul
|
||||
|
||||
func (c *Compiler) compileOneRule(state *FirewallState, tag, srcSpec, dstSpec, proto string,
|
||||
dports, sports config.PortSpec, action config.RuleAction, logLevel string,
|
||||
dnatDest string, fwZone string, section config.RuleSection) error {
|
||||
dnatDest, origDest string, fwZone string, section config.RuleSection) error {
|
||||
|
||||
for _, src := range zoneSpecs(srcSpec) {
|
||||
for _, srcAddr := range splitAddrs(src.Addr) {
|
||||
if action == config.RuleDNAT || action == config.RuleRedirect {
|
||||
if err := c.compileDNATRule(state, tag, src.Zone, srcAddr, dstSpec, proto, dports, action, logLevel); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, dst := range zoneSpecs(dstSpec) {
|
||||
for _, dstAddr := range splitAddrs(dst.Addr) {
|
||||
if err := c.compileZonePair(state, tag, src.Zone, srcAddr, dst.Zone, dstAddr, proto,
|
||||
dports, sports, action, logLevel, fwZone, section); err != nil {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, dst := range zoneSpecs(dstSpec) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -384,17 +450,18 @@ func (c *Compiler) compileOneRule(state *FirewallState, tag, srcSpec, dstSpec, p
|
||||
}
|
||||
|
||||
// specCount is how many zone/address combinations compileOneRule expands src and dst into.
|
||||
func specCount(srcSpec, dstSpec string, action config.RuleAction) int {
|
||||
func specCount(srcSpec, dstSpec, origDest string, action config.RuleAction) int {
|
||||
count := func(spec string) (n int) {
|
||||
for _, z := range zoneSpecs(spec) {
|
||||
n += len(splitAddrs(z.Addr))
|
||||
}
|
||||
return n
|
||||
}
|
||||
n := count(srcSpec) * len(splitAddrs(origDest))
|
||||
if action == config.RuleDNAT || action == config.RuleRedirect {
|
||||
return count(srcSpec)
|
||||
return n
|
||||
}
|
||||
return count(srcSpec) * count(dstSpec)
|
||||
return n * count(dstSpec)
|
||||
}
|
||||
|
||||
// zoneSpecs expands a comma zone list; "all"/"any" forms keep their own comma (exclusion) syntax.
|
||||
@@ -414,12 +481,16 @@ func splitAddrs(addr string) []string {
|
||||
return strings.Split(addr, ",")
|
||||
}
|
||||
|
||||
func (c *Compiler) compileZonePair(state *FirewallState, tag, srcZone, srcAddr, dstZone, dstAddr, proto string,
|
||||
func (c *Compiler) compileZonePair(state *FirewallState, tag, srcZone, srcAddr, dstZone, dstAddr, origDest, proto string,
|
||||
dports, sports config.PortSpec, action config.RuleAction, logLevel string,
|
||||
fwZone string, section config.RuleSection) error {
|
||||
srcIfaces := c.resolveZoneInterfaces(srcZone)
|
||||
dstIfaces := c.resolveZoneInterfaces(dstZone)
|
||||
srcIfaces := c.resolveZoneInterfaces(srcZone, srcAddr)
|
||||
dstIfaces := c.resolveZoneInterfaces(dstZone, dstAddr)
|
||||
chain := c.selectChain(srcZone, dstZone, fwZone)
|
||||
// ponytail: forward daddr is post-DNAT; lift with `ct original daddr` (expr.Ct Direction, google/nftables v0.3.0).
|
||||
if origDest != "" && chain == "forward" {
|
||||
return fmt.Errorf("origdest: ORIGDEST on forwarded rules is not supported yet")
|
||||
}
|
||||
|
||||
for _, srcIface := range srcIfaces {
|
||||
for _, dstIface := range dstIfaces {
|
||||
@@ -427,6 +498,15 @@ func (c *Compiler) compileZonePair(state *FirewallState, tag, srcZone, srcAddr,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if origDest != "" {
|
||||
od, err := matchOrigDest(origDest)
|
||||
if err != nil {
|
||||
return fmt.Errorf("origdest: %w", err)
|
||||
}
|
||||
for i := range matches {
|
||||
matches[i].exprs = append(matches[i].exprs, od...)
|
||||
}
|
||||
}
|
||||
|
||||
for _, m := range matches {
|
||||
exprs := m.exprs
|
||||
@@ -455,7 +535,7 @@ func (c *Compiler) compileZonePair(state *FirewallState, tag, srcZone, srcAddr,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr, dstSpec, proto string,
|
||||
func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr, origDest, dstSpec, proto string,
|
||||
dports config.PortSpec, action config.RuleAction, logLevel string) error {
|
||||
chain := "prerouting"
|
||||
|
||||
@@ -474,7 +554,15 @@ func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr,
|
||||
dnatPort = uint16(p)
|
||||
}
|
||||
|
||||
srcIfaces := c.resolveZoneInterfaces(srcZone)
|
||||
srcIfaces := c.resolveZoneInterfaces(srcZone, srcAddr)
|
||||
|
||||
var odExprs []expr.Any
|
||||
if origDest != "" {
|
||||
var err error
|
||||
if odExprs, err = matchOrigDest(origDest); err != nil {
|
||||
return fmt.Errorf("origdest: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
matches, err := l4Matches(proto, dports, nil)
|
||||
if err != nil {
|
||||
@@ -501,6 +589,7 @@ func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr,
|
||||
}
|
||||
exprs = append(exprs, src...)
|
||||
}
|
||||
exprs = append(exprs, odExprs...)
|
||||
|
||||
exprs = append(exprs, m.exprs...)
|
||||
|
||||
@@ -538,6 +627,7 @@ func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr,
|
||||
)
|
||||
natExpr.RegProtoMin = 2
|
||||
natExpr.RegProtoMax = 2
|
||||
natExpr.Specified = true
|
||||
}
|
||||
exprs = append(exprs, natExpr)
|
||||
} else {
|
||||
@@ -558,6 +648,7 @@ func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr,
|
||||
)
|
||||
natExpr.RegProtoMin = 2
|
||||
natExpr.RegProtoMax = 2
|
||||
natExpr.Specified = true
|
||||
}
|
||||
exprs = append(exprs, natExpr)
|
||||
}
|
||||
@@ -589,8 +680,8 @@ func (c *Compiler) compilePolicies(state *FirewallState) error {
|
||||
}
|
||||
|
||||
chain := c.selectChain(sz, dz, fwZone)
|
||||
srcIfaces := c.resolveZoneInterfaces(sz)
|
||||
dstIfaces := c.resolveZoneInterfaces(dz)
|
||||
srcIfaces := c.resolveZoneInterfaces(sz, "")
|
||||
dstIfaces := c.resolveZoneInterfaces(dz, "")
|
||||
|
||||
for _, si := range srcIfaces {
|
||||
for _, di := range dstIfaces {
|
||||
@@ -599,7 +690,7 @@ func (c *Compiler) compilePolicies(state *FirewallState) error {
|
||||
if si != "" {
|
||||
exprs = append(exprs, matchIfaceName(true, si)...)
|
||||
}
|
||||
if di != "" && chain == "forward" {
|
||||
if di != "" && chain != "input" {
|
||||
exprs = append(exprs, matchIfaceName(false, di)...)
|
||||
}
|
||||
|
||||
@@ -932,34 +1023,25 @@ func (c *Compiler) selectChain(srcZone, dstZone, fwZone string) string {
|
||||
return "forward"
|
||||
}
|
||||
|
||||
func (c *Compiler) resolveZoneInterfaces(zone string) []string {
|
||||
if zone == "all" || zone == "" {
|
||||
// resolveZoneInterfaces returns nil (fail closed) for a zone with no interfaces unless a non-negated address match narrows the rule.
|
||||
func (c *Compiler) resolveZoneInterfaces(zone, addr string) []string {
|
||||
if z, ok := c.cfg.Zones[zone]; !ok || z.Type == config.ZoneFirewall {
|
||||
return []string{""}
|
||||
}
|
||||
ifaces := c.cfg.ZoneInterfaces(zone)
|
||||
if len(ifaces) > 0 {
|
||||
if ifaces := c.cfg.ZoneInterfaces(zone); len(ifaces) > 0 {
|
||||
return ifaces
|
||||
}
|
||||
if z, ok := c.cfg.Zones[zone]; ok && z.Type == config.ZoneIP && !c.zoneHasHosts(zone) {
|
||||
if !c.warned[zone] {
|
||||
if c.warned == nil {
|
||||
c.warned = map[string]bool{}
|
||||
}
|
||||
c.warned[zone] = true
|
||||
slog.Warn("compiler: zone has no interfaces, skipping its rules", "zone", zone)
|
||||
}
|
||||
return nil
|
||||
if addr != "" && !strings.HasPrefix(addr, "!") {
|
||||
return []string{""}
|
||||
}
|
||||
return []string{""}
|
||||
}
|
||||
|
||||
func (c *Compiler) zoneHasHosts(zone string) bool {
|
||||
for _, h := range c.cfg.Hosts {
|
||||
if h.Zone == zone {
|
||||
return true
|
||||
if !c.warned[zone] {
|
||||
if c.warned == nil {
|
||||
c.warned = map[string]bool{}
|
||||
}
|
||||
c.warned[zone] = true
|
||||
slog.Warn("compiler: zone has no interfaces, skipping its rules", "zone", zone)
|
||||
}
|
||||
return false
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Compiler) expandZoneRef(ref string) []string {
|
||||
@@ -997,7 +1079,7 @@ func (c *Compiler) buildMatchExprs(srcIface, dstIface, chain, proto string, dpor
|
||||
if srcIface != "" {
|
||||
exprs = append(exprs, matchIfaceName(true, srcIface)...)
|
||||
}
|
||||
if dstIface != "" && chain == "forward" {
|
||||
if dstIface != "" && chain != "input" {
|
||||
exprs = append(exprs, matchIfaceName(false, dstIface)...)
|
||||
}
|
||||
|
||||
@@ -1386,6 +1468,30 @@ func matchDestCIDR(cidr string) ([]expr.Any, error) {
|
||||
return matchAddrCIDR(cidr, false)
|
||||
}
|
||||
|
||||
// matchOrigDest guards the daddr match with the address's nfproto so it is family-correct in the inet table.
|
||||
func matchOrigDest(addr string) ([]expr.Any, error) {
|
||||
var proto byte
|
||||
for i, a := range strings.Split(strings.TrimPrefix(addr, "!"), ",") {
|
||||
a, _, _ = strings.Cut(a, "/")
|
||||
p := byte(unix.NFPROTO_IPV6)
|
||||
if ip := net.ParseIP(a); ip != nil && ip.To4() != nil {
|
||||
p = unix.NFPROTO_IPV4
|
||||
}
|
||||
if i > 0 && p != proto {
|
||||
return nil, fmt.Errorf("%q mixes IPv4 and IPv6 addresses", addr)
|
||||
}
|
||||
proto = p
|
||||
}
|
||||
dst, err := matchDestCIDR(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append([]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) {
|
||||
negated := false
|
||||
if strings.HasPrefix(cidr, "!") {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package nftables
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -141,17 +144,17 @@ func TestCompiler_ResolveZoneInterfaces(t *testing.T) {
|
||||
}
|
||||
c := NewCompiler(cfg)
|
||||
|
||||
ifaces := c.resolveZoneInterfaces("net")
|
||||
ifaces := c.resolveZoneInterfaces("net", "")
|
||||
if len(ifaces) != 1 || ifaces[0] != "eth0" {
|
||||
t.Errorf("resolveZoneInterfaces(net) = %v, want [eth0]", ifaces)
|
||||
}
|
||||
|
||||
ifaces = c.resolveZoneInterfaces("all")
|
||||
ifaces = c.resolveZoneInterfaces("all", "")
|
||||
if len(ifaces) != 1 || ifaces[0] != "" {
|
||||
t.Errorf("resolveZoneInterfaces(all) = %v, want [\"\"]", ifaces)
|
||||
}
|
||||
|
||||
ifaces = c.resolveZoneInterfaces("fw")
|
||||
ifaces = c.resolveZoneInterfaces("fw", "")
|
||||
if len(ifaces) != 1 || ifaces[0] != "" {
|
||||
t.Errorf("resolveZoneInterfaces(fw) = %v, want [\"\"]", ifaces)
|
||||
}
|
||||
@@ -453,15 +456,19 @@ func TestCompile_DNAT(t *testing.T) {
|
||||
t.Fatalf("Compile() error: %v", err)
|
||||
}
|
||||
|
||||
found := false
|
||||
var nat *expr.NAT
|
||||
for _, r := range state.Rules["prerouting"] {
|
||||
if r.Tag == "rule:0" {
|
||||
found = true
|
||||
nat, _ = r.Exprs[len(r.Exprs)-1].(*expr.NAT)
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("no DNAT rule found in prerouting chain")
|
||||
if nat == nil {
|
||||
t.Fatal("no DNAT rule found in prerouting chain")
|
||||
}
|
||||
// The kernel reports PROTO_SPECIFIED whenever a port register is set.
|
||||
if nat.RegProtoMin != 2 || !nat.Specified {
|
||||
t.Errorf("DNAT with port must set RegProtoMin and Specified to match kernel readback, got %+v", nat)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1758,6 +1765,83 @@ func TestCompile_PortAndProtoLists(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompile_OutputPolicyMatchesOif(t *testing.T) {
|
||||
cfg := listCfg(func(c *config.Config) {
|
||||
c.Zones["lan"] = config.Zone{Type: config.ZoneIP}
|
||||
c.Interfaces = append(c.Interfaces, config.Interface{Zone: "lan", Interface: "eth1"})
|
||||
c.Policy = []config.Policy{{Source: "fw", Dest: "lan", Action: config.PolicyAccept}}
|
||||
})
|
||||
got := taggedRules(mustCompile(t, cfg), "output", "policy:0")
|
||||
if len(got) != 1 || describeRule(got[0]) != "oif=eth1" {
|
||||
t.Fatalf("fw->lan policy = %v, want one rule oif=eth1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompile_InterfacelessZonesFailClosed(t *testing.T) {
|
||||
ipsec := func(c *config.Config) { c.Zones["ips"] = config.Zone{Type: config.ZoneIPSec} }
|
||||
rule := func(dest string) func(*config.Config) {
|
||||
return func(c *config.Config) {
|
||||
ipsec(c)
|
||||
c.Rules = []config.Rule{{Action: config.RuleAccept, Source: "fw", Dest: dest}}
|
||||
}
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
mod func(*config.Config)
|
||||
tag string
|
||||
want int
|
||||
warns []string
|
||||
}{
|
||||
{"ipsec zone without interface", func(c *config.Config) {
|
||||
ipsec(c)
|
||||
c.Policy = []config.Policy{{Source: "fw", Dest: "ips", Action: config.PolicyAccept}}
|
||||
}, "policy:0", 0, []string{"ips"}},
|
||||
{"hosts-only zone", func(c *config.Config) {
|
||||
c.Zones["hst"] = config.Zone{Type: config.ZoneIP}
|
||||
c.Hosts = []config.Host{{Zone: "hst", Interface: "eth0", Addresses: []string{"192.0.2.0/24"}}}
|
||||
c.Policy = []config.Policy{{Source: "fw", Dest: "hst", Action: config.PolicyAccept}}
|
||||
}, "policy:0", 0, []string{"hst"}},
|
||||
{"fw all expansion keeps zones with interfaces", func(c *config.Config) {
|
||||
ipsec(c)
|
||||
c.Zones["hst"] = config.Zone{Type: config.ZoneIP}
|
||||
c.Hosts = []config.Host{{Zone: "hst", Interface: "eth0", Addresses: []string{"192.0.2.0/24"}}}
|
||||
c.Policy = []config.Policy{{Source: "fw", Dest: "all", Action: config.PolicyDrop}}
|
||||
}, "policy:0", 1, []string{"hst", "ips"}},
|
||||
{"negated address does not scope", rule("ips:!192.0.2.1"), "rule:0", 0, []string{"ips"}},
|
||||
{"address scopes", rule("ips:192.0.2.1"), "rule:0", 1, []string{"ips"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
prev := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil)))
|
||||
defer slog.SetDefault(prev)
|
||||
|
||||
state := mustCompile(t, listCfg(tt.mod))
|
||||
got := 0
|
||||
for chain := range state.Rules {
|
||||
for _, r := range taggedRules(state, chain, tt.tag) {
|
||||
got++
|
||||
if describeRule(r) == "" {
|
||||
t.Errorf("%s: un-scoped rule", chain)
|
||||
}
|
||||
}
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("got %d %s rules, want %d", got, tt.tag, tt.want)
|
||||
}
|
||||
if n := strings.Count(logs.String(), "zone has no interfaces"); n != len(tt.warns) {
|
||||
t.Errorf("got %d warnings, want %d:\n%s", n, len(tt.warns), logs.String())
|
||||
}
|
||||
for _, z := range tt.warns {
|
||||
if n := strings.Count(logs.String(), "zone="+z+"\n"); n != 1 {
|
||||
t.Errorf("zone %s warned %d times, want 1", z, n)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// describeRule renders a rule's iif/oif/saddr/daddr matches, e.g. "iif=eth1 oif=eth2 daddr=192.0.2.1".
|
||||
func describeRule(r ManagedRule) string {
|
||||
var parts []string
|
||||
@@ -1781,12 +1865,12 @@ func describeRule(r ManagedRule) string {
|
||||
parts = append(parts, "oif="+strings.TrimRight(string(cmp.Data), "\x00"))
|
||||
}
|
||||
case *expr.Payload:
|
||||
if m.Base == expr.PayloadBaseNetworkHeader && m.Len == 4 {
|
||||
name := map[uint32]string{12: "saddr", 16: "daddr"}[m.Offset]
|
||||
if m.Base == expr.PayloadBaseNetworkHeader && (m.Len == 4 || m.Len == 16) {
|
||||
name := map[uint32]string{12: "saddr", 16: "daddr", 8: "saddr", 24: "daddr"}[m.Offset]
|
||||
if cmp.Op == expr.CmpOpNeq {
|
||||
name = "!" + name
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf("%s=%d.%d.%d.%d", name, cmp.Data[0], cmp.Data[1], cmp.Data[2], cmp.Data[3]))
|
||||
parts = append(parts, name+"="+net.IP(cmp.Data).String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1803,7 +1887,7 @@ func TestCompile_CommaZoneLists(t *testing.T) {
|
||||
{
|
||||
name: "fw in source list goes to output",
|
||||
rule: config.Rule{Action: config.RuleAccept, Source: "fw,lan", Dest: "svr", Proto: "tcp", DPort: config.PortSpec{"22"}},
|
||||
want: map[string][]string{"output": {""}, "forward": {"iif=eth1 oif=eth2"}},
|
||||
want: map[string][]string{"output": {"oif=eth2"}, "forward": {"iif=eth1 oif=eth2"}},
|
||||
},
|
||||
{
|
||||
name: "dest list with fw splits input and forward",
|
||||
@@ -1846,9 +1930,54 @@ func TestCompile_CommaZoneLists(t *testing.T) {
|
||||
want: map[string][]string{"forward": {"iif=eth1 oif=eth3", "iif=eth1 oif=eth0"}},
|
||||
},
|
||||
{
|
||||
name: "interface-less ipsec zone keeps zone-agnostic rule, ip zone skipped",
|
||||
name: "interface-less zones are skipped",
|
||||
rule: config.Rule{Action: config.RuleAccept, Source: "lan", Dest: "vpn,dmz"},
|
||||
want: map[string][]string{"forward": {"iif=eth1"}},
|
||||
want: map[string][]string{},
|
||||
},
|
||||
{
|
||||
name: "interface-less zone kept when address narrows it",
|
||||
rule: config.Rule{Action: config.RuleAccept, Source: "lan", Dest: "vpn:192.0.2.1"},
|
||||
want: map[string][]string{"forward": {"iif=eth1 daddr=192.0.2.1"}},
|
||||
},
|
||||
{
|
||||
name: "fw source matches dest zone oif",
|
||||
rule: config.Rule{Action: config.RuleAccept, Source: "fw", Dest: "lan,vpn,dmz", Proto: "tcp", DPort: config.PortSpec{"22"}},
|
||||
want: map[string][]string{"output": {"oif=eth1"}},
|
||||
},
|
||||
{
|
||||
name: "fw to all has no oif",
|
||||
rule: config.Rule{Action: config.RuleAccept, Source: "fw", Dest: "all:192.0.2.1"},
|
||||
want: map[string][]string{"output": {"daddr=192.0.2.1"}},
|
||||
},
|
||||
{
|
||||
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"}},
|
||||
},
|
||||
{
|
||||
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"}},
|
||||
},
|
||||
{
|
||||
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"}},
|
||||
},
|
||||
{
|
||||
name: "accept origdest",
|
||||
rule: config.Rule{Action: config.RuleAccept, Source: "net", Dest: "fw", Proto: "tcp", DPort: config.PortSpec{"22"}, OrigDest: "203.0.113.5"},
|
||||
want: map[string][]string{"input": {"iif=eth0 daddr=203.0.113.5"}},
|
||||
},
|
||||
{
|
||||
name: "origdest does not scope interface-less zone",
|
||||
rule: config.Rule{Action: config.RuleAccept, Source: "vpn", Dest: "fw", Proto: "tcp", DPort: config.PortSpec{"22"}, OrigDest: "203.0.113.5"},
|
||||
want: map[string][]string{},
|
||||
},
|
||||
{
|
||||
name: "accept ipv6 origdest",
|
||||
rule: config.Rule{Action: config.RuleAccept, Source: "net", Dest: "fw", Proto: "tcp", DPort: config.PortSpec{"22"}, OrigDest: "2001:db8::5"},
|
||||
want: map[string][]string{"input": {"iif=eth0 daddr=2001:db8::5"}},
|
||||
},
|
||||
{
|
||||
name: "blrule zone list",
|
||||
@@ -2255,3 +2384,96 @@ func TestCompile_ColonRanges(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchOrigDest_FamilyGuard(t *testing.T) {
|
||||
for addr, want := range map[string]byte{
|
||||
"203.0.113.5": unix.NFPROTO_IPV4,
|
||||
"!203.0.113.0/24,192.0.2.1": unix.NFPROTO_IPV4,
|
||||
"2001:db8::5": unix.NFPROTO_IPV6,
|
||||
} {
|
||||
e, err := matchOrigDest(addr)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", addr, err)
|
||||
}
|
||||
if m, ok := e[0].(*expr.Meta); !ok || m.Key != expr.MetaKeyNFPROTO || e[1].(*expr.Cmp).Data[0] != want {
|
||||
t.Errorf("%s: missing nfproto %d guard: %v", addr, want, e[:2])
|
||||
}
|
||||
}
|
||||
if _, err := matchOrigDest("!203.0.113.5,2001:db8::5"); err == nil {
|
||||
t.Error("mixed IPv4/IPv6 origdest: want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompile_OrigDestForwardRejected(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}, "svr": {Type: config.ZoneIP}},
|
||||
Interfaces: []config.Interface{{Zone: "net", Interface: "eth0"}, {Zone: "svr", Interface: "eth2"}},
|
||||
Rules: []config.Rule{{Action: config.RuleAccept, Source: "net", Dest: "svr", Proto: "tcp", DPort: config.PortSpec{"80"}, OrigDest: "203.0.113.5"}},
|
||||
PortGroups: make(map[string]config.PortGroup),
|
||||
}
|
||||
_, err := NewCompiler(cfg).Compile()
|
||||
if err == nil || !strings.Contains(err.Error(), "not supported yet") {
|
||||
t.Fatalf("Compile() error = %v, want forwarded ORIGDEST rejection", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompile_ConntrackHelper(t *testing.T) {
|
||||
compile := func(rules ...config.ConntrackRule) (*FirewallState, error) {
|
||||
cfg := &config.Config{
|
||||
Settings: config.Settings{TableName: "test", AddressFamily: config.FamilyINET},
|
||||
Zones: map[string]config.Zone{"fw": {Type: config.ZoneFirewall}},
|
||||
Conntrack: rules,
|
||||
PortGroups: map[string]config.PortGroup{},
|
||||
}
|
||||
return NewCompiler(cfg).Compile()
|
||||
}
|
||||
|
||||
state, err := compile(
|
||||
config.ConntrackRule{Action: config.ConntrackHelper, Helper: "ftp", Proto: "tcp", DPort: config.PortSpec{"21"}},
|
||||
config.ConntrackRule{Action: config.ConntrackHelper, Helper: "sip", Proto: "tcp", DPort: config.PortSpec{"5060"}, Chain: config.ConntrackPrerouting},
|
||||
config.ConntrackRule{Action: config.ConntrackHelper, Helper: "tftp", Chain: config.ConntrackOutput},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
want := []Helper{
|
||||
{"ftp", expr.CtHelper{Name: "ftp", L3Proto: unix.NFPROTO_INET, L4Proto: unix.IPPROTO_TCP}},
|
||||
{"sip-tcp", expr.CtHelper{Name: "sip", L3Proto: unix.NFPROTO_INET, L4Proto: unix.IPPROTO_TCP}},
|
||||
{"tftp", expr.CtHelper{Name: "tftp", L3Proto: unix.NFPROTO_INET, L4Proto: unix.IPPROTO_UDP}},
|
||||
}
|
||||
if !reflect.DeepEqual(state.Helpers, want) {
|
||||
t.Errorf("helpers = %+v, want %+v", state.Helpers, want)
|
||||
}
|
||||
|
||||
refs := func(chain string) []string {
|
||||
var out []string
|
||||
for _, r := range state.Rules[chain] {
|
||||
ref, ok := r.Exprs[len(r.Exprs)-1].(*expr.Objref)
|
||||
if !ok || ref.Type != unix.NFT_OBJECT_CT_HELPER {
|
||||
t.Fatalf("%s: rule %s does not end in a ct helper objref", chain, r.Tag)
|
||||
}
|
||||
out = append(out, r.Tag+"="+ref.Name)
|
||||
}
|
||||
return out
|
||||
}
|
||||
if got := refs("helper_prerouting"); !reflect.DeepEqual(got, []string{
|
||||
"conntrack:0:helper_prerouting=ftp", "conntrack:1:helper_prerouting=sip-tcp"}) {
|
||||
t.Errorf("helper_prerouting = %v", got)
|
||||
}
|
||||
if got := refs("helper_output"); !reflect.DeepEqual(got, []string{
|
||||
"conntrack:0:helper_output=ftp", "conntrack:2:helper_output=tftp"}) {
|
||||
t.Errorf("helper_output = %v", got)
|
||||
}
|
||||
|
||||
ftp := state.Rules["helper_prerouting"][0].Exprs
|
||||
l4, _ := l4Matches("tcp", config.PortSpec{"21"}, nil)
|
||||
if !reflect.DeepEqual(ftp[:len(ftp)-1], l4[0].exprs) {
|
||||
t.Errorf("ftp rule does not match tcp dport 21: %#v", ftp)
|
||||
}
|
||||
|
||||
if _, err := compile(config.ConntrackRule{Action: config.ConntrackHelper, Helper: "nope"}); err == nil {
|
||||
t.Error("expected error for unknown helper without proto")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,15 +20,25 @@ type ManagedRule struct {
|
||||
|
||||
type FirewallState struct {
|
||||
Rules map[string][]ManagedRule
|
||||
// Helpers are the ct helper objects in kernel (insertion) order.
|
||||
Helpers []Helper
|
||||
}
|
||||
|
||||
// Helper is a named ct helper object.
|
||||
type Helper struct {
|
||||
Name string `json:"name"`
|
||||
Helper expr.CtHelper `json:"helper"`
|
||||
}
|
||||
|
||||
type ChangeSet struct {
|
||||
Add []ManagedRule
|
||||
Remove []ManagedRule
|
||||
Add []ManagedRule
|
||||
Remove []ManagedRule
|
||||
AddHelpers []Helper
|
||||
RemoveHelpers []string
|
||||
}
|
||||
|
||||
func (cs *ChangeSet) Empty() bool {
|
||||
return len(cs.Add) == 0 && len(cs.Remove) == 0
|
||||
return len(cs.Add) == 0 && len(cs.Remove) == 0 && len(cs.AddHelpers) == 0 && len(cs.RemoveHelpers) == 0
|
||||
}
|
||||
|
||||
func (cs *ChangeSet) Summary() string {
|
||||
@@ -49,6 +59,12 @@ func (cs *ChangeSet) Summary() string {
|
||||
fmt.Fprintf(&b, " - [%s] %s (handle %d)\n", r.Chain, r.Tag, r.Handle)
|
||||
}
|
||||
}
|
||||
for _, h := range cs.AddHelpers {
|
||||
fmt.Fprintf(&b, " + ct helper %q\n", h.Name)
|
||||
}
|
||||
for _, n := range cs.RemoveHelpers {
|
||||
fmt.Fprintf(&b, " - ct helper %q\n", n)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
@@ -56,7 +72,7 @@ func (cs *ChangeSet) Summary() string {
|
||||
// each chain, replace the middle, and insert the new rules before the first kept
|
||||
// suffix rule (or append when there is none).
|
||||
func computeDiff(current, desired *FirewallState) *ChangeSet {
|
||||
cs := &ChangeSet{}
|
||||
cs := diffHelpers(current, desired)
|
||||
|
||||
chains := make([]string, 0, len(current.Rules)+len(desired.Rules))
|
||||
for c := range current.Rules {
|
||||
@@ -109,7 +125,10 @@ func ruleEqual(a, b ManagedRule) bool {
|
||||
// restoreChangeSet replaces every managed rule in current with the snapshot's,
|
||||
// in snapshot order, so a restore cannot reorder rules.
|
||||
func restoreChangeSet(current, snap *FirewallState) *ChangeSet {
|
||||
cs := &ChangeSet{}
|
||||
cs := &ChangeSet{AddHelpers: snap.Helpers}
|
||||
for _, h := range current.Helpers {
|
||||
cs.RemoveHelpers = append(cs.RemoveHelpers, h.Name)
|
||||
}
|
||||
for _, rules := range current.Rules {
|
||||
for _, r := range rules {
|
||||
if r.Tag != "" {
|
||||
@@ -131,3 +150,29 @@ func restoreChangeSet(current, snap *FirewallState) *ChangeSet {
|
||||
}
|
||||
return cs
|
||||
}
|
||||
|
||||
// diffHelpers replaces any ct helper object that is missing or differs.
|
||||
// L3Proto is ignored: the kernel narrows inet to ip/ip6 for single-family helpers such as pptp.
|
||||
func diffHelpers(current, desired *FirewallState) *ChangeSet {
|
||||
cs := &ChangeSet{}
|
||||
same := func(a, b expr.CtHelper) bool { return a.Name == b.Name && a.L4Proto == b.L4Proto }
|
||||
find := func(hs []Helper, name string) (expr.CtHelper, bool) {
|
||||
for _, h := range hs {
|
||||
if h.Name == name {
|
||||
return h.Helper, true
|
||||
}
|
||||
}
|
||||
return expr.CtHelper{}, false
|
||||
}
|
||||
for _, h := range current.Helpers {
|
||||
if want, ok := find(desired.Helpers, h.Name); !ok || !same(want, h.Helper) {
|
||||
cs.RemoveHelpers = append(cs.RemoveHelpers, h.Name)
|
||||
}
|
||||
}
|
||||
for _, h := range desired.Helpers {
|
||||
if have, ok := find(current.Helpers, h.Name); !ok || !same(have, h.Helper) {
|
||||
cs.AddHelpers = append(cs.AddHelpers, h)
|
||||
}
|
||||
}
|
||||
return cs
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/nftables/expr"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func TestRestoreChangeSet(t *testing.T) {
|
||||
@@ -64,3 +65,42 @@ func TestRestoreChangeSetEmptySnapshotRemovesAll(t *testing.T) {
|
||||
t.Errorf("expected 1 remove 0 add, got %d/%d", len(cs.Remove), len(cs.Add))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiffHelpers(t *testing.T) {
|
||||
h := func(name, typ string, l3 uint16, l4 uint8) Helper {
|
||||
return Helper{Name: name, Helper: expr.CtHelper{Name: typ, L3Proto: l3, L4Proto: l4}}
|
||||
}
|
||||
ftp := h("ftp", "ftp", unix.NFPROTO_INET, unix.IPPROTO_TCP)
|
||||
tftp := h("tftp", "tftp", unix.NFPROTO_INET, unix.IPPROTO_UDP)
|
||||
sipUDP := h("sip", "sip", unix.NFPROTO_INET, unix.IPPROTO_UDP)
|
||||
sipTCP := h("sip", "sip", unix.NFPROTO_INET, unix.IPPROTO_TCP)
|
||||
|
||||
current := &FirewallState{Helpers: []Helper{tftp, ftp, sipUDP}}
|
||||
desired := &FirewallState{Helpers: []Helper{ftp, sipTCP}}
|
||||
|
||||
cs := computeDiff(current, desired)
|
||||
if !reflect.DeepEqual(cs.RemoveHelpers, []string{"tftp", "sip"}) {
|
||||
t.Errorf("remove = %v", cs.RemoveHelpers)
|
||||
}
|
||||
if !reflect.DeepEqual(cs.AddHelpers, []Helper{sipTCP}) {
|
||||
t.Errorf("add = %v", cs.AddHelpers)
|
||||
}
|
||||
|
||||
// Restore recreates every helper so kernel listing order matches the snapshot.
|
||||
cs = restoreChangeSet(desired, current)
|
||||
if !reflect.DeepEqual(cs.RemoveHelpers, []string{"ftp", "sip"}) || !reflect.DeepEqual(cs.AddHelpers, current.Helpers) {
|
||||
t.Errorf("restore = -%v +%v", cs.RemoveHelpers, cs.AddHelpers)
|
||||
}
|
||||
|
||||
live := &FirewallState{Helpers: []Helper{h("pptp", "pptp", unix.NFPROTO_IPV4, unix.IPPROTO_TCP)}}
|
||||
want := &FirewallState{Helpers: []Helper{h("pptp", "pptp", unix.NFPROTO_INET, unix.IPPROTO_TCP)}}
|
||||
if cs := computeDiff(live, want); !cs.Empty() {
|
||||
t.Errorf("kernel-narrowed l3proto should not diff: %+v", cs)
|
||||
}
|
||||
if cs := computeDiff(desired, desired); !cs.Empty() {
|
||||
t.Errorf("identical helpers should be empty: %+v", cs)
|
||||
}
|
||||
if cs := computeDiff(&FirewallState{}, desired); cs.Empty() {
|
||||
t.Error("missing helpers should not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/google/nftables"
|
||||
"github.com/google/nftables/expr"
|
||||
|
||||
"git.unkin.net/unkin/tomswall/internal/config"
|
||||
)
|
||||
@@ -69,6 +70,20 @@ func (e *Engine) ensureChains(table *nftables.Table, policies map[string]nftable
|
||||
Hooknum: nftables.ChainHookPrerouting,
|
||||
Priority: nftables.ChainPriorityNATDest,
|
||||
},
|
||||
"helper_prerouting": {
|
||||
Name: "helper_prerouting",
|
||||
Table: table,
|
||||
Type: nftables.ChainTypeFilter,
|
||||
Hooknum: nftables.ChainHookPrerouting,
|
||||
Priority: nftables.ChainPriorityMangle,
|
||||
},
|
||||
"helper_output": {
|
||||
Name: "helper_output",
|
||||
Table: table,
|
||||
Type: nftables.ChainTypeFilter,
|
||||
Hooknum: nftables.ChainHookOutput,
|
||||
Priority: nftables.ChainPriorityMangle,
|
||||
},
|
||||
}
|
||||
|
||||
for name, chain := range chains {
|
||||
@@ -112,6 +127,13 @@ func (e *Engine) apply(changes *ChangeSet, policies map[string]nftables.ChainPol
|
||||
})
|
||||
}
|
||||
|
||||
for _, n := range changes.RemoveHelpers {
|
||||
e.conn.DeleteObject(helperObj(table, n, expr.CtHelper{}))
|
||||
}
|
||||
for _, h := range changes.AddHelpers {
|
||||
e.conn.AddObj(helperObj(table, h.Name, h.Helper))
|
||||
}
|
||||
|
||||
for _, r := range changes.Add {
|
||||
chain, ok := chains[r.Chain]
|
||||
if !ok {
|
||||
@@ -172,6 +194,18 @@ func (e *Engine) readCurrentState() (*FirewallState, error) {
|
||||
return state, err
|
||||
}
|
||||
|
||||
objs, err := e.conn.GetNamedObjects(ourTable)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("listing objects: %w", err)
|
||||
}
|
||||
for _, o := range objs {
|
||||
if no, ok := o.(*nftables.NamedObj); ok && no.Type == nftables.ObjTypeCtHelper {
|
||||
if h, ok := no.Obj.(*expr.CtHelper); ok {
|
||||
state.Helpers = append(state.Helpers, Helper{Name: no.Name, Helper: *h})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
chains, err := e.conn.ListChainsOfTableFamily(nftables.TableFamilyINet)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("listing chains: %w", err)
|
||||
@@ -205,6 +239,7 @@ type Snapshot struct {
|
||||
Present bool `json:"present"`
|
||||
Policies map[string]nftables.ChainPolicy `json:"policies,omitempty"`
|
||||
Rules map[string][]SnapshotRule `json:"rules,omitempty"`
|
||||
Helpers []Helper `json:"helpers,omitempty"`
|
||||
}
|
||||
|
||||
// SnapshotRule is a managed rule with its expressions in netlink wire format.
|
||||
@@ -241,6 +276,7 @@ func (e *Engine) Snapshot() (*Snapshot, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
snap.Helpers = state.Helpers
|
||||
return snap, nil
|
||||
}
|
||||
|
||||
@@ -257,6 +293,7 @@ func (e *Engine) Restore(s *Snapshot) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
want.Helpers = s.Helpers
|
||||
current, err := e.readCurrentState()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -264,6 +301,10 @@ func (e *Engine) Restore(s *Snapshot) error {
|
||||
return e.apply(restoreChangeSet(current, want), s.Policies)
|
||||
}
|
||||
|
||||
func helperObj(table *nftables.Table, name string, h expr.CtHelper) *nftables.NamedObj {
|
||||
return &nftables.NamedObj{Table: table, Name: name, Type: nftables.ObjTypeCtHelper, Obj: &h}
|
||||
}
|
||||
|
||||
func policyPtr(p nftables.ChainPolicy) *nftables.ChainPolicy {
|
||||
return &p
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user