File size: 11,960 Bytes
82c37ae | 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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | #!/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)
|