rules
rules
¶
nftables ruleset generation and verification.
Generates per-container nftables rulesets as an ordered tier policy and provides set operations for runtime allow/deny/override management, plus verification of applied rulesets against security invariants.
The UP ruleset is a single output chain whose body is an ordered list of
tier rules. nft evaluates them top to bottom: an accept/reject is a
terminal verdict (short-circuit), and a non-match falls through to the next
tier (a Pass). Tier order is the authority order::
preamble accept lo / established / DNS / infra ports
t00 hard-deny reject the host's loopback + @HARD_DENY_RANGES (absolute)
t10 override accept @override (break-glass, above the deny)
t20 security-deny reject @deny + @PRIVATE_RANGES (vault hosts + RFC1918)
t30/40 allow accept @allow (provider + project)
bypass window accept @bypass_window (kernel-timed allow-all)
terminal reject (log BLOCKED)
Because the deny tier sits above the allow tier, an explicit deny wins over an allow; an override (t10) sits above the deny and is the only way to reach a security-denied host. The hard-deny floor (t00) sits above the override and is absolute: link-local and IMDS, and the host's own loopback past the ports the preamble opens — the slirp4netns gateway, which lies in a private range and would otherwise be refused only below t10. An override that carries an expiry is an element with a kernel timeout, like the bypass window's: the kernel ends the break-glass on time, with nothing in userspace keeping the clock.
The DOWN postures accept by policy instead of refusing. They keep the UP
order down to the allow tiers (DISENGAGED drops every reject from it) and end
in a catch-all that logs DOWN — so a DOWN line is precisely a
connection the UP chain would have refused::
preamble accept lo / established / DNS / infra ports
t00 hard-deny reject host loopback + ranges (plain DOWN only)
t10 override accept @override (logged ALLOWED)
t20 security-deny reject @deny + @PRIVATE_RANGES (plain DOWN only)
t30/40 allow accept @allow (logged ALLOWED)
catch-all log DOWN, then the accept policy
Security boundary: only stdlib + nft.constants imports. All inputs are
validated before interpolation into nft commands.
RulesetBuilder(*, dns=PASTA_DNS, loopback_ports=(), gateway_v4='', gateway_v6='', set_timeout='')
¶
Builder for nftables ruleset generation and verification.
Security boundary: only stdlib + nft.constants imports. All inputs validated before interpolation.
Binds dns, loopback_ports, gateways, and the dnsmasq set timeout
once at construction so callers do not repeat them on every call.
Create a builder with validated DNS, gateway, and port config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dns
|
str
|
DNS server address (pasta default forwarder). |
PASTA_DNS
|
loopback_ports
|
tuple[int, ...]
|
TCP ports to allow on the host-loopback map address. |
()
|
gateway_v4
|
str
|
IPv4 gateway address (e.g. slirp4netns |
''
|
gateway_v6
|
str
|
IPv6 gateway address (e.g. slirp4netns |
''
|
set_timeout
|
str
|
dnsmasq-tier element timeout for the allow sets (e.g. |
''
|
Source code in src/terok_shield/nft/rules.py
build_up()
¶
Generate the UP (deny-all + ordered tiers) ruleset.
Applied by the OCI hook into the container's own netns. Dual-stack. Infra ports (DNS, host-loopback proxy, gateway) are accepted in the preamble before any tier, so the control plane survives the hard-deny of link-local space. See the module docstring for the tier order.
Source code in src/terok_shield/nft/rules.py
build_down(*, disengaged=False)
¶
Generate the DOWN-posture (manual shield down) ruleset.
Output policy is accept. Plain DOWN still enforces the hard-deny
floor — the host's own loopback past its ports included — and the
security-deny tier (deny set + private ranges), with the t10 override
kept above the deny — a break-glass host must stay reachable in
every posture that enforces the deny.
The allow tiers (t10 override, t30 provider, t40 project) accept
logged ALLOWED before the catch-all, exactly as UP would, so the
catch-all's DOWN line is left for what the UP posture would have
refused: a new connection accepted only because the shield is down.
That is what makes a task running DOWN harvestable — the reader
records each DOWN line as a promotion candidate. The timed
window has no place here: it only ever widens UP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
disengaged
|
bool
|
If True (DISENGAGED), enforce nothing: no hard-deny
floor, no deny set, no private-range rejects — every
destination is accepted. The allow tiers still accept
|
False
|
Source code in src/terok_shield/nft/rules.py
build_quarantine()
staticmethod
¶
Generate the quarantine-mode (total blackout) ruleset.
Drops all traffic except loopback and established connections. No DNS, no allowlists, no gateway ports. All dropped packets are tagged for the audit log.
Source code in src/terok_shield/nft/rules.py
verify_up(nft_output)
¶
Check applied UP ruleset invariants. Returns errors (empty = OK).
Expects output from nft list table inet terok_shield (scoped to the
managed table), not nft list ruleset. Verifies the table header,
policy drop, both chains, the reject type, every tier set, the
terminal deny-all rule, both range-reject floors and — for a builder
that knows the slirp4netns gateway — the host-loopback reject above
t10. It also checks that the timed window, if open, is timed: a window
element with no timeout is a permanent allow-all below the deny tiers,
so a ruleset carrying one is not the UP posture, whatever else it holds.
Source code in src/terok_shield/nft/rules.py
verify_down(nft_output, *, disengaged=False)
¶
Check applied DOWN-posture ruleset invariants. Returns errors (empty = OK).
Verifies the table header, policy accept on output / drop on
input, both chains, every tier set, and the DOWN nflog prefix.
Plain DOWN must carry both range-reject floors, and the host-loopback
reject when the builder knows the slirp4netns gateway; DISENGAGED
must carry neither floor nor the deny-set reject — a partially applied
ruleset that keeps any reject must not pass as DISENGAGED.
The ALLOWED accepts ahead of the catch-all are left unchecked on
purpose: they decide what the audit trail records, not what the
posture enforces, and a DOWN table applied before they existed is
still the DOWN posture — shield_state
must keep naming it so rather than report an error.
Source code in src/terok_shield/nft/rules.py
verify_quarantine(nft_output)
staticmethod
¶
Check applied quarantine ruleset invariants. Returns errors (empty = OK).
Verifies the table header, both chains with policy drop, the blocked
log prefix, and that no allow sets exist (total blackout).
Source code in src/terok_shield/nft/rules.py
add_elements_dual(ips)
¶
Add IPs to the tier-40 project-allow sets, honouring the dnsmasq permanent-element rule.
When a set_timeout is configured (live tier), profile/live IPs are
written with timeout 0s so they do not auto-expire with the
dnsmasq-learned entries.
Source code in src/terok_shield/nft/rules.py
add_elements_dual(ips, *, permanent=False)
¶
Add IPs to the tier-40 project-allow sets, split by address family.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
permanent
|
bool
|
annotate elements with |
False
|
Source code in src/terok_shield/nft/rules.py
add_deny_elements_dual(ips)
¶
Add IPs to the tier-20 security-deny sets, split by address family.
add_override_elements_dual(ips, *, timeouts=None)
¶
Add IPs to the tier-10 override (break-glass) sets, split by address family.
timeouts gives an element the whole seconds its override has left, so the kernel drops it on its expiry with nothing in userspace keeping time — the way the bypass window closes. An address absent from timeouts is added without one: an override that never expires.
Source code in src/terok_shield/nft/rules.py
flush_override_sets()
¶
Empty both tier-10 override sets — the head of a reseed that swaps the whole tier at once.
Sent in one transaction with the new elements, a flush never leaves the tier empty in between, and a re-added address takes its new timeout even on a kernel that keeps an existing element's timeout on a plain add.
Source code in src/terok_shield/nft/rules.py
delete_deny_elements_dual(ips)
¶
Remove IPs from the tier-20 security-deny sets, split by address family.
arm_bypass_window(timeout)
¶
Open the timed allow-all window.
Adds 0.0.0.0/0 / ::/0 to the bypass_window sets with a kernel
timeout so the window closes itself when the element expires — no
userspace timer, fail-closed (any disruption only closes it sooner).
The sets are flushed first, in the same transaction: a re-arm then always
replaces the countdown, even on a kernel that keeps an existing element's
timeout on a plain add — so bypass --for 1m while a two-hour window is
open shortens it, as it says.
Raises:
| Type | Description |
|---|---|
ValueError
|
When timeout is not an nft timeout, or is zero — nft
reads |
Source code in src/terok_shield/nft/rules.py
disarm_bypass_window()
¶
Close the timed allow-all window immediately by flushing both sets.
parse_window_expiry(nft_output)
¶
Whole seconds left on the timed allow-all window, read from an nft -T table listing.
Reads only the set bypass_window_v4 { … } block: the listing carries
every tier set ahead of the window, and on the live tier the t40 set's
learned addresses print countdowns of their own, so the first
expires in the listing is rarely the window's. -T prints the
countdown in whole seconds (expires 299s) — seconds are the smallest
unit the shield reports — and that is the only form read. A plain
listing's compound countdown (4m59s693ms) is not mistaken for
seconds, 512ms least of all: it reads as no countdown, which is why
the posture listing always carries -T.
Returns None when the set holds no element, or the listing has no
window set at all: the kernel clock is the window's only record, so an
empty set means closed rather than unknown. An element with no timeout
at all — a permanent allow-all, which the shield never adds — has no
countdown either; verify_up
refuses a listing that holds one, so it never reads as UP with the
window closed.
Source code in src/terok_shield/nft/rules.py
parse_set_elements(nft_output)
¶
Parse nft list set output into (ip, timeout) pairs.
timeout is the element's printed timeout token ("30m", "0s",
compound "1h22m") or "" when the element carries none. The
remaining expires countdown is deliberately dropped — a restore via
restore_elements re-grants
the full timeout. Atoms that fail validation are skipped rather than
raised: the snapshot/restore path is best-effort by design (a dropped
learned IP is re-learned on the workload's next DNS answer), and a
parse quirk must never abort a shield state transition.
Source code in src/terok_shield/nft/rules.py
restore_elements(set_name, elements, table=NFT_TABLE)
¶
Generate an nft command re-adding dumped (ip, timeout) elements.
Counterpart of parse_set_elements:
every input is re-validated before interpolation (the snapshot crosses a
subprocess boundary, so it is treated as untrusted like any other input).
Timed elements are re-granted their full timeout. Returns "" when
there is nothing to restore.
Source code in src/terok_shield/nft/rules.py
add_elements(set_name, ips, table=NFT_TABLE, *, timeout_zero=False, timeouts=None)
¶
Generate an nft command to add validated IPs to a set.
Both set_name and table are validated against injection.
Returns empty string if no valid IPs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout_zero
|
bool
|
annotate each element with |
False
|
timeouts
|
Mapping[str, int] | None
|
per-address kernel timeouts in whole seconds (keys in any
notation |
None
|
Source code in src/terok_shield/nft/rules.py
delete_elements(set_name, ips, table=NFT_TABLE)
¶
Generate an nft command to delete validated IPs from a set.
Both set_name and table are validated against injection.
Returns empty string if no valid IPs.
Source code in src/terok_shield/nft/rules.py
safe_ip(value)
¶
Validate and normalize an IPv4 or IPv6 address or CIDR notation.
Prevents nft command injection by ensuring the value is a valid IP address or network. Returns the canonical string form so comparisons across state files are reliable regardless of input notation.
Raises ValueError on invalid input.