Files
attack-defense-platform/panel/gen_receiver_services.py
T
MythEclipse c6fd9ec268 feat: challenge registry-driven platform + XVI/XVII imports + admin toggle + domain rename
- Rename repo/domain: attack-defense-platform / attackdefense.imrnes.team (all refs replaced)
- challenge_registry.json: single source of truth (28 challs across gemastik18/xvi/xvii)
- teams.py: registry-driven CHALLENGES, set_challenge_enabled, sync_challenge_runtime
  (apply enable/disable to live teams: build/up or stop/remove + receiver restart)
- compose_gen.py: render per-team compose from canonical per-challenge templates
  (image reuse, per-team ports 30xxx, flag mounts, passwords)
- gen_canonical_composes.py: canonical docker-compose.yml for all services
- import_new_challenges.py: import XVI/XVII services + EOL base image fixes
  (debian:buster→bookworm, node:14→20, python:3.7-slim→3.11)
- receiver: xvi package (10 checkers) + xvii package (12 generic checkers),
  Challenge base reads PASSWORD_<team_port> from env; gen_receiver_main.py
  generates per-team main.py from registry
- main.py: /api/challenges returns full registry; PATCH /api/challenges/<name>
  toggles enabled + applies to live teams
- index.html: 🏗️ Challenge Manager tab (toggle per challenge, grouped by set)
- SLA bonus now dynamic (all enabled challenges, not hardcoded 6)
2026-09-25 14:04:33 +08:00

78 lines
2.9 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
for ch in st["ports"]:
if ch in ("receiver", "panel"):
continue
env[f"CHALLENGE_PORT_{ch.upper()}"] = str(st["ports"][ch]["chall"])
env[f"CHALLENGE_CONTAINER_{ch.upper()}"] = 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()