terok_shield
terok_shield
¶
terok-shield: nftables-based egress firewalling for Podman containers.
Public API facade. The Shield class coordinates collaborators:
- HookMode (
hooks.mode) — per-container nft ruleset lifecycle - DnsResolver (
dns.resolver) — domain resolution and caching - ProfileLoader (
profiles) — allowlist profile composition - RulesetBuilder (
nft.rules) — nftables ruleset generation - AuditLogger (
audit) — per-container JSONL audit trail - CommandRunner (
run) — subprocess execution boundary
Core and support modules are imported lazily — from terok_shield
import ShieldConfig does not pull in nft, dnsmasq, or subprocess
helpers. Heavy imports are deferred until Shield is instantiated.
HOOK_ENTRYPOINT_NAME = 'terok-shield-hook'
module-attribute
¶
Canonical filename of the shield OCI hook entrypoint script.
Used (a) under ~/.local/share/containers/oci/hooks.d/ for user-wide
installation and (b) under each per-container state_dir after
Shield.pre_start() materialises it. Keeping both sites consuming
the same constant means renaming the entrypoint is a single edit.
COMMANDS = CommandTree((_lazy('status', 'Show shield configuration overview', 'observe:STATUS'), _lazy('prepare', 'Prepare shield and print podman flags', 'launch:PREPARE'), _lazy('run', 'Launch a shielded container via podman', 'launch:RUN'), _lazy('resolve', 'Resolve DNS profiles and cache IPs', 'launch:RESOLVE'), _lazy('allow', 'Allow a domain or IP for a container (live, or at its next start when stopped)', 'control:ALLOW'), _lazy('deny', 'Live-deny a domain or IP for a container', 'control:DENY'), _lazy('override', 'Open a break-glass override above the security tier until a date, or revoke it', 'control:OVERRIDE'), _lazy('down', 'Switch container to the DOWN posture (accept + log)', 'control:DOWN'), _lazy('up', 'Restore deny-all mode for a container', 'control:UP'), _lazy('bypass', 'Open, close or show the timed allow-all window for a container', 'control:BYPASS'), _lazy('reset', 'Forget DNS-learned allow state (back to authored policy seeds)', 'control:RESET'), _lazy('quarantine', 'Total network blackout (drop all, log dropped traffic)', 'control:QUARANTINE'), _lazy('rules', 'Show current nft rules for a container', 'control:RULES'), _lazy('harvest', 'Show what a container reached for (refusals, window and DOWN accepts)', 'observe:HARVEST'), _lazy('watch', 'Stream shield events — audit log, NFLOG packets, and DNS blocks on the dnsmasq tiers', 'stream:WATCH'), _lazy('simple-clearance', 'Terminal clearance fallback — prompts operator for each blocked connection (no D-Bus)', 'stream:SIMPLE_CLEARANCE'), _lazy('logs', 'Show audit log entries', 'observe:LOGS'), _lazy('profiles', 'List available shield profiles', 'observe:PROFILES'), _lazy('setup', 'Install global OCI hooks for restart persistence', 'launch:SETUP'), _lazy('check-environment', 'Check podman environment for compatibility issues', 'observe:CHECK_ENVIRONMENT'), _lazy('preview', 'Show ruleset that would be applied', 'control:PREVIEW')))
module-attribute
¶
logger = logging.getLogger(__name__)
module-attribute
¶
__version__ = _meta_version('terok-shield')
module-attribute
¶
__all__ = ['AllowResult', 'ArgDef', 'COMMANDS', 'CommandDef', 'DnsTier', 'EnvironmentCheck', 'ExecError', 'HOOK_ENTRYPOINT_NAME', 'HarvestEntry', 'HarvestReport', 'HooksInstaller', 'OverrideRevocation', 'RotationRisk', 'SecurityTierRefusal', 'Shield', 'ShieldConfig', 'ShieldMode', 'ShieldReading', 'ShieldRuntime', 'ShieldState', 'ensure_user_hooks_dir_configured', 'recorded_container_id', 'recorded_dns_tier', 'recorded_rotation_risk', 'user_hooks_dir_configured', 'validate_target']
module-attribute
¶
DnsTier
¶
Bases: Enum
How domain allowlists reach the nft allow sets.
dnsmasq with --nftset adds every answered address to the
allow sets before the reply reaches the workload. Follows IP rotation, covers subdomains, accepts wildcard entries, names blocked domains.
DNSMASQ_STATIC: a dnsmasq built without nftset support. The allow sets are
resolved once at launch; the query log still names blocked domains.
LOOKUP: no dnsmasq. The allow sets are resolved once at launch with
dig or drill.
GETENT: no dnsmasq and no lookup tool. The allow sets are resolved once
at launch with getent hosts.
DNSMASQ_LIVE = 'dnsmasq-live'
class-attribute
instance-attribute
¶
DNSMASQ_STATIC = 'dnsmasq-static'
class-attribute
instance-attribute
¶
LOOKUP = 'lookup'
class-attribute
instance-attribute
¶
GETENT = 'getent'
class-attribute
instance-attribute
¶
live
property
¶
True when the allow sets follow DNS answers as they arrive.
runs_dnsmasq
property
¶
True when a per-container dnsmasq serves the container's DNS.
hint
property
¶
What a degraded tier lacks and what restores the live one; empty for the live tier.
parse(recorded)
classmethod
¶
The tier a recorded name means; None for a name that is not a tier.
A retired name reads as the tier it named, so a container recorded under it restarts instead of being recreated.
Source code in src/terok_shield/config.py
OverrideRevocation(target, closed=(), kept=(), live=True)
dataclass
¶
What revoking a break-glass override closed, and when the revoke takes hold.
Returned by Shield.revoke_override.
An operator told that a break-glass ended needs two things a bare success
would hide. A running container drops the override at once, while a
stopped one only stops opening it at its next start. And an address the
override held can stay reachable above the security tier through another
override that covers it — a range, say — which a revoke of this one
leaves alone. So the addresses are split into the ones closed and the
ones still open.
Attributes:
| Name | Type | Description |
|---|---|---|
target |
str
|
The domain, IP or CIDR whose override ended, as its tier entry recorded it. |
closed |
tuple[str, ...]
|
The addresses the override held that no t10 element admits any more. |
kept |
tuple[str, ...]
|
The addresses the override held that another override still in force admits above the security tier, because it covers them. |
live |
bool
|
True when the container was running, so its ruleset no longer holds the override now; False when podman said no process runs for it — it is stopped, or gone — so the revoke applies from its next start. |
ShieldConfig(state_dir, mode=ShieldMode.HOOK, default_profiles=(), loopback_ports=(), audit_enabled=True, profiles_dir=None, runtime=ShieldRuntime.DEFAULT, dns_cache_dir=None, bypass_duration='5m', dnsmasq_path=None)
dataclass
¶
Per-container shield configuration.
The library is a pure function of its inputs. Given a
ShieldConfig with state_dir, it writes to that directory
and nowhere else. No env-var reading, no config-file parsing.
state_dir
instance-attribute
¶
mode = ShieldMode.HOOK
class-attribute
instance-attribute
¶
default_profiles = ()
class-attribute
instance-attribute
¶
Profiles to compose when a call's profiles argument is None; empty composes no profile.
loopback_ports = ()
class-attribute
instance-attribute
¶
audit_enabled = True
class-attribute
instance-attribute
¶
profiles_dir = None
class-attribute
instance-attribute
¶
runtime = ShieldRuntime.DEFAULT
class-attribute
instance-attribute
¶
dns_cache_dir = None
class-attribute
instance-attribute
¶
Resolved-allowlist cache shared across containers.
The one deliberate exception to the state_dir-only rule: many tasks with the
same allowlist share one resolve. None selects
dns_cache_dir under the shield state
root. Only the tiers that resolve at launch use it.
bypass_duration = '5m'
class-attribute
instance-attribute
¶
How long the timed allow-all window stays open when a caller names no duration.
An nft timeout (30s, 5m, 2h). The kernel closes the window when
the element expires, so nothing outlives the timeout it was opened with.
dnsmasq_path = None
class-attribute
instance-attribute
¶
The dnsmasq binary to run; None finds one on the current host PATH.
Set it for a dnsmasq built outside the distro package, for example one built with nftset support in the operator's home.
ShieldMode
¶
ShieldReading(state, bypass_remaining=None)
dataclass
¶
One reading of a container's live ruleset: its posture and its timed window.
Both come out of a single nft -T list table — the listing that
classifies the posture already holds the window set — so a caller that
shows both (a status line, a task pane) pays for one netns entry, not two,
and never pairs a posture with a window read a moment apart.
Attributes:
| Name | Type | Description |
|---|---|---|
state |
ShieldState
|
The posture the listing classifies as. |
bypass_remaining |
int | None
|
Whole seconds left on the timed allow-all window
( |
ShieldRuntime
¶
Bases: Enum
Container runtime category — drives DNS-reachability assumptions.
crun / runc / youki. The container shares the netns,
so dnsmasq on 127.0.0.1 is reachable directly.
KRUN: libkrun microVM. The guest has its own loopback isolated
from the netns, so dnsmasq must bind to a link-local address
on netns lo that the guest can reach via passt.
DEFAULT = 'default'
class-attribute
instance-attribute
¶
KRUN = 'krun'
class-attribute
instance-attribute
¶
from_runtime_name(name)
classmethod
¶
Map a podman --runtime <name> string (or None) to the enum.
Centralises the wire-format vocabulary so callers don't repeat
"krun" → KRUN mappings inline. Anything other than
"krun" (including None and unknown runtime names) maps
to DEFAULT — the loopback-shared-with-netns assumption holds
for every runtime shield has been tested against besides krun.
Source code in src/terok_shield/config.py
ShieldState
¶
Bases: Enum
Per-container shield state, derived from the live nft ruleset.
QUARANTINE: Total network blackout — all traffic dropped, dropped traffic logged. UP: Normal enforcing mode (deny-all with allowlists). DOWN: Accept-by-default posture, private-range protection retained (RFC 1918 + RFC 4193). DISENGAGED: Accept-everything posture — no deny set, no private-range or hard-deny reject. OFFLINE: No ruleset found (container stopped or unshielded). ERROR: Ruleset present but unrecognised.
confirmed_posture,
which a live allow and a revoke route on, keeps OFFLINE for a container podman says runs
no process — stopped, or gone. A running container whose ruleset could
not be read, or that carries none (unshielded), is ERROR there.
QUARANTINE = 'quarantine'
class-attribute
instance-attribute
¶
UP = 'up'
class-attribute
instance-attribute
¶
DOWN = 'down'
class-attribute
instance-attribute
¶
DISENGAGED = 'disengaged'
class-attribute
instance-attribute
¶
OFFLINE = 'offline'
class-attribute
instance-attribute
¶
ERROR = 'error'
class-attribute
instance-attribute
¶
RotationRisk(tier, allow=(), deny=(), override=())
dataclass
¶
Policy names the container's DNS tier pins to the addresses they resolved to.
A name the shield resolves itself — once at launch, again at most hourly
on a posture change — is enforced by those addresses only, and the
provider behind it can move to another at any time. What that costs
depends on the name's tier and on the posture, so the value keeps the
three kinds apart and words them per posture
(lines).
Computed on read from the bundle — the recorded DNS tier and the
authored policy (recorded_rotation_risk)
— so it never disagrees with what the container runs. IP and CIDR
entries cannot rotate and stable local names
(STABLE_LOCAL_NAMES) never
do, so neither is ever listed.
Attributes:
| Name | Type | Description |
|---|---|---|
tier |
DnsTier
|
The DNS tier the container launched with. |
allow |
tuple[str, ...]
|
Allowlisted names (t30, t40, runtime |
deny |
tuple[str, ...]
|
Denied names (t20, runtime |
override |
tuple[str, ...]
|
Break-glass names (t10), resolved once on every tier — the live tier included, since dnsmasq never populates the override set. An address they rotate to is not reached. |
tier
instance-attribute
¶
allow = ()
class-attribute
instance-attribute
¶
deny = ()
class-attribute
instance-attribute
¶
override = ()
class-attribute
instance-attribute
¶
lines(posture=None)
¶
The warning lines that matter in posture, worded for it.
posture None means a launch or restart: the container boots UP
and may be lowered afterwards, so every line counts and the deny line
names both ways out. In UP every line counts; in DOWN only the deny
line — accept-by-default makes a pinned allow moot, while the security
tier is still meant to hold; DISENGAGED enforces nothing, so nothing
is worth a word.
Source code in src/terok_shield/state.py
SecurityTierRefusal(target, *, entry, address='')
¶
Bases: RuntimeError
A grant the t20 security tier refuses: only a break-glass override reaches the target.
The security tier (policy/20-security-deny) holds what the
orchestrator denies direct egress to — the vault-relayed provider hosts,
above all. A live allow may lift the operator's own runtime deny, never
this tier: the one way past it is the t10 override, authored with a
reason and an expiry and sitting above the deny. Raised before anything
changes, so a refused allow leaves the ruleset and the bundle as they were.
Attributes:
| Name | Type | Description |
|---|---|---|
target |
The domain or IP the caller asked to allow. |
|
entry |
The security-tier name, address or range that refuses it. |
|
address |
The address the target shares with the tier, when the refusal is by address; empty when the name itself is refused. |
Record what was refused and by which entry; the message names a shared address.
Source code in src/terok_shield/state.py
HarvestEntry(action, target, count, first_seen, last_seen, ports, addresses, tier=TIER_ALLOWLIST, remedies=(REMEDY_TASK, REMEDY_PROJECT, REMEDY_SET))
dataclass
¶
One destination a task reached for, what the shield did, and what could change it.
action
instance-attribute
¶
What the shield did, as the reader recorded it: blocked — refused by
the terminal rule; bypass — let through by the timed allow-all window;
down — accepted only because the shield was down; security_deny —
refused by the t20 deny set; private_range — refused by a range floor.
target
instance-attribute
¶
The domain the reader recovered, or the address when it had none.
This is what a promotion would name, which is why it is the grouping key: an allowlist entry for a rotating CDN is worth nothing as an IP.
count
instance-attribute
¶
Audit lines seen for this target.
A floor on attempts, not a connection count: the reader records one line per target per 30 s, so a tight retry loop and a single request can both land as one.
first_seen
instance-attribute
¶
last_seen
instance-attribute
¶
ports
instance-attribute
¶
Destination ports, ascending — a promotion candidate on 443 and one on 25 deserve different scrutiny.
addresses
instance-attribute
¶
Addresses seen behind target, in first-seen order; empty when the target is itself an address.
tier = TIER_ALLOWLIST
class-attribute
instance-attribute
¶
The tier that stands between the task and the target: t40 when no
refusing tier claims it (the allowlist just does not name it),
t20_operator for the operator's own runtime deny, t20_security for
the security tier (vault-relayed hosts above all), t20_private for a
private range, t00 for the hard-deny floor. Read from the
destination against the container's bundle, so a down line from a
DISENGAGED shield lands in the tier that would refuse it once the shield
is back up. Defaults to the ordinary t40 case.
remedies = (REMEDY_TASK, REMEDY_PROJECT, REMEDY_SET)
class-attribute
instance-attribute
¶
What could let the task reach the target, in preference order: task
/ project (an allow), set (a curated or user set), override
(break-glass, with a reason and an expiry), host_port (a
+localhost:PORT grant for the host's own loopback — pasta's map or
the slirp4netns gateway, both refused in t00, above every override).
Empty for the rest of the hard-deny floor, which nothing reaches.
Defaults to the remedies of the ordinary t40 case.
HarvestReport(entries=(), audit_enabled=True)
dataclass
¶
What harvest found, and whether it could find anything.
An empty harvest means two different things depending on
audit_enabled: with audit on, the task reached for nothing it could
not have; with audit off, the reader recorded nothing to begin with, so
the emptiness says nothing about the task. A caller shows the second as
such rather than as an all-clear.
Iterating the report yields its entries, and its length is theirs, so a caller that only ever listed the entries reads it unchanged.
HooksInstaller(target_dir=_default_target_dir())
dataclass
¶
Persistent installation of terok-shield's OCI hook pair.
The createRuntime/poststop hook pair must persist across container
restarts: podman ≥ 5.x drops per-container --hooks-dir on
stop/start (containers/podman#17935), so global hooks are the
only reliable activation path until that upstream regression is
fixed.
Scripts, ballast, and JSON descriptors all land in target_dir
(default: namespace_state_dir("shield") / "hooks").
containers.conf is patched to register that path so podman
discovers the descriptors on the next container start.
Symmetric lifecycle: install
writes, uninstall
removes. Both are idempotent.
target_dir = field(default_factory=_default_target_dir)
class-attribute
instance-attribute
¶
Directory the hook scripts, ballast, and JSON descriptors all live in.
check_setup(*, live=False)
¶
Check Shield's receipt and hooks, optionally probing launch prerequisites.
Source code in src/terok_shield/hooks/install.py
install()
¶
Install global standalone hooks after preflight; certify only verified work.
Source code in src/terok_shield/hooks/install.py
uninstall()
¶
Remove every hook file install would write.
Idempotent — missing files are tolerated. containers.conf
is left untouched: other terok packages may still register
their own hooks_dir entries the operator wants to keep.
Source code in src/terok_shield/hooks/install.py
is_installed()
¶
True when target_dir carries the canonical createRuntime hook JSON.
Use check_setup for receipt, interpreter, and artifact validation.
Source code in src/terok_shield/hooks/install.py
ExecError(cmd, rc, stderr)
¶
Bases: Exception
Raised when a subprocess fails.
Store command details and format the error message.
Source code in src/terok_shield/run.py
EnvironmentCheck(dns_tier='', ok=True, podman_version=(0,), hooks='not-installed', health='ok', issues=list(), needs_setup=False, setup_hint='')
dataclass
¶
Result of Shield.check_environment.
Machine-readable fields for programmatic consumers (terok TUI, scripts).
Human-readable issues and setup_hint for CLI display.
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
True if no issues found. |
podman_version |
tuple[int, ...]
|
Detected podman version tuple. |
hooks |
str
|
Hook installation type ( |
health |
str
|
Environment health ( |
dns_tier |
str
|
Active DNS resolution tier, a |
issues |
list[str]
|
List of human-readable issue descriptions. |
needs_setup |
bool
|
True if one-time setup is required. |
setup_hint |
str
|
Setup instructions (empty if not needed). |
dns_tier = ''
class-attribute
instance-attribute
¶
ok = True
class-attribute
instance-attribute
¶
podman_version = (0,)
class-attribute
instance-attribute
¶
hooks = 'not-installed'
class-attribute
instance-attribute
¶
health = 'ok'
class-attribute
instance-attribute
¶
issues = field(default_factory=list)
class-attribute
instance-attribute
¶
needs_setup = False
class-attribute
instance-attribute
¶
setup_hint = ''
class-attribute
instance-attribute
¶
AllowResult(target, ips=(), live=True)
dataclass
¶
What Shield.allow granted, and when it takes effect.
A grant lands one of two ways, and a caller reporting it to an operator has to say which: a running container takes it live, a stopped one only at its next start.
Attributes:
| Name | Type | Description |
|---|---|---|
target |
str
|
The domain or IP the caller asked to allow. |
ips |
tuple[str, ...]
|
The addresses the running ruleset admits now. Empty when the grant waits for the next start — or when every live attempt failed, which a caller should treat as nothing allowed. |
live |
bool
|
True when the grant went to the container's running ruleset; False when podman said no process runs for the container — it is stopped, or gone — so the grant sits in its runtime overlay and applies at its next start. |
Shield(config, *, runner=None, audit=None, dns=None, profiles=None, ruleset=None, hub_events=None)
¶
Public API facade — coordinates collaborators per container.
Delegates to HookMode for netns/nft operations, DnsResolver
for name resolution, ProfileLoader for allowlists,
RulesetBuilder for ruleset generation, and AuditLogger for
the audit trail. All collaborators are injectable for testing.
Create the shield facade.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ShieldConfig
|
Shield configuration (must include state_dir). |
required |
runner
|
CommandRunner | None
|
Command runner (default: |
None
|
audit
|
AuditLogger | None
|
Audit logger (default: from config.state_dir). |
None
|
dns
|
DnsResolver | None
|
DNS resolver (default: from runner). |
None
|
profiles
|
ProfileLoader | None
|
Profile loader (default: from config.profiles_dir). |
None
|
ruleset
|
RulesetBuilder | None
|
Ruleset builder (default: from config loopback_ports). |
None
|
hub_events
|
HubEventEmitter | None
|
Best-effort emitter for |
None
|
Source code in src/terok_shield/__init__.py
config = config
instance-attribute
¶
runner = runner or SubprocessRunner()
instance-attribute
¶
audit = audit or AuditLogger(audit_path=StateBundle(config.state_dir).audit, enabled=config.audit_enabled)
instance-attribute
¶
dns = dns or DnsResolver(runner=self.runner, host_cache_dir=config.dns_cache_dir)
instance-attribute
¶
profiles = profiles or ProfileLoader(user_dir=config.profiles_dir or Path('/nonexistent'))
instance-attribute
¶
ruleset = ruleset or RulesetBuilder(loopback_ports=config.loopback_ports)
instance-attribute
¶
hub_events = hub_events or HubEventEmitter()
instance-attribute
¶
check_environment()
¶
Check the podman environment for compatibility issues.
Proactive check for API consumers (e.g. terok). Returns an
EnvironmentCheck with detected issues and setup hints.
Does not raise — the caller decides how to handle issues.
Source code in src/terok_shield/__init__.py
status()
¶
Return current shield status information.
pre_start(container, profiles=None, *, security_deny=(), provider_allow=(), project_allow=(), override=())
¶
Prepare shield for container start. Returns extra podman args.
The four tier arguments are the orchestrator-generated policy tiers, which shield writes into the bundle so callers pass data and never touch the layout: security_deny → t20 (vault hosts denied direct), provider_allow → t30 (provider egress), project_allow → t40 (git remote + custom, merged with the composed profiles), override → t10 (break-glass allow above the deny; a CIDR is accepted but logged as a warning).
Source code in src/terok_shield/__init__.py
refresh(container, profiles=None, *, security_deny=(), provider_allow=(), project_allow=(), override=())
¶
Recompute an existing container's policy bundle before a plain restart.
Same tier arguments as pre_start,
but for a container that already exists: rewrites the tiers and
static-resolution caches and regenerates the pre-applied artifacts
(ruleset.nft, dnsmasq config), so the next podman start
enforces current policy instead of the bundle frozen at creation.
Returns nothing — the container keeps its launch-time podman args.
Source code in src/terok_shield/__init__.py
allow(container, target)
¶
Allow a domain or IP for container: live when it runs, from its next start when not.
Tier authority is settled before anything changes. A target the t20
security tier refuses — that very host, a name under one of its
domains, or anything that resolves to one of its addresses — raises
SecurityTierRefusal and
nothing is granted, not even the addresses that were not shared: a
security-tier host is reachable through a break-glass override only.
The refusal lands in the audit trail as allow_refused.
A running container takes the grant live, address by address — an nft
failure is logged and skipped — and a domain also joins its dnsmasq
config, so the addresses the name rotates to follow. A stopped
container gets the target recorded in its runtime overlay instead, for
its next start to apply. The
AllowResult says which of the two happened.
A container counts as stopped only when podman says it has no process
— or has no such container, which a recreate under the same name
starts from the same bundle — never because its ruleset could not be
read: a running one whose listing failed, or that carries no ruleset,
takes the live path, where a failure is reported.
Raises:
| Type | Description |
|---|---|
SecurityTierRefusal
|
When the security tier refuses the target. |
ShieldNeedsSetup
|
A |
RuntimeError
|
When neither the ruleset nor podman says whether the container runs — with nothing changed — or a stopped container's bundle was never prepared by a launch. Also, on a running container with the addresses already added, when its dnsmasq cannot reload to follow the name. |
Source code in src/terok_shield/__init__.py
override(container, target, expires, *, reason)
¶
Break glass for target on a running container, valid through expires, for reason.
The one way past the security tier on a live task — direct reach to a
vault-relayed provider host, a LAN service in a private range — and
deliberately narrow: target joins the t10 override set with a kernel
timeout, so the kernel itself ends it when expires runs out (a date
holds through that day, host local time). Agents keep using the
vault for key relaying; the override only adds the direct route. The
hard-deny floor (link-local, cloud metadata) is never overridden, nor
is the host's own loopback, which a +localhost:PORT grant reaches.
A break-glass needs both a reason and an expiry, and the shield
enforces both: an empty reason is refused like a passed expires.
The reason is recorded on the tier entry and in the audit trail
(override), which takes the grant the moment the kernel does —
before the dnsmasq reload a domain needs, so a failed reload never
leaves a grant that holds without a record. The tier entry is
written only after that: the swap is computed from the tier as the
grant will leave it, held in memory, so the tier never records a
grant the kernel did not take. A grant and a
revoke_override never
interleave: each holds the container's t10 lock from its read of the
tier through its swap, and a grant resolves its names before taking
it, so a revoke never waits on a resolver.
The grant survives shield down/up, re-timed at each rebuild,
until it expires or the next restart re-derives the tier from the
orchestrator's policy — persist it there (shield.override) for it
to outlive the task's run.
Returns:
| Type | Description |
|---|---|
list[str]
|
The addresses opened: the target itself for an IP or a CIDR. |
Raises:
| Type | Description |
|---|---|
ValueError
|
For a target no override can carry, an expires that is no date or already passed, or an empty reason. |
RuntimeError
|
When container has no running ruleset to take it, or the target resolves to no address — or, with the grant already holding in the kernel, when the tier or the override cache cannot record it (the message says what the next rebuild seeds in its place) or dnsmasq cannot reload to open the name. |
Source code in src/terok_shield/__init__.py
revoke_override(container, target)
¶
End target's break-glass on container now, before its expiry runs out.
The way to close a door override
opened, or one the orchestrator authored as shield.override. Only
an override still in force can be revoked: a target with none, or
one whose expiry already passed, raises instead of passing for a
success.
The revoke is ordered to fail closed. The tier entry goes first, so
no shield down/up re-opens the override, and the files a
plain podman start replays are rewritten without it. Only then
is it dropped from the running ruleset's t10 set, in one nft
transaction that keeps every other override. A name's dnsmasq
sinkhole punch-through closes too. The revoke is audited as
override_revoked once nothing running holds the override. A
stopped container's bundle is rewritten for its next start — and a
container counts as stopped only when podman says it has no process,
or has no such container, never because its ruleset could not be read.
A revoke stops new connections; connections already open keep running until they close, as they do when the override expires. It holds until the next restart re-derives the tier from the orchestrator's policy: an override authored there comes back unless it is removed there too.
Returns:
| Type | Description |
|---|---|
OverrideRevocation
|
|
OverrideRevocation
|
naming the addresses closed, those another override still holds |
OverrideRevocation
|
open, and whether the container was running. |
Raises:
| Type | Description |
|---|---|
ValueError
|
For text that is no domain, IP or CIDR, and for
|
RuntimeError
|
When target has no override in force, or neither the ruleset nor podman says whether the container runs — with nothing changed, in both cases. Also, with the record already gone, when nft cannot drop it from the running ruleset, or no dnsmasq reloads to sinkhole its name again — the message says which. |
Source code in src/terok_shield/__init__.py
deny(container, target)
¶
Live-deny a domain or IP for a running container.
Source code in src/terok_shield/__init__.py
rules(container)
¶
down(container, container_id, *, disengaged=False)
¶
Switch a running container to the DOWN posture.
container is the operator-facing podman name (audit log key); container_id is the full podman UUID — the routing key for the per-container hub socket the supervisor listens on. The caller knows both at every emit site, so neither carries a default.
With disengaged, the container takes the DISENGAGED posture instead: nothing is enforced — no deny set, no private-range or hard-deny reject — and every new connection is only logged.
Source code in src/terok_shield/__init__.py
quarantine(container)
¶
Total network blackout — drop all traffic, log dropped traffic.
up(container, container_id)
¶
Restore normal deny-all mode for a running container.
container / container_id — see
down.
Source code in src/terok_shield/__init__.py
harvest()
¶
Summarise what this container reached for, from its audit log.
A read, not a policy change: the entries say what was refused, what the timed window let through and what the DOWN posture accepted only because the shield was down — each with the tier that stands in the way and the remedies that could lift it — and promoting any of them stays an explicit act elsewhere. The report also says whether audit was on for this container at all: with it off, the reader recorded nothing, and an empty harvest is no all-clear.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
The audit log exists but cannot be read. |
Source code in src/terok_shield/__init__.py
bypass(container, duration=None)
¶
Open the timed allow-all window and return the duration granted.
duration is an nft timeout; None takes
bypass_duration from the
config. The window lives in the kernel: it closes when the element
expires, a rebuild or a restart closes it sooner, and nothing renews it.
It accepts what the allowlist would refuse — never the security tier,
the private ranges or the hard-deny floor, which all sit above it in
the chain — and it opens in the UP posture only, the one chain that
reads it.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the container's posture is not UP. |
ValueError
|
When duration is not an nft timeout. |
Source code in src/terok_shield/__init__.py
bypass_off(container)
¶
Close the timed allow-all window before its timeout runs out.
bypass_remaining(container)
¶
Whole seconds left on the timed allow-all window, or None when none is open.
The window half of inspect; a caller
that also shows the posture reads both from that one listing instead.
Source code in src/terok_shield/__init__.py
inspect(container)
¶
Read container's posture and its timed window from one ruleset listing.
One nft -T list table inside the container's netns answers both, so
a surface showing both — a status line, a task pane — pays for one
listing, and the two are never read a moment apart. The countdown is
the kernel's own, in whole seconds, and reported only for UP: the one
posture whose chain reads the window set.
Source code in src/terok_shield/__init__.py
reset(container)
¶
Forget DNS-learned allow state, keeping the authored policy seeds.
The live tier accumulates every IP the workload legitimately
resolved; reset returns the allow sets to their just-launched
contents (policy literals only) without touching the deny tier or
the operator's runtime overlay.
Source code in src/terok_shield/__init__.py
state(container)
¶
preview(*, down=False, disengaged=False, profiles=None)
¶
Generate the ruleset that would be applied to a container.
profiles compose into the preview exactly as they would into a
launch (None means the config's default_profiles, as in
pre_start): their host-service
grants join the preamble and their literal IPs seed the allow set.
See HookMode.preview.
Source code in src/terok_shield/__init__.py
resolve(*, force=False)
¶
Re-resolve the container's authored policy into its static-resolution caches.
Refreshes the caches pre_start and
refresh fill — the allow cache on the
tiers without DNS interception, the t10 override cache and the two t20
deny caches (the security tier's, the runtime overlay's) — without
rewriting any tier. force re-resolves even
when a cache is fresh. Returns the resolved allow IPs; the
dnsmasq-live tier resolves per query, so it returns none.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When pre_start never completed for this state dir. |
Source code in src/terok_shield/__init__.py
profiles_list()
¶
tail_log(n=50)
¶
validate_target(target)
¶
Accept a domain (optionally *.-prefixed), an IP literal, or a CIDR.
The target grammar every policy line obeys, on its own: no action prefix,
no :port, no %markers. Public so a caller that keeps host lists
of its own (an orchestrator's named egress sets, a promotion target)
validates them by the same rule the shield will apply, instead of a copy
of the pattern that drifts. A caller that wants a narrower grammar — no
wildcards, no CIDRs — layers its own check on top.
Raises:
| Type | Description |
|---|---|
ValueError
|
When target is neither a domain, an IP literal, nor a CIDR. |
Source code in src/terok_shield/policy.py
recorded_container_id(state_dir)
¶
The short id of the container shielded from state_dir, as its OCI hook recorded it.
The 12-character short id is the one key every per-container surface
shares: the NFLOG reader stamps it on each event, and the clearance hub
keys its socket and its mute by it. A caller that holds only the state
dir — a task's orchestrator — names the container exactly as those
surfaces do, instead of by a podman name they have never seen. Thin
public wrapper over
StateBundle.read_container_id,
like recorded_dns_tier;
None until the container's first start.
Source code in src/terok_shield/state.py
recorded_dns_tier(state_dir)
¶
The DNS tier a shielded container launched with, read from state_dir.
Thin public wrapper over
StateBundle.read_dns_tier
so callers that only want the tier need not know the bundle layout.
Source code in src/terok_shield/state.py
recorded_rotation_risk(state_dir)
¶
What the DNS tier of the container shielded from state_dir pins to resolved addresses.
A file read — the recorded tier and the authored policy — computed on
read, so an orchestrator shows the same warning the shield logs without
a Shield or a container to ask: at launch, in a task pane, after a
posture change. Thin public wrapper over
StateBundle.read_rotation_risk,
like recorded_dns_tier; None
when nothing is at risk or nothing was recorded.
Source code in src/terok_shield/state.py
ensure_user_hooks_dir_configured(hooks_dir=None)
¶
Ensure ~/.config/containers/containers.conf lists hooks_dir.
The canonical SSOT for the rootless OCI hooks directory across
every terok package: shield calls it at setup time; other
installers (e.g. terok-sandbox's per-container supervisor) call
it before dropping their own descriptors so they don't have to
re-implement the containers.conf patcher. Idempotent.
hooks_dir defaults to namespace_state_dir("shield") / "hooks"
— shield's canonical install location under paths.root.
Creates the conf file if absent. Inserts hooks_dir into the
existing [engine] section or appends a new section if none
exists. Skips silently when hooks_dir is already listed. When
a different hooks_dir is configured, appends ours to the list
rather than failing — the operator owns containers.conf and may
have intentionally pinned other locations.
Pure line-based editing — comments and formatting are preserved.
Source code in src/terok_shield/hooks/install.py
user_hooks_dir_configured(hooks_dir)
¶
Whether the user's containers.conf registers this package-owned hook directory.
Source code in src/terok_shield/hooks/install.py
__getattr__(name)
¶
Lazy import for re-exported core/support layer names.