GuardBench / build_items_v1.py
Soaperloafidksum's picture
GuardBench: 120 items, 20 patterns, 6 guard shapes
82c37ae verified
Raw History Blame Contribute Delete
12 kB
#!/usr/bin/env python3
"""Build GuardBench items. Five shapes per pattern; the delta defines the label.
The guard is always at distance from the sink: a helper above, a decorator, a module constant,
or a branch several lines up. Never the adjacent line.
"""
import json, ast, os, hashlib
from collections import Counter
P = []
def pattern(fn): P.append(fn); return fn
# ---------------------------------------------------------------- patterns
@pattern
def xxe(_):
cls = "xml external entity"
head = '''import defusedxml.ElementTree as SAFEET
import xml.etree.ElementTree as ET
def _parse_trusted(blob):
"""Internal feeds only; these come from our own signed bundles."""
return ET.fromstring(blob)
'''
none = head + '''def import_feed(request):
return ET.fromstring(request.body)'''
covers = head + '''def import_feed(request):
return SAFEET.fromstring(request.body)'''
wrong = head + '''def import_feed(request):
SAFEET.fromstring(request.headers.get("X-Manifest", "<m/>"))
return ET.fromstring(request.body)'''
irrelevant = head + '''def import_feed(request):
if len(request.body) > 2_000_000:
raise ValueError("feed too large")
return ET.fromstring(request.body)'''
elsewhere = head + '''def import_manifest(request):
return SAFEET.fromstring(request.body)
def import_feed(request):
return _parse_trusted(request.body)'''
return cls, none, covers, wrong, irrelevant, elsewhere
@pattern
def ssti(_):
cls = "server-side template injection"
head = '''from jinja2 import Environment, select_autoescape
from jinja2.sandbox import SandboxedEnvironment
SANDBOX = SandboxedEnvironment(autoescape=select_autoescape())
LOOSE = Environment(autoescape=select_autoescape())
'''
none = head + '''def render_signature(user):
return LOOSE.from_string(user.signature_template).render(user=user)'''
covers = head + '''def render_signature(user):
return SANDBOX.from_string(user.signature_template).render(user=user)'''
wrong = head + '''def render_signature(user):
SANDBOX.from_string(user.display_name).render()
return LOOSE.from_string(user.signature_template).render(user=user)'''
irrelevant = head + '''def render_signature(user):
if "<script" in user.signature_template.lower():
raise ValueError("no script tags")
return LOOSE.from_string(user.signature_template).render(user=user)'''
elsewhere = head + '''def render_footer(org):
return SANDBOX.from_string(org.footer_template).render(org=org)
def render_signature(user):
return LOOSE.from_string(user.signature_template).render(user=user)'''
return cls, none, covers, wrong, irrelevant, elsewhere
@pattern
def redos(_):
cls = "regular expression denial of service"
head = '''import re, regex
MAX_PATTERN_LEN = 200
def _compile_bounded(p):
"""regex module supports a match timeout; re does not."""
return regex.compile(p)
'''
none = head + '''def search_logs(lines, user_pattern):
rx = re.compile(user_pattern)
return [l for l in lines if rx.search(l)]'''
covers = head + '''def search_logs(lines, user_pattern):
rx = _compile_bounded(user_pattern)
return [l for l in lines if rx.search(l, timeout=0.25)]'''
wrong = head + '''def search_logs(lines, user_pattern, highlight):
_compile_bounded(highlight)
rx = re.compile(user_pattern)
return [l for l in lines if rx.search(l)]'''
irrelevant = head + '''def search_logs(lines, user_pattern):
if len(user_pattern) > MAX_PATTERN_LEN:
raise ValueError("pattern too long")
rx = re.compile(user_pattern)
return [l for l in lines if rx.search(l)]'''
elsewhere = head + '''def search_alerts(rows, user_pattern):
rx = _compile_bounded(user_pattern)
return [r for r in rows if rx.search(r, timeout=0.25)]
def search_logs(lines, user_pattern):
rx = re.compile(user_pattern)
return [l for l in lines if rx.search(l)]'''
return cls, none, covers, wrong, irrelevant, elsewhere
@pattern
def host_header(_):
cls = "host header injection"
head = '''TRUSTED_HOSTS = {"app.example.com", "www.example.com"}
def _origin(request):
host = request.headers.get("Host", "")
if host not in TRUSTED_HOSTS:
raise ValueError("untrusted host")
return "https://" + host
'''
none = head + '''def send_reset(user, request, token):
link = "https://" + request.headers["Host"] + "/reset?t=" + token
mail(user.email, link)'''
covers = head + '''def send_reset(user, request, token):
mail(user.email, _origin(request) + "/reset?t=" + token)'''
wrong = head + '''def send_reset(user, request, token):
_origin(request)
link = "https://" + request.headers.get("X-Forwarded-Host", "") + "/reset?t=" + token
mail(user.email, link)'''
irrelevant = head + '''def send_reset(user, request, token):
host = request.headers.get("Host", "")
if len(host) > 253 or "\\n" in host:
raise ValueError("malformed host")
mail(user.email, "https://" + host + "/reset?t=" + token)'''
elsewhere = head + '''def send_invite(user, request, token):
mail(user.email, _origin(request) + "/invite?t=" + token)
def send_reset(user, request, token):
mail(user.email, "https://" + request.headers["Host"] + "/reset?t=" + token)'''
return cls, none, covers, wrong, irrelevant, elsewhere
@pattern
def weak_token(_):
cls = "insecure randomness"
head = '''import random, secrets
TOKEN_BYTES = 32
def _strong_token():
return secrets.token_urlsafe(TOKEN_BYTES)
'''
none = head + '''def new_reset_token(user):
t = "".join(random.choice("0123456789abcdef") for _ in range(32))
store(user, t); return t'''
covers = head + '''def new_reset_token(user):
t = _strong_token()
store(user, t); return t'''
wrong = head + '''def new_reset_token(user):
_strong_token()
t = "%d%d" % (int(time.time()), random.randint(0, 10**9))
store(user, t); return t'''
irrelevant = head + '''def new_reset_token(user):
t = "".join(random.choice("0123456789abcdef") for _ in range(64))
if len(t) < 32:
raise ValueError("token too short")
store(user, t); return t'''
elsewhere = head + '''def new_session_token(user):
t = _strong_token()
store(user, t); return t
def new_reset_token(user):
t = "".join(random.choice("0123456789abcdef") for _ in range(32))
store(user, t); return t'''
return cls, none, covers, wrong, irrelevant, elsewhere
@pattern
def csv_injection(_):
cls = "formula injection"
head = '''DANGEROUS_PREFIX = ("=", "+", "-", "@", "\\t", "\\r")
def _neutralise(v):
s = "" if v is None else str(v)
return "'" + s if s.startswith(DANGEROUS_PREFIX) else s
'''
none = head + '''def export_rows(rows, out):
w = csv.writer(out)
for r in rows:
w.writerow([r.name, r.note])'''
covers = head + '''def export_rows(rows, out):
w = csv.writer(out)
for r in rows:
w.writerow([_neutralise(r.name), _neutralise(r.note)])'''
wrong = head + '''def export_rows(rows, out):
w = csv.writer(out)
for r in rows:
w.writerow([_neutralise(r.name), r.note])'''
irrelevant = head + '''def export_rows(rows, out):
w = csv.writer(out)
for r in rows:
w.writerow([html.escape(r.name), html.escape(r.note)])'''
elsewhere = head + '''def export_summary(rows, out):
w = csv.writer(out)
for r in rows:
w.writerow([_neutralise(r.label)])
def export_rows(rows, out):
w = csv.writer(out)
for r in rows:
w.writerow([r.name, r.note])'''
return cls, none, covers, wrong, irrelevant, elsewhere
@pattern
def zip_bomb(_):
cls = "resource exhaustion"
head = '''MAX_TOTAL = 200 * 1024 * 1024
def _checked_members(z):
total = 0
for info in z.infolist():
total += info.file_size
if total > MAX_TOTAL:
raise ValueError("archive expands too large")
yield info
'''
none = head + '''def unpack(path, dest):
with zipfile.ZipFile(path) as z:
z.extractall(dest)'''
covers = head + '''def unpack(path, dest):
with zipfile.ZipFile(path) as z:
for info in _checked_members(z):
z.extract(info, dest)'''
wrong = head + '''def unpack(path, dest):
with zipfile.ZipFile(path) as z:
list(_checked_members(z))
z.extractall(dest)'''
irrelevant = head + '''def unpack(path, dest):
if os.path.getsize(path) > 20 * 1024 * 1024:
raise ValueError("archive file too large")
with zipfile.ZipFile(path) as z:
z.extractall(dest)'''
elsewhere = head + '''def unpack_theme(path, dest):
with zipfile.ZipFile(path) as z:
for info in _checked_members(z):
z.extract(info, dest)
def unpack(path, dest):
with zipfile.ZipFile(path) as z:
z.extractall(dest)'''
return cls, none, covers, wrong, irrelevant, elsewhere
@pattern
def ldap_injection(_):
cls = "ldap injection"
head = '''from ldap3.utils.conv import escape_filter_chars
BASE_DN = "ou=people,dc=example,dc=com"
def _filter_for(uid):
return "(uid=%s)" % escape_filter_chars(uid)
'''
none = head + '''def find_user(conn, uid):
conn.search(BASE_DN, "(uid=%s)" % uid)
return conn.entries'''
covers = head + '''def find_user(conn, uid):
conn.search(BASE_DN, _filter_for(uid))
return conn.entries'''
wrong = head + '''def find_user(conn, uid, dept):
_filter_for(dept)
conn.search(BASE_DN, "(&(uid=%s)(ou=%s))" % (uid, escape_filter_chars(dept)))
return conn.entries'''
irrelevant = head + '''def find_user(conn, uid):
if not uid or len(uid) > 64:
raise ValueError("bad uid length")
conn.search(BASE_DN, "(uid=%s)" % uid)
return conn.entries'''
elsewhere = head + '''def find_group(conn, gid):
conn.search(BASE_DN, "(cn=%s)" % escape_filter_chars(gid))
return conn.entries
def find_user(conn, uid):
conn.search(BASE_DN, "(uid=%s)" % uid)
return conn.entries'''
return cls, none, covers, wrong, irrelevant, elsewhere
# ---------------------------------------------------------------- assembly
SHAPES = ["none", "covers", "wrong_value", "irrelevant", "elsewhere"]
LABEL = {"none":"unsafe","covers":"safe","wrong_value":"unsafe","irrelevant":"unsafe","elsewhere":"unsafe"}
WHY = {
"none": "no guard is applied on this path",
"covers": "the guard is applied to the tainted value and addresses the weakness",
"wrong_value": "the guard is applied to a sibling value, not the one that reaches the sink",
"irrelevant": "a guard is applied to the right value but does not address this weakness",
"elsewhere": "the guard exists and is used by a neighbouring function, not on this path",
}
def build():
out, seen = [], set()
for fn in P:
cls, *variants = fn(None)
for shape, code in zip(SHAPES, variants):
h = hashlib.sha1(code.encode()).hexdigest()[:12]
if h in seen: continue
seen.add(h)
out.append({
"id": f"{fn.__name__}_{shape}",
"pattern": fn.__name__,
"shape": shape,
"label": LABEL[shape],
"vuln_class": cls if LABEL[shape]=="unsafe" else None,
"why": WHY[shape],
"code": code,
})
return out
if __name__ == "__main__":
rows = build()
bad = []
for r in rows:
try: ast.parse(r["code"])
except SyntaxError as e: bad.append((r["id"], str(e)))
p = os.path.expanduser("~/loreacyber-ft/guardbench/items.jsonl")
with open(p,"w") as fh:
for r in rows: fh.write(json.dumps(r)+"\n")
print(f"items: {len(rows)} -> {p}")
print("shape :", dict(Counter(r['shape'] for r in rows)))
print("label :", dict(Counter(r['label'] for r in rows)))
print(f"syntax errors: {len(bad)}")
for i,e in bad[:6]: print(" ",i,e)