File size: 8,045 Bytes
ab59633 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | """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]}}]
|