Compare commits
40 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| 63c46fec81 | |||
| 5238886c6e | |||
| 532bd80a8a | |||
| 036021d726 | |||
| ff5a52b9e2 | |||
| 44e1ba852e | |||
| 34cf6dc9ab | |||
| b5be665902 |
@@ -104,3 +104,45 @@ steps:
|
|||||||
limits:
|
limits:
|
||||||
memory: 512Mi
|
memory: 512Mi
|
||||||
cpu: 500m
|
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,19 +3,18 @@ module git.unkin.net/unkin/tomswall
|
|||||||
go 1.23
|
go 1.23
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/google/nftables v0.2.0
|
github.com/google/nftables v0.3.0
|
||||||
github.com/mdlayher/netlink v1.7.2
|
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42
|
||||||
github.com/spf13/cobra v1.8.1
|
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
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/google/go-cmp v0.6.0 // indirect
|
github.com/google/go-cmp v0.6.0 // indirect
|
||||||
github.com/inconshreveable/mousetrap v1.1.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/mdlayher/socket v0.5.1 // indirect
|
||||||
github.com/spf13/pflag v1.0.5 // 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
|
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/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 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
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.3.0 h1:bkyZ0cbpVeMHXOrtlFc8ISmfVqq5gPJukoYieyVmITg=
|
||||||
github.com/google/nftables v0.2.0/go.mod h1:Beg6V6zZ3oEn0JuiUQ4wqwuyqqzasOltcoXPtgLbFp4=
|
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 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLA=
|
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42 h1:A1Cq6Ysb0GM0tpKMbdCXCIfBclan4oHk1Jb+Hrejirg=
|
||||||
github.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
|
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42/go.mod h1:BB4YCPDOzfy7FniQ/lxuYQ3dgmM2cZumHbK8RpTjN2o=
|
||||||
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/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
|
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
|
||||||
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
|
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=
|
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/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 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
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.4 h1:Oeaw1EM2JMxD51g9uhtC0D7erkIjgmj8+JZc26m1YX8=
|
||||||
github.com/vishvananda/netns v0.0.0-20180720170159-13995c7128cc/go.mod h1:ZjcWmFBXmLKZu9Nxj3WKYEafiSqer2rnvPr0en9UNpI=
|
github.com/vishvananda/netns v0.0.4/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||||
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
|
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
|
||||||
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
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 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
|
||||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
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.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||||
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
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 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
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)
|
return fmt.Errorf("blrules[%d]: dest required", i)
|
||||||
}
|
}
|
||||||
|
|
||||||
if r.Source != "all" && r.Source != "any" && r.Source != "none" &&
|
if err := c.validateZoneRef(r.Source); err != nil {
|
||||||
!hasPrefix(r.Source, "all!") && !hasPrefix(r.Source, "any!") {
|
return fmt.Errorf("blrules[%d]: source %w", i, err)
|
||||||
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.Dest); err != nil {
|
||||||
if r.Dest != "all" && r.Dest != "any" && r.Dest != "none" &&
|
return fmt.Errorf("blrules[%d]: dest %w", i, err)
|
||||||
!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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import "fmt"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
type ConntrackAction string
|
type ConntrackAction string
|
||||||
|
|
||||||
@@ -68,8 +71,14 @@ func (c *Config) validateConntrack() error {
|
|||||||
return fmt.Errorf("conntrack[%d]: helper name required for helper action", i)
|
return fmt.Errorf("conntrack[%d]: helper name required for helper action", i)
|
||||||
}
|
}
|
||||||
|
|
||||||
if ct.Source == "" && ct.Dest == "" && ct.Action != ConntrackHelper {
|
if HasZoneExclusion(ct.Source) || HasZoneExclusion(ct.Dest) {
|
||||||
return fmt.Errorf("conntrack[%d]: source or dest required", i)
|
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 != "" {
|
if ct.User != "" {
|
||||||
@@ -84,3 +93,9 @@ func (c *Config) validateConntrack() error {
|
|||||||
}
|
}
|
||||||
return nil
|
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",
|
name: "omitted source and dest is valid",
|
||||||
rules: []ConntrackRule{
|
rules: []ConntrackRule{{Action: ConntrackNoTrack, Proto: "udp", DPort: PortSpec{"53"}}},
|
||||||
{Action: ConntrackDrop},
|
},
|
||||||
},
|
{
|
||||||
wantErr: "source or dest required",
|
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",
|
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)
|
return fmt.Errorf("rule[%d]: dest required", i)
|
||||||
}
|
}
|
||||||
|
|
||||||
if r.Source != "all" && r.Source != "any" && r.Source != "none" &&
|
if err := c.validateZoneRef(r.Source); err != nil {
|
||||||
!hasPrefix(r.Source, "all+") && !hasPrefix(r.Source, "all!") && !hasPrefix(r.Source, "any!") {
|
return fmt.Errorf("rule[%d]: source %w", i, err)
|
||||||
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 r.Action != RuleDNAT && r.Action != RuleRedirect && r.Action != RuleNoNAT {
|
if r.Action != RuleDNAT && r.Action != RuleRedirect && r.Action != RuleNoNAT {
|
||||||
if r.Dest != "all" && r.Dest != "any" && r.Dest != "none" &&
|
if err := c.validateZoneRef(r.Dest); err != nil {
|
||||||
!hasPrefix(r.Dest, "all+") && !hasPrefix(r.Dest, "all!") && !hasPrefix(r.Dest, "any!") {
|
return fmt.Errorf("rule[%d]: dest %w", i, err)
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,6 +248,32 @@ func zoneFromSpec(spec string) string {
|
|||||||
return spec
|
return spec
|
||||||
}
|
}
|
||||||
|
|
||||||
func hasPrefix(s, prefix string) bool {
|
// validateZoneRef checks a SOURCE/DEST spec: all/any[+][!excluded,...][:addr], none, or a declared zone list.
|
||||||
return len(s) >= len(prefix) && s[:len(prefix)] == prefix
|
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
|
||||||
}
|
}
|
||||||
|
|||||||
+383
-117
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
|
"slices"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -125,40 +126,23 @@ func (c *Compiler) compileDHCP(state *FirewallState) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
name := iface.PhysicalName()
|
name := iface.PhysicalName()
|
||||||
// Allow DHCPv4 client traffic (bootpc:68 → bootps:67)
|
dhcp := func(chain, dir string, ifaceMatch []expr.Any) {
|
||||||
state.Rules["input"] = append(state.Rules["input"], ManagedRule{
|
state.Rules[chain] = append(state.Rules[chain], ManagedRule{
|
||||||
Chain: "input",
|
Chain: chain,
|
||||||
Exprs: append(append(append(
|
Exprs: append(append(append(append(ifaceMatch,
|
||||||
matchIfaceName(true, name),
|
matchNFProto(unix.NFPROTO_IPV4)...),
|
||||||
matchProtoNum(unix.IPPROTO_UDP)...),
|
matchProtoNum(unix.IPPROTO_UDP)...),
|
||||||
matchSPort(68)...),
|
matchDPortRange(67, 68)...),
|
||||||
matchDPort(67)...,
|
&expr.Verdict{Kind: expr.VerdictAccept}),
|
||||||
),
|
Tag: fmt.Sprintf("dhcp:%s:%s", dir, iface.Interface),
|
||||||
Tag: fmt.Sprintf("dhcp:in:%s", iface.Interface),
|
})
|
||||||
})
|
}
|
||||||
// Allow DHCPv4 server → client replies
|
// shorewall: udp dport 67:68 both ways between fw and iface, forwarded back out a bridge
|
||||||
state.Rules["input"] = append(state.Rules["input"], ManagedRule{
|
dhcp("input", "in", matchIfaceName(true, name))
|
||||||
Chain: "input",
|
dhcp("output", "out", matchIfaceName(false, name))
|
||||||
Exprs: append(append(append(append(
|
if iface.Options.Bridge {
|
||||||
matchIfaceName(true, name),
|
dhcp("forward", "fwd", append(matchIfaceName(true, name), matchIfaceName(false, 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),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,47 +189,151 @@ func (c *Compiler) compileBlrules(state *FirewallState) error {
|
|||||||
}
|
}
|
||||||
if err := c.compileOneRule(state, tag, rule.Source, rule.Dest,
|
if err := c.compileOneRule(state, tag, rule.Source, rule.Dest,
|
||||||
rule.Proto, rule.DPort, rule.SPort,
|
rule.Proto, rule.DPort, rule.SPort,
|
||||||
action, rule.Log, "", fwZone, ""); err != nil {
|
action, rule.Log, "", "", fwZone, ""); err != nil {
|
||||||
return fmt.Errorf("blrule[%d]: %w", i, err)
|
return fmt.Errorf("blrule[%d]: %w", i, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
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 {
|
func (c *Compiler) compileConntrack(state *FirewallState) error {
|
||||||
|
fwZone := c.cfg.FirewallZone()
|
||||||
for i, ct := range c.cfg.Conntrack {
|
for i, ct := range c.cfg.Conntrack {
|
||||||
tag := fmt.Sprintf("conntrack:%d", i)
|
tag := fmt.Sprintf("conntrack:%d", i)
|
||||||
|
if config.HasZoneExclusion(ct.Source) || config.HasZoneExclusion(ct.Dest) {
|
||||||
chains := []string{"prerouting"}
|
return fmt.Errorf("conntrack[%d]: zone exclusions are not supported in conntrack entries", i)
|
||||||
switch ct.Chain {
|
}
|
||||||
case config.ConntrackOutput:
|
cts := []config.ConntrackRule{ct}
|
||||||
chains = []string{"output"}
|
if ct.Action == config.ConntrackHelper {
|
||||||
case config.ConntrackBoth:
|
if ct.Chain == "" {
|
||||||
chains = []string{"prerouting", "output"}
|
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)
|
for _, src := range srcs {
|
||||||
if err != nil {
|
if src.Zone == "all" || src.Zone == "any" {
|
||||||
return fmt.Errorf("conntrack[%d]: %w", i, err)
|
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 {
|
for _, m := range matches {
|
||||||
exprs := append([]expr.Any{}, m.exprs...)
|
exprs := m.exprs
|
||||||
|
|
||||||
switch ct.Action {
|
switch ct.Action {
|
||||||
case config.ConntrackNoTrack:
|
case config.ConntrackNoTrack:
|
||||||
exprs = append(exprs, &expr.Notrack{})
|
exprs = append(exprs, &expr.Notrack{})
|
||||||
case config.ConntrackHelper:
|
|
||||||
continue
|
|
||||||
case config.ConntrackDrop:
|
case config.ConntrackDrop:
|
||||||
exprs = append(exprs, &expr.Verdict{Kind: expr.VerdictDrop})
|
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[out] = append(state.Rules[out], ManagedRule{
|
||||||
state.Rules[chain] = append(state.Rules[chain], ManagedRule{
|
Chain: out,
|
||||||
Chain: chain,
|
|
||||||
Exprs: exprs,
|
Exprs: exprs,
|
||||||
Tag: tag + ":" + chain,
|
Tag: tag + ":" + out,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -276,14 +364,14 @@ func (c *Compiler) compileRules(state *FirewallState) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("rule[%d]: %w", i, err)
|
return fmt.Errorf("rule[%d]: %w", i, err)
|
||||||
}
|
}
|
||||||
if len(matches)*specCount(rule.Source, rule.Dest, 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)
|
return fmt.Errorf("rule[%d]: ratelimit/connlimit cannot be combined with proto, port, zone or address lists (each expanded rule would get its own limiter)", i)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := c.compileOneRule(state, tag, rule.Source, rule.Dest,
|
if err := c.compileOneRule(state, tag, rule.Source, rule.Dest,
|
||||||
proto, dports, sport,
|
proto, dports, sport,
|
||||||
rule.Action, rule.Log, rule.Dest, fwZone, rule.Section); err != nil {
|
rule.Action, rule.Log, rule.Dest, rule.OrigDest, fwZone, rule.Section); err != nil {
|
||||||
return fmt.Errorf("rule[%d]: %w", i, err)
|
return fmt.Errorf("rule[%d]: %w", i, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -360,19 +448,32 @@ func (c *Compiler) applyChainExtras(state *FirewallState, chain, tag string, rul
|
|||||||
|
|
||||||
func (c *Compiler) compileOneRule(state *FirewallState, tag, srcSpec, dstSpec, proto string,
|
func (c *Compiler) compileOneRule(state *FirewallState, tag, srcSpec, dstSpec, proto string,
|
||||||
dports, sports config.PortSpec, action config.RuleAction, logLevel string,
|
dports, sports config.PortSpec, action config.RuleAction, logLevel string,
|
||||||
dnatDest string, fwZone string, section config.RuleSection) error {
|
dnatDest, origDest string, fwZone string, section config.RuleSection) error {
|
||||||
|
|
||||||
for _, src := range zoneSpecs(srcSpec) {
|
if action == config.RuleDNAT || action == config.RuleRedirect {
|
||||||
for _, srcAddr := range splitAddrs(src.Addr) {
|
for _, src := range c.dnatSourceSpecs(srcSpec, fwZone) {
|
||||||
if action == config.RuleDNAT || action == config.RuleRedirect {
|
if dnatSkipsIntrazone(srcSpec, src.Zone, dstSpec) {
|
||||||
if err := c.compileDNATRule(state, tag, src.Zone, srcAddr, dstSpec, proto, dports, action, logLevel); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for _, dst := range zoneSpecs(dstSpec) {
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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) {
|
for _, dstAddr := range splitAddrs(dst.Addr) {
|
||||||
if err := c.compileZonePair(state, tag, src.Zone, srcAddr, dst.Zone, dstAddr, proto,
|
if err := c.compileZonePair(state, tag, src.Zone, srcAddr, dst.Zone, dstAddr, od, proto,
|
||||||
dports, sports, action, logLevel, fwZone, section); err != nil {
|
dports, sports, action, logLevel, fwZone, section); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -383,27 +484,135 @@ func (c *Compiler) compileOneRule(state *FirewallState, tag, srcSpec, dstSpec, p
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// specCount is how many zone/address combinations compileOneRule expands src and dst into.
|
// dnatSourceSpecs hooks DNAT per source zone like shorewall: all/any expand to every zone but fw (prerouting never sees fw traffic).
|
||||||
func specCount(srcSpec, dstSpec string, action config.RuleAction) int {
|
func (c *Compiler) dnatSourceSpecs(spec, fwZone string) []config.ZoneSpec {
|
||||||
count := func(spec string) (n int) {
|
zone, addr := splitZoneSpec(spec)
|
||||||
for _, z := range zoneSpecs(spec) {
|
base, _, _ := strings.Cut(zone, "!")
|
||||||
n += len(splitAddrs(z.Addr))
|
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
|
|
||||||
}
|
}
|
||||||
if action == config.RuleDNAT || action == config.RuleRedirect {
|
return out
|
||||||
return count(srcSpec)
|
|
||||||
}
|
|
||||||
return count(srcSpec) * count(dstSpec)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// zoneSpecs expands a comma zone list; "all"/"any" forms keep their own comma (exclusion) syntax.
|
// dnatSkipsIntrazone mirrors shorewall: a zone list or all/any source never pairs a zone with itself unless marked "+".
|
||||||
func zoneSpecs(spec string) []config.ZoneSpec {
|
func dnatSkipsIntrazone(srcSpec, srcZone, dstSpec string) bool {
|
||||||
zone, addr := splitZoneSpec(spec)
|
zones, _, _ := strings.Cut(srcSpec, ":")
|
||||||
if base, _, _ := strings.Cut(strings.TrimSuffix(zone, "+"), "!"); base == "all" || base == "any" {
|
base, _, _ := strings.Cut(zones, "!")
|
||||||
return []config.ZoneSpec{{Zone: zone, Addr: addr}}
|
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.
|
// splitAddrs yields one alternative per listed address; a negated list stays one AND-ed match.
|
||||||
@@ -414,12 +623,16 @@ func splitAddrs(addr string) []string {
|
|||||||
return strings.Split(addr, ",")
|
return strings.Split(addr, ",")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Compiler) compileZonePair(state *FirewallState, tag, srcZone, srcAddr, dstZone, dstAddr, proto string,
|
func (c *Compiler) compileZonePair(state *FirewallState, tag, srcZone, srcAddr, dstZone, dstAddr, origDest, proto string,
|
||||||
dports, sports config.PortSpec, action config.RuleAction, logLevel string,
|
dports, sports config.PortSpec, action config.RuleAction, logLevel string,
|
||||||
fwZone string, section config.RuleSection) error {
|
fwZone string, section config.RuleSection) error {
|
||||||
srcIfaces := c.resolveZoneInterfaces(srcZone)
|
srcIfaces := c.resolveZoneInterfaces(srcZone, srcAddr)
|
||||||
dstIfaces := c.resolveZoneInterfaces(dstZone)
|
dstIfaces := c.resolveZoneInterfaces(dstZone, dstAddr)
|
||||||
chain := c.selectChain(srcZone, dstZone, fwZone)
|
chain := c.selectChain(srcZone, dstZone, fwZone)
|
||||||
|
// ponytail: forward daddr is post-DNAT; lift with `ct original daddr` (expr.Ct Direction, google/nftables v0.3.0).
|
||||||
|
if origDest != "" && chain == "forward" {
|
||||||
|
return fmt.Errorf("origdest: ORIGDEST on forwarded rules is not supported yet")
|
||||||
|
}
|
||||||
|
|
||||||
for _, srcIface := range srcIfaces {
|
for _, srcIface := range srcIfaces {
|
||||||
for _, dstIface := range dstIfaces {
|
for _, dstIface := range dstIfaces {
|
||||||
@@ -427,6 +640,15 @@ func (c *Compiler) compileZonePair(state *FirewallState, tag, srcZone, srcAddr,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if origDest != "" {
|
||||||
|
od, err := matchOrigDest(origDest)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("origdest: %w", err)
|
||||||
|
}
|
||||||
|
for i := range matches {
|
||||||
|
matches[i].exprs = append(matches[i].exprs, od...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for _, m := range matches {
|
for _, m := range matches {
|
||||||
exprs := m.exprs
|
exprs := m.exprs
|
||||||
@@ -455,8 +677,8 @@ func (c *Compiler) compileZonePair(state *FirewallState, tag, srcZone, srcAddr,
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr, dstSpec, proto string,
|
func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr, origDest, dstSpec, proto string,
|
||||||
dports config.PortSpec, action config.RuleAction, logLevel string) error {
|
dports, sports config.PortSpec, action config.RuleAction, logLevel string) error {
|
||||||
chain := "prerouting"
|
chain := "prerouting"
|
||||||
|
|
||||||
parts := strings.SplitN(dstSpec, ":", 3)
|
parts := strings.SplitN(dstSpec, ":", 3)
|
||||||
@@ -474,9 +696,17 @@ func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr,
|
|||||||
dnatPort = uint16(p)
|
dnatPort = uint16(p)
|
||||||
}
|
}
|
||||||
|
|
||||||
srcIfaces := c.resolveZoneInterfaces(srcZone)
|
srcIfaces := c.resolveZoneInterfaces(srcZone, srcAddr)
|
||||||
|
|
||||||
matches, err := l4Matches(proto, dports, nil)
|
var odExprs []expr.Any
|
||||||
|
if origDest != "" {
|
||||||
|
var err error
|
||||||
|
if odExprs, err = matchOrigDest(origDest); err != nil {
|
||||||
|
return fmt.Errorf("origdest: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
matches, err := l4Matches(proto, dports, sports)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -501,6 +731,7 @@ func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr,
|
|||||||
}
|
}
|
||||||
exprs = append(exprs, src...)
|
exprs = append(exprs, src...)
|
||||||
}
|
}
|
||||||
|
exprs = append(exprs, odExprs...)
|
||||||
|
|
||||||
exprs = append(exprs, m.exprs...)
|
exprs = append(exprs, m.exprs...)
|
||||||
|
|
||||||
@@ -538,6 +769,7 @@ func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr,
|
|||||||
)
|
)
|
||||||
natExpr.RegProtoMin = 2
|
natExpr.RegProtoMin = 2
|
||||||
natExpr.RegProtoMax = 2
|
natExpr.RegProtoMax = 2
|
||||||
|
natExpr.Specified = true
|
||||||
}
|
}
|
||||||
exprs = append(exprs, natExpr)
|
exprs = append(exprs, natExpr)
|
||||||
} else {
|
} else {
|
||||||
@@ -558,6 +790,7 @@ func (c *Compiler) compileDNATRule(state *FirewallState, tag, srcZone, srcAddr,
|
|||||||
)
|
)
|
||||||
natExpr.RegProtoMin = 2
|
natExpr.RegProtoMin = 2
|
||||||
natExpr.RegProtoMax = 2
|
natExpr.RegProtoMax = 2
|
||||||
|
natExpr.Specified = true
|
||||||
}
|
}
|
||||||
exprs = append(exprs, natExpr)
|
exprs = append(exprs, natExpr)
|
||||||
}
|
}
|
||||||
@@ -589,8 +822,8 @@ func (c *Compiler) compilePolicies(state *FirewallState) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
chain := c.selectChain(sz, dz, fwZone)
|
chain := c.selectChain(sz, dz, fwZone)
|
||||||
srcIfaces := c.resolveZoneInterfaces(sz)
|
srcIfaces := c.resolveZoneInterfaces(sz, "")
|
||||||
dstIfaces := c.resolveZoneInterfaces(dz)
|
dstIfaces := c.resolveZoneInterfaces(dz, "")
|
||||||
|
|
||||||
for _, si := range srcIfaces {
|
for _, si := range srcIfaces {
|
||||||
for _, di := range dstIfaces {
|
for _, di := range dstIfaces {
|
||||||
@@ -599,7 +832,7 @@ func (c *Compiler) compilePolicies(state *FirewallState) error {
|
|||||||
if si != "" {
|
if si != "" {
|
||||||
exprs = append(exprs, matchIfaceName(true, si)...)
|
exprs = append(exprs, matchIfaceName(true, si)...)
|
||||||
}
|
}
|
||||||
if di != "" && chain == "forward" {
|
if di != "" && chain != "input" {
|
||||||
exprs = append(exprs, matchIfaceName(false, di)...)
|
exprs = append(exprs, matchIfaceName(false, di)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -932,34 +1165,34 @@ func (c *Compiler) selectChain(srcZone, dstZone, fwZone string) string {
|
|||||||
return "forward"
|
return "forward"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Compiler) resolveZoneInterfaces(zone string) []string {
|
// resolveZoneInterfaces returns nil (fail closed) for an unknown zone, or one with no interfaces unless a non-negated address match narrows the rule.
|
||||||
if zone == "all" || zone == "" {
|
func (c *Compiler) resolveZoneInterfaces(zone, addr string) []string {
|
||||||
|
switch zone {
|
||||||
|
case "", "all", "all+", "any", "any+":
|
||||||
return []string{""}
|
return []string{""}
|
||||||
}
|
}
|
||||||
ifaces := c.cfg.ZoneInterfaces(zone)
|
z, ok := c.cfg.Zones[zone]
|
||||||
if len(ifaces) > 0 {
|
if !ok {
|
||||||
return ifaces
|
slog.Warn("compiler: unknown zone, skipping its rules", "zone", zone)
|
||||||
}
|
|
||||||
if z, ok := c.cfg.Zones[zone]; ok && z.Type == config.ZoneIP && !c.zoneHasHosts(zone) {
|
|
||||||
if !c.warned[zone] {
|
|
||||||
if c.warned == nil {
|
|
||||||
c.warned = map[string]bool{}
|
|
||||||
}
|
|
||||||
c.warned[zone] = true
|
|
||||||
slog.Warn("compiler: zone has no interfaces, skipping its rules", "zone", zone)
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return []string{""}
|
if z.Type == config.ZoneFirewall {
|
||||||
}
|
return []string{""}
|
||||||
|
|
||||||
func (c *Compiler) zoneHasHosts(zone string) bool {
|
|
||||||
for _, h := range c.cfg.Hosts {
|
|
||||||
if h.Zone == zone {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return false
|
if ifaces := c.cfg.ZoneInterfaces(zone); len(ifaces) > 0 {
|
||||||
|
return ifaces
|
||||||
|
}
|
||||||
|
if addr != "" && !strings.HasPrefix(addr, "!") {
|
||||||
|
return []string{""}
|
||||||
|
}
|
||||||
|
if !c.warned[zone] {
|
||||||
|
if c.warned == nil {
|
||||||
|
c.warned = map[string]bool{}
|
||||||
|
}
|
||||||
|
c.warned[zone] = true
|
||||||
|
slog.Warn("compiler: zone has no interfaces, skipping its rules", "zone", zone)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Compiler) expandZoneRef(ref string) []string {
|
func (c *Compiler) expandZoneRef(ref string) []string {
|
||||||
@@ -977,7 +1210,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
|
var zones []string
|
||||||
for name := range c.cfg.Zones {
|
for name := range c.cfg.Zones {
|
||||||
if excluded != nil && excluded[name] {
|
if excluded != nil && excluded[name] {
|
||||||
@@ -997,7 +1230,7 @@ func (c *Compiler) buildMatchExprs(srcIface, dstIface, chain, proto string, dpor
|
|||||||
if srcIface != "" {
|
if srcIface != "" {
|
||||||
exprs = append(exprs, matchIfaceName(true, srcIface)...)
|
exprs = append(exprs, matchIfaceName(true, srcIface)...)
|
||||||
}
|
}
|
||||||
if dstIface != "" && chain == "forward" {
|
if dstIface != "" && chain != "input" {
|
||||||
exprs = append(exprs, matchIfaceName(false, dstIface)...)
|
exprs = append(exprs, matchIfaceName(false, dstIface)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1386,6 +1619,34 @@ func matchDestCIDR(cidr string) ([]expr.Any, error) {
|
|||||||
return matchAddrCIDR(cidr, false)
|
return matchAddrCIDR(cidr, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// matchOrigDest guards the daddr match with the address's nfproto so it is family-correct in the inet table.
|
||||||
|
func matchOrigDest(addr string) ([]expr.Any, error) {
|
||||||
|
var proto byte
|
||||||
|
for i, a := range strings.Split(strings.TrimPrefix(addr, "!"), ",") {
|
||||||
|
a, _, _ = strings.Cut(a, "/")
|
||||||
|
p := byte(unix.NFPROTO_IPV6)
|
||||||
|
if ip := net.ParseIP(a); ip != nil && ip.To4() != nil {
|
||||||
|
p = unix.NFPROTO_IPV4
|
||||||
|
}
|
||||||
|
if i > 0 && p != proto {
|
||||||
|
return nil, fmt.Errorf("%q mixes IPv4 and IPv6 addresses", addr)
|
||||||
|
}
|
||||||
|
proto = p
|
||||||
|
}
|
||||||
|
dst, err := matchDestCIDR(addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return append(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}},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func matchAddrCIDR(cidr string, isSrc bool) ([]expr.Any, error) {
|
func matchAddrCIDR(cidr string, isSrc bool) ([]expr.Any, error) {
|
||||||
negated := false
|
negated := false
|
||||||
if strings.HasPrefix(cidr, "!") {
|
if strings.HasPrefix(cidr, "!") {
|
||||||
@@ -1471,13 +1732,18 @@ const (
|
|||||||
ctStateRelated = 4
|
ctStateRelated = 4
|
||||||
ctStateNew = 8
|
ctStateNew = 8
|
||||||
ctStateUntracked = 64
|
ctStateUntracked = 64
|
||||||
|
ctStatusDNAT = 32
|
||||||
)
|
)
|
||||||
|
|
||||||
func matchCtState(stateMask uint32) []expr.Any {
|
func matchCtState(stateMask uint32) []expr.Any {
|
||||||
|
return matchCtBits(expr.CtKeySTATE, stateMask)
|
||||||
|
}
|
||||||
|
|
||||||
|
func matchCtBits(key expr.CtKey, stateMask uint32) []expr.Any {
|
||||||
stateBytes := make([]byte, 4)
|
stateBytes := make([]byte, 4)
|
||||||
binary.NativeEndian.PutUint32(stateBytes, stateMask)
|
binary.NativeEndian.PutUint32(stateBytes, stateMask)
|
||||||
return []expr.Any{
|
return []expr.Any{
|
||||||
&expr.Ct{Key: expr.CtKeySTATE, Register: 1},
|
&expr.Ct{Key: key, Register: 1},
|
||||||
&expr.Bitwise{
|
&expr.Bitwise{
|
||||||
SourceRegister: 1,
|
SourceRegister: 1,
|
||||||
DestRegister: 1,
|
DestRegister: 1,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -20,15 +20,25 @@ type ManagedRule struct {
|
|||||||
|
|
||||||
type FirewallState struct {
|
type FirewallState struct {
|
||||||
Rules map[string][]ManagedRule
|
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 {
|
type ChangeSet struct {
|
||||||
Add []ManagedRule
|
Add []ManagedRule
|
||||||
Remove []ManagedRule
|
Remove []ManagedRule
|
||||||
|
AddHelpers []Helper
|
||||||
|
RemoveHelpers []string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cs *ChangeSet) Empty() bool {
|
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 {
|
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)
|
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()
|
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
|
// each chain, replace the middle, and insert the new rules before the first kept
|
||||||
// suffix rule (or append when there is none).
|
// suffix rule (or append when there is none).
|
||||||
func computeDiff(current, desired *FirewallState) *ChangeSet {
|
func computeDiff(current, desired *FirewallState) *ChangeSet {
|
||||||
cs := &ChangeSet{}
|
cs := diffHelpers(current, desired)
|
||||||
|
|
||||||
chains := make([]string, 0, len(current.Rules)+len(desired.Rules))
|
chains := make([]string, 0, len(current.Rules)+len(desired.Rules))
|
||||||
for c := range current.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,
|
// restoreChangeSet replaces every managed rule in current with the snapshot's,
|
||||||
// in snapshot order, so a restore cannot reorder rules.
|
// in snapshot order, so a restore cannot reorder rules.
|
||||||
func restoreChangeSet(current, snap *FirewallState) *ChangeSet {
|
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 _, rules := range current.Rules {
|
||||||
for _, r := range rules {
|
for _, r := range rules {
|
||||||
if r.Tag != "" {
|
if r.Tag != "" {
|
||||||
@@ -131,3 +150,29 @@ func restoreChangeSet(current, snap *FirewallState) *ChangeSet {
|
|||||||
}
|
}
|
||||||
return cs
|
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"
|
"testing"
|
||||||
|
|
||||||
"github.com/google/nftables/expr"
|
"github.com/google/nftables/expr"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestRestoreChangeSet(t *testing.T) {
|
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))
|
t.Errorf("expected 1 remove 0 add, got %d/%d", len(cs.Remove), len(cs.Add))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDiffHelpers(t *testing.T) {
|
||||||
|
h := func(name, typ string, l3 uint16, l4 uint8) Helper {
|
||||||
|
return Helper{Name: name, Helper: expr.CtHelper{Name: typ, L3Proto: l3, L4Proto: l4}}
|
||||||
|
}
|
||||||
|
ftp := h("ftp", "ftp", unix.NFPROTO_INET, unix.IPPROTO_TCP)
|
||||||
|
tftp := h("tftp", "tftp", unix.NFPROTO_INET, unix.IPPROTO_UDP)
|
||||||
|
sipUDP := h("sip", "sip", unix.NFPROTO_INET, unix.IPPROTO_UDP)
|
||||||
|
sipTCP := h("sip", "sip", unix.NFPROTO_INET, unix.IPPROTO_TCP)
|
||||||
|
|
||||||
|
current := &FirewallState{Helpers: []Helper{tftp, ftp, sipUDP}}
|
||||||
|
desired := &FirewallState{Helpers: []Helper{ftp, sipTCP}}
|
||||||
|
|
||||||
|
cs := computeDiff(current, desired)
|
||||||
|
if !reflect.DeepEqual(cs.RemoveHelpers, []string{"tftp", "sip"}) {
|
||||||
|
t.Errorf("remove = %v", cs.RemoveHelpers)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(cs.AddHelpers, []Helper{sipTCP}) {
|
||||||
|
t.Errorf("add = %v", cs.AddHelpers)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore recreates every helper so kernel listing order matches the snapshot.
|
||||||
|
cs = restoreChangeSet(desired, current)
|
||||||
|
if !reflect.DeepEqual(cs.RemoveHelpers, []string{"ftp", "sip"}) || !reflect.DeepEqual(cs.AddHelpers, current.Helpers) {
|
||||||
|
t.Errorf("restore = -%v +%v", cs.RemoveHelpers, cs.AddHelpers)
|
||||||
|
}
|
||||||
|
|
||||||
|
live := &FirewallState{Helpers: []Helper{h("pptp", "pptp", unix.NFPROTO_IPV4, unix.IPPROTO_TCP)}}
|
||||||
|
want := &FirewallState{Helpers: []Helper{h("pptp", "pptp", unix.NFPROTO_INET, unix.IPPROTO_TCP)}}
|
||||||
|
if cs := computeDiff(live, want); !cs.Empty() {
|
||||||
|
t.Errorf("kernel-narrowed l3proto should not diff: %+v", cs)
|
||||||
|
}
|
||||||
|
if cs := computeDiff(desired, desired); !cs.Empty() {
|
||||||
|
t.Errorf("identical helpers should be empty: %+v", cs)
|
||||||
|
}
|
||||||
|
if cs := computeDiff(&FirewallState{}, desired); cs.Empty() {
|
||||||
|
t.Error("missing helpers should not be empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/google/nftables"
|
"github.com/google/nftables"
|
||||||
|
"github.com/google/nftables/expr"
|
||||||
|
|
||||||
"git.unkin.net/unkin/tomswall/internal/config"
|
"git.unkin.net/unkin/tomswall/internal/config"
|
||||||
)
|
)
|
||||||
@@ -69,6 +70,36 @@ func (e *Engine) ensureChains(table *nftables.Table, policies map[string]nftable
|
|||||||
Hooknum: nftables.ChainHookPrerouting,
|
Hooknum: nftables.ChainHookPrerouting,
|
||||||
Priority: nftables.ChainPriorityNATDest,
|
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 {
|
for name, chain := range chains {
|
||||||
@@ -112,6 +143,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 {
|
for _, r := range changes.Add {
|
||||||
chain, ok := chains[r.Chain]
|
chain, ok := chains[r.Chain]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -172,6 +210,18 @@ func (e *Engine) readCurrentState() (*FirewallState, error) {
|
|||||||
return state, err
|
return state, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
objs, err := e.conn.GetNamedObjects(ourTable)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("listing objects: %w", err)
|
||||||
|
}
|
||||||
|
for _, o := range objs {
|
||||||
|
if no, ok := o.(*nftables.NamedObj); ok && no.Type == nftables.ObjTypeCtHelper {
|
||||||
|
if h, ok := no.Obj.(*expr.CtHelper); ok {
|
||||||
|
state.Helpers = append(state.Helpers, Helper{Name: no.Name, Helper: *h})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
chains, err := e.conn.ListChainsOfTableFamily(nftables.TableFamilyINet)
|
chains, err := e.conn.ListChainsOfTableFamily(nftables.TableFamilyINet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("listing chains: %w", err)
|
return nil, fmt.Errorf("listing chains: %w", err)
|
||||||
@@ -205,6 +255,7 @@ type Snapshot struct {
|
|||||||
Present bool `json:"present"`
|
Present bool `json:"present"`
|
||||||
Policies map[string]nftables.ChainPolicy `json:"policies,omitempty"`
|
Policies map[string]nftables.ChainPolicy `json:"policies,omitempty"`
|
||||||
Rules map[string][]SnapshotRule `json:"rules,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.
|
// SnapshotRule is a managed rule with its expressions in netlink wire format.
|
||||||
@@ -241,6 +292,7 @@ func (e *Engine) Snapshot() (*Snapshot, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
snap.Helpers = state.Helpers
|
||||||
return snap, nil
|
return snap, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,6 +309,7 @@ func (e *Engine) Restore(s *Snapshot) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
want.Helpers = s.Helpers
|
||||||
current, err := e.readCurrentState()
|
current, err := e.readCurrentState()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -264,6 +317,10 @@ func (e *Engine) Restore(s *Snapshot) error {
|
|||||||
return e.apply(restoreChangeSet(current, want), s.Policies)
|
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 {
|
func policyPtr(p nftables.ChainPolicy) *nftables.ChainPolicy {
|
||||||
return &p
|
return &p
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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}
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -191,13 +191,12 @@ snat:
|
|||||||
# conntrack:
|
# conntrack:
|
||||||
# - action: notrack
|
# - action: notrack
|
||||||
# source: net
|
# source: net
|
||||||
# dest: fw
|
# dest: fw:203.0.113.1
|
||||||
# proto: udp
|
# proto: udp
|
||||||
# dport: [53]
|
# dport: [53]
|
||||||
# comment: "Skip conntrack for DNS"
|
# comment: "Skip conntrack for DNS"
|
||||||
# - action: helper
|
# - action: helper
|
||||||
# source: loc
|
# source: loc
|
||||||
# dest: net
|
|
||||||
# proto: tcp
|
# proto: tcp
|
||||||
# dport: [21]
|
# dport: [21]
|
||||||
# helper: ftp
|
# helper: ftp
|
||||||
|
|||||||
Reference in New Issue
Block a user