Automation is what turns a misc challenge from a grind into a solved challenge. The pattern is always the same: solve one round by hand, capture the exact request and response, write a loop that does that round, and add retries and logging so a hiccup does not kill a long run. This sub-skill covers the authorized methodology for scripting misc services, with reusable templates for sessions, retries, and parallel workers. Scope is CTF competitions, lab services, and systems you have explicit permission to test.
Quick Workflow
- Solve one round by hand and record the raw request and response.
- Identify the state carrier (cookie, token, or round counter) and keep it in a session object.
- Write the single round solver and test it for five rounds.
- Wrap it in a loop with retries, backoff, and logging.
- Add a flag check on every response so the run stops the moment it wins.
- Parallelize only if the rules allow it and the server tolerates it, otherwise stay sequential.
- Run the full solver in one process from start to flag.
- Save the log and the final script for the writeup.
1. Session handling and a robust request loop
A session object keeps cookies and connection reuse across rounds, and a retry wrapper keeps one dropped packet from ending the run.
#!/usr/bin/env python3
"""Robust session loop template for a misc service challenge."""
import re
import time
import requests
BASE = "http://chals.ctf:8000"
FLAG_RE = re.compile(r"[A-Za-z0-9_]+\{[^}]{3,120}\}")
session = requests.Session()
session.headers.update({"User-Agent": "ctf-solver/1.0"})
def get_with_retry(url: str, tries: int = 5) -> requests.Response:
last_error = None
for attempt in range(tries):
try:
resp = session.get(url, timeout=10)
if resp.status_code == 200:
return resp
last_error = f"HTTP {resp.status_code}"
except requests.RequestException as exc:
last_error = str(exc)
time.sleep(0.5 * (2 ** attempt)) # 0.5s, 1s, 2s, 4s, 8s
raise RuntimeError(f"GET {url} failed after {tries} tries: {last_error}")
def post_with_retry(url: str, data: dict, tries: int = 5) -> requests.Response:
last_error = None
for attempt in range(tries):
try:
resp = session.post(url, data=data, timeout=10)
if resp.status_code == 200:
return resp
last_error = f"HTTP {resp.status_code}"
except requests.RequestException as exc:
last_error = str(exc)
time.sleep(0.5 * (2 ** attempt))
raise RuntimeError(f"POST {url} failed after {tries} tries: {last_error}")
# Capture the hand solved round first, so the script matches reality
curl -s -c cookies.txt http://chals.ctf:8000/start | head -c 500
curl -s -b cookies.txt http://chals.ctf:8000/challenge | head -c 500
curl -s -b cookies.txt -X POST http://chals.ctf:8000/answer -d 'answer=42' | head -c 500
2. Parsing changing output and answering rounds
Challenge output changes shape between stages, so parse defensively and log the raw text whenever parsing fails.
#!/usr/bin/env python3
"""Answer loop that parses each round, logs failures, and stops on a flag."""
import json
import re
import time
import requests
BASE = "http://chals.ctf:8000"
FLAG_RE = re.compile(r"[A-Za-z0-9_]+\{[^}]{3,120}\}")
session = requests.Session()
def solve_round(text: str) -> str:
"""Derive the answer from the current round text. Replace this
logic with the real rule for the challenge, for example arithmetic,
a hash, a sequence, or a lookup."""
numbers = re.findall(r"-?\d+", text)
if len(numbers) >= 2:
return str(int(numbers[0]) + int(numbers[1]))
raise ValueError(f"cannot parse round: {text[:200]!r}")
session.get(BASE + "/start", timeout=10)
for round_no in range(1, 1001):
resp = session.get(BASE + "/challenge", timeout=10)
match = FLAG_RE.search(resp.text)
if match:
print("FLAG:", match.group(0))
break
try:
answer = solve_round(resp.text)
except ValueError as exc:
print(f"round {round_no} parse failure: {exc}")
with open("failed_rounds.log", "a") as log:
log.write(f"round {round_no}: {resp.text[:1000]}\n")
break
resp = session.post(BASE + "/answer", data={"answer": answer}, timeout=10)
if resp.status_code != 200:
print(f"round {round_no} submit failed: {resp.status_code}")
break
time.sleep(0.05) # be polite to shared CTF infrastructure
else:
print("finished 1000 rounds with no flag, re-read the challenge")
# Watch a long run without blocking the terminal
nohup python3 solver.py > solver.log 2>&1 &
tail -f solver.log
grep -E "FLAG|failed" solver.log | tail -20
3. Parallel workers within the rules
Some challenges allow multiple connections, and a small worker pool can cut a long grind down sharply. Check the rules first, many challenges forbid concurrency or count it as abuse.
#!/usr/bin/env python3
"""Worker pool template for independent misc tasks, such as checking
a list of candidate answers or fetching many challenge pages.
Only use this when the challenge rules allow parallel requests and
each task is independent (no shared session state between workers).
"""
import concurrent.futures
import re
import requests
FLAG_RE = re.compile(r"[A-Za-z0-9_]+\{[^}]{3,120}\}")
CANDIDATES = [f"candidate-{i}" for i in range(1000)]
def check(candidate: str) -> str | None:
try:
resp = requests.get(
"http://chals.ctf:8000/check",
params={"value": candidate}, timeout=10)
except requests.RequestException:
return None
match = FLAG_RE.search(resp.text)
return match.group(0) if match else None
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
for result in pool.map(check, CANDIDATES):
if result:
print("FLAG:", result)
pool.shutdown(wait=False, cancel_futures=True)
break
Edge cases
- The server sets a new token per round. Re-read the token from each response instead of reusing the first one.
- The challenge counts a wrong answer as a reset. Validate the answer logic on hand solved rounds before letting the loop run unattended.
- Rate limiting returns 429. Back off, sleep longer, and resume from the last logged round instead of restarting.
- The session expires mid run. Detect a login redirect, re-run the start step, and resume, keeping a checkpoint of progress.
- Parallel workers corrupt shared state. Give each worker its own session, or keep the run sequential when rounds depend on each other.
- Output parsing breaks on a new stage. Log the raw text, stop cleanly, and add a parser branch for the new stage before resuming.
Escalation
- The loop runs but never wins. Print ten raw rounds and solve them by hand to check whether the answer logic is actually correct.
- The server is too slow for a sequential run. Batch where the API allows, parallelize only within the rules, or precompute answers offline and submit in a tight loop.
- Retries hide a real bug. If retries fire often, inspect the failure pattern, a systematic 500 or redirect usually means the request shape changed, not the network.
- The challenge changes after N rounds. Treat each stage as a new solver, log the transition point, and write a parser per stage.
Key references
- Python requests documentation: https://docs.python-requests.org/
- Python concurrent futures documentation: https://docs.python.org/3/library/concurrent.futures.html
- MITRE ATT&CK T1071 (Application Layer Protocol) for service interaction patterns.
- CWE-400 (Uncontrolled Resource Consumption) for rate limit and retry design.
- CTFtime writeup archive for automation patterns: https://ctftime.org/
