Files
attack-defense-platform/panel/gen_receiver_services.py
T
MythEclipse d4c741926d fix: make challenge toggle actually work end-to-end (5 root-cause bugs)
Found by testing a real enable/disable cycle (art, fjb, gift-card):

1. compose_gen always swapped build->image, so a never-built challenge
   produced 'pull access denied for services-<name>'. Now it only reuses
   the image when it exists locally, otherwise keeps build: so
   'docker compose up --build' builds it.
2. Canonical templates use 'build: context: .' (written for the shared
   services/ tree). In the per-team compose that resolves to the team dir
   which has no Dockerfile -> 'failed to read dockerfile'. The renderer
   now rewrites the main service's context to ./<name>.
3. Teams created before the XVI/XVII import had no xvi/xvii subpackages
   under their local challenges/ dir, so the regenerated receiver main.py
   crash-looped on import. gen_receiver_main now mirrors ALL shared
   checkers (native + xvi + xvii) into every team receiver on each sync.
4. systemd Environment= keys can't contain hyphens, so
   CHALLENGE_PORT_GIFT-CARD was silently dropped. Keys are now
   normalized to underscores on both the writer and reader side.
5. Several checkers called 'docker exec' with no timeout; against a
   container with accumulated chall.py zombies that blocks forever and
   stalls the whole SLA loop. Added mandatory timeouts (Phew, Sheesh,
   Carbeat, Poke, Warmup).

Also: enabling a challenge now copies its source tree into each team's
services/ dir (team dirs only held challenges enabled at create_team
time), and the XVII checkers were rewritten to be protocol-aware
(gift-card/gift-voucher are socat TCP, not HTTP) with strict timeouts.
2026-09-25 15:36:09 +08:00

82 lines
3.1 KiB
Python

#!/usr/bin/env python3
"""Generate + (re)start per-team receiver systemd services.
Each team receiver becomes gemastik-receiver-teamN.service, independent of
the panel service. This fixes the bug where restarting gemastik-panel killed
all team receivers (they were child processes of the panel systemd cgroup).
"""
import json
import os
import subprocess
import sys
from pathlib import Path
TEAMS_DIR = Path("/opt/gemastik18-final/teams")
RECEIVER_VENV = "/opt/gemastik18-final/receiver/.venv/bin/python"
UNIT_DIR = Path("/etc/systemd/system")
def write_unit(idx: int, st: dict):
port = st["ports"]["receiver"]
recv_dir = TEAMS_DIR / f"team{idx}" / "receiver"
env = {}
# ports/containers for challenge classes.
# NOTE: systemd Environment= keys must be [A-Za-z0-9_]+ — a hyphen in the
# challenge name (gift-card) would make systemd silently drop the line, so
# normalize the name to underscores here. main.py looks up the same key.
for ch in st["ports"]:
if ch in ("receiver", "panel"):
continue
key = ch.upper().replace("-", "_")
env[f"CHALLENGE_PORT_{key}"] = str(st["ports"][ch]["chall"])
env[f"CHALLENGE_CONTAINER_{key}"] = f"{ch}_container_team{idx}"
# SSH passwords: checker Challenge.credentials() reads PASSWORD_<self.port>
# where self.port is the team challenge port.
pwd = st.get("chall_passwords", {}).get(ch)
if pwd:
env[f"PASSWORD_{st['ports'][ch]['chall']}"] = pwd
env["COMPOSE_LOCATION"] = str(TEAMS_DIR / f"team{idx}" / "services" / "docker-compose.yml")
env_lines = "\n".join(f'Environment="{k}={v}"' for k, v in env.items())
unit = f"""[Unit]
Description=Gemastik A/D receiver for team {idx}
After=docker.service
Wants=docker.service
[Service]
Type=simple
WorkingDirectory={recv_dir}
EnvironmentFile={recv_dir}/.env
{env_lines}
ExecStart={RECEIVER_VENV} -m uvicorn main:app --host 0.0.0.0 --port {port}
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
"""
(UNIT_DIR / f"gemastik-receiver-team{idx}.service").write_text(unit)
def main():
action = sys.argv[1] if len(sys.argv) > 1 else "start"
# Regenerate receiver main.py for existing teams from the registry
try:
from gen_receiver_main import sync_team_receivers
sync_team_receivers()
except Exception as e:
print(f"WARN: receiver main.py regen failed: {e}")
for d in sorted(TEAMS_DIR.glob("team*")):
sf = d / "state.json"
if not sf.exists():
continue
st = json.loads(sf.read_text())
idx = st["index"]
write_unit(idx, st)
subprocess.run(["systemctl", "daemon-reload"], check=False)
subprocess.run(["systemctl", "enable", f"gemastik-receiver-team{idx}.service"], check=False)
if action == "stop":
subprocess.run(["systemctl", "stop", f"gemastik-receiver-team{idx}.service"], check=False)
else:
subprocess.run(["systemctl", "restart", f"gemastik-receiver-team{idx}.service"], check=False)
print(f"gemastik-receiver-team{idx}: {action} (port {st['ports']['receiver']})")
if __name__ == "__main__":
main()