Read a ufw rule's direction: an outgoing rule answers no opening, and incoming is the default ufw merges on (hq ADR 0103)

This commit is contained in:
2026-09-22 19:51:35 +02:00
parent dc861fb4a8
commit d3f2595968
4 changed files with 92 additions and 10 deletions
+17 -2
View File
@@ -479,7 +479,10 @@ func words(rule string) []string {
type ufwRule struct {
route bool
action, in, out string
log string
// dir is which way the rule matches: "" (ufw's default, incoming and forwarded), "in" or
// "out". A rule on the outgoing path admits nothing that arrives.
dir string
log string
from, fromPort, to string
port, proto, app string
comment string
@@ -529,6 +532,7 @@ func parseRule(rule string) (ufwRule, bool) {
iface = w[i+1]
i += 2
}
r.dir = dir
if dir == "in" {
r.in = iface
} else {
@@ -586,6 +590,12 @@ func parseRule(rule string) (ufwRule, bool) {
if r.proto == "any" {
r.proto = ""
}
// Incoming is ufw's default direction, and it prints `allow in 9005/tcp` back as
// `allow 9005/tcp` and merges the two — captured in testdata/ufw-direction.txt. An outgoing
// rule is its own rule and stays one.
if r.dir == "in" && r.in == "" {
r.dir = ""
}
return r, true
}
@@ -616,10 +626,15 @@ func (r ufwRule) sameAs(o ufwRule) bool {
// protocol — and on any interface, or the private network's for an opening from it.
func (r ufwRule) admits(o *declaration.Opening) bool {
want, ok := parseRule(strings.Join(Rule(o), " "))
if !ok || r.route != want.route || r.action != "allow" || r.out != "" || r.app != "" ||
if !ok || r.route != want.route || r.action != "allow" || r.app != "" ||
r.from != "any" || r.fromPort != "" || r.to != "any" {
return false
}
// A rule on the outgoing path lets this machine reach others; it admits nothing that arrives,
// so it never answers an opening.
if r.dir == "out" || r.out != "" {
return false
}
if r.proto != "" && r.proto != want.proto {
return false
}