terok-shield 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- terok_shield/__init__.py +513 -0
- terok_shield/_hub_events.py +157 -0
- terok_shield/_wire_sanitize.py +70 -0
- terok_shield/audit.py +99 -0
- terok_shield/cli/__init__.py +10 -0
- terok_shield/cli/__main__.py +21 -0
- terok_shield/cli/main.py +554 -0
- terok_shield/commands.py +379 -0
- terok_shield/config.py +261 -0
- terok_shield/container.py +127 -0
- terok_shield/dns/__init__.py +9 -0
- terok_shield/dns/apparmor.py +68 -0
- terok_shield/dns/dnsmasq.py +344 -0
- terok_shield/dns/resolver.py +134 -0
- terok_shield/hooks/__init__.py +9 -0
- terok_shield/hooks/install.py +355 -0
- terok_shield/hooks/mode.py +758 -0
- terok_shield/hooks/reader_install.py +46 -0
- terok_shield/nft/__init__.py +9 -0
- terok_shield/nft/constants.py +72 -0
- terok_shield/nft/rules.py +676 -0
- terok_shield/paths.py +51 -0
- terok_shield/podman_info/__init__.py +38 -0
- terok_shield/podman_info/_conf.py +27 -0
- terok_shield/podman_info/hooks_dir.py +84 -0
- terok_shield/podman_info/info.py +133 -0
- terok_shield/podman_info/network.py +75 -0
- terok_shield/prereqs.py +95 -0
- terok_shield/profiles.py +96 -0
- terok_shield/py.typed +0 -0
- terok_shield/resources/__init__.py +4 -0
- terok_shield/resources/_oci_state.py +546 -0
- terok_shield/resources/dns/__init__.py +4 -0
- terok_shield/resources/dns/base.txt +28 -0
- terok_shield/resources/dns/dev-node.txt +12 -0
- terok_shield/resources/dns/dev-python.txt +15 -0
- terok_shield/resources/dns/dev-standard.txt +32 -0
- terok_shield/resources/dns/krun_guest.txt +25 -0
- terok_shield/resources/dns/nvidia-hpc.txt +12 -0
- terok_shield/resources/nflog_reader.py +1070 -0
- terok_shield/resources/nft_hook.py +261 -0
- terok_shield/resources/reader_hook.py +334 -0
- terok_shield/resources/shield_probe.py +167 -0
- terok_shield/run.py +271 -0
- terok_shield/simple_clearance.py +323 -0
- terok_shield/state.py +280 -0
- terok_shield/subprocess_env.py +32 -0
- terok_shield/util.py +35 -0
- terok_shield/validation.py +72 -0
- terok_shield/watch.py +153 -0
- terok_shield/watchers/__init__.py +29 -0
- terok_shield/watchers/_event.py +53 -0
- terok_shield/watchers/audit_log.py +66 -0
- terok_shield/watchers/dns_log.py +106 -0
- terok_shield/watchers/domain_cache.py +46 -0
- terok_shield/watchers/nflog.py +251 -0
- terok_shield-0.7.0.dist-info/METADATA +150 -0
- terok_shield-0.7.0.dist-info/RECORD +62 -0
- terok_shield-0.7.0.dist-info/WHEEL +4 -0
- terok_shield-0.7.0.dist-info/entry_points.txt +3 -0
- terok_shield-0.7.0.dist-info/licenses/LICENSE +177 -0
- terok_shield-0.7.0.dist-info/licenses/LICENSES/Apache-2.0.txt +202 -0
terok_shield/__init__.py
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Jiri Vyskocil
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""terok-shield: nftables-based egress firewalling for Podman containers.
|
|
5
|
+
|
|
6
|
+
Public API facade. The ``Shield`` class coordinates collaborators:
|
|
7
|
+
|
|
8
|
+
- **HookMode** (``hooks.mode``) — per-container nft ruleset lifecycle
|
|
9
|
+
- **DnsResolver** (``dns.resolver``) — domain resolution and caching
|
|
10
|
+
- **ProfileLoader** (``profiles``) — allowlist profile composition
|
|
11
|
+
- **RulesetBuilder** (``nft.rules``) — nftables ruleset generation
|
|
12
|
+
- **AuditLogger** (``audit``) — per-container JSONL audit trail
|
|
13
|
+
- **CommandRunner** (``run``) — subprocess execution boundary
|
|
14
|
+
|
|
15
|
+
Core and support modules are imported lazily — ``from terok_shield
|
|
16
|
+
import ShieldConfig`` does not pull in nft, dnsmasq, or subprocess
|
|
17
|
+
helpers. Heavy imports are deferred until ``Shield`` is instantiated.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import importlib as _importlib
|
|
21
|
+
import logging
|
|
22
|
+
from collections.abc import Iterator
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from importlib.metadata import PackageNotFoundError, version as _meta_version
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import TYPE_CHECKING
|
|
27
|
+
|
|
28
|
+
# ── Eager: foundation layer (zero-cost, pure data) ─────
|
|
29
|
+
from .config import (
|
|
30
|
+
DnsTier,
|
|
31
|
+
ShieldConfig,
|
|
32
|
+
ShieldMode,
|
|
33
|
+
ShieldModeBackend,
|
|
34
|
+
ShieldRuntime,
|
|
35
|
+
ShieldState,
|
|
36
|
+
)
|
|
37
|
+
from .paths import HOOK_ENTRYPOINT_NAME
|
|
38
|
+
from .podman_info import (
|
|
39
|
+
find_hooks_dirs,
|
|
40
|
+
global_hooks_hint,
|
|
41
|
+
has_global_hooks,
|
|
42
|
+
parse_podman_info,
|
|
43
|
+
)
|
|
44
|
+
from .state import StateBundle
|
|
45
|
+
from .util import is_ip as _is_ip
|
|
46
|
+
|
|
47
|
+
if TYPE_CHECKING:
|
|
48
|
+
from terok_util import ArgDef, CommandDef
|
|
49
|
+
|
|
50
|
+
from ._hub_events import HubEventEmitter
|
|
51
|
+
from .audit import AuditLogger
|
|
52
|
+
from .commands import COMMANDS
|
|
53
|
+
from .dns.resolver import DnsResolver
|
|
54
|
+
from .hooks.install import HooksInstaller
|
|
55
|
+
from .nft.rules import RulesetBuilder
|
|
56
|
+
from .profiles import ProfileLoader
|
|
57
|
+
from .run import CommandRunner, ExecError
|
|
58
|
+
|
|
59
|
+
# ── Lazy: core + support layer ──────────────────────────
|
|
60
|
+
# Re-exported names from __all__ that are deferred until first access.
|
|
61
|
+
# Keeps ``from terok_shield import ShieldConfig`` lightweight.
|
|
62
|
+
|
|
63
|
+
_LAZY_IMPORTS: dict[str, tuple[str, str]] = {
|
|
64
|
+
"BinaryCheck": ("terok_shield.prereqs", "BinaryCheck"),
|
|
65
|
+
"ExecError": ("terok_shield.run", "ExecError"),
|
|
66
|
+
"HooksInstaller": ("terok_shield.hooks.install", "HooksInstaller"),
|
|
67
|
+
"ensure_user_hooks_dir_configured": (
|
|
68
|
+
"terok_shield.hooks.install",
|
|
69
|
+
"ensure_user_hooks_dir_configured",
|
|
70
|
+
),
|
|
71
|
+
"NftNotFoundError": ("terok_shield.run", "NftNotFoundError"),
|
|
72
|
+
"ShieldNeedsSetup": ("terok_shield.run", "ShieldNeedsSetup"),
|
|
73
|
+
"check_firewall_binaries": ("terok_shield.prereqs", "check_firewall_binaries"),
|
|
74
|
+
"check_krun_binaries": ("terok_shield.prereqs", "check_krun_binaries"),
|
|
75
|
+
# Command registry — re-exported for the terok integration layer.
|
|
76
|
+
# ArgDef/CommandDef now live in terok-util; we route through it so
|
|
77
|
+
# existing consumers (terok.lib.integrations.shield) keep working.
|
|
78
|
+
"ArgDef": ("terok_util", "ArgDef"),
|
|
79
|
+
"COMMANDS": ("terok_shield.commands", "COMMANDS"),
|
|
80
|
+
"CommandDef": ("terok_util", "CommandDef"),
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def __getattr__(name: str) -> object:
|
|
85
|
+
"""Lazy import for re-exported core/support layer names."""
|
|
86
|
+
if name in _LAZY_IMPORTS:
|
|
87
|
+
mod_path, attr = _LAZY_IMPORTS[name]
|
|
88
|
+
mod = _importlib.import_module(mod_path)
|
|
89
|
+
value = getattr(mod, attr)
|
|
90
|
+
globals()[name] = value # cache for subsequent access
|
|
91
|
+
return value
|
|
92
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
logger = logging.getLogger(__name__)
|
|
96
|
+
|
|
97
|
+
__version__: str = "0.7.0" # placeholder; replaced at build time
|
|
98
|
+
try:
|
|
99
|
+
__version__ = _meta_version("terok-shield")
|
|
100
|
+
except PackageNotFoundError:
|
|
101
|
+
pass # editable install or running from source without metadata
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass(frozen=True)
|
|
105
|
+
class EnvironmentCheck:
|
|
106
|
+
"""Result of [`Shield.check_environment`][terok_shield.Shield.check_environment].
|
|
107
|
+
|
|
108
|
+
Machine-readable fields for programmatic consumers (terok TUI, scripts).
|
|
109
|
+
Human-readable ``issues`` and ``setup_hint`` for CLI display.
|
|
110
|
+
|
|
111
|
+
Attributes:
|
|
112
|
+
ok: True if no issues found.
|
|
113
|
+
podman_version: Detected podman version tuple.
|
|
114
|
+
hooks: Hook installation type (``per-container``, ``global``,
|
|
115
|
+
``not-installed``).
|
|
116
|
+
health: Environment health (``ok``, ``setup-needed``, ``stale-hooks``).
|
|
117
|
+
dns_tier: Active DNS resolution tier (``dnsmasq``, ``dig``, ``getent``).
|
|
118
|
+
issues: List of human-readable issue descriptions.
|
|
119
|
+
needs_setup: True if one-time setup is required.
|
|
120
|
+
setup_hint: Setup instructions (empty if not needed).
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
dns_tier: str = ""
|
|
124
|
+
ok: bool = True
|
|
125
|
+
podman_version: tuple[int, ...] = (0,)
|
|
126
|
+
hooks: str = "per-container"
|
|
127
|
+
health: str = "ok"
|
|
128
|
+
issues: list[str] = field(default_factory=list)
|
|
129
|
+
needs_setup: bool = False
|
|
130
|
+
setup_hint: str = ""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _read_installed_hook_version(hooks_dirs: list[Path]) -> int | None:
|
|
134
|
+
"""Read ``BUNDLE_VERSION`` from the installed ballast module, or ``None``.
|
|
135
|
+
|
|
136
|
+
The ballast (``_oci_state.py``) lives *next to* the role script, not
|
|
137
|
+
necessarily in *hooks_dirs* — shield's own installer keeps them in
|
|
138
|
+
one directory, but another package may register a *hooks_dirs* entry
|
|
139
|
+
that holds only descriptors. So the ballast is located via the
|
|
140
|
+
descriptor's ``path`` (the load-bearing reference to the role
|
|
141
|
+
script) rather than scanned for directly in *hooks_dirs*.
|
|
142
|
+
"""
|
|
143
|
+
import json
|
|
144
|
+
import re
|
|
145
|
+
|
|
146
|
+
from .podman_info.hooks_dir import HOOK_JSON_FILENAME
|
|
147
|
+
|
|
148
|
+
pattern = re.compile(r"^BUNDLE_VERSION\s*=\s*(\d+)", re.MULTILINE)
|
|
149
|
+
# find_hooks_dirs() yields directories in precedence order with the
|
|
150
|
+
# last entry taking effect (podman's last-wins --hooks-dir rule), so
|
|
151
|
+
# walk in reverse and stop at the first descriptor we find: that is
|
|
152
|
+
# the *active* install. If its descriptor or ballast is broken we
|
|
153
|
+
# report ``None`` (unknown / broken) rather than falling through to a
|
|
154
|
+
# lower-precedence dir — podman still loads the broken higher one, so
|
|
155
|
+
# reporting a stale lower version would mask the real active install.
|
|
156
|
+
for d in reversed(hooks_dirs):
|
|
157
|
+
descriptor = d / HOOK_JSON_FILENAME
|
|
158
|
+
if not descriptor.is_file():
|
|
159
|
+
continue
|
|
160
|
+
try:
|
|
161
|
+
data = json.loads(descriptor.read_text())
|
|
162
|
+
if not isinstance(data, dict):
|
|
163
|
+
return None
|
|
164
|
+
hook = data.get("hook")
|
|
165
|
+
if not isinstance(hook, dict):
|
|
166
|
+
return None
|
|
167
|
+
argv = hook.get("path")
|
|
168
|
+
if not isinstance(argv, str):
|
|
169
|
+
return None
|
|
170
|
+
ballast = Path(argv).parent / "_oci_state.py"
|
|
171
|
+
if ballast.is_file():
|
|
172
|
+
m = pattern.search(ballast.read_text())
|
|
173
|
+
if m:
|
|
174
|
+
return int(m.group(1))
|
|
175
|
+
except (OSError, ValueError):
|
|
176
|
+
return None
|
|
177
|
+
return None
|
|
178
|
+
return None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# ── Shield Facade ────────────────────────────────────────
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class Shield:
|
|
185
|
+
"""Public API facade — coordinates collaborators per container.
|
|
186
|
+
|
|
187
|
+
Delegates to ``HookMode`` for netns/nft operations, ``DnsResolver``
|
|
188
|
+
for name resolution, ``ProfileLoader`` for allowlists,
|
|
189
|
+
``RulesetBuilder`` for ruleset generation, and ``AuditLogger`` for
|
|
190
|
+
the audit trail. All collaborators are injectable for testing.
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
def __init__(
|
|
194
|
+
self,
|
|
195
|
+
config: ShieldConfig,
|
|
196
|
+
*,
|
|
197
|
+
runner: "CommandRunner | None" = None,
|
|
198
|
+
audit: "AuditLogger | None" = None,
|
|
199
|
+
dns: "DnsResolver | None" = None,
|
|
200
|
+
profiles: "ProfileLoader | None" = None,
|
|
201
|
+
ruleset: "RulesetBuilder | None" = None,
|
|
202
|
+
hub_events: "HubEventEmitter | None" = None,
|
|
203
|
+
) -> None:
|
|
204
|
+
"""Create the shield facade.
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
config: Shield configuration (must include state_dir).
|
|
208
|
+
runner: Command runner (default: ``SubprocessRunner``).
|
|
209
|
+
audit: Audit logger (default: from config.state_dir).
|
|
210
|
+
dns: DNS resolver (default: from runner).
|
|
211
|
+
profiles: Profile loader (default: from config.profiles_dir).
|
|
212
|
+
ruleset: Ruleset builder (default: from config loopback_ports).
|
|
213
|
+
hub_events: Best-effort emitter for ``shield_up`` / ``shield_down``
|
|
214
|
+
events bound for the terok-clearance hub (default: a fresh
|
|
215
|
+
[`HubEventEmitter`][terok_shield._hub_events.HubEventEmitter]). The
|
|
216
|
+
emitter routes each event to the supervisor's
|
|
217
|
+
per-container socket using the ``container_id`` supplied
|
|
218
|
+
on every [`up`][terok_shield.Shield.up] /
|
|
219
|
+
[`down`][terok_shield.Shield.down] call. Pass a no-op
|
|
220
|
+
stub in tests that should not touch the socket.
|
|
221
|
+
"""
|
|
222
|
+
from ._hub_events import HubEventEmitter
|
|
223
|
+
from .audit import AuditLogger
|
|
224
|
+
from .dns.resolver import DnsResolver
|
|
225
|
+
from .nft.rules import RulesetBuilder
|
|
226
|
+
from .profiles import ProfileLoader
|
|
227
|
+
from .run import SubprocessRunner
|
|
228
|
+
|
|
229
|
+
self.config = config
|
|
230
|
+
self.runner = runner or SubprocessRunner()
|
|
231
|
+
self.audit = audit or AuditLogger(
|
|
232
|
+
audit_path=StateBundle(config.state_dir).audit,
|
|
233
|
+
enabled=config.audit_enabled,
|
|
234
|
+
)
|
|
235
|
+
self.dns = dns or DnsResolver(runner=self.runner)
|
|
236
|
+
self.profiles = profiles or ProfileLoader(
|
|
237
|
+
user_dir=config.profiles_dir or Path("/nonexistent"),
|
|
238
|
+
)
|
|
239
|
+
self.ruleset = ruleset or RulesetBuilder(loopback_ports=config.loopback_ports)
|
|
240
|
+
self.hub_events = hub_events or HubEventEmitter()
|
|
241
|
+
self._mode = self._create_mode(config.mode)
|
|
242
|
+
|
|
243
|
+
def _create_mode(self, mode: ShieldMode) -> ShieldModeBackend:
|
|
244
|
+
"""Create the mode backend for the given mode."""
|
|
245
|
+
if mode == ShieldMode.HOOK:
|
|
246
|
+
from .hooks.mode import HookMode
|
|
247
|
+
|
|
248
|
+
return HookMode(
|
|
249
|
+
config=self.config,
|
|
250
|
+
runner=self.runner,
|
|
251
|
+
audit=self.audit,
|
|
252
|
+
dns=self.dns,
|
|
253
|
+
profiles=self.profiles,
|
|
254
|
+
ruleset=self.ruleset,
|
|
255
|
+
)
|
|
256
|
+
raise ValueError(f"Unsupported shield mode: {mode!r}")
|
|
257
|
+
|
|
258
|
+
def check_environment(self) -> EnvironmentCheck:
|
|
259
|
+
"""Check the podman environment for compatibility issues.
|
|
260
|
+
|
|
261
|
+
Proactive check for API consumers (e.g. terok). Returns an
|
|
262
|
+
[`EnvironmentCheck`][terok_shield.EnvironmentCheck] with detected issues and setup hints.
|
|
263
|
+
Does not raise — the caller decides how to handle issues.
|
|
264
|
+
"""
|
|
265
|
+
from . import state
|
|
266
|
+
from .dns import apparmor
|
|
267
|
+
|
|
268
|
+
output = self.runner.run(["podman", "info", "-f", "json"], check=False)
|
|
269
|
+
info = parse_podman_info(output)
|
|
270
|
+
issues: list[str] = []
|
|
271
|
+
needs_setup = False
|
|
272
|
+
setup_hint = ""
|
|
273
|
+
hooks = "per-container"
|
|
274
|
+
health = "ok"
|
|
275
|
+
|
|
276
|
+
tier, apparmor_blocked = apparmor.detect_dns_tier_under_apparmor(
|
|
277
|
+
self.runner, self.config.state_dir
|
|
278
|
+
)
|
|
279
|
+
dns_tier = tier.value
|
|
280
|
+
if apparmor_blocked:
|
|
281
|
+
issues.append(
|
|
282
|
+
"dnsmasq is present but AppArmor confines it from the shield "
|
|
283
|
+
f"state directory — domain allowlisting falls back to static {tier.value} "
|
|
284
|
+
"resolution (no IP rotation handling). Install the terok AppArmor "
|
|
285
|
+
"profile to enable the dnsmasq tier (see docs/apparmor.md)"
|
|
286
|
+
)
|
|
287
|
+
elif tier == DnsTier.DIG:
|
|
288
|
+
issues.append(
|
|
289
|
+
"dnsmasq not found — domain allowlisting uses static pre-start "
|
|
290
|
+
"resolution (no IP rotation handling). "
|
|
291
|
+
"Install dnsmasq for dynamic domain-based egress control"
|
|
292
|
+
)
|
|
293
|
+
elif tier == DnsTier.GETENT:
|
|
294
|
+
issues.append(
|
|
295
|
+
"Neither dnsmasq nor dig found — DNS resolution uses getent "
|
|
296
|
+
"(single IP, no AAAA). Install dnsmasq or at minimum dnsutils/bind-utils"
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
hooks_dirs = find_hooks_dirs()
|
|
300
|
+
global_hooks = has_global_hooks(hooks_dirs)
|
|
301
|
+
|
|
302
|
+
if not info.hooks_dir_persists:
|
|
303
|
+
if global_hooks:
|
|
304
|
+
hooks = "global"
|
|
305
|
+
health = "ok"
|
|
306
|
+
# Check hook version matches current package
|
|
307
|
+
hook_ver = _read_installed_hook_version(hooks_dirs)
|
|
308
|
+
if hook_ver != state.BUNDLE_VERSION:
|
|
309
|
+
health = "stale-hooks"
|
|
310
|
+
issues.append(
|
|
311
|
+
f"Installed hook version {hook_ver} != expected {state.BUNDLE_VERSION}. "
|
|
312
|
+
"Run `terok-shield setup` to update."
|
|
313
|
+
)
|
|
314
|
+
else:
|
|
315
|
+
hooks = "not-installed"
|
|
316
|
+
health = "setup-needed"
|
|
317
|
+
needs_setup = True
|
|
318
|
+
setup_hint = global_hooks_hint()
|
|
319
|
+
issues.append(
|
|
320
|
+
"Global hooks not installed - containers will lose firewall on restart"
|
|
321
|
+
)
|
|
322
|
+
elif global_hooks:
|
|
323
|
+
health = "stale-hooks"
|
|
324
|
+
issues.append(
|
|
325
|
+
"Stale global hooks detected - not needed on podman >= 5.6.0. "
|
|
326
|
+
"Consider removing them."
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
return EnvironmentCheck(
|
|
330
|
+
ok=not issues,
|
|
331
|
+
podman_version=info.version,
|
|
332
|
+
hooks=hooks,
|
|
333
|
+
health=health,
|
|
334
|
+
dns_tier=dns_tier,
|
|
335
|
+
issues=issues,
|
|
336
|
+
needs_setup=needs_setup,
|
|
337
|
+
setup_hint=setup_hint,
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
def status(self) -> dict:
|
|
341
|
+
"""Return current shield status information."""
|
|
342
|
+
return {
|
|
343
|
+
"mode": self.config.mode.value,
|
|
344
|
+
"profiles": self.profiles.list_profiles(),
|
|
345
|
+
"audit_enabled": self.config.audit_enabled,
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
def pre_start(self, container: str, profiles: list[str] | None = None) -> list[str]:
|
|
349
|
+
"""Prepare shield for container start. Returns extra podman args."""
|
|
350
|
+
if profiles is None:
|
|
351
|
+
profiles = list(self.config.default_profiles)
|
|
352
|
+
result = self._mode.pre_start(container, profiles)
|
|
353
|
+
self.audit.log_event(container, "setup", detail=f"profiles={','.join(profiles)}")
|
|
354
|
+
return result
|
|
355
|
+
|
|
356
|
+
def allow(self, container: str, target: str) -> list[str]:
|
|
357
|
+
"""Live-allow a domain or IP for a running container."""
|
|
358
|
+
from .run import ExecError
|
|
359
|
+
|
|
360
|
+
is_domain = not _is_ip(target)
|
|
361
|
+
ips = [target] if not is_domain else self.dns.resolve_domains([target])
|
|
362
|
+
allowed: list[str] = []
|
|
363
|
+
for ip in ips:
|
|
364
|
+
try:
|
|
365
|
+
self._mode.allow_ip(container, ip)
|
|
366
|
+
except (ExecError, OSError) as exc:
|
|
367
|
+
logger.warning("allow_ip failed for %s on %s: %s", ip, container, exc)
|
|
368
|
+
continue
|
|
369
|
+
allowed.append(ip)
|
|
370
|
+
self.audit.log_event(container, "allowed", dest=ip, detail=f"target={target}")
|
|
371
|
+
# Update dnsmasq config for domain targets (so future IP rotations are captured)
|
|
372
|
+
if is_domain and allowed:
|
|
373
|
+
self._mode.allow_domain(target)
|
|
374
|
+
return allowed
|
|
375
|
+
|
|
376
|
+
def deny(self, container: str, target: str) -> list[str]:
|
|
377
|
+
"""Live-deny a domain or IP for a running container."""
|
|
378
|
+
from .run import ExecError
|
|
379
|
+
|
|
380
|
+
is_domain = not _is_ip(target)
|
|
381
|
+
ips = [target] if not is_domain else self.dns.resolve_domains([target])
|
|
382
|
+
denied: list[str] = []
|
|
383
|
+
for ip in ips:
|
|
384
|
+
try:
|
|
385
|
+
self._mode.deny_ip(container, ip)
|
|
386
|
+
except (ExecError, OSError) as exc:
|
|
387
|
+
logger.warning("deny_ip failed for %s on %s: %s", ip, container, exc)
|
|
388
|
+
continue
|
|
389
|
+
denied.append(ip)
|
|
390
|
+
self.audit.log_event(container, "denied", dest=ip, detail=f"target={target}")
|
|
391
|
+
# Remove domain from dnsmasq config (stops future auto-population)
|
|
392
|
+
if is_domain and denied:
|
|
393
|
+
self._mode.deny_domain(target)
|
|
394
|
+
return denied
|
|
395
|
+
|
|
396
|
+
def rules(self, container: str) -> str:
|
|
397
|
+
"""Return current nft rules for a container."""
|
|
398
|
+
return self._mode.list_rules(container)
|
|
399
|
+
|
|
400
|
+
def down(self, container: str, container_id: str, *, allow_all: bool = False) -> None:
|
|
401
|
+
"""Switch a running container to bypass mode.
|
|
402
|
+
|
|
403
|
+
*container* is the operator-facing podman name (audit log key);
|
|
404
|
+
*container_id* is the full podman UUID — the routing key for
|
|
405
|
+
the per-container hub socket the supervisor listens on. The
|
|
406
|
+
caller knows both at every emit site, so neither carries a
|
|
407
|
+
default.
|
|
408
|
+
"""
|
|
409
|
+
self._mode.shield_down(container, allow_all=allow_all)
|
|
410
|
+
self.audit.log_event(
|
|
411
|
+
container,
|
|
412
|
+
"shield_down",
|
|
413
|
+
detail="allow_all=True" if allow_all else None,
|
|
414
|
+
)
|
|
415
|
+
self.hub_events.shield_down(
|
|
416
|
+
container,
|
|
417
|
+
container_id,
|
|
418
|
+
allow_all=allow_all,
|
|
419
|
+
dossier=self._read_dossier(),
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
def quarantine(self, container: str) -> None:
|
|
423
|
+
"""Total network blackout — drop all traffic, log dropped traffic."""
|
|
424
|
+
self._mode.shield_quarantine(container)
|
|
425
|
+
self.audit.log_event(container, "shield_quarantine")
|
|
426
|
+
|
|
427
|
+
def up(self, container: str, container_id: str) -> None:
|
|
428
|
+
"""Restore normal deny-all mode for a running container.
|
|
429
|
+
|
|
430
|
+
*container* / *container_id* — see
|
|
431
|
+
[`down`][terok_shield.Shield.down].
|
|
432
|
+
"""
|
|
433
|
+
self._mode.shield_up(container)
|
|
434
|
+
self.audit.log_event(container, "shield_up")
|
|
435
|
+
self.hub_events.shield_up(container, container_id, dossier=self._read_dossier())
|
|
436
|
+
|
|
437
|
+
def _read_dossier(self) -> dict[str, str]:
|
|
438
|
+
"""Resolve the wire dossier for this container by reading the orchestrator's task meta.
|
|
439
|
+
|
|
440
|
+
The bridge ``createRuntime`` hook writes the ``dossier.meta_path``
|
|
441
|
+
OCI annotation to ``state_dir/meta_path``; ``Shield.up()`` /
|
|
442
|
+
``Shield.down()`` follow that pointer, open the orchestrator's
|
|
443
|
+
live task-meta JSON, and project it to the wire-dossier shape
|
|
444
|
+
``{project, task, name}`` — the same projection the per-container
|
|
445
|
+
reader applies to every block event, so every event for one
|
|
446
|
+
container renders identically in the clearance UI.
|
|
447
|
+
|
|
448
|
+
Empty meta_path (standalone container, no orchestrator) →
|
|
449
|
+
``{}`` → bare-container-name popup. No staleness window: the
|
|
450
|
+
meta JSON is the orchestrator's live state and is re-read on
|
|
451
|
+
every call.
|
|
452
|
+
"""
|
|
453
|
+
from .resources._oci_state import read_meta_path, resolve_dossier_from_meta
|
|
454
|
+
|
|
455
|
+
return resolve_dossier_from_meta(read_meta_path(self.config.state_dir))
|
|
456
|
+
|
|
457
|
+
def state(self, container: str) -> ShieldState:
|
|
458
|
+
"""Query the live nft ruleset to determine a container's shield state."""
|
|
459
|
+
return self._mode.shield_state(container)
|
|
460
|
+
|
|
461
|
+
def preview(self, *, down: bool = False, allow_all: bool = False) -> str:
|
|
462
|
+
"""Generate the ruleset that would be applied to a container."""
|
|
463
|
+
return self._mode.preview(down=down, allow_all=allow_all)
|
|
464
|
+
|
|
465
|
+
def resolve(
|
|
466
|
+
self,
|
|
467
|
+
profiles: list[str] | None = None,
|
|
468
|
+
*,
|
|
469
|
+
force: bool = False,
|
|
470
|
+
) -> list[str]:
|
|
471
|
+
"""Resolve DNS profiles and cache the results."""
|
|
472
|
+
if profiles is None:
|
|
473
|
+
profiles = list(self.config.default_profiles)
|
|
474
|
+
entries = self.profiles.compose_profiles(profiles)
|
|
475
|
+
if not entries:
|
|
476
|
+
return []
|
|
477
|
+
max_age = 0 if force else 3600
|
|
478
|
+
cache_path = StateBundle(self.config.state_dir).profile_allowed
|
|
479
|
+
return self.dns.resolve_and_cache(entries, cache_path, max_age=max_age)
|
|
480
|
+
|
|
481
|
+
def profiles_list(self) -> list[str]:
|
|
482
|
+
"""List available profile names."""
|
|
483
|
+
return self.profiles.list_profiles()
|
|
484
|
+
|
|
485
|
+
def tail_log(self, n: int = 50) -> Iterator[dict]:
|
|
486
|
+
"""Yield the last *n* audit events."""
|
|
487
|
+
return self.audit.tail_log(n)
|
|
488
|
+
|
|
489
|
+
def compose_profiles(self, names: list[str]) -> list[str]:
|
|
490
|
+
"""Load and merge multiple profiles."""
|
|
491
|
+
return self.profiles.compose_profiles(names)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
__all__ = [
|
|
495
|
+
"ArgDef",
|
|
496
|
+
"BinaryCheck",
|
|
497
|
+
"COMMANDS",
|
|
498
|
+
"CommandDef",
|
|
499
|
+
"EnvironmentCheck",
|
|
500
|
+
"ExecError",
|
|
501
|
+
"HOOK_ENTRYPOINT_NAME",
|
|
502
|
+
"HooksInstaller",
|
|
503
|
+
"NftNotFoundError",
|
|
504
|
+
"Shield",
|
|
505
|
+
"ShieldConfig",
|
|
506
|
+
"ShieldMode",
|
|
507
|
+
"ShieldNeedsSetup",
|
|
508
|
+
"ShieldRuntime",
|
|
509
|
+
"ShieldState",
|
|
510
|
+
"check_firewall_binaries",
|
|
511
|
+
"check_krun_binaries",
|
|
512
|
+
"ensure_user_hooks_dir_configured",
|
|
513
|
+
]
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Jiri Vyskocil
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Best-effort JSON event emitter for the terok-clearance hub.
|
|
5
|
+
|
|
6
|
+
Shield CLI calls (``up``/``down``) notify the hub so desktop/TUI consumers
|
|
7
|
+
can reflect the state change — in particular, the hub closes pending
|
|
8
|
+
block notifications for a container whose shield just dropped. Stays
|
|
9
|
+
stdlib-only so the reader script resource (which bypasses the package)
|
|
10
|
+
can mirror the same wire format without importing this module.
|
|
11
|
+
|
|
12
|
+
Every emit targets the *per-container* ingester socket under
|
|
13
|
+
``$XDG_RUNTIME_DIR/terok/events/<short_id>.sock``, where ``<short_id>``
|
|
14
|
+
is the 12-char prefix of the container id — the same addressing the
|
|
15
|
+
NFLOG reader uses, and deliberately distinct from the varlink
|
|
16
|
+
subscriber socket at ``terok/clearance/<id>.sock`` that operator UIs
|
|
17
|
+
glob. Callers therefore supply ``container_id`` (the full podman
|
|
18
|
+
container UUID) on every call: the destination socket is per-container,
|
|
19
|
+
so the id is what selects it.
|
|
20
|
+
|
|
21
|
+
Fails silent when the hub isn't listening: flipping shield state must
|
|
22
|
+
never be held up by a desktop-side daemon being absent.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import contextlib
|
|
28
|
+
import json
|
|
29
|
+
import logging
|
|
30
|
+
import os
|
|
31
|
+
import socket
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
from terok_shield._wire_sanitize import sanitize, sanitize_mapping
|
|
35
|
+
from terok_shield.validation import validate_container_id
|
|
36
|
+
|
|
37
|
+
_log = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
#: Cap on the socket connect/send syscalls so a dead but unreaped hub
|
|
40
|
+
#: (listener exists, accept thread wedged) can't block the shield CLI
|
|
41
|
+
#: for longer than the operator will patiently hold the keyboard.
|
|
42
|
+
_IO_TIMEOUT_S = 0.5
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _per_container_hub_socket(container_id: str) -> Path:
|
|
46
|
+
"""Return the per-container ingester path under ``$XDG_RUNTIME_DIR``.
|
|
47
|
+
|
|
48
|
+
Mirrors the NFLOG reader's path scheme (12-char short ID under
|
|
49
|
+
``terok/events/``) so every event for one container converges on the
|
|
50
|
+
same supervisor-owned ingester socket — without the truncation
|
|
51
|
+
match, ``shield_up``/``shield_down`` events and ``pending`` events
|
|
52
|
+
for the same container land on different sockets.
|
|
53
|
+
|
|
54
|
+
*container_id* is validated as a hex id before it is spliced into
|
|
55
|
+
the path: a malformed value (path separators, ``..``, leading slash)
|
|
56
|
+
could otherwise escape ``terok/events/`` or redirect the connection.
|
|
57
|
+
|
|
58
|
+
Raises:
|
|
59
|
+
ValueError: If *container_id* is not a 12-to-64-char hex string.
|
|
60
|
+
"""
|
|
61
|
+
validate_container_id(container_id)
|
|
62
|
+
xdg = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
|
|
63
|
+
return Path(xdg) / "terok" / "events" / f"{container_id[:12]}.sock"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class HubEventEmitter:
|
|
67
|
+
"""One-shot writer of JSON-line events to the hub's unix ingester.
|
|
68
|
+
|
|
69
|
+
Each ``emit_*`` call opens a fresh connection to the per-container
|
|
70
|
+
socket, sends a single line, and closes. The hub stays up across
|
|
71
|
+
many CLI invocations while each CLI invocation is short-lived —
|
|
72
|
+
pooling would save nothing and would complicate the fail-silent
|
|
73
|
+
semantics.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
def shield_up(
|
|
77
|
+
self,
|
|
78
|
+
container: str,
|
|
79
|
+
container_id: str,
|
|
80
|
+
*,
|
|
81
|
+
dossier: dict[str, str] | None = None,
|
|
82
|
+
) -> None:
|
|
83
|
+
"""Emit a ``shield_up`` event for *container* (optional *dossier*).
|
|
84
|
+
|
|
85
|
+
*container_id* — full podman container UUID; routes the event
|
|
86
|
+
to the supervisor's per-container hub socket.
|
|
87
|
+
|
|
88
|
+
*dossier* mirrors the orchestrator-supplied identity bundle the
|
|
89
|
+
per-container reader already attaches to ``connection_blocked``
|
|
90
|
+
events; passing it through here keeps the clearance UI's
|
|
91
|
+
rendering of every event for the same container consistent
|
|
92
|
+
(``project/task · name`` rather than the bare container slug).
|
|
93
|
+
Empty / omitted dossier omits the key entirely.
|
|
94
|
+
"""
|
|
95
|
+
self._send(container_id, {"type": "shield_up", "container": container}, dossier)
|
|
96
|
+
|
|
97
|
+
def shield_down(
|
|
98
|
+
self,
|
|
99
|
+
container: str,
|
|
100
|
+
container_id: str,
|
|
101
|
+
*,
|
|
102
|
+
allow_all: bool = False,
|
|
103
|
+
dossier: dict[str, str] | None = None,
|
|
104
|
+
) -> None:
|
|
105
|
+
"""Emit a ``shield_down`` (or ``shield_disengaged``) event for *container*.
|
|
106
|
+
|
|
107
|
+
*container_id* — see
|
|
108
|
+
[`shield_up`][terok_shield._hub_events.HubEventEmitter.shield_up].
|
|
109
|
+
|
|
110
|
+
*dossier* — see
|
|
111
|
+
[`shield_up`][terok_shield._hub_events.HubEventEmitter.shield_up].
|
|
112
|
+
"""
|
|
113
|
+
event_type = "shield_disengaged" if allow_all else "shield_down"
|
|
114
|
+
self._send(container_id, {"type": event_type, "container": container}, dossier)
|
|
115
|
+
|
|
116
|
+
def _send(
|
|
117
|
+
self,
|
|
118
|
+
container_id: str,
|
|
119
|
+
payload: dict,
|
|
120
|
+
dossier: dict[str, str] | None = None,
|
|
121
|
+
) -> None:
|
|
122
|
+
"""Write one JSON line to the per-container ingester socket, swallowing all I/O errors.
|
|
123
|
+
|
|
124
|
+
*container_id* selects the destination socket
|
|
125
|
+
(``$XDG_RUNTIME_DIR/terok/events/<short_id>.sock`` where
|
|
126
|
+
``<short_id> = container_id[:12]``); the caller — the shield
|
|
127
|
+
CLI — knows the full UUID at every emit site.
|
|
128
|
+
|
|
129
|
+
*dossier* is folded into the payload only when non-empty —
|
|
130
|
+
keeps the wire flat for standalone containers (``podman run``
|
|
131
|
+
without orchestrator annotations) so the ingester only has
|
|
132
|
+
to handle the dossier key when one is actually populated.
|
|
133
|
+
|
|
134
|
+
Every string value is run through the producer-side sanitiser
|
|
135
|
+
(``WIRE_SPEC(safe-string)``) before serialisation so the wire
|
|
136
|
+
format invariant — printable ASCII, length-capped — holds at
|
|
137
|
+
the boundary the container actually crosses. The clearance
|
|
138
|
+
hub re-applies the same rule on receive as belt-and-braces.
|
|
139
|
+
"""
|
|
140
|
+
sanitised: dict[str, object] = {
|
|
141
|
+
k: sanitize(v) if isinstance(v, str) else v for k, v in payload.items()
|
|
142
|
+
}
|
|
143
|
+
if dossier:
|
|
144
|
+
sanitised["dossier"] = sanitize_mapping(dossier)
|
|
145
|
+
line = (json.dumps(sanitised, separators=(",", ":")) + "\n").encode()
|
|
146
|
+
path = _per_container_hub_socket(container_id)
|
|
147
|
+
try:
|
|
148
|
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
149
|
+
sock.settimeout(_IO_TIMEOUT_S)
|
|
150
|
+
with contextlib.closing(sock):
|
|
151
|
+
sock.connect(str(path))
|
|
152
|
+
sock.sendall(line)
|
|
153
|
+
except OSError as exc:
|
|
154
|
+
# Hub absent, socket path stale, peer buffer full — none of
|
|
155
|
+
# these should block a state-change CLI command. Log at debug
|
|
156
|
+
# so a diagnosing operator can still see the reason.
|
|
157
|
+
_log.debug("hub event emit failed (%s): %s", payload.get("type"), exc)
|