firewall

package module
v0.0.0-...-9a713f4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 35 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-firewall

Go Reference

A Go module that presents a single, uniform interface over the many firewall managers found across operating systems. You describe rules with one platform‑agnostic Rule struct and the module translates them to whatever backend is actually running on the host.

Reference documentation: https://pkg.go.dev/github.com/grmrgecko/go-firewall

import "github.com/grmrgecko/go-firewall"

Supported backends

Platform Backends
Linux firewalld → ufw → CSF → APF → iptables → nftables
macOS pf (Packet Filter)
FreeBSD pf (Packet Filter)
Windows Windows Filtering Platform (WFP)

Usage

package main

import (
	"context"
	"log"

	"github.com/grmrgecko/go-firewall"
)

func main() {
	ctx := context.Background()

	// Detect and connect to the host's firewall. The rule prefix tags/namespaces
	// rules this module creates.
	mgr, err := firewall.NewManager(ctx, "myapp")
	if err != nil {
		log.Fatal(err)
	}
	defer mgr.Close(ctx)

	// Resolve the zone for an interface (empty for backends without zones).
	zone, err := mgr.GetZone(ctx, "eth0")
	if err != nil {
		log.Fatal(err)
	}

	// Allow inbound TCP 443 from a subnet, logged and rate-limited.
	rule := &firewall.Rule{
		Family:    firewall.IPv4,
		Source:    "192.168.0.0/24",
		Port:      443,
		Proto:     firewall.TCP,
		Action:    firewall.Accept,
		Log:       true,
		LogPrefix: "https",
		RateLimit: &firewall.RateLimit{Rate: 20, Unit: firewall.PerSecond, Burst: 10},
	}

	if err := mgr.AddRule(ctx, zone, rule); err != nil {
		log.Fatal(err)
	}

	// Forward inbound TCP 8080 to an internal host (a NAT rule).
	nat := &firewall.NATRule{
		Kind:      firewall.DNAT,
		Family:    firewall.IPv4,
		Proto:     firewall.TCP,
		Port:      8080,
		ToAddress: "10.0.0.5",
		ToPort:    80,
	}
	if err := mgr.AddNATRule(ctx, zone, nat); err != nil {
		log.Fatal(err)
	}

	// Some backends stage changes; Reload activates them (a no-op where
	// changes apply immediately).
	if err := mgr.Reload(ctx); err != nil {
		log.Fatal(err)
	}
}

CLI

cmd/go-firewall is a unified firewall management CLI and implementation demo for the library. It auto-detects the host's active backend and exposes the same surface across all of them. Build it from the repo root:

make cli                  # builds ./build/go-firewall
make install              # installs into $GOBIN

Managing rules needs appropriate privileges (root/Administrator), and the CLI never modifies the host unless you run a mutating subcommand.

go-firewall status                                    # backend + capabilities
go-firewall rule list                                 # all filter rules (PREFIX column flags ours)
go-firewall rule add --proto tcp --port 443 --source 192.168.0.0/24 --log
go-firewall rule add --proto tcp --ports 80,443,1000-2000 --comment "web"
go-firewall rule remove --proto tcp --port 443
go-firewall rule insert 1 --proto tcp --port 22       # 1-based position
go-firewall nat add --kind dnat --proto tcp --port 8080 --to-address 10.0.0.5 --to-port 80
go-firewall nat insert 1 --kind dnat --proto tcp --port 8080 --to-address 10.0.0.5 --to-port 80
go-firewall nat add --kind masquerade
go-firewall policy get
go-firewall policy set --input drop --forward drop
go-firewall set create blocklist --family ipv4 --type hash:net
go-firewall set add-entry blocklist 203.0.113.0/24
go-firewall set show blocklist                        # metadata + every entry
go-firewall backup -o snapshot.json                   # portable JSON snapshot (rules, NAT, policy, sets)
go-firewall restore -f snapshot.json                  # replay the snapshot
go-firewall zone eth0
go-firewall reload
go-firewall install-completions                       # bash/zsh/fish completion

Global flags: --prefix (rule namespace; default go_firewall), --no-reload (skip the automatic reload after a mutation), -j/--json (machine-readable output — list, status, and a {"status":...} object on mutations), --version. A rule's flags are identical across add, remove, insert and move, so the flag set that creates a rule is also its match key for removal. Run go-firewall <command> --help for the full flag reference.

The Rule type

Field Meaning
Direction DirInput (default), DirOutput, DirForward, or DirAny — the input, output, forward (routing) chain, or both input and output. See Capabilities().Forward and the multi-state note below.
Priority Rule priority, where the backend supports it (e.g. firewalld rich rules).
Family FamilyAny, IPv4, or IPv6.
Source Source address/CIDR. Prefix with ! to negate, where supported.
Destination Destination address/CIDR. Prefix with ! to negate, where supported.
Port Single destination port. A non-zero port requires a port-carrying proto (TCP, UDP, TCPUDP, SCTP).
Ports Destination port list/ranges ([]PortRange). Overrides Port when non-empty.
Proto ProtocolAny, TCP, UDP, TCPUDP, ICMP, ICMPv6, SCTP, GRE, ESP, or AH. TCPUDP matches both transports; ProtocolAny matches every IP protocol and cannot carry a port.
ICMPType Optional single ICMP type for an ICMP/ICMPv6 rule (*uint8, nil = any type).
State Connection-tracking states to match, OR-combined (e.g. StateEstablished|StateRelated).
InInterface Inbound interface to match. Empty means any interface. A forward rule may match this alongside OutInterface.
OutInterface Outbound interface to match. Empty means any interface. A forward rule may match this alongside InInterface.
Action Accept, Reject, or Drop.
Log Log each matched packet before applying Action.
LogPrefix Optional label on the log line (not all backends carry a prefix; pf ignores it).
RateLimit *RateLimit (Rate/Unit/Burst) — cap the packet rate the rule matches. nil = unlimited.
ConnLimit *ConnLimit (Count/PerSource) — cap concurrent connections. nil = unlimited.
Packets Per-rule packet counter, populated by GetRules on backends that read them (nftables, iptables, pf). Zero elsewhere and ignored when adding a rule.
Bytes Per-rule byte counter, populated alongside Packets. Not part of rule identity.
Comment Optional human-readable label carried where the backend can store one. Informational: not part of rule identity, ignored where unsupported. See Capabilities().Comments.
HasPrefix Informational flag reporting whether the rule carries the configured prefix.

Capabilities().Output reports whether a backend distinguishes input from output (firewalld, for example, does not), and Capabilities().Forward reports whether it can express a forward-chain (routing) rule. A DirForward rule on a backend without forward support is rejected with ErrUnsupportedForward.

Multi-state rules and coverage

Three values each describe a rule spanning both values of one axis:

  • FamilyAny — both IPv4 and IPv6.
  • TCPUDP — both TCP and UDP; it carries a port just as TCP or UDP does. It is not ProtocolAny, which matches every IP protocol (ICMP, GRE, ESP, …).
  • DirAny — both the input and output directions (never forward). A DirAny rule is authored in the inbound frame, and its outbound half is the role swap: Source↔Destination, source↔destination ports, and InInterface↔OutInterface. So DirAny with Source: X matches inbound traffic from X and outbound traffic to X.

Whether such a rule becomes one object in the firewall or several depends entirely on the backend's own model:

  • On add, the rule is split only on the axes the backend cannot express. nftables stores a FamilyAny + TCPUDP rule as a single row; iptables must write a line per family, per transport and per chain, so a rule spanning all three axes becomes eight lines.
  • On read, GetRules reports the firewall's actual rows. It reports a multi-state value only for an entry that genuinely carries both values and never fabricates one by pairing up separately-stored rows, so that same rule reads back as one rule from nftables and as eight from iptables.
  • On remove, a target clears every row it covers. Where a stored row covers more than the target, the backend deletes it and re-adds the remainder in its place so the untargeted coverage survives; where its model cannot express the remainder, it returns ErrUnsupported rather than over-removing.
  • Where an axis does not exist at all — Capabilities().Output is false, as on firewalld — a DirAny rule degrades to its input half (DirInput, same fields) rather than being rejected.

Because the read-back shape is backend-specific, a caller cannot check for a rule with ==. Covers and CoveredBy express the relation directly, and are the supported way to test a multi-state rule against what the firewall actually holds:

// Does this one rule contain that one?
want := &fw.Rule{Family: fw.FamilyAny, Proto: fw.TCPUDP, Direction: fw.DirAny, Port: 53, Action: fw.Accept}
want.Covers(&fw.Rule{Family: fw.IPv4, Proto: fw.UDP, Direction: fw.DirInput, Port: 53, Action: fw.Accept}) // true

// Is this rule fully present across a set — even if no single rule contains it?
existing, _ := mgr.GetRules(ctx, "")
if !want.CoveredBy(existing) {
    _ = mgr.AddRule(ctx, "", want)
}

Covers is asymmetric: a TCPUDP rule covers its TCP half, never the reverse. CoveredBy is its set-valued inverse — it expands the receiver across all three axes and requires every resulting cell to be covered by some rule in the set. That is what makes it work against a fan-out backend, where no single stored row covers the rule but the rows together do, and why a rule spanning both transports is not reported present when only its TCP half is. NATRule.Covers and NATRule.CoveredBy mirror them over family, the only axis a NAT rule spans. Sync compares this way, which is why it stays a no-op against its own output whichever representation the backend chose.

NAT (port forwarding and masquerade)

NAT rules are managed separately from filter rules through AddNATRule/RemoveNATRule/GetNATRules, using the NATRule type.

Field Meaning
Kind DNAT, Redirect, SNAT, or Masquerade.
Family FamilyAny, IPv4, or IPv6.
Proto Protocol to match (TCP, UDP, etc.).
Port Matched destination port (Ports for a list/range). Requires a tcp/udp protocol.
ToAddress Rewrite target address: new destination for DNAT, new source for SNAT.
ToPort Rewrite target port (DNAT/Redirect). Unused for SNAT/Masquerade.
Interface Inbound interface for DNAT/Redirect; outbound for SNAT/Masquerade.
HasPrefix Informational flag, same semantics as Rule.HasPrefix.

DNAT forwards inbound traffic to ToAddress:ToPort. Redirect sends matching traffic to a local ToPort. SNAT rewrites the source to a fixed address, and Masquerade uses the outgoing interface address. Backends that cannot express NAT return ErrUnsupportedNAT.

Capabilities

mgr.Capabilities() returns a Capabilities struct advertising which features the active backend can express, so a caller can branch before trial-and-error:

caps := mgr.Capabilities()
if !caps.NAT {
    log.Println("this backend cannot do NAT")
}
if caps.RuleCounters {
    // rules read back will carry Packets/Bytes
}

Every boolean corresponds to a Rule/NATRule field or an interface method. A false field means the corresponding operation returns an unsupported error, except RuleCounters and Comments, where it means GetRules reports the value empty. Features every backend supports are not advertised as booleans. The matrix below documents each backend's coverage, booleans and unconditional features alike.

Feature firewalld ufw CSF APF iptables nftables pf WFP
Forward rules no yes yes yes yes yes no no
IPv6 yes yes yes yes yes yes yes yes
ICMP yes yes yes yes yes yes yes yes
ICMP type yes yes yes yes yes yes yes yes
SCTP/GRE/ESP/AH yes yes yes yes yes yes yes partial (no SCTP port)
Comment no yes yes yes yes yes yes yes
Port range yes yes yes yes yes yes yes yes
Port list no yes yes yes yes yes yes yes
Source port partial (not with a destination port) yes yes yes yes yes yes yes
Connection state no yes yes yes yes yes no no
Interface match no yes yes yes yes yes yes no
Logging yes yes yes yes yes yes partial (no prefix) no
Rate limit yes yes yes yes yes yes partial (per-source) no
Connection limit no yes yes yes yes yes partial (per-source) no
NAT partial (forward-port and masquerade only) yes yes yes yes yes partial (no redirect) no

A yes means the feature is fully expressible, whatever route the backend takes to get there: firewalld reaches several through a rich rule, ufw through its route ruleset, and CSF and APF write the shapes their own config files cannot hold through their managed pre-hook. A partial cell means the backend can only express the narrowed form named beside it. Two of the no cells have a backend-specific reason: firewalld binds interfaces to zones rather than matching them per rule, and pf keeps state on a pass rule automatically but exposes no equivalent of the connection-state match this model carries.

Capabilities().DenyActionFromConfig (true for CSF and APF) flags a backend whose native deny store carries no per-entry action: the tool applies the action its own config names (csf.conf DROP, conf.apf ALL_STOP), so a deny added with the config's action is stored natively, one with a differing action is expressed through the backend's pre-hook, and RemoveRule clears a native deny entry whatever action the removal target names.

The IPv6 row above is the one capability resolved per host rather than per backend, and it covers every IPv6 rule shape, ICMPv6 included. CSF and APF report it false when their own config disables IPv6 (csf.conf IPV6, conf.apf USE_IPV6), since neither tool then keeps an IPv6 ruleset in sync. iptables reports it false on a host whose packaging ships no ip6tables save file — a system built without IPv6, or one that never installed the ip6tables package — and manages IPv4 alone: reads report IPv4 rows only, a FamilyAny write narrows to the IPv4 file, a concrete-IPv6 write returns ErrUnsupported, and a removal is a no-op (there is nothing IPv6 to remove).

Default policy

GetDefaultPolicy/SetDefaultPolicy read and set the default action applied to packets that match no rule. A DefaultPolicy carries an Action per direction (Input, Output, Forward); a direction left as ActionInvalid is not exposed (on Get) or left unchanged (on Set). On a backend that supports it, the policy is captured in a Backup and re-asserted by Restore, so a snapshot of a default-drop host reproduces that policy on replay rather than inheriting the restore host's.

Backend Directions supported
iptables input, output, forward
ufw input, output, forward
nftables input, output, forward
firewalld input (the zone target)
others unsupported (ErrUnsupportedPolicy)

Address sets (ipset / nftset / pf tables)

Address sets are named collections of addresses (AddressSet) that rules can match against, managed separately from filter and NAT rules. A Backup captures the managed sets (with their entries) and Restore recreates them before the rules, so a set-referencing rule (@set) resolves when a snapshot is replayed on a host that does not yet have the set. They map onto the backend's native construct:

Backend Construct
iptables ipset (hash:ip, hash:net)
ufw ipset (via the host iptables)
nftables a set in the private inet table
firewalld a firewalld ipset (D-Bus)
pf a pf table
CSF/APF ipset commands in the managed pre-hook
WFP unsupported (ErrUnsupportedSet)
set := &firewall.AddressSet{Name: "blocklist", Family: firewall.IPv4, Type: firewall.SetHashNet}
_ = mgr.AddAddressSet(ctx, set)
_ = mgr.AddAddressSetEntry(ctx, "blocklist", "203.0.113.0/24")
sets, _ := mgr.GetAddressSets(ctx)

Testing

The Makefile drives every test path; run these from the repo root.

make test-general              # unit/parser tests — fast, no root, no VM
make test-integration-linux    # Linux backends end-to-end in a throwaway QEMU VM
make test-integration-freebsd  # pf end-to-end in a throwaway FreeBSD VM
make test-integration-windows  # Windows Firewall end-to-end in a throwaway Windows VM
make test-integration          # all three integration suites
make test                      # test-general plus every integration suite
make lint                      # golangci-lint across every target GOOS

make test-general is the plain go test ./... suite — rule encoding/decoding, capability and helper logic. It never touches a live firewall and needs no root, so it is the one to run while iterating.

The test-integration* targets boot disposable QEMU VMs and run the capability-driven suite against the real backends inside them, so nothing on the host is modified. Backend detection and rule application need the corresponding firewall installed and running, which is what the VMs provide. Limit the Linux run to particular backends with BACKENDS:

BACKENDS="nft firewalld ufw iptables apf csf" make test-integration-linux

They require qemu-system-x86_64, KVM (/dev/kvm), genisoimage, and python3 for the FreeBSD image. VM artifacts are cached under ./.cache; make clean removes that cache and the compiled test binaries.

macOS cannot be automated in a VM, so run its pf backend manually on a Mac:

sudo go test -tags integration -run TestIntegration

Documentation

Index

Constants

View Source
const (
	APFConf  = "/etc/apf/conf.apf"
	APFAllow = "/etc/apf/allow_hosts.rules"
	APFDeny  = "/etc/apf/deny_hosts.rules"
	// APFPreroute and APFPostroute are apf's user routing-rule files, sourced as
	// shell during a (re)start. Like the pre-hook below, this backend uses them as a
	// raw-iptables fallback for rules apf's native config and allow/deny files cannot
	// express — here the routing-stage cases, which in practice are NAT: destination
	// NAT (DNAT/Redirect) is written into preroute.rules and source NAT
	// (SNAT/Masquerade) into postroute.rules.
	APFPreroute  = "/etc/apf/preroute.rules"
	APFPostroute = "/etc/apf/postroute.rules"
	// APFHook is apf's pre-hook, run after the flush but before apf adds its own
	// rules. This library writes the iptables rules for features apf's native
	// config cannot express directly into this hook.
	APFHook = "/etc/apf/hook_pre.sh"
)
View Source
const (
	CSFConf  = "/etc/csf/csf.conf"
	CSFAllow = "/etc/csf/csf.allow"
	CSFDeny  = "/etc/csf/csf.deny"
	// CSFRedirect holds csf's port-forwarding rules, one per line in the
	// pipe-delimited form "IPx|portA|IPy|portB|proto". A destination IP (IPy) of
	// "*" is a local port redirect; a concrete IPy is a forward to another host.
	CSFRedirect = "/etc/csf/csf.redirect"
	// CSFHook is the csf pre-hook, run after csf flushes and before it loads its
	// own rules, so injected rules land at the top of the chains and are re-added
	// on every reload. This library writes the iptables rules for features csf's
	// native config cannot express directly into this hook. (csf sources both
	// /usr/local/csf/bin/csfpre.sh and /etc/csf/csfpre.sh when present, so this
	// /etc/csf hook always runs.)
	CSFHook = "/etc/csf/csfpre.sh"
)
View Source
const (
	IPTablesType  = "iptables"
	NFTType       = "nftables"
	UFWType       = "ufw"
	FirewallDType = "firewalld"
	CSFType       = "csf"
	APFType       = "apf"
	PFType        = "pf"
	WFType        = "windows-firewall"
)

The backend type strings Manager.Type reports, one per backend. They are declared here beside the interface rather than beside each implementation because every backend lives behind a build tag for its own platform: a caller — or a test — that branches on mgr.Type() must be able to name any backend on any platform, not only the ones that compile for the host.

View Source
const (
	// IPTablesNoSave is the error text returned when no iptables save path is found.
	IPTablesNoSave = "unable to find iptables save path"
	// IPTablesNoService is the error text returned when no iptables service is found.
	IPTablesNoService = "unable to find iptables service"
)
View Source
const (
	// UFWIPv4 is ufw's IPv4 user-rules file.
	UFWIPv4 = "/etc/ufw/user.rules"
	// UFWIPv6 is ufw's IPv6 user-rules file.
	UFWIPv6 = "/etc/ufw/user6.rules"
	// UFWConf is ufw's main configuration file (ENABLED/LOGLEVEL).
	UFWConf = "/etc/ufw/ufw.conf"
	// UFWDefaults is ufw's defaults file, where the default-policy keys
	// (DEFAULT_INPUT_POLICY, ...) actually live — not ufw.conf.
	UFWDefaults = "/etc/default/ufw"
	// UFWBefore and its peers are the iptables rules files holding rules that run
	// before/after the user rules, in iptables-restore format with ufw's own
	// chains. They are the raw-iptables fallback for what ufw's tuple format
	// cannot express — ICMP, SCTP, state matches, custom log prefixes,
	// rate/connection limits, and NAT (written into before.rules' nat table via
	// natHelper).
	UFWBefore  = "/etc/ufw/before.rules"
	UFWBefore6 = "/etc/ufw/before6.rules"
	UFWAfter   = "/etc/ufw/after.rules"
	UFWAfter6  = "/etc/ufw/after6.rules"
)
View Source
const (
	// NFTDefaultTable is the table name used when no rule prefix is supplied.
	NFTDefaultTable = "go_firewall"
)

Variables

View Source
var (
	// ErrUnsupported is the common ancestor of every unsupported-feature error.
	// errors.Is returns true for any of the more specific sentinels below.
	ErrUnsupported = errors.New("feature unsupported by this firewall backend")
	// ErrUnsupportedNAT is returned when a backend cannot express NAT.
	ErrUnsupportedNAT = fmt.Errorf("%w: NAT", ErrUnsupported)
	// ErrUnsupportedOrdering is returned by backends whose rule model is not
	// ordered, for InsertRule/MoveRule.
	ErrUnsupportedOrdering = fmt.Errorf("%w: explicit rule ordering", ErrUnsupported)
	// ErrUnsupportedPolicy is returned when a backend cannot read or set a
	// default policy.
	ErrUnsupportedPolicy = fmt.Errorf("%w: default-policy management", ErrUnsupported)
	// ErrUnsupportedSet is returned when a backend cannot manage address sets
	// (ipset/nftset/tables).
	ErrUnsupportedSet = fmt.Errorf("%w: address sets", ErrUnsupported)
	// ErrUnsupportedLog is returned when per-rule logging cannot be expressed.
	ErrUnsupportedLog = fmt.Errorf("%w: per-rule logging", ErrUnsupported)
	// ErrUnsupportedRateLimit is returned when rate limiting cannot be expressed.
	ErrUnsupportedRateLimit = fmt.Errorf("%w: rate limiting", ErrUnsupported)
	// ErrUnsupportedConnLimit is returned when connection limiting cannot be
	// expressed.
	ErrUnsupportedConnLimit = fmt.Errorf("%w: connection limiting", ErrUnsupported)
	// ErrUnsupportedState is returned when connection-state matching cannot be
	// expressed.
	ErrUnsupportedState = fmt.Errorf("%w: connection-state matching", ErrUnsupported)
	// ErrUnsupportedInterface is returned when per-rule interface matching
	// cannot be expressed.
	ErrUnsupportedInterface = fmt.Errorf("%w: per-rule interface matching", ErrUnsupported)
	// ErrUnsupportedSourcePort is returned when source-port matching cannot be
	// expressed.
	ErrUnsupportedSourcePort = fmt.Errorf("%w: source-port matching", ErrUnsupported)
	// ErrUnsupportedForward is returned when a backend cannot express a rule in
	// the forward (routing) chain.
	ErrUnsupportedForward = fmt.Errorf("%w: forward-chain rules", ErrUnsupported)
	// ErrForeignTable is returned by RemoveRule and RemoveNATRule when the target
	// matches no rule in the backend's own table or anchor but does match a rule
	// GetRules or GetNATRules reports from another one (a foreign nftables table,
	// the pf main ruleset or another pf anchor). The backend writes only to its
	// own, so the rule is still in place. Sync skips such a rule instead of failing
	// or counting it as removed.
	ErrForeignTable = errors.New("rule is outside this backend's own table or anchor")
)

Sentinel errors a caller can match with errors.Is to tell apart a genuine failure from a feature the active backend cannot express. The helpers below (unsupportedNAT, unsupportedOrdering, ...) wrap these, and per-backend marshal paths use fmt.Errorf("...: %w", err) so the message stays readable while the sentinel is preserved for programmatic handling.

Functions

func FormatPortRanges

func FormatPortRanges(prs []PortRange, sep string) string

FormatPortRanges renders a slice of ranges as a separated list.

func ParseICMPType

func ParseICMPType(tok string, v6 bool) (uint8, bool)

ParseICMPType parses an ICMP type token as either a number (0-255) or a well-known type name, resolving names through the ICMPv6 table when v6 is true (the same name maps to a different number under ICMPv6 — e.g. echo-request is 8 for ICMPv4 but 128 for ICMPv6). It is the exported form of the resolution the backends use internally, so a caller or CLI authoring a rule by name accepts exactly the spellings the library itself emits and reads back.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to v. It is a convenience for setting optional rule fields such as ICMPType, e.g. firewall.Ptr[uint8](8).

func RestoreReader

func RestoreReader(ctx context.Context, mgr Manager, zoneName string, r io.Reader) error

RestoreReader reads a backup from r and applies it via mgr.Restore. It is the streaming counterpart of Manager.Restore: a caller can replay a backup straight from a file or network reader without first buffering it into a *Backup. A read error is returned before any rules are touched.

f, _ := os.Open("backup.json")
_ = firewall.RestoreReader(ctx, mgr, zone, f)

func Sync

func Sync(ctx context.Context, mgr Manager, zoneName string, desired []*Rule) (added, removed int, err error)

Sync reconciles the zone's filter rules toward desired: it removes any rule the backend reports that desired does not cover and adds desired rules that are not yet present, leaving rules already in place untouched. It reconciles the actual firewall state and does not filter on HasPrefix — a rule without the configured prefix (HasPrefix=false) is reconciled like any other, so a foreign rule not in desired is removed. A rule unchanged between existing and desired is never removed and re-added, but removal still runs as its own pass before additions, so a desired set that shares nothing with the existing rules is not applied atomically. Sync reports how many rules were added and removed.

The diff is a coverage relation, not rule-for-rule equality, because GetRules reports the firewall's actual rows and a backend stores a rule the way its model allows: iptables holds a FamilyAny rule as an IPv4 row plus an IPv6 row, pf holds a DirAny rule as an inbound row plus an outbound row, while nftables holds either as one row. An existing rule is kept when every concrete cell it spans is wanted (Rule.CoveredBy over desired), and a desired rule is added when some cell it spans is not yet present (its CoveredBy over existing). On a backend that does not manage IPv6 (Capabilities.IPv6 false) a family-agnostic rule is compared on its IPv4 half alone, since that is all such a backend stores for it. Comparing this way keeps Sync a no-op against its own output whichever representation the backend chose, where plain equality would remove-and-re-add every fanned-out rule on each run. A rule only partially covered by desired is removed whole and the wanted part re-added. The Comment, HasPrefix and Packets/Bytes fields never affect the diff.

func WriteBackup

func WriteBackup(w io.Writer, backup *Backup) error

WriteBackup encodes backup as JSON to w so it can be persisted to disk (or moved to another host) and later replayed with ReadBackup or RestoreReader.

The encoding is portable: enum fields are written as their stable string names, so a backup survives a reordering of the library's iota constants and is readable on a host running a different version of the library. Per-rule counters (Packets/Bytes) are carried through for the record but are ignored when a backup is restored (they are not part of rule identity).

f, _ := os.Create("backup.json")
_ = firewall.WriteBackup(f, backup)

Types

type APF

type APF struct {
	ConfigChanged bool
	// contains filtered or unexported fields
}

APF manages the firewall through apf's config files and a managed pre-hook.

func NewAPF

func NewAPF(ctx context.Context, rulePrefix string) (*APF, error)

NewAPF verifies apf is installed and active, then returns a manager bound to rulePrefix.

func (*APF) AddAddressSet

func (f *APF) AddAddressSet(ctx context.Context, set *AddressSet) error

AddAddressSet writes a set as ipset commands in the pre-hook; apf --restart (Reload) sources the hook to create the set. Re-adding a set is idempotent.

func (*APF) AddAddressSetEntry

func (f *APF) AddAddressSetEntry(ctx context.Context, name, entry string) error

AddAddressSetEntry adds an entry to an existing set in the pre-hook.

func (*APF) AddNATRule

func (f *APF) AddNATRule(ctx context.Context, zoneName string, r *NATRule) error

AddNATRule adds a NAT rule to apf's preroute or postroute routing file.

func (*APF) AddRule

func (f *APF) AddRule(ctx context.Context, zoneName string, r *Rule) error

AddRule adds a rule to apf, routing it to conf.apf, the allow/deny lists, or the pre-hook.

func (*APF) Backup

func (f *APF) Backup(ctx context.Context, zoneName string) (*Backup, error)

Backup captures the current filter and NAT rules managed by this backend.

func (*APF) Capabilities

func (f *APF) Capabilities() Capabilities

Capabilities reports the firewall features apf supports.

func (*APF) Close

func (f *APF) Close(ctx context.Context) error

Close releases resources held by the manager; apf holds none.

func (*APF) EditConf

func (f *APF) EditConf(ctx context.Context, r *Rule, remove bool) error

func (*APF) EditIPList

func (f *APF) EditIPList(ctx context.Context, filePath string, action Action, r *Rule, remove bool) error

EditIPList adds or removes a rule in an apf allow_hosts/deny_hosts file, rewriting it in place. An add expands the rule into the rows it materializes into (see listRows), notes which of them the file already holds, and appends only the rest, so a rule that fans out across families is completed rather than duplicated on every reconcile. A removal drops every line the target covers.

func (*APF) EditRulePort

func (f *APF) EditRulePort(orig, key, val string, r *Rule, remove bool) string

EditRulePort returns the conf.apf line with the rule's tokens added to or removed from the list that key manages.

func (*APF) GetAddressSet

func (f *APF) GetAddressSet(ctx context.Context, name string) (*AddressSet, error)

GetAddressSet returns a single address set by name, or an error if absent.

func (*APF) GetAddressSets

func (f *APF) GetAddressSets(ctx context.Context) ([]*AddressSet, error)

GetAddressSets returns the address sets carried by the apf pre-hook.

func (*APF) GetDefaultPolicy

func (f *APF) GetDefaultPolicy(ctx context.Context, zoneName string) (*DefaultPolicy, error)

GetDefaultPolicy is unsupported: apf has no managed default-policy control.

func (*APF) GetNATRules

func (f *APF) GetNATRules(ctx context.Context, zoneName string) ([]*NATRule, error)

GetNATRules returns the NAT rules held in apf's preroute and postroute routing files, parsed through the shared hook mechanism.

func (*APF) GetRules

func (f *APF) GetRules(ctx context.Context, zoneName string) (rules []*Rule, err error)

GetRules returns the current filter rules read from conf.apf, the allow/deny lists, and the pre-hook.

func (*APF) GetZone

func (f *APF) GetZone(ctx context.Context, iface string) (zoneName string, err error)

GetZone returns no zone; apf has no zone support.

func (*APF) InsertNATRule

func (f *APF) InsertNATRule(ctx context.Context, zoneName string, position int, r *NATRule) error

InsertNATRule is unsupported: APF stores NAT in a config file it applies as a whole, with no explicit ordering.

func (*APF) InsertRule

func (f *APF) InsertRule(ctx context.Context, zoneName string, position int, r *Rule) error

InsertRule is unsupported: APF organizes rules in config files, not an ordered list.

func (*APF) MarshalAdvRule

func (f *APF) MarshalAdvRule(r *Rule) string

MarshalAdvRule encodes a rule as an apf advanced allow/deny line: an optional protocol field, a direction, one port-flow field (a source or a destination port) and one address field, joined by ":". It validates nothing; addRule/RemoveRule route every shape the line cannot carry elsewhere first (see needsHook).

func (*APF) MoveNATRule

func (f *APF) MoveNATRule(ctx context.Context, zoneName string, r *NATRule, position int) error

MoveNATRule is unsupported for the same reason as InsertNATRule.

func (*APF) MoveRule

func (f *APF) MoveRule(ctx context.Context, zoneName string, r *Rule, position int) error

MoveRule is unsupported for the same reason as InsertRule.

func (*APF) ParseAdvRule

func (f *APF) ParseAdvRule(val string, action Action) (r *Rule)

ParseAdvRule decodes an apf advanced allow/deny rule of the form proto:flow:s/d=port:s/d=ip. IPv6 addresses use bracket notation.

func (*APF) ParseConnLimit

func (f *APF) ParseConnLimit(val string, proto Protocol) (rules []*Rule)

ParseConnLimit decodes a conf.apf IG_TCP_CLIMIT/IG_UDP_CLIMIT value ("port:limit,...", port may be an underscore range) into connection-limit rules: apf caps concurrent connections per source and rejects the excess, so each entry becomes an inbound reject rule carrying a per-source ConnLimit.

func (*APF) ParseICMPTypes

func (f *APF) ParseICMPTypes(val string, proto Protocol, dir Direction) (rules []*Rule)

ParseICMPTypes decodes an apf ICMP type list (IG_ICMP_TYPES/EG_ICMP_TYPES for proto ICMP, IG_ICMPV6_TYPES/EG_ICMPV6_TYPES for proto ICMPv6) into accept rules, one per type. The "all" wildcard (which apf applies as a typeless `-p icmp -j ACCEPT`) becomes a rule with a nil ICMPType, matching every type.

func (*APF) ParseIPList

func (f *APF) ParseIPList(filePath string, action Action) (rules []*Rule, err error)

ParseIPList reads an apf allow_hosts/deny_hosts file and returns the rules it holds, each carrying any full-line comment that precedes it (see scanCommentGroups for the comment-attachment convention).

func (*APF) ParsePorts

func (f *APF) ParsePorts(val string, proto Protocol, dir Direction) (rules []*Rule)

ParsePorts decodes an apf comma-separated port list into accept rules, one per port entry.

func (*APF) Reload

func (f *APF) Reload(ctx context.Context) error

Reload restarts apf to apply config changes, but only when a mutation changed its files.

func (*APF) RemoveAddressSet

func (f *APF) RemoveAddressSet(ctx context.Context, name string) error

RemoveAddressSet drops a set's ipset commands from the pre-hook. It fails if a hook rule still references the set; removing an absent set is a no-op.

func (*APF) RemoveAddressSetEntry

func (f *APF) RemoveAddressSetEntry(ctx context.Context, name, entry string) error

RemoveAddressSetEntry removes an entry from an existing set in the pre-hook.

func (*APF) RemoveNATRule

func (f *APF) RemoveNATRule(ctx context.Context, zoneName string, r *NATRule) error

RemoveNATRule removes a NAT rule from apf's preroute or postroute routing file.

func (*APF) RemoveRule

func (f *APF) RemoveRule(ctx context.Context, zoneName string, r *Rule) error

RemoveRule removes a rule from apf, routing it to the config file or pre-hook that holds it.

func (*APF) Restore

func (f *APF) Restore(ctx context.Context, zoneName string, backup *Backup) error

Restore replaces the managed rules with the contents of a Backup.

func (*APF) SetDefaultPolicy

func (f *APF) SetDefaultPolicy(ctx context.Context, zoneName string, policy *DefaultPolicy) error

SetDefaultPolicy is unsupported: apf has no managed default-policy control.

func (*APF) Type

func (f *APF) Type() string

Type returns the backend identifier for apf.

type Action

type Action uint8

Action is the firewall action taken on a rule's matching packets.

const (
	// ActionInvalid is the zero value of Action, meaning no action; it is
	// rejected when authoring a rule or policy.
	ActionInvalid Action = iota
	// Accept permits matching packets through.
	Accept
	// Reject refuses matching packets with an error response to the sender.
	Reject
	// Drop silently discards matching packets.
	Drop
)

func ParseAction

func ParseAction(s string) (Action, error)

ParseAction parses a caller-supplied action token (case-insensitive), accepting only the concrete actions Accept, Reject and Drop. The sentinel "invalid" (ActionInvalid) is rejected here so callers cannot author a rule or policy with no real action; backup decoding round-trips it separately in Action.UnmarshalJSON.

func (Action) MarshalJSON

func (a Action) MarshalJSON() ([]byte, error)

MarshalJSON renders the action as its stable name (e.g. "accept").

func (Action) String

func (t Action) String() string

String returns the canonical lower-case name of the action.

func (*Action) UnmarshalJSON

func (a *Action) UnmarshalJSON(data []byte) error

UnmarshalJSON parses an action from its stable name. The sentinel "invalid" (ActionInvalid) is accepted on the wire for round-trip fidelity even though ParseAction rejects it as caller input.

type AddressSet

type AddressSet struct {
	// Name of the set. Backends that namespace sets (nftables table, pf anchor)
	// keep it within their own container.
	Name string
	// Family restricts the set to an IP family. Some backends require a concrete
	// family (nftables inet sets carry a single address type); FamilyAny is
	// resolved to IPv4 by those backends.
	Family Family
	// Type is the entry kind, defaulting to SetHashIP when zero.
	Type SetType
	// Entries are the addresses or CIDRs in the set.
	Entries []string
}

AddressSet is a named collection of addresses (an ipset, an nftables set or a pf table) that rules can match against. It is managed separately from filter and NAT rules through the Manager's address-set methods.

type Backup

type Backup struct {
	// Filter rules saved in the order they were returned by GetRules.
	Rules []*Rule
	// NAT rules saved in the order they were returned by GetNATRules.
	NATRules []*NATRule
	// DefaultPolicy is the per-direction default action captured at backup time,
	// on backends that advertise Capabilities().DefaultPolicy; nil otherwise. A
	// direction the backend does not expose is ActionInvalid and is left unchanged
	// on Restore. Capturing it lets Restore re-assert a restrictive policy (e.g. a
	// default DROP) rather than silently inherit the restore host's current one.
	DefaultPolicy *DefaultPolicy
	// AddressSets are the named address sets (ipsets, nftables sets, pf tables) the
	// backend manages, captured on backends that advertise
	// Capabilities().AddressSets; nil otherwise. Restore recreates them before the
	// filter rules so a set-referencing rule (@set) resolves on a host that does
	// not yet have the set.
	AddressSets []*AddressSet
}

Backup is a portable snapshot of the state a backend manages. It can be used to restore that state later via Manager.Restore.

func ReadBackup

func ReadBackup(r io.Reader) (*Backup, error)

ReadBackup decodes a backup previously written by WriteBackup from r.

f, _ := os.Open("backup.json")
backup, _ := firewall.ReadBackup(f)
_ = mgr.Restore(ctx, zone, backup)

type CSF

type CSF struct {
	// contains filtered or unexported fields
}

CSF manages a ConfigServer Security & Firewall (csf) installation, mapping rules onto its config files (csf.conf, csf.allow, csf.deny, csf.redirect) and a managed pre-hook for features csf's native config cannot express.

func NewCSF

func NewCSF(ctx context.Context, rulePrefix string) (*CSF, error)

NewCSF constructs a CSF manager, verifying the csf service is enabled and its config files are present, and reading whether csf's own IPv6 handling is on.

func (*CSF) AddAddressSet

func (f *CSF) AddAddressSet(ctx context.Context, set *AddressSet) error

AddAddressSet writes a set as ipset commands in the pre-hook; csf -r (Reload) sources the hook to create the set. Re-adding a set is idempotent.

func (*CSF) AddAddressSetEntry

func (f *CSF) AddAddressSetEntry(ctx context.Context, name, entry string) error

AddAddressSetEntry adds an entry to an existing set in the pre-hook.

func (*CSF) AddNATRule

func (f *CSF) AddNATRule(ctx context.Context, zoneName string, r *NATRule) error

AddNATRule adds a NAT rule to csf.redirect, or — for the shapes csf.redirect cannot hold (natNeedsHook) — as a raw nat-table command in the pre-hook.

func (*CSF) AddRule

func (f *CSF) AddRule(ctx context.Context, zoneName string, r *Rule) error

AddRule adds a filter rule to the appropriate csf construct: a csf.conf port list, an advanced rule, a bare address list, CONNLIMIT, or the pre-hook.

func (*CSF) Backup

func (f *CSF) Backup(ctx context.Context, zoneName string) (*Backup, error)

Backup captures the current filter and NAT rules managed by this backend.

func (*CSF) Capabilities

func (f *CSF) Capabilities() Capabilities

Capabilities reports the firewall features csf supports.

func (*CSF) Close

func (f *CSF) Close(ctx context.Context) error

Close releases any resources held by the manager; csf holds none.

func (*CSF) EditConf

func (f *CSF) EditConf(ctx context.Context, r *Rule, remove bool) error

EditConf rewrites csf.conf to add or remove a port-list or CONNLIMIT rule.

func (*CSF) EditIPList

func (f *CSF) EditIPList(ctx context.Context, filePath string, action Action, r *Rule, remove bool) error

EditIPList adds or removes a rule in a csf.allow/csf.deny list, rewriting it in place. An add expands the rule into the rows it materializes into (see listRows), notes which of them the file already holds, and appends only the rest, so a rule that fans out across families or transports is completed rather than duplicated on every reconcile. A removal drops every line the target covers.

func (*CSF) EditRulePort

func (f *CSF) EditRulePort(orig, key, val string, r *Rule, remove bool) string

EditRulePort returns the config line for key with the rule's port added or removed, leaving lines the rule does not apply to unchanged.

func (*CSF) GetAddressSet

func (f *CSF) GetAddressSet(ctx context.Context, name string) (*AddressSet, error)

GetAddressSet returns a single address set by name, or an error if absent.

func (*CSF) GetAddressSets

func (f *CSF) GetAddressSets(ctx context.Context) ([]*AddressSet, error)

GetAddressSets returns the address sets carried by the csf pre-hook.

func (*CSF) GetDefaultPolicy

func (f *CSF) GetDefaultPolicy(ctx context.Context, zoneName string) (*DefaultPolicy, error)

GetDefaultPolicy is unsupported: csf exposes no chain default policy.

func (*CSF) GetNATRules

func (f *CSF) GetNATRules(ctx context.Context, zoneName string) ([]*NATRule, error)

GetNATRules reads the NAT rules from csf.redirect and the raw nat-table commands the pre-hook carries.

func (*CSF) GetRules

func (f *CSF) GetRules(ctx context.Context, zoneName string) (rules []*Rule, err error)

GetRules reads all filter rules from csf's config files and the managed pre-hook, merging family and protocol fan-outs back to their written form.

func (*CSF) GetZone

func (f *CSF) GetZone(ctx context.Context, iface string) (zoneName string, err error)

GetZone reports no zone; csf has no concept of zones.

func (*CSF) InsertNATRule

func (f *CSF) InsertNATRule(ctx context.Context, zoneName string, position int, r *NATRule) error

InsertNATRule is unsupported: CSF stores redirects in a config file it applies as a whole, with no explicit ordering.

func (*CSF) InsertRule

func (f *CSF) InsertRule(ctx context.Context, zoneName string, position int, r *Rule) error

InsertRule is unsupported: CSF organizes rules in config files, not an ordered list.

func (*CSF) MarshalAdvRule

func (f *CSF) MarshalAdvRule(r *Rule) string

MarshalAdvRule encodes a rule as a csf advanced allow/deny line: a protocol token, a direction, one port-flow field (an icmp type, a source port or a destination port) and one address field, joined by "|". It validates nothing; addRule/RemoveRule route every shape the line cannot carry elsewhere first.

func (*CSF) MarshalNATRule

func (f *CSF) MarshalNATRule(r *NATRule) string

MarshalNATRule encodes a NAT rule as a csf.redirect line ("IPx|portA|IPy|portB|proto"): a Redirect to a local port (IPy = "*") or a DNAT forward to another host (IPy = ToAddress). Like MarshalAdvRule it validates nothing and assumes a natively-expressible rule; AddNATRule/RemoveNATRule route every shape csf.redirect cannot hold — source NAT, a non-tcp/udp protocol, a port range or list, a source/interface match, an address-less family pin, and the DNAT pairings csf.pl aborts on — to the pre-hook first (natNeedsHook), exactly as addRule routes non-native filter rules before they reach MarshalAdvRule.

func (*CSF) MoveNATRule

func (f *CSF) MoveNATRule(ctx context.Context, zoneName string, r *NATRule, position int) error

MoveNATRule is unsupported for the same reason as InsertNATRule.

func (*CSF) MoveRule

func (f *CSF) MoveRule(ctx context.Context, zoneName string, r *Rule, position int) error

MoveRule is unsupported for the same reason as InsertRule.

func (*CSF) ParseAdvRule

func (f *CSF) ParseAdvRule(val string, action Action) (r *Rule)

ParseAdvRule decodes a csf advanced allow/deny rule of the form tcp/udp/icmp|in/out|s/d=port(s)|s/d=ip. The port field accepts a comma multiport list and underscore ranges; for icmp it holds the ICMP type.

func (*CSF) ParseConnLimit

func (f *CSF) ParseConnLimit(val string) (rules []*Rule)

ParseConnLimit decodes a csf.conf CONNLIMIT value ("port;limit,...") into connection-limit rules: csf caps concurrent new TCP connections per source and rejects the excess with a TCP reset, so each entry becomes an inbound tcp reject rule carrying a per-source ConnLimit.

func (*CSF) ParseIPList

func (f *CSF) ParseIPList(filePath string, action Action) (rules []*Rule, err error)

ParseIPList reads a csf.allow/csf.deny file into rules, stamping each with the given action and any full-line comment that precedes it (see scanCommentGroups for the comment-attachment convention).

func (*CSF) ParsePorts

func (f *CSF) ParsePorts(val string, family Family, proto Protocol, dir Direction) (rules []*Rule)

ParsePorts decodes a csf.conf port-list value into one accept rule per port token for the given family, protocol, and direction.

func (*CSF) Reload

func (f *CSF) Reload(ctx context.Context) error

Reload restarts csf to apply config changes, retrying past csf's transient restart lock.

func (*CSF) RemoveAddressSet

func (f *CSF) RemoveAddressSet(ctx context.Context, name string) error

RemoveAddressSet drops a set's ipset commands from the pre-hook. It fails if a hook rule still references the set; removing an absent set is a no-op.

func (*CSF) RemoveAddressSetEntry

func (f *CSF) RemoveAddressSetEntry(ctx context.Context, name, entry string) error

RemoveAddressSetEntry removes an entry from an existing set in the pre-hook.

func (*CSF) RemoveNATRule

func (f *CSF) RemoveNATRule(ctx context.Context, zoneName string, r *NATRule) error

RemoveNATRule removes a NAT rule from csf.redirect and from the pre-hook. The hook is swept first whatever the rule's shape: a hook-only shape lives nowhere else, and a natively-expressible rule may still have a stray hook copy a customer added by hand, mirroring the filter-side RemoveRule.

func (*CSF) RemoveRule

func (f *CSF) RemoveRule(ctx context.Context, zoneName string, r *Rule) error

RemoveRule removes a filter rule from whichever csf construct holds it.

func (*CSF) Restore

func (f *CSF) Restore(ctx context.Context, zoneName string, backup *Backup) error

Restore replaces the managed rules with the contents of a Backup.

func (*CSF) SetDefaultPolicy

func (f *CSF) SetDefaultPolicy(ctx context.Context, zoneName string, policy *DefaultPolicy) error

SetDefaultPolicy is unsupported: csf exposes no chain default policy.

func (*CSF) Type

func (f *CSF) Type() string

Type reports the backend identifier, "csf".

func (*CSF) UnmarshalNATRule

func (f *CSF) UnmarshalNATRule(line string) *NATRule

UnmarshalNATRule decodes a csf.redirect line into a NATRule.

type Capabilities

type Capabilities struct {
	// Output is true when the backend distinguishes input from output rules.
	Output bool
	// Forward is true when the backend can express a rule in the forward (routing)
	// chain. A false Forward means a rule with Direction DirForward is rejected
	// with ErrUnsupportedForward.
	Forward bool
	// Zones is true when the backend maps interfaces to zones.
	Zones bool
	// Priority is true when per-rule priority is honored.
	Priority bool
	// IPv6 is true when the backend manages IPv6 rules at all. It is host-resolved
	// on the backends whose own configuration can disable IPv6 (csf, apf) or whose
	// packaging can omit it (iptables); a false IPv6 means every IPv6 rule shape,
	// ICMPv6 included, is unmanageable, not merely rejected on one axis. (IPv4 is
	// managed by every backend, so it is not advertised as a capability.)
	IPv6 bool
	// PortPair is true when a source-port match can be combined with a
	// destination-port match in one rule. A false PortPair means such a rule is
	// rejected with ErrUnsupportedSourcePort (a firewalld rich rule carries a
	// single port element).
	PortPair bool
	// ConnState is true when connection-tracking state can be matched.
	ConnState bool
	// InterfaceMatch is true when a rule can bind to a per-rule interface (as
	// opposed to a zone).
	InterfaceMatch bool
	// Logging is true when per-rule packet logging is honored.
	Logging bool
	// RateLimit is true when per-rule rate limiting is honored.
	RateLimit bool
	// ConnLimit is true when per-rule connection limiting is honored.
	ConnLimit bool
	// NAT is true when AddNATRule/RemoveNATRule/GetNATRules are supported.
	NAT bool
	// RuleOrdering is true when InsertRule/MoveRule are supported, and when NAT is
	// also true, InsertNATRule/MoveNATRule.
	RuleOrdering bool
	// DefaultPolicy is true when GetDefaultPolicy/SetDefaultPolicy are supported.
	DefaultPolicy bool
	// RuleCounters is true when GetRules populates the Packets/Bytes fields.
	RuleCounters bool
	// AddressSets is true when the address-set methods are supported.
	AddressSets bool
	// Comments is true when a rule's Comment field round-trips: it is stored on
	// AddRule and populated by GetRules. A false Comments means the backend
	// silently ignores the Comment field.
	Comments bool
	// Negation is true when a "!"-negated Source/Destination match is honored.
	// A false Negation means such a rule is rejected with ErrUnsupported (WFP
	// has no negated address condition).
	Negation bool
	// RejectAction is true when the Reject action — refuse with an error
	// response, as opposed to a silent Drop — is expressible. A false
	// RejectAction means a Reject rule is rejected with ErrUnsupported (WFP
	// only permits or blocks).
	RejectAction bool
	// FamilyWithoutAddress is true when a rule with a concrete Family but no
	// Source/Destination is expressible. A false value means family scoping
	// rides on addresses alone and such a rule is rejected with ErrUnsupported
	// (a WFP filter scopes family through its address conditions).
	FamilyWithoutAddress bool
	// DenyActionFromConfig is true when the backend's native deny store carries
	// no per-entry action — the firewall tool applies the deny action its own
	// config names (csf.conf DROP, conf.apf ALL_STOP). A deny added with the
	// config's action is stored natively and reads back with it; one with a
	// differing action is expressed elsewhere (the raw-iptables hook). Because
	// the native entry encodes no action, RemoveRule clears it whatever action
	// the removal target names.
	DenyActionFromConfig bool
}

Capabilities advertises which features a backend can express. It lets a caller detect support before trial-and-error: a false field means the corresponding operation returns an unsupported error (or, for RuleCounters, simply reports zero).

type ConnLimit

type ConnLimit struct {
	// Count is the maximum number of concurrent connections the rule matches.
	Count uint
	// PerSource, when set, applies Count per source address rather than as a
	// single global cap.
	PerSource bool
}

ConnLimit caps the number of concurrent connections a rule matches. When PerSource is set the cap is applied per source address; otherwise it is a single global cap. A nil *ConnLimit means no connection limiting.

type ConnState

type ConnState uint8

ConnState is a set of connection-tracking states to match, combined as a bitmask (e.g. StateEstablished|StateRelated). The zero value matches no particular state (i.e. the rule is stateless).

const (
	// StateNew matches packets starting a new connection.
	StateNew ConnState = 1 << iota
	// StateEstablished matches packets belonging to an existing connection.
	StateEstablished
	// StateRelated matches packets starting a connection related to an existing
	// one.
	StateRelated
	// StateInvalid matches packets the tracker cannot associate with a connection.
	StateInvalid
)

func ParseConnState

func ParseConnState(tokens ...string) (ConnState, error)

ParseConnState parses state names (case-insensitive) into a ConnState bitmask. Each token may itself be a comma-separated list. An unknown name is an error.

func (ConnState) MarshalJSON

func (s ConnState) MarshalJSON() ([]byte, error)

MarshalJSON renders the connection-state set as a comma-joined name list.

func (ConnState) String

func (s ConnState) String() string

String renders the state set as a comma-separated list (e.g. "established,related"), or the empty string when no state is set.

func (ConnState) Strings

func (s ConnState) Strings() []string

Strings returns the set states as lower-case names in canonical order.

func (*ConnState) UnmarshalJSON

func (s *ConnState) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a connection-state set from a comma-joined name list.

type DefaultPolicy

type DefaultPolicy struct {
	// Input is the default action for inbound packets.
	Input Action
	// Output is the default action for outbound packets.
	Output Action
	// Forward is the default action for routed packets.
	Forward Action
}

DefaultPolicy describes the default action a firewall applies to packets that match no rule, per direction. A field left as ActionInvalid has backend- defined meaning: on Get it means the backend does not expose that direction, and on Set it means the direction should be left unchanged.

type Direction

type Direction uint8

Direction names the traffic direction a default policy or rule applies to.

const (
	// DirInput is the inbound (input) direction. It must remain the zero value so
	// a rule with no explicit direction is an input rule.
	DirInput Direction = iota
	// DirOutput is the outbound (output) direction.
	DirOutput
	// DirForward is the routing (forward) direction, where a backend models it.
	DirForward
	// DirAny applies to both the input and output directions. It is the direction
	// analog of FamilyAny: a backend that can store a bidirectional rule as one
	// object reads it back as DirAny, while one that cannot fans it into a concrete
	// input row plus a role-swapped output row on write (expandDirections). It never
	// covers DirForward (a routed rule has no input/output twin) and must be declared
	// last so DirInput stays the zero value.
	DirAny
)

func ParseDirection

func ParseDirection(s string) (Direction, error)

ParseDirection parses a direction token (case-insensitive), accepting the canonical name emitted by Direction.String. An unknown value is an error.

func (Direction) MarshalJSON

func (d Direction) MarshalJSON() ([]byte, error)

MarshalJSON renders the direction as its stable name (e.g. "input").

func (Direction) String

func (d Direction) String() string

String returns the canonical lower-case name of the direction.

func (*Direction) UnmarshalJSON

func (d *Direction) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a direction from its stable name.

type Family

type Family uint8

Family is the IP family a rule targets.

const (
	// FamilyAny targets both IPv4 and IPv6.
	FamilyAny Family = iota
	// IPv4 targets IPv4 traffic only.
	IPv4
	// IPv6 targets IPv6 traffic only.
	IPv6
)

func ParseFamily

func ParseFamily(s string) (Family, error)

ParseFamily parses a family token (case-insensitive), accepting the canonical name emitted by Family.String plus the common aliases (v4/inet4, v6/inet6). An unknown value is an error.

func (Family) MarshalJSON

func (f Family) MarshalJSON() ([]byte, error)

MarshalJSON renders the family as its stable name (e.g. "ipv4").

func (Family) String

func (t Family) String() string

String returns the canonical lower-case name of the family.

func (*Family) UnmarshalJSON

func (f *Family) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a family from its stable name.

type FirewallD

type FirewallD struct {
	Conn *firewalld.Conn
	// contains filtered or unexported fields
}

FirewallD manages a firewalld instance over D-Bus, mapping the Manager interface onto firewalld's zones, rich rules, and ipsets.

func NewFirewallD

func NewFirewallD(ctx context.Context, rulePrefix string) (*FirewallD, error)

NewFirewallD connects to firewalld and returns a manager, or an error when firewalld cannot be reached.

func (*FirewallD) AddAddressSet

func (f *FirewallD) AddAddressSet(ctx context.Context, set *AddressSet) error

AddAddressSet creates the permanent ipset, or updates it in place when it already exists.

func (*FirewallD) AddAddressSetEntry

func (f *FirewallD) AddAddressSetEntry(ctx context.Context, name, entry string) error

AddAddressSetEntry adds entry to the named permanent ipset. AddEntry resolves the ipset by name itself and returns firewalld.ErrInvalidIPSet if it does not exist, so a separate existence pre-check would just double the D-Bus round trips.

func (*FirewallD) AddNATRule

func (f *FirewallD) AddNATRule(ctx context.Context, zoneName string, r *NATRule) error

AddNATRule adds a NAT rule to a zone via firewalld's forward-port or masquerade API.

func (*FirewallD) AddRule

func (f *FirewallD) AddRule(ctx context.Context, zoneName string, r *Rule) error

AddRule adds a filter rule to a zone, using a zone-level entry when the rule fits one and a rich rule otherwise.

func (*FirewallD) Backup

func (f *FirewallD) Backup(ctx context.Context, zoneName string) (*Backup, error)

Backup captures the current filter and NAT rules managed by this backend.

func (*FirewallD) Capabilities

func (f *FirewallD) Capabilities() Capabilities

Capabilities reports which optional features this backend supports.

func (*FirewallD) Close

func (f *FirewallD) Close(ctx context.Context) error

Close releases the D-Bus connection to firewalld.

func (*FirewallD) GetAddressSet

func (f *FirewallD) GetAddressSet(ctx context.Context, name string) (*AddressSet, error)

GetAddressSet returns the named permanent ipset, or an error if it does not exist.

func (*FirewallD) GetAddressSets

func (f *FirewallD) GetAddressSets(ctx context.Context) ([]*AddressSet, error)

GetAddressSets returns all permanent firewalld ipsets as address sets.

func (*FirewallD) GetDefaultPolicy

func (f *FirewallD) GetDefaultPolicy(ctx context.Context, zoneName string) (*DefaultPolicy, error)

GetDefaultPolicy returns the zone's default input policy, derived from its target.

func (*FirewallD) GetNATRules

func (f *FirewallD) GetNATRules(ctx context.Context, zoneName string) (rules []*NATRule, err error)

GetNATRules returns the NAT rules for a zone, mapping forward ports and masquerade.

func (*FirewallD) GetRules

func (f *FirewallD) GetRules(ctx context.Context, zoneName string) (rules []*Rule, err error)

GetRules returns the filter rules for a zone, resolving an empty zone to the default.

func (*FirewallD) GetZone

func (f *FirewallD) GetZone(ctx context.Context, iface string) (zoneName string, err error)

GetZone returns the firewalld zone bound to the interface, falling back to the default zone when the interface is unbound.

func (*FirewallD) InsertNATRule

func (f *FirewallD) InsertNATRule(ctx context.Context, zoneName string, position int, r *NATRule) error

InsertNATRule is unsupported: firewalld models NAT through zone toggles and rich rules, which carry no explicit ordering.

func (*FirewallD) InsertRule

func (f *FirewallD) InsertRule(ctx context.Context, zoneName string, position int, r *Rule) error

InsertRule is unsupported: firewalld rich rules and port/source shortcuts are not positionally ordered.

func (*FirewallD) MarshalRichRule

func (f *FirewallD) MarshalRichRule(r *Rule) (richRule string, err error)

MarshalRichRule encodes a rule into a firewalld rich-rule string.

func (*FirewallD) MoveNATRule

func (f *FirewallD) MoveNATRule(ctx context.Context, zoneName string, r *NATRule, position int) error

MoveNATRule is unsupported for the same reason as InsertNATRule.

func (*FirewallD) MoveRule

func (f *FirewallD) MoveRule(ctx context.Context, zoneName string, r *Rule, position int) error

MoveRule is unsupported for the same reason as InsertRule.

func (*FirewallD) Reload

func (f *FirewallD) Reload(ctx context.Context) error

Reload reloads firewalld's permanent configuration into the runtime.

func (*FirewallD) RemoveAddressSet

func (f *FirewallD) RemoveAddressSet(ctx context.Context, name string) error

RemoveAddressSet removes the named permanent ipset. Remove resolves the ipset by name itself and returns firewalld.ErrInvalidIPSet if it does not exist, so a separate existence pre-check would just double the D-Bus round trips.

func (*FirewallD) RemoveAddressSetEntry

func (f *FirewallD) RemoveAddressSetEntry(ctx context.Context, name, entry string) error

RemoveAddressSetEntry removes entry from the named permanent ipset. RemoveEntry resolves the ipset by name itself and returns firewalld.ErrInvalidIPSet if it does not exist, so a separate existence pre-check would just double the D-Bus round trips.

func (*FirewallD) RemoveNATRule

func (f *FirewallD) RemoveNATRule(ctx context.Context, zoneName string, r *NATRule) error

RemoveNATRule removes a NAT rule from a zone via firewalld's forward-port or masquerade API.

func (*FirewallD) RemoveRule

func (f *FirewallD) RemoveRule(ctx context.Context, zoneName string, r *Rule) error

RemoveRule removes a filter rule from a zone, clearing every form it may be stored in: the zone-level entry AddRule would have used and any rich rule whose parsed form matches the target.

func (*FirewallD) Restore

func (f *FirewallD) Restore(ctx context.Context, zoneName string, backup *Backup) error

Restore replaces the managed rules with the contents of a Backup.

func (*FirewallD) SetDefaultPolicy

func (f *FirewallD) SetDefaultPolicy(ctx context.Context, zoneName string, policy *DefaultPolicy) error

SetDefaultPolicy sets the zone's default input policy via its target; firewalld zones only expose the input direction.

func (*FirewallD) Type

func (f *FirewallD) Type() string

Type returns the backend identifier for firewalld.

func (*FirewallD) UnmarshalRichRule

func (f *FirewallD) UnmarshalRichRule(richRule string) (r *Rule, err error)

UnmarshalRichRule takes a rich-rule string and returns a parsed rule for supported rules.

type IPTables

type IPTables struct {
	IP4Path, IP6Path string
	// IP6Path and IP6Service are empty on a host whose packaging ships no
	// ip6tables save file — a system built without IPv6, or one where the
	// ip6tables package was never installed — and on one whose IPv6 restore
	// service is not enabled, since nothing would replay the file at boot. Such a
	// host is managed IPv4-only; see managesIPv6 for what that changes.
	IP4Service, IP6Service string
	// IPSetPath and IPSetService describe the optional ipset persistence
	// mechanism detected for this host. IPSetPath is the file address sets are
	// staged in — the authority for the sets this backend manages, loaded into the
	// kernel by Reload and by IPSetService at boot, before the rules that
	// reference them. Both are empty when no mechanism is installed, in which case
	// address sets are created live and do not survive a reboot.
	IPSetPath, IPSetService string
	// contains filtered or unexported fields
}

IPTables manages filter and NAT rules through iptables save files and the service that restores them.

func NewIPTables

func NewIPTables(ctx context.Context, rulePrefix string) (*IPTables, error)

NewIPTables creates an iptables manager, detecting the save-file layout and confirming its IPv4 restore service is enabled. An IPv6 half that has no save file, or whose restore service is not enabled, is left unmanaged rather than failing.

func (*IPTables) AddAddressSet

func (f *IPTables) AddAddressSet(ctx context.Context, set *AddressSet) error

AddAddressSet stages an address set; it is created in the kernel by Reload. Adding a set that already exists by name merges its entries, matching what a re-create with -exist does live; re-declaring one with a different family or type is a conflict and is reported rather than silently rewriting the set.

func (*IPTables) AddAddressSetEntry

func (f *IPTables) AddAddressSetEntry(ctx context.Context, name, entry string) error

AddAddressSetEntry adds an entry to the named set.

func (*IPTables) AddNATRule

func (f *IPTables) AddNATRule(ctx context.Context, zoneName string, r *NATRule) error

AddNATRule adds a NAT rule to the zone. A family-agnostic set-referencing rule is pinned to its set's family first, as with AddRule.

func (*IPTables) AddRule

func (f *IPTables) AddRule(ctx context.Context, zoneName string, r *Rule) error

AddRule adds a rule to the zone. A family-agnostic set-referencing rule is pinned to its set's family first, so its line lands only in the save file the single-family ipset can match.

func (*IPTables) Backup

func (f *IPTables) Backup(ctx context.Context, zoneName string) (*Backup, error)

Backup captures the current filter and NAT rules managed by this backend.

func (*IPTables) Capabilities

func (f *IPTables) Capabilities() Capabilities

Capabilities returns the set of features this backend can express.

func (*IPTables) Close

func (f *IPTables) Close(ctx context.Context) error

Close releases manager resources.

func (*IPTables) GetAddressSet

func (f *IPTables) GetAddressSet(ctx context.Context, name string) (*AddressSet, error)

GetAddressSet returns a single address set by name, or an error if it does not exist.

func (*IPTables) GetAddressSets

func (f *IPTables) GetAddressSets(ctx context.Context) ([]*AddressSet, error)

GetAddressSets returns the address sets managed by this backend: the staged sets, or the live kernel's on a host with no staging file.

func (*IPTables) GetDefaultPolicy

func (f *IPTables) GetDefaultPolicy(ctx context.Context, zoneName string) (*DefaultPolicy, error)

GetDefaultPolicy returns the default action applied to packets that match no rule.

func (*IPTables) GetNATRules

func (f *IPTables) GetNATRules(ctx context.Context, zoneName string) (rules []*NATRule, err error)

GetNATRules returns the existing NAT rules from the zone.

func (*IPTables) GetRules

func (f *IPTables) GetRules(ctx context.Context, zoneName string) (rules []*Rule, err error)

GetRules returns the existing filter rules from the zone.

func (*IPTables) GetZone

func (f *IPTables) GetZone(ctx context.Context, iface string) (zoneName string, err error)

GetZone reports no zone: iptables has only policy groups, and rules are inserted at the top of the INPUT/OUTPUT policies.

func (*IPTables) InsertNATRule

func (f *IPTables) InsertNATRule(ctx context.Context, zoneName string, position int, r *NATRule) error

InsertNATRule inserts a NAT rule at the given 1-based position within its nat chain. A non-positive position is treated as 1; a position larger than the chain's current rule count appends the rule.

func (*IPTables) InsertRule

func (f *IPTables) InsertRule(ctx context.Context, zoneName string, position int, r *Rule) error

InsertRule inserts rule before the given 1-based position in the iptables save file. A non-positive position is treated as 1; a position larger than the current rule count appends the rule. A family-agnostic set-referencing rule is pinned to its set's family first, as in AddRule.

func (*IPTables) MarshalNATRule

func (f *IPTables) MarshalNATRule(r *NATRule) (string, error)

MarshalNATRule encodes a NAT rule as an iptables-save rulespec for the nat table (e.g. `-A PREROUTING -p tcp --dport 80 -j DNAT --to-destination ...`). It is a pure encoder: callers run NATRule.validate first. iptables' nat targets cover every modeled shape, so it takes no rejections of its own.

func (*IPTables) MarshalRule

func (f *IPTables) MarshalRule(r *Rule) (string, error)

MarshalRule encodes a rule as a single iptables-save rulespec ending in its action target.

func (*IPTables) MoveNATRule

func (f *IPTables) MoveNATRule(ctx context.Context, zoneName string, r *NATRule, position int) error

MoveNATRule moves an existing NAT rule to the given 1-based position within its nat chain. A non-positive position is treated as 1; a position larger than the chain's current rule count moves the rule to the end.

func (*IPTables) MoveRule

func (f *IPTables) MoveRule(ctx context.Context, zoneName string, r *Rule, position int) error

MoveRule moves an existing rule to the given 1-based position within its chain.

func (*IPTables) Reload

func (f *IPTables) Reload(ctx context.Context) error

Reload activates the staged state: the address sets first, so a rule matching on one resolves when the save files load, then the restore service(s) for the rules, then the kernel-side destroy of any set removed this session, which has to wait until the rules that referenced it are gone.

The sets are loaded here directly rather than by restarting IPSetService, whose stop hook varies by packaging — some flush, some save the live state back over the file — and would put this backend's staged file at the mercy of it. The service still matters for boot, which is why writeStagedSets enables it.

func (*IPTables) RemoveAddressSet

func (f *IPTables) RemoveAddressSet(ctx context.Context, name string) error

RemoveAddressSet removes an address set by name. The set is dropped from the staging file now and destroyed in the kernel by Reload, once the rules that referenced it are gone. Removing a set that is not staged is a no-op.

func (*IPTables) RemoveAddressSetEntry

func (f *IPTables) RemoveAddressSetEntry(ctx context.Context, name, entry string) error

RemoveAddressSetEntry removes an entry from the named set. A missing entry, or a missing set, is a no-op.

func (*IPTables) RemoveNATRule

func (f *IPTables) RemoveNATRule(ctx context.Context, zoneName string, r *NATRule) error

RemoveNATRule removes a NAT rule from the zone.

func (*IPTables) RemoveRule

func (f *IPTables) RemoveRule(ctx context.Context, zoneName string, r *Rule) error

RemoveRule removes a rule from the zone. A family-agnostic set-referencing rule is deliberately not pinned here: leaving it FamilyAny sweeps both family files, which also clears a stray wrong-family line and still works after the referenced set is gone.

func (*IPTables) Restore

func (f *IPTables) Restore(ctx context.Context, zoneName string, backup *Backup) error

Restore replaces the managed INPUT/OUTPUT/FORWARD filter rules and the nat rules with the contents of a Backup, splicing them into each family's existing save file, and re-asserts the captured filter chain policies and ipsets. User-defined chains and the *mangle/*raw tables — none of which Backup captures — are left untouched.

func (*IPTables) SetDefaultPolicy

func (f *IPTables) SetDefaultPolicy(ctx context.Context, zoneName string, policy *DefaultPolicy) error

SetDefaultPolicy sets the default action for the directions named in policy.

func (*IPTables) Type

func (f *IPTables) Type() string

Type returns the manager type.

func (*IPTables) UnmarshalNATRule

func (f *IPTables) UnmarshalNATRule(spec string, family Family) (*NATRule, error)

UnmarshalNATRule decodes one iptables-save nat line (-A PREROUTING / -A POSTROUTING ...) into a NATRule. A line the model cannot hold faithfully — a negated interface/protocol/port match, an unknown protocol, an unsupported jump, or another chain — is rejected so the raw line stays foreign and is preserved verbatim; an OUTPUT-chain DNAT, for example, has no distinct model here and would otherwise be relocated to PREROUTING on Restore.

func (*IPTables) UnmarshalRule

func (f *IPTables) UnmarshalRule(ruleSpec string, family Family) (*Rule, error)

UnmarshalRule decodes an iptables rulespec into a firewall rule.

type Manager

type Manager interface {
	// Type returns the manager type.
	Type() string

	// Capabilities returns the set of features this backend can express.
	Capabilities() Capabilities

	// GetZone returns the zone for the specified interface.
	GetZone(ctx context.Context, iface string) (string, error)

	// GetRules returns the existing filter rules from the zone.
	GetRules(ctx context.Context, zoneName string) ([]*Rule, error)

	// AddRule adds a rule to the zone.
	AddRule(ctx context.Context, zoneName string, rule *Rule) error

	// InsertRule adds rule at the given position. position uses 1-based indexing
	// (1 = first rule); a non-positive position is treated as 1, and a position
	// larger than the current rule count appends the rule. Backends that do not
	// support ordered rules return an error.
	InsertRule(ctx context.Context, zoneName string, position int, rule *Rule) error

	// MoveRule moves an existing rule to the given position. position uses 1-based
	// indexing; a non-positive position is treated as 1, and a position larger
	// than the current rule count moves the rule to the end. Backends that do not
	// support ordered rules return an error.
	MoveRule(ctx context.Context, zoneName string, rule *Rule, position int) error

	// RemoveRule removes a rule from the zone.
	RemoveRule(ctx context.Context, zoneName string, rule *Rule) error

	// GetNATRules returns the existing NAT rules from the zone. Backends without
	// NAT support return an unsupported error.
	GetNATRules(ctx context.Context, zoneName string) ([]*NATRule, error)

	// AddNATRule adds a NAT rule to the zone.
	AddNATRule(ctx context.Context, zoneName string, rule *NATRule) error

	// InsertNATRule adds a NAT rule at the given position within its nat chain.
	// position uses 1-based indexing (1 = first rule in that chain); a non-positive
	// position is treated as 1, and a position larger than the chain's current rule
	// count appends the rule. Backends that do not support ordered rules return an
	// error; backends without NAT support return the NAT sentinel.
	InsertNATRule(ctx context.Context, zoneName string, position int, rule *NATRule) error

	// MoveNATRule moves an existing NAT rule to the given position within its nat
	// chain. position uses 1-based indexing; a non-positive position is treated as
	// 1, and a position larger than the chain's current rule count moves the rule
	// to the end. Backends that do not support ordered rules return an error;
	// backends without NAT support return the NAT sentinel.
	MoveNATRule(ctx context.Context, zoneName string, rule *NATRule, position int) error

	// RemoveNATRule removes a NAT rule from the zone.
	RemoveNATRule(ctx context.Context, zoneName string, rule *NATRule) error

	// GetDefaultPolicy returns the default action applied to packets that match
	// no rule. A direction the backend cannot express is returned as
	// ActionInvalid. Backends that cannot manage a default policy at all return
	// an unsupported error.
	GetDefaultPolicy(ctx context.Context, zoneName string) (*DefaultPolicy, error)

	// SetDefaultPolicy sets the default action for the directions named in
	// policy. A direction left as ActionInvalid is left unchanged. Backends that
	// cannot manage a default policy return an unsupported error.
	SetDefaultPolicy(ctx context.Context, zoneName string, policy *DefaultPolicy) error

	// GetAddressSets returns the address sets managed by this backend. Backends
	// that cannot manage address sets return an unsupported error.
	GetAddressSets(ctx context.Context) ([]*AddressSet, error)

	// GetAddressSet returns a single address set by name, or an error if it does
	// not exist. Backends that cannot manage address sets return an unsupported
	// error.
	GetAddressSet(ctx context.Context, name string) (*AddressSet, error)

	// AddAddressSet creates an address set. Adding a set that already exists (by
	// name) is a no-op. Backends that cannot manage address sets return an
	// unsupported error.
	AddAddressSet(ctx context.Context, set *AddressSet) error

	// RemoveAddressSet removes an address set by name. Backends that cannot
	// manage address sets return an unsupported error.
	RemoveAddressSet(ctx context.Context, name string) error

	// AddAddressSetEntry adds an entry to the named set. Backends that cannot
	// manage address sets return an unsupported error.
	AddAddressSetEntry(ctx context.Context, name, entry string) error

	// RemoveAddressSetEntry removes an entry from the named set. Backends that
	// cannot manage address sets return an unsupported error.
	RemoveAddressSetEntry(ctx context.Context, name, entry string) error

	// Backup captures the current filter and NAT rules the manager reports, plus —
	// on backends that advertise them — the default policy and the managed address
	// sets. On container backends (nftables table, pf anchor, firewalld zone) this
	// is scoped to the library's container by construction; on tag/comment backends
	// it is the whole chain, foreign rules included. It does not filter on the
	// HasPrefix flag.
	Backup(ctx context.Context, zoneName string) (*Backup, error)

	// Restore reconciles the firewall to the contents of a Backup. The captured
	// address sets are recreated first (so a set-referencing rule resolves), then
	// existing filter and NAT rules the backend acts on are removed and the backup
	// rules added, and finally the captured default policy is re-asserted. Like Sync
	// it reconciles the actual state and does not filter on HasPrefix.
	Restore(ctx context.Context, zoneName string, backup *Backup) error

	// Reload reloads the manager to activate new rules.
	Reload(ctx context.Context) error

	// Close closes the connection to the manager.
	Close(ctx context.Context) error
}

Manager is the standard firewall manager interface.

Every method that performs I/O (shelling out, D-Bus, or the Windows API) takes a context.Context as its first argument so callers can apply timeouts and cancellation. Type and Capabilities are pure and take none.

func NewManager

func NewManager(ctx context.Context, rulePrefix string) (Manager, error)

NewManager gets a firewall manager for this server, probing the higher-level managers first: firewalld, then ufw/csf/apf, then plain iptables, and nftables last, so a manager that is itself backed by iptables or nftables is preferred over managing its tables behind its back. The context bounds the detection probes (each shells out or opens a D-Bus/systemd connection).

type NATKind

type NATKind uint8

NATKind is the kind of network address translation a NATRule performs.

const (
	// NATInvalid is the zero value of NATKind, meaning no translation; it is
	// rejected when authoring a NAT rule.
	NATInvalid NATKind = iota
	// DNAT rewrites the destination of matching inbound packets to ToAddress
	// (and ToPort when set) — a classic port-forward to another host.
	DNAT
	// Redirect sends matching inbound packets to a port on the local host
	// (ToPort). It is destination NAT to this machine and takes no ToAddress.
	Redirect
	// SNAT rewrites the source of matching outbound packets to the fixed
	// ToAddress.
	SNAT
	// Masquerade rewrites the source of matching outbound packets to the
	// address of the outgoing interface, chosen dynamically at send time.
	Masquerade
)

func ParseNATKind

func ParseNATKind(s string) (NATKind, error)

ParseNATKind parses a NAT-kind token (case-insensitive), accepting only the concrete kinds NATKind.String emits. The sentinel "invalid" (NATInvalid) is rejected, mirroring ParseAction, so callers cannot author a NAT rule with no real kind; backup decoding round-trips it separately in NATKind.UnmarshalJSON.

func (NATKind) MarshalJSON

func (k NATKind) MarshalJSON() ([]byte, error)

MarshalJSON renders the NAT kind as its stable name (e.g. "dnat").

func (NATKind) String

func (k NATKind) String() string

String returns the canonical lower-case name of the NAT kind.

func (*NATKind) UnmarshalJSON

func (k *NATKind) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a NAT kind from its stable name. The sentinel "invalid" (NATInvalid) is accepted on the wire for round-trip fidelity even though ParseNATKind rejects it as caller input, mirroring Action.

type NATRule

type NATRule struct {
	// Kind is the translation to perform.
	Kind NATKind
	// Family is the IP family the rule targets. FamilyAny is resolved from the
	// translation target or a matched address when left unset.
	Family Family
	// Proto is the network protocol the rule matches.
	Proto Protocol
	// Interface matches the inbound interface for DNAT/Redirect and the
	// outbound interface for SNAT/Masquerade. Empty means any interface.
	Interface string
	// Source matches the packet's source address or CIDR, with the same
	// semantics as Rule.Source. Empty matches any source.
	Source string
	// Destination matches the packet's destination address or CIDR, with the
	// same semantics as Rule.Destination. Empty matches any destination.
	Destination string
	// Port is the single destination port the rule matches; Ports takes
	// precedence when non-empty.
	Port uint16
	// Ports is a list of destination port ranges the rule matches.
	Ports []PortRange
	// ToAddress is the translation target: the new destination for DNAT, the
	// new source for SNAT. It is empty for Redirect and Masquerade.
	ToAddress string
	// ToPort is the translation target port for DNAT/Redirect (0 leaves the
	// port unchanged). It is unused for SNAT/Masquerade.
	ToPort uint16
	// HasPrefix reports whether the rule carries the library's configured
	// prefix, mirroring Rule.HasPrefix. It is derived on read and purely
	// informational.
	HasPrefix bool
	// Number is the rule's 1-based position within its nat chain, populated by
	// GetNATRules on backends that advertise Capabilities().RuleOrdering. It
	// mirrors the position argument of InsertNATRule and MoveNATRule.
	Number int
	// contains filtered or unexported fields
}

A NATRule describes a network-address-translation rule: a port-forward (DNAT/Redirect) applied to inbound traffic, or source NAT (SNAT/Masquerade) applied to outbound traffic. NAT rules are managed separately from filter Rules through the Manager's NAT methods.

func (*NATRule) CoveredBy

func (r *NATRule) CoveredBy(rules []*NATRule) bool

CoveredBy reports whether every concrete NAT rule the receiver spans is covered by at least one rule in rules, mirroring Rule.CoveredBy. A FamilyAny receiver requires both families to be covered, whether by one FamilyAny rule or by an IPv4 rule and an IPv6 rule; a match-port list requires every port to be covered, whether by one list rule or by a row per port on a backend that fans lists out.

func (*NATRule) Covers

func (r *NATRule) Covers(o *NATRule) bool

Covers reports whether the receiver's coverage contains o's, mirroring Rule.Covers for NAT rules. A FamilyAny rule covers either family and a concrete one covers only itself; a match-port list or range covers the ports it contains. NAT has no direction axis and a translation applies per transport, so family and ports are the only axes a NAT rule spans.

func (*NATRule) Equal

func (r *NATRule) Equal(o *NATRule) bool

Equal reports whether two NAT rules are the same, including the IP family. Family is compared through impliedFamily so a FamilyAny rule matches the concrete family a backend stores it under (mirroring Rule.Equal).

func (*NATRule) EqualBase

func (r *NATRule) EqualBase(o *NATRule) bool

EqualBase reports whether two NAT rules describe the same translation and match, ignoring the IP family (mirroring Rule.EqualBase). Backends use it to deduplicate and remove rules regardless of a FamilyAny/concrete distinction.

func (*NATRule) EqualForDedup

func (r *NATRule) EqualForDedup(o *NATRule) bool

EqualForDedup is the NAT-rule add guard mirroring Rule.EqualForDedup: the same base translation, and the receiver's family covers o's.

func (*NATRule) EqualForRemoval

func (r *NATRule) EqualForRemoval(o *NATRule) bool

EqualForRemoval is the NAT-rule remove guard mirroring Rule.EqualForRemoval: the same base translation, and o's family may touch the receiver row's.

func (*NATRule) HasPortSet

func (r *NATRule) HasPortSet() bool

HasPortSet reports whether the rule matches more than a single discrete port.

func (*NATRule) HasPorts

func (r *NATRule) HasPorts() bool

HasPorts reports whether the rule matches on any destination port.

func (*NATRule) PortSpecs

func (r *NATRule) PortSpecs() []PortRange

PortSpecs returns the rule's matched destination ports as a normalized list.

type NFT

type NFT struct {
	// contains filtered or unexported fields
}

NFT manages firewall rules through the nftables netlink API. To avoid clobbering rules owned by other tooling, every rule this backend creates lives in a private `inet` table (named after the rule prefix) with its own input and output base chains. Writes are scoped to that table; reads also report rules found in other tables so callers can see the whole ruleset.

func NewNFT

func NewNFT(ctx context.Context, rulePrefix string) (*NFT, error)

NewNFT constructs an nftables-backed Manager, deriving the private table name from rulePrefix and verifying nf_tables is reachable over netlink.

func (*NFT) AddAddressSet

func (f *NFT) AddAddressSet(ctx context.Context, set *AddressSet) error

AddAddressSet creates an address set. Adding a set that already exists (by name) with the same definition is a no-op.

func (*NFT) AddAddressSetEntry

func (f *NFT) AddAddressSetEntry(ctx context.Context, name, entry string) error

AddAddressSetEntry adds an entry to the named set.

func (*NFT) AddNATRule

func (f *NFT) AddNATRule(ctx context.Context, zoneName string, r *NATRule) error

AddNATRule adds a NAT rule to the zone.

func (*NFT) AddRule

func (f *NFT) AddRule(ctx context.Context, zoneName string, r *Rule) error

AddRule adds a rule to the zone.

func (*NFT) Backup

func (f *NFT) Backup(ctx context.Context, zoneName string) (*Backup, error)

Backup captures the filter and NAT rules in this backend's private table.

func (*NFT) Capabilities

func (f *NFT) Capabilities() Capabilities

Capabilities returns the set of features this backend can express.

func (*NFT) Close

func (f *NFT) Close(ctx context.Context) error

Close closes the connection to the manager.

func (*NFT) GetAddressSet

func (f *NFT) GetAddressSet(ctx context.Context, name string) (*AddressSet, error)

GetAddressSet returns a single address set by name, or an error if it does not exist.

func (*NFT) GetAddressSets

func (f *NFT) GetAddressSets(ctx context.Context) ([]*AddressSet, error)

GetAddressSets returns the address sets managed by this backend.

func (*NFT) GetDefaultPolicy

func (f *NFT) GetDefaultPolicy(ctx context.Context, zoneName string) (*DefaultPolicy, error)

GetDefaultPolicy returns the default action applied to packets that match no rule.

func (*NFT) GetNATRules

func (f *NFT) GetNATRules(ctx context.Context, zoneName string) (rules []*NATRule, err error)

GetNATRules returns the existing NAT rules from the zone.

func (*NFT) GetRules

func (f *NFT) GetRules(ctx context.Context, zoneName string) (rules []*Rule, err error)

GetRules returns the existing filter rules from the zone.

func (*NFT) GetZone

func (f *NFT) GetZone(ctx context.Context, iface string) (zoneName string, err error)

GetZone reports no zone; nftables has no interface-to-zone mapping in this model.

func (*NFT) InsertNATRule

func (f *NFT) InsertNATRule(ctx context.Context, zoneName string, position int, r *NATRule) error

InsertNATRule inserts a NAT rule before the given 1-based position within its nat chain. position <= 0 is treated as 1; a position larger than the chain's current rule count appends the rule.

func (*NFT) InsertRule

func (f *NFT) InsertRule(ctx context.Context, zoneName string, position int, r *Rule) error

InsertRule inserts rule before the given 1-based position. position <= 0 is treated as 1 (prepend); a position larger than the current rule count appends the rule. Normalizing here keeps insertRule's -1 sentinel reserved for AddRule's plain append.

func (*NFT) MarshalNATRule

func (f *NFT) MarshalNATRule(r *NATRule) (*nftEncoded, error)

MarshalNATRule encodes a NAT rule as an expression list, returning it in the chain it belongs in (prerouting for destination NAT, postrouting for source NAT). It is a pure encoder: callers run validateNAT first.

func (*NFT) MarshalRule

func (f *NFT) MarshalRule(r *Rule) (*nftEncoded, error)

MarshalRule encodes a filter rule as the nftables expression list the kernel stores, plus the anonymous sets and meter set it references. It is a pure encoder: callers run validateRule first.

func (*NFT) MoveNATRule

func (f *NFT) MoveNATRule(ctx context.Context, zoneName string, r *NATRule, position int) error

MoveNATRule moves an existing NAT rule to the given 1-based position within its nat chain. position <= 0 is treated as 1; a position larger than the chain's current rule count moves the rule to the end.

func (*NFT) MoveRule

func (f *NFT) MoveRule(ctx context.Context, zoneName string, r *Rule, position int) error

MoveRule moves an existing rule to the given 1-based position.

func (*NFT) Reload

func (f *NFT) Reload(ctx context.Context) error

Reload is a no-op; nftables applies changes immediately, so there is nothing to reload.

func (*NFT) RemoveAddressSet

func (f *NFT) RemoveAddressSet(ctx context.Context, name string) error

RemoveAddressSet removes an address set by name.

func (*NFT) RemoveAddressSetEntry

func (f *NFT) RemoveAddressSetEntry(ctx context.Context, name, entry string) error

RemoveAddressSetEntry removes an entry from the named set.

func (*NFT) RemoveNATRule

func (f *NFT) RemoveNATRule(ctx context.Context, zoneName string, r *NATRule) error

RemoveNATRule removes a NAT rule from the zone.

func (*NFT) RemoveRule

func (f *NFT) RemoveRule(ctx context.Context, zoneName string, r *Rule) error

RemoveRule removes a rule from the zone. A target that matches nothing in the library's own table but matches a rule in another table returns ErrForeignTable: GetRules reports that rule, but this backend writes only to its own table, so the rule is left in place. Foreign rules are deliberately not deleted by handle: Sync removes every reported rule outside the desired set, so that would wipe every other table on the host, and a foreign rule is parsed best-effort, so its handle may carry more than the parsed Rule shows.

func (*NFT) Restore

func (f *NFT) Restore(ctx context.Context, zoneName string, backup *Backup) error

Restore replaces the managed rules with the contents of a Backup.

func (*NFT) SetDefaultPolicy

func (f *NFT) SetDefaultPolicy(ctx context.Context, zoneName string, policy *DefaultPolicy) error

SetDefaultPolicy sets the policy of the named directions. nftables chain policies may only be accept or drop; reject is not expressible. Re-adding the base chain with a policy is how a policy is changed, so its hook properties are restated alongside.

func (*NFT) Type

func (f *NFT) Type() string

Type returns the manager type.

func (*NFT) UnmarshalNATRule

func (f *NFT) UnmarshalNATRule(nr *nftables.Rule, sets *nftSetReader, tbl *nftables.Table) (*NATRule, error)

UnmarshalNATRule decodes a nat chain row's expression list into a NAT rule.

func (*NFT) UnmarshalRule

func (f *NFT) UnmarshalRule(nr *nftables.Rule, chain string, sets *nftSetReader, tbl *nftables.Table) (*Rule, error)

UnmarshalRule decodes a chain row's expression list into a filter rule. It returns an error for any row carrying a construct the model cannot hold, so the caller can keep the row as an opaque slot rather than misrepresenting it.

type PortRange

type PortRange struct {
	// Start is the first port in the inclusive range.
	Start uint16
	// End is the last port in the inclusive range.
	End uint16
}

PortRange is an inclusive range of ports. A single port is represented with End equal to Start (or End left zero, which normalizes to Start).

func ParsePortRange

func ParsePortRange(s string) (PortRange, error)

ParsePortRange parses a single "80" or "80-90"/"80:90" token into a PortRange.

func ParsePortRanges

func ParsePortRanges(s, sep string) ([]PortRange, error)

ParsePortRanges parses a separated list such as "80,443,1000-2000" into a slice of PortRange values. sep is the separator between entries (typically ",").

func (PortRange) String

func (pr PortRange) String() string

String renders the range as "80" for a single port or "80-90" for a span.

type Protocol

type Protocol uint8

Protocol is the network protocol a rule matches.

const (
	// ProtocolAny matches every IP protocol and is the zero value.
	ProtocolAny Protocol = iota
	// UDP is the connectionless transport protocol.
	UDP
	// TCP is the connection-oriented transport protocol.
	TCP
	// ICMP and ICMPv6 are the control-message protocols. ICMP implies IPv4 and
	// ICMPv6 implies IPv6.
	ICMP
	ICMPv6
	// SCTP is a transport protocol that, like TCP and UDP, carries ports.
	SCTP
	// GRE, ESP and AH are portless IP protocols (tunneling and IPsec). A rule
	// carrying one of these cannot also match a port.
	GRE
	ESP
	AH
	// TCPUDP matches TCP and UDP together.
	TCPUDP
)

func GetProtocol

func GetProtocol(proto string) Protocol

GetProtocol converts a string to the network protocol. The common spellings each backend emits for ICMPv6 (icmpv6, ipv6-icmp, icmp6) are all recognized. An unknown token resolves to ProtocolAny (the widest match), so a caller that must distinguish an unknown protocol from a genuine "any" checks the token itself, as the save-file parsers do.

func (Protocol) HasPorts

func (t Protocol) HasPorts() bool

HasPorts reports whether the protocol carries layer-4 ports (TCP, UDP, SCTP or the merged TCPUDP). A port match is only meaningful and only valid for these protocols.

func (Protocol) IsICMP

func (t Protocol) IsICMP() bool

IsICMP reports whether the protocol is ICMP or ICMPv6.

func (Protocol) MarshalJSON

func (p Protocol) MarshalJSON() ([]byte, error)

MarshalJSON renders the protocol as its stable name (e.g. "tcp").

func (Protocol) String

func (t Protocol) String() string

String returns the canonical lower-case name of the protocol.

func (*Protocol) UnmarshalJSON

func (p *Protocol) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a protocol from its stable name. An unrecognized token is rejected rather than silently widening the rule to ProtocolAny; only the wildcard spellings ("any" or empty) resolve to ProtocolAny.

type RateLimit

type RateLimit struct {
	// Rate is the maximum number of matching packets allowed per Unit.
	Rate uint
	// Unit is the time window Rate is counted over.
	Unit RateUnit
	// Burst is an optional allowance for bursts above Rate. 0 leaves the burst
	// at the backend default.
	Burst uint
}

RateLimit caps the rate at which a rule matches packets: up to Rate packets per Unit, with an optional Burst allowance. A nil *RateLimit on a Rule means no rate limiting. Backends that cannot express a rate limit reject a rule carrying one rather than applying it unlimited.

func (RateLimit) String

func (rl RateLimit) String() string

String renders the limit as "<rate>/<unit>" (e.g. "10/minute").

type RateUnit

type RateUnit uint8

RateUnit is the time unit a RateLimit is expressed over.

const (
	// PerSecond expresses a rate per second.
	PerSecond RateUnit = iota
	// PerMinute expresses a rate per minute.
	PerMinute
	// PerHour expresses a rate per hour.
	PerHour
	// PerDay expresses a rate per day.
	PerDay
)

func ParseRateUnit

func ParseRateUnit(s string) (RateUnit, error)

ParseRateUnit parses a rate-unit token, accepting the long, short and single-letter spellings the various backends emit (e.g. second/sec/s).

func (RateUnit) MarshalJSON

func (u RateUnit) MarshalJSON() ([]byte, error)

MarshalJSON renders the rate unit as its stable name (e.g. "minute").

func (RateUnit) String

func (u RateUnit) String() string

String returns the canonical (nftables-style) unit name.

func (*RateUnit) UnmarshalJSON

func (u *RateUnit) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a rate unit from its stable name.

type Rule

type Rule struct {
	// Direction is the traffic direction the rule applies to: DirInput,
	// DirOutput, DirForward or DirAny.
	Direction Direction
	// Priority orders this rule relative to others on backends that advertise
	// Capabilities().Priority.
	Priority int
	// Family is the IP family the rule targets. FamilyAny targets both and is
	// resolved from an address or ICMP protocol when left unset.
	Family Family
	// Source matches the packet's source address or CIDR. A leading "!" negates
	// the match, and a non-IP token names an address set where supported. Empty
	// matches any source.
	Source string
	// Destination matches the packet's destination address or CIDR, with the
	// same semantics as Source. Empty matches any destination.
	Destination string
	// Port is the single destination port to match; Ports takes precedence when
	// non-empty.
	Port uint16
	// Ports is a list of destination port ranges to match.
	Ports []PortRange
	// SourcePort is the single source port to match; SourcePorts takes
	// precedence when non-empty.
	SourcePort uint16
	// SourcePorts is a list of source port ranges to match.
	SourcePorts []PortRange
	// Proto is the network protocol the rule matches. ProtocolAny matches every
	// protocol.
	Proto Protocol
	// ICMPType, when set, restricts an ICMP/ICMPv6 rule to a single message
	// type. A nil pointer matches every type. It is only meaningful when Proto
	// is ICMP or ICMPv6.
	ICMPType *uint8
	// State restricts the rule to the given connection-tracking states. The
	// zero value applies no state match.
	State ConnState
	// InInterface matches the inbound interface the packet arrived on. Empty
	// matches any interface.
	InInterface string
	// OutInterface matches the outbound interface the packet leaves on. Empty
	// matches any interface.
	OutInterface string
	// Action is the action applied to matching packets.
	Action Action
	// Log, when set, logs each matched packet before the Action is applied.
	Log bool
	// LogPrefix is an optional label attached to the log line when Log is set.
	LogPrefix string
	// RateLimit caps the packet rate the rule matches; nil applies no limit.
	RateLimit *RateLimit
	// ConnLimit caps the concurrent connections the rule matches; nil applies
	// no limit.
	ConnLimit *ConnLimit
	// Packets is the per-rule packet counter, populated by GetRules on backends
	// that advertise Capabilities().RuleCounters.
	Packets uint64
	// Bytes is the per-rule byte counter, populated alongside Packets.
	Bytes uint64
	// Comment is an optional human-readable label stored alongside the rule on
	// backends that advertise Capabilities().Comments.
	Comment string
	// HasPrefix reports whether the rule carries the library's configured
	// prefix. It is derived on read and purely informational — the library
	// itself never branches on it.
	HasPrefix bool
	// Number is the rule's 1-based position within its chain, populated by
	// GetRules on backends that advertise Capabilities().RuleOrdering. It
	// mirrors the position argument of InsertRule and MoveRule.
	Number int
	// contains filtered or unexported fields
}

Rule is a firewall filter rule: a packet match and the action applied to matching packets. Its identity is the match fields and action; the derived fields (HasPrefix, Number, Packets, Bytes, Comment) describe how the backend stores or reports it and do not affect equality.

func (*Rule) CheckExpandedProtocol

func (r *Rule) CheckExpandedProtocol() error

CheckExpandedProtocol reports a TCPUDP rule reaching a row-level marshaller. TCPUDP is a merged, logical protocol: a backend with no both-transports form fans it into a tcp row and a udp row with expandProtocols before marshalling, so a TCPUDP rule arriving here means that fan-out was skipped. Backends whose native syntax does carry both transports in one row (nftables' `meta l4proto { tcp, udp }`) do not call it.

func (*Rule) CoveredBy

func (r *Rule) CoveredBy(rules []*Rule) bool

CoveredBy reports whether every concrete rule the receiver spans is covered by at least one rule in rules. It is the set form of Covers, and its inverse: where a.Covers(b) asks whether one rule contains another, b.CoveredBy([]*Rule{a}) asks whether a set contains one.

A rule that spans several axes is rarely stored as one object: GetRules reports the firewall's actual rows, so a rule the caller authored as FamilyAny may read back as an IPv4 row and an IPv6 row on a backend that cannot store one family-agnostic row. Such a rule is fully present in the set even though no single member Covers it, so coverage is decided cell by cell rather than rule by rule. A caller uses it to decide whether a rule is already installed before adding it.

It expands the receiver across family, transport, direction and ports and requires every resulting cell to be covered, so a rule spanning both transports is not reported present when only its TCP half is, and a port-list rule is not reported present when only some of its ports are. The receiver is not modified.

func (*Rule) Covers

func (r *Rule) Covers(o *Rule) bool

Covers reports whether the receiver's coverage contains o's: the same match in every ordinary field, with the receiver's family, transport, direction and port axes each spanning o's. FamilyAny spans both IP families, TCPUDP spans TCP and UDP, DirAny spans input and output, and a port list or range spans the ports it contains; a concrete value spans only itself. ProtocolAny is not a multi-state value — it matches every IP protocol — so it covers only ProtocolAny.

It is the exported form of the coverage relation the library reasons with. A caller holding a rule read back from GetRules uses it to tell whether that rule already contains one it is about to add, rather than re-deriving the per-axis rules. It is asymmetric: a TCPUDP rule covers its TCP half, never the reverse. Direction is always honored; a backend that has no output concept reports Capabilities().Output false and folds a DirAny rule to its input half on write.

func (*Rule) Equal

func (r *Rule) Equal(rule *Rule, outputSupported bool) bool

Equal reports whether two rules are the same. Family is compared through impliedFamily so a FamilyAny rule matches the concrete family its own content forces (an ICMP rule is IPv4, an ICMPv6 rule IPv6, an addressed rule its address's family). outputSupported is false on a backend with no output concept (Capabilities().Output), where direction does not distinguish two rules.

func (*Rule) EqualBase

func (r *Rule) EqualBase(rule *Rule, outputSupported bool) bool

EqualBase reports whether two rules are the same, ignoring family. outputSupported has Equal's meaning.

func (*Rule) EqualForDedup

func (r *Rule) EqualForDedup(o *Rule, outputSupported bool) bool

EqualForDedup reports whether the receiver (an existing rule) already makes o redundant on add: the same base rule, with the receiver's family, direction and transport (a TCPUDP row covers its tcp/udp halves) all covering o's. It is the family- and direction-aware add guard the container backends need because EqualBase ignores Family — without the coverage check, adding an IPv6 rule whose IPv4 twin already exists would be dropped as a false duplicate, leaving that family unprotected. Family and direction are checked first so a non-covering row skips the field compare. Coverage: a FamilyAny receiver covers either family, a DirAny receiver covers either direction; a concrete value covers only its own. The match fields are compared in the inbound frame (canonicalMatch) so a DirAny row and a concrete DirOutput target line up, with direction excluded from the field compare since coversDirection already gated it.

func (*Rule) EqualForRemoval

func (r *Rule) EqualForRemoval(o *Rule, outputSupported bool) bool

EqualForRemoval reports whether the receiver (an existing row) should be acted on when the caller targets o: the same base rule, and o's family, transport and direction each touch the row's. It is the overlap relation a removal walks the stored rows with: a target removes every row it covers, and also matches a row that covers more than the target, which the backend then deletes and re-adds minus the targeted cell (splitMergedRow). A FamilyAny/TCPUDP/DirAny target matches every row on that axis, such a row matches any target, and otherwise the values must match so acting on one twin never disturbs the other. The field compare runs in the inbound frame (canonicalMatch) with direction excluded, since the axis gates above already decided it.

func (*Rule) HasPortSet

func (r *Rule) HasPortSet() bool

HasPortSet reports whether the rule matches more than a single discrete port (a list, or a range spanning more than one port). Backends limited to a single port use this to reject rules they cannot represent.

func (*Rule) HasPorts

func (r *Rule) HasPorts() bool

HasPorts reports whether the rule matches on any destination port.

func (*Rule) HasSourcePortSet

func (r *Rule) HasSourcePortSet() bool

HasSourcePortSet reports whether the rule matches more than a single discrete source port.

func (*Rule) HasSourcePorts

func (r *Rule) HasSourcePorts() bool

HasSourcePorts reports whether the rule matches on any source port.

func (*Rule) IsForward

func (r *Rule) IsForward() bool

IsForward reports whether the rule is a forward (routing) rule.

func (*Rule) IsInput

func (r *Rule) IsInput() bool

IsInput reports whether the rule's direction is exactly input (inbound). It is a strict, single-direction test: a DirAny rule is not an input rule. Backends use it to route a rule to the input chain and to stamp read-back values, so it must not fire for DirAny; a DirAny rule reaches a per-chain path only after expandDirections has already split it into concrete rows. The both-directions coverage a DirAny rule spans is decided by coversDirection, not here.

func (*Rule) IsOutput

func (r *Rule) IsOutput() bool

IsOutput reports whether the rule's direction is exactly output (outbound). It is the strict output analog of IsInput; see that method for why a DirAny rule must not report true here.

func (*Rule) MatchesAny

func (r *Rule) MatchesAny(targets []*Rule) bool

MatchesAny reports whether the receiver is the same underlying rule as any of targets, honoring direction but ignoring the comment, which is not part of rule identity. It is the set form of Equal, and unlike CoveredBy it demands identity rather than coverage: a TCPUDP target does not match its TCP half. It backs comment-agnostic removal, where a stored row is acted on when it means the same rule as one the caller named, however that row was spelled or commented.

func (*Rule) OrphanLogMatchesAny

func (r *Rule) OrphanLogMatchesAny(targets []*Rule) bool

OrphanLogMatchesAny reports whether the receiver is a log-only row — a LOG rule whose action partner is gone, carried as Log with no action — belonging to a logged rule named by one of targets. A logged rule is stored as a LOG row plus the action row under it; when the action row is edited away by hand the stray LOG row no longer reads back as a rule, and this is how a removal still claims it. It reports false for any receiver that carries an action, so a complete rule is matched by MatchesAny alone.

func (*Rule) PortNeedsConcreteProtocol

func (r *Rule) PortNeedsConcreteProtocol() bool

PortNeedsConcreteProtocol reports whether the rule specifies a destination or source port without a concrete port-carrying protocol (TCP/UDP/SCTP). Most firewall backends cannot express a port match without such a protocol, so they use this to reject such a rule rather than silently widening it (matching every protocol) or emitting an invalid rule. A ported `any` in a ufw tuple is not this shape: it means tcp+udp and is modeled as TCPUDP.

func (*Rule) PortSpecs

func (r *Rule) PortSpecs() []PortRange

PortSpecs returns the rule's destination ports as a normalized list of ranges: Ports when set, otherwise the single Port, otherwise nil.

func (*Rule) SourcePortSpecs

func (r *Rule) SourcePortSpecs() []PortRange

SourcePortSpecs returns the rule's source ports as a normalized list of ranges: SourcePorts when set, otherwise the single SourcePort, otherwise nil.

type SetType

type SetType uint8

SetType names the kind of entries an AddressSet holds.

const (
	// SetHashIP is a set of individual IP addresses.
	SetHashIP SetType = iota
	// SetHashNet is a set of CIDR network ranges.
	SetHashNet
)

func ParseSetType

func ParseSetType(s string) (SetType, error)

ParseSetType parses a set-type token (case-insensitive), accepting the canonical name emitted by SetType.String ("hash:ip"/"hash:net") plus the short aliases "ip"/"net". An unknown value is an error.

func (SetType) MarshalJSON

func (t SetType) MarshalJSON() ([]byte, error)

MarshalJSON renders the set type as its stable name (e.g. "hash:net").

func (SetType) String

func (t SetType) String() string

String returns the ipset-style name of the set type.

func (*SetType) UnmarshalJSON

func (t *SetType) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a set type from its stable name.

type UFW

type UFW struct {
	// contains filtered or unexported fields
}

UFW manages a host firewall through the ufw command-line tool and its rules files.

func NewUFW

func NewUFW(ctx context.Context, rulePrefix string) (*UFW, error)

NewUFW connects to ufw, verifies it is enabled, and returns a manager for it.

func (*UFW) AddAddressSet

func (f *UFW) AddAddressSet(ctx context.Context, set *AddressSet) error

AddAddressSet creates an address set.

func (*UFW) AddAddressSetEntry

func (f *UFW) AddAddressSetEntry(ctx context.Context, name, entry string) error

AddAddressSetEntry adds an entry to an address set.

func (*UFW) AddNATRule

func (f *UFW) AddNATRule(ctx context.Context, zoneName string, r *NATRule) error

AddNATRule adds a NAT rule to the zone.

func (*UFW) AddRule

func (f *UFW) AddRule(ctx context.Context, zoneName string, r *Rule) error

AddRule adds a filter rule to the zone.

func (*UFW) Backup

func (f *UFW) Backup(ctx context.Context, zoneName string) (*Backup, error)

Backup captures the current filter and NAT rules managed by this backend.

func (*UFW) Capabilities

func (f *UFW) Capabilities() Capabilities

Capabilities reports the features this backend supports.

func (*UFW) Close

func (f *UFW) Close(ctx context.Context) error

Close releases any resources held by the backend.

func (*UFW) GetAddressSet

func (f *UFW) GetAddressSet(ctx context.Context, name string) (*AddressSet, error)

GetAddressSet returns the named address set.

func (*UFW) GetAddressSets

func (f *UFW) GetAddressSets(ctx context.Context) ([]*AddressSet, error)

GetAddressSets returns all managed address sets.

func (*UFW) GetDefaultPolicy

func (f *UFW) GetDefaultPolicy(ctx context.Context, zoneName string) (*DefaultPolicy, error)

GetDefaultPolicy returns the default filter policy for each direction.

func (*UFW) GetNATRules

func (f *UFW) GetNATRules(ctx context.Context, zoneName string) ([]*NATRule, error)

GetNATRules returns the current NAT rules for the zone.

func (*UFW) GetRules

func (f *UFW) GetRules(ctx context.Context, zoneName string) (rules []*Rule, err error)

GetRules returns the existing filter rules from the zone: ufw's own numbered tuples from user.rules and user6.rules, then the raw iptables rules from the before.rules files, which carry the matches the tuple format cannot express.

func (*UFW) GetZone

func (f *UFW) GetZone(ctx context.Context, iface string) (zoneName string, err error)

GetZone reports no zone; ufw has no zone support.

func (*UFW) InsertNATRule

func (f *UFW) InsertNATRule(ctx context.Context, zoneName string, position int, r *NATRule) error

InsertNATRule positions a NAT rule within ufw's before.rules nat table, reusing the iptables helper's insert machinery.

func (*UFW) InsertRule

func (f *UFW) InsertRule(ctx context.Context, zoneName string, position int, r *Rule) error

InsertRule inserts rule before the given 1-based position using `ufw insert`. position <= 0 is treated as 1; a position larger than the current rule count appends the rule (ufw itself rejects an out-of-range position, so that case falls back to a plain add).

func (*UFW) MarshalRule

func (f *UFW) MarshalRule(r *Rule) string

MarshalRule encodes a firewall rule into a ufw rulespec. It validates nothing: the entry points run Rule.validate and then route every shape the tuple cannot carry elsewhere — ICMP/SCTP, a state match, a custom log prefix, a connection limit, a non-native rate limit and a negated or ipset address go to the before.rules files (needsIPTablesRules), while a portless or multiport tcp+udp match fans out into concrete tcp and udp rules (tcpudpNeedsExpand).

func (*UFW) MoveNATRule

func (f *UFW) MoveNATRule(ctx context.Context, zoneName string, r *NATRule, position int) error

MoveNATRule repositions a NAT rule within ufw's before.rules nat table, reusing the iptables helper's move machinery.

func (*UFW) MoveRule

func (f *UFW) MoveRule(ctx context.Context, zoneName string, r *Rule, position int) error

MoveRule repositions an existing rule. ufw has no native move verb, so a move is a positional delete-then-insert: the rule is removed and re-inserted at the requested slot. It is therefore not atomic — if the re-insert fails the rule is left removed. A position larger than the rule count moves the rule to the end (via InsertRule's append fallback).

func (*UFW) ParseIPTablesRules

func (f *UFW) ParseIPTablesRules(filePath string, family Family) (rules []*Rule, err error)

ParseIPTablesRules parses a ufw before/after rules file, which is in iptables-restore format using ufw's own chains. Each `-A <chain> ...` line in the filter table on an input/output/forward chain is reparsed with the iptables rulespec parser, a logged rule's LOG and action lines folding back into one rule; lines whose match or action this model cannot represent are skipped by the scan.

func (*UFW) ParseRules

func (f *UFW) ParseRules(filePath string, family Family) (rules []*Rule, err error)

ParseRules reads a ufw rules file and returns the rules it models, in file order.

func (*UFW) Reload

func (f *UFW) Reload(ctx context.Context) error

Reload re-applies edits to the iptables rules files; rules added through the ufw CLI apply immediately, but edits to those files only take effect after a reload. Address sets are staged the same way this backend's raw iptables rules are, so they are loaded here too: the sets first, so a rule matching on one resolves when ufw reloads, and the destroys owed for removed sets last, once the rules that referenced them are gone.

func (*UFW) RemoveAddressSet

func (f *UFW) RemoveAddressSet(ctx context.Context, name string) error

RemoveAddressSet removes the named address set.

func (*UFW) RemoveAddressSetEntry

func (f *UFW) RemoveAddressSetEntry(ctx context.Context, name, entry string) error

RemoveAddressSetEntry removes an entry from an address set.

func (*UFW) RemoveNATRule

func (f *UFW) RemoveNATRule(ctx context.Context, zoneName string, r *NATRule) error

RemoveNATRule removes a NAT rule from the zone.

func (*UFW) RemoveRule

func (f *UFW) RemoveRule(ctx context.Context, zoneName string, r *Rule) error

RemoveRule removes a filter rule from the zone.

func (*UFW) Restore

func (f *UFW) Restore(ctx context.Context, zoneName string, backup *Backup) error

Restore replaces the managed rules with the contents of a Backup.

func (*UFW) SetDefaultPolicy

func (f *UFW) SetDefaultPolicy(ctx context.Context, zoneName string, policy *DefaultPolicy) error

SetDefaultPolicy sets the default filter policy for each direction.

func (*UFW) Type

func (f *UFW) Type() string

Type returns the backend identifier for ufw.

func (*UFW) UnmarshalRule

func (f *UFW) UnmarshalRule(tuple string, family Family) (r *Rule, err error)

UnmarshalRule decodes a ufw tuple into a firewall rule. A ufw tuple carries six core fields (action, proto, dport, dst, sport, src), an optional pair of application-name fields (dapp, sapp), and a trailing direction/interface field, so a tuple ufw itself writes has 7 tokens, or 9 for the application-profile form; a bare 6-token tuple (direction/interface omitted, defaulting to inbound) is also accepted here for tolerance, though ufw does not generate one. An application-profile rule's six core fields already carry the concrete proto/port the profile expands to (e.g. `allow tcp 80 ... Apache - in`) — dapp and sapp are just the profile's name, informational labels this library has no field for, so they are parsed to locate the trailing direction field and then discarded; the rule decodes exactly like an ordinary 7-token tuple otherwise. An 8-token tuple is ufw's old storage format (six core fields plus dapp/sapp with no direction field), which this library does not model; it is rejected so the row stays opaque and is preserved verbatim.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址