"""Cybersecurity: find the one vulnerable line in a small web service and classify it.""" from typing import Any, Literal from pydantic import Field from ..core import Action, ProxyTask, Step CWES = {"CWE-89": "SQL injection", "CWE-22": "path traversal", "CWE-78": "OS command injection", "CWE-798": "hard-coded credentials", "CWE-862": "missing authorization"} SAFE = { "db.py": '''import sqlite3 DB = "app.db" def get_user(user_id): with sqlite3.connect(DB) as conn: return conn.execute("SELECT id, name, email FROM users WHERE id = ?", (user_id,)).fetchone() def search_orders(customer_id, status): with sqlite3.connect(DB) as conn: query = "SELECT id, total FROM orders WHERE customer_id = ? AND status = ?" return conn.execute(query, (customer_id, status)).fetchall() ''', "files.py": '''import os UPLOAD_ROOT = "/srv/uploads" def read_upload(name): path = os.path.realpath(os.path.join(UPLOAD_ROOT, name)) if not path.startswith(UPLOAD_ROOT + os.sep): raise PermissionError("outside upload root") with open(path, "rb") as fh: return fh.read() ''', "tools.py": '''import subprocess def ping(host): if not host.replace(".", "").replace("-", "").isalnum(): raise ValueError("bad host") return subprocess.run(["ping", "-c", "1", host], capture_output=True, text=True).stdout ''', "config.py": '''import os SECRET_KEY = os.environ["APP_SECRET_KEY"] DB_PASSWORD = os.environ.get("DB_PASSWORD", "") DEBUG = os.environ.get("DEBUG") == "1" ''', "routes.py": '''from auth import current_user, require_admin from db import get_user, search_orders @require_admin def admin_user(request, user_id): return get_user(user_id) def my_orders(request): user = current_user(request) return search_orders(user.id, request.args.get("status", "open")) def delete_account(request, user_id): user = current_user(request) if user.id != user_id and not user.is_admin: raise PermissionError("forbidden") return {"deleted": user_id} ''', } VULNS = [ ("db.py", "CWE-89", ''' query = "SELECT id, total FROM orders WHERE customer_id = ? AND status = ?" return conn.execute(query, (customer_id, status)).fetchall()''', ''' query = f"SELECT id, total FROM orders WHERE customer_id = {customer_id} AND status = '{status}'" return conn.execute(query).fetchall()''', 0), ("files.py", "CWE-22", ''' path = os.path.realpath(os.path.join(UPLOAD_ROOT, name)) if not path.startswith(UPLOAD_ROOT + os.sep): raise PermissionError("outside upload root")''', ''' path = os.path.join(UPLOAD_ROOT, name) if not os.path.exists(path): raise FileNotFoundError(name)''', 0), ("tools.py", "CWE-78", ''' if not host.replace(".", "").replace("-", "").isalnum(): raise ValueError("bad host") return subprocess.run(["ping", "-c", "1", host], capture_output=True, text=True).stdout''', ''' if not host: raise ValueError("bad host") return subprocess.run(f"ping -c 1 {host}", shell=True, capture_output=True, text=True).stdout''', 2), ("config.py", "CWE-798", '''DB_PASSWORD = os.environ.get("DB_PASSWORD", "")''', '''DB_PASSWORD = os.environ.get("DB_PASSWORD", "Spring2026!prod")''', 0), ("routes.py", "CWE-862", ''' user = current_user(request) if user.id != user_id and not user.is_admin: raise PermissionError("forbidden") return {"deleted": user_id}''', ''' user = current_user(request) log_event("delete_account", actor=user.id, target=user_id) return {"deleted": user_id}''', 2), ] class AuditAction(Action): tool: Literal["list", "open", "search", "report"] = Field( description="list files, open a file (path; shows line numbers), search all files for a substring " "(pattern), or report the finding (finding), which ends the episode.") path: str = Field(default="", description="File to open.") pattern: str = Field(default="", description="Substring to search for.") finding: dict[str, Any] = Field(default_factory=dict, description="{file, line, cwe}") class VulnHunt(ProxyTask): family = "security-audit" domain = "cybersecurity" Action = AuditAction max_steps = 10 finish_action = {"tool": "report", "finding": {}} def setup(self): r = self.rng fname, cwe, safe_text, bad_text, offset = VULNS[self.seed % len(VULNS)] self.files = {k: v for k, v in SAFE.items()} body = self.files[fname] assert safe_text in body # pad the vulnerable file with harmless helpers so the line number varies pad = "".join(f"\n\ndef _helper_{i}(value):\n return str(value).strip()\n" for i in range(r.randint(0, 3))) head, tail = body.split(safe_text) head = head.rstrip("\n").rsplit("\n\ndef ", 1) if len(head) == 2: head = head[0] + pad + "\n\ndef " + head[1] + "\n" else: head = head[0] + "\n" self.files[fname] = head + bad_text + tail lines = self.files[fname].split("\n") first = bad_text.split("\n")[offset] self.truth = (fname, lines.index(first) + 1, cwe) self.files["auth.py"] = '''def current_user(request): return request.session["user"] def require_admin(view): def wrapper(request, *args, **kwargs): if not current_user(request).is_admin: raise PermissionError("admin only") return view(request, *args, **kwargs) return wrapper ''' self.files["routes.py"] = self.files["routes.py"].replace( "from auth import current_user, require_admin", "from auth import current_user, require_admin\nfrom audit import log_event") if fname == "routes.py": lines = self.files[fname].split("\n") self.truth = (fname, lines.index(bad_text.split("\n")[offset]) + 1, cwe) def reset(self): cwes = "; ".join(f"{k} {v}" for k, v in CWES.items()) return {"output": f"Security review of a small Python web service. Exactly one line introduces a " f"vulnerability. Find it and report {{\"file\": ..., \"line\": <1-based line number>, " f"\"cwe\": ...}} using one of: {cwes}.", "steps_left": self.max_steps} def act(self, a): left = self.max_steps - self.steps if a.tool == "list": return Step({"output": "\n".join(sorted(self.files)), "steps_left": left}) if a.tool == "open": body = self.files.get(a.path.strip().lstrip("./")) if body is None: return Step({"output": f"No such file: {a.path}", "steps_left": left}) return Step({"output": "\n".join(f"{i:3d} {line}" for i, line in enumerate(body.split("\n"), 1)), "steps_left": left}) if a.tool == "search": if not a.pattern: return Step({"output": "search needs a pattern", "steps_left": left}) hits = [f"{f}:{i}: {line.strip()}" for f, body in sorted(self.files.items()) for i, line in enumerate(body.split("\n"), 1) if a.pattern in line] return Step({"output": "\n".join(hits[:40]) or "no matches", "steps_left": left}) f = {str(k).lower(): v for k, v in a.finding.items()} try: ok = (str(f.get("file", "")).strip().lstrip("./") == self.truth[0] and abs(int(f.get("line")) - self.truth[1]) <= 1 and (str(f.get("cwe", "")).strip().upper().split() or [""])[0].rstrip(":") == self.truth[2]) except (TypeError, ValueError): ok = False return Step({"output": "Finding recorded.", "steps_left": 0}, True, 1.0 if ok else 0.0) def oracle(self): return [{"tool": "list"}, {"tool": "open", "path": self.truth[0]}, {"tool": "report", "finding": {"file": self.truth[0], "line": self.truth[1], "cwe": self.truth[2]}}]