firewall

package
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: MIT Imports: 13 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.

Documentation

Overview

Package firewall is a cross-backend abstraction for host packet-filter management. It is a general-purpose Go library: nothing in the package is specific to any one consumer. Callers construct a Manager for an explicit backend, a namespace of their choosing, and an injected command exec.Runner; every subsequent operation is scoped to that namespace.

Manager + namespace

Identity has two parts: the Manager's namespace and each Rule's ID. The namespace is set at construction (New) and isolates one consumer's rules from every other consumer's rules on the host. Two libraries linked into the same Go process, each constructing their own Manager with their own namespace, will not see each other's rules and cannot accidentally mutate them.

r, _ := exec.NewRunner(exec.Sudo)
mgr, err := firewall.New(firewall.Nftables, "myapp", r)
if err != nil { ... }
mgr.ApplyRule(ctx, firewall.Rule{
    ID:       "allow-https",
    Allow:    true,
    Protocol: firewall.ProtocolTCP,
    Port:     443,
})

Rule.ID is opaque to the SDK. Pick whatever scheme fits the application — a per-rule ULID, a hierarchical path, a UUID, a hash. The only constraint is the safe-identifier regex (`^[a-z0-9][a-z0-9_-]{0,62}$`) so the value round-trips through every backend's native annotation field without per-backend escaping.

Multi-rule actions / batches are first-class: a single caller can install N rules under one namespace just by issuing N ApplyRule calls with distinct IDs.

Backends

v1 ships three concrete backends. Pass the chosen one to New; Detect reports which are usable on the current host (it lists, it never picks).

  • Nftables — talks to the kernel directly via nft(8). Each Manager owns a dedicated `inet <namespace>_filter` table. Use on hosts where no higher-level firewall manager is active (Debian without ufw, Arch, NixOS, minimal base installs).

  • Firewalld — talks to the firewalld daemon via firewall-cmd. firewalld is the authoritative manager on RHEL/Fedora/CentOS Stream; writing raw nft rules behind its back gets blown away on the next reload. Each Rule materialises as a custom service `<namespace>-<id>.xml` in the default zone. v1 scope is narrow: allow-only, concrete tcp/udp, port — no source/dest scoping (an out-of-scope rule returns ErrInvalidRule).

  • UFW — talks to ufw via the ufw(8) CLI. ufw is the standard manager on Debian/Ubuntu desktops and many container hosts. Identity is the rule's native `comment` field, formatted `<namespace>:<id>`. v1 scope is broader than firewalld: allow + deny, source/dest scoping, and the long-form syntax all round-trip.

Backend selection is explicit per Manager (no process-global selector): the caller decides — usually from Detect plus its own configuration — and passes the value to New. The zero value and any unimplemented backend are rejected with ErrUnknownBackend.

Idempotency

Rule.ID is the key every backend uses to find a previously installed rule. Manager.ApplyRule with an existing ID updates the rule in place (delete-then-add inside a single atomic operation where the backend supports it). Manager.RemoveRule on a missing ID is a no-op — the post-condition "this rule is absent" already holds.

Manager.List returns every rule the Manager owns. Rules outside the Manager's namespace — system-installed defaults, rules owned by a different Manager, operator-added rules — are not returned. Inspecting the surface is safe: callers can iterate List output and remove or update entries without clobbering something they didn't install.

Error model

Three sentinels callers branch on:

  • ErrUnknownBackend — New was given the zero value or a backend the SDK does not implement.

  • ErrInvalidRule — the Rule can't be expressed by the active backend (a deny rule on firewalld v1, a port without a concrete protocol on nftables/ufw) or the ID fails validation. The wrapped message names the offending field.

  • ErrInvalidNamespace — the namespace passed to New fails validation.

Manager.List additionally distinguishes absence from emptiness. When the namespace was never provisioned (the nftables backend's table does not exist yet) List returns a wrapped io/fs.ErrNotExist, never an empty slice — so a caller can never confuse "this namespace has never been set up" with "set up, currently holding zero rules". Callers that want absent-treated-as- empty opt in explicitly with errors.Is(err, fs.ErrNotExist). A backend whose firewall is installed-but-empty (an inactive ufw, an empty firewalld zone) returns a nil slice and nil error — that is genuine emptiness, not absence.

When a backend's CLI tool fails for any other reason — escalation denied, the tool absent, a crash — the wrapped error carries an exec.CommandError with the exit code and stderr. List never reports such a failure as "zero managed rules"; it propagates. Do not collapse these into a sentinel.

Concurrency

A Manager is safe for concurrent use by multiple goroutines, but the CLI tools each backend calls (nft, firewall-cmd, ufw) are not themselves guaranteed reentrant, so simultaneous mutations from many goroutines may serialise inside the OS.

Privilege

Every backend's mutating calls go through the injected exec.Runner with escalation requested, so the consumer's configured privilege backend (sudo, doas, or direct-root) is honoured. The package never shells out directly.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidNamespace = errors.New("invalid firewall namespace")

ErrInvalidNamespace is returned by New when the namespace fails validation.

View Source
var ErrInvalidRule = errors.New("invalid firewall rule")

ErrInvalidRule is returned by Manager methods when a Rule fails validation — the backend-independent checks (ID/port/protocol/addr) or a backend-specific scope limit (e.g. a deny rule on the firewalld v1 backend).

View Source
var ErrUnknownBackend = errors.New("firewall: unknown backend")

ErrUnknownBackend is returned by New for the zero value or any Backend the SDK does not implement (fail-closed).

Functions

This section is empty.

Types

type Backend

type Backend int

Backend selects the packet-filter framework the SDK targets. Passed explicitly to New; the zero value is invalid (New → ErrUnknownBackend). The never-implemented iptables/pf scaffolds are not ported; a real fourth backend is appended here when actually written.

const (
	// Nftables is Linux nftables via nft(8) — the modern framework iptables is
	// migrating toward. Each Manager owns a dedicated `inet <namespace>_filter`
	// table.
	Nftables Backend = iota + 1
	// Firewalld wraps firewall-cmd (Red Hat family). Each rule becomes a custom
	// service in the default zone. v1 scope: allow-only, concrete tcp/udp, port.
	Firewalld
	// UFW wraps ufw(8) (Debian/Ubuntu). Identity is the native comment field.
	UFW
)

func Detect

func Detect(ctx context.Context) []Backend

Detect reports the firewall backends usable on THIS host: Nftables when nft is on PATH, Firewalld when firewall-cmd is, UFW when ufw is. It lists; it never picks and never constructs a Manager. An empty slice means no usable manager.

The ctx is accepted for signature uniformity with the other capability Detect functions; the present probe is a pure PATH lookup.

func (Backend) String

func (b Backend) String() string

String renders the backend as its canonical tool name.

type Manager

type Manager interface {
	// ApplyRule installs or updates a rule (idempotent by Rule.ID). Returns
	// ErrInvalidRule for a rule the active backend can't express.
	ApplyRule(ctx context.Context, rule Rule) error
	// RemoveRule removes a rule by ID; a missing rule is a no-op.
	RemoveRule(ctx context.Context, id string) error
	// List returns every rule this Manager owns (namespace-scoped).
	List(ctx context.Context) ([]Rule, error)
	// Namespace returns the namespace this Manager was constructed with.
	Namespace() string
}

Manager owns a namespaced set of firewall rules. Two Managers with different namespaces are isolated: each one's List, ApplyRule, and RemoveRule only see and touch rules in its own namespace. Other rules on the host (system, operator-added, or owned by a different caller) stay invisible and untouched.

func New

func New(b Backend, namespace string, runner exec.Runner, _ ...Option) (Manager, error)

New constructs a Manager for the given backend and namespace, driven by runner. Pure: it validates inputs and does not probe the host (use Detect). The zero / unimplemented backend is rejected with ErrUnknownBackend, a bad namespace with ErrInvalidNamespace, and a nil runner with an error.

namespace must match `^[a-z][a-z0-9_]{0,30}$`. The 31-char cap and the 63-char Rule.ID cap together leave room for the separators every backend needs.

type Option

type Option func(*base)

Option is the functional-option type for backend-specific knobs (none today).

type Protocol

type Protocol string

Protocol names a network protocol for rule matching.

const (
	ProtocolTCP Protocol = "tcp"
	ProtocolUDP Protocol = "udp"
	ProtocolAny Protocol = ""
)

type Rule

type Rule struct {
	ID       string   // stable, namespace-scoped identifier
	Allow    bool     // true = allow, false = deny
	Protocol Protocol // tcp / udp / "" (any)
	Port     int      // 0 = any
	Source   string   // IPv4/IPv6 CIDR or address; empty = any
	Dest     string   // IPv4/IPv6 CIDR or address; empty = any
}

Rule describes a single allow-or-deny decision. The cross-backend surface stays intentionally minimal — implementations translate it into the backend's native grammar (chains + priorities for nft, zones + services for firewalld, numbered rules for ufw).

Idempotency: ID is the key every backend uses to find a previously installed rule. ApplyRule with an existing ID updates the rule in place; RemoveRule on a missing ID is a no-op. ID is opaque to the SDK — pick whatever scheme fits (a ULID, a UUID, a path, a hash). The on-host identity stored by every backend is derived from the Manager's namespace plus this ID, so two Managers with different namespaces never see each other's rules even with the same ID.

ID must match `^[a-z0-9][a-z0-9_-]{0,62}$` so it round-trips through nft comments, firewalld service names, and ufw comments without per-backend escaping.

Jump to

Keyboard shortcuts

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