This commit is contained in:
DurkaHelper contributors committed 2026-10-10 07:29:48 +03:00
commit 303438d206
217 files changed
+66681

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
<a id="deployment-kit"></a>
# Deployment kit
[English](README.md) | Русский
Для обычной работы используйте `durka.py`. Он связывает поддерживаемый deployment S4DFarm/Neo/Packmate, генерирует приватные пароли и автоматически обрабатывает внутренние ID/checksum образов.
<a id="configure-and-start"></a>
## Настроить и запустить
```bash
python3 durka.py init
```
Заполните `local/durka.json`: Ethernet bind, список команд, формат флага, receiver/token и IP сервиса для Packmate. Подготовьте при доступном Интернете:
```bash
python3 durka.py setup
python3 durka.py up
python3 durka.py status
```
`setup` получает закреплённые исходники/образы и собирает четыре поддерживаемых source-компонента. `up` поднимает ферму, координатор Neo и Packmate FILE UI. Отправку и исполнение Neo не включает.
```bash
python3 durka.py worker
python3 durka.py submit
```
Worker включайте после подготовки доверенных скриптов/зависимостей. Отправку — после проверки адаптера/receiver соревнования. Поддерживается только `ructf_http`; это не выбор протокола для неизвестного соревнования.
<a id="change-event-settings"></a>
## Изменить настройки площадки
Если изменились LAN-адреса, команды, отправка или IP сервиса Packmate, остановите стек, отредактируйте конфиг, примените настройки и снова запустите:
```bash
python3 durka.py down
python3 durka.py configure
python3 durka.py up
```
Редактируйте `local/durka.json` между первой и второй командой. Данные сохраняются, используются кешированные образы; скачивания/пересборки нет. Замена платформы или учётных данных требует отдельной подготовки.
<a id="traffic-and-shutdown"></a>
## Трафик и остановка
```bash
python3 durka.py traffic import /path/to/closed-capture.pcap
python3 durka.py down
```
Импорт заменяет **закрытый** PCAP, сохраняет предыдущий и перезапускает только Packmate. Зарегистрируйте сервис/шаблон и один раз нажмите жёлтую кнопку обработки со стрелкой вниз в UI. `down` сохраняет данные и образы.
На Apple Silicon текущий Packmate работает через amd64-эмуляцию. LAN и скорость проверяются на целевой машине. Разрешённый Linux LIVE и ручной capture описаны в [трафике](../docs/traffic-capture-RU.md). Обычный Docker Desktop deployment — только FILE.
<a id="advanced-tools"></a>
## Расширенные инструменты
Они остаются для специальных операций, автоматизации и диагностики; это не дополнительные шаги знакомства с тулсетом:
| Скрипт | Назначение |
|---|---|
| `toolkit.py` | Прямой preview/prepare/build/preflight/start/stop |
| `packmate_file.py` | Ограниченная замена PCAP с сохранением старого файла и app-only restart |
| `packmate_host.py` | Разрешённый native Linux host-interface LIVE |
| `packmate_live.py` | Разрешённый существующий Linux container-namespace LIVE |
| `recovery.py` | Native backup стека, проверка и изолированный restore БД |
| `recovery_activation.py` | Restore/check/activation нового приложения-кандидата |
Прямые скрипты записи имеют явные `--apply`/confirmation-параметры; точные входы смотрите в help операции. Общий prune хоста не выполняется.
<a id="native-backup-and-quarantine-restore"></a>
<a id="backup-and-recovery"></a>
## Backup и recovery
Backup стека содержит секреты и native данные/состояние; храните вне Git и трансляции. Нужны окно обслуживания без параллельной записи и восстанавливаемый snapshot машины.
```bash
python3 deployment/recovery.py backup --help
python3 deployment/recovery.py verify --help
python3 deployment/recovery.py restore-native-stage --help
```
Backup останавливает запись, делает PostgreSQL native dumps, Redis snapshots и копирует остановленное состояние Neo/Redis. **Исходный стек остаётся остановленным для записи**, в том числе после прерывания. Restore создаёт новое изолированное хранилище, а не переписывает source. Образы и входной PCAP сохраняйте отдельно.
<a id="application-recovery-and-explicit-activation"></a>
<a id="application-recovery"></a>
## Восстановление приложений
```bash
python3 deployment/recovery_activation.py recover --help
python3 deployment/recovery_activation.py verify --help
python3 deployment/recovery_activation.py activate --help
```
Процедура берёт проверенные backup/stage, восстанавливает PostgreSQL и Neo в нового кандидата, проверяет вход/restart и оставляет его остановленным. **Все Redis-очереди/кеш/сессии кандидата удаляются**, чтобы не повторить старую работу; оригинальные RDB остаются в backup. Не используйте этот вариант, если эти значения должны сохраниться.
Activation отделена от restore и ничего не запускает. После принятия поднимите только выбранного кандидата, проверьте полезные действия и включите отправку/worker отдельно. Не запускайте source и замену на одинаковых endpoint.
<a id="approved-linux-container-namespace-live"></a>
<a id="linux-container-namespace-live"></a>
## Linux container-namespace LIVE
`packmate_live.py` работает с разрешённым существующим, запущенным single-bridge container namespace на native Linux amd64 Engine. У owner/network должны быть capture-label и опубликованный UI. Используется NET_RAW, а не privileged; БД доступна соседям bridge. Mirroring и общий захват хоста Vulnbox он не настраивает.
Для разрешённого host/mirror интерфейса используйте `packmate_host.py`. [Инструкция захвата](../docs/traffic-capture-RU.md) объясняет выбор и профиль. Ни один launcher не добавляет видимость пакетов Docker Desktop.
[Установка админа](../docs/MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) · [Шпаргалка админа](../docs/TEAM_LAN_ADMIN_CHEATSHEET-RU.md)
+101
View File
@@ -0,0 +1,101 @@
# Deployment kit
English | [Русский](README-RU.md)
Use `durka.py` for normal operation. It connects the maintained S4DFarm/Neo/Packmate deployment, generates private credentials and handles internal image IDs/checksums automatically.
## Configure and start
```bash
python3 durka.py init
```
Edit `local/durka.json`: Ethernet bind, competition teams, flag format, receiver/token and Packmate service-side IP. Then prepare while connected:
```bash
python3 durka.py setup
python3 durka.py up
python3 durka.py status
```
`setup` fetches the pinned sources/images and builds the four maintained source components. `up` starts the farm, Neo coordinator and Packmate FILE UI. It starts neither submission nor Neo execution.
```bash
python3 durka.py worker
python3 durka.py submit
```
Enable the worker after preparing trusted scripts/dependencies. Enable submission after checking the competition adapter/receiver. Only `ructf_http` is maintained; this does not select the protocol for an unknown competition.
## Change event settings
For changed LAN addresses, team maps, submission settings or Packmate service IP, stop the stack, edit the local config, apply configuration, then start again:
```bash
python3 durka.py down
python3 durka.py configure
python3 durka.py up
```
Edit `local/durka.json` between the first and second command. This preserves data and uses cached images; it does not rebuild/download. Platform or credential replacement needs separate preparation.
## Traffic and shutdown
```bash
python3 durka.py traffic import /path/to/closed-capture.pcap
python3 durka.py down
```
Import replaces a **closed** PCAP, preserves the previous file and restarts only Packmate. Register the service/pattern and click the yellow downward-arrow processing button once in its UI. `down` retains data and images.
On Apple Silicon the current Packmate image uses amd64 emulation. Shared LAN and performance must be checked on the intended machine. For permitted Linux LIVE and manual capture, see [traffic capture](../docs/traffic-capture.md). Ordinary Docker Desktop deployment is FILE-only.
## Advanced tools
These remain available for dedicated operations, automation and troubleshooting; they are not extra onboarding steps:
| Script | Purpose |
|---|---|
| `toolkit.py` | Preview/prepare/build/preflight/start/stop the maintained deployment directly |
| `packmate_file.py` | Bounded PCAP replacement, prior-file retention and app-only restart |
| `packmate_host.py` | Approved native Linux host-interface LIVE |
| `packmate_live.py` | Approved existing Linux container-namespace LIVE |
| `recovery.py` | Native stack backup, verification and isolated database restore |
| `recovery_activation.py` | New application candidate restore/check/activation |
Direct mutating scripts have explicit `--apply`/confirmation flags; use their help for the operation's exact inputs. They never perform a host-wide prune.
<a id="native-backup-and-quarantine-restore"></a>
## Backup and recovery
Backups for this stack contain secrets and native database/state data; keep them outside Git and broadcasts. Use an exclusive maintenance window and a recoverable machine snapshot.
```bash
python3 deployment/recovery.py backup --help
python3 deployment/recovery.py verify --help
python3 deployment/recovery.py restore-native-stage --help
```
Backup pauses writers, dumps PostgreSQL natively, snapshots Redis and copies stopped Neo/Redis state. **The source stays quiesced**, including after an interrupted attempt. Restore creates new isolated storage; it does not overwrite the source. Retain images and input PCAP separately.
<a id="application-recovery-and-explicit-activation"></a>
## Application recovery
```bash
python3 deployment/recovery_activation.py recover --help
python3 deployment/recovery_activation.py verify --help
python3 deployment/recovery_activation.py activate --help
```
Application recovery consumes the verified backup/stage, restores PostgreSQL and Neo into a new candidate, checks authenticated startup/restart and leaves it stopped. **All candidate Redis queues/cache/sessions are discarded** to avoid replay; original RDBs stay in the backup. Do not use this policy if those values must be preserved.
Activation is separate from restore and starts no services. After acceptance, start only the chosen candidate, verify useful application scenarios and deliberately enable submission/worker. Never run the original and replacement on the same endpoints.
<a id="approved-linux-container-namespace-live"></a>
## Linux container-namespace LIVE
`packmate_live.py` serves an approved existing, running single-bridge container namespace on native Linux amd64 Engine. The owner/network need the expected capture ownership label and UI publication. It uses NET_RAW, not privileged mode; the database is reachable by peers on that bridge. It does not configure mirroring or general Vulnbox host capture.
Use `packmate_host.py` for an approved host/mirror interface instead. [Capture instructions](../docs/traffic-capture.md) explain the choice and exact profile. None of these launchers adds packet visibility to Docker Desktop.
[Administrator setup](../docs/MACOS_FULL_DEPLOYMENT_AND_TESTING.md) · [Admin cheat sheet](../docs/TEAM_LAN_ADMIN_CHEATSHEET.md)
+7
View File
@@ -0,0 +1,7 @@
{
"farm_password": "REPLACE_WITH_A_UNIQUE_RANDOM_VALUE",
"database_password": "REPLACE_WITH_A_UNIQUE_RANDOM_VALUE",
"neo_key": "REPLACE_WITH_A_UNIQUE_RANDOM_VALUE",
"packmate_user": "operator",
"packmate_password": "REPLACE_WITH_A_UNIQUE_RANDOM_VALUE"
}
+213
View File
@@ -0,0 +1,213 @@
"""Read-only host checks for the first Apple Silicon deployment.
Only local metadata and explicit read-only CLI operations are used. In
particular, this module never starts Desktop, executes Neo, or fetches images.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
import platform
import re
import shutil
import stat
import struct
import subprocess
import sys
from types import SimpleNamespace
GIB = 1024 ** 3
def query(argv, empty_ok=False):
"""Caller supplies fixed read-only commands; suppress all raw diagnostics."""
try:
result = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, timeout=10, check=False)
if len(result.stdout) > 65536 or len(result.stderr) > 65536:
return None
if result.returncode and not (empty_ok and result.returncode == 1 and not result.stderr and not result.stdout):
return None
return result.stdout.decode('utf-8', errors='strict').strip()
except (OSError, ValueError, UnicodeError, subprocess.SubprocessError):
return None
def neo_arm64(path, kit):
"""Inspect a regular Mach-O header, never execute a downloaded program."""
path = kit.shared.no_links(Path(path).absolute())
before = path.lstat()
if not stat.S_ISREG(before.st_mode) or not 32 <= before.st_size <= 64 * 1024 * 1024:
return False
descriptor = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0))
try:
opened = os.fstat(descriptor)
raw = os.read(descriptor, 4096)
after = os.fstat(descriptor)
current = path.lstat()
if (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) != (opened.st_dev, opened.st_ino, opened.st_size, opened.st_mtime_ns):
return False
if (opened.st_dev, opened.st_ino, opened.st_size, opened.st_mtime_ns) != (current.st_dev, current.st_ino, current.st_size, current.st_mtime_ns):
return False
if (opened.st_size, opened.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
return False
if os.name != 'nt' and not opened.st_mode & 0o111:
return False
if raw[:4] == b'\xcf\xfa\xed\xfe':
return struct.unpack_from('<I', raw, 4)[0] == 0x0100000C and struct.unpack_from('<I', raw, 12)[0] == 2
# Universal executables are accepted only with a bounded ARM64 slice.
if raw[:4] in (b'\xca\xfe\xba\xbe', b'\xca\xfe\xba\xbf'):
count = struct.unpack_from('>I', raw, 4)[0]
width = 20 if raw[:4] == b'\xca\xfe\xba\xbe' else 32
if not 1 <= count <= 16 or len(raw) < 8 + width * count:
return False
for index in range(count):
position = 8 + width * index
cpu = struct.unpack_from('>I', raw, position)[0]
offset, size = struct.unpack_from('>II' if width == 20 else '>QQ', raw, position + 8)
if cpu == 0x0100000C and offset >= 8 + width * count and size >= 32 and offset + size <= opened.st_size:
os.lseek(descriptor, offset, os.SEEK_SET)
header = os.read(descriptor, 32)
return (header[:4] == b'\xcf\xfa\xed\xfe' and struct.unpack_from('<I', header, 4)[0] == cpu
and struct.unpack_from('<I', header, 12)[0] == 2)
return False
finally:
os.close(descriptor)
def inspect(operator, config, neo_client=None):
kit = operator.kit
rows = []
def add(name, status, detail, next_step=''):
rows.append(dict(check=name, status=status, detail=detail, guidance=next_step))
mac = platform.system() == 'Darwin'
machine = platform.machine()
version = platform.mac_ver()[0] if mac else ''
add('macOS ARM64', 'READY' if mac and machine == 'arm64' and version else 'BLOCKED',
('macOS ' + version + ' / ' + machine) if mac else 'This is not macOS; no Mac compatibility is inferred.',
'Run on the approved Mac with native ARM64 Python (not a Rosetta shell).')
add('Python', 'READY' if sys.version_info >= (3, 10) else 'BLOCKED',
'.'.join(map(str, sys.version_info[:3])), 'Python 3.10+ is required; installation is a separate approved step.')
git = query(['git', '--version']) if shutil.which('git') else None
git_match = re.fullmatch(r'git version (\d+)\.(\d+)\.[\w. ()-]+', git or '')
add('Git', 'READY' if git_match and tuple(map(int, git_match.groups())) >= (2, 30) else 'BLOCKED',
git if git_match else 'Git unavailable or version could not be verified.', 'Prepare Git 2.30+ before setup.')
value, paths = None, {'workspace': operator.ROOT / 'local/workspace'}
try:
value, paths = operator.load_config(config)
cfg = operator.config_path(config)
private = os.name == 'nt' or (not cfg.stat().st_mode & 0o077 and not cfg.parent.stat().st_mode & 0o077)
expected = {'os': 'darwin', 'architecture': 'arm64', 'runtime': 'docker-desktop'}
add('Local configuration', 'READY' if private and value['profile']['platform'] == expected else 'BLOCKED',
'Schema valid; values and credentials are not printed.',
'Use a private config/directory and the Darwin ARM64 Docker Desktop profile; see the first-run guide.')
add('Submission safety', 'WARNING', 'Maintained adapter: ructf_http. Do not run submit during acceptance.',
'Keep the example endpoint/token until protocol compatibility is reviewed; other protocols need separate validation.')
except (kit.Error, OSError, ValueError, TypeError, KeyError):
add('Local configuration', 'BLOCKED', 'Missing, invalid, linked or unreadable operator configuration; raw values suppressed.',
'After approval: python3 durka.py init; edit local/durka.json using the first-run guide.')
available = bool(shutil.which('docker'))
add('Docker CLI', 'READY' if available else 'BLOCKED', 'Available.' if available else 'Not found.',
'Install/start Docker Desktop only after approval; doctor does not start it.')
desktop = mac and (Path('/Applications/Docker.app').is_dir() or (Path.home() / 'Applications/Docker.app').is_dir())
add('Docker Desktop application', 'READY' if desktop else 'NOT VERIFIED',
'Application directory found (not a running-engine test).' if desktop else 'Standard application location not confirmed.',
'Check the approved installation and Desktop version manually.')
engine = None
local = False
if available:
# Never inspect a remotely selected daemon as evidence about this laptop.
endpoint = os.environ.get('DOCKER_HOST') if not os.environ.get('DOCKER_CONTEXT') else None
if not endpoint:
endpoint = query(['docker', 'context', 'inspect', '--format', '{{.Endpoints.docker.Host}}'])
local = bool(endpoint and endpoint.startswith('unix://') and not endpoint[7:].startswith('@'))
add('Docker endpoint', 'READY' if local else 'BLOCKED',
'Local Unix socket selected.' if local else 'Local daemon not confirmed; remote queries skipped.',
'Select the local Desktop context yourself; do not use a remote Engine for this check.')
if local:
# Select fields, never dump daemon configuration, proxies or credentials.
text = query(['docker', 'info', '--format', '{"os":{{json .OSType}},"arch":{{json .Architecture}},"desktop":{{json .OperatingSystem}},"cpus":{{.NCPU}},"memory":{{.MemTotal}}}'])
try:
parsed = json.loads(text or '')
if (isinstance(parsed, dict) and parsed.get('os') == 'linux' and parsed.get('arch') in ('aarch64', 'arm64')
and isinstance(parsed.get('cpus'), int) and not isinstance(parsed['cpus'], bool)
and isinstance(parsed.get('memory'), int) and not isinstance(parsed['memory'], bool)
and isinstance(parsed.get('desktop'), str) and 'docker desktop' in parsed['desktop'].lower()):
engine = parsed
except (ValueError, TypeError, KeyError):
pass
add('Docker Desktop Engine', 'READY' if engine else 'BLOCKED',
'Responsive Linux ARM64 Desktop Engine.' if engine else 'Desktop Engine is stopped, unavailable, or not confirmed as local ARM64.',
'Open the approved Docker Desktop app and retry; raw Docker output is suppressed.')
compose = query(['docker', 'compose', 'version', '--short']) if available else None
compose_match = re.fullmatch(r'v?(\d+)\.(\d+)\.\d+(?:[-+][\w.-]+)?', compose or '')
add('Compose', 'READY' if compose_match and int(compose_match[1]) >= 2 else 'BLOCKED',
compose if compose_match else 'Compose version unavailable.', 'Docker Compose v2+ is required.')
add('Docker resources', 'NOT VERIFIED' if engine is None else 'READY' if engine['cpus'] >= 4 and engine['memory'] >= 8 * GIB else 'WARNING',
'CPU/RAM allocation unavailable.' if engine is None else f"{engine['cpus']} CPUs / {engine['memory'] / GIB:.1f} GiB allocated.",
'Start with 4 CPUs / 8 GiB on a 16 GiB laptop; measure stack load before increasing limits.')
try:
location = paths['workspace']
while not location.exists():
if location.parent == location:
raise OSError('workspace filesystem unavailable')
location = location.parent
free = shutil.disk_usage(location).free
add('Disk space', 'BLOCKED' if free < 10 * GIB else 'WARNING' if free < 96 * GIB else 'READY',
f'{free / GIB:.1f} GiB free on the workspace filesystem.',
'Plan at least 96 GiB for Desktop images/data plus separate backup space; VM disk capacity remains a manual check.')
except (OSError, ValueError):
add('Disk space', 'NOT VERIFIED', 'Workspace filesystem capacity unavailable.', 'Check free space and Desktop disk quota manually.')
ports = sorted(value['profile']['ports'].values()) if value else [8080, 5005, 65000]
listeners = query(['lsof', '-nP', '-a', '-iTCP:' + ','.join(map(str, ports)), '-sTCP:LISTEN', '-Fn'], empty_ok=True) if mac and shutil.which('lsof') else None
add('Required TCP ports', 'NOT VERIFIED' if listeners is None else 'WARNING' if listeners else 'READY',
', '.join(map(str, ports)) + (': listeners detected; names/addresses suppressed.' if listeners else ': no visible listeners.' if listeners is not None else ': not checked.'),
'If already running, these may be your services. Resolve conflicts without killing unrelated processes; LAN access still needs two-device testing.')
prepared = False
if value and engine and local:
try:
operator.pending(paths['workspace'])
root, _, _, _ = operator.check_config(paths['workspace'], value)
result = kit.execute(SimpleNamespace(action='preflight', workspace=str(root), runtime=True, apply=False))
prepared = result.get('runtime') == 'PASS'
except (kit.Error, OSError, ValueError, TypeError, KeyError, subprocess.SubprocessError):
pass
add('Prepared runtime / cached image platforms', 'READY' if prepared else 'BLOCKED',
'Existing runtime preflight passed: configuration, ownership, immutable cached images and platforms match.' if prepared else 'Not verified; missing cache/build receipt, changed config, or runtime check failed.',
'After approval and with Internet: setup. If prepared already, use the existing deployment preflight to diagnose; do not rebuild/delete data blindly.')
add('Packmate emulation', 'WARNING', 'Pinned Packmate is Linux AMD64; Apple Silicon uses emulation. FILE is not continuous LIVE capture.',
'Measure import latency/storage on the Mac. LIVE needs an approved Linux traffic source; closed PCAP transfer is a fallback only.')
try:
binary = Path(neo_client) if neo_client else operator.ROOT / 'local/neo-client/neo'
client = neo_arm64(binary, kit)
except (kit.Error, OSError, ValueError, TypeError, struct.error):
client = False
add('Neo Darwin ARM64 client', 'READY' if client else 'BLOCKED',
'Executable ARM64 Mach-O present; header check only, version/auth not proven.' if client else 'Native client missing, non-executable, linked or wrong format/architecture.',
'Prepare the locked v2.4.2 Darwin ARM64 release before going offline; pass --neo-client PATH if installed elsewhere. Never print neo info on a shared screen.')
add('Offline / real Mac acceptance', 'NOT VERIFIED', 'Cached-image inspection is not an offline cold start. Hosted CI does not prove Desktop, LAN or local policy compatibility.',
'Complete MACOS_FIRST_RUN-RU.md and the isolated stack procedure; keep submission disabled. Workers need every script dependency inside their selected image.')
statuses = {row['status'] for row in rows}
status = 'BLOCKED' if 'BLOCKED' in statuses else 'WARNING' if 'WARNING' in statuses else 'NOT VERIFIED' if 'NOT VERIFIED' in statuses else 'READY'
return dict(tool='DurkaHelper doctor', read_only=True, status=status, competition_ready=False,
exit_code=2 if status == 'BLOCKED' else 1 if status in ('WARNING', 'NOT VERIFIED') else 0, checks=rows)
def run(operator, args):
report = inspect(operator, args.config, args.neo_client)
if args.json:
print(json.dumps(report, ensure_ascii=True, sort_keys=True, indent=2))
else:
print('DurkaHelper doctor: ' + report['status'] + ' (read-only; not competition certification)')
for row in report['checks']:
print(row['status'] + ' | ' + row['check'] + ': ' + row['detail'])
if row['status'] != 'READY':
print(' Next: ' + row['guidance'])
return report['exit_code']
+294
View File
@@ -0,0 +1,294 @@
#!/usr/bin/env python3
"""Safely replace one closed PCAP in an existing maintained FILE deployment.
Only Packmate is stopped/restarted. Its database is retained and must already
be running. Processing is NOT started: configure services/patterns, then press
Start once in the UI. A FILE session must be restarted between closed files.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import secrets
import stat
import struct
import sys
SPEC = importlib.util.spec_from_file_location("file_recovery_activation", Path(__file__).with_name("recovery_activation.py"))
activation = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(activation)
rec, kit, ops, Error = activation.rec, activation.kit, activation.ops, activation.Error
MAX_BYTES = 512 * 1024 * 1024
MAX_BLOCK = 16 * 1024 * 1024
SCHEMA = "durkahelper.closed-pcap-replacement.v1"
def pcap_summary(descriptor):
"""Bound framing/hash validation, not traffic analysis or content acceptance."""
before = os.fstat(descriptor)
if not stat.S_ISREG(before.st_mode) or not 24 <= before.st_size <= MAX_BYTES:
raise Error("closed capture must be a bounded regular file (24 bytes to 512 MiB)")
os.lseek(descriptor, 0, os.SEEK_SET)
digest, size, packets = hashlib.sha256(), 0, 0
with os.fdopen(os.dup(descriptor), "rb") as stream:
def read(count, eof=False):
nonlocal size
value = stream.read(count)
size += len(value)
if size > MAX_BYTES or (len(value) != count and not (eof and not value)):
raise Error("capture framing is truncated or exceeds byte bounds")
digest.update(value)
return value
def discard(count):
while count:
take = min(count, 65536)
read(take)
count -= take
magic = read(4)
classic = {b"\xd4\xc3\xb2\xa1": ("<", 1000000), b"\xa1\xb2\xc3\xd4": (">", 1000000),
b"\x4d\x3c\xb2\xa1": ("<", 1000000000), b"\xa1\xb2\x3c\x4d": (">", 1000000000)}
if magic in classic:
endian, resolution = classic[magic]
major, minor, zone, accuracy, snaplen, linktype = struct.unpack(endian + "HHIIII", read(20))
if (major, minor) != (2, 4) or not 1 <= snaplen <= MAX_BLOCK:
raise Error("unsupported PCAP version or snapshot length")
while True:
header = read(16, eof=True)
if not header:
break
seconds, fraction, captured, original = struct.unpack(endian + "IIII", header)
if captured > min(snaplen, original) or fraction >= resolution:
raise Error("invalid PCAP packet lengths or timestamp framing")
discard(captured)
packets += 1
if packets > 2_000_000:
raise Error("PCAP packet count exceeds bound")
kind = "PCAP"
elif magic == b"\x0a\x0d\x0d\x0a":
endian, blocks, block_type = None, 0, magic
while block_type:
length_raw = read(4)
if block_type == magic:
bom = read(4)
endian = {b"\x4d\x3c\x2b\x1a": "<", b"\x1a\x2b\x3c\x4d": ">"}.get(bom)
if endian is None:
raise Error("invalid PCAPNG byte order marker")
length = struct.unpack(endian + "I", length_raw)[0]
if not 28 <= length <= MAX_BLOCK or length % 4:
raise Error("invalid PCAPNG section length")
version = read(4)
if struct.unpack(endian + "HH", version) != (1, 0):
raise Error("unsupported PCAPNG section version")
discard(length - 20)
else:
length = struct.unpack(endian + "I", length_raw)[0]
if not 12 <= length <= MAX_BLOCK or length % 4:
raise Error("invalid PCAPNG block length")
number = struct.unpack(endian + "I", block_type)[0]
if number in {2, 3, 6}:
packets += 1
discard(length - 12)
if struct.unpack(endian + "I", read(4))[0] != length:
raise Error("PCAPNG block footer mismatch")
blocks += 1
if blocks > 2_000_000:
raise Error("PCAPNG block count exceeds bound")
block_type = read(4, eof=True)
kind = "PCAPNG"
else:
raise Error("input is not a supported closed PCAP/PCAPNG container")
if ops._stat_identity(before) != ops._stat_identity(os.fstat(descriptor)) or size != before.st_size:
raise Error("capture changed while validating; close the writer and record a new checksum")
return before, {"format": kind, "bytes": size, "sha256": digest.hexdigest(), "packet_records": packets,
"validation": "container framing only; upstream import acceptance not run"}
def inspect_file(path, expected=None):
source = ops._canonical_input_leaf(Path(path))
descriptor = ops._open_anchored_regular(source.parent, source.name, ops._root_anchor_identity(source.parent.stat()))
try:
metadata, summary = pcap_summary(descriptor)
finally:
os.close(descriptor)
if expected is not None and summary["sha256"] != expected:
raise Error("closed capture does not match independently recorded SHA-256")
return source, metadata, summary
def gates(args):
if not args.approval_id or not re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id):
raise Error("replacement requires a non-secret approval ID")
if not args.closed_pcap_confirmed or not args.maintenance_confirmed:
raise Error("replacement requires closed capture and exclusive file-maintenance confirmations")
if os.name != "posix" or os.geteuid() == 0:
raise Error("FILE replacement requires a non-root POSIX operator")
rec.daemon(args.daemon_id)
def stage_files(root, source, summary, previous, previous_summary):
target = root / ("pcap-import-" + secrets.token_hex(8))
staging = ops._StagingDirectory.create(target, ".closed-pcap-")
try:
for source_path, destination, expected in ((source, "incoming.pcap", summary), (previous, "previous.pcap", previous_summary)):
metadata, digest = ops._copy_stable(source_path.parent, source_path.name, (staging, destination), MAX_BYTES,
[0, MAX_BYTES], ops._root_anchor_identity(source_path.parent.stat()))
if metadata.st_size != expected["bytes"] or digest != expected["sha256"]:
raise Error("closed capture changed while creating immutable replacement/rollback copies")
receipt = {"schema": SCHEMA, "configured_file": previous.name, "incoming": summary, "previous": previous_summary}
staging.write_new_bytes("replacement.json", ops._canonical(receipt))
ops._publish_directory(staging, target)
finally:
staging.cleanup()
return target
def cutover(root, configured_name, transaction, expected_previous, expected_new):
"""Descriptor-anchored cutover, with a retained immutable rollback copy."""
folder = ops._canonical_root_directory(root / "pcaps")
anchor = ops._root_anchor_identity(folder.stat())
directory = os.open(folder, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
source_fd = new_fd = old_fd = None
temporary = ".pcap-next-" + secrets.token_hex(12)
new_identity = None
try:
if ops._root_anchor_identity(os.fstat(directory)) != anchor:
raise Error("configured capture directory changed")
old_fd = os.open(configured_name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
old_meta, old_summary = pcap_summary(old_fd)
if old_summary != expected_previous:
raise Error("previous configured capture changed before cutover")
source_fd = ops._open_anchored_regular(transaction, "incoming.pcap", ops._root_anchor_identity(transaction.stat()))
_, source_summary = pcap_summary(source_fd)
if source_summary != expected_new:
raise Error("immutable incoming capture changed before cutover")
os.lseek(source_fd, 0, os.SEEK_SET)
new_fd = os.open(temporary, os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=directory)
new_identity = ops._root_anchor_identity(os.fstat(new_fd))
copied = 0
for chunk in iter(lambda: os.read(source_fd, 65536), b""):
copied += len(chunk)
if copied > min(MAX_BYTES, expected_new["bytes"]):
raise Error("immutable incoming capture grew during copy")
ops._write_all(new_fd, chunk)
os.fchmod(new_fd, 0o644)
os.fsync(new_fd)
_, staged_summary = pcap_summary(new_fd)
if staged_summary != expected_new:
raise Error("incoming copy changed before cutover")
named = os.stat(configured_name, dir_fd=directory, follow_symlinks=False)
if (ops._stat_identity(named) != ops._stat_identity(old_meta) or
ops._stat_identity(os.fstat(old_fd)) != ops._stat_identity(old_meta) or
ops._root_anchor_identity(os.stat(temporary, dir_fd=directory, follow_symlinks=False)) != new_identity or
ops._root_anchor_identity(folder.stat()) != anchor):
raise Error("capture path changed before cutover; rollback retained")
replace_error = None
try:
os.replace(temporary, configured_name, src_dir_fd=directory, dst_dir_fd=directory)
except BaseException as error:
replace_error = error
named = os.stat(configured_name, dir_fd=directory, follow_symlinks=False)
if ops._root_anchor_identity(named) != new_identity:
if replace_error is not None:
raise replace_error
raise Error("capture destination changed at cutover; app must remain stopped; rollback retained")
descriptor = os.open(configured_name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
try:
final_meta, final_summary = pcap_summary(descriptor)
if ops._root_anchor_identity(final_meta) != new_identity or final_summary != expected_new:
raise Error("capture destination bytes changed at cutover; app must remain stopped")
finally:
os.close(descriptor)
os.fsync(directory)
finally:
for descriptor in (source_fd, new_fd, old_fd):
if descriptor is not None:
os.close(descriptor)
if new_identity is not None:
try:
named = os.stat(temporary, dir_fd=directory, follow_symlinks=False)
if ops._root_anchor_identity(named) == new_identity:
os.unlink(temporary, dir_fd=directory)
except FileNotFoundError:
pass
os.close(directory)
def replace(args):
if not isinstance(args.expected_sha256, str) or not re.fullmatch(r"[a-f0-9]{64}", args.expected_sha256):
raise Error("an independently recorded lower-case SHA-256 is required")
root, state, runtime, profile, _ = rec.source_workspace(args.workspace)
source, _, summary = inspect_file(args.pcap, args.expected_sha256)
previous, _, previous_summary = inspect_file(root / "pcaps" / profile["packmate"]["pcap_file"])
if source == previous:
raise Error("incoming capture must be separate from the configured current file")
if not args.apply:
return {"status": "NOT_RUN", "action": "replace", "daemon_contacted": False, "incoming": summary,
"effects": ["stop only Packmate", "retain private previous capture", "atomic file replacement", "restart only Packmate"],
"processing": "NOT_RUN; configure service/patterns then press Start once"}
gates(args)
context = (root, state["project"], runtime, args.daemon_id, kit.LABEL)
current = rec.owned(*context, exclusive=False)
if not current.get("packmate-db", {}).get("running"):
raise Error("owned Packmate database must already be running; this helper never starts dependencies")
kit.image_preflight({"services": {"packmate": runtime["services"]["packmate"]}}, profile)
transaction = None
succeeded = False
try:
rec.stop(context, ("packmate",), exclusive=False)
transaction = stage_files(root, source, summary, previous, previous_summary)
if rec.source_workspace(root)[2] != runtime:
raise Error("maintained deployment changed during file replacement")
current = rec.owned(*context, exclusive=False)
if current.get("packmate", {}).get("running") or not current.get("packmate-db", {}).get("running"):
raise Error("Packmate was restarted or database stopped while staging; no file replaced")
cutover(root, previous.name, transaction, previous_summary, summary)
current = rec.owned(*context, exclusive=False)
if current.get("packmate", {}).get("running") or not current.get("packmate-db", {}).get("running"):
raise Error("candidate Packmate was restarted or database stopped during maintenance")
rec.run(kit.command(root, state, runtime=True) + ["up", "--detach", "--no-deps", "--no-build", "--pull", "never", "packmate"], timeout=120)
activation.packmate_ready(root, profile)
current = rec.owned(*context, exclusive=False)
if not current.get("packmate", {}).get("running") or not current.get("packmate-db", {}).get("running"):
raise Error("Packmate readiness is not bound to owned running resources")
inspect_file(previous, summary["sha256"])
succeeded = True
finally:
if not succeeded:
rec.stop(context, ("packmate",), exclusive=False)
return {"status": "PASS", "action": "replace", "authenticated_ready": True, "capture_started": False,
"incoming": summary, "processing": "NOT_RUN; configure services/patterns then press Start once",
"database": "retained; importing overlapping captures may create duplicate stored traffic",
"rollback": {"relative_input": transaction.name + "/previous.pcap", "sha256": previous_summary["sha256"],
"procedure": "run this same explicit replacement command with previous.pcap and its checksum"},
"limits": ["container framing checked, not upstream packet compatibility", "FILE is not continuous LIVE capture"]}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("replace",))
for name in ("workspace", "pcap", "expected-sha256"):
parser.add_argument("--" + name, required=True)
for name in ("approval-id", "daemon-id"):
parser.add_argument("--" + name)
for name in ("apply", "closed-pcap-confirmed", "maintenance-confirmed"):
parser.add_argument("--" + name, action="store_true")
args = parser.parse_args(argv)
try:
print(json.dumps(replace(args), sort_keys=True, indent=2))
return 0
except (Exception, KeyboardInterrupt) as error:
print(json.dumps({"status": "BLOCKED", "reason": str(error) if isinstance(error, Error) else
"closed capture replacement rejected: " + type(error).__name__, "raw_output": "suppressed",
"rollback": "inspect private pcap-import-* copies; do not delete them; restart only after a verified replacement"}))
return 2
if __name__ == "__main__":
sys.exit(main())
+439
View File
@@ -0,0 +1,439 @@
#!/usr/bin/env python3
"""Opt-in native Linux host-interface Packmate; never a Desktop capture fallback.
The entire selected interface must be approved: unchanged upstream briefly uses
a broad TCP/UDP filter at startup. Host networking and NET_RAW are explicit
trust-boundary expansions. No interface, route or firewall is modified here.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import ipaddress
import json
import os
from pathlib import Path
import re
import secrets
import stat
import sys
SPEC = importlib.util.spec_from_file_location("host_live", Path(__file__).with_name("packmate_live.py"))
live = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(live)
kit, shared, Error = live.kit, live.shared, live.Error
SCHEMA = "durkahelper.packmate-host.v1"
LABEL = "io.durkahelper.packmate-host"
def profile(value):
keys = {"schema", "daemon_id", "interface", "ifindex", "interface_mac", "local_ip",
"bind_address", "ui_port", "db_port", "tcp_timeout_seconds", "udp_timeout_seconds",
"timeout_check_seconds", "retention_minutes", "cleanup_interval_minutes"}
if not isinstance(value, dict) or set(value) != keys or value["schema"] != SCHEMA:
raise Error("invalid host capture profile")
if not isinstance(value["daemon_id"], str) or not re.fullmatch(r"[A-Za-z0-9:_.-]{8,128}", value["daemon_id"]):
raise Error("exact approved Engine identity required")
if not isinstance(value["interface"], str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}", value["interface"]):
raise Error("one explicit Linux interface is required; any is not supported")
if value["interface"] == "any":
raise Error("any-interface capture is forbidden")
if type(value["ifindex"]) is not int or not 1 <= value["ifindex"] <= 2**31 - 1:
raise Error("exact interface index required")
if not isinstance(value["interface_mac"], str) or not re.fullmatch(r"(?:[a-f0-9]{2}:){5}[a-f0-9]{2}", value["interface_mac"]):
raise Error("exact interface hardware address required")
for key in ("local_ip", "bind_address"):
address = ipaddress.ip_address(value[key])
if address.version != 4 or address.is_unspecified or address.is_multicast or address.is_link_local:
raise Error("explicit unicast IPv4 required")
for key, lower, upper in (("ui_port", 1024, 65535), ("db_port", 1024, 65535),
("tcp_timeout_seconds", 1, 600), ("udp_timeout_seconds", 1, 600),
("timeout_check_seconds", 1, 60), ("retention_minutes", 1, 1440),
("cleanup_interval_minutes", 1, 60)):
if type(value[key]) is not int or not lower <= value[key] <= upper:
raise Error("invalid bounded host capture setting")
if value["ui_port"] == value["db_port"]:
raise Error("UI and loopback database ports must differ")
return value
def properties(config, secret):
# Reuse the pinned upstream field names and exact logger mitigation.
pairs = dict(line.split("=", 1) for line in live.properties(config, secret, "unused").decode("ascii").splitlines())
pairs.update({"spring.datasource.url": "jdbc:postgresql://127.0.0.1:" + str(config["db_port"]) + "/packmate",
"server.address": config["bind_address"], "server.port": str(config["ui_port"])})
return "".join(key + "=" + str(value) + "\n" for key, value in sorted(pairs.items())).encode("ascii")
def compose_spec(config, secret, project, images=None):
images = images or {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB}
base = {"restart": "no", "cpus": 1.0, "mem_limit": "512m", "pids_limit": 128,
"security_opt": ["no-new-privileges:true"], "logging": {"driver": "none"}, "labels": {LABEL: project}}
db = dict(base, image=images["db"], platform="linux/amd64",
environment={"POSTGRES_DB": "packmate", "POSTGRES_USER": "packmate", "POSTGRES_PASSWORD": secret["db_password"]},
volumes=["./data/postgres:/var/lib/postgresql/data"], networks=["database"],
ports=[{"target": 5432, "published": str(config["db_port"]), "host_ip": "127.0.0.1", "protocol": "tcp"}],
healthcheck={"test": ["CMD", "pg_isready", "-U", "packmate", "-d", "packmate"],
"interval": "2s", "timeout": "2s", "retries": 45})
app = dict(base, image=images["packmate"], platform="linux/amd64", user="0:0", read_only=True,
cap_drop=["ALL"], cap_add=["NET_RAW"], network_mode="host", mem_limit="1536m",
tmpfs=["/tmp:size=67108864,mode=1777,noexec,nosuid,nodev", "/jna:size=16777216,mode=0700,nosuid,nodev,exec"],
volumes=["./application.properties:/configuration/application.properties:ro"], entrypoint=["java"],
command=["-Xms64m", "-Xmx768m", "-XX:ActiveProcessorCount=1", "-Djna.tmpdir=/jna",
"-Djava.net.preferIPv4Stack=true", "-jar", "/app/app.jar",
"--spring.config.additional-location=file:/configuration/application.properties"],
depends_on={"db": {"condition": "service_healthy"}})
return {"services": {"db": db, "packmate": app}, "networks": {"database": {"labels": {LABEL: project}}}}
def prepare(args):
config, secret = profile(kit.load(args.profile)), live.credentials(kit.load(args.credentials))
root = kit.safe_path(args.workspace)
if root.exists() or not root.parent.is_dir():
raise Error("new workspace with existing private parent required")
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "daemon_contacted": False,
"capture_started": False, "requires": "approved entire interface, host networking and NET_RAW"}
if os.name != "posix":
raise Error("host capture preparation requires POSIX")
if root.parent.stat().st_uid != os.getuid() or root.parent.stat().st_mode & 0o077:
raise Error("workspace parent must be owned and mode 0700")
state = {"schema": SCHEMA, "project": "dh-host-" + secrets.token_hex(6), "profile": config, "credentials": secret}
root.mkdir(mode=0o700)
shared.write(root / "state.json", shared.canonical(state))
shared.write(root / "compose.json", shared.canonical(compose_spec(config, secret, state["project"])))
shared.write(root / "application.properties", properties(config, secret))
# Root with DAC_OVERRIDE dropped cannot read the operator-owned 0600 file.
# Only this individually mounted file is readable by the container; its
# parent remains 0700, and the credential ledger is never made public.
(root / "application.properties").chmod(0o644)
(root / "data").mkdir(mode=0o700)
(root / "data/postgres").mkdir(mode=0o700)
return {"status": "PASS", "action": "prepare", "capture_started": False}
def workspace(path):
root = kit.safe_path(path)
if not root.is_dir() or (os.name == "posix" and (root.stat().st_uid != os.getuid() or root.stat().st_mode & 0o077)):
raise Error("private owned workspace required")
state = kit.load(root / "state.json")
if (not isinstance(state, dict) or set(state) != {"schema", "project", "profile", "credentials"} or
state["schema"] != SCHEMA or not isinstance(state["project"], str) or
not re.fullmatch(r"dh-host-[a-f0-9]{12}", state["project"])):
raise Error("invalid host capture state")
profile(state["profile"])
live.credentials(state["credentials"])
for name, expected in {"compose.json": shared.canonical(compose_spec(state["profile"], state["credentials"], state["project"])),
"application.properties": properties(state["profile"], state["credentials"])}.items():
if kit.read(root / name) != expected:
raise Error("immutable host capture configuration changed")
for name in ("data", "data/postgres"):
if (root / name).is_symlink() or not (root / name).is_dir():
raise Error("host capture data must remain ordinary directories")
return root, state
def interface(config):
data = json.loads(shared.checked(["ip", "-json", "link", "show", "dev", config["interface"]], capture=True))
if (not isinstance(data, list) or len(data) != 1 or data[0].get("ifname") != config["interface"] or
data[0].get("ifindex") != config["ifindex"] or data[0].get("address") != config["interface_mac"] or
"UP" not in data[0].get("flags", [])):
raise Error("approved interface identity or UP state changed")
def local_engine():
"""Host-interface approval must refer to this kernel, never a remote daemon."""
if any(os.environ.get(name) for name in ("DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH")):
raise Error("host capture refuses Docker endpoint override variables; use the local standard Engine context")
endpoint = json.loads(shared.checked(["docker", "context", "inspect", "--format", "{{json .Endpoints.docker}}"], capture=True))
if not isinstance(endpoint, dict) or endpoint.get("Host") != "unix:///var/run/docker.sock":
raise Error("host capture requires the local standard Unix Docker socket, not a remote context")
metadata = Path("/var/run/docker.sock").lstat()
if not stat.S_ISSOCK(metadata.st_mode) or metadata.st_uid != 0:
raise Error("host capture requires a real root-owned local Docker socket")
observed = json.loads(shared.checked(["docker", "info", "--format",
'{"security":{{json .SecurityOptions}},"kernel":{{json .KernelVersion}}}'], capture=True))
if (not isinstance(observed, dict) or not isinstance(observed.get("security"), list) or
any(not isinstance(value, str) or "rootless" in value.lower() for value in observed["security"]) or
observed.get("kernel") != os.uname().release):
raise Error("host capture requires the local rootful Engine on this kernel")
def image_ids(images):
if not isinstance(images, dict) or set(images) != {"packmate", "db"} or any(
not isinstance(v, str) or not re.fullmatch(r"sha256:[a-f0-9]{64}", v) for v in images.values()):
raise Error("invalid cached host capture image receipt")
return images
def receipt_images(root):
return image_ids(kit.load(root / "images.json"))
def fresh_runtime(root):
# lexists, rather than exists, also rejects a dangling symlink. A partial
# previous publication is deliberately not repaired or overwritten here.
if any(os.path.lexists(root / name) for name in ("images.json", "runtime-compose.json")):
raise Error("bootstrap requires a fresh workspace without runtime or image receipt")
def bootstrap_receipt(root, path, expected_sha256):
"""Detached operator approval binds IDs reviewed against the pinned refs.
The receipt does not prove upstream provenance on its own. It is portable
between approved daemons only after the independently recorded hash is
checked; Docker is never contacted while validating this input.
"""
fresh_runtime(root)
if not isinstance(expected_sha256, str) or not re.fullmatch(r"[a-f0-9]{64}", expected_sha256):
raise Error("bootstrap requires an independently approved canonical image receipt SHA-256")
source = kit.safe_path(path)
before = source.lstat()
if (not stat.S_ISREG(before.st_mode) or before.st_size > 4096 or before.st_nlink != 1 or
(os.name == "posix" and (before.st_uid != os.getuid() or before.st_mode & 0o077))):
raise Error("bootstrap receipt must be a private owned bounded regular file")
def stamp(metadata):
return (metadata.st_dev, metadata.st_ino, metadata.st_size, metadata.st_mtime_ns,
metadata.st_ctime_ns, metadata.st_mode, metadata.st_uid, metadata.st_nlink)
def unique(pairs):
result = {}
for key, value in pairs:
if key in result:
raise Error("duplicate bootstrap receipt key")
result[key] = value
return result
content = kit.read(source, limit=4096)
if stamp(source.lstat()) != stamp(before):
raise Error("bootstrap receipt changed while reading")
images = image_ids(json.loads(content, object_pairs_hook=unique))
if len(set(images.values())) != 2:
raise Error("bootstrap requires distinct application and database image IDs")
if hashlib.sha256(shared.canonical(images)).hexdigest() != expected_sha256:
raise Error("bootstrap receipt differs from independently approved canonical checksum")
return images, (stamp(before), content)
def publish_bootstrap(root, payload, identities):
"""No-replace publication, retaining descriptors until both paths verify.
On an interrupted or raced publication, keep partial files for inspection;
they are never repaired automatically and cannot trigger container startup.
"""
fresh_runtime(root)
parent = root.lstat()
descriptors = []
try:
for name, content in (("runtime-compose.json", payload), ("images.json", shared.canonical(identities))):
current = root.lstat()
if (not stat.S_ISDIR(current.st_mode) or
(current.st_dev, current.st_ino) != (parent.st_dev, parent.st_ino)):
raise Error("bootstrap workspace changed during publication")
path = root / name
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL |
getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0), 0o600)
descriptors.append((descriptor, path, content))
with os.fdopen(descriptor, "wb", closefd=False) as stream:
stream.write(content)
stream.flush()
os.fsync(descriptor)
for descriptor, path, content in descriptors:
held, named = os.fstat(descriptor), path.lstat()
if (not stat.S_ISREG(named.st_mode) or named.st_nlink != 1 or
(held.st_dev, held.st_ino) != (named.st_dev, named.st_ino) or
kit.read(path) != content):
raise Error("bootstrap publication changed; partial workspace retained for inspection")
current = root.lstat()
if not stat.S_ISDIR(current.st_mode) or (current.st_dev, current.st_ino) != (parent.st_dev, parent.st_ino):
raise Error("bootstrap workspace changed during publication")
finally:
for descriptor, _, _ in descriptors:
os.close(descriptor)
def owned(root, state, images=None):
"""Validate exact project IDs, immutable images and mounts without foreign logs."""
project = state["project"]
if not isinstance(project, str) or not re.fullmatch(r"dh-host-[a-f0-9]{12}", project):
raise Error("invalid host capture ownership project")
def listing(argv, maximum):
values = shared.checked(argv, capture=True).decode().split()
if len(values) > maximum or len(set(values)) != len(values) or any(not re.fullmatch(r"[a-f0-9]{64}", item) for item in values):
raise Error("unexpected host capture resource inventory")
return values
identifiers = listing(["docker", "ps", "--all", "--quiet", "--no-trunc", "--filter", "label=com.docker.compose.project=" + project], 2)
images = (image_ids(images) if images is not None else receipt_images(root)) if identifiers else None
current = {}
fmt = ('{"id":{{json .Id}},"labels":{{json .Config.Labels}},"image":{{json .Image}},'
'"running":{{json .State.Running}},"mounts":{{json .Mounts}},"networks":{{json .NetworkSettings.Networks}},'
'"mode":{{json .HostConfig.NetworkMode}},"ports":{{json .HostConfig.PortBindings}},'
'"privileged":{{json .HostConfig.Privileged}},"readonly":{{json .HostConfig.ReadonlyRootfs}},'
'"caps":{{json .HostConfig.CapAdd}},"drop":{{json .HostConfig.CapDrop}}}')
physical = project + "_database"
for identity in identifiers:
value = json.loads(shared.checked(["docker", "container", "inspect", "--format", fmt, identity], capture=True))
labels, mounts = value.get("labels") or {}, value.get("mounts")
service = labels.get("com.docker.compose.service")
if (value.get("id") != identity or labels.get("com.docker.compose.project") != project or
labels.get(LABEL) != project or service not in {"db", "packmate"} or service in current or
value.get("image") != images[service] or value.get("privileged") is not False or
type(value.get("running")) is not bool or not isinstance(mounts, list)):
raise Error("host capture resource ownership, service or image mismatch")
expected = {"/configuration/application.properties": (str(root / "application.properties"), False)} if service == "packmate" else {
"/var/lib/postgresql/data": (str(root / "data/postgres"), True)}
actual = {item.get("Destination"): (item.get("Source"), item.get("RW")) for item in mounts if item.get("Type") == "bind"}
tmpfs = {"/tmp", "/jna"} if service == "packmate" else set()
if (actual != expected or any(item.get("Type") != "bind" and not (item.get("Type") == "tmpfs" and
item.get("Destination") in tmpfs) for item in mounts)):
raise Error("host capture bind mounts differ from the private workspace")
if service == "packmate":
if (value.get("mode") != "host" or set(value.get("networks") or {}) != {"host"} or
value.get("ports") not in (None, {}) or value.get("readonly") is not True or
value.get("caps") not in (["NET_RAW"], ["CAP_NET_RAW"]) or value.get("drop") != ["ALL"]):
raise Error("host capture runtime privilege or network boundary changed")
else:
ports = {"5432/tcp": [{"HostIp": "127.0.0.1", "HostPort": str(state["profile"]["db_port"])}]}
if value.get("mode") != physical or set(value.get("networks") or {}) != {physical} or value.get("ports") != ports:
raise Error("host capture database network or loopback publication changed")
current[service] = value
networks = listing(["docker", "network", "ls", "--quiet", "--no-trunc", "--filter", "label=com.docker.compose.project=" + project], 1)
# A name collision without our ownership labels must be rejected before up.
exact = listing(["docker", "network", "ls", "--quiet", "--no-trunc", "--filter", "name=^" + re.escape(physical) + "$"], 1)
if set(exact) != set(networks):
raise Error("host capture database network name or ownership collision")
for identity in networks:
fmt = '{"id":{{json .Id}},"name":{{json .Name}},"labels":{{json .Labels}},"containers":{{json .Containers}},"internal":{{json .Internal}}}'
value = json.loads(shared.checked(["docker", "network", "inspect", "--format", fmt, identity], capture=True))
labels = value.get("labels") or {}
expected_members = {current["db"]["id"]} if current.get("db", {}).get("running") else set()
if (value.get("id") != identity or value.get("name") != physical or labels.get(LABEL) != project or
labels.get("com.docker.compose.project") != project or value.get("internal") is not False or
not isinstance(value.get("containers"), dict) or set(value["containers"]) != expected_members):
raise Error("host capture database network isolation or membership changed")
if "db" in current and current["db"]["networks"][physical].get("NetworkID") != identity:
raise Error("host capture database network identity mismatch")
if "db" in current and not networks:
raise Error("host capture database network missing")
return current
def runtime(root, state, expected_images_sha256=None, bootstrap_images=None):
receipt = root / "images.json"
bootstrap_identity = None
if bootstrap_images is not None:
images, bootstrap_identity = bootstrap_receipt(root, bootstrap_images, expected_images_sha256)
elif receipt.exists():
images = receipt_images(root)
checksum = hashlib.sha256(shared.canonical(images)).hexdigest()
if expected_images_sha256 is not None and expected_images_sha256 != checksum:
raise Error("host capture image receipt differs from independently approved checksum")
# An operator-recorded checksum enables tag-free Docker save/load. If
# none is supplied, independently resolve the pinned upstream refs on
# each launch; a mutable receipt alone never authorizes another image.
if expected_images_sha256 is None:
for name, reference in {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB}.items():
observed = shared.checked(["docker", "image", "inspect", "--format", "{{.Id}}", reference], capture=True).decode().strip()
if observed != images[name]:
raise Error("host capture image receipt differs from pinned upstream image")
else:
images = {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB}
if expected_images_sha256 is not None:
raise Error("no cached image receipt exists to bind the independently approved checksum")
identities = {}
for name, reference in images.items():
observed = shared.checked(["docker", "image", "inspect", "--format", "{{.Id}};{{.Os}};{{.Architecture}}", reference], capture=True).decode().strip().split(";")
if (len(observed) != 3 or not re.fullmatch(r"sha256:[a-f0-9]{64}", observed[0]) or observed[1:] != ["linux", "amd64"] or
(reference.startswith("sha256:") and reference != observed[0])):
raise Error("host capture image identity or architecture mismatch")
identities[name] = observed[0]
payload = shared.canonical(compose_spec(state["profile"], state["credentials"], state["project"], identities))
if bootstrap_images is not None:
# The source and both destination names must still match the approved
# preflight after Docker inspection. No partial state is overwritten.
verified, current_identity = bootstrap_receipt(root, bootstrap_images, expected_images_sha256)
if current_identity != bootstrap_identity or verified != identities:
raise Error("bootstrap receipt changed during image inspection")
publish_bootstrap(root, payload, identities)
elif receipt.exists():
if kit.read(root / "runtime-compose.json") != payload:
raise Error("host capture runtime changed")
else:
shared.write(root / "runtime-compose.json", payload)
shared.write(receipt, shared.canonical(identities))
return hashlib.sha256(shared.canonical(identities)).hexdigest()
def command(root, state, runtime=False):
return ["docker", "compose", "--project-name", state["project"], "--project-directory", str(root),
"--file", str(root / ("runtime-compose.json" if runtime else "compose.json"))]
def execute(args):
root, state = workspace(args.workspace)
config = state["profile"]
bootstrap = getattr(args, "bootstrap_images", None)
if bootstrap is not None:
if args.action != "up":
raise Error("bootstrap images are accepted only for the first up")
bootstrap_receipt(root, bootstrap, getattr(args, "expected_images_sha256", None))
if not args.apply:
return {"status": "NOT_RUN", "action": args.action, "daemon_contacted": False,
"capture_scope": "entire approved host interface; upstream startup filter is TCP/UDP"}
if not sys.platform.startswith("linux"):
raise Error("host capture requires native Linux, not Docker Desktop")
if args.action == "up" and not (args.host_network_approved and args.interface_scope_approved and
args.capture_approval == config["interface"] + ":" + str(config["ifindex"]) + ":" + config["interface_mac"]):
raise Error("up requires exact interface capture approval, whole-interface scope and host-network approval")
local_engine()
live.daemon(config)
owned(root, state)
if args.action == "down":
shared.checked(command(root, state) + ["down", "--timeout", "10"], timeout=60)
return {"status": "PASS", "action": "down", "data_retained": True, "interface_unchanged": True}
interface(config)
checksum = runtime(root, state, getattr(args, "expected_images_sha256", None), bootstrap)
shared.checked(command(root, state, True) + ["config", "--quiet"])
shared.checked(command(root, state, True) + ["up", "--detach", "--no-build", "--pull", "never"], timeout=180)
live.ready(config, state["credentials"])
current = owned(root, state)
if set(current) != {"db", "packmate"} or not all(value["running"] for value in current.values()):
raise Error("host capture readiness is not bound to exactly two owned running services")
return {"status": "PASS", "action": "up", "authenticated_capture_started": True,
"traffic_correctness": "NOT_RUN", "retention": "age policy, not a hard disk quota",
"network_scope": "explicit host network; DB published only on IPv4 loopback",
"not_validated": ["actual event interface", "physical team LAN", "sustained load", "hard storage bound"],
"images_sha256": checksum, "offline_note": "record this checksum independently for tag-free restart approval",
"rollback": "down with same workspace, apply and approval ID; data retained"}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "up", "down"])
parser.add_argument("--workspace", required=True)
for name in ("profile", "credentials", "approval-id", "capture-approval", "expected-images-sha256", "bootstrap-images"):
parser.add_argument("--" + name)
for name in ("apply", "host-network-approved", "interface-scope-approved"):
parser.add_argument("--" + name, action="store_true")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise Error("mutations require --apply and non-secret --approval-id")
if args.action == "prepare" and not (args.profile and args.credentials):
raise Error("prepare requires private profile and credentials")
if args.bootstrap_images is not None and args.action != "up":
raise Error("bootstrap images are accepted only for the first up")
result = prepare(args) if args.action == "prepare" else execute(args)
print(json.dumps(result, sort_keys=True))
return 0
except (Error, OSError, ValueError, KeyError, TypeError, AttributeError, KeyboardInterrupt) as error:
print(json.dumps({"status": "BLOCKED", "reason": str(error) if isinstance(error, Error) else "host capture operation rejected; raw details suppressed",
"rollback": "down only this workspace with apply/approval; databases retained; inspect partial resources before retry"}))
return 2
if __name__ == "__main__":
raise SystemExit(main())
+309
View File
@@ -0,0 +1,309 @@
#!/usr/bin/env python3
"""Explicitly approved Linux container-namespace LIVE capture, unchanged Packmate.
The namespace owner must already publish the selected UI port and carry the
approved ownership label. Its single user-defined bridge is shared with the
private (unpublished) database: every bridge peer is inside the trust boundary.
Host capture, Docker Desktop and automatic network changes are unsupported.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import importlib.util
import ipaddress
import json
import os
from pathlib import Path
import re
import secrets
import sys
import time
import urllib.error
import urllib.request
_SPEC = importlib.util.spec_from_file_location("live_toolkit", Path(__file__).with_name("toolkit.py"))
kit = importlib.util.module_from_spec(_SPEC)
_SPEC.loader.exec_module(kit)
shared, Error = kit.shared, kit.Error
SCHEMA = "durkahelper.packmate-live.v1"
LABEL = "io.durkahelper.packmate-live"
CAPTURE_LABEL = "io.durkahelper.capture-scope"
PORT = 65000
API = re.compile(r"/(?:$|api/(?:service/|pattern/|pcap/(?:started|start|stop)|stream/[1-9][0-9]{0,4}|packet/[1-9][0-9]{0,18}))\Z")
NOT_VALIDATED = ["host or mirrored-interface capture", "Docker Desktop", "team LAN", "real Vulnbox traffic",
"packet loss under load", "hard storage quota", "60 minute sustained capture", "actual Mac"]
def profile(value):
keys = {"schema", "daemon_id", "capture_container", "network_id", "capture_scope", "interface", "local_ip",
"bind_address", "ui_port", "tcp_timeout_seconds", "udp_timeout_seconds", "timeout_check_seconds",
"retention_minutes", "cleanup_interval_minutes"}
if not isinstance(value, dict) or set(value) != keys or value["schema"] != SCHEMA:
raise Error("invalid LIVE profile; only explicitly approved container namespace mode is supported")
for key, pattern in (("daemon_id", r"[A-Za-z0-9:_.-]{8,128}"), ("capture_container", r"[a-f0-9]{64}"),
("network_id", r"[a-f0-9]{64}"), ("capture_scope", r"[A-Za-z0-9_.-]{1,80}")):
if not isinstance(value[key], str) or not re.fullmatch(pattern, value[key]):
raise Error("invalid LIVE identity")
# A single ordinary bridge endpoint has eth0. Multi-network, host, loopback,
# interface aliases and guessed mirrored interfaces require separate review.
if value["interface"] != "eth0":
raise Error("this profile supports only a reviewed single-bridge eth0 namespace")
for key in ("local_ip", "bind_address"):
address = ipaddress.ip_address(value[key])
if address.version != 4 or address.is_unspecified or address.is_multicast or address.is_link_local:
raise Error("LIVE addresses must be explicit unicast IPv4 addresses")
if key == "local_ip" and address.is_loopback:
raise Error("capture local IP must be the inspected bridge endpoint")
for key, maximum in (("ui_port", 65535), ("tcp_timeout_seconds", 600), ("udp_timeout_seconds", 600),
("timeout_check_seconds", 60), ("retention_minutes", 1440), ("cleanup_interval_minutes", 60)):
if type(value[key]) is not int or not 1 <= value[key] <= maximum:
raise Error("invalid LIVE bounded policy value")
return value
def credentials(value):
if not isinstance(value, dict) or set(value) != {"username", "password", "db_password"}:
raise Error("invalid LIVE credential fields")
for key, text in value.items():
pattern = r"[A-Za-z0-9_.-]{4,64}" if key == "username" else r"[A-Za-z0-9_.-]{20,128}"
if not isinstance(text, str) or not re.fullmatch(pattern, text) or text.startswith("REPLACE_"):
raise Error("LIVE requires privately generated credentials")
return value
def properties(config, secret, project):
pairs = {"spring.datasource.url": "jdbc:postgresql://" + project + "-db:5432/packmate",
"spring.datasource.username": "packmate", "spring.datasource.password": secret["db_password"],
"packmate.web.account-login": secret["username"], "packmate.web.account-password": secret["password"],
"packmate.capture-mode": "LIVE", "packmate.interface-name": config["interface"],
"packmate.local-ip": config["local_ip"], "packmate.timeout.tcp-stream-timeout": config["tcp_timeout_seconds"],
"packmate.timeout.udp-stream-timeout": config["udp_timeout_seconds"],
"packmate.timeout.check-interval": config["timeout_check_seconds"], "packmate.cleanup.enabled": "true",
"packmate.cleanup.threshold": config["retention_minutes"], "packmate.cleanup.interval": config["cleanup_interval_minutes"],
"server.port": PORT, "server.address": config["local_ip"], "logging.level." + kit.LOGGER: "OFF"}
return "".join(key + "=" + str(value) + "\n" for key, value in sorted(pairs.items())).encode("ascii")
def compose_spec(config, secret, project, images=None):
images = images or {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB}
base = {"restart": "no", "cpus": 1.0, "mem_limit": "512m", "pids_limit": 128,
"security_opt": ["no-new-privileges:true"], "logging": {"driver": "none"}, "labels": {LABEL: project}}
database = dict(base, image=images["db"], platform="linux/amd64",
environment={"POSTGRES_DB": "packmate", "POSTGRES_USER": "packmate", "POSTGRES_PASSWORD": secret["db_password"]},
volumes=["./data/postgres:/var/lib/postgresql/data"], networks={"capture": {"aliases": [project + "-db"]}},
healthcheck={"test": ["CMD", "pg_isready", "-U", "packmate", "-d", "packmate"],
"interval": "2s", "timeout": "2s", "retries": 45})
# Linux libpcap opens AF_PACKET sockets with NET_RAW. UID 0 with ALL dropped
# and only NET_RAW added is used because nonroot Docker cap_add does not
# reliably retain effective capabilities for the unmodified upstream Java.
app = dict(base, image=images["packmate"], platform="linux/amd64", user="0:0", read_only=True,
cap_drop=["ALL"], cap_add=["NET_RAW"], mem_limit="1536m",
network_mode="container:" + config["capture_container"],
tmpfs=["/tmp:size=67108864,mode=1777,noexec,nosuid,nodev", "/jna:size=16777216,mode=0700,nosuid,nodev,exec"],
volumes=["./application.properties:/configuration/application.properties:ro"], entrypoint=["java"],
command=["-Xms64m", "-Xmx768m", "-XX:ActiveProcessorCount=1", "-Djna.tmpdir=/jna",
"-Djava.net.preferIPv4Stack=true", "-jar", "/app/app.jar",
"--spring.config.additional-location=file:/configuration/application.properties"],
depends_on={"db": {"condition": "service_healthy"}})
return {"services": {"db": database, "packmate": app},
"networks": {"capture": {"external": True, "name": config["network_id"]}}}
def validate_state(value):
if (not isinstance(value, dict) or set(value) != {"schema", "project", "profile", "credentials"} or
value["schema"] != SCHEMA or not re.fullmatch(r"dh-live-[a-f0-9]{12}", value.get("project", ""))):
raise Error("invalid LIVE ownership state")
profile(value["profile"])
credentials(value["credentials"])
return value
def workspace(path):
root = kit.safe_path(path)
if not root.is_dir():
raise Error("LIVE workspace missing")
if os.name == "posix" and (root.stat().st_uid != os.getuid() or root.stat().st_mode & 0o077):
raise Error("LIVE workspace must be private and owned by the current user")
state = validate_state(kit.load(root / "state.json"))
expected = {"compose.json": shared.canonical(compose_spec(state["profile"], state["credentials"], state["project"])),
"application.properties": properties(state["profile"], state["credentials"], state["project"])}
for name, content in expected.items():
if kit.read(root / name) != content:
raise Error("LIVE immutable configuration changed; prepare a new workspace")
if (root / "data").is_symlink() or (root / "data/postgres").is_symlink() or not (root / "data/postgres").is_dir():
raise Error("LIVE database data must remain an ordinary owned path")
return root, state
def prepare(args):
config, secret = profile(kit.load(args.profile)), credentials(kit.load(args.credentials))
root = kit.safe_path(args.workspace)
if root.exists() or not root.parent.is_dir():
raise Error("LIVE workspace must be a new directory with an existing parent")
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "mode": "LIVE", "daemon_contacted": False,
"effects": "new private workspace only; no capture or Docker operation"}
if os.name != "posix":
raise Error("LIVE preparation requires POSIX private permissions")
state = {"schema": SCHEMA, "project": "dh-live-" + secrets.token_hex(6), "profile": config, "credentials": secret}
root.mkdir(mode=0o700)
shared.write(root / "state.json", shared.canonical(state))
shared.write(root / "compose.json", shared.canonical(compose_spec(config, secret, state["project"])))
shared.write(root / "application.properties", properties(config, secret, state["project"]))
(root / "application.properties").chmod(0o644)
(root / "data/postgres").mkdir(mode=0o700, parents=True)
return {"status": "PASS", "action": "prepare", "mode": "LIVE", "capture_started": False,
"retention": "age policy only, not a hard storage quota", "not_validated": NOT_VALIDATED}
def daemon(config):
raw = shared.checked(["docker", "info", "--format", "{{.ID}};{{.OSType}};{{.Architecture}};{{.OperatingSystem}}"], capture=True).decode().strip().split(";", 3)
if len(raw) != 4 or raw[0] != config["daemon_id"] or raw[1] != "linux" or raw[2] not in {"x86_64", "amd64"} or "docker desktop" in raw[3].lower():
raise Error("LIVE requires the approved native Linux amd64 Docker Engine, not Docker Desktop")
def capture_scope(config):
template = '{"id":{{json .Id}},"running":{{json .State.Running}},"mode":{{json .HostConfig.NetworkMode}},"networks":{{json .NetworkSettings.Networks}},"ports":{{json .NetworkSettings.Ports}},"owner":{{json (index .Config.Labels "' + CAPTURE_LABEL + '")}}}'
item = json.loads(shared.checked(["docker", "container", "inspect", "--format", template, config["capture_container"]], capture=True))
if (item.get("id") != config["capture_container"] or item.get("running") is not True or
item.get("owner") != config["capture_scope"] or item.get("mode") in {"host", "none", "default", "bridge"} or
str(item.get("mode", "")).startswith("container:") or not isinstance(item.get("networks"), dict) or len(item["networks"]) != 1):
raise Error("capture namespace identity, ownership, running state or network scope mismatch")
endpoint = next(iter(item["networks"].values()))
if endpoint.get("NetworkID") != config["network_id"] or endpoint.get("IPAddress") != config["local_ip"]:
raise Error("capture bridge endpoint changed")
if item.get("ports", {}).get(str(PORT) + "/tcp") != [{"HostIp": config["bind_address"], "HostPort": str(config["ui_port"])}]:
raise Error("namespace owner must already publish exactly the approved Packmate UI binding")
template = '{"id":{{json .Id}},"driver":{{json .Driver}},"owner":{{json (index .Labels "' + CAPTURE_LABEL + '")}}}'
network = json.loads(shared.checked(["docker", "network", "inspect", "--format", template, config["network_id"]], capture=True))
if network != {"id": config["network_id"], "driver": "bridge", "owner": config["capture_scope"]}:
raise Error("capture bridge ownership or driver mismatch")
def owned(state):
project = state["project"]
identifiers = shared.checked(["docker", "ps", "--all", "--quiet", "--filter", "label=com.docker.compose.project=" + project], capture=True).decode().split()
if len(identifiers) > 4 or any(not re.fullmatch(r"[a-f0-9]{12,64}", item) for item in identifiers):
raise Error("unexpected LIVE resource listing")
for identity in identifiers:
owner = shared.checked(["docker", "inspect", "--format", '{{index .Config.Labels "' + LABEL + '"}}', identity], capture=True).decode().strip()
if owner != project:
raise Error("LIVE resource owner mismatch; operation refused")
def runtime(root, state):
receipt_path = root / "images.json"
if receipt_path.exists():
images = kit.load(receipt_path)
if not isinstance(images, dict) or set(images) != {"packmate", "db"} or any(not isinstance(v, str) or not re.fullmatch(r"sha256:[a-f0-9]{64}", v) for v in images.values()):
raise Error("invalid LIVE immutable image receipt")
else:
images = {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB}
identities = {}
for name, reference in images.items():
raw = shared.checked(["docker", "image", "inspect", "--format", "{{.Id}};{{.Os}};{{.Architecture}}", reference], capture=True).decode().strip().split(";")
if len(raw) != 3 or not re.fullmatch(r"sha256:[a-f0-9]{64}", raw[0]) or raw[1:] != ["linux", "amd64"] or (reference.startswith("sha256:") and reference != raw[0]):
raise Error("LIVE cached image identity or architecture mismatch")
identities[name] = raw[0]
spec = compose_spec(state["profile"], state["credentials"], state["project"], identities)
payload = shared.canonical(spec)
if receipt_path.exists():
if kit.read(root / "runtime-compose.json") != payload:
raise Error("LIVE runtime Compose differs from immutable image receipt")
else:
shared.write(root / "runtime-compose.json", payload)
shared.write(receipt_path, shared.canonical(identities))
return spec
def command(root, state, runtime=False):
return ["docker", "compose", "--project-name", state["project"], "--project-directory", str(root),
"--file", str(root / ("runtime-compose.json" if runtime else "compose.json"))]
def request(config, secret, path, method="GET", body=None, auth=True):
if method not in {"GET", "POST"} or not isinstance(path, str) or not API.fullmatch(path):
raise Error("unlisted LIVE API operation")
headers = {"Content-Type": "application/json", "Accept-Encoding": "identity"}
if auth:
headers["Authorization"] = "Basic " + base64.b64encode((secret["username"] + ":" + secret["password"]).encode("ascii")).decode("ascii")
req = urllib.request.Request("http://" + config["bind_address"] + ":" + str(config["ui_port"]) + path,
headers=headers, method=method, data=None if body is None else shared.canonical(body))
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), shared.NoRedirect())
try:
response = opener.open(req, timeout=3)
except urllib.error.HTTPError as error:
response = error
with response:
raw = response.read(1024 * 1024 + 1)
if len(raw) > 1024 * 1024:
raise Error("LIVE API response exceeded bound")
if response.status != 200:
raise Error("LIVE API did not return HTTP 200; body suppressed")
return json.loads(raw) if raw else None
def ready(config, secret, timeout=120):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
if isinstance(request(config, secret, "/api/service/"), list) and request(config, secret, "/api/pcap/started") is True:
return
except (Error, OSError, ValueError, urllib.error.URLError):
pass
time.sleep(1)
raise Error("authenticated LIVE capture readiness timed out; inspect owned deployment or run down")
def execute(args):
root, state = workspace(args.workspace)
config = state["profile"]
if not args.apply:
return {"status": "NOT_RUN", "action": args.action, "mode": "LIVE", "daemon_contacted": False,
"capture_scope": "explicitly approved container namespace only", "retention": "age policy, not hard storage quota"}
if not sys.platform.startswith("linux"):
raise Error("LIVE operations require a native Linux host")
if args.action == "up" and args.capture_approval != config["capture_container"]:
raise Error("LIVE startup requires --capture-approval matching the exact approved container ID")
daemon(config)
owned(state)
if args.action == "down":
shared.checked(command(root, state) + ["down", "--timeout", "10"], timeout=60)
return {"status": "PASS", "action": "down", "capture_owner_unchanged": True, "database_data_retained": True}
capture_scope(config)
runtime(root, state)
shared.checked(command(root, state, True) + ["config", "--quiet"])
shared.checked(command(root, state, True) + ["up", "--detach", "--no-build", "--pull", "never"], timeout=180)
ready(config, state["credentials"])
return {"status": "PASS", "action": "up", "mode": "LIVE", "authenticated_capture_started": True,
"traffic_correctness": "NOT_RUN", "network_scope": "approved bridge peers can reach authenticated DB; no host DB publication",
"retention": "upstream age cleanup enabled; not a hard disk quota", "not_validated": NOT_VALIDATED,
"rollback": "down --workspace SAME_WORKSPACE --apply --approval-id ID; namespace owner/network/data retained"}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "up", "down"])
parser.add_argument("--workspace", required=True)
for name in ("profile", "credentials", "approval-id", "capture-approval"):
parser.add_argument("--" + name)
parser.add_argument("--apply", action="store_true")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise Error("mutations require --apply and a non-secret --approval-id")
if args.action == "prepare" and not (args.profile and args.credentials):
raise Error("prepare requires private profile and credentials JSON")
result = prepare(args) if args.action == "prepare" else execute(args)
print(json.dumps(result, sort_keys=True))
return 0
except (Error, OSError, ValueError, KeyError, TypeError, AttributeError, KeyboardInterrupt) as error:
print(json.dumps({"status": "BLOCKED", "reason": str(error) if isinstance(error, Error) else "LIVE operation rejected; raw details suppressed",
"rollback": "inspect exact owned project; down retains namespace owner, network and database data"}))
return 2
if __name__ == "__main__":
raise SystemExit(main())
+514
View File
@@ -0,0 +1,514 @@
#!/usr/bin/env python3
"""Operator-side SSH deployment of existing Packmate host LIVE, including offline images.
Python runs ONLY on the operator workstation. The target needs native Linux
amd64, local rootful Docker/Compose, sh, tar, ip, ss, stat, df and sha256sum.
No package installs, remote pulls, firewall changes or foreign cleanup.
"""
from __future__ import annotations
import argparse
import contextlib
import hashlib
import importlib.util
import io
import json
import os
from pathlib import Path, PurePosixPath
import re
import secrets
import shlex
import socket
import stat
import subprocess
import sys
import tarfile
import time
SPEC = importlib.util.spec_from_file_location("remote_host_live", Path(__file__).with_name("packmate_host.py"))
host = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(host)
kit, shared, Error = host.kit, host.shared, host.Error
SCHEMA = "durkahelper.packmate-remote.v1"
REFS = {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB}
DEFAULT = "local/packmate-remote.json"
def ssh_settings(value):
if not isinstance(value, dict) or set(value) != {"target", "port", "key", "known_hosts", "docker"}:
raise Error("invalid SSH settings")
if not isinstance(value["target"], str) or not re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}@[A-Za-z0-9][A-Za-z0-9.-]{0,252}", value["target"]):
raise Error("SSH target must be USER@HOST, not a command")
if type(value["port"]) is not int or not 1 <= value["port"] <= 65535:
raise Error("invalid SSH port")
for field in ("key", "known_hosts"):
if value[field] is not None and (not isinstance(value[field], str) or not Path(value[field]).is_absolute()):
raise Error("SSH key and known_hosts paths must be absolute")
if not isinstance(value["docker"], str) or not re.fullmatch(r"(?:docker|/[A-Za-z0-9_./-]+)", value["docker"]):
raise Error("Docker must be docker or an absolute approved wrapper path; no shell commands")
return value
def remote_path(value):
if not isinstance(value, str) or not re.fullmatch(r"/(?:home/[a-z_][a-z0-9_-]*|root)/[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*", value):
raise Error("use a dedicated absolute directory below /home/USER or /root")
if any(part in {".", ".."} for part in value.split("/")):
raise Error("remote directory traversal is forbidden")
return PurePosixPath(value)
def settings(value):
if not isinstance(value, dict) or set(value) != {"schema", "ssh", "workspace", "project", "profile", "credentials", "images"} or value["schema"] != SCHEMA:
raise Error("invalid remote LIVE configuration")
ssh_settings(value["ssh"])
remote_path(value["workspace"])
user = value["ssh"]["target"].split("@", 1)[0]
prefix = "/root/" if user == "root" else "/home/" + user + "/"
if not value["workspace"].startswith(prefix):
raise Error("workspace must be inside the SSH user's own home directory")
if not re.fullmatch(r"dh-host-[a-f0-9]{12}", value.get("project", "")):
raise Error("invalid owned project")
host.profile(value["profile"])
host.live.credentials(value["credentials"])
if value["images"] is not None:
host.image_ids(value["images"])
return value
def private_config(path):
path = kit.safe_path(path)
metadata = path.stat()
if os.name == "posix" and (metadata.st_uid != os.getuid() or metadata.st_mode & 0o077):
raise Error("local LIVE config must be owned and mode 0600")
return path, settings(kit.load(path))
def write_config(path, value, replace=False):
path = kit.safe_path(path)
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
if not replace:
shared.write(path, shared.canonical(value))
return
temporary = path.with_name(path.name + "." + secrets.token_hex(6) + ".tmp")
shared.write(temporary, shared.canonical(value))
os.replace(temporary, path)
class SSH:
def __init__(self, config):
self.config = ssh_settings(config)
def argv(self):
value = self.config
args = ["ssh", "-T", "-p", str(value["port"]), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
"-o", "UpdateHostKeys=no", "-o", "PermitLocalCommand=no",
"-o", "ConnectTimeout=8", "-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=2"]
if value["key"]:
args += ["-i", value["key"], "-o", "IdentitiesOnly=yes"]
if value["known_hosts"]:
args += ["-o", "UserKnownHostsFile=" + value["known_hosts"]]
return args
def shell(self, script, data=None, stream=None, timeout=60):
try:
result = subprocess.run(self.argv() + [self.config["target"], script], input=data,
stdin=stream if stream is not None else (subprocess.DEVNULL if data is None else None),
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout, check=False)
except (OSError, subprocess.SubprocessError) as error:
raise Error("SSH unavailable or timed out; partial owned state is retained") from error
if result.returncode or len(result.stdout) > 1024 * 1024:
raise Error("SSH operation failed; check host trust, ssh-agent, approved wrapper and target prerequisites; raw output suppressed")
return result.stdout
def checked(self, argv, cwd=None, timeout=60, capture=False, environment=None):
if argv[0] not in {"docker", "ip"} or cwd is not None or environment is not None:
raise Error("unlisted remote operation")
command = ([self.config["docker"]] + argv[1:]) if argv[0] == "docker" else argv
raw = self.shell('test -z "${DOCKER_HOST}${DOCKER_CONTEXT}${DOCKER_TLS_VERIFY}${DOCKER_CERT_PATH}" && ' + shlex.join(command), timeout=timeout)
return raw if capture else b""
@contextlib.contextmanager
def route(self):
original = shared.checked
shared.checked = self.checked
try:
yield
finally:
shared.checked = original
def engine(self):
raw = self.shell("set -eu; test -S /var/run/docker.sock; test ! -L /var/run/docker.sock; "
"stat -c %u /var/run/docker.sock; uname -s; uname -m; uname -r").decode().splitlines()
if len(raw) != 4 or raw[:2] != ["0", "Linux"] or raw[2] not in {"x86_64", "amd64"}:
raise Error("native Linux amd64 with root-owned Docker socket required")
endpoint = json.loads(self.checked(["docker", "context", "inspect", "--format", "{{json .Endpoints.docker}}"], capture=True))
info = json.loads(self.checked(["docker", "info", "--format", "{{json .}}"], capture=True))
if (endpoint.get("Host") != "unix:///var/run/docker.sock" or info.get("KernelVersion") != raw[3] or
info.get("OSType") != "linux" or info.get("Architecture") not in {"x86_64", "amd64"} or
"docker desktop" in info.get("OperatingSystem", "").lower() or
any("rootless" in item.lower() for item in info.get("SecurityOptions", []))):
raise Error("local native rootful Engine required; Desktop/remote Docker contexts unsupported")
compose = self.checked(["docker", "compose", "version", "--short"], capture=True).decode().strip()
if not re.fullmatch(r"v?2\.[0-9]+\.[0-9]+(?:[A-Za-z0-9_.+-]*)", compose):
raise Error("Docker Compose v2 required")
info["durka_compose_version"] = compose
return info
def inspect_images(check, refs, *, platform=None):
images = {}
for name, reference in refs.items():
command = ["docker", "image", "inspect"]
if platform is not None:
command += ["--platform", platform]
row = check(command + ["--format", "{{.Id}};{{.Os}};{{.Architecture}}", reference], capture=True).decode().strip().split(";")
if len(row) != 3 or not re.fullmatch(r"sha256:[a-f0-9]{64}", row[0]) or row[1:] != ["linux", "amd64"]:
raise Error("cached image missing or not Linux amd64; prepare the offline bundle first")
if reference.startswith("sha256:") and row[0] != reference:
raise Error("cached image identity changed")
images[name] = row[0]
return host.image_ids(images)
def digest_file(path):
path = kit.safe_path(path)
before = path.stat()
if not stat.S_ISREG(before.st_mode) or before.st_size > 8 * 1024**3:
raise Error("image archive must be a regular file at most 8 GiB")
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(block)
stamp = lambda item: (item.st_dev, item.st_ino, item.st_size, item.st_mtime_ns, item.st_ctime_ns)
if stamp(path.stat()) != stamp(before):
raise Error("image archive changed while reading")
return path, digest.hexdigest()
def bundle(path):
root = kit.safe_path(path)
value = kit.load(root / "manifest.json")
if (not isinstance(value, dict) or set(value) != {"schema", "refs", "images", "sha256"} or
value["schema"] != "durkahelper.packmate-images.v1" or value["refs"] != REFS):
raise Error("bundle is not for the retained pinned Packmate/PostgreSQL pair")
host.image_ids(value["images"])
archive, checksum = digest_file(root / "images.tar")
if checksum != value["sha256"]:
raise Error("offline archive checksum mismatch; do not load")
return archive, value["images"]
def make_bundle(args):
root = kit.safe_path(args.output)
if root.exists():
raise Error("bundle output must be a new directory; existing files are preserved")
if not args.apply:
return {"status": "NOT_RUN", "action": "bundle", "downloads": bool(args.download)}
root.mkdir(mode=0o700, parents=True)
if args.download:
for reference in REFS.values():
shared.checked(["docker", "pull", "--platform", "linux/amd64", reference], timeout=900)
# Multi-platform stores on ARM Macs retain both PostgreSQL variants. Pulling
# AMD64 does not change the native default used by image inspect or save.
images = inspect_images(shared.checked, REFS, platform="linux/amd64")
# Containerd may expose a platform child ID through inspect without making
# that ID addressable by save. Resolve the retained digest-pinned names and
# let the exporter select the verified AMD64 variant; never use floating tags.
shared.checked(["docker", "image", "save", "--platform", "linux/amd64", "--output", str(root / "images.tar"), *REFS.values()], timeout=900)
(root / "images.tar").chmod(0o600)
_, checksum = digest_file(root / "images.tar")
shared.write(root / "manifest.json", shared.canonical({"schema": "durkahelper.packmate-images.v1", "refs": REFS,
"images": images, "sha256": checksum}))
return {"status": "PASS", "action": "bundle", "offline_bundle": str(root), "target_platform": "linux/amd64"}
def init(args):
path = kit.safe_path(args.config)
if path.exists():
raise Error("LIVE config already exists; no overwrite")
ssh = ssh_settings({"target": args.host, "port": args.ssh_port, "key": str(Path(args.key).expanduser().absolute()) if args.key else None,
"known_hosts": str(Path(args.known_hosts).expanduser().absolute()) if args.known_hosts else None, "docker": args.docker})
remote_path(args.remote_dir)
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}", args.interface or "") or args.interface == "any":
raise Error("one approved interface is required")
client = SSH(ssh)
info = client.engine()
rows = json.loads(client.checked(["ip", "-json", "link", "show", "dev", args.interface], capture=True))
if len(rows) != 1 or "UP" not in rows[0].get("flags", []):
raise Error("selected interface not UP")
config = host.profile({"schema": host.SCHEMA, "daemon_id": info["ID"], "interface": args.interface,
"ifindex": rows[0]["ifindex"], "interface_mac": rows[0]["address"], "local_ip": args.service_ip,
"bind_address": args.bind, "ui_port": args.ui_port, "db_port": args.db_port,
"tcp_timeout_seconds": 30, "udp_timeout_seconds": 10, "timeout_check_seconds": 5,
"retention_minutes": 60, "cleanup_interval_minutes": 1})
value = {"schema": SCHEMA, "ssh": ssh, "workspace": args.remote_dir, "project": "dh-host-" + secrets.token_hex(6),
"profile": config, "credentials": {"username": "operator", "password": secrets.token_hex(24),
"db_password": secrets.token_hex(24)}, "images": None}
write_config(path, settings(value))
return {"status": "PASS", "action": "init", "config": str(path), "remote_changed": False,
"interface": config["interface"], "next": "doctor; then up with explicit capture approvals"}
def discover(args):
"""Read-only target doctor before a local configuration exists."""
client = SSH({"target": args.host, "port": args.ssh_port, "key": str(Path(args.key).expanduser().absolute()) if args.key else None,
"known_hosts": str(Path(args.known_hosts).expanduser().absolute()) if args.known_hosts else None, "docker": args.docker})
for port in (args.ui_port, args.db_port):
if type(port) is not int or not 1024 <= port <= 65535:
raise Error("doctor ports must be between 1024 and 65535")
if args.interface and (not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}", args.interface) or args.interface == "any"):
raise Error("doctor requires an ordinary interface name, not any")
info = client.engine()
rows = json.loads(client.checked(["ip", "-json", "address", "show"] + (["dev", args.interface] if args.interface else []), capture=True))
interfaces = [{"name": row["ifname"], "index": row["ifindex"], "mac": row.get("address"), "up": "UP" in row.get("flags", []),
"ipv4": [item["local"] for item in row.get("addr_info", []) if item.get("family") == "inet"]} for row in rows]
disk_path = remote_path(args.remote_dir) if args.remote_dir else PurePosixPath("/home/" + args.host.split("@", 1)[0])
raw = client.shell(path_guard(disk_path) + "for x in sh tar ip ss stat df sha256sum cut awk; do command -v $x >/dev/null; done; "
"awk '/MemAvailable:/ {print $2}' /proc/meminfo; p=" + shlex.quote(str(disk_path)) + "; "
'while test ! -d "$p"; do p=${p%/*}; test -n "$p" || p=/; done; df -Pk "$p" | awk \'NR==2 {print $4}\'').decode().split()
available, disk = [int(item) for item in raw]
ports = client.shell("ss -H -ltn '( sport = :" + str(args.ui_port) + " or sport = :" + str(args.db_port) + " )'").strip()
images = "CACHED_AMD64_VERIFIED"
try:
inspect_images(client.checked, REFS)
except Error:
images = "MISSING_OR_WRONG_PLATFORM"
blockers = []
if ports:
blockers.append("requested_ports_occupied")
if available < 3072 * 1024:
blockers.append("available_ram_below_3_gib")
if disk < 5 * 1024**2:
blockers.append("free_disk_below_5_gib")
if args.interface and not any(row["up"] for row in interfaces):
blockers.append("selected_interface_not_up")
return {"status": "BLOCKED" if blockers else ("WARNING" if images != "CACHED_AMD64_VERIFIED" else "PASS"), "blockers": blockers,
"action": "doctor", "read_only": True, "engine_id": info["ID"], "engine": "native-linux-amd64",
"linux": info.get("OperatingSystem"), "kernel": info.get("KernelVersion"), "docker_version": info.get("ServerVersion"),
"compose_version": info.get("durka_compose_version"), "cpus": info.get("NCPU"),
"interfaces": interfaces, "available_ram_mib": available // 1024, "free_disk_mib": disk // 1024,
"requested_ports": {"ui": args.ui_port, "db_loopback": args.db_port, "occupied": bool(ports)},
"images": images, "python_on_target": "NOT_REQUIRED", "capture_permission": "NOT_VERIFIED",
"next": "choose the permitted interface/service IP/UI bind; resolve ports/resources; init config; prepare offline bundle if needed",
"traffic_visibility": "NOT_VERIFIED: network placement and a known request/response must be checked manually"}
def path_guard(root):
# Reject symlink ancestors before ANY reads/writes in the target directory.
return "set -eu; " + "; ".join("test ! -L " + shlex.quote(str(parent)) for parent in [*reversed(root.parents), root]) + "; "
def files(value):
state = {"schema": host.SCHEMA, "project": value["project"], "profile": value["profile"], "credentials": value["credentials"]}
return {"state.json": shared.canonical(state), "images.json": shared.canonical(value["images"]),
"runtime-compose.json": shared.canonical(host.compose_spec(value["profile"], value["credentials"], value["project"], value["images"])),
"application.properties": host.properties(value["profile"], value["credentials"])}
def verify_workspace(client, value):
root = remote_path(value["workspace"])
script = path_guard(root) + "if test ! -e " + shlex.quote(str(root)) + "; then printf MISSING; else "
script += "test -d " + shlex.quote(str(root)) + "; test \"$(stat -c %u:%a " + shlex.quote(str(root)) + ")\" = \"$(id -u):700\"; "
for name, content in files(value).items():
path = shlex.quote(str(root / name))
mode = "644" if name == "application.properties" else "600"
script += "test -f " + path + "; test ! -L " + path + "; "
script += "test \"$(stat -c %u:%a:%h " + path + ")\" = \"$(id -u):" + mode + ":1\"; "
script += "test \"$(sha256sum " + path + " | cut -d ' ' -f 1)\" = " + hashlib.sha256(content).hexdigest() + "; "
for name in ("data", "data/postgres"):
script += "test -d " + shlex.quote(str(root / name)) + "; test ! -L " + shlex.quote(str(root / name)) + "; "
script += "printf PRESENT; fi"
return client.shell(script).decode() == "PRESENT"
def upload(client, value):
root = remote_path(value["workspace"])
payload = io.BytesIO()
with tarfile.open(fileobj=payload, mode="w") as archive:
for name, content in files(value).items():
entry = tarfile.TarInfo(name)
entry.size, entry.mode = len(content), 0o644 if name == "application.properties" else 0o600
archive.addfile(entry, io.BytesIO(content))
script = path_guard(root) + "umask 077; test ! -e " + shlex.quote(str(root)) + "; "
script += "mkdir -p " + shlex.quote(str(root.parent)) + "; mkdir " + shlex.quote(str(root)) + "; "
script += "tar -xf - -C " + shlex.quote(str(root)) + "; chmod 644 " + shlex.quote(str(root / "application.properties")) + "; "
script += "mkdir -p " + shlex.quote(str(root / "data/postgres"))
client.shell(script, data=payload.getvalue())
if not verify_workspace(client, value):
raise Error("remote transfer incomplete; retain partial workspace for inspection")
def doctor(client, value):
info = client.engine()
if info["ID"] != value["profile"]["daemon_id"]:
raise Error("approved Docker Engine identity changed; review before reinitializing")
host.interface(value["profile"])
addresses = json.loads(client.checked(["ip", "-json", "address", "show"], capture=True))
if not any(item.get("local") == value["profile"]["bind_address"] and item.get("family") == "inet"
for row in addresses for item in row.get("addr_info", [])):
raise Error("UI bind address is not assigned to this Linux host")
current = host.owned(remote_path(value["workspace"]), value, images=value["images"])
if current and not verify_workspace(client, value):
raise Error("running owned resources have no matching workspace")
root = remote_path(value["workspace"])
script = path_guard(root) + "for x in sh tar ip ss stat df sha256sum cut awk; do command -v $x >/dev/null; done; "
script += "awk '/MemAvailable:/ {print $2}' /proc/meminfo; p=" + shlex.quote(str(root)) + "; "
script += 'while test ! -d "$p"; do p=${p%/*}; test -n "$p" || p=/; done; df -Pk "$p" | awk \'NR==2 {print $4}\''
available, disk = [int(item) for item in client.shell(script).decode().split()]
if available < (1024 if current else 3072) * 1024 or disk < 5 * 1024**2:
raise Error("insufficient free resources: need 3 GiB RAM before startup and 5 GiB disk")
ports = client.shell("ss -H -ltn '( sport = :" + str(value["profile"]["ui_port"]) + " or sport = :" + str(value["profile"]["db_port"]) + " )'").strip()
if ports and not (set(current) == {"db", "packmate"} and all(item["running"] for item in current.values())):
raise Error("requested ports are occupied; stop/reconfigure ONLY the known conflicting deployment yourself")
return {"status": "PASS", "action": "doctor", "read_only": True, "python_on_target": "NOT_REQUIRED",
"engine": "native-linux-amd64", "interface": value["profile"]["interface"], "ifindex": value["profile"]["ifindex"],
"linux": info.get("OperatingSystem"), "kernel": info.get("KernelVersion"), "docker_version": info.get("ServerVersion"),
"compose_version": info.get("durka_compose_version"), "cpus": info.get("NCPU"),
"available_ram_mib": available // 1024, "free_disk_mib": disk // 1024,
"owned_services": {key: item["running"] for key, item in current.items()},
"capture_permission": "NOT_VERIFIED until explicit approved up", "traffic_correctness": "NOT_TESTED"}
@contextlib.contextmanager
def tunnel(client, profile):
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
command = client.argv() + ["-N", "-o", "ExitOnForwardFailure=yes", "-L",
"127.0.0.1:" + str(port) + ":" + profile["bind_address"] + ":" + str(profile["ui_port"]), client.config["target"]]
process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
for _ in range(30):
if process.poll() is not None:
raise Error("SSH readiness tunnel failed; forwarding must be permitted")
try:
with socket.create_connection(("127.0.0.1", port), timeout=0.2):
break
except OSError:
time.sleep(0.1)
else:
raise Error("SSH readiness tunnel did not open")
yield {"bind_address": "127.0.0.1", "ui_port": port}
finally:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
def run(args):
if args.action == "bundle":
return make_bundle(args)
if args.action == "init":
return init(args)
if args.action == "doctor" and args.host:
return discover(args)
path, value = private_config(args.config)
if args.action == "password":
if sys.platform != "darwin":
raise Error("clipboard helper is Mac-only; use the private credentials.password field without screen sharing")
subprocess.run(["/usr/bin/pbcopy"], input=value["credentials"]["password"].encode("ascii"), check=True)
return {"status": "PASS", "action": "password", "username": value["credentials"]["username"], "password": "COPIED_NOT_PRINTED"}
if args.action in {"up", "down"} and not args.apply:
return {"status": "NOT_RUN", "action": args.action, "requires": "--apply; up also requires whole-interface and host-network approvals"}
if args.action == "up" and not (args.host_network_approved and args.interface_scope_approved):
raise Error("up requires --host-network-approved --interface-scope-approved for the configured entire interface")
client = SSH(value["ssh"])
with client.route():
if args.action == "down":
info = client.engine()
if info["ID"] != value["profile"]["daemon_id"] or value["images"] is None or not verify_workspace(client, value):
raise Error("down requires the original Engine and intact owned workspace")
host.owned(remote_path(value["workspace"]), value, images=value["images"])
client.checked(host.command(remote_path(value["workspace"]), value, runtime=True) + ["down", "--timeout", "10"], timeout=90)
return {"status": "PASS", "action": "down", "data_retained": True}
report = doctor(client, value)
if args.action == "status":
return dict(report, action="status", url="http://" + value["profile"]["bind_address"] + ":" + str(value["profile"]["ui_port"]))
archive = None
if args.bundle:
archive, images = bundle(args.bundle)
else:
try:
images = inspect_images(client.checked, REFS if value["images"] is None else value["images"])
except Error:
if args.action == "doctor":
return dict(report, status="WARNING", images="MISSING_OR_WRONG_PLATFORM", next="prepare bundle and pass --bundle; no downloads on target")
raise
if args.action == "doctor":
return dict(report, images="OFFLINE_BUNDLE_VERIFIED" if archive else "CACHED_AMD64_VERIFIED", remote_changed=False)
if value["images"] is not None and images != value["images"]:
raise Error("image identities differ from this deployment; do not upgrade implicitly")
if archive:
try:
inspect_images(client.checked, images)
except Error:
with archive.open("rb") as stream:
client.shell('test -z "${DOCKER_HOST}${DOCKER_CONTEXT}${DOCKER_TLS_VERIFY}${DOCKER_CERT_PATH}" && ' +
shlex.join([value["ssh"]["docker"], "image", "load"]), stream=stream, timeout=900)
_, rechecked = bundle(args.bundle)
if rechecked != images:
raise Error("offline bundle changed during transfer; startup blocked")
inspect_images(client.checked, images)
value["images"] = images
write_config(path, value, replace=True)
if not verify_workspace(client, value):
upload(client, value)
host.owned(remote_path(value["workspace"]), value, images=images)
host.interface(value["profile"])
doctor(client, value)
command = host.command(remote_path(value["workspace"]), value, runtime=True)
client.checked(command + ["config", "--quiet"])
client.checked(command + ["up", "--detach", "--no-build", "--pull", "never"], timeout=180)
with tunnel(client, value["profile"]) as endpoint:
host.live.ready(endpoint, value["credentials"])
current = host.owned(remote_path(value["workspace"]), value, images=images)
if set(current) != {"db", "packmate"} or not all(item["running"] for item in current.values()):
raise Error("exactly two owned running services required")
return {"status": "PASS", "action": "up", "authenticated_capture_started": True, "traffic_correctness": "NOT_TESTED",
"url": "http://" + value["profile"]["bind_address"] + ":" + str(value["profile"]["ui_port"]),
"username": value["credentials"]["username"], "password_command": "durka.py traffic live password --config " + str(path),
"retention": "age cleanup, not hard disk quota", "rollback": "traffic live down --config SAME_CONFIG --apply"}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["init", "doctor", "preflight", "bundle", "up", "status", "down", "password"])
parser.add_argument("--config", default=DEFAULT, help="private remote LIVE config; separate from the local farm config")
parser.add_argument("--host", help="approved USER@HOST")
parser.add_argument("--key", help="existing SSH identity; load encrypted identities into ssh-agent first")
parser.add_argument("--known-hosts", help="existing verified known_hosts; never auto-accept host keys")
parser.add_argument("--ssh-port", type=int, default=22)
parser.add_argument("--docker", default="docker", help="docker or absolute path of existing approved wrapper")
parser.add_argument("--remote-dir", help="new dedicated directory on Linux; never overwrites existing deployment")
parser.add_argument("--interface", help="entire approved Linux capture interface, never any")
parser.add_argument("--service-ip", help="service-side IPv4 in captured traffic")
parser.add_argument("--bind", help="explicit Linux UI IPv4")
parser.add_argument("--ui-port", type=int, default=65000)
parser.add_argument("--db-port", type=int, default=55432)
parser.add_argument("--bundle", help="prepared local offline image directory")
parser.add_argument("--output", help="new local offline image directory for bundle")
for flag in ("apply", "download", "host-network-approved", "interface-scope-approved"):
parser.add_argument("--" + flag, action="store_true")
args = parser.parse_args(argv)
try:
if args.action == "preflight":
args.action = "doctor"
if args.action == "init" and not all((args.host, args.remote_dir, args.interface, args.service_ip, args.bind)):
raise Error("init requires --host --remote-dir --interface --service-ip --bind")
if args.action == "bundle" and not args.output:
raise Error("bundle requires --output NEW_DIRECTORY")
result = run(args)
print(json.dumps(result, sort_keys=True))
return 2 if result.get("status") == "BLOCKED" else 0
except (Error, OSError, ValueError, TypeError, KeyError, subprocess.SubprocessError, KeyboardInterrupt) as error:
print(json.dumps({"status": "BLOCKED", "action": args.action,
"reason": str(error) if isinstance(error, Error) else "operation failed (" + type(error).__name__ + "); raw details suppressed",
"rollback": "retain partial files/data; down only the matching config with --apply; no automatic removal"}))
return 2
if __name__ == "__main__":
raise SystemExit(main())
+15
View File
@@ -0,0 +1,15 @@
{
"schema": "durkahelper.deployment-profile.v1",
"platform": {"os": "darwin", "architecture": "arm64", "runtime": "docker-desktop"},
"bind_address": "127.0.0.1",
"ports": {"farm": 8080, "neo": 5005, "packmate": 65000},
"allow_amd64_emulation": false,
"farm": {
"teams": {"Synthetic": "192.0.2.1"},
"flag_format": "[A-Z0-9]{31}=",
"protocol": "ructf_http",
"protocol_settings": {"SYSTEM_URL": "http://receiver.example.invalid/flags", "SYSTEM_TOKEN": "REPLACE_WITH_PRIVATE_COMPETITION_TOKEN"},
"submit_limit": 10, "submit_period": 2, "flag_lifetime": 300
},
"packmate": {"mode": "FILE", "local_ip": "192.0.2.1", "pcap_file": "capture.pcap", "interface": "", "retention_minutes": 60}
}
File diff suppressed because it is too large. Load diff
+557
View File
@@ -0,0 +1,557 @@
#!/usr/bin/env python3
"""Restore applications into a NEW stopped deployment; never overwrite a source.
The separate inert promotion scaffold is intentionally not consumed or changed.
Redis is reset in the NEW deployment only, with an explicit data-loss gate:
its original queues, cache and session values remain in the verified backup.
Application acceptance precedes a second, receipt-bound activation approval.
"""
from __future__ import annotations
import argparse
import base64
import copy
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import secrets
import stat
import struct
import sys
import time
import urllib.error
import urllib.request
SPEC = importlib.util.spec_from_file_location("activation_recovery", Path(__file__).with_name("recovery.py"))
rec = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(rec)
kit, ops, Error = rec.kit, rec.ops, rec.Error
SCHEMA = "durkahelper.application-recovery.v1"
ACCEPTANCE = "durkahelper.application-recovery-acceptance.v1"
APPS = ("farm", "front", "neo-server", "packmate")
ACTIVE = tuple(rec.BACKENDS) + APPS
EMPTY_PCAP = struct.pack("<IHHIIII", 0xa1b2c3d4, 2, 4, 0, 0, 65535, 1)
CHECKS = {"postgres", "packmate-db", "candidate_redis_empty", "runtime_ownership",
"farm_authenticated", "neo_authenticated", "packmate_authenticated",
"packmate_capture_stopped", "restart_reconnect", "source_stopped", "stage_stopped"}
LIMITS = ["new candidate Redis state intentionally reset; original RDBs retained in backup",
"real traffic, team LAN, physical Mac and large-data RPO/RTO not validated",
"no worker, submission or capture automatically enabled",
"Neo authentication and native state restored; task execution requires a separate synthetic drill"]
def selected(runtime, names=ACTIVE):
result = copy.deepcopy(runtime)
result["services"] = {name: result["services"][name] for name in names}
return result
def inputs(args, target):
data = rec._promotion_inputs(args, target)
backup, manifest, original, spec, runtime, profile, stage = data
source, state, source_runtime, source_profile, _ = rec.source_workspace(args.workspace)
if (state != original or source_runtime != runtime or source_profile != profile or
state["project"] != manifest["source_project"]):
raise Error("selected source does not match the verified backup")
rec._separate_promotion_target(target, source)
return data, (source, state["project"], runtime, args.daemon_id, kit.LABEL)
def require_gates(args):
rec.require_promotion_apply(args)
if not args.discard_candidate_redis_state:
raise Error("requires --discard-candidate-redis-state: new Redis queues, caches and sessions are reset; backup retained")
def stopped(context, *, strict=False):
current = rec.owned(*context, exclusive=False, strict_networks=strict)
if any(value["running"] for value in current.values()):
raise Error("source or verified recovery stage is running; stop it separately before recovery")
return current
def command(root, state):
return kit.command(root, state, runtime=True)
def prepare_files(args, target, data):
backup, manifest, original, spec, runtime, profile, stage = data
project = "dh-deploy-" + secrets.token_hex(6)
projected = rec.reproject_spec(spec, project)
images = kit.image_preflight(runtime, profile)
kit.check_build_receipt(backup / "private", spec, images)
projected_runtime = kit.runtime_spec(projected, images)
context = (target, project, selected(projected_runtime), args.daemon_id, kit.LABEL)
if rec.owned(*context, exclusive=False, require_no_networks=True):
raise Error("new candidate project already has Docker resources")
# The pinned Neo server image currently runs as root. Reject a changed
# runtime identity rather than broadly chmod/chown restored bbolt files.
user = json.loads(rec.run(["docker", "image", "inspect", "--format", "{{json .Config.User}}",
images["neo-server"]]))
if user not in ("", "0", "0:0", "root", "root:root"):
raise Error("unsupported Neo runtime UID/GID; no ownership mutation attempted")
staging = ops._StagingDirectory.create(target, ".application-recovery-")
try:
anchor, total = ops._root_anchor_identity(backup.stat()), [0, rec.MAX_TOTAL]
for name, expected in sorted(manifest["files"].items()):
if not name.startswith(("private/config/", "private/sources/")):
continue
destination = name[len("private/"):]
meta, digest = ops._copy_stable(backup, name, (staging, destination), rec.MAX_FILE, total, anchor)
if expected != {"bytes": meta.st_size, "sha256": digest}:
raise Error("immutable recovery source changed")
staging.set_file_metadata(destination, 0o644 if destination in {
"config/neo-client.yml", "config/packmate.properties"} else 0o600)
for name in (*rec.BACKENDS, "neo"):
staging.mkdir("data/" + name)
staging.mkdir("pcaps")
# This is a closed empty file, never an automatic capture/import.
staging.write_new_bytes("pcaps/" + profile["packmate"]["pcap_file"], EMPTY_PCAP, mode=0o644)
relative = "cold/neo.tar"
if rec.cold_members(backup / relative, staging=staging, directory="neo", source_root=backup,
expected=manifest["files"][relative]) != manifest["cold"]["neo"]:
raise Error("Neo cold state changed while restoring")
generated = {"compose.json": projected, "runtime-compose.json": projected_runtime, "profile.json": profile}
model = kit.model(projected, profile)
generated.update({"model.json": model, "policy.json": kit.policy(profile, model),
"build-receipt.json": {"schema": "durkahelper.deployment-build.v2", "images": images,
"compose_sha256": rec.sha(kit.shared.canonical(projected)),
"runtime_sha256": rec.sha(kit.shared.canonical(projected_runtime))}})
for name, value in generated.items():
staging.write_new_bytes(name, kit.shared.canonical(value))
files = {name: value["sha256"] for name, value in rec.inventory(staging).items()
if not name.startswith(("data/", "pcaps/"))}
pending = {"schema": kit.SCHEMA, "project": project, "source_pins": kit.shared.PINS,
"approval_id": args.approval_id, "files": files}
staging.write_new_bytes("deployment.pending.json", ops._canonical(pending))
state = {"schema": SCHEMA, "project": project, "source_project": original["project"],
"stage_project": stage[1]["project"], "daemon_id": args.daemon_id,
"backup_sha256": rec.sha(ops._canonical(manifest)),
"stage_verification_sha256": stage[3]["verification_sha256"],
"pending_sha256": rec.sha(ops._canonical(pending)),
"owner": {"uid": args.target_uid, "gid": args.target_gid},
"redis_policy": "DISCARD_CANDIDATE_ALL_STATE_BACKUP_RETAINED",
"neo_runtime_owner": "0:0", "pcap_policy": "EMPTY_CLOSED_FILE_NO_AUTO_IMPORT"}
staging.write_new_bytes("application-recovery.json", ops._canonical(state))
# Validate once more before publishing a private, non-toolkit-runnable
# candidate. No database service has been started at this point.
if rec.verify_backup(backup)[1] != manifest:
raise Error("backup changed during application recovery preparation")
ops._publish_directory(staging, target)
finally:
staging.cleanup()
# Only this exact newly published public-to-container directory needs
# traversal by UID 65534. Its parent stays operator-only 0700.
folder = ops._canonical_root_directory(target / "pcaps")
fd = os.open(folder, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fchmod(fd, 0o755)
finally:
os.close(fd)
return workspace(target)
def workspace(path):
root = rec.private_root(path)
state = kit.load(root / "application-recovery.json")
fields = {"schema", "project", "source_project", "stage_project", "daemon_id", "backup_sha256",
"stage_verification_sha256", "pending_sha256", "owner", "redis_policy", "neo_runtime_owner", "pcap_policy"}
ops._strict_keys(state, fields, fields, "application recovery")
if (state["schema"] != SCHEMA or not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", state["project"]) or
not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", state["source_project"]) or
state["project"] == state["source_project"] or
not re.fullmatch(r"dh-recovery-[a-f0-9]{12}", state["stage_project"]) or
not re.fullmatch(r"[A-Za-z0-9:_.-]{8,128}", state["daemon_id"]) or
any(not re.fullmatch(r"[a-f0-9]{64}", state[name]) for name in
("backup_sha256", "stage_verification_sha256", "pending_sha256")) or
state["owner"] != {"uid": root.stat().st_uid, "gid": root.stat().st_gid} or
state["redis_policy"] != "DISCARD_CANDIDATE_ALL_STATE_BACKUP_RETAINED" or
state["neo_runtime_owner"] != "0:0" or state["pcap_policy"] != "EMPTY_CLOSED_FILE_NO_AUTO_IMPORT"):
raise Error("application recovery identity or ownership contract changed")
pending = kit.load(root / "deployment.pending.json")
ops._strict_keys(pending, {"schema", "project", "source_pins", "approval_id", "files"},
{"schema", "project", "source_pins", "approval_id", "files"}, "pending deployment")
if (rec.sha(ops._canonical(pending)) != state["pending_sha256"] or pending["schema"] != kit.SCHEMA or
pending["project"] != state["project"] or pending["source_pins"] != kit.shared.PINS or
not isinstance(pending["files"], dict) or not 1 <= len(pending["files"]) <= rec.MAX_FILES):
raise Error("application recovery pending manifest changed")
anchor = ops._root_anchor_identity(root.stat())
for name, digest in pending["files"].items():
ops._portable_relative_posix(name, "pending recovery member")
if name.startswith(("data/", "pcaps/")) or not re.fullmatch(r"[a-f0-9]{64}", digest):
raise Error("invalid recovery immutable member")
metadata, observed = ops._hash_anchored_regular(root, name, anchor, rec.MAX_FILE)
if observed != digest or metadata.st_uid != state["owner"]["uid"]:
raise Error("application recovery immutable input changed")
for folder in ("data", *["data/" + name for name in (*rec.BACKENDS, "neo")], "pcaps"):
if ops._canonical_root_directory(root / folder) != root / folder:
raise Error("linked recovery data directory")
runtime = rec.maintained_runtime(root, pending, kit.load(root / "compose.json"), kit.validate_profile(kit.load(root / "profile.json")))
return root, state, pending, runtime, kit.load(root / "profile.json")
def ready(identity, database):
deadline = time.monotonic() + 60
while True:
try:
if database:
rec.run(["docker", "exec", identity, "pg_isready", "-h", "127.0.0.1", "-U", database, "-d", database], timeout=5)
elif rec.run(["docker", "exec", identity, "redis-cli", "--raw", "PING"], timeout=5).strip() != b"PONG":
raise Error("candidate Redis not ready")
return
except Error:
if time.monotonic() >= deadline:
raise Error("candidate native database readiness timed out")
time.sleep(0.5)
def restore_pg(backup, manifest, identity, name, database):
base = ["docker", "exec", identity, "psql", "-X", "-A", "-t", "-U", database, "-d", database, "-c"]
if rec.run(base + ["SELECT count(*) FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE';"]).strip() != b"0":
raise Error("application recovery database is not empty")
relative = "dumps/" + name + ".dump"
fd = ops._open_anchored_regular(backup, relative, ops._root_anchor_identity(backup.stat()))
try:
before = os.fstat(fd)
digest = hashlib.sha256()
for chunk in iter(lambda: os.read(fd, rec.CHUNK), b""):
digest.update(chunk)
if manifest["files"][relative] != {"bytes": before.st_size, "sha256": digest.hexdigest()}:
raise Error("native application restore dump changed before use")
os.lseek(fd, 0, os.SEEK_SET)
rec.run(["docker", "exec", "-i", identity, "pg_restore", "-U", database, "-d", database,
"--exit-on-error", "--single-transaction", "--no-owner", "--no-privileges"], stdin=fd, timeout=300)
if ops._stat_identity(before) != ops._stat_identity(os.fstat(fd)):
raise Error("native application restore dump changed during use")
finally:
os.close(fd)
if rec.pg_summary(identity, database) != manifest["databases"][name]:
raise Error("restored application database differs from verified native backup")
def runtime_ownership(current):
owners = {}
for name, database in rec.BACKENDS.items():
identity = current[name]["id"]
account = "postgres" if database else "redis"
uid = rec.run(["docker", "exec", identity, "id", "-u", account]).decode().strip()
gid = rec.run(["docker", "exec", identity, "id", "-g", account]).decode().strip()
if not all(re.fullmatch(r"[0-9]{1,10}", value) and 0 < int(value) < 2 ** 31 for value in (uid, gid)):
raise Error("invalid native database runtime UID/GID")
path = "/var/lib/postgresql/data" if database else "/data"
actual = rec.run(["docker", "exec", identity, "stat", "-c", "%u:%g:%a", path]).decode().strip().split(":")
# Official Redis's entrypoint can change only the owner, retaining the
# operator's group. A 0700 root is accessible by its runtime UID only;
# no broad group permission or recursive chmod is required.
if (len(actual) != 3 or actual[0] != uid or
not re.fullmatch(r"[0-9]{1,10}", actual[1]) or actual[2] != "700"):
raise Error("component-native data ownership differs from its runtime account")
owners[name] = actual[0] + ":" + actual[1]
owners.update({"neo-server": "0:0", "packmate": "65534:65534"})
return owners
def stopped_epochs(context):
current = stopped(context, strict=True)
result = {}
for name, item in sorted(current.items()):
value = json.loads(rec.run(["docker", "inspect", "--format",
'{"id":{{json .Id}},"running":{{json .State.Running}},"started":{{json .State.StartedAt}},'
'"finished":{{json .State.FinishedAt}},"restarts":{{json .RestartCount}}}', item["id"]]))
if (set(value) != {"id", "running", "started", "finished", "restarts"} or value["id"] != item["id"] or
value["running"] is not False or type(value["restarts"]) is not int or value["restarts"] < 0 or
any(not isinstance(value[key], str) or not re.fullmatch(r"[0-9T:.Z+-]{20,40}", value[key])
for key in ("started", "finished"))):
raise Error("candidate stopped-container epoch changed during inspection")
result[name] = value
return result
def packmate_ready(root, profile, timeout=120):
pairs = dict(line.split("=", 1) for line in kit.read(root / "config/packmate.properties").decode().splitlines())
credentials = (pairs["packmate.web.account-login"] + ":" + pairs["packmate.web.account-password"]).encode("ascii")
headers = {"Authorization": "Basic " + base64.b64encode(credentials).decode("ascii"), "Accept-Encoding": "identity"}
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), kit.shared.NoRedirect())
url = "http://" + profile["bind_address"] + ":" + str(profile["ports"]["packmate"])
deadline = time.monotonic() + timeout
while True:
try:
values = []
for path in ("/api/service/", "/api/pcap/started"):
with opener.open(urllib.request.Request(url + path, headers=headers), timeout=5) as response:
data = response.read(1024 * 1024 + 1)
if response.status != 200 or len(data) > 1024 * 1024:
raise Error("Packmate recovery response rejected; raw data suppressed")
values.append(json.loads(data))
if not isinstance(values[0], list) or values[1] is not False:
raise Error("Packmate application or stopped-capture acceptance failed")
return
except (OSError, ValueError, urllib.error.URLError):
if time.monotonic() >= deadline:
raise Error("authenticated Packmate recovery readiness timed out")
time.sleep(0.5)
def start_and_check(root, state, runtime, profile):
context = (root, state["project"], selected(runtime), state["daemon_id"], kit.LABEL)
rec.owned(*context, exclusive=False)
rec.run(command(root, state) + ["up", "--detach", "--no-build", "--pull", "never", "farm", "front", "packmate"], timeout=180)
kit.wait_farm(profile, runtime)
rec.run(command(root, state) + ["up", "--detach", "--no-build", "--pull", "never", "neo-server"], timeout=60)
kit.wait_neo(root, state, runtime)
packmate_ready(root, profile)
observed = rec.wait_strict_owned(context)
if set(observed) != set(ACTIVE) or not all(value["running"] for value in observed.values()):
raise Error("application recovery running service set mismatch")
def acceptance(root, state):
value = kit.load(root / "recovery-acceptance.json")
fields = {"schema", "project", "recovery_sha256", "checks", "runtime_owners", "redis_policy", "stopped_containers",
"candidate_stopped", "submission_enabled", "worker_enabled", "capture_enabled", "seconds"}
ops._strict_keys(value, fields, fields, "application recovery acceptance")
if (value["schema"] != ACCEPTANCE or value["project"] != state["project"] or
value["recovery_sha256"] != rec.sha(ops._canonical(state)) or
not isinstance(value["checks"], dict) or set(value["checks"]) != CHECKS or
not all(result is True for result in value["checks"].values()) or
value["redis_policy"] != state["redis_policy"] or value["candidate_stopped"] is not True or
any(value[key] is not False for key in ("submission_enabled", "worker_enabled", "capture_enabled")) or
not isinstance(value["runtime_owners"], dict) or set(value["runtime_owners"]) != set(rec.BACKENDS) | {"neo-server", "packmate"} or
any(not isinstance(owner, str) or not re.fullmatch(r"[0-9]{1,10}:[0-9]{1,10}", owner)
for owner in value["runtime_owners"].values()) or
not isinstance(value["stopped_containers"], dict) or set(value["stopped_containers"]) != set(ACTIVE) or
type(value["seconds"]) not in (int, float) or not 0 <= value["seconds"] <= 86400):
raise Error("application recovery acceptance is incomplete or not bound to this candidate")
return value
def recover(args):
target = ops._safe_output_parent(Path(args.output))
data, source = inputs(args, target)
if not args.apply:
return {"status": "NOT_RUN", "action": "recover", "source_auto_resume": False,
"redis_policy": "DISCARD_CANDIDATE_ALL_STATE_BACKUP_RETAINED", "limits": LIMITS,
"effects": ["new native restore", "app authentication and restart checks", "leave candidate stopped and not toolkit-runnable"]}
require_gates(args)
stage = data[6]
stage_context = (stage[0], stage[1]["project"], stage[2], args.daemon_id, rec.LABEL)
stopped(source)
stopped(stage_context, strict=True)
started = time.monotonic()
root, state, pending, runtime, profile = prepare_files(args, target, data)
context = (root, state["project"], selected(runtime), args.daemon_id, kit.LABEL)
checks = {}
try:
stopped(source)
stopped(stage_context, strict=True)
rec.run(command(root, state) + ["up", "--detach", "--no-build", "--pull", "never"] + list(rec.BACKENDS), timeout=180)
current = rec.owned(*context, exclusive=False)
if set(current) != set(rec.BACKENDS):
raise Error("candidate native restore service set mismatch")
for name, database in rec.BACKENDS.items():
identity = current[name]["id"]
ready(identity, database)
if database:
restore_pg(data[0], data[1], identity, name, database)
checks[name] = True
elif rec.run(["docker", "exec", identity, "redis-cli", "--raw", "DBSIZE"]).strip() != b"0":
raise Error("candidate Redis contains state; refusing queue replay")
checks["candidate_redis_empty"] = True
owners = runtime_ownership(current)
checks["runtime_ownership"] = True
start_and_check(root, state, runtime, profile)
rec.stop(context, APPS, exclusive=False)
start_and_check(root, state, runtime, profile)
checks.update({name: True for name in ("farm_authenticated", "neo_authenticated", "packmate_authenticated",
"packmate_capture_stopped", "restart_reconnect")})
finally:
# Reconcile an interrupted Compose create by exact project ownership.
# A cleanup failure is BLOCKED; no acceptance or runnable manifest exists.
try:
kit.cleanup_readiness_probes(state)
finally:
# A probe reconciliation failure must not skip stopping the
# separately owned application stack. Either failure stays BLOCKED.
rec.stop(context, ACTIVE, exclusive=False)
epochs = stopped_epochs(context)
stopped(source)
stopped(stage_context, strict=True)
checks.update(source_stopped=True, stage_stopped=True)
if rec.verify_backup(data[0])[1] != data[1]:
raise Error("backup changed during application acceptance")
workspace(root)
record = {"schema": ACCEPTANCE, "project": state["project"], "recovery_sha256": rec.sha(ops._canonical(state)),
"checks": checks, "runtime_owners": owners, "stopped_containers": epochs,
"redis_policy": state["redis_policy"], "candidate_stopped": True,
"submission_enabled": False, "worker_enabled": False, "capture_enabled": False,
"seconds": round(time.monotonic() - started, 3)}
ops._atomic_write_new(root / "recovery-acceptance.json", ops._canonical(record))
return {"status": "PASS", "action": "recover", "application_acceptance": "PASS", "toolkit_runnable": False,
"candidate_stopped": True, "acceptance_sha256": rec.sha(ops._canonical(record)), "checks": checks,
"limits": LIMITS, "next": "review acceptance; explicitly activate with its checksum; then separately toolkit up",
"rollback": "source, backup, stage and candidate retained stopped; no data removed"}
def activate(args):
root, state, pending, runtime, profile = workspace(args.output)
data, source = inputs(args, root)
record = acceptance(root, state)
if (state["backup_sha256"] != rec.sha(ops._canonical(data[1])) or
state["stage_verification_sha256"] != data[6][3]["verification_sha256"] or
state["daemon_id"] != args.daemon_id):
raise Error("activation provenance differs from verified recovery inputs")
if (root / "deployment.json").exists():
raise Error("candidate is already activated; no manifest overwritten")
if not args.apply:
return {"status": "NOT_RUN", "action": "activate", "acceptance_sha256": rec.sha(ops._canonical(record)),
"effects": ["publish maintained deployment ownership manifest", "no services started"], "limits": LIMITS}
require_gates(args)
if not args.activation_confirmed or args.acceptance_sha256 != rec.sha(ops._canonical(record)):
raise Error("activation requires --activation-confirmed and the reviewed --acceptance-sha256")
stage = data[6]
stopped(source)
stopped((stage[0], stage[1]["project"], stage[2], args.daemon_id, rec.LABEL), strict=True)
if stopped_epochs((root, state["project"], selected(runtime), args.daemon_id, kit.LABEL)) != record["stopped_containers"]:
raise Error("candidate restarted or changed after application acceptance; recover into a fresh candidate")
kit.check_build_receipt(root, kit.load(root / "compose.json"), kit.image_preflight(runtime, profile))
workspace(root)
# The no-replace hard link is the final commit. A lost completion response
# is reconciled by inode identity, never by mere file contents.
anchor = ops._root_anchor_identity(root.stat())
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
descriptor = None
try:
if ops._root_anchor_identity(os.fstat(directory)) != anchor:
raise Error("candidate root changed before activation commit")
descriptor = os.open("deployment.pending.json", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory)
metadata = os.fstat(descriptor)
raw = b""
while True:
part = os.read(descriptor, 65536)
if not part:
break
raw += part
if len(raw) > 8 * 1024 * 1024:
raise Error("pending manifest exceeds activation bound")
before = os.stat("deployment.pending.json", dir_fd=directory, follow_symlinks=False)
if (not stat.S_ISREG(before.st_mode) or before.st_uid != args.target_uid or
ops._stat_identity(before) != ops._stat_identity(metadata) or
ops._stat_identity(os.fstat(descriptor)) != ops._stat_identity(metadata) or
raw != ops._canonical(pending) or rec.sha(raw) != state["pending_sha256"]):
raise Error("pending deployment identity changed before activation")
link_error = None
try:
os.link("deployment.pending.json", "deployment.json", src_dir_fd=directory, dst_dir_fd=directory, follow_symlinks=False)
except BaseException as error:
link_error = error
# Hold the verified source descriptor through the commit. link(2)
# resolves its source NAME afresh, so a successful syscall alone does
# not prove it linked the inode we verified before the call.
published = None
final_descriptor = None
try:
published = os.stat("deployment.json", dir_fd=directory, follow_symlinks=False)
final_descriptor = os.open("deployment.json", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory)
final_metadata = os.fstat(final_descriptor)
final_raw = b""
while True:
part = os.read(final_descriptor, 65536)
if not part:
break
final_raw += part
if len(final_raw) > 8 * 1024 * 1024:
raise Error("published activation manifest exceeds bounds")
if (not stat.S_ISREG(published.st_mode) or
ops._stat_identity(final_metadata) != ops._stat_identity(published) or
ops._root_anchor_identity(published) != ops._root_anchor_identity(os.fstat(descriptor)) or
final_raw != raw or rec.sha(final_raw) != state["pending_sha256"] or
ops._stat_identity(os.fstat(final_descriptor)) != ops._stat_identity(final_metadata) or
ops._root_anchor_identity(root.stat()) != anchor):
raise Error("activation source changed at commit; candidate manifest rejected")
except BaseException:
if published is not None and link_error is None:
# Remove only the exact new destination just inspected. Never
# remove a concurrently replaced destination by pathname alone.
try:
named = os.stat("deployment.json", dir_fd=directory, follow_symlinks=False)
if ops._root_anchor_identity(named) == ops._root_anchor_identity(published):
os.unlink("deployment.json", dir_fd=directory)
except OSError:
pass
if link_error is not None:
raise link_error
raise
finally:
if final_descriptor is not None:
try:
os.close(final_descriptor)
except OSError:
pass
finally:
if descriptor is not None:
try:
os.close(descriptor)
except OSError:
pass
try:
os.fsync(directory)
except OSError:
pass
try:
os.close(directory)
except OSError:
pass
return {"status": "PASS", "action": "activate", "toolkit_runnable": True, "candidate_stopped": True,
"services_started": False, "limits": LIMITS,
"next": "toolkit up on this NEW workspace; submission and worker remain separate explicit decisions",
"rollback": "toolkit down on this candidate only; source and backup unchanged"}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("recover", "verify", "activate", "stop"))
parser.add_argument("--output", required=True)
for name in ("workspace", "backup", "stage", "stage-project", "daemon-id", "approval-id", "acceptance-sha256"):
parser.add_argument("--" + name)
for name in ("apply", "snapshot-confirmed", "maintenance-confirmed", "queue-reviewed", "ttl-reviewed",
"discard-candidate-redis-state", "activation-confirmed"):
parser.add_argument("--" + name, action="store_true")
for name in ("target-uid", "target-gid"):
parser.add_argument("--" + name, type=int)
args = parser.parse_args(argv)
try:
if args.action in {"recover", "activate"}:
if not all((args.workspace, args.backup, args.stage, args.stage_project, args.daemon_id)):
raise Error("recover/activate require source workspace, backup, stage, exact stage project and daemon ID")
result = recover(args) if args.action == "recover" else activate(args)
else:
root, state, pending, runtime, profile = workspace(args.output)
if args.action == "verify":
record = acceptance(root, state)
result = {"status": "PASS", "configuration_integrity": "PASS", "runtime": "NOT_RUN",
"acceptance_sha256": rec.sha(ops._canonical(record)), "limits": LIMITS}
elif not args.apply:
result = {"status": "NOT_RUN", "action": "stop", "effects": ["stop only owned candidate services; retain data"]}
else:
rec.require_apply(args)
if args.daemon_id != state["daemon_id"]:
raise Error("stop daemon differs from candidate identity")
try:
kit.cleanup_readiness_probes(state)
finally:
rec.stop((root, state["project"], selected(runtime), args.daemon_id, kit.LABEL), ACTIVE, exclusive=False)
result = {"status": "PASS", "action": "stop", "data_retained": True}
print(json.dumps(result, sort_keys=True, indent=2))
return 0
except (Exception, KeyboardInterrupt) as error:
print(json.dumps({"status": "BLOCKED", "reason": str(error) if isinstance(error, Error) else
"recovery rejected: " + type(error).__name__, "raw_output": "suppressed",
"rollback": "inspect exact candidate with stop; retain all source/backup/stage data"}))
return 2
if __name__ == "__main__":
sys.exit(main())
+593
View File
@@ -0,0 +1,593 @@
#!/usr/bin/env python3
"""Pinned, private S4DFarm/Neo/Packmate deployment. Preview is the default.
Never run this against an untrusted Docker daemon or untrusted source checkout.
No secrets, expanded Compose model or upstream command output are printed.
"""
from __future__ import annotations
import argparse
import copy
import hashlib
import importlib.util
import ipaddress
import json
import os
from pathlib import Path
import re
import secrets
import stat
import subprocess
import sys
import time
import urllib.error
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location("deployment_shared", ROOT / "integration/stack_smoke.py")
shared = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(shared)
Error = shared.FixtureError
SCHEMA = "durkahelper.deployment.v1"
LABEL = "io.durkahelper.deployment"
PROBE_LABEL = "io.durkahelper.readiness-probe"
LIGHT = "ghcr.io/c4t-but-s4d/neo_env_light:v2.4.2@sha256:75deed498a6451f702d88f05495af8c7006707ac223ad4b2e7def0d947b622bc"
PACKMATE = "registry.gitlab.com/packmate/packmate:v4.0@sha256:faa39ec74a63d84558e08ab949b7724a0a014f6629d105a5212a3afb05c7cbf7"
PACKMATE_DB = "postgres:15.2@sha256:78a275d4c891f7b3a33d3f1a78eda9f1d744954d9e20122bfdc97cdda25cddaf"
LOGGER = "ru.serega6531.packmate.configuration.SecurityConfiguration"
BUILD_SERVICES = ("farm", "celery", "front", "neo-server")
SERVICES = ("postgres", "redis", "neo-redis", "farm", "front", "neo-server", "packmate-db", "packmate")
NOT_VALIDATED = ["Docker Desktop", "physical team LAN", "continuous capture",
"competition protocol", "component recovery", "full offline cold start"]
def safe_path(path):
"""Allow ordinary macOS ancestor aliases, reject a linked leaf/reparse point."""
raw = Path(os.path.abspath(path))
if raw.is_symlink() or getattr(raw.lstat() if raw.exists() else None, "st_file_attributes", 0) & 0x400:
raise Error("linked deployment paths are not allowed")
resolved = shared.no_links(raw) if os.name == "nt" else raw.parent.resolve(strict=True) / raw.name
if any(c in str(resolved) for c in (",", "\r", "\n", "$")):
raise Error("deployment path contains unsupported delimiter")
return resolved
def read(path, limit=1024 * 1024):
path = safe_path(path)
before = path.lstat()
if not stat.S_ISREG(before.st_mode) or before.st_size > limit:
raise Error("input must be a bounded regular file")
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) |
getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0))
try:
same = lambda s: (s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns)
opened = os.fstat(fd)
if not stat.S_ISREG(opened.st_mode) or same(opened) != same(before):
raise Error("input changed while opening")
with os.fdopen(fd, "rb", closefd=False) as stream:
result = stream.read(limit + 1)
if len(result) > limit or same(opened) != same(os.fstat(fd)) or same(opened) != same(path.lstat()):
raise Error("input changed while reading")
return result
finally:
os.close(fd)
def load(path):
def unique(pairs):
result = {}
for key, value in pairs:
if key in result:
raise Error("duplicate JSON key")
result[key] = value
return result
return json.loads(read(path), object_pairs_hook=unique)
def validate_profile(value):
required = {"schema", "platform", "bind_address", "ports", "allow_amd64_emulation", "farm", "packmate"}
if not isinstance(value, dict) or set(value) != required or value["schema"] != "durkahelper.deployment-profile.v1":
raise Error("invalid deployment profile schema or fields")
platform = value["platform"]
if platform not in ({"os": "linux", "architecture": "amd64", "runtime": "docker-engine"},
{"os": "linux", "architecture": "arm64", "runtime": "docker-engine"},
{"os": "darwin", "architecture": "arm64", "runtime": "docker-desktop"}):
raise Error("unsupported deployment platform")
ip = ipaddress.ip_address(value["bind_address"])
if ip.version != 4 or ip.is_unspecified or ip.is_multicast or ip.is_link_local:
raise Error("bind_address must be an explicit unicast IPv4 address, never wildcard")
ports = value["ports"]
if (not isinstance(ports, dict) or set(ports) != {"farm", "neo", "packmate"} or
any(type(p) is not int or not 1024 <= p <= 65535 for p in ports.values()) or len(set(ports.values())) != 3):
raise Error("three distinct unprivileged UI/API ports are required")
if type(value["allow_amd64_emulation"]) is not bool:
raise Error("allow_amd64_emulation must be boolean")
pm = value["packmate"]
if not isinstance(pm, dict) or set(pm) != {"mode", "local_ip", "pcap_file", "interface", "retention_minutes"}:
raise Error("invalid Packmate profile")
if pm["mode"] not in {"FILE", "LIVE"}:
raise Error("Packmate mode must be FILE or LIVE")
ipaddress.ip_address(pm["local_ip"])
if not isinstance(pm["pcap_file"], str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,100}\.pcap", pm["pcap_file"]):
raise Error("pcap_file must be a simple .pcap filename")
if not isinstance(pm["interface"], str) or not re.fullmatch(r"[A-Za-z0-9_.:-]{0,32}", pm["interface"]):
raise Error("invalid capture interface")
if type(pm["retention_minutes"]) is not int or not 5 <= pm["retention_minutes"] <= 1440:
raise Error("capture retention must be 5..1440 minutes")
farm = value["farm"]
required_farm = {"teams", "flag_format", "protocol", "protocol_settings", "submit_limit", "submit_period", "flag_lifetime"}
if not isinstance(farm, dict) or set(farm) != required_farm:
raise Error("invalid farm profile")
if not isinstance(farm["teams"], dict) or not 1 <= len(farm["teams"]) <= 512:
raise Error("explicit bounded competition team map required")
for name, addr in farm["teams"].items():
if not re.fullmatch(r"[A-Za-z0-9 _.-]{1,80}", name):
raise Error("invalid team label")
ipaddress.ip_address(addr)
if not isinstance(farm["flag_format"], str) or not 1 <= len(farm["flag_format"]) <= 512:
raise Error("explicit bounded competition flag format required")
# Only the reviewed JSON-scalar adapter configuration is accepted. This is
# not a claim that ructf_http is correct for any particular competition.
if farm["protocol"] != "ructf_http" or set(farm["protocol_settings"]) != {"SYSTEM_URL", "SYSTEM_TOKEN"}:
raise Error("only reviewed ructf_http adapter supported; other competition protocols need an adapter review")
import urllib.parse
endpoint = urllib.parse.urlsplit(farm["protocol_settings"]["SYSTEM_URL"])
if endpoint.scheme not in {"http", "https"} or not endpoint.hostname or endpoint.username or endpoint.password:
raise Error("competition endpoint must be explicit HTTP(S), without embedded credentials")
for name in ("submit_limit", "submit_period", "flag_lifetime"):
if type(farm[name]) is not int or not 1 <= farm[name] <= 86400:
raise Error("invalid competition timing/limit setting")
if not isinstance(farm["protocol_settings"]["SYSTEM_TOKEN"], str) or not 1 <= len(farm["protocol_settings"]["SYSTEM_TOKEN"]) <= 512:
raise Error("competition token must be supplied privately")
return value
def validate_credentials(value):
if not isinstance(value, dict) or set(value) != {"farm_password", "database_password", "neo_key", "packmate_user", "packmate_password"}:
raise Error("invalid credential fields")
for name, text in value.items():
pattern = r"[A-Za-z0-9_.-]{4,64}" if name == "packmate_user" else r"[A-Za-z0-9_.-]{20,128}"
if not isinstance(text, str) or not re.fullmatch(pattern, text) or text.startswith("REPLACE_"):
raise Error("credentials require safe generated ASCII values; passwords/key at least 20 characters")
return value
def compose_spec(profile, credentials, project, images):
spec = shared.compose_spec(project, images)
for name in ("receiver", "neo-client", "neo-client-denied"):
del spec["services"][name]
for name, service in spec["services"].items():
service["labels"] = {LABEL: project}
service["restart"] = "unless-stopped"
service["platform"] = "linux/" + profile["platform"]["architecture"]
if "build" in service:
service["image"] = project + "-" + name + ":pinned"
if name in {"farm", "celery"}:
service["networks"] = ["fixture", "edge"]
service["environment"]["POSTGRES_DSN"] = "host=postgres port=5432 user=farm password=" + credentials["database_password"] + " dbname=farm"
service["environment"]["SERVER_PASSWORD"] = credentials["farm_password"]
service["depends_on"].pop("receiver", None)
if name == "postgres":
service["environment"]["POSTGRES_PASSWORD"] = credentials["database_password"]
if name in {"redis", "neo-redis"}:
service["healthcheck"] = {"test": ["CMD", "redis-cli", "ping"], "interval": "5s", "timeout": "2s", "retries": 12}
# Submission is opt-in so a restored deployment cannot send old queued data.
spec["services"]["celery"]["profiles"] = ["submission"]
for service, label in (("front", "farm"), ("neo-server", "neo")):
port = spec["services"][service]["ports"][0]
port.update(host_ip=profile["bind_address"], published=str(profile["ports"][label]))
spec["services"]["neo-worker"] = {
"image": LIGHT, "platform": "linux/" + profile["platform"]["architecture"],
"entrypoint": ["/usr/local/bin/neo"], "command": ["--verbose=false", "--config", "/client.yml", "run", "--jobs", "1"],
"user": "65534:65534", "read_only": True, "cap_drop": ["ALL"], "init": True,
"security_opt": ["no-new-privileges:true"], "cpus": 1.0, "mem_limit": "512m", "pids_limit": 64,
"volumes": ["./config/neo-client.yml:/client.yml:ro"],
"tmpfs": ["/work:rw,nosuid,nodev,size=268435456,mode=0700,uid=65534,gid=65534,exec"],
"working_dir": "/work", "networks": ["fixture", "edge"], "restart": "no", "profiles": ["worker"],
"labels": {LABEL: project}, "logging": {"driver": "none"}}
base = {"restart": "unless-stopped", "cpus": 1.0, "mem_limit": "512m", "pids_limit": 128,
"security_opt": ["no-new-privileges:true"], "logging": {"driver": "none"}, "labels": {LABEL: project}}
spec["services"]["packmate-db"] = dict(base, image=PACKMATE_DB, networks=["fixture"],
environment={"POSTGRES_USER": "packmate", "POSTGRES_DB": "packmate", "POSTGRES_PASSWORD": credentials["database_password"]},
volumes=["./data/packmate-db:/var/lib/postgresql/data"],
healthcheck={"test": ["CMD", "pg_isready", "-U", "packmate", "-d", "packmate"], "interval": "5s", "timeout": "2s", "retries": 24})
spec["services"]["packmate"] = dict(base, image=PACKMATE, platform="linux/amd64", user="65534:65534",
read_only=True, cap_drop=["ALL"], mem_limit="1536m", networks=["fixture", "edge"],
tmpfs=["/tmp:size=67108864,mode=1777,noexec,nosuid,nodev", "/jna:size=16777216,mode=0700,uid=65534,gid=65534,nosuid,nodev,exec"],
volumes=["./config/packmate.properties:/configuration/application.properties:ro", "./pcaps:/app/pcaps:ro"],
entrypoint=["java"], command=["-Xms64m", "-Xmx768m", "-XX:ActiveProcessorCount=1", "-Djna.tmpdir=/jna", "-jar", "/app/app.jar",
"--spring.config.additional-location=file:/configuration/application.properties"],
ports=[{"target": 65000, "published": str(profile["ports"]["packmate"]), "host_ip": profile["bind_address"], "protocol": "tcp"}],
depends_on={"packmate-db": {"condition": "service_healthy"}})
for network in spec["networks"].values():
network["labels"] = {LABEL: project}
return spec
def properties(profile, credentials):
pm = profile["packmate"]
pairs = {"spring.datasource.url": "jdbc:postgresql://packmate-db:5432/packmate", "spring.datasource.username": "packmate",
"spring.datasource.password": credentials["database_password"], "packmate.web.account-login": credentials["packmate_user"],
"packmate.web.account-password": credentials["packmate_password"], "packmate.capture-mode": pm["mode"],
"packmate.pcap-file": pm["pcap_file"], "packmate.local-ip": pm["local_ip"], "packmate.interface-name": pm["interface"],
"packmate.cleanup.enabled": "true" if pm["mode"] == "LIVE" else "false",
"packmate.cleanup.threshold": str(pm["retention_minutes"]), "server.port": "65000", "server.address": "0.0.0.0",
"logging.level." + LOGGER: "OFF"}
return "".join(key + "=" + value + "\n" for key, value in sorted(pairs.items()))
def model(spec, profile, image_ids=None):
services = []
for name, service in sorted(spec["services"].items()):
mounts = []
for mount in service.get("volumes", []):
source, target, *flags = mount.split(":")
scope = "approved-data" if source.startswith(("./data/", "./pcaps")) else "approved-config"
mounts.append({"kind": "bind", "target": target, "source_scope": scope, "read_only": "ro" in flags})
for mount in service.get("tmpfs", []):
mounts.append({"kind": "tmpfs", "target": mount.split(":")[0], "source_scope": "approved-data", "read_only": False})
role = "backend" if name in {"postgres", "redis", "neo-redis", "packmate-db"} else "worker" if name in {"celery", "neo-worker"} else "ui" if name in {"front", "packmate"} else "api"
services.append({"id": name, "role": role, "image": (image_ids or {}).get(name, service["image"]),
"architectures": ["amd64"] if name == "packmate" else [profile["platform"]["architecture"]],
"mode": "file" if name == "packmate" else "none",
"ports": [{"host_ip": p["host_ip"], "host_port": int(p["published"]), "container_port": p["target"], "protocol": p["protocol"]} for p in service.get("ports", [])],
"mounts": mounts, "privileged": False, "network_mode": "bridge", "capabilities": [],
"nonroot": service.get("user", "0").split(":")[0] != "0" if "user" in service else None,
"healthcheck": bool(service.get("healthcheck")), "memory_limit_mb": int(service["mem_limit"][:-1]),
"cpu_limit": service["cpus"], "restart": service["restart"]})
return {"schema": "durkahelper.deployment-model.v1", "source_sha256": hashlib.sha256(shared.canonical(spec)).hexdigest(),
"platform": profile["platform"], "services": services}
def policy(profile, deployment_model):
return {"schema": "durkahelper.deployment-policy.v1", "team_lan": not ipaddress.ip_address(profile["bind_address"]).is_loopback,
"approved_bind_addresses": [profile["bind_address"]],
"approved_publications": [dict(service=s["id"], **{k: v for k, v in p.items() if k != "host_ip"}) for s in deployment_model["services"] for p in s["ports"]],
"approved_images": sorted({s["image"] for s in deployment_model["services"] if "@sha256:" in s["image"] or re.fullmatch(r"sha256:[a-f0-9]{64}", s["image"])}),
"require_healthcheck": True, "require_resource_limits": True, "require_nonroot": True,
"require_restart": True, "allow_amd64_emulation": profile["allow_amd64_emulation"], "approved_live_capture": []}
def write_build_files(workspace, images):
replacements = {"python:3.9-slim": images["python"], "node:20-slim": images["node"],
"nginx:1.21.0-alpine": images["nginx"], "golang:1.21-alpine": images["golang"], "alpine": images["alpine"]}
for role in ("server", "celery", "front"):
root = workspace / "sources/s4dfarm/server"
value = shared.pin_dockerfile(read(root / "docker" / role / "Dockerfile").decode(), replacements)
if role == "front":
value = value.replace("ENV PNPM_HOME=", 'ENV NODE_OPTIONS="--max-old-space-size=768"\nENV COREPACK_DEFAULT_TO_LATEST=0\nENV COREPACK_ENABLE_AUTO_PIN=0\nENV PNPM_HOME=')
value = value.replace("RUN corepack enable", 'RUN corepack enable && corepack prepare ' + shared.PNPM_DESCRIPTOR + ' --activate && test "$(pnpm --version)" = "' + shared.PNPM_VERSION + '"')
value = value.replace("COPY --from=front-build /app/dist /front", "COPY --from=front-build /app/dist /front\nRUN chmod -R a+rX /front")
shared.write(root / ("Dockerfile.fixture." + role), value)
root = workspace / "sources/neo"
value = shared.pin_dockerfile(read(root / "Dockerfile").decode(), replacements)
value = value.replace("ENV CGO_ENABLED=0", "ENV CGO_ENABLED=0\nENV GOMAXPROCS=1\nENV GOFLAGS=-p=1\nENV GOMEMLIMIT=768MiB")
shared.write(root / "Dockerfile.fixture", value)
def neo_farm_url(profile):
"""Neo advertises this same URL to workers; bridge DNS is not LAN DNS."""
if ipaddress.ip_address(profile["bind_address"]).is_loopback:
# Laptop-only demo with the bundled container worker, not LAN clients.
return "http://front"
return "http://" + profile["bind_address"] + ":" + str(profile["ports"]["farm"])
def prepare(args):
profile = validate_profile(load(args.profile))
credentials = validate_credentials(load(args.credentials))
root = safe_path(args.workspace)
if root.exists():
raise Error("deployment workspace must be new; existing data is never overwritten")
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "source_pins": shared.PINS,
"effects": ["private source/config/data directory", "no downloads or Docker operations"], "not_validated": NOT_VALIDATED}
if os.name == "nt":
raise Error("private deployment creation requires POSIX permissions; Windows is preview/test only")
if profile["packmate"]["mode"] == "LIVE":
raise Error("LIVE needs a separately approved Linux capture namespace and database routing; this bridge deployment is FILE-only")
if profile["platform"]["architecture"] == "arm64" and not profile["allow_amd64_emulation"]:
raise Error("pinned Packmate image is amd64-only; explicit emulation acceptance required")
images = shared.image_map(ROOT / "config/integration-images.lock.json")
root.mkdir(mode=0o700)
project = "dh-deploy-" + secrets.token_hex(6)
for component in shared.PINS:
shared.export_source(getattr(args, component + "_source"), root / "sources" / component, component)
write_build_files(root, images)
for folder in ("postgres", "redis", "neo-redis", "neo", "packmate-db"):
(root / "data" / folder).mkdir(parents=True, mode=0o700)
(root / "pcaps").mkdir(mode=0o755)
farm = profile["farm"]
config = dict(DEBUG=False, TEAMS=farm["teams"], FLAG_FORMAT=farm["flag_format"], SYSTEM_PROTOCOL=farm["protocol"],
SUBMIT_FLAG_LIMIT=farm["submit_limit"], SUBMIT_PERIOD=farm["submit_period"], FLAG_LIFETIME=farm["flag_lifetime"],
SERVER_PASSWORD=credentials["farm_password"], TIMEZONE="UTC", **farm["protocol_settings"])
shared.write(root / "config/farm.py", "CONFIG = " + repr(config) + "\n")
shared.write(root / "config/neo-server.yml", 'db_path: "/data/db.db"\nredis_url: "redis://neo-redis:6379/0"\nbase_dir: "/data/exploits"\nping_every: "5s"\nsubmit_every: "2s"\ngrpc_auth_key: "' + credentials["neo_key"] + '"\nfarm:\n url: "' + neo_farm_url(profile) + '"\n password: "' + credentials["farm_password"] + '"\n')
shared.write(root / "config/neo-client.yml", 'host: "neo-server:5005"\ngrpc_auth_key: "' + credentials["neo_key"] + '"\nexploit_dir: "/work/exploits"\nclient_id: "deployment-worker"\n')
shared.write(root / "config/packmate.properties", properties(profile, credentials))
for filename in ("neo-client.yml", "packmate.properties"):
(root / "config" / filename).chmod(0o644) # Individually mounted for UID 65534; private 0700 parent.
spec = compose_spec(profile, credentials, project, images)
shared.write(root / "compose.json", shared.canonical(spec))
shared.write(root / "profile.json", shared.canonical(profile))
deployment_model = model(spec, profile)
shared.write(root / "model.json", shared.canonical(deployment_model))
shared.write(root / "policy.json", shared.canonical(policy(profile, deployment_model)))
files = {p.relative_to(root).as_posix(): hashlib.sha256(read(p, shared.MAX_SOURCE)).hexdigest()
for p in root.rglob("*") if p.is_file()}
shared.write(root / "deployment.json", shared.canonical({"schema": SCHEMA, "project": project, "files": files,
"source_pins": shared.PINS, "approval_id": args.approval_id}))
return {"status": "PASS", "action": "prepare", "project": project, "not_validated": NOT_VALIDATED,
"submission": "disabled; enable only after protocol and restored-queue review", "rollback": "retain private workspace; no services started"}
def workspace(path):
root = safe_path(path)
if os.name != "nt" and root.stat().st_mode & 0o077:
raise Error("deployment workspace must have private 0700 permissions")
state = load(root / "deployment.json")
if (not isinstance(state, dict) or set(state) != {"schema", "project", "files", "source_pins", "approval_id"} or
state["schema"] != SCHEMA or not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", state["project"]) or state["source_pins"] != shared.PINS):
raise Error("invalid deployment ownership manifest")
if not isinstance(state["files"], dict) or not 1 <= len(state["files"]) <= 20000:
raise Error("invalid deployment file manifest")
for name, checksum in state["files"].items():
if (not isinstance(name, str) or Path(name).is_absolute() or "\\" in name or ":" in name or
any(part in {"..", "."} for part in name.split("/")) or not re.fullmatch(r"[a-f0-9]{64}", checksum)):
raise Error("invalid deployment manifest member")
# Parent aliases are allowed for the operator's workspace, never inside it.
candidate = root / name
if any(p.is_symlink() for p in (candidate, *candidate.parents) if p != root and root in p.parents):
raise Error("linked deployment member")
if hashlib.sha256(read(candidate, shared.MAX_SOURCE)).hexdigest() != checksum:
raise Error("deployment immutable configuration/source changed; prepare a new deployment")
for folder in ("data", "data/postgres", "data/redis", "data/neo-redis", "data/neo", "data/packmate-db", "pcaps"):
if (root / folder).is_symlink() or not (root / folder).is_dir():
raise Error("deployment data path must be a real directory")
return root, state, load(root / "compose.json"), validate_profile(load(root / "profile.json"))
def command(root, state, runtime=False):
return ["docker", "compose", "--project-name", state["project"], "--project-directory", str(root), "--file", str(root / ("runtime-compose.json" if runtime else "compose.json"))]
def owned_resources(state):
"""All matched resources must carry BOTH the Compose and private owner labels."""
project = state["project"]
for kind, listing in (("container", ["ps", "--all", "--quiet"]), ("network", ["network", "ls", "--quiet"])):
output = shared.checked(["docker"] + listing + ["--filter", "label=com.docker.compose.project=" + project], capture=True).decode().split()
if len(output) > 64 or any(not re.fullmatch(r"[a-f0-9]{12,64}", item) for item in output):
raise Error("unexpected project resource listing")
for identity in output:
fmt = '{{index .Config.Labels "' + LABEL + '"}}' if kind == "container" else '{{index .Labels "' + LABEL + '"}}'
actual = shared.checked(["docker", kind, "inspect", "--format", fmt, identity], capture=True).decode().strip()
if actual != project:
raise Error("ownership mismatch; refusing to affect project resources")
def image_preflight(spec, profile, require_build=True):
checks = {}
for name, svc in spec["services"].items():
if "build" in svc and not require_build:
continue
actual = shared.checked(["docker", "image", "inspect", "--format", "{{.Id}};{{.Os}};{{.Architecture}}", svc["image"]], capture=True).decode().strip().split(";")
expected = "amd64" if name == "packmate" else profile["platform"]["architecture"]
if len(actual) != 3 or not re.fullmatch(r"sha256:[a-f0-9]{64}", actual[0]) or actual[1:] != ["linux", expected]:
raise Error("cached image architecture mismatch or invalid image identity")
checks[name] = actual[0]
return checks
def runtime_spec(spec, identities):
result = copy.deepcopy(spec)
if set(identities) != set(spec["services"]) or any(not isinstance(value, str) or not re.fullmatch(r"sha256:[a-f0-9]{64}", value) for value in identities.values()):
raise Error("every runtime service requires an exact immutable local image identity")
for name, identity in identities.items():
result["services"][name]["image"] = identity
result["services"][name].pop("build", None)
return result
def check_build_receipt(root, spec, identities=None):
receipt = load(root / "build-receipt.json")
if receipt.get("schema") == "durkahelper.deployment-build.v1":
raise Error("legacy receipt does not pin all runtime images; prepare and build a new deployment before offline use")
if (set(receipt) != {"schema", "compose_sha256", "runtime_sha256", "images"} or receipt["schema"] != "durkahelper.deployment-build.v2"
or receipt["compose_sha256"] != hashlib.sha256(shared.canonical(spec)).hexdigest()
or set(receipt["images"]) != set(spec["services"])):
raise Error("build receipt does not match this deployment")
runtime = runtime_spec(spec, receipt["images"])
if (load(root / "runtime-compose.json") != runtime or
hashlib.sha256(read(root / "runtime-compose.json")).hexdigest() != receipt["runtime_sha256"]):
raise Error("runtime Compose changed after immutable build receipt")
if identities is not None and identities != receipt["images"]:
raise Error("runtime image identities differ from immutable receipt")
return runtime
def wait_farm(profile, spec, timeout=60):
"""Authenticate with the private configured password without emitting it."""
url = "http://" + profile["bind_address"] + ":" + str(profile["ports"]["farm"]) + "/api/get_config"
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), shared.NoRedirect())
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
request = urllib.request.Request(url, headers={"Authorization": spec["services"]["farm"]["environment"]["SERVER_PASSWORD"]})
try:
with opener.open(request, timeout=3) as response:
raw = response.read(1024 * 1024 + 1)
if len(raw) > 1024 * 1024:
raise Error("farm readiness response exceeded its bound")
data = json.loads(raw)
if response.status == 200 and isinstance(data, dict) and data.get("TEAMS") == profile["farm"]["teams"] and data.get("SYSTEM_PROTOCOL") == profile["farm"]["protocol"]:
return
except (OSError, ValueError, urllib.error.URLError):
pass
time.sleep(0.5)
raise Error("authenticated farm readiness timed out; services retained for scoped down")
def cleanup_readiness_probes(state, name=None):
"""Reconcile uncertain creates by exact name and both private labels.
The down path also finds probes whose Docker create outlived an interrupted
CLI. Never infer ownership from a matching name alone or delete by a name.
"""
project = state["project"]
if not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", project):
raise Error("invalid readiness project identity")
pattern = re.escape(project) + r"-readiness-[a-f0-9]{8}"
if name is not None and not re.fullmatch(pattern, name):
raise Error("invalid readiness probe name")
command = ["docker", "ps", "--all", "--quiet", "--no-trunc"]
if name is not None:
command += ["--filter", "name=^/" + name + "$"]
else:
command += ["--filter", "label=" + LABEL + "=" + project,
"--filter", "label=" + PROBE_LABEL + "=neo"]
identifiers = shared.checked(command, capture=True).decode().split()
if len(identifiers) > (1 if name else 64) or any(not re.fullmatch(r"[a-f0-9]{64}", item) for item in identifiers):
raise Error("unexpected readiness probe resource listing")
template = '{"id":{{json .Id}},"name":{{json .Name}},"owner":{{json (index .Config.Labels "' + LABEL + '")}},"purpose":{{json (index .Config.Labels "' + PROBE_LABEL + '")}}}'
for identity in identifiers:
observed = json.loads(shared.checked(["docker", "inspect", "--format", template, identity], capture=True))
actual_name = observed.get("name", "")
if (observed.get("id") != identity or observed.get("owner") != project or observed.get("purpose") != "neo" or
not isinstance(actual_name, str) or not re.fullmatch("/" + pattern, actual_name) or
(name is not None and actual_name != "/" + name)):
raise Error("readiness probe ownership mismatch; cleanup refused")
shared.checked(["docker", "rm", "--force", identity], timeout=20)
def wait_neo(root, state, runtime, timeout=60):
"""Info-only authenticated probe, nonroot and scoped to the owned bridge."""
project = state["project"]
name = project + "-readiness-" + secrets.token_hex(4)
image = runtime["services"]["neo-worker"]["image"]
# The name is registered before issuing create: a cancelled CLI can leave
# a successful daemon-side create whose response was never observed.
attempted = False
try:
attempted = True
shared.checked(["docker", "create", "--name", name, "--label", LABEL + "=" + project,
"--label", PROBE_LABEL + "=neo",
"--network", project + "_fixture", "--user", "65534:65534", "--read-only", "--cap-drop=ALL",
"--security-opt=no-new-privileges:true", "--memory=128m", "--memory-swap=128m", "--cpus=0.5", "--pids-limit=32",
"--log-driver=none", "--pull=never", "--mount", "type=bind,src=" + str(root / "config/neo-client.yml") + ",dst=/client.yml,readonly",
"--entrypoint", "/usr/local/bin/neo", image, "--verbose=false", "--config", "/client.yml", "info"], timeout=20)
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
shared.checked(["docker", "start", "--attach", name], timeout=min(10, max(1, deadline - time.monotonic())))
return
except Error:
time.sleep(0.5)
raise Error("authenticated Neo readiness timed out; services retained for scoped down")
finally:
if attempted:
cleanup_readiness_probes(state, name)
def execute(args):
root, state, spec, profile = workspace(args.workspace)
cmd = command(root, state)
if args.action == "model":
return model(check_build_receipt(root, spec), profile) if (root / "build-receipt.json").exists() else model(spec, profile)
if args.action == "preflight":
result = {"status": "PASS", "action": "preflight", "configuration_integrity": "PASS",
"runtime": "NOT_RUN", "not_validated": NOT_VALIDATED, "competition_ready": False}
if args.runtime:
runtime = check_build_receipt(root, spec)
shared.checked(command(root, state, runtime=True) + ["config", "--quiet"])
owned_resources(state)
result["cached_image_ids"] = image_preflight(runtime, profile)
check_build_receipt(root, spec, result["cached_image_ids"])
result["runtime"] = "PASS"
return result
if not args.apply:
return {"status": "NOT_RUN", "action": args.action, "project": state["project"],
"effects": ["project-scoped Docker operation"], "rollback": "down retains data and images"}
if os.name == "nt":
raise Error("deployment mutations require POSIX permissions")
owned_resources(state)
shared.checked(cmd + ["config", "--quiet"])
if args.action == "build":
if not args.connected_preparation:
raise Error("build requires --connected-preparation; prepare dependencies before offline rehearsal")
if (root / "build-receipt.json").exists():
raise Error("deployment already built; prepare a new workspace instead of overwriting its receipt")
for name in BUILD_SERVICES:
svc = spec["services"][name]
build = svc["build"]
shared.checked(["docker", "build", "--platform", svc["platform"], "--memory", "1536m", "--memory-swap", "1536m",
"--cpu-period", "100000", "--cpu-quota", "100000", "--tag", svc["image"], "--file",
str(root / build["context"] / build["dockerfile"]), str(root / build["context"])], timeout=1800,
environment=dict(os.environ, DOCKER_BUILDKIT="0"))
# Docker save/load by ID deliberately loses tags and RepoDigests. Pin
# *every* service to its verified platform-specific configuration ID,
# including databases and externally published runtime images.
identities = image_preflight(spec, profile)
runtime = runtime_spec(spec, identities)
runtime_data = shared.canonical(runtime)
shared.write(root / "runtime-compose.json", runtime_data)
runtime_model = model(runtime, profile)
shared.write(root / "runtime-model.json", shared.canonical(runtime_model))
shared.write(root / "runtime-policy.json", shared.canonical(policy(profile, runtime_model)))
shared.write(root / "build-receipt.json", shared.canonical({"schema": "durkahelper.deployment-build.v2",
"compose_sha256": hashlib.sha256(shared.canonical(spec)).hexdigest(), "runtime_sha256": hashlib.sha256(runtime_data).hexdigest(), "images": identities}))
return {"status": "PASS", "action": "build", "image_ids": identities,
"rollback": "images retained; interrupted builds may require inspection of exact build identity"}
if args.action == "down":
cleanup_readiness_probes(state)
shared.checked(cmd + ["--profile", "submission", "--profile", "worker", "down", "--timeout", "15"], timeout=90)
return {"status": "PASS", "action": "down", "rollback": "data and images retained; up recreates only this project"}
runtime = check_build_receipt(root, spec)
check_build_receipt(root, spec, image_preflight(runtime, profile))
cmd = command(root, state, runtime=True)
if args.action == "up":
pcap = safe_path(root / "pcaps" / profile["packmate"]["pcap_file"])
if not pcap.is_file() or pcap.is_symlink():
raise Error("FILE mode requires an operator-provided closed regular PCAP before startup")
# The retained Neo server fetches farm configuration once at startup.
# Compose's service_started condition is insufficient for that contract.
shared.checked(cmd + ["up", "--detach", "--no-build", "--pull", "never"] + [name for name in SERVICES if name != "neo-server"], timeout=180)
wait_farm(profile, spec)
shared.checked(cmd + ["up", "--detach", "--no-build", "--pull", "never", "neo-server"], timeout=60)
wait_neo(root, state, runtime)
elif args.action == "enable-submission":
if not args.protocol_reviewed or not args.queue_reviewed:
raise Error("submission requires --protocol-reviewed and --queue-reviewed")
shared.checked(cmd + ["--profile", "submission", "up", "--detach", "--no-build", "--pull", "never", "celery"], timeout=60)
elif args.action == "worker":
shared.checked(cmd + ["--profile", "worker", "up", "--detach", "--no-build", "--pull", "never", "neo-worker"], timeout=60)
return {"status": "PASS", "action": args.action, "readiness": {"farm_authenticated": "PASS", "neo_authenticated": "PASS", "packmate": "NOT_RUN", "team_lan": "NOT_RUN"} if args.action == "up" else "NOT_RUN", "not_validated": NOT_VALIDATED,
"rollback": "run down with the same workspace and approval; no volumes or data are deleted"}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "preflight", "model", "build", "up", "down", "worker", "enable-submission"])
parser.add_argument("--workspace", required=True)
for option in ("profile", "credentials", "s4dfarm-source", "neo-source", "approval-id"):
parser.add_argument("--" + option)
for option in ("apply", "runtime", "connected-preparation", "protocol-reviewed", "queue-reviewed"):
parser.add_argument("--" + option, action="store_true")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise Error("mutations require --apply and a non-secret --approval-id")
if args.action == "prepare" and not all((args.profile, args.credentials, args.s4dfarm_source, args.neo_source)):
raise Error("prepare requires profile, credentials and both pinned source checkout paths")
result = prepare(args) if args.action == "prepare" else execute(args)
print(json.dumps(result, sort_keys=True, indent=2))
return 0
except KeyboardInterrupt:
print(json.dumps({"status": "BLOCKED", "reason": "interrupted; inspect exact owned project before retry; data retained"}))
return 2
except (Error, OSError, ValueError, KeyError, TypeError, AttributeError, subprocess.SubprocessError) as error:
reason = str(error) if isinstance(error, Error) else "operation rejected: " + type(error).__name__
print(json.dumps({"status": "BLOCKED", "reason": reason, "raw_output": "suppressed"}))
return 2
if __name__ == "__main__":
sys.exit(main())