mode
mode
¶
Hook mode: OCI hooks + per-container netns.
Uses OCI hooks to apply per-container nftables rules inside each container's network namespace. No root required — only podman and nft.
Orchestrates collaborators per lifecycle phase:
- RulesetBuilder (
nft.rules) — generates and verifies nft rulesets - DnsResolver (
dns.resolver) — pre-start domain resolution - ProfileLoader (
profiles) — allowlist profile composition - AuditLogger (
audit) — event logging - CommandRunner (
run) — subprocess execution (nft, nsenter) - dnsmasq (
dns.dnsmasq) — runtime DNS with nftset auto-population - hook_install (
hooks.install) — OCI hook file generation - state (
state) — per-container state bundle I/O
logger = logging.getLogger(__name__)
module-attribute
¶
WINDOW_NEEDS_UP = 'The bypass window opens only in the UP posture, and {container} is {posture}: outside UP the window set is unreferenced, so an open window would grant nothing. Raise the shield first.'
module-attribute
¶
Refusal for arming the timed window outside UP, where nothing would read it.
OVERRIDE_NEEDS_RULESET = "{container} is {posture}: a live override goes into a running ruleset's t10 set, and there is none to take it. An authored shield.override applies from the next start."
module-attribute
¶
Refusal for a live override on a container with no override set to add to.
HookMode(*, config, runner, audit, dns, profiles, ruleset)
¶
Hook-mode shield backend (Strategy, implements ShieldModeBackend).
Coordinates the full lifecycle of OCI-hook-based container firewalling.
Delegates to RulesetBuilder for nft generation, DnsResolver for
name resolution, ProfileLoader for allowlists, dnsmasq for
runtime DNS, and state for per-container persistence.
Create a hook mode backend with all collaborators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ShieldConfig
|
Shield configuration (provides state_dir). |
required |
runner
|
CommandRunner
|
Command runner for subprocess calls. |
required |
audit
|
AuditLogger
|
Audit logger for event logging. |
required |
dns
|
DnsResolver
|
DNS resolver for domain resolution and caching. |
required |
profiles
|
ProfileLoader
|
Profile loader for allowlist profiles. |
required |
ruleset
|
RulesetBuilder
|
Ruleset builder for nft generation and verification. |
required |
Source code in src/terok_shield/hooks/mode.py
pre_start(container, profiles, *, security_deny=(), provider_allow=(), project_allow=(), override=())
¶
Prepare for container start in hook mode.
Verifies setup, composes profiles, resolves DNS, writes allowlist, detects DNS tier, sets annotations, and returns the podman CLI arguments needed for shield protection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
security_deny
|
Sequence[str]
|
Hosts/IPs an upstream layer (executor's roster projection, carried by sandbox) generates for the t20 security-deny tier — vault hosts denied direct egress. |
()
|
provider_allow
|
Sequence[str]
|
Hosts/IPs generated for the t30 provider-allow tier — agent/provider egress endpoints. |
()
|
project_allow
|
Sequence[str]
|
Hosts/IPs authored by the orchestrator for the t40 project-allow tier (git remote, custom domains) — merged with the composed profiles. |
()
|
override
|
Sequence[str]
|
Hosts/IPs/CIDRs authored for the t10 break-glass override
tier, which sits above the security-deny; statically resolved
and seeded into a separate nft set. A CIDR opens a whole
subnet above the deny — accepted, but logged as a warning and
an |
()
|
Raises:
| Type | Description |
|---|---|
SetupRequiredError
|
When global hooks are not installed or need refreshing. |
Source code in src/terok_shield/hooks/mode.py
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 | |
refresh(container, profiles, *, security_deny=(), provider_allow=(), project_allow=(), override=())
¶
Recompute an existing container's policy bundle before a plain restart.
The policy-authoring half of
pre_start without the
launch half: rewrites every tier from the caller's current data,
refreshes the static-resolution caches, and regenerates
ruleset.nft + the dnsmasq config — so the OCI hook applies
current policy at the next podman start instead of replaying
the bundle frozen at creation. Reuses every launch-detected fact the
bundle persisted — DNS tier, upstream DNS, network mode, loopback
ports — rather than re-detecting: the container's mounts and
annotations were built for those, a fresh detection could disagree
with them, and a restart stays free of podman info.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the bundle carries no persisted DNS tier /
upstream DNS / network mode ( |
Source code in src/terok_shield/hooks/mode.py
resolve(*, force=False)
¶
Re-resolve the authored policy into its static-resolution caches.
The resolution step of refresh
on its own: every cache the bundle's policy feeds is refreshed, and no
tier, ruleset or dnsmasq config is rewritten — the project-allow tier
keeps every host its caller authored. force re-resolves even when a
cache is fresh. Returns the resolved allow IPs, which stay empty on
the live tier, where dnsmasq resolves per query.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the bundle carries no persisted DNS tier
( |
Source code in src/terok_shield/hooks/mode.py
allow_domain(container, domain)
¶
Record +domain in the runtime overlay and reload dnsmasq.
The overlay (policy/live) flips any prior deny of domain and
survives reloads; the dnsmasq restart picks up the new nftset=
line so future IP rotations of domain are auto-populated. The
IP-level allow (nft set update) is handled separately by allow_ip().
No-op when the container runs no dnsmasq (the static IP-level allow
already happened via allow_ip()).
Source code in src/terok_shield/hooks/mode.py
deny_domain(container, domain)
¶
Record -domain in the runtime overlay and reload dnsmasq.
Counterpart of allow_domain(): the dnsmasq restart picks up the
local= sinkhole, so domain stops resolving (NXDOMAIN) and the
deny fails fast in the DNS plane instead of timing out against the
filter.
No-op when the container runs no dnsmasq.
Source code in src/terok_shield/hooks/mode.py
security_tier(*, refresh=False)
¶
The t20 security tier this container's bundle records, as a matcher.
With refresh, on a DNS tier that runs no dnsmasq, the tier's names are resolved afresh and their current addresses join the cached ones. Nothing sinkholes a vault host's name on those tiers, so the container can reach an address the launch-time resolution never saw — and that address arrives as an unattributed refusal an operator may be asked to allow. The dnsmasq tiers sinkhole the names, so the cache stands.
Source code in src/terok_shield/hooks/mode.py
check_security_tier(target, ips)
¶
Refuse target when the t20 security tier refuses it — by name, suffix, or any of ips.
Meant to run once per grant, before anything changes, with every
address the target resolved to: a refusal is all or nothing, never a
grant of some addresses and a refusal of the rest. The tiers without
dnsmasq re-resolve the security names first
(security_tier).
Raises:
| Type | Description |
|---|---|
SecurityTierRefusal
|
Naming the security-tier entry, and the shared address when that is the cause. |
Source code in src/terok_shield/hooks/mode.py
allow_ip(container, ip)
¶
Live-allow an IP for a running container via nsenter.
Tier authority holds at this API itself, whoever calls it. An address
in the t20 security tier is refused — never deleted from the deny set,
where it would stay lifted until the next rebuild. Only the
operator's own runtime deny (a - entry of policy/live, or an
address one of its denied names resolved to) is lifted before the
address joins the t40 allow set. The check reads the bundle as it
stands; check_security_tier
is the caller's place to add a fresh resolution.
Raises:
| Type | Description |
|---|---|
SecurityTierRefusal
|
When ip falls in the security tier. |
Source code in src/terok_shield/hooks/mode.py
allow_offline(target)
¶
Record +target for a container that is not running: no nft, nothing live.
A stopped container has no ruleset to take a live grant, so the grant
goes where every runtime allow persists — the policy/live overlay,
flipping any earlier deny of the same target — and the files the OCI
hook applies at the next start are re-derived from the bundle at
once. The hook replays ruleset.nft and starts dnsmasq from
dnsmasq.conf as they stand, re-deriving nothing, so without that
a plain podman start would come up without the grant; terok's
restart path, which runs refresh
before podman start, carries it either way. A domain is recorded
as the name, so its own DNS tier resolves it — at once on a tier that
pins names, per query on dnsmasq-live.
Raises:
| Type | Description |
|---|---|
SecurityTierRefusal
|
When the bundle's security tier refuses target by name, suffix or address. |
RuntimeError
|
When no launch ever prepared this bundle — no start would read the overlay, so recording into it would only look like success (a mistyped container, say). |
Source code in src/terok_shield/hooks/mode.py
override(container, target, expires, *, reason)
¶
Break glass for target on a running container, valid through expires, for reason.
The live counterpart of an authored shield.override: target
joins the t10 set — above the security tier and the private ranges —
with a kernel timeout that runs out at the end of the expires day,
host local time (or at the instant, for a full timestamp). The kernel
ends the break-glass on time with nothing in userspace keeping the
clock, as it closes the bypass window. Agents keep reaching a
vault-relayed provider through the vault; the override only adds the
direct route.
The grant is recorded in the t10 tier with its %expires and its
%reason, so every shield down/up rebuild re-seeds it,
timed afresh. The tier stays the orchestrator's: the next restart
re-derives it from the orchestrator's own policy, which is where an
override that should outlive the task belongs. The whole t10 set is
swapped in one nft transaction — flushed and re-seeded — so every
element takes its current timeout and nothing overlaps. A domain
also opens in the dnsmasq sinkhole, so the workload can resolve it.
The tier follows the kernel, never the other way round. The override
names resolve first, held in memory (_resolve_grant). The rest
holds the t10 lock
(override_change),
so no revoke or other grant interleaves: the swap is computed from
the tier as it stands then — whatever a revoke or a grant changed
while the names resolved — with this grant in place of any earlier
entry for target. The tier records the grant only once the kernel
has taken that swap, and the override cache takes the answers the
swap was seeded from after the tier, so it post-dates the tier it
answers for. A refusal or a failed swap leaves both as they were,
and at no moment does the tier hold a grant the kernel never took.
The grant is audited as override — with its expiry and reason —
the moment the transaction commits, before the tier records it and
before the dnsmasq reload: once the kernel holds it, the audit trail
must too, whatever happens next.
The hard-deny floor (link-local, cloud metadata) sits above t10 and is
never overridden: a target that is, or resolves into, a hard-deny
range is refused, and so is a name that resolves to nothing. So is
anything that takes in the host's own loopback — the address
host.containers.internal names under the recorded network mode —
which only a +localhost:PORT grant reaches, one port at a time. An
IP or CIDR is judged before anything else, so it is refused with the
same message in every posture, a stopped container's included. A
name is resolved once, so the addresses checked are the addresses
seeded. That resolution covers every other override name as well,
and none of their answers is checked here: the seed itself leaves out
whatever no override may open, and the grant notes it. Under
slirp4netns the ruleset refuses the gateway above t10 regardless.
An expires that runs out while the names resolve is refused like
one that had passed already: the grant would never reach the kernel.
Returns:
| Type | Description |
|---|---|
list[str]
|
The addresses target opened (itself, for an IP or a CIDR). |
Raises:
| Type | Description |
|---|---|
ValueError
|
For a target no override can carry ( |
RuntimeError
|
When the container has no running ruleset with an override set (stopped, quarantined, unrecognised), or the target resolves to no address — and, once the kernel holds the grant, when the tier or the override cache cannot record it or dnsmasq cannot reload to open the name. |
Source code in src/terok_shield/hooks/mode.py
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 | |
revoke_override(container, target)
¶
End target's break-glass on container now, ahead of its expiry.
The counterpart of override.
It ends a live grant and an authored shield.override alike, since
the t10 tier records both the same way. Only an override still in
force can be revoked. A target with no t10 entry, or one whose
%expires already ran out, is refused, so a typo never passes for
a door that was closed.
Closing must not depend on a step that can fail open, so the order
matters. The tier entry goes first: every rebuild re-seeds t10 from
the tier, so from then on no shield up/down re-opens the
override, whatever fails next. Next, ruleset.nft and
override.expiry are re-derived from the bundle, because the OCI
hook replays them at every start, so a plain podman start does
not re-open it either. A rewrite that fails stops nothing after it:
the swap, the audit and the dnsmasq reload still run, and its error
is raised last — otherwise the running ruleset would keep admitting
the target, and a retry would find no override left to revoke. Last,
the running ruleset's t10 set is swapped in one nft transaction,
flushed and re-seeded with the overrides still in force. The target's elements go, and every other
element stays, timed to its own deadline. No DNS lookup takes part:
a revoke must not wait on, or fail with, a resolver. From the read of
the tier through the swap it holds the t10 lock
(override_change),
so a grant whose names resolved meanwhile swaps from the tier as the
revoke left it and never re-opens the target. A grant resolves
before it takes the lock, so the wait is never on a resolver.
The revoke is audited as override_revoked once nothing running
holds the override: when that transaction commits, or at once when
the ruleset carries no t10 set (a stopped or quarantined container).
For a name, dnsmasq is then reloaded if its config still punches the
name through the sinkhole, so the name stops resolving again. A
stopped container's dnsmasq config is rewritten on disk instead, for
its next start.
"Stopped" is podman's word, never an unreadable ruleset's: a listing
that fails reads as OFFLINE too, so before a revoke treats the
container as stopped, podman must confirm it has no process, or has
no such container
(confirmed_posture).
A running container whose ruleset could not be read gets the swap,
and its failure is raised.
Connections already established keep running: the ruleset accepts established traffic ahead of every tier, so a revoke stops new connections, as the override's own expiry does.
Returns:
| Type | Description |
|---|---|
OverrideRevocation
|
The addresses closed, the ones another override still holds open, |
OverrideRevocation
|
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 on the container (or it has no state bundle at all), or when neither the ruleset nor podman says whether the container runs — both before anything changes. Also, with the record already gone, when nft cannot drop the elements from the running ruleset, dnsmasq cannot reload to sinkhole the name again, or the files a plain start replays cannot be rewritten — each message saying what still holds. |
Source code in src/terok_shield/hooks/mode.py
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 | |
deny_ip(container, ip)
¶
Live-deny an IP for a running container via nsenter.
Removes from the nft allow set (best-effort), adds to the nft deny set,
and records -ip in policy/live so the deny sticks across
shield up / restart and flips any prior allow.
Source code in src/terok_shield/hooks/mode.py
shield_down(container, *, disengaged=False)
¶
Switch a running container to the DOWN posture (DISENGAGED when disengaged).
Plain DOWN accepts by default but keeps the deny set and both range
floors; DISENGAGED enforces nothing, so its deny sets are left empty —
the next shield up repopulates them from the composed policy.
Both postures re-seed the t10 override set: it tags break-glass
traffic ALLOWED ahead of the DOWN catch-all in DISENGAGED
too, so that traffic is never recorded as accepted only because the
shield is down.
On a tier that pins names, caches older than an hour are re-resolved
first (_refresh_pinned_names), so the deny set the down posture keeps enforcing holds the vault
hosts' current addresses; and plain DOWN notes the denied names a
rotation would carry past it.
Source code in src/terok_shield/hooks/mode.py
shield_quarantine(container)
¶
Total network blackout — drop all traffic, log dropped traffic.
Reads no settings — no DNS, no allowlists, no loopback ports,
no gateway probe, no profile lookup. build_quarantine /
verify_quarantine are static; the only inputs are the
container name and the live ruleset state (table-or-no-table).
Any config-conditional branch added here is a bug.
Source code in src/terok_shield/hooks/mode.py
shield_up(container)
¶
Restore normal deny-all mode for a running container.
The rebuild is delete table + re-apply, which would forget every
dnsmasq-learned allow-set element — a container coming out of the down
posture would suddenly lose IPs its workload already resolved (clients
cache answers, so they do not necessarily re-query). The allow sets
are therefore snapshotted before the rebuild and restored after it.
On a tier that pins names, caches older than an hour are re-resolved
before anything changes (_refresh_pinned_names): a container raised after hours down would otherwise come up seeded
with its launch-time addresses. The names the tier still pins are
noted once the posture holds.
Source code in src/terok_shield/hooks/mode.py
shield_reset(container)
¶
Forget learned allow-set state — back to the just-launched contents.
Flushes both tier-40 project-allow sets and re-seeds them from the
effective policy in a single nft transaction, so authored literals
never blink out. dnsmasq-learned IPs vanish until the workload
resolves the corresponding names again; the operator overlay
(policy/live) and the deny tier are untouched.
Source code in src/terok_shield/hooks/mode.py
arm_window(container, timeout)
¶
Open the timed allow-all window for timeout — in the UP posture only.
The element carries a kernel timeout, so the window closes itself even
if nothing ever calls disarm_window
— and any disruption (a rebuild, a restart, a crashed host process)
only closes it sooner.
Only the UP chain references the window set. Armed in any other posture the element would grant nothing — DOWN accepts by default already, quarantine drops everything — while the caller would be told a window is open, so arming there is refused instead.
Raises:
| Type | Description |
|---|---|
ValueError
|
When timeout is not an nft timeout. |
RuntimeError
|
When the container's posture is not UP. |
Source code in src/terok_shield/hooks/mode.py
disarm_window(container)
¶
Close the timed allow-all window now, before its timeout runs out.
inspect(container)
¶
Read the container's posture and its timed window from one ruleset listing.
One nft -T list table serves both: the posture comes from the
verifiers, the window's countdown from its own set block, in whole
seconds — -T prints them so, where a plain listing would print
4m59s693ms. The window keeps no host-side deadline, so the
kernel's clock is the only record and a stale answer is impossible by
construction. Only the UP chain reads the window set, so the
countdown is reported for UP alone.
Source code in src/terok_shield/hooks/mode.py
shield_state(container)
¶
confirmed_posture(container)
¶
The posture allow and revoke route on: OFFLINE only when podman says no process runs.
An empty listing reads as OFFLINE, and so does one that failed:
_list_table swallows a podman inspect, nsenter or nft
error, because a status poll must not crash on one. A change must not
take that for a stopped container. It would skip the kernel, as an
allow recorded only in the overlay or a revoke with no t10 swap, and
report the change as waiting for the next start while the running
ruleset stays as it was. It would also rewrite the dnsmasq config on
disk, which a running dnsmasq never reads, and after which no
reconcile finds anything left to reload. So an OFFLINE reading is
checked against podman's own record. No process (pid 0) is a stopped
container, and so is one podman has no record of at all: removed, it
runs nothing, and an orchestrator that recreates it under the same
name starts it from the same bundle. A process means a running
container whose ruleset could not be read, or that carries none at
all: that reads as ERROR, so the live path is tried and its failure
reported.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When podman cannot say whether the container runs either — before the caller changes anything, so the change can simply be tried again. |
Source code in src/terok_shield/hooks/mode.py
list_rules(container)
¶
preview(*, down=False, disengaged=False, profiles=())
¶
Generate the ruleset that would be applied to a container.
With profiles, the ruleset the hook applies on the live tier at
createRuntime: their +localhost:PORT grants join the
preamble and their literal IPs seed the t40 project-allow set.
Domains are left out on purpose — the live tier never resolves
them at apply time (dnsmasq learns them per query), so nothing is
approximated. Touches no setup, podman, DNS or state dir, which
makes it the generator for applying a ruleset by hand.