#!/usr/bin/env python3 """DurkaHelper operator commands: configure, prepare, start, scan and import traffic.""" from __future__ import annotations import argparse import hashlib import importlib.util import json import os from pathlib import Path import platform import re import secrets import struct import subprocess import sys import tempfile from types import SimpleNamespace from urllib.parse import urlsplit ROOT = Path(__file__).resolve().parent DEFAULT_CONFIG = ROOT / "local/durka.json" SCHEMA = "durkahelper.operator.v1" CONFIG_FILES = ("config/farm.py", "config/neo-server.yml", "config/packmate.properties", "profile.json", "compose.json", "model.json", "policy.json", "runtime-compose.json", "runtime-model.json", "runtime-policy.json", "build-receipt.json", "deployment.json") CONFIG_JOURNAL = ".durka-configuration.json" def module(name, path): spec = importlib.util.spec_from_file_location(name, ROOT / path) value = importlib.util.module_from_spec(spec) spec.loader.exec_module(value) return value # Operator commands must not leave import-cache writes in an offline checkout; # this also keeps the doctor path read-only without requiring a special flag. sys.dont_write_bytecode = True kit = module("durka_deployment", "deployment/toolkit.py") Error = kit.Error def target_platform(): architecture = {"aarch64": "arm64", "x86_64": "amd64", "AMD64": "amd64"}.get(platform.machine(), platform.machine()) if sys.platform == "darwin" and architecture == "arm64": return {"os": "darwin", "architecture": "arm64", "runtime": "docker-desktop"} if sys.platform.startswith("linux") and architecture in {"amd64", "arm64"}: return {"os": "linux", "architecture": architecture, "runtime": "docker-engine"} # Windows can configure an Apple Silicon deployment and run the scanner. return {"os": "darwin", "architecture": "arm64", "runtime": "docker-desktop"} def private_directory(path): path = kit.shared.no_links(path) path.mkdir(mode=0o700, parents=True, exist_ok=True) if not path.is_dir() or (os.name != "nt" and path.stat().st_mode & 0o077): raise Error("operator directories must be private (chmod 700); use a new private directory") return path def config_path(value): return kit.shared.no_links(Path(value).absolute()) def init(path): path = config_path(path) if path.exists(): raise Error("configuration already exists; edit it instead of running init again") private_directory(path.parent) value = kit.load(ROOT / "config/durka.example.json") value["profile"]["platform"] = target_platform() value["profile"]["allow_amd64_emulation"] = value["profile"]["platform"]["architecture"] == "arm64" value["credentials"] = {name: secrets.token_hex(20) for name in ("farm_password", "database_password", "neo_key", "packmate_password")} value["credentials"]["packmate_user"] = "operator" kit.shared.write(path, kit.shared.canonical(value)) print("Created " + str(path)) print("Edit the LAN address, team map and competition settings before setup. Passwords are stored in this private file.") if os.name == "nt": print("Run deployment commands on the Mac or Linux host; source scanning also works on Windows.") elif value["profile"]["platform"]["architecture"] == "arm64": print("Packmate uses its pinned amd64 image through Docker emulation on ARM64.") return 0 def load_config(path): path = config_path(path) try: value = kit.load(path) except FileNotFoundError as error: raise Error("configuration is missing; run python3 durka.py init first") from error if (not isinstance(value, dict) or set(value) != {"schema", "profile", "credentials", "paths"} or value["schema"] != SCHEMA or not isinstance(value["paths"], dict) or set(value["paths"]) != {"sources", "workspace"}): raise Error("invalid operator configuration; use config/durka.example.json as the reference") kit.validate_profile(value["profile"]) kit.validate_credentials(value["credentials"]) paths = {} for name, text in value["paths"].items(): if not isinstance(text, str) or not text.strip(): raise Error("sources and workspace paths must be nonempty") candidate = Path(text) paths[name] = kit.shared.no_links(candidate if candidate.is_absolute() else ROOT / candidate) if paths[name] == ROOT or paths[name] in ROOT.parents: raise Error("deployment paths must use dedicated directories") if (paths["sources"] == paths["workspace"] or paths["sources"] in paths["workspace"].parents or paths["workspace"] in paths["sources"].parents): raise Error("source and deployment directories must be separate") return value, paths def args_for(action, workspace, **values): defaults = dict(action=action, workspace=str(workspace), apply=True, approval_id="operator-" + secrets.token_hex(8), runtime=False, connected_preparation=False, protocol_reviewed=False, queue_reviewed=False, profile=None, credentials=None, s4dfarm_source=None, neo_source=None) defaults.update(values) return SimpleNamespace(**defaults) def require_host(profile): if os.name == "nt": raise Error("deployment commands require macOS or Linux; use scan on Windows") if profile["platform"] != target_platform(): raise Error("configured platform differs from this host; correct profile.platform before setup") def source_checkout(root, component, source): """Fetch only a locked repository/commit; resume only our private source cache.""" expected = {"schema": "durkahelper.operator-sources.v1", "sources": source} if root.exists(): private_directory(root) if not (root / ".durka-sources.json").is_file() or kit.load(root / ".durka-sources.json") != expected: raise Error("source directory is not this operator cache; choose a new sources path") else: private_directory(root) kit.shared.write(root / ".durka-sources.json", kit.shared.canonical(expected)) path = kit.shared.no_links(root / component) item = source[component] environment = {k: v for k, v in os.environ.items() if not k.upper().startswith("GIT_")} environment.update(GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1", GIT_TERMINAL_PROMPT="0", GIT_NO_REPLACE_OBJECTS="1", GIT_ATTR_NOSYSTEM="1", GIT_OPTIONAL_LOCKS="0") def git(*argv, capture=False): return kit.shared.checked(["git", "-c", "core.hooksPath=" + os.devnull, "-c", "core.fsmonitor=false", "-C", str(path), *argv], capture=capture, timeout=600, environment=environment) if not path.exists(): path.mkdir(mode=0o700) git("init", "--template=") git("remote", "add", "origin", item["repository"]) if not (path / ".git").is_dir() or (path / ".git").is_symlink(): raise Error("source checkout is incomplete or linked; use a new sources path") if git("remote", "get-url", "origin", capture=True).decode().strip() != item["repository"]: raise Error("source checkout origin differs from the locked upstream") try: head = git("rev-parse", "--verify", "HEAD", capture=True).decode().strip() except Error: head = None if head is not None: if head != item["commit"] or git("status", "--porcelain", "--untracked-files=all", capture=True): raise Error("source checkout changed; use a new sources path rather than overwriting it") else: git("fetch", "--depth", "1", "origin", item["commit"]) git("checkout", "--detach", item["commit"]) if git("rev-parse", "HEAD", capture=True).decode().strip() != item["commit"]: raise Error("source checkout did not resolve to the locked version") return path def check_config(root, value): if not root.exists(): raise Error("deployment is missing; run python3 durka.py setup first") root, state, spec, profile = kit.workspace(root) if profile != value["profile"] or spec != kit.compose_spec(profile, value["credentials"], state["project"], kit.shared.image_map(ROOT / "config/integration-images.lock.json")): raise Error("configuration changed after setup; run durka.py down, then durka.py configure to apply event settings") if not credentials_match(root, state, spec, profile, value["credentials"]): raise Error("configuration changed after setup; keep the old workspace for its data and set paths.workspace to a new directory") return root, state, spec, profile def credentials_match(root, state, spec, profile, credentials): return (spec == kit.compose_spec(profile, credentials, state["project"], kit.shared.image_map(ROOT / "config/integration-images.lock.json")) and kit.read(root / "config/packmate.properties").decode("ascii") == kit.properties(profile, credentials) and ('grpc_auth_key: "' + credentials["neo_key"] + '"\n') in kit.read(root / "config/neo-server.yml").decode("ascii")) def checksum(data): return hashlib.sha256(data).hexdigest() def replace_file(path, data, expected): """Replace one known private file atomically; never blindly overwrite a changed file.""" if checksum(kit.read(path)) != expected: raise Error("configuration changed concurrently; retained backup must be inspected") metadata = path.lstat() temporary = path.with_name(".durka-write-" + secrets.token_hex(8)) try: kit.shared.write(temporary, data) temporary.chmod(metadata.st_mode & 0o777) if checksum(kit.read(path)) != expected: raise Error("configuration changed concurrently; retained backup must be inspected") os.replace(temporary, path) if kit.read(path) != data: raise Error("configuration changed during publication; retained backup must be inspected") finally: if temporary.exists(): temporary.unlink() def bind_paths(root, paths): expected = {"schema": "durkahelper.operator-paths.v1", "paths": {name: str(path) for name, path in paths.items()}} path = root / "operator-paths.json" if path.exists(): if kit.load(path) != expected: raise Error("operator paths changed; retain the existing deployment and restore its original paths") return root, state, _, _ = kit.workspace(root) before = kit.read(root / "deployment.json") kit.shared.write(path, kit.shared.canonical(expected)) state["files"]["operator-paths.json"] = checksum(kit.read(path)) replace_file(root / "deployment.json", kit.shared.canonical(state), checksum(before)) def stopped(state): kit.owned_resources(state) identities = kit.shared.checked(["docker", "ps", "--all", "--quiet", "--filter", "label=com.docker.compose.project=" + state["project"]], capture=True).decode().split() if len(identities) > 64 or any(not re.fullmatch(r"[a-f0-9]{12,64}", item) for item in identities): raise Error("unexpected deployment resource inventory") for identity in identities: state_text = kit.shared.checked(["docker", "container", "inspect", "--format", "{{.State.Running}};{{.State.Restarting}}", identity], capture=True).decode().strip() if state_text != "false;false": raise Error("stop the entire deployment with durka.py down before configure") def pending(root): path = root / CONFIG_JOURNAL if path.exists() and kit.load(path).get("phase") == "pending": raise Error("configuration update was interrupted; run durka.py configure --rollback") def configuration_rollback(root): """Recover only the bounded files of the latest recorded configuration change.""" journal = kit.load(root / CONFIG_JOURNAL) if (set(journal) != {"schema", "phase", "backup", "files"} or journal["schema"] != "durkahelper.operator-configuration.v1" or journal["phase"] not in {"pending", "committed", "rolled-back"} or not isinstance(journal["backup"], str) or not re.fullmatch(r"configuration-backups/[a-f0-9]{16}", journal["backup"]) or not isinstance(journal["files"], dict) or set(journal["files"]) != set(CONFIG_FILES)): raise Error("invalid configuration recovery record") backup = kit.shared.no_links(root / journal["backup"]) originals = {} for name, hashes in journal["files"].items(): if (not isinstance(hashes, dict) or set(hashes) != {"before", "after"} or any(not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{64}", value) for value in hashes.values())): raise Error("invalid configuration recovery checks") originals[name] = kit.read(backup / name) if checksum(originals[name]) != hashes["before"] or checksum(kit.read(root / name)) not in set(hashes.values()): raise Error("configuration recovery files changed; retained backup must be inspected") state = json.loads(originals["deployment.json"]) if (state.get("schema") != kit.SCHEMA or state.get("source_pins") != kit.shared.PINS or not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", state.get("project", "")) or not isinstance(state.get("files"), dict) or not 1 <= len(state["files"]) <= 20000): raise Error("configuration recovery ownership record is invalid") for name, digest 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("/"))): raise Error("unsafe recovery member") candidate = kit.shared.no_links(root / name) data = originals[name] if name in originals else kit.read(candidate, kit.shared.MAX_SOURCE) if checksum(data) != digest: raise Error("original deployment changed outside configuration; refusing recovery") stopped(state) for name in CONFIG_FILES: current = checksum(kit.read(root / name)) if current != journal["files"][name]["before"]: replace_file(root / name, originals[name], current) root, state, spec, _ = kit.workspace(root) kit.check_build_receipt(root, spec) before = kit.read(root / CONFIG_JOURNAL) journal["phase"] = "rolled-back" replace_file(root / CONFIG_JOURNAL, kit.shared.canonical(journal), checksum(before)) return backup / "operator.json" def configure(value, paths, rollback=False): require_host(value["profile"]) root = paths["workspace"] if rollback: previous = configuration_rollback(root) print("Previous deployment configuration restored; data retained.") print("Copy " + str(previous) + " over the private operator config before up.") return 0 pending(root) root, state, old_spec, old_profile = kit.workspace(root) expected_paths = {"schema": "durkahelper.operator-paths.v1", "paths": {name: str(path) for name, path in paths.items()}} if kit.load(root / "operator-paths.json") != expected_paths: raise Error("configure cannot change operator paths; restore the original paths") new_profile = value["profile"] if (any(old_profile[name] != new_profile[name] for name in ("schema", "platform", "allow_amd64_emulation")) or any(old_profile["packmate"][name] != new_profile["packmate"][name] for name in ("mode", "pcap_file", "interface")) or new_profile["packmate"]["mode"] != "FILE"): raise Error("configure changes event settings only; platform, runtime and capture layout require a new deployment") if not credentials_match(root, state, old_spec, old_profile, value["credentials"]): raise Error("configure cannot rotate credentials; restore their original values") old_runtime = kit.check_build_receipt(root, old_spec) receipt = kit.load(root / "build-receipt.json") stopped(state) kit.check_build_receipt(root, old_spec, kit.image_preflight(old_runtime, old_profile)) spec = kit.compose_spec(new_profile, value["credentials"], state["project"], kit.shared.image_map(ROOT / "config/integration-images.lock.json")) runtime = kit.runtime_spec(spec, receipt["images"]) deployment_model = kit.model(spec, new_profile) runtime_model = kit.model(runtime, new_profile) farm = new_profile["farm"] 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=value["credentials"]["farm_password"], TIMEZONE="UTC", **farm["protocol_settings"]) candidate = {"config/farm.py": ("CONFIG = " + repr(farm_config) + "\n").encode("utf-8"), "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: "' + value["credentials"]["neo_key"] + '"\nfarm:\n url: "' + kit.neo_farm_url(new_profile) + '"\n password: "' + value["credentials"]["farm_password"] + '"\n').encode("ascii"), "config/packmate.properties": kit.properties(new_profile, value["credentials"]).encode("ascii"), "profile.json": kit.shared.canonical(new_profile), "compose.json": kit.shared.canonical(spec), "model.json": kit.shared.canonical(deployment_model), "policy.json": kit.shared.canonical(kit.policy(new_profile, deployment_model)), "runtime-compose.json": kit.shared.canonical(runtime), "runtime-model.json": kit.shared.canonical(runtime_model), "runtime-policy.json": kit.shared.canonical(kit.policy(new_profile, runtime_model)), "build-receipt.json": kit.shared.canonical({"schema": "durkahelper.deployment-build.v2", "images": receipt["images"], "compose_sha256": checksum(kit.shared.canonical(spec)), "runtime_sha256": checksum(kit.shared.canonical(runtime))})} originals = {name: kit.read(root / name) for name in CONFIG_FILES} for name, payload in candidate.items(): if name in state["files"]: state["files"][name] = checksum(payload) candidate["deployment.json"] = kit.shared.canonical(state) backup = root / "configuration-backups" / secrets.token_hex(8) private_directory(backup) for name, data in originals.items(): kit.shared.write(backup / name, data) old_operator = dict(value, profile=old_profile) kit.shared.write(backup / "operator.json", kit.shared.canonical(old_operator)) journal = {"schema": "durkahelper.operator-configuration.v1", "phase": "pending", "backup": backup.relative_to(root).as_posix(), "files": {name: {"before": checksum(originals[name]), "after": checksum(candidate[name])} for name in CONFIG_FILES}} journal_path = root / CONFIG_JOURNAL if journal_path.exists(): replace_file(journal_path, kit.shared.canonical(journal), checksum(kit.read(journal_path))) else: kit.shared.write(journal_path, kit.shared.canonical(journal)) try: for name in CONFIG_FILES: stopped(state) replace_file(root / name, candidate[name], checksum(originals[name])) kit.workspace(root) kit.check_build_receipt(root, spec) before = kit.read(journal_path) journal["phase"] = "committed" replace_file(journal_path, kit.shared.canonical(journal), checksum(before)) except (Exception, KeyboardInterrupt): configuration_rollback(root) raise print("Event settings updated. Data and cached images retained; no downloads or rebuild required.") print("Previous configuration: " + str(backup / "operator.json")) print("Run python3 durka.py up, then worker and submit when needed.") return 0 def empty_capture(root, profile): path = root / "pcaps" / profile["packmate"]["pcap_file"] if path.is_symlink(): raise Error("capture path cannot be a link") if not path.exists(): kit.shared.write(path, struct.pack("