Files
attack-defense-platform/receiver/challenges/Phew.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

201 lines
8.5 KiB
Python

from .Challenge import Challenge
import subprocess
import time
import re
import os
class Phew(Challenge):
flag_location = 'flags/phew.txt'
history_location = 'history/phew.txt'
_CONTAINER = os.environ.get("CHALLENGE_CONTAINER_PHEW", "phew_container")
_SERVICE_CMD = ["docker", "exec", "-i", _CONTAINER, "python3", "/home/ctfuser/chall/src/chall.py"]
_HEX_RE = re.compile(r'^[0-9a-fA-F]+$')
def _read_container_flag(self) -> str:
# NB: a timeout is mandatory here. `docker exec` against a container
# whose process table is saturated (accumulated chall.py zombies) can
# block forever and take the whole SLA check loop down with it.
try:
out = subprocess.run(["docker", "exec", self._CONTAINER, "cat", "/flag.txt"],
capture_output=True, text=True, timeout=30)
except subprocess.TimeoutExpired:
raise TimeoutError("docker exec cat /flag.txt timed out (container overloaded?)")
if out.returncode != 0 or not out.stdout.strip():
raise FileNotFoundError("Flag not found in container (/flag.txt)")
return out.stdout.strip()
def _spawn(self):
return subprocess.Popen(
self._SERVICE_CMD,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=0,
)
def _read_until(self, proc, token, timeout=5.0, max_bytes=1_000_000):
start = time.time()
buf = []
r = proc.stdout.read
while True:
if time.time() - start > timeout:
tail = ''.join(buf)[-500:]
raise TimeoutError(f"Timeout waiting for '{token}'. Got so far:\n{tail}")
ch = r(1)
if ch == "" and proc.poll() is not None:
raise RuntimeError(f"Process ended while waiting for '{token}'. Output:\n{''.join(buf)}")
buf.append(ch)
if len(buf) > max_bytes:
raise RuntimeError("Exceeded max read size")
if token in "".join(buf):
return "".join(buf)
def _send_line(self, proc, s: str):
proc.stdin.write(s + "\n")
proc.stdin.flush()
def _expect_hex_field(self, text: str, label: str) -> str:
m = re.search(rf"{re.escape(label)}\s*:\s*([0-9a-fA-F]+)", text)
assert m, f"Missing '{label}' in output. Tail:\n{text[-400:]}"
hx = m.group(1)
assert self._HEX_RE.match(hx), f"{label} is not hex"
return hx
def distribute(self, flag):
try:
os.makedirs(os.path.dirname(self.flag_location), exist_ok=True)
with open(self.flag_location, 'w') as f:
f.write(flag)
os.makedirs(os.path.dirname(self.history_location), exist_ok=True)
with open(self.history_location, 'a') as f:
f.write(flag + '\n')
self.logger.info(f'Flag {flag} written to {self.flag_location}')
return True
except Exception as e:
self.logger.error(f'Could not write flag to {self.flag_location}: {e}')
return False
def check(self):
try:
# parity check
with open(self.flag_location, 'r') as f:
host_flag = f.read().strip()
container_flag = self._read_container_flag()
assert host_flag == container_flag, 'Flag mismatch between host and container'
self.logger.info('[ok] flag parity (phew)')
def run_encrypt_once(pt_hex: str) -> str:
proc = self._spawn()
try:
self._read_until(proc, "> ", timeout=10.0)
self._send_line(proc, "1")
self._read_until(proc, "pt (hex)", timeout=3.0)
self._read_until(proc, "> ", timeout=3.0)
self._send_line(proc, pt_hex)
out = self._read_until(proc, "> ", timeout=5.0)
ct_hex = self._expect_hex_field(out, "ct")
self._send_line(proc, "9")
try:
proc.wait(timeout=2.0)
except subprocess.TimeoutExpired:
proc.kill()
raise AssertionError("Program did not exit after exit command (encrypt)")
return ct_hex
finally:
if proc.poll() is None:
proc.kill()
def run_decrypt_once(ct_hex: str) -> str:
proc = self._spawn()
try:
self._read_until(proc, "> ", timeout=10.0)
self._send_line(proc, "3")
self._read_until(proc, "ct (hex)", timeout=3.0)
self._read_until(proc, "> ", timeout=3.0)
self._send_line(proc, ct_hex)
out = self._read_until(proc, "> ", timeout=5.0)
pt_hex = self._expect_hex_field(out, "pt")
self._send_line(proc, "9")
try:
proc.wait(timeout=2.0)
except subprocess.TimeoutExpired:
proc.kill()
raise AssertionError("Program did not exit after exit command (decrypt)")
return pt_hex
finally:
if proc.poll() is None:
proc.kill()
def run_keyct_once() -> str:
proc = self._spawn()
try:
self._read_until(proc, "> ", timeout=10.0)
self._send_line(proc, "4")
out = self._read_until(proc, "> ", timeout=5.0)
ct_hex = self._expect_hex_field(out, "ct")
self._send_line(proc, "9")
try:
proc.wait(timeout=2.0)
except subprocess.TimeoutExpired:
proc.kill()
raise AssertionError("Program did not exit after exit command (keyct)")
return ct_hex
finally:
if proc.poll() is None:
proc.kill()
def run_bingo_reject_wrong_key():
wrong_key_hex = "00" * 66
proc = self._spawn()
try:
self._read_until(proc, "> ", timeout=10.0)
self._send_line(proc, "2")
self._read_until(proc, "key (hex)", timeout=3.0)
self._read_until(proc, "> ", timeout=3.0)
self._send_line(proc, wrong_key_hex)
out = self._read_until(proc, "> ", timeout=5.0)
assert "nope" in out.lower(), f"bingo did not reject wrong key; got:\n{out[-300:]}"
self._send_line(proc, "9")
try:
proc.wait(timeout=2.0)
except subprocess.TimeoutExpired:
proc.kill()
raise AssertionError("Program did not exit after exit command (bingo)")
finally:
if proc.poll() is None:
proc.kill()
ct1 = run_encrypt_once("414243444546")
assert ct1 and self._HEX_RE.match(ct1), "encrypt(1) did not return hex"
self.logger.info("[ok] encrypt produced hex")
pt_back = run_decrypt_once(ct1)
assert pt_back.strip() != "", "decrypt returned empty output"
assert self._HEX_RE.match(pt_back), "decrypt(3) did not return hex"
self.logger.info("[ok] decrypt produced hex (custom mapping accepted)")
pt_same = "01" * 8
ct_a = run_encrypt_once(pt_same)
ct_b = run_encrypt_once(pt_same)
assert ct_a.lower() != ct_b.lower(), "Encryption appears deterministic for same plaintext"
self.logger.info("[ok] encrypt randomness")
k1 = run_keyct_once()
k2 = run_keyct_once()
assert k1.lower() != k2.lower(), "key? ciphertexts reused randomness"
self.logger.info("[ok] key? randomness")
# run_bingo_reject_wrong_key()
# self.logger.info("[ok] bingo rejects wrong key")
return True
except Exception as e:
self.logger.error(f'Could not check phew: {e}')
return False