Compare commits
40 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b8410488d2 | |||
| 200b4d3bdf | |||
| d6dfeb62b6 | |||
| 11fafc0e6a | |||
| d949fc4772 | |||
| 2ed5b958b4 | |||
| c3049e3ed4 | |||
| fe689e99ed | |||
| 1e32bde555 | |||
| 87be6bc6af | |||
| 599c483cd8 | |||
| 110b109d97 | |||
| ac63f65f2f | |||
| e3130b6c3b | |||
| df9326330a | |||
| b29ed2446e | |||
| 0551120eec | |||
| ff4c9b63e8 | |||
| e48e9079bd | |||
| 2dd408c54e | |||
| 6fc8ae9256 | |||
| b849626a8c | |||
| da32729556 | |||
| b85ba61fe6 | |||
| 9abaa85d6a | |||
| 9078f410ee | |||
| da65c5d0a8 | |||
| 90d2875301 | |||
| c557c4b78a | |||
| bf235291d0 | |||
| 1c379bf5f1 | |||
| b6d67897de | |||
| 9432bb05c9 | |||
| 9a7d1ab35b | |||
| 3c5d23a811 | |||
| 337490d995 | |||
| 6af17a4c02 | |||
| 3c5f1cacd4 | |||
| 445d14c61e | |||
| c9adff32f6 |
@@ -104,3 +104,45 @@ steps:
|
||||
limits:
|
||||
memory: 512Mi
|
||||
cpu: 500m
|
||||
|
||||
- name: release
|
||||
image: artifactapi.k8s.syd1.au.unkin.net/docker-internal/tea:0.1.0
|
||||
environment:
|
||||
RELEASER_TOKEN:
|
||||
from_secret: RELEASER_TOKEN
|
||||
commands:
|
||||
- |
|
||||
tea logins add --name gitea --url https://git.unkin.net --token "$${RELEASER_TOKEN}" --no-version-check
|
||||
CUR_SHA=$$(git rev-list -n1 "${CI_COMMIT_TAG}")
|
||||
PREV_TAG=""
|
||||
for t in $$(git tag --sort=-v:refname); do
|
||||
[ "$$t" = "${CI_COMMIT_TAG}" ] && continue
|
||||
[ "$$(git rev-list -n1 "$$t")" = "$$CUR_SHA" ] && continue
|
||||
if git merge-base --is-ancestor "$$t" "${CI_COMMIT_TAG}" 2>/dev/null; then
|
||||
PREV_TAG="$$t"; break
|
||||
fi
|
||||
done
|
||||
if [ -n "$$PREV_TAG" ]; then
|
||||
NOTES=$$(git log "$${PREV_TAG}..${CI_COMMIT_TAG}" --pretty=format:"- %s")
|
||||
else
|
||||
NOTES=$$(git log --pretty=format:"- %s")
|
||||
fi
|
||||
tea releases create --tag "${CI_COMMIT_TAG}" --title "${CI_COMMIT_TAG}" --note "$${NOTES}" --login gitea --repo "${CI_REPO}"
|
||||
cp dist/tomswall tomswall-linux-amd64
|
||||
ASSETS="tomswall-linux-amd64"
|
||||
RPM=$$(ls dist/*.rpm 2>/dev/null | head -1)
|
||||
[ -n "$$RPM" ] && ASSETS="$$ASSETS $$RPM"
|
||||
sha256sum $$ASSETS > sha256sums.txt
|
||||
tea releases assets create "${CI_COMMIT_TAG}" $$ASSETS sha256sums.txt \
|
||||
--login gitea --repo "${CI_REPO}"
|
||||
depends_on: [upload-rpm]
|
||||
backend_options:
|
||||
kubernetes:
|
||||
serviceAccountName: default
|
||||
resources:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 512Mi
|
||||
cpu: 500m
|
||||
|
||||
+3
-3
@@ -89,10 +89,10 @@ func tryApply(cfg *config.Config, fallback time.Duration) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
if err := engine.Apply(changes); err != nil {
|
||||
if derr := tryapply.Discard(); derr != nil {
|
||||
err = fmt.Errorf("%w (discarding snapshot: %v)", err, derr)
|
||||
if aerr := tryapply.Abort(); aerr != nil {
|
||||
return "", fmt.Errorf("applying changes: %w; %v; the revert timer restores the previous ruleset within %s", err, aerr, fallback)
|
||||
}
|
||||
return "", fmt.Errorf("applying changes: %w", err)
|
||||
return "", fmt.Errorf("applying changes: %w: previous ruleset restored", err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
@@ -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=
|
||||
|
||||
@@ -55,28 +55,11 @@ func (c *Config) validateBlrules() error {
|
||||
return fmt.Errorf("blrules[%d]: dest required", i)
|
||||
}
|
||||
|
||||
if r.Source != "all" && r.Source != "any" && r.Source != "none" &&
|
||||
!hasPrefix(r.Source, "all!") && !hasPrefix(r.Source, "any!") {
|
||||
for _, zs := range SplitZoneList(r.Source) {
|
||||
if _, ok := c.Zones[zs.Zone]; !ok {
|
||||
return fmt.Errorf("blrules[%d]: source zone %q not defined", i, zs.Zone)
|
||||
}
|
||||
if !validAddrList(zs.Addr) {
|
||||
return fmt.Errorf("blrules[%d]: source %q: '!' may only prefix the whole address list", i, zs.Addr)
|
||||
}
|
||||
}
|
||||
if err := c.validateZoneRef(r.Source); err != nil {
|
||||
return fmt.Errorf("blrules[%d]: source %w", i, err)
|
||||
}
|
||||
|
||||
if r.Dest != "all" && r.Dest != "any" && r.Dest != "none" &&
|
||||
!hasPrefix(r.Dest, "all!") && !hasPrefix(r.Dest, "any!") {
|
||||
for _, zs := range SplitZoneList(r.Dest) {
|
||||
if _, ok := c.Zones[zs.Zone]; !ok {
|
||||
return fmt.Errorf("blrules[%d]: dest zone %q not defined", i, zs.Zone)
|
||||
}
|
||||
if !validAddrList(zs.Addr) {
|
||||
return fmt.Errorf("blrules[%d]: dest %q: '!' may only prefix the whole address list", i, zs.Addr)
|
||||
}
|
||||
}
|
||||
if err := c.validateZoneRef(r.Dest); err != nil {
|
||||
return fmt.Errorf("blrules[%d]: dest %w", i, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -59,6 +59,11 @@ type Settings struct {
|
||||
|
||||
// When true, auto-generate CONTINUE policies for sub-zones to their parent zones.
|
||||
ImplicitContinue bool `yaml:"implicit_continue,omitempty"`
|
||||
|
||||
// Verdict for ct state invalid/untracked packets; continue passes them to the rules.
|
||||
// Unset: invalid drops, untracked continues.
|
||||
InvalidDisposition PolicyAction `yaml:"invalid_disposition,omitempty"`
|
||||
UntrackedDisposition PolicyAction `yaml:"untracked_disposition,omitempty"`
|
||||
}
|
||||
|
||||
// Load reads a config file in YAML or JSON format (detected by extension).
|
||||
@@ -115,6 +120,16 @@ func (c *Config) validateSettings() error {
|
||||
if !validAddressFamilies[c.Settings.AddressFamily] {
|
||||
return fmt.Errorf("unknown address_family %q (use inet, ip, or ip6)", c.Settings.AddressFamily)
|
||||
}
|
||||
for name, d := range map[string]PolicyAction{
|
||||
"invalid_disposition": c.Settings.InvalidDisposition,
|
||||
"untracked_disposition": c.Settings.UntrackedDisposition,
|
||||
} {
|
||||
switch d {
|
||||
case "", PolicyAccept, PolicyDrop, PolicyReject, PolicyContinue:
|
||||
default:
|
||||
return fmt.Errorf("unknown %s %q (use accept, drop, reject, or continue)", name, d)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -1052,3 +1052,20 @@ func TestSplitZoneList(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDispositions(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
invalid, untracked PolicyAction
|
||||
wantErr string
|
||||
}{
|
||||
{"", "", ""},
|
||||
{PolicyContinue, PolicyDrop, ""},
|
||||
{"bogus", "", `unknown invalid_disposition "bogus"`},
|
||||
{PolicyAccept, "log", `unknown untracked_disposition "log"`},
|
||||
} {
|
||||
c := baseConfig()
|
||||
c.Settings.InvalidDisposition = tc.invalid
|
||||
c.Settings.UntrackedDisposition = tc.untracked
|
||||
checkErr(t, c.Validate(), tc.wantErr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package config
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ConntrackAction string
|
||||
|
||||
@@ -68,8 +71,14 @@ func (c *Config) validateConntrack() error {
|
||||
return fmt.Errorf("conntrack[%d]: helper name required for helper action", i)
|
||||
}
|
||||
|
||||
if ct.Source == "" && ct.Dest == "" && ct.Action != ConntrackHelper {
|
||||
return fmt.Errorf("conntrack[%d]: source or dest required", i)
|
||||
if HasZoneExclusion(ct.Source) || HasZoneExclusion(ct.Dest) {
|
||||
return fmt.Errorf("conntrack[%d]: zone exclusions are not supported in conntrack entries", i)
|
||||
}
|
||||
if err := c.validateZoneRef(ct.Source); err != nil {
|
||||
return fmt.Errorf("conntrack[%d]: source %w", i, err)
|
||||
}
|
||||
if err := c.validateZoneRef(ct.Dest); err != nil {
|
||||
return fmt.Errorf("conntrack[%d]: dest %w", i, err)
|
||||
}
|
||||
|
||||
if ct.User != "" {
|
||||
@@ -84,3 +93,9 @@ func (c *Config) validateConntrack() error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// HasZoneExclusion reports an all/any zone ref with a "+" or "!" modifier (all+, all!x, any+!x, ...).
|
||||
func HasZoneExclusion(spec string) bool {
|
||||
zones, _, _ := strings.Cut(spec, ":")
|
||||
return (strings.HasPrefix(zones, "all") || strings.HasPrefix(zones, "any")) && strings.ContainsAny(zones[3:], "+!")
|
||||
}
|
||||
|
||||
@@ -53,11 +53,52 @@ func TestValidateConntrack(t *testing.T) {
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "source or dest required for non-helper",
|
||||
rules: []ConntrackRule{
|
||||
{Action: ConntrackDrop},
|
||||
},
|
||||
wantErr: "source or dest required",
|
||||
name: "omitted source and dest is valid",
|
||||
rules: []ConntrackRule{{Action: ConntrackNoTrack, Proto: "udp", DPort: PortSpec{"53"}}},
|
||||
},
|
||||
{
|
||||
name: "unknown source zone",
|
||||
rules: []ConntrackRule{{Action: ConntrackNoTrack, Source: "nte"}},
|
||||
wantErr: `source zone "nte" not defined`,
|
||||
},
|
||||
{
|
||||
name: "unknown dest zone",
|
||||
rules: []ConntrackRule{{Action: ConntrackDrop, Source: "net", Dest: "nte:192.0.2.1"}},
|
||||
wantErr: `dest zone "nte" not defined`,
|
||||
},
|
||||
{
|
||||
name: "all and plain zone forms are valid",
|
||||
rules: []ConntrackRule{{Action: ConntrackNoTrack, Source: "net,fw", Dest: "all:192.0.2.1"}},
|
||||
},
|
||||
{
|
||||
name: "Source all!net rejected",
|
||||
rules: []ConntrackRule{{Action: ConntrackNoTrack, Source: "all!net"}},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "Dest all!net:192.0.2.1 rejected",
|
||||
rules: []ConntrackRule{{Action: ConntrackNoTrack, Dest: "all!net:192.0.2.1"}},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "Source all+ rejected",
|
||||
rules: []ConntrackRule{{Action: ConntrackNoTrack, Source: "all+"}},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "Dest all+!net rejected",
|
||||
rules: []ConntrackRule{{Action: ConntrackNoTrack, Dest: "all+!net"}},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "Source any!net rejected",
|
||||
rules: []ConntrackRule{{Action: ConntrackNoTrack, Source: "any!net"}},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "Dest any+ rejected",
|
||||
rules: []ConntrackRule{{Action: ConntrackNoTrack, Dest: "any+"}},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "helper without source/dest is valid",
|
||||
|
||||
+32
-22
@@ -173,29 +173,13 @@ func (c *Config) validateRules() error {
|
||||
return fmt.Errorf("rule[%d]: dest required", i)
|
||||
}
|
||||
|
||||
if r.Source != "all" && r.Source != "any" && r.Source != "none" &&
|
||||
!hasPrefix(r.Source, "all+") && !hasPrefix(r.Source, "all!") && !hasPrefix(r.Source, "any!") {
|
||||
for _, zs := range SplitZoneList(r.Source) {
|
||||
if _, ok := c.Zones[zs.Zone]; !ok {
|
||||
return fmt.Errorf("rule[%d]: source zone %q not defined", i, zs.Zone)
|
||||
}
|
||||
if !validAddrList(zs.Addr) {
|
||||
return fmt.Errorf("rule[%d]: source %q: '!' may only prefix the whole address list", i, zs.Addr)
|
||||
}
|
||||
}
|
||||
if err := c.validateZoneRef(r.Source); err != nil {
|
||||
return fmt.Errorf("rule[%d]: source %w", i, err)
|
||||
}
|
||||
|
||||
if r.Action != RuleDNAT && r.Action != RuleRedirect && r.Action != RuleNoNAT {
|
||||
if r.Dest != "all" && r.Dest != "any" && r.Dest != "none" &&
|
||||
!hasPrefix(r.Dest, "all+") && !hasPrefix(r.Dest, "all!") && !hasPrefix(r.Dest, "any!") {
|
||||
for _, zs := range SplitZoneList(r.Dest) {
|
||||
if _, ok := c.Zones[zs.Zone]; !ok {
|
||||
return fmt.Errorf("rule[%d]: dest zone %q not defined", i, zs.Zone)
|
||||
}
|
||||
if !validAddrList(zs.Addr) {
|
||||
return fmt.Errorf("rule[%d]: dest %q: '!' may only prefix the whole address list", i, zs.Addr)
|
||||
}
|
||||
}
|
||||
if err := c.validateZoneRef(r.Dest); err != nil {
|
||||
return fmt.Errorf("rule[%d]: dest %w", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,6 +248,32 @@ func zoneFromSpec(spec string) string {
|
||||
return spec
|
||||
}
|
||||
|
||||
func hasPrefix(s, prefix string) bool {
|
||||
return len(s) >= len(prefix) && s[:len(prefix)] == prefix
|
||||
// validateZoneRef checks a SOURCE/DEST spec: all/any[+][!excluded,...][:addr], none, or a declared zone list.
|
||||
func (c *Config) validateZoneRef(spec string) error {
|
||||
zones, addr, _ := strings.Cut(spec, ":")
|
||||
base, excl, isExcl := strings.Cut(zones, "!")
|
||||
switch base {
|
||||
case "", "none", "all", "all+", "any", "any+":
|
||||
if base == "" && isExcl {
|
||||
return fmt.Errorf("%q: exclusion needs all or any", spec)
|
||||
}
|
||||
for _, z := range strings.Split(excl, ",") {
|
||||
if _, ok := c.Zones[strings.TrimSpace(z)]; isExcl && !ok {
|
||||
return fmt.Errorf("excluded zone %q not defined", z)
|
||||
}
|
||||
}
|
||||
if !validAddrList(addr) {
|
||||
return fmt.Errorf("%q: '!' may only prefix the whole address list", addr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, zs := range SplitZoneList(spec) {
|
||||
if _, ok := c.Zones[zs.Zone]; !ok {
|
||||
return fmt.Errorf("zone %q not defined", zs.Zone)
|
||||
}
|
||||
if !validAddrList(zs.Addr) {
|
||||
return fmt.Errorf("%q: '!' may only prefix the whole address list", zs.Addr)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func (e *Engine) FindForeignRules() ([]ForeignRule, error) {
|
||||
|
||||
var ourTable *nftables.Table
|
||||
for _, t := range tables {
|
||||
if t.Name == e.cfg.Settings.TableName && t.Family == nftables.TableFamilyINet {
|
||||
if t.Name == e.cfg.Settings.TableName && t.Family == e.family() {
|
||||
ourTable = t
|
||||
break
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func (e *Engine) FindForeignRules() ([]ForeignRule, error) {
|
||||
|
||||
var foreign []ForeignRule
|
||||
|
||||
chains, err := e.conn.ListChainsOfTableFamily(nftables.TableFamilyINet)
|
||||
chains, err := e.conn.ListChainsOfTableFamily(e.family())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("listing chains: %w", err)
|
||||
}
|
||||
|
||||
+350
-104
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -69,21 +70,34 @@ func (c *Compiler) Compile() (*FirewallState, error) {
|
||||
}
|
||||
|
||||
func (c *Compiler) compileConntrackFastPath(state *FirewallState) error {
|
||||
invalid := c.cfg.Settings.InvalidDisposition
|
||||
if invalid == "" {
|
||||
invalid = config.PolicyDrop
|
||||
}
|
||||
for _, chain := range []string{"input", "forward", "output"} {
|
||||
state.Rules[chain] = append(state.Rules[chain],
|
||||
ManagedRule{
|
||||
state.Rules[chain] = append(state.Rules[chain], ManagedRule{
|
||||
Chain: chain,
|
||||
Exprs: append(matchCtState(ctStateEstablished|ctStateRelated),
|
||||
&expr.Verdict{Kind: expr.VerdictAccept}),
|
||||
Tag: "ct:fastpath:" + chain,
|
||||
})
|
||||
for _, d := range []struct {
|
||||
name string
|
||||
state uint32
|
||||
action config.PolicyAction
|
||||
}{
|
||||
{"invalid", ctStateInvalid, invalid},
|
||||
{"untracked", ctStateUntracked, c.cfg.Settings.UntrackedDisposition},
|
||||
} {
|
||||
if d.action == "" || d.action == config.PolicyContinue {
|
||||
continue
|
||||
}
|
||||
state.Rules[chain] = append(state.Rules[chain], ManagedRule{
|
||||
Chain: chain,
|
||||
Exprs: append(matchCtState(ctStateEstablished|ctStateRelated),
|
||||
&expr.Verdict{Kind: expr.VerdictAccept}),
|
||||
Tag: "ct:fastpath:" + chain,
|
||||
},
|
||||
ManagedRule{
|
||||
Chain: chain,
|
||||
Exprs: append(matchCtState(ctStateInvalid),
|
||||
&expr.Verdict{Kind: expr.VerdictDrop}),
|
||||
Tag: "ct:invalid:" + chain,
|
||||
},
|
||||
)
|
||||
Exprs: append(matchCtState(d.state), policyVerdict(d.action, c.cfg.Settings.AddressFamily)...),
|
||||
Tag: "ct:" + d.name + ":" + chain,
|
||||
})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -125,40 +139,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)...))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,40 +209,144 @@ func (c *Compiler) compileBlrules(state *FirewallState) error {
|
||||
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",
|
||||
}
|
||||
|
||||
func helperObjName(helper, proto string) string {
|
||||
if proto != helperProtos[helper] {
|
||||
return helper + "-" + proto
|
||||
}
|
||||
return helper
|
||||
}
|
||||
|
||||
// expandHelper declares a ct helper object per (helper, proto) and returns one entry per proto.
|
||||
func expandHelper(state *FirewallState, ct config.ConntrackRule) ([]config.ConntrackRule, error) {
|
||||
proto := ct.Proto
|
||||
if proto == "" {
|
||||
if proto = helperProtos[ct.Helper]; proto == "" {
|
||||
return nil, fmt.Errorf("proto required for helper %q", ct.Helper)
|
||||
}
|
||||
}
|
||||
var out []config.ConntrackRule
|
||||
for _, p := range strings.Split(proto, ",") {
|
||||
p = strings.TrimSpace(p)
|
||||
n, err := protoNumber(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
name := helperObjName(ct.Helper, 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}})
|
||||
}
|
||||
pct := ct
|
||||
pct.Proto = p
|
||||
out = append(out, pct)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *Compiler) compileConntrack(state *FirewallState) error {
|
||||
fwZone := c.cfg.FirewallZone()
|
||||
for i, ct := range c.cfg.Conntrack {
|
||||
tag := fmt.Sprintf("conntrack:%d", i)
|
||||
|
||||
chains := []string{"prerouting"}
|
||||
switch ct.Chain {
|
||||
case config.ConntrackOutput:
|
||||
chains = []string{"output"}
|
||||
case config.ConntrackBoth:
|
||||
chains = []string{"prerouting", "output"}
|
||||
if config.HasZoneExclusion(ct.Source) || config.HasZoneExclusion(ct.Dest) {
|
||||
return fmt.Errorf("conntrack[%d]: zone exclusions are not supported in conntrack entries", i)
|
||||
}
|
||||
cts := []config.ConntrackRule{ct}
|
||||
if ct.Action == config.ConntrackHelper {
|
||||
if ct.Chain == "" {
|
||||
ct.Chain = config.ConntrackBoth
|
||||
}
|
||||
var err error
|
||||
if cts, err = expandHelper(state, ct); err != nil {
|
||||
return fmt.Errorf("conntrack[%d]: %w", i, err)
|
||||
}
|
||||
}
|
||||
srcs, dsts := c.zoneSpecs(ct.Source), c.zoneSpecs(ct.Dest)
|
||||
if len(srcs) == 0 {
|
||||
srcs = []config.ZoneSpec{{}}
|
||||
}
|
||||
if len(dsts) == 0 {
|
||||
dsts = []config.ZoneSpec{{}}
|
||||
}
|
||||
|
||||
matches, err := l4Matches(ct.Proto, ct.DPort, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("conntrack[%d]: %w", i, err)
|
||||
for _, src := range srcs {
|
||||
if src.Zone == "all" || src.Zone == "any" {
|
||||
src.Zone = ""
|
||||
}
|
||||
chains := []string{"raw_prerouting"}
|
||||
switch {
|
||||
case ct.Chain == config.ConntrackOutput && src.Zone != fwZone && src.Zone != "":
|
||||
return fmt.Errorf("conntrack[%d]: chain output needs SOURCE %s, got %q", i, fwZone, src.Zone)
|
||||
case ct.Chain == config.ConntrackPrerouting && src.Zone == fwZone:
|
||||
return fmt.Errorf("conntrack[%d]: SOURCE %s cannot use chain prerouting", i, fwZone)
|
||||
case ct.Chain != config.ConntrackPrerouting && src.Zone == fwZone, ct.Chain == config.ConntrackOutput:
|
||||
chains = []string{"raw_output"}
|
||||
case ct.Chain == config.ConntrackBoth && src.Zone == "":
|
||||
chains = []string{"raw_prerouting", "raw_output"}
|
||||
}
|
||||
for _, srcAddr := range splitAddrs(src.Addr) {
|
||||
for _, dst := range dsts {
|
||||
for _, dstAddr := range splitAddrs(dst.Addr) {
|
||||
for _, chain := range chains {
|
||||
for _, pct := range cts {
|
||||
if err := c.compileConntrackPair(state, tag, chain, pct, src.Zone, srcAddr, dst.Zone, dstAddr); err != nil {
|
||||
return fmt.Errorf("conntrack[%d]: %w", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, chain := range chains {
|
||||
// compileConntrackPair matches iif of the source zone in raw_prerouting and oif of the dest zone in raw_output.
|
||||
// Helpers are assigned after conntrack (-200) has created the entry, so they go to the mangle-priority
|
||||
// helper_* chain instead; a raw-priority assignment is a no-op.
|
||||
func (c *Compiler) compileConntrackPair(state *FirewallState, tag, chain string, ct config.ConntrackRule,
|
||||
srcZone, srcAddr, dstZone, dstAddr string) error {
|
||||
if _, ok := c.cfg.Zones[dstZone]; ok && chain == "raw_prerouting" &&
|
||||
(dstAddr == "" || strings.HasPrefix(dstAddr, "!")) {
|
||||
return fmt.Errorf("conntrack DEST zone %q needs an address in prerouting", dstZone)
|
||||
}
|
||||
srcIfaces, dstIfaces := c.resolveZoneInterfaces(srcZone, srcAddr), []string{""}
|
||||
if chain == "raw_prerouting" && c.resolveZoneInterfaces(dstZone, dstAddr) == nil {
|
||||
return nil
|
||||
}
|
||||
if chain == "raw_output" {
|
||||
srcIfaces, dstIfaces = []string{""}, c.resolveZoneInterfaces(dstZone, dstAddr)
|
||||
}
|
||||
out := chain
|
||||
if ct.Action == config.ConntrackHelper {
|
||||
out = "helper_" + strings.TrimPrefix(chain, "raw_")
|
||||
}
|
||||
for _, srcIface := range srcIfaces {
|
||||
for _, dstIface := range dstIfaces {
|
||||
matches, err := c.buildMatchExprs(srcIface, dstIface, chain, ct.Proto, ct.DPort, ct.SPort, srcAddr, dstAddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range matches {
|
||||
exprs := append([]expr.Any{}, m.exprs...)
|
||||
|
||||
exprs := m.exprs
|
||||
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})
|
||||
case config.ConntrackHelper:
|
||||
exprs = append(exprs, &expr.Objref{Type: unix.NFT_OBJECT_CT_HELPER, Name: helperObjName(ct.Helper, ct.Proto)})
|
||||
}
|
||||
|
||||
state.Rules[chain] = append(state.Rules[chain], ManagedRule{
|
||||
Chain: chain,
|
||||
state.Rules[out] = append(state.Rules[out], ManagedRule{
|
||||
Chain: out,
|
||||
Exprs: exprs,
|
||||
Tag: tag + ":" + chain,
|
||||
Tag: tag + ":" + out,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -276,7 +377,7 @@ 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.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)
|
||||
}
|
||||
}
|
||||
@@ -362,21 +463,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 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 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
|
||||
}
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -385,28 +497,135 @@ 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 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))
|
||||
// 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))
|
||||
if action == config.RuleDNAT || action == config.RuleRedirect {
|
||||
return n
|
||||
}
|
||||
return n * count(dstSpec)
|
||||
return out
|
||||
}
|
||||
|
||||
// zoneSpecs expands a comma zone list; "all"/"any" forms keep their own comma (exclusion) syntax.
|
||||
func zoneSpecs(spec string) []config.ZoneSpec {
|
||||
zone, addr := splitZoneSpec(spec)
|
||||
if base, _, _ := strings.Cut(strings.TrimSuffix(zone, "+"), "!"); base == "all" || base == "any" {
|
||||
return []config.ZoneSpec{{Zone: zone, Addr: addr}}
|
||||
// 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")
|
||||
}
|
||||
return config.SplitZoneList(spec)
|
||||
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 {
|
||||
for _, src := range c.dnatSourceSpecs(srcSpec, fwZone) {
|
||||
n += len(splitAddrs(src.Addr))
|
||||
}
|
||||
return n * len(splitAddrs(origDest))
|
||||
}
|
||||
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.
|
||||
func (c *Compiler) zoneSpecs(spec string) []config.ZoneSpec {
|
||||
zone, addr := splitZoneSpec(spec)
|
||||
if !isZoneExclusion(zone) {
|
||||
if base := strings.TrimSuffix(zone, "+"); base == "all" || base == "any" {
|
||||
return []config.ZoneSpec{{Zone: zone, Addr: addr}}
|
||||
}
|
||||
return config.SplitZoneList(spec)
|
||||
}
|
||||
var out []config.ZoneSpec
|
||||
for _, z := range c.expandZoneRef(zone) {
|
||||
out = append(out, config.ZoneSpec{Zone: z, Addr: addr})
|
||||
}
|
||||
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, "+")
|
||||
return ok && (base == "all" || base == "any")
|
||||
}
|
||||
|
||||
// splitAddrs yields one alternative per listed address; a negated list stays one AND-ed match.
|
||||
@@ -472,7 +691,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)
|
||||
@@ -500,7 +719,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
|
||||
}
|
||||
@@ -563,6 +782,7 @@ func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr,
|
||||
)
|
||||
natExpr.RegProtoMin = 2
|
||||
natExpr.RegProtoMax = 2
|
||||
natExpr.Specified = true
|
||||
}
|
||||
exprs = append(exprs, natExpr)
|
||||
} else {
|
||||
@@ -583,6 +803,7 @@ func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr,
|
||||
)
|
||||
natExpr.RegProtoMin = 2
|
||||
natExpr.RegProtoMax = 2
|
||||
natExpr.Specified = true
|
||||
}
|
||||
exprs = append(exprs, natExpr)
|
||||
}
|
||||
@@ -957,9 +1178,18 @@ func (c *Compiler) selectChain(srcZone, dstZone, fwZone string) string {
|
||||
return "forward"
|
||||
}
|
||||
|
||||
// resolveZoneInterfaces returns nil (fail closed) for a zone with no interfaces unless a non-negated address match narrows the rule.
|
||||
// resolveZoneInterfaces returns nil (fail closed) for an unknown zone, or one 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 {
|
||||
switch zone {
|
||||
case "", "all", "all+", "any", "any+":
|
||||
return []string{""}
|
||||
}
|
||||
z, ok := c.cfg.Zones[zone]
|
||||
if !ok {
|
||||
slog.Warn("compiler: unknown zone, skipping its rules", "zone", zone)
|
||||
return nil
|
||||
}
|
||||
if z.Type == config.ZoneFirewall {
|
||||
return []string{""}
|
||||
}
|
||||
if ifaces := c.cfg.ZoneInterfaces(zone); len(ifaces) > 0 {
|
||||
@@ -993,7 +1223,7 @@ func (c *Compiler) expandZoneRef(ref string) []string {
|
||||
}
|
||||
}
|
||||
|
||||
if base == "all" || base == "all+" {
|
||||
if base == "all" || base == "all+" || base == "any" || base == "any+" {
|
||||
var zones []string
|
||||
for name := range c.cfg.Zones {
|
||||
if excluded != nil && excluded[name] {
|
||||
@@ -1420,10 +1650,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) {
|
||||
@@ -1511,13 +1745,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,
|
||||
@@ -1823,6 +2062,13 @@ func rejectExprs(proto byte, family config.AddressFamily) []expr.Any {
|
||||
Code: 0,
|
||||
}}
|
||||
}
|
||||
// icmpx is inet-only; ip and ip6 tables silently drop on it.
|
||||
switch family {
|
||||
case config.FamilyIP:
|
||||
return []expr.Any{&expr.Reject{Type: unix.NFT_REJECT_ICMP_UNREACH, Code: 3}} // port-unreachable
|
||||
case config.FamilyIP6:
|
||||
return []expr.Any{&expr.Reject{Type: unix.NFT_REJECT_ICMP_UNREACH, Code: 4}} // port-unreachable
|
||||
}
|
||||
return []expr.Any{&expr.Reject{
|
||||
Type: unix.NFT_REJECT_ICMPX_UNREACH,
|
||||
Code: unix.NFT_REJECT_ICMPX_PORT_UNREACH,
|
||||
|
||||
@@ -456,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -579,7 +583,7 @@ func TestCompile_ConntrackNoTrack(t *testing.T) {
|
||||
{
|
||||
Action: config.ConntrackNoTrack,
|
||||
Source: "net",
|
||||
Dest: "fw",
|
||||
Dest: "fw:192.0.2.1",
|
||||
Proto: "udp",
|
||||
DPort: config.PortSpec{"53"},
|
||||
},
|
||||
@@ -593,14 +597,17 @@ func TestCompile_ConntrackNoTrack(t *testing.T) {
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, r := range state.Rules["prerouting"] {
|
||||
if r.Tag == "conntrack:0:prerouting" {
|
||||
for _, r := range state.Rules["raw_prerouting"] {
|
||||
if r.Tag == "conntrack:0:raw_prerouting" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("no notrack rule found in prerouting chain")
|
||||
t.Error("no notrack rule found in raw_prerouting chain")
|
||||
}
|
||||
if len(state.Rules["prerouting"]) != 0 {
|
||||
t.Error("conntrack rule leaked into the nat prerouting chain")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1006,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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1868,6 +1921,9 @@ func describeRule(r ManagedRule) string {
|
||||
}
|
||||
parts = append(parts, name+"="+net.IP(cmp.Data).String())
|
||||
}
|
||||
if m.Base == expr.PayloadBaseTransportHeader && m.Offset == 0 && m.Len == 2 && cmp.Op == expr.CmpOpEq {
|
||||
parts = append(parts, fmt.Sprintf("sport=%d", binary.BigEndian.Uint16(cmp.Data)))
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, " ")
|
||||
@@ -1908,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",
|
||||
@@ -1948,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",
|
||||
@@ -2009,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))
|
||||
}
|
||||
}
|
||||
@@ -2177,7 +2282,7 @@ func TestCompile_ListExpansionCounts(t *testing.T) {
|
||||
}, "postrouting", "snat:0", 4},
|
||||
{"conntrack dport list", func(c *config.Config) {
|
||||
c.Conntrack = []config.ConntrackRule{{Action: config.ConntrackNoTrack, Proto: "udp", DPort: config.PortSpec{"53", "123"}}}
|
||||
}, "prerouting", "conntrack:0:prerouting", 2},
|
||||
}, "raw_prerouting", "conntrack:0:raw_prerouting", 2},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -2207,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{
|
||||
@@ -2353,7 +2563,7 @@ func TestCompile_ColonRanges(t *testing.T) {
|
||||
}, "postrouting", "snat:0", 2},
|
||||
{"conntrack dport", func(c *config.Config) {
|
||||
c.Conntrack = []config.ConntrackRule{{Action: config.ConntrackNoTrack, Proto: "udp", DPort: config.PortSpec{"1024:2048"}}}
|
||||
}, "prerouting", "conntrack:0:prerouting", 2},
|
||||
}, "raw_prerouting", "conntrack:0:raw_prerouting", 2},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -2413,3 +2623,535 @@ func TestCompile_OrigDestForwardRejected(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompile_ConntrackZones(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ct config.ConntrackRule
|
||||
want map[string][]string
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "source zone matches iif",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "net", Proto: "udp", DPort: config.PortSpec{"53"}},
|
||||
want: map[string][]string{"raw_prerouting": {"iif=eth0"}},
|
||||
},
|
||||
{
|
||||
name: "source and dest addresses",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackDrop, Source: "net:192.0.2.1,198.51.100.1", Dest: "fw:203.0.113.1"},
|
||||
want: map[string][]string{"raw_prerouting": {"iif=eth0 saddr=192.0.2.1 daddr=203.0.113.1", "iif=eth0 saddr=198.51.100.1 daddr=203.0.113.1"}},
|
||||
},
|
||||
{
|
||||
name: "fw source goes to raw_output with dest oif",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "fw", Dest: "net,lan"},
|
||||
want: map[string][]string{"raw_output": {"oif=eth0", "oif=eth1"}},
|
||||
},
|
||||
{
|
||||
name: "all matches no interface",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "all", Dest: "fw:192.0.2.53"},
|
||||
want: map[string][]string{"raw_prerouting": {"daddr=192.0.2.53"}},
|
||||
},
|
||||
{
|
||||
name: "interface-less zone fails closed",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "dmz"},
|
||||
want: map[string][]string{},
|
||||
},
|
||||
{
|
||||
name: "chain output with fw source matches dest oif",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "fw", Dest: "net", Chain: config.ConntrackOutput},
|
||||
want: map[string][]string{"raw_output": {"oif=eth0"}},
|
||||
},
|
||||
{
|
||||
name: "chain output with non-fw source is rejected",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "net", Dest: "fw", Chain: config.ConntrackOutput},
|
||||
wantErr: "chain output needs SOURCE fw",
|
||||
},
|
||||
{
|
||||
name: "chain prerouting with fw source is rejected",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "fw", Dest: "net", Chain: config.ConntrackPrerouting},
|
||||
wantErr: "SOURCE fw cannot use chain prerouting",
|
||||
},
|
||||
{
|
||||
name: "omitted source and dest is global in both chains",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Proto: "udp", DPort: config.PortSpec{"53"}, Chain: config.ConntrackBoth},
|
||||
want: map[string][]string{"raw_prerouting": {""}, "raw_output": {""}},
|
||||
},
|
||||
{
|
||||
name: "all source with chain both is global in both chains",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "all", Proto: "udp", DPort: config.PortSpec{"53"}, Chain: config.ConntrackBoth},
|
||||
want: map[string][]string{"raw_prerouting": {""}, "raw_output": {""}},
|
||||
},
|
||||
{
|
||||
name: "all source with chain output is global in raw_output",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "all", Proto: "udp", DPort: config.PortSpec{"53"}, Chain: config.ConntrackOutput},
|
||||
want: map[string][]string{"raw_output": {""}},
|
||||
},
|
||||
{
|
||||
name: "any source with chain both is global in both chains",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "any", Proto: "udp", DPort: config.PortSpec{"53"}, Chain: config.ConntrackBoth},
|
||||
want: map[string][]string{"raw_prerouting": {""}, "raw_output": {""}},
|
||||
},
|
||||
{
|
||||
name: "any source with chain output is global in raw_output",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "any", Proto: "udp", DPort: config.PortSpec{"53"}, Chain: config.ConntrackOutput},
|
||||
want: map[string][]string{"raw_output": {""}},
|
||||
},
|
||||
{
|
||||
name: "chain both with non-fw source emits prerouting only",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "net", Proto: "udp", DPort: config.PortSpec{"53"}, Chain: config.ConntrackBoth},
|
||||
want: map[string][]string{"raw_prerouting": {"iif=eth0"}},
|
||||
},
|
||||
{
|
||||
name: "chain both with fw source emits output only",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "fw", Dest: "lan", Chain: config.ConntrackBoth},
|
||||
want: map[string][]string{"raw_output": {"oif=eth1"}},
|
||||
},
|
||||
{
|
||||
name: "negated addresses stay one AND-ed match",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackDrop, Source: "net:!192.0.2.1,198.51.100.1"},
|
||||
want: map[string][]string{"raw_prerouting": {"iif=eth0 !saddr=192.0.2.1 !saddr=198.51.100.1"}},
|
||||
},
|
||||
{
|
||||
name: "sport",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "net", Proto: "udp", SPort: config.PortSpec{"123"}},
|
||||
want: map[string][]string{"raw_prerouting": {"iif=eth0 sport=123"}},
|
||||
},
|
||||
{
|
||||
name: "dest zone without address is rejected in prerouting",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "net", Dest: "lan"},
|
||||
wantErr: `conntrack DEST zone "lan" needs an address in prerouting`,
|
||||
},
|
||||
{
|
||||
name: "fw dest zone without address is rejected in prerouting",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackDrop, Source: "net", Dest: "fw"},
|
||||
wantErr: `conntrack DEST zone "fw" needs an address in prerouting`,
|
||||
},
|
||||
{
|
||||
name: "fw dest zone with address matches daddr",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "net", Dest: "fw:192.0.2.1"},
|
||||
want: map[string][]string{"raw_prerouting": {"iif=eth0 daddr=192.0.2.1"}},
|
||||
},
|
||||
{
|
||||
name: "unknown zone fails closed",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackDrop, Source: "nte"},
|
||||
want: map[string][]string{},
|
||||
},
|
||||
{
|
||||
name: "unknown dest zone fails closed in prerouting",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackDrop, Source: "net", Dest: "typo"},
|
||||
want: map[string][]string{},
|
||||
},
|
||||
{
|
||||
name: "none dest zone yields no rule",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackDrop, Source: "net", Dest: "none"},
|
||||
want: map[string][]string{},
|
||||
},
|
||||
{
|
||||
name: "all!net rejected",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "all!net"},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "all!net rejected",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Dest: "all!net"},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "all+ rejected",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "all+"},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "all+!net rejected",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Dest: "all+!net"},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "any!net rejected",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "any!net"},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "any+ rejected",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Dest: "any+"},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
{
|
||||
name: "omitted source and dest is global",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Proto: "udp", DPort: config.PortSpec{"53"}},
|
||||
want: map[string][]string{"raw_prerouting": {""}},
|
||||
},
|
||||
{
|
||||
name: "dest zone with address matches daddr",
|
||||
ct: config.ConntrackRule{Action: config.ConntrackNoTrack, Source: "net", Dest: "lan:203.0.113.10"},
|
||||
want: map[string][]string{"raw_prerouting": {"iif=eth0 daddr=203.0.113.10"}},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg := listCfg(func(cfg *config.Config) {
|
||||
cfg.Zones["lan"] = config.Zone{Type: config.ZoneIP}
|
||||
cfg.Zones["dmz"] = config.Zone{Type: config.ZoneIP}
|
||||
cfg.Interfaces = append(cfg.Interfaces, config.Interface{Zone: "lan", Interface: "eth1"})
|
||||
cfg.Conntrack = []config.ConntrackRule{tt.ct}
|
||||
})
|
||||
if tt.wantErr != "" {
|
||||
if _, err := NewCompiler(cfg).Compile(); err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("Compile() error = %v, want %q", err, tt.wantErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
state := mustCompile(t, cfg)
|
||||
got := map[string][]string{}
|
||||
for _, chain := range []string{"raw_prerouting", "raw_output"} {
|
||||
for _, r := range taggedRules(state, chain, "conntrack:0:"+chain) {
|
||||
got[chain] = append(got[chain], describeRule(r))
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("rules = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompile_RuleZoneExclusionExpands(t *testing.T) {
|
||||
cfg := listCfg(func(cfg *config.Config) {
|
||||
cfg.Zones["lan"] = config.Zone{Type: config.ZoneIP}
|
||||
cfg.Interfaces = append(cfg.Interfaces, config.Interface{Zone: "lan", Interface: "eth1"})
|
||||
cfg.Rules = []config.Rule{
|
||||
{Source: "all!net", Dest: "fw", Action: config.RuleAccept, Proto: "tcp", DPort: config.PortSpec{"22"}},
|
||||
{Source: "nte", Dest: "fw", Action: config.RuleAccept},
|
||||
}
|
||||
})
|
||||
state := mustCompile(t, cfg)
|
||||
var got []string
|
||||
for _, r := range taggedRules(state, "input", "rule:0") {
|
||||
got = append(got, describeRule(r))
|
||||
}
|
||||
if want := []string{"iif=eth1"}; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("all!net -> fw input rules = %v, want %v", got, want)
|
||||
}
|
||||
if r := taggedRules(state, "input", "rule:1"); len(r) != 0 {
|
||||
t.Errorf("unknown zone compiled %d rules, want 0", len(r))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompile_RuleZoneExclusionIntraZoneSymmetric(t *testing.T) {
|
||||
cfg := listCfg(func(cfg *config.Config) {
|
||||
cfg.Zones["lan"] = config.Zone{Type: config.ZoneIP}
|
||||
cfg.Interfaces = append(cfg.Interfaces, config.Interface{Zone: "lan", Interface: "eth1"})
|
||||
cfg.Rules = []config.Rule{
|
||||
{Source: "lan", Dest: "all+!net", Action: config.RuleAccept},
|
||||
{Source: "lan", Dest: "all!net", Action: config.RuleAccept},
|
||||
}
|
||||
})
|
||||
state := mustCompile(t, cfg)
|
||||
for i, want := range []bool{true, false} {
|
||||
got := false
|
||||
for _, r := range taggedRules(state, "forward", fmt.Sprintf("rule:%d", i)) {
|
||||
got = got || describeRule(r) == "iif=eth1 oif=eth1"
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("rule:%d lan->lan forward = %v, want %v", i, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompile_ConntrackHelperZones(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ct config.ConntrackRule
|
||||
want map[string][]string
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "non-fw source is prerouting only",
|
||||
ct: config.ConntrackRule{Source: "net", Proto: "tcp", DPort: config.PortSpec{"21"}},
|
||||
want: map[string][]string{"helper_prerouting": {"iif=eth0"}},
|
||||
},
|
||||
{
|
||||
name: "fw source is output only with dest oif",
|
||||
ct: config.ConntrackRule{Source: "fw", Dest: "lan", Proto: "tcp", DPort: config.PortSpec{"21"}},
|
||||
want: map[string][]string{"helper_output": {"oif=eth1"}},
|
||||
},
|
||||
{
|
||||
name: "any source is global in both chains",
|
||||
ct: config.ConntrackRule{Source: "any", Proto: "tcp", DPort: config.PortSpec{"21"}},
|
||||
want: map[string][]string{"helper_prerouting": {""}, "helper_output": {""}},
|
||||
},
|
||||
{
|
||||
name: "dest zone with address in prerouting",
|
||||
ct: config.ConntrackRule{Source: "net", Dest: "lan:203.0.113.10", Proto: "tcp", DPort: config.PortSpec{"21"}},
|
||||
want: map[string][]string{"helper_prerouting": {"iif=eth0 daddr=203.0.113.10"}},
|
||||
},
|
||||
{
|
||||
name: "dest zone without address is rejected in prerouting",
|
||||
ct: config.ConntrackRule{Source: "net", Dest: "lan"},
|
||||
wantErr: `conntrack DEST zone "lan" needs an address in prerouting`,
|
||||
},
|
||||
{
|
||||
name: "chain output with non-fw source is rejected",
|
||||
ct: config.ConntrackRule{Source: "net", Chain: config.ConntrackOutput},
|
||||
wantErr: "chain output needs SOURCE fw",
|
||||
},
|
||||
{
|
||||
name: "interface-less zone fails closed",
|
||||
ct: config.ConntrackRule{Source: "dmz"},
|
||||
want: map[string][]string{},
|
||||
},
|
||||
{
|
||||
name: "unknown zone fails closed",
|
||||
ct: config.ConntrackRule{Source: "nte"},
|
||||
want: map[string][]string{},
|
||||
},
|
||||
{
|
||||
name: "exclusion rejected",
|
||||
ct: config.ConntrackRule{Source: "all!net"},
|
||||
wantErr: "zone exclusions are not supported in conntrack entries",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
tt.ct.Action, tt.ct.Helper = config.ConntrackHelper, "ftp"
|
||||
cfg := listCfg(func(cfg *config.Config) {
|
||||
cfg.Zones["lan"] = config.Zone{Type: config.ZoneIP}
|
||||
cfg.Zones["dmz"] = config.Zone{Type: config.ZoneIP}
|
||||
cfg.Interfaces = append(cfg.Interfaces, config.Interface{Zone: "lan", Interface: "eth1"})
|
||||
cfg.Conntrack = []config.ConntrackRule{tt.ct}
|
||||
})
|
||||
if tt.wantErr != "" {
|
||||
if _, err := NewCompiler(cfg).Compile(); err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("Compile() error = %v, want %q", err, tt.wantErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
state := mustCompile(t, cfg)
|
||||
got := map[string][]string{}
|
||||
for _, chain := range []string{"helper_prerouting", "helper_output"} {
|
||||
for _, r := range taggedRules(state, chain, "conntrack:0:"+chain) {
|
||||
got[chain] = append(got[chain], describeRule(r))
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("rules = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompile_Dispositions(t *testing.T) {
|
||||
cases := []struct {
|
||||
invalid, untracked config.PolicyAction
|
||||
want map[string]expr.Any // tag prefix -> verdict expr, nil = absent
|
||||
}{
|
||||
{"", "", map[string]expr.Any{"ct:invalid:": &expr.Verdict{Kind: expr.VerdictDrop}, "ct:untracked:": nil}},
|
||||
{config.PolicyContinue, config.PolicyContinue, map[string]expr.Any{"ct:invalid:": nil, "ct:untracked:": nil}},
|
||||
{config.PolicyReject, config.PolicyAccept, map[string]expr.Any{
|
||||
"ct:invalid:": rejectExprs(0, config.FamilyINET)[0],
|
||||
"ct:untracked:": &expr.Verdict{Kind: expr.VerdictAccept},
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
cfg := &config.Config{
|
||||
Settings: config.Settings{
|
||||
TableName: "test",
|
||||
AddressFamily: config.FamilyINET,
|
||||
InvalidDisposition: tc.invalid,
|
||||
UntrackedDisposition: tc.untracked,
|
||||
},
|
||||
Zones: map[string]config.Zone{"fw": {Type: config.ZoneFirewall}, "net": {Type: config.ZoneIP}},
|
||||
Interfaces: []config.Interface{{Zone: "net", Interface: "eth0"}},
|
||||
Policy: []config.Policy{{Source: "all", Dest: "all", Action: config.PolicyDrop}},
|
||||
PortGroups: make(map[string]config.PortGroup),
|
||||
}
|
||||
state, err := NewCompiler(cfg).Compile()
|
||||
if err != nil {
|
||||
t.Fatalf("Compile: %v", err)
|
||||
}
|
||||
for _, chain := range []string{"input", "forward", "output"} {
|
||||
for prefix, want := range tc.want {
|
||||
var got *ManagedRule
|
||||
for i, r := range state.Rules[chain] {
|
||||
if r.Tag == prefix+chain {
|
||||
got = &state.Rules[chain][i]
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case want == nil && got != nil:
|
||||
t.Errorf("%q/%q: unexpected %s%s rule", tc.invalid, tc.untracked, prefix, chain)
|
||||
case want != nil && got == nil:
|
||||
t.Errorf("%q/%q: missing %s%s rule", tc.invalid, tc.untracked, prefix, chain)
|
||||
case want != nil && !reflect.DeepEqual(got.Exprs[len(got.Exprs)-1], want):
|
||||
t.Errorf("%q/%q: %s%s verdict = %#v, want %#v", tc.invalid, tc.untracked, prefix, chain, got.Exprs[len(got.Exprs)-1], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
+195
-19
@@ -4,6 +4,9 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/google/nftables"
|
||||
"github.com/google/nftables/expr"
|
||||
"github.com/mdlayher/netlink"
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"git.unkin.net/unkin/tomswall/internal/config"
|
||||
)
|
||||
@@ -14,16 +17,101 @@ type Engine struct {
|
||||
}
|
||||
|
||||
func NewEngine(cfg *config.Config) (*Engine, error) {
|
||||
conn, err := nftables.New()
|
||||
conn, err := nftables.New(nftables.WithSockOptions(largeBuffers))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connecting to nftables: %w", err)
|
||||
}
|
||||
return &Engine{cfg: cfg, conn: conn}, nil
|
||||
}
|
||||
|
||||
var tableFamilies = map[config.AddressFamily]nftables.TableFamily{
|
||||
config.FamilyINET: nftables.TableFamilyINet,
|
||||
config.FamilyIP: nftables.TableFamilyIPv4,
|
||||
config.FamilyIP6: nftables.TableFamilyIPv6,
|
||||
}
|
||||
|
||||
func (e *Engine) family() nftables.TableFamily {
|
||||
if f, ok := tableFamilies[e.cfg.Settings.AddressFamily]; ok {
|
||||
return f
|
||||
}
|
||||
return nftables.TableFamilyINet
|
||||
}
|
||||
|
||||
func addressFamily(tf nftables.TableFamily) config.AddressFamily {
|
||||
for f, t := range tableFamilies {
|
||||
if t == tf {
|
||||
return f
|
||||
}
|
||||
}
|
||||
return config.FamilyINET
|
||||
}
|
||||
|
||||
// withFamily is the engine for the same table name in another address family.
|
||||
func (e *Engine) withFamily(f config.AddressFamily) *Engine {
|
||||
cfg := *e.cfg
|
||||
cfg.Settings.AddressFamily = f
|
||||
return &Engine{cfg: &cfg, conn: e.conn}
|
||||
}
|
||||
|
||||
// overlaps reports whether tables of families a and b filter the same traffic:
|
||||
// inet covers both ip and ip6, which do not overlap each other.
|
||||
func overlaps(a, b nftables.TableFamily) bool {
|
||||
if a == b {
|
||||
return false
|
||||
}
|
||||
return (a == nftables.TableFamilyINet && (b == nftables.TableFamilyIPv4 || b == nftables.TableFamilyIPv6)) ||
|
||||
(b == nftables.TableFamilyINet && (a == nftables.TableFamilyIPv4 || a == nftables.TableFamilyIPv6))
|
||||
}
|
||||
|
||||
// staleTables are our-named tables left by a different address_family that
|
||||
// would still filter the traffic this family now owns.
|
||||
func (e *Engine) staleTables() ([]*nftables.Table, error) {
|
||||
tables, err := e.conn.ListTables()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("listing tables: %w", err)
|
||||
}
|
||||
var stale []*nftables.Table
|
||||
for _, t := range tables {
|
||||
if t.Name == e.cfg.Settings.TableName && overlaps(e.family(), t.Family) {
|
||||
stale = append(stale, t)
|
||||
}
|
||||
}
|
||||
return stale, nil
|
||||
}
|
||||
|
||||
// batchBufSize bounds one batch: the kernel rejects a batch larger than the
|
||||
// send buffer (EMSGSIZE) and drops ACKs beyond the receive buffer (ENOBUFS)
|
||||
// after committing it.
|
||||
// ponytail: fixed cap of tens of thousands of rules; size per batch if exceeded.
|
||||
const batchBufSize = 64 << 20
|
||||
|
||||
// largeBuffers raises both socket buffers, ignoring rmem_max/wmem_max when
|
||||
// CAP_NET_ADMIN allows it and falling back to the capped sizes otherwise.
|
||||
func largeBuffers(c *netlink.Conn) error {
|
||||
rc, err := c.SyscallConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var serr error
|
||||
err = rc.Control(func(fd uintptr) {
|
||||
for _, o := range [][2]int{{unix.SO_SNDBUFFORCE, unix.SO_SNDBUF}, {unix.SO_RCVBUFFORCE, unix.SO_RCVBUF}} {
|
||||
if unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, o[0], batchBufSize) == nil {
|
||||
continue
|
||||
}
|
||||
if serr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, o[1], batchBufSize); serr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return serr
|
||||
}
|
||||
|
||||
func (e *Engine) ensureTable() *nftables.Table {
|
||||
return e.conn.AddTable(&nftables.Table{
|
||||
Family: nftables.TableFamilyINet,
|
||||
Family: e.family(),
|
||||
Name: e.cfg.Settings.TableName,
|
||||
})
|
||||
}
|
||||
@@ -69,6 +157,36 @@ 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,
|
||||
},
|
||||
"raw_prerouting": {
|
||||
Name: "raw_prerouting",
|
||||
Table: table,
|
||||
Type: nftables.ChainTypeFilter,
|
||||
Hooknum: nftables.ChainHookPrerouting,
|
||||
Priority: nftables.ChainPriorityRaw,
|
||||
Policy: policyPtr(nftables.ChainPolicyAccept),
|
||||
},
|
||||
"raw_output": {
|
||||
Name: "raw_output",
|
||||
Table: table,
|
||||
Type: nftables.ChainTypeFilter,
|
||||
Hooknum: nftables.ChainHookOutput,
|
||||
Priority: nftables.ChainPriorityRaw,
|
||||
Policy: policyPtr(nftables.ChainPolicyAccept),
|
||||
},
|
||||
}
|
||||
|
||||
for name, chain := range chains {
|
||||
@@ -101,6 +219,13 @@ func (e *Engine) Apply(changes *ChangeSet) error {
|
||||
}
|
||||
|
||||
func (e *Engine) apply(changes *ChangeSet, policies map[string]nftables.ChainPolicy) error {
|
||||
stale, err := e.staleTables()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, t := range stale {
|
||||
e.conn.DelTable(t)
|
||||
}
|
||||
table := e.ensureTable()
|
||||
chains := e.ensureChains(table, policies)
|
||||
|
||||
@@ -112,6 +237,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 {
|
||||
@@ -135,18 +267,24 @@ func (e *Engine) apply(changes *ChangeSet, policies map[string]nftables.ChainPol
|
||||
}
|
||||
|
||||
func (e *Engine) Flush() error {
|
||||
tables, err := e.conn.ListTables()
|
||||
tables, err := e.staleTables()
|
||||
if err != nil {
|
||||
return fmt.Errorf("listing tables: %w", err)
|
||||
return err
|
||||
}
|
||||
own, err := e.findTable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if own != nil {
|
||||
tables = append(tables, own)
|
||||
}
|
||||
if len(tables) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, t := range tables {
|
||||
if t.Name == e.cfg.Settings.TableName {
|
||||
e.conn.DelTable(t)
|
||||
return e.conn.Flush()
|
||||
}
|
||||
e.conn.DelTable(t)
|
||||
}
|
||||
return nil
|
||||
return e.conn.Flush()
|
||||
}
|
||||
|
||||
func (e *Engine) findTable() (*nftables.Table, error) {
|
||||
@@ -155,7 +293,7 @@ func (e *Engine) findTable() (*nftables.Table, error) {
|
||||
return nil, fmt.Errorf("listing tables: %w", err)
|
||||
}
|
||||
for _, t := range tables {
|
||||
if t.Name == e.cfg.Settings.TableName && t.Family == nftables.TableFamilyINet {
|
||||
if t.Name == e.cfg.Settings.TableName && t.Family == e.family() {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
@@ -172,7 +310,19 @@ func (e *Engine) readCurrentState() (*FirewallState, error) {
|
||||
return state, err
|
||||
}
|
||||
|
||||
chains, err := e.conn.ListChainsOfTableFamily(nftables.TableFamilyINet)
|
||||
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(e.family())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("listing chains: %w", err)
|
||||
}
|
||||
@@ -202,9 +352,11 @@ func (e *Engine) readCurrentState() (*FirewallState, error) {
|
||||
// survives the process that took it.
|
||||
type Snapshot struct {
|
||||
Table string `json:"table"`
|
||||
Family config.AddressFamily `json:"family,omitempty"`
|
||||
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.
|
||||
@@ -213,16 +365,30 @@ type SnapshotRule struct {
|
||||
Exprs [][]byte `json:"exprs"`
|
||||
}
|
||||
|
||||
// Snapshot captures the live tomswall table so Restore can roll back to it.
|
||||
// Snapshot captures the live tomswall table so Restore can roll back to it,
|
||||
// falling back to the overlapping table of another family that apply replaces.
|
||||
func (e *Engine) Snapshot() (*Snapshot, error) {
|
||||
snap := &Snapshot{Table: e.cfg.Settings.TableName}
|
||||
t, err := e.findTable()
|
||||
if err != nil || t == nil {
|
||||
return snap, err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if t == nil {
|
||||
stale, err := e.staleTables()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// ponytail: captures one stale table; an inet config replacing both ip and ip6 restores only the first.
|
||||
if len(stale) > 0 {
|
||||
return e.withFamily(addressFamily(stale[0].Family)).Snapshot()
|
||||
}
|
||||
}
|
||||
snap := &Snapshot{Table: e.cfg.Settings.TableName, Family: addressFamily(e.family())}
|
||||
if t == nil {
|
||||
return snap, nil
|
||||
}
|
||||
snap.Present = true
|
||||
|
||||
chains, err := e.conn.ListChainsOfTableFamily(nftables.TableFamilyINet)
|
||||
chains, err := e.conn.ListChainsOfTableFamily(e.family())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("listing chains: %w", err)
|
||||
}
|
||||
@@ -237,10 +403,11 @@ func (e *Engine) Snapshot() (*Snapshot, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
snap.Rules, err = encodeState(state)
|
||||
snap.Rules, err = encodeState(state, byte(e.family()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
snap.Helpers = state.Helpers
|
||||
return snap, nil
|
||||
}
|
||||
|
||||
@@ -250,13 +417,18 @@ func (e *Engine) Restore(s *Snapshot) error {
|
||||
if s.Table != e.cfg.Settings.TableName {
|
||||
return fmt.Errorf("snapshot is of table %q, engine manages %q", s.Table, e.cfg.Settings.TableName)
|
||||
}
|
||||
// Snapshots predating the family field are of the inet table.
|
||||
if f := addressFamily(tableFamilies[s.Family]); f != addressFamily(e.family()) {
|
||||
return e.withFamily(f).Restore(s)
|
||||
}
|
||||
if !s.Present {
|
||||
return e.Flush()
|
||||
}
|
||||
want, err := decodeState(s.Rules)
|
||||
want, err := decodeState(s.Rules, byte(e.family()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
want.Helpers = s.Helpers
|
||||
current, err := e.readCurrentState()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -264,6 +436,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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package nftables
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mdlayher/netlink"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func TestLargeBuffersRaisesSocketBuffers(t *testing.T) {
|
||||
c, err := netlink.Dial(unix.NETLINK_NETFILTER, nil)
|
||||
if err != nil {
|
||||
t.Skipf("netlink unavailable: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
if err := largeBuffers(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Without CAP_NET_ADMIN the kernel caps at the sysctl max; it doubles either way.
|
||||
for opt, sysctl := range map[int]string{unix.SO_RCVBUF: "rmem_max", unix.SO_SNDBUF: "wmem_max"} {
|
||||
want := 2 * min(batchBufSize, procInt(t, "/proc/sys/net/core/"+sysctl))
|
||||
if got := sockBuf(t, c, opt); got < want {
|
||||
t.Errorf("%s-bounded buffer = %d, want >= %d", sysctl, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func procInt(t *testing.T, path string) int {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Skipf("reading %s: %v", path, err)
|
||||
}
|
||||
v, err := strconv.Atoi(strings.TrimSpace(string(b)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func sockBuf(t *testing.T, c *netlink.Conn, opt int) int {
|
||||
t.Helper()
|
||||
rc, err := c.SyscallConn()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var v int
|
||||
var serr error
|
||||
if err := rc.Control(func(fd uintptr) { v, serr = unix.GetsockoptInt(int(fd), unix.SOL_SOCKET, opt) }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if serr != nil {
|
||||
t.Fatal(serr)
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package nftables
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/nftables"
|
||||
"github.com/google/nftables/expr"
|
||||
"github.com/mdlayher/netlink"
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"git.unkin.net/unkin/tomswall/internal/config"
|
||||
)
|
||||
|
||||
type sentTable struct {
|
||||
msg int
|
||||
family nftables.TableFamily
|
||||
}
|
||||
|
||||
// familyEngine fakes a kernel holding tomswall tables of the given families
|
||||
// and records table creations/deletions.
|
||||
func familyEngine(t *testing.T, af config.AddressFamily, live ...nftables.TableFamily) (*Engine, *[]sentTable) {
|
||||
var sent []sentTable
|
||||
e := testEngine(t, func(req []netlink.Message) ([]netlink.Message, error) {
|
||||
var out []netlink.Message
|
||||
for _, m := range req {
|
||||
switch m.Header.Type {
|
||||
case nftType(unix.NFT_MSG_GETTABLE):
|
||||
for _, f := range live {
|
||||
attrs, _ := netlink.MarshalAttributes([]netlink.Attribute{{Type: unix.NFTA_TABLE_NAME, Data: []byte("tomswall\x00")}})
|
||||
out = append(out, netlink.Message{Header: netlink.Header{Type: nftType(unix.NFT_MSG_NEWTABLE), Sequence: m.Header.Sequence}, Data: append([]byte{byte(f), 0, 0, 0}, attrs...)})
|
||||
}
|
||||
case nftType(unix.NFT_MSG_NEWTABLE):
|
||||
sent = append(sent, sentTable{unix.NFT_MSG_NEWTABLE, nftables.TableFamily(m.Data[0])})
|
||||
case nftType(unix.NFT_MSG_DELTABLE):
|
||||
sent = append(sent, sentTable{unix.NFT_MSG_DELTABLE, nftables.TableFamily(m.Data[0])})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
})
|
||||
e.cfg.Settings.AddressFamily = af
|
||||
return e, &sent
|
||||
}
|
||||
|
||||
func TestApplyIPFamilyReplacesInetTable(t *testing.T) {
|
||||
e, sent := familyEngine(t, config.FamilyIP, nftables.TableFamilyINet, nftables.TableFamilyIPv6)
|
||||
if err := e.Apply(&ChangeSet{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []sentTable{{unix.NFT_MSG_DELTABLE, nftables.TableFamilyINet}, {unix.NFT_MSG_NEWTABLE, nftables.TableFamilyIPv4}}
|
||||
if len(*sent) != len(want) || (*sent)[0] != want[0] || (*sent)[1] != want[1] {
|
||||
t.Errorf("got %+v, want %+v (the ip6 table must survive)", *sent, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyInetFamilyReplacesIPTables(t *testing.T) {
|
||||
e, sent := familyEngine(t, config.FamilyINET, nftables.TableFamilyIPv4, nftables.TableFamilyIPv6)
|
||||
if err := e.Apply(&ChangeSet{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var dels int
|
||||
for _, s := range *sent {
|
||||
if s.msg == unix.NFT_MSG_DELTABLE {
|
||||
dels++
|
||||
}
|
||||
}
|
||||
if dels != 2 {
|
||||
t.Errorf("want ip and ip6 tables deleted, got %+v", *sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlushIPFamilyKeepsIP6Table(t *testing.T) {
|
||||
e, sent := familyEngine(t, config.FamilyIP, nftables.TableFamilyIPv6, nftables.TableFamilyIPv4)
|
||||
if err := e.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(*sent) != 1 || (*sent)[0] != (sentTable{unix.NFT_MSG_DELTABLE, nftables.TableFamilyIPv4}) {
|
||||
t.Errorf("got %+v, want only the ip table deleted", *sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotFallsBackToReplacedTable(t *testing.T) {
|
||||
e, _ := familyEngine(t, config.FamilyIP, nftables.TableFamilyINet)
|
||||
snap, err := e.Snapshot()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !snap.Present || snap.Family != config.FamilyINET {
|
||||
t.Fatalf("want present inet snapshot, got %+v", snap)
|
||||
}
|
||||
|
||||
// Reverting to the inet snapshot drops the tried ip table.
|
||||
e, sent := familyEngine(t, config.FamilyIP, nftables.TableFamilyIPv4)
|
||||
if err := e.Restore(&Snapshot{Table: "tomswall", Family: config.FamilyINET, Present: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []sentTable{{unix.NFT_MSG_DELTABLE, nftables.TableFamilyIPv4}, {unix.NFT_MSG_NEWTABLE, nftables.TableFamilyINet}}
|
||||
if len(*sent) != 2 || (*sent)[0] != want[0] || (*sent)[1] != want[1] {
|
||||
t.Errorf("got %+v, want %+v", *sent, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectExprsFamily(t *testing.T) {
|
||||
for af, want := range map[config.AddressFamily]expr.Reject{
|
||||
config.FamilyINET: {Type: unix.NFT_REJECT_ICMPX_UNREACH, Code: unix.NFT_REJECT_ICMPX_PORT_UNREACH},
|
||||
config.FamilyIP: {Type: unix.NFT_REJECT_ICMP_UNREACH, Code: 3},
|
||||
config.FamilyIP6: {Type: unix.NFT_REJECT_ICMP_UNREACH, Code: 4},
|
||||
} {
|
||||
got := rejectExprs(unix.IPPROTO_UDP, af)[0].(*expr.Reject)
|
||||
if *got != want {
|
||||
t.Errorf("%s: got %+v, want %+v", af, *got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,11 @@ import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/nftables"
|
||||
"github.com/google/nftables/expr"
|
||||
"github.com/mdlayher/netlink"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const inet = byte(nftables.TableFamilyINet)
|
||||
|
||||
// exprByName mirrors the expression types google/nftables can parse back from the kernel.
|
||||
var exprByName = map[string]func() expr.Any{
|
||||
"ct": func() expr.Any { return &expr.Ct{} },
|
||||
@@ -40,13 +37,13 @@ var exprByName = map[string]func() expr.Any{
|
||||
"notrack": func() expr.Any { return &expr.Notrack{} },
|
||||
}
|
||||
|
||||
func encodeState(state *FirewallState) (map[string][]SnapshotRule, error) {
|
||||
func encodeState(state *FirewallState, fam byte) (map[string][]SnapshotRule, error) {
|
||||
out := make(map[string][]SnapshotRule, len(state.Rules))
|
||||
for chain, rules := range state.Rules {
|
||||
for _, r := range rules {
|
||||
sr := SnapshotRule{Tag: r.Tag}
|
||||
for _, e := range r.Exprs {
|
||||
b, err := expr.Marshal(inet, e)
|
||||
b, err := expr.Marshal(fam, e)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encoding %s rule %q: %w", chain, r.Tag, err)
|
||||
}
|
||||
@@ -58,13 +55,13 @@ func encodeState(state *FirewallState) (map[string][]SnapshotRule, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func decodeState(rules map[string][]SnapshotRule) (*FirewallState, error) {
|
||||
func decodeState(rules map[string][]SnapshotRule, fam byte) (*FirewallState, error) {
|
||||
state := &FirewallState{Rules: make(map[string][]ManagedRule, len(rules))}
|
||||
for chain, rs := range rules {
|
||||
for _, sr := range rs {
|
||||
r := ManagedRule{Chain: chain, Tag: sr.Tag}
|
||||
for _, b := range sr.Exprs {
|
||||
e, err := decodeExpr(b)
|
||||
e, err := decodeExpr(b, fam)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decoding %s rule %q: %w", chain, sr.Tag, err)
|
||||
}
|
||||
@@ -77,7 +74,7 @@ func decodeState(rules map[string][]SnapshotRule) (*FirewallState, error) {
|
||||
}
|
||||
|
||||
// decodeExpr reverses expr.Marshal, as google/nftables does when reading rules.
|
||||
func decodeExpr(b []byte) (expr.Any, error) {
|
||||
func decodeExpr(b []byte, fam byte) (expr.Any, error) {
|
||||
ad, err := netlink.NewAttributeDecoder(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -104,13 +101,13 @@ func decodeExpr(b []byte) (expr.Any, error) {
|
||||
if name == "notrack" {
|
||||
return e, nil
|
||||
}
|
||||
if err := expr.Unmarshal(inet, data, e); err != nil {
|
||||
if err := expr.Unmarshal(fam, data, e); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A verdict is an immediate into the verdict register with no data.
|
||||
if imm, ok := e.(*expr.Immediate); ok && imm.Register == unix.NFT_REG_VERDICT && len(imm.Data) == 0 {
|
||||
v := &expr.Verdict{}
|
||||
if err := expr.Unmarshal(inet, data, v); err != nil {
|
||||
if err := expr.Unmarshal(fam, data, v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
|
||||
@@ -29,7 +29,7 @@ func TestSnapshotRulesRoundTrip(t *testing.T) {
|
||||
"input": {{Chain: "input", Tag: "ssh", Exprs: exprs}, {Chain: "input", Tag: "drop", Exprs: []expr.Any{&expr.Verdict{Kind: expr.VerdictDrop}}}},
|
||||
}}
|
||||
|
||||
rules, err := encodeState(state)
|
||||
rules, err := encodeState(state, byte(nftables.TableFamilyINet))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func TestSnapshotRulesRoundTrip(t *testing.T) {
|
||||
if snap.Policies["input"] != nftables.ChainPolicyAccept {
|
||||
t.Errorf("policy lost: %v", snap.Policies)
|
||||
}
|
||||
got, err := decodeState(snap.Rules)
|
||||
got, err := decodeState(snap.Rules, byte(nftables.TableFamilyINet))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -79,7 +79,7 @@ func TestSnapshotAndRestoreAbsentTable(t *testing.T) {
|
||||
for _, m := range req {
|
||||
sent = append(sent, m.Header.Type)
|
||||
if m.Header.Type == nftType(unix.NFT_MSG_GETTABLE) && tablePresent {
|
||||
data := []byte{inet, 0, 0, 0}
|
||||
data := []byte{byte(nftables.TableFamilyINet), 0, 0, 0}
|
||||
attrs, _ := netlink.MarshalAttributes([]netlink.Attribute{{Type: unix.NFTA_TABLE_NAME, Data: []byte("tomswall\x00")}})
|
||||
return []netlink.Message{{Header: netlink.Header{Type: nftType(unix.NFT_MSG_NEWTABLE), Sequence: m.Header.Sequence}, Data: append(data, attrs...)}}, nil
|
||||
}
|
||||
@@ -116,7 +116,7 @@ func TestRestorePresentTable(t *testing.T) {
|
||||
{Tag: "ssh", Exprs: []expr.Any{&expr.Ct{Register: 1, Key: expr.CtKeySTATE}, &expr.Verdict{Kind: expr.VerdictAccept}}},
|
||||
{Tag: "drop", Exprs: []expr.Any{&expr.Verdict{Kind: expr.VerdictDrop}}},
|
||||
} {
|
||||
enc, err := encodeState(&FirewallState{Rules: map[string][]ManagedRule{"input": {r}}})
|
||||
enc, err := encodeState(&FirewallState{Rules: map[string][]ManagedRule{"input": {r}}}, byte(nftables.TableFamilyINet))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -132,7 +132,7 @@ func TestRestorePresentTable(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return append([]byte{inet, 0, 0, 0}, b...)
|
||||
return append([]byte{byte(nftables.TableFamilyINet), 0, 0, 0}, b...)
|
||||
}
|
||||
handle := make([]byte, 8)
|
||||
binary.BigEndian.PutUint64(handle, 7)
|
||||
@@ -243,3 +243,17 @@ func testEngine(t *testing.T, dial func([]netlink.Message) ([]netlink.Message, e
|
||||
}
|
||||
return &Engine{cfg: &config.Config{Settings: config.Settings{TableName: "tomswall"}}, conn: conn}
|
||||
}
|
||||
|
||||
func TestEnsureChainsRawPriority(t *testing.T) {
|
||||
e := testEngine(t, nil)
|
||||
chains := e.ensureChains(e.ensureTable(), nil)
|
||||
for name, hook := range map[string]*nftables.ChainHook{"raw_prerouting": nftables.ChainHookPrerouting, "raw_output": nftables.ChainHookOutput} {
|
||||
c, ok := chains[name]
|
||||
if !ok {
|
||||
t.Fatalf("%s chain not declared", name)
|
||||
}
|
||||
if *c.Priority != *nftables.ChainPriorityRaw || *c.Hooknum != *hook || c.Type != nftables.ChainTypeFilter || *c.Policy != nftables.ChainPolicyAccept {
|
||||
t.Errorf("%s: got type %s hook %d prio %d", name, c.Type, *c.Hooknum, *c.Priority)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +99,15 @@ func convertDir(dir string, ipv6 bool) (*config.Config, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// disposition maps a shorewall *_DISPOSITION value; unset means CONTINUE and A_ (audit) variants map to their base action.
|
||||
func disposition(v string) config.PolicyAction {
|
||||
v = strings.TrimPrefix(strings.ToLower(v), "a_")
|
||||
if v == "" {
|
||||
return config.PolicyContinue
|
||||
}
|
||||
return config.PolicyAction(v)
|
||||
}
|
||||
|
||||
func subst(s string, params map[string]string) string {
|
||||
if !strings.Contains(s, "$") {
|
||||
return s
|
||||
@@ -115,6 +124,8 @@ func convertConf(dir string, cfg *config.Config, params map[string]string, ipv6
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Settings.InvalidDisposition = disposition(conf["INVALID_DISPOSITION"])
|
||||
cfg.Settings.UntrackedDisposition = disposition(conf["UNTRACKED_DISPOSITION"])
|
||||
if conf == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -136,7 +147,6 @@ func convertConf(dir string, cfg *config.Config, params map[string]string, ipv6
|
||||
if v, ok := conf["IMPLICIT_CONTINUE"]; ok {
|
||||
cfg.Settings.ImplicitContinue = v == "Yes"
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -725,3 +725,34 @@ func TestIsIPv6Dir(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestConvert_Dispositions(t *testing.T) {
|
||||
cases := []struct {
|
||||
conf string
|
||||
invalid, untracked config.PolicyAction
|
||||
}{
|
||||
{"", config.PolicyContinue, config.PolicyContinue},
|
||||
{"IP_FORWARDING=Yes", config.PolicyContinue, config.PolicyContinue},
|
||||
{"INVALID_DISPOSITION=CONTINUE\nUNTRACKED_DISPOSITION=ACCEPT", config.PolicyContinue, config.PolicyAccept},
|
||||
{"INVALID_DISPOSITION=DROP\nUNTRACKED_DISPOSITION=A_DROP", config.PolicyDrop, config.PolicyDrop},
|
||||
{"INVALID_DISPOSITION=A_REJECT", config.PolicyReject, config.PolicyContinue},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "shorewall.conf", tc.conf)
|
||||
writeFile(t, dir, "zones", "fw firewall\nnet ipv4\n")
|
||||
writeFile(t, dir, "interfaces", "net eth0 -\n")
|
||||
writeFile(t, dir, "policy", "all all DROP\n")
|
||||
cfg, err := Convert(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("Convert(%q): %v", tc.conf, err)
|
||||
}
|
||||
if cfg.Settings.InvalidDisposition != tc.invalid || cfg.Settings.UntrackedDisposition != tc.untracked {
|
||||
t.Errorf("%q: got invalid=%q untracked=%q, want %q/%q", tc.conf,
|
||||
cfg.Settings.InvalidDisposition, cfg.Settings.UntrackedDisposition, tc.invalid, tc.untracked)
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
t.Errorf("%q: Validate: %v", tc.conf, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,10 +175,28 @@ func Revert(id string) (reverted bool, err error) {
|
||||
if err != nil || p == nil || (id != "" && p.ID != id) {
|
||||
return false, err
|
||||
}
|
||||
if err := restore(p.Snapshot); err != nil {
|
||||
return false, fmt.Errorf("restoring snapshot: %w", err)
|
||||
return true, restorePending(p)
|
||||
}
|
||||
|
||||
// Abort restores the pending snapshot after a failed apply, which may have
|
||||
// committed partially. A failed restore keeps the snapshot and timer so the
|
||||
// timer still reverts. The caller must hold the lock.
|
||||
func Abort() error {
|
||||
p, err := load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return true, Discard()
|
||||
if p == nil {
|
||||
return errors.New("no pending try to abort")
|
||||
}
|
||||
return restorePending(p)
|
||||
}
|
||||
|
||||
func restorePending(p *pending) error {
|
||||
if err := restore(p.Snapshot); err != nil {
|
||||
return fmt.Errorf("restoring snapshot: %w", err)
|
||||
}
|
||||
return Discard()
|
||||
}
|
||||
|
||||
func load() (*pending, error) {
|
||||
|
||||
@@ -209,3 +209,41 @@ func TestRevertStaleIDIgnored(t *testing.T) {
|
||||
t.Errorf("newer try's snapshot removed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAbortRestoresAndDisarms(t *testing.T) {
|
||||
cmds := setup(t)
|
||||
restored := stubRestore(t, nil)
|
||||
snap := &nftables.Snapshot{Table: "tomswall", Present: true}
|
||||
arm(t, snap)
|
||||
|
||||
if err := Abort(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(*restored) != 1 || !reflect.DeepEqual((*restored)[0], snap) {
|
||||
t.Errorf("restored %+v, want the armed snapshot", *restored)
|
||||
}
|
||||
if _, err := os.Stat(snapshotPath()); !os.IsNotExist(err) {
|
||||
t.Error("snapshot not removed")
|
||||
}
|
||||
if last := (*cmds)[len(*cmds)-1]; last != "systemctl stop "+Unit+".timer" {
|
||||
t.Errorf("timer not stopped, last command %q", last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAbortFailureKeepsSnapshotAndTimer(t *testing.T) {
|
||||
cmds := setup(t)
|
||||
boom := errors.New("netlink down")
|
||||
stubRestore(t, boom)
|
||||
arm(t, &nftables.Snapshot{Table: "tomswall"})
|
||||
armed := len(*cmds)
|
||||
|
||||
if err := Abort(); !errors.Is(err, boom) {
|
||||
t.Fatalf("Abort error = %v, want %v", err, boom)
|
||||
}
|
||||
if _, err := os.Stat(snapshotPath()); err != nil {
|
||||
t.Fatalf("snapshot gone after failed abort: %v", err)
|
||||
}
|
||||
if len(*cmds) != armed {
|
||||
t.Errorf("revert timer touched after failed abort: %v", (*cmds)[armed:])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,10 @@ settings:
|
||||
log_level: info
|
||||
table_name: tomswall
|
||||
implicit_continue: false
|
||||
# ct state invalid/untracked verdict: accept, drop, reject, continue (pass to rules)
|
||||
# defaults: invalid drop, untracked continue (migrate defaults both to continue, as shorewall)
|
||||
invalid_disposition: drop
|
||||
untracked_disposition: continue
|
||||
|
||||
# Named port groups — reusable port+protocol combos referenced in rules
|
||||
portgroups:
|
||||
@@ -191,13 +195,12 @@ snat:
|
||||
# conntrack:
|
||||
# - action: notrack
|
||||
# source: net
|
||||
# dest: fw
|
||||
# dest: fw:203.0.113.1
|
||||
# proto: udp
|
||||
# dport: [53]
|
||||
# comment: "Skip conntrack for DNS"
|
||||
# - action: helper
|
||||
# source: loc
|
||||
# dest: net
|
||||
# proto: tcp
|
||||
# dport: [21]
|
||||
# helper: ftp
|
||||
|
||||
Reference in New Issue
Block a user