A comprehensive analysis of what we learned building autonomous AI agents for CTF challenges across three major challenge categories: Hac-Man, Kanto Region, and Turing's Labyrinth.
Challenges Solved: 14/14 fully documented
Total Points: 2,675+
Agent Versions: 30+ iterations across all categories
Time Investment: ~12 hours total
Success Rate: 93% (14 solved, 1 locked)
Pattern: Single agent with pluggable solvers per challenge type
agent/
├── agent.py # Main entry, routing
├── solvers/
│ ├── race_condition.py
│ ├── sat_solver.py
│ ├── ecdsa_nonce.py
│ ├── ssrf.py
│ └── timing_attack.py
└── utils/
├── mcp_client.py
└── submit.py
Why it works:
- Per-solver isolation makes debugging easy
- Can test solvers independently
- Graceful degradation if one fails
- Shared utilities reduce code duplication
Anti-pattern: Monolithic agent trying to handle everything in one file
Problem: Some challenges require files that MCP can't fetch (binary exploits, obfuscated scripts)
Solution:
- Human downloads files from challenge page
- Drops into
agent/attachments/ - Dockerfile bakes files into image
- Agent loads from bundle at runtime
Example: Achilles' Heel binary exploitation required the exact binary served on the port, but the port was raw TCP (not HTTP). Bundle-offline solved this.
Pattern: Deterministic solvers first, LLM fallback for unknown/failed cases
Why:
- Deterministic code is faster (ms vs seconds)
- No token cost for known patterns
- Predictable behavior for debugging
- LLM handles edge cases gracefully
Bounds for LLM fallback:
- Max steps: 14
- Wall clock timeout: 5 minutes
- Submission quota: 2 per run
- Tool vocabulary: Limited to essential operations
Anti-pattern: LLM-first approach wastes tokens and time on solvable problems
Problem: Field names and API structures kept changing between challenges, requiring v4/v5/v6 rebuilds for single-field fixes.
Solution: Hybrid deterministic + LLM fallback architecture
# Fast path: Deterministic field extraction
for field in ("crew", "ashore", "men", "register"):
if field in response:
names = response[field]
break
# Adaptive path: LLM fallback when deterministic fails
if not names:
names = llm_extract_json(
"Extract crew names from this shore register",
response.text,
["name1", "name2"]
)Results:
- [SOLVED] No rebuild needed for API variations
- [SOLVED] 2-5 second overhead only when deterministic fails
- [SOLVED] Scylla/Aeolus/Lotus all got LLM fallbacks in v10
- [SOLVED] Bow of Odysseus uses LLM to parse protocol spec AND generate implementation
When to use:
- Field names unknown at build time
- Protocol specs only available at runtime
- API structure varies between challenges
- Code generation needed (e.g., binary protocol clients)
When NOT to use:
- Known, stable APIs (waste of tokens)
- Time-critical operations (deterministic is faster)
- Simple transformations (overkill)
Learning: Building against live CTF challenges accelerated development far more than building against synthetic test cases.
Process:
- Attempt challenge with agent v1
- Read logs to understand failure
- Fix specific issue
- Rebuild and retry
- Repeat until solved
Typical iteration cycle: 15-30 minutes per version
Pattern: Tag every working version
docker build -t kanto-agent:v13 .
docker save kanto-agent:v13 > kanto-agent-v13.tarWhy:
- Can roll back to last working version
- Easy to diff what changed between versions
- Upload history for auditing
- Disk is cheap; debugging time is expensive
Pattern: Structured logging with request/response capture
logging.info(f"[SOLVER] Attempting {challenge_name}")
logging.debug(f"[API] Request: {method} {endpoint}")
logging.debug(f"[API] Body: {json.dumps(body)}")
logging.debug(f"[API] Response: {response.text}")
logging.info(f"[RESULT] Flag: {flag}")Why:
- Remote debugging is impossible without logs
- Response bodies often contain hints
- Error messages reveal API expectations
- Timing information aids optimization
Key Insight: "Concurrency" means REAL parallelism, not sequential requests
# WRONG - Sequential (no race)
for _ in range(20):
requests.post("/api/withdraw")
# CORRECT - Concurrent (exploits TOCTOU)
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
futures = [executor.submit(requests.post, "/api/withdraw") for _ in range(20)]Lesson: Async/threading isn't optional for race conditions; it's the exploit
Key Insight: Use battle-tested solvers, don't reinvent the wheel
Anti-pattern: Implementing DPLL algorithm from scratch
Correct approach: Use pycosat (optimized C library)
Gotchas:
- 0-indexed vs 1-indexed clauses (auto-detect)
- Response format must be wrapped:
{"assignment": [...]} - Off-by-one in output array
Lesson: For NP-complete problems, leverage existing optimized implementations
Key Insight: String matching is dangerous
# WRONG - "p256" matches "secp256k1"!
if "p256" in curve_name:
return NIST256p # Incorrect for secp256k1
# CORRECT - Check longest match first
if "256k1" in curve_name:
return SECP256k1
elif "256r1" in curve_name or "p256" in curve_name:
return NIST256pLesson: Substring matching needs careful ordering; prefer exact matches
Key Insight: API endpoint names aren't consistent across hosts
- Lobby:
/api/staff/{id}(IDs from 101+) - Mainframe:
/api/records/{id}(IDs from 1+)
Don't assume similar hosts use identical schemas!
Lesson: Verify API structure per host, don't generalize from one example
Key Insight: Network timing attacks work, but require statistics
Single measurement: Unreliable (network jitter)
Median of 10 samples: Robust to outliers
samples = []
for _ in range(10):
start = time.time()
response = requests.post("/verify", json={"token": guess})
samples.append(time.time() - start)
timing = statistics.median(samples) # Not mean!Lesson: Median filters noise better than mean for timing side-channels
Key Insight: LLM creativity beats exhaustive enumeration for word puzzles
Scripted list: 100 attempts, all failed
LLM-generated: 30 attempts, success on #10
Why: LLM found compound camelCase variation (WakaWaka) that scripted list missed
Lesson: For creative/linguistic challenges, LLM generation is cost-effective
Bad assumption: All endpoints use the same authentication method
Reality: Silph Co. had different auth per host (internal key vs vault token)
Bad assumption: Field names are standard across endpoints
Reality: Indigo League used "message" for badges but "trial_message" for champion
Lesson: Read every response, extract robustly, never hardcode field names
Mistake: Multi-stage Docker build for size optimization in v1
Reality: Didn't need it until image exceeded limits (never happened)
Cost: Debugging was harder (build cache invalidation)
Lesson: Build straightforward images first; optimize only when necessary
Mistake: Building generic "crypto solver" framework anticipating many crypto challenges
Reality: Each crypto challenge was unique (timing attack, obfuscated python, transform cascade)
Cost: Framework code was never reused
Lesson: YAGNI (You Aren't Gonna Need It) - solve the challenge at hand
Mistake: Guessing flag formats instead of reading hint penalty costs
Reality: Pythia's Whisper hints cost 38 points each; could have solved without hints
Lesson: Read all available information before spending resources
Mistake: Catching all exceptions and continuing
Reality: Masked bugs that could have been fixed quickly
# BAD
try:
result = solve_challenge()
except:
pass # Silent failure!
# GOOD
try:
result = solve_challenge()
except Exception as e:
logging.error(f"Solver failed: {e}")
raise # Or handle specificallyLesson: Fail loudly during development; graceful degradation in production
Pattern: Multi-stage build when build dependencies ≠ runtime dependencies
# Stage 1: Build (needs gcc)
FROM python:3.11-slim as builder
RUN apt-get install gcc
RUN pip wheel pycosat
# Stage 2: Runtime (only binutils)
FROM python:3.11-slim
COPY --from=builder /wheels /wheels
RUN pip install /wheels/*Result: 415MB → 172MB for Kanto agent
When to use: When build-time tools (gcc, make, g++) aren't needed at runtime
Problem: 100MB log file in memory
Solution: Stream and process line-by-line
# BAD
log_text = requests.get("/access.log").text # 100MB in memory!
for line in log_text.split('\n'):
process(line)
# GOOD
response = requests.get("/access.log", stream=True)
for line in response.iter_lines(decode_unicode=True):
process(line)Lesson: Always stream large responses
Hierarchy:
- Deterministic code (free, instant)
- Small model (gemma, cheap, fast)
- Medium model (qwen, balanced)
- Large model (llama-3.1-70b, expensive, slow)
Never default to large model - use only when complexity demands it
Lesson: Right-size model to task complexity
Pattern: Validate all external inputs (API responses, environment variables)
def parse_challenge_id(env_value):
"""
HAL_CHALLENGE_ID must be integer, not string
"""
if not env_value:
return None
try:
return int(env_value)
except ValueError:
logging.error(f"Invalid challenge ID: {env_value}")
return NoneLesson: Never trust external data, even from "trusted" sources
Problem: LLM copilot could hallucinate 100 flags and waste submission quota
Solution: Gate submissions through validation
def propose_flag(candidate):
# Validate format
if not re.match(r'HALCTF\{[^}]+\}', candidate):
return False
# Deduplicate
if candidate in submitted_flags:
return False
# Enforce limit
if len(submitted_flags) >= MAX_SUBMITS:
return False
# Actually submit
return submit_flag(candidate)Lesson: Never give LLMs direct access to rate-limited resources
Pattern: Use list arguments, not shell strings
# VULNERABLE
subprocess.run(f"ping {user_input}", shell=True)
# SAFE
subprocess.run(["ping", user_input])Lesson: Even in CTF agents, practice secure coding (teaches good habits)
Pattern: Compare working vs failing runs
# Extract API calls from successful run
grep "\[API\]" run_success.log > success_api.txt
# Extract API calls from failed run
grep "\[API\]" run_fail.log > fail_api.txt
# Diff them
diff success_api.txt fail_api.txtFrequently revealed: Missing headers, wrong endpoints, malformed bodies
Pattern: Start with minimal request, add complexity incrementally
# Step 1: Can we reach the endpoint?
response = requests.get(f"{target}/api/records/1")
print(response.status_code)
# Step 2: What headers are required?
response = requests.get(f"{target}/api/records/1",
headers={"X-Silph-Key": "..."})
print(response.status_code)
# Step 3: What about body format?
# ... continueLesson: Binary search for the minimal working request
Pattern: Capture working manual solution, then automate
# Manual exploration
curl -X POST http://target/api/withdraw
curl -X POST http://target/api/withdraw
curl http://target/api/storage
# -> Got flag!
# Now automate exact same sequence
requests.post(f"{target}/api/withdraw")
requests.post(f"{target}/api/withdraw")
requests.get(f"{target}/api/storage")Lesson: Prove exploit works manually before automating
Human responsibilities:
- High-level strategy (which challenges to attempt)
- Downloading unreachable files (bundle-offline pattern)
- Reading challenge hints and translating to solver specs
- Approving risky operations (submission attempts)
AI agent responsibilities:
- Executing deterministic solvers
- Making API calls with correct formatting
- Retrying with backoff
- Logging for post-mortem analysis
Collaborative tasks:
- Debugging (human reads logs, AI proposes fixes)
- Optimization (human identifies bottleneck, AI refactors)
- Testing (AI runs tests, human interprets failures)
Red flags:
- Agent repeating the same failed approach
- API calls clearly malformed (from logs)
- Solver logic has obvious bug
- Approaching quota limits without progress
Action: Stop agent, fix code, rebuild, retry
Lesson: Autonomous doesn't mean unsupervised; monitor and intervene
Strategy: Scan environment variables, test simple exploits, grab easy points
Why: Early points build confidence and leaderboard position
Quick wins in our run:
- BONUS_FLAG (instant)
- Icarus Uplink (20 pts, 5 minutes)
- The Haystack (30 pts, 10 minutes)
- Hac-Man (50 pts, 15 minutes)
Strategy: Work on multiple agents simultaneously (separate directories)
How:
# Terminal 1
cd hacman-agent/
# Iterate on Hac-Man
# Terminal 2
cd kanto-agent/
# Iterate on Kanto challenges
# Terminal 3
cd labyrinth-agent/
# Iterate on LabyrinthBenefit: Blocked on one challenge? Switch to another.
Pattern: 3-attempt rule
- First attempt fails → Read logs, fix obvious issue
- Second attempt fails → Try alternative approach
- Third attempt fails → Move to different challenge
Reasoning: Diminishing returns; other challenges might be easier
We skipped: The Exchange (modem protocol) - would have taken hours
Pattern: Every successful solve gets a version tag
docker build -t hacman-agent:v7 . # Working version
docker save hacman-agent:v7 > hacman-agent-v7.tarWhy:
- Can submit last working version if new attempt breaks
- Easy to see progression (v1 → v7)
- Upload history for post-CTF analysis
Hac-Man (LLM-heavy):
- Phase 1: Scripted (0 tokens)
- Phase 2: LLM generation (~2,000 tokens)
- Phase 3: Conversational (reserved, not used)
Kanto (mostly deterministic):
- Bill's PC: 0 tokens (pure race condition)
- Cerulean Cave: 0 tokens (pycosat)
- Indigo League: 0 tokens (ECDSA math)
- Silph Co.: 0 tokens (SSRF chain)
Labyrinth (mixed):
- 6 network challenges: 0 tokens (deterministic)
- 2 file-based challenges: ~1,000 tokens (analysis)
- LLM copilot fallback: ~5,000 tokens (bounded runs)
Total estimated: ~8,000 tokens across all challenges
Cost (at $0.50/1M tokens): < $0.01
Lesson: Deterministic solvers massively reduce token costs
| Challenge Category | Time Invested | Iterations |
|---|---|---|
| Hac-Man | 2 hours | 7 versions |
| Kanto Region | 4 hours | 13 versions |
| Turing's Labyrinth | 5 hours | 10 versions |
| Write-ups | 3 hours | - |
| Total | 14 hours | 30 versions |
Time per challenge: ~1 hour average (range: 15 min to 3 hours)
- Docker - Consistent environments, easy upload
- Python - Rapid prototyping, rich library ecosystem
- requests - HTTP client (used in every challenge)
- MCP SDK - Challenge discovery and submission
- pycosat - 3-SAT solving (Cerulean Cave)
- pwntools - Binary exploitation (Achilles' Heel)
- ecdsa library - ECDSA math (Indigo League)
- statistics.median - Timing attack noise reduction (Pythia)
- pyelftools - ELF binary parsing
- OpenAI SDK - LLM integration (for copilot and word generation)
- Burp Suite (all challenges scriptable)
- Ghidra (binary was bundled, no complex RE)
- sqlmap (no SQL injection challenges)
Lesson: Pack light; install specialized tools as needed
- Earlier parallelization - Could have tackled challenges simultaneously from day 1
- Upfront research - Reading all challenge hints before starting would have saved time
- Test-driven development - Writing tests for solvers before implementing
- Documented solver specs - Formal API contract per challenge
- Premature optimization - Multi-stage builds weren't needed initially
- Generic frameworks - Most "reusable" code was never reused
- Guess-and-check - More upfront analysis, fewer blind attempts
- Monolithic commits - Smaller, more atomic changes would aid debugging
- Unified agent harness - Single codebase with pluggable solvers (instead of separate agents per category)
- Solver registry - Dynamic routing based on challenge metadata
- Offline test suite - Mock challenges for regression testing
- Cost tracking - Log token usage per challenge for optimization
- Read the rules thoroughly - USER_ID print, heartbeat, submission format
- Test against dry-run environment - Validate agent can boot and submit
- Build modular from day 1 - Per-solver isolation pays dividends
- Set up logging infrastructure - You'll need it for debugging
- Start with easy challenges - Build momentum and confidence
- Don't chase locked challenges - Some aren't worth the time investment
- Version control religiously - Tag every working version
- Read logs between attempts - Don't spam retries blindly
- Deterministic solvers > LLM - Code is faster and cheaper
- Robust error handling - Remote debugging is hard; fail gracefully
- Structured logging - Request/response capture aids debugging
- Quota management - Never let LLM waste submission attempts
Autonomous agent ≠ Unsupervised agent
- Monitor progress via logs
- Intervene when stuck
- Human strategy + AI execution = winning combination
Building autonomous CTF agents is a collaboration between human insight and AI execution. The human provides:
- Strategic direction
- Domain knowledge
- Debugging intuition
- Resource management
The AI provides:
- Tireless execution
- Fast iteration
- Pattern matching
- Graceful degradation
The winning formula: Right-size the problem, right-size the solution, iterate rapidly.
Most important lesson: Don't overthink it. Start simple, iterate on real challenges, and let the failures guide your improvements.
- Multi-solver architecture (pluggable per challenge type)
- MCP integration (challenge discovery + submission)
- Environment variable scanning (quick wins)
- Structured logging (debugging)
- Graceful error handling (retries with backoff)
- Version tagging (rollback capability)
- Docker optimization (multi-stage if needed)
- LLM copilot (bounded, fallback only)
- Read challenge description thoroughly
- Check for existing libraries/tools
- Test approach manually first
- Implement deterministic solver
- Add robust error handling
- Log request/response pairs
- Test against live challenge
- Iterate based on failures
- USER_ID prints within 30 seconds
- Heartbeat logs every 60 seconds
- All solvers tested individually
- Docker image builds successfully
- Image size < 2.5GB
- Submission format validated
- Version tagged and saved
Total challenges documented: 14
Total points earned: 2,675+
Success rate: 93%
Time invested: 14 hours
Lessons learned: Priceless