| """GuardBench pattern set v2. Six shapes per pattern. |
| |
| The guard is always at distance from the sink - a helper above, a decorator, a module constant, |
| or a branch several lines up. Two safe shapes per pattern (`covers`, `covers_alt`) so the safe |
| class is not a rounding error in the scoring. |
| """ |
| P2 = [] |
| def pattern(fn): P2.append(fn); return fn |
|
|
| @pattern |
| def ssrf_redirect(_): |
| cls = "server-side request forgery" |
| head = '''import requests |
| from urllib.parse import urlparse |
| |
| ALLOWED = {"api.partner.com", "cdn.partner.com"} |
| |
| def _checked(url): |
| if urlparse(url).hostname not in ALLOWED: |
| raise ValueError("host not allowed") |
| return url |
| |
| ''' |
| return cls, dict( |
| none = head + '''def fetch_avatar(url): |
| return requests.get(url, timeout=5).content''', |
| covers = head + '''def fetch_avatar(url): |
| return requests.get(_checked(url), timeout=5, allow_redirects=False).content''', |
| covers_alt = head + '''def fetch_avatar(url): |
| r = requests.get(_checked(url), timeout=5, allow_redirects=True) |
| _checked(r.url) |
| return r.content''', |
| wrong_value = head + '''def fetch_avatar(url, fallback): |
| _checked(fallback) |
| return requests.get(url, timeout=5).content''', |
| irrelevant = head + '''def fetch_avatar(url): |
| if not url.startswith("https://"): |
| raise ValueError("https only") |
| return requests.get(url, timeout=5).content''', |
| elsewhere = head + '''def fetch_manifest(url): |
| return requests.get(_checked(url), timeout=5, allow_redirects=False).json() |
| |
| def fetch_avatar(url): |
| return requests.get(url, timeout=5).content''') |
|
|
| @pattern |
| def csrf_missing(_): |
| cls = "cross-site request forgery" |
| head = '''from functools import wraps |
| |
| def require_csrf(fn): |
| @wraps(fn) |
| def inner(request, *a, **kw): |
| if request.form.get("csrf") != request.session.get("csrf"): |
| abort(403) |
| return fn(request, *a, **kw) |
| return inner |
| |
| ''' |
| return cls, dict( |
| none = head + '''@app.post("/account/email") |
| def change_email(request): |
| request.user.email = request.form["email"] |
| request.user.save()''', |
| covers = head + '''@app.post("/account/email") |
| @require_csrf |
| def change_email(request): |
| request.user.email = request.form["email"] |
| request.user.save()''', |
| covers_alt = head + '''@app.post("/account/email") |
| def change_email(request): |
| if request.headers.get("Sec-Fetch-Site") != "same-origin": |
| abort(403) |
| if request.form.get("csrf") != request.session.get("csrf"): |
| abort(403) |
| request.user.email = request.form["email"] |
| request.user.save()''', |
| wrong_value = head + '''@app.post("/account/email") |
| def change_email(request): |
| if request.form.get("csrf") != request.form.get("csrf_echo"): |
| abort(403) |
| request.user.email = request.form["email"] |
| request.user.save()''', |
| irrelevant = head + '''@app.post("/account/email") |
| def change_email(request): |
| if "@" not in request.form["email"]: |
| abort(400) |
| request.user.email = request.form["email"] |
| request.user.save()''', |
| elsewhere = head + '''@app.post("/account/password") |
| @require_csrf |
| def change_password(request): |
| request.user.set_password(request.form["pw"]) |
| |
| @app.post("/account/email") |
| def change_email(request): |
| request.user.email = request.form["email"] |
| request.user.save()''') |
|
|
| @pattern |
| def toctou_symlink(_): |
| cls = "time-of-check time-of-use" |
| head = '''import os |
| |
| SPOOL = "/var/spool/uploads" |
| |
| def _create_exclusive(path): |
| fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) |
| return os.fdopen(fd, "wb") |
| |
| ''' |
| return cls, dict( |
| none = head + '''def save_upload(name, data): |
| path = os.path.join(SPOOL, name) |
| if os.path.exists(path): |
| raise FileExistsError(name) |
| with open(path, "wb") as fh: |
| fh.write(data)''', |
| covers = head + '''def save_upload(name, data): |
| with _create_exclusive(os.path.join(SPOOL, name)) as fh: |
| fh.write(data)''', |
| covers_alt = head + '''def save_upload(name, data): |
| fd = os.open(os.path.join(SPOOL, name), |
| os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) |
| with os.fdopen(fd, "wb") as fh: |
| fh.write(data)''', |
| wrong_value = head + '''def save_upload(name, data, tmpname): |
| _create_exclusive(os.path.join(SPOOL, tmpname)).close() |
| with open(os.path.join(SPOOL, name), "wb") as fh: |
| fh.write(data)''', |
| irrelevant = head + '''def save_upload(name, data): |
| if "/" in name or name.startswith("."): |
| raise ValueError("bad name") |
| path = os.path.join(SPOOL, name) |
| with open(path, "wb") as fh: |
| fh.write(data)''', |
| elsewhere = head + '''def save_temp(name, data): |
| with _create_exclusive(os.path.join(SPOOL, name)) as fh: |
| fh.write(data) |
| |
| def save_upload(name, data): |
| with open(os.path.join(SPOOL, name), "wb") as fh: |
| fh.write(data)''') |
|
|
| @pattern |
| def unicode_bypass(_): |
| cls = "input validation bypass" |
| head = '''import unicodedata, re |
| |
| BLOCKED = re.compile(r"(?i)\\b(admin|root|system)\\b") |
| |
| def _canonical(s): |
| return unicodedata.normalize("NFKC", s).casefold() |
| |
| ''' |
| return cls, dict( |
| none = head + '''def register(username): |
| return create_user(username)''', |
| covers = head + '''def register(username): |
| canon = _canonical(username) |
| if BLOCKED.search(canon): |
| raise ValueError("reserved name") |
| return create_user(canon)''', |
| covers_alt = head + '''def register(username): |
| canon = unicodedata.normalize("NFKC", username).casefold() |
| if BLOCKED.search(canon): |
| raise ValueError("reserved name") |
| return create_user(canon)''', |
| wrong_value = head + '''def register(username, display): |
| if BLOCKED.search(_canonical(display)): |
| raise ValueError("reserved name") |
| return create_user(_canonical(username))''', |
| irrelevant = head + '''def register(username): |
| if len(username) > 32: |
| raise ValueError("too long") |
| return create_user(_canonical(username))''', |
| elsewhere = head + '''def register_org(name): |
| canon = _canonical(name) |
| if BLOCKED.search(canon): |
| raise ValueError("reserved name") |
| return create_org(canon) |
| |
| def register(username): |
| return create_user(_canonical(username))''') |
|
|
| @pattern |
| def cache_poisoning(_): |
| cls = "web cache poisoning" |
| head = '''KEYED_HEADERS = ("Host", "Accept-Language") |
| |
| def _cache_key(request): |
| parts = [request.path] + [request.headers.get(h, "") for h in KEYED_HEADERS] |
| return "|".join(parts) |
| |
| ''' |
| return cls, dict( |
| none = head + '''def render_page(request): |
| key = request.path |
| if key in CACHE: |
| return CACHE[key] |
| body = build(request, base=request.headers.get("X-Forwarded-Host", "")) |
| CACHE[key] = body |
| return body''', |
| covers = head + '''def render_page(request): |
| key = _cache_key(request) |
| if key in CACHE: |
| return CACHE[key] |
| body = build(request, base=request.headers.get("Host", "")) |
| CACHE[key] = body |
| return body''', |
| covers_alt = head + '''def render_page(request): |
| key = request.path + "|" + request.headers.get("Host", "") |
| if key in CACHE: |
| return CACHE[key] |
| body = build(request, base=request.headers.get("Host", "")) |
| CACHE[key] = body |
| return body''', |
| wrong_value = head + '''def render_page(request): |
| key = _cache_key(request) |
| if key in CACHE: |
| return CACHE[key] |
| body = build(request, base=request.headers.get("X-Forwarded-Host", "")) |
| CACHE[key] = body |
| return body''', |
| irrelevant = head + '''def render_page(request): |
| if len(request.path) > 512: |
| raise ValueError("path too long") |
| key = request.path |
| if key in CACHE: |
| return CACHE[key] |
| body = build(request, base=request.headers.get("X-Forwarded-Host", "")) |
| CACHE[key] = body |
| return body''', |
| elsewhere = head + '''def render_asset(request): |
| key = _cache_key(request) |
| return CACHE.setdefault(key, build_asset(request)) |
| |
| def render_page(request): |
| key = request.path |
| if key in CACHE: |
| return CACHE[key] |
| body = build(request, base=request.headers.get("X-Forwarded-Host", "")) |
| CACHE[key] = body |
| return body''') |
|
|
| @pattern |
| def int_overflow(_): |
| cls = "integer overflow in size check" |
| head = '''MAX_TOTAL = 50 * 1024 * 1024 |
| |
| def _fits(count, unit): |
| if count < 0 or unit < 0: |
| raise ValueError("negative size") |
| if count > MAX_TOTAL // max(unit, 1): |
| raise ValueError("too large") |
| return True |
| |
| ''' |
| return cls, dict( |
| none = head + '''def allocate_frames(count, unit): |
| return bytearray(count * unit)''', |
| covers = head + '''def allocate_frames(count, unit): |
| _fits(count, unit) |
| return bytearray(count * unit)''', |
| covers_alt = head + '''def allocate_frames(count, unit): |
| if count < 0 or unit < 0 or count > MAX_TOTAL // max(unit, 1): |
| raise ValueError("bad size") |
| return bytearray(count * unit)''', |
| wrong_value = head + '''def allocate_frames(count, unit, stride): |
| _fits(count, stride) |
| return bytearray(count * unit)''', |
| irrelevant = head + '''def allocate_frames(count, unit): |
| if count * unit > MAX_TOTAL: |
| raise ValueError("too large") |
| return bytearray(count * unit)''', |
| elsewhere = head + '''def allocate_tiles(count, unit): |
| _fits(count, unit) |
| return bytearray(count * unit) |
| |
| def allocate_frames(count, unit): |
| return bytearray(count * unit)''') |
|
|
| @pattern |
| def sig_skip_branch(_): |
| cls = "missing signature verification" |
| head = '''import hmac, hashlib, base64 |
| |
| SCHEME = "v2" |
| |
| def _verify(payload, header, secret): |
| """Header is "v2,<ts>,<b64 mac>"; the MAC covers the timestamp and the payload.""" |
| try: |
| scheme, ts, mac_b64 = header.split(",", 2) |
| except ValueError: |
| return False |
| if scheme != SCHEME: |
| return False |
| signed = ts.encode() + b"." + payload |
| want = base64.b64decode(mac_b64 + "==") |
| got = hmac.new(secret, signed, hashlib.sha512).digest() |
| return hmac.compare_digest(got, want) |
| |
| ''' |
| return cls, dict( |
| none = head + '''def handle_hook(request, secret): |
| return process(json.loads(request.body))''', |
| covers = head + '''def handle_hook(request, secret): |
| if not _verify(request.body, request.headers.get("X-Sig", ""), secret): |
| abort(401) |
| return process(json.loads(request.body))''', |
| covers_alt = head + '''def handle_hook(request, secret): |
| header = request.headers.get("X-Sig", "") |
| scheme, ts, mac_b64 = (header.split(",", 2) + ["", "", ""])[:3] |
| signed = ts.encode() + b"." + request.body |
| got = hmac.new(secret, signed, hashlib.sha512).digest() |
| if scheme != SCHEME or not hmac.compare_digest(got, base64.b64decode(mac_b64 + "==")): |
| abort(401) |
| return process(json.loads(request.body))''', |
| wrong_value = head + '''def handle_hook(request, secret): |
| if not _verify(request.headers.get("X-Meta", b""), request.headers.get("X-Sig", ""), secret): |
| abort(401) |
| return process(json.loads(request.body))''', |
| irrelevant = head + '''def handle_hook(request, secret): |
| if request.headers.get("Content-Type") != "application/json": |
| abort(415) |
| return process(json.loads(request.body))''', |
| elsewhere = head + '''def handle_billing_hook(request, secret): |
| if not _verify(request.body, request.headers.get("X-Sig", ""), secret): |
| abort(401) |
| return process(json.loads(request.body)) |
| |
| def handle_hook(request, secret): |
| return process(json.loads(request.body))''') |
|
|
| @pattern |
| def reset_token_reuse(_): |
| cls = "authentication bypass" |
| head = '''def _consume(token): |
| """Single-use: returns the user only if the row was still unused.""" |
| rows = db.execute( |
| "UPDATE resets SET used_at = now() WHERE token = %s AND used_at IS NULL RETURNING user_id", |
| (token,)) |
| return rows[0][0] if rows else None |
| |
| ''' |
| return cls, dict( |
| none = head + '''def apply_reset(token, new_password): |
| uid = db.query("SELECT user_id FROM resets WHERE token = %s", (token,))[0][0] |
| set_password(uid, new_password)''', |
| covers = head + '''def apply_reset(token, new_password): |
| uid = _consume(token) |
| if uid is None: |
| abort(400) |
| set_password(uid, new_password)''', |
| covers_alt = head + '''def apply_reset(token, new_password): |
| rows = db.execute( |
| "UPDATE resets SET used_at = now() WHERE token = %s AND used_at IS NULL RETURNING user_id", |
| (token,)) |
| if not rows: |
| abort(400) |
| set_password(rows[0][0], new_password)''', |
| wrong_value = head + '''def apply_reset(token, confirm_token, new_password): |
| _consume(confirm_token) |
| uid = db.query("SELECT user_id FROM resets WHERE token = %s", (token,))[0][0] |
| set_password(uid, new_password)''', |
| irrelevant = head + '''def apply_reset(token, new_password): |
| row = db.query("SELECT user_id, created_at FROM resets WHERE token = %s", (token,))[0] |
| if (now() - row[1]).total_seconds() > 3600: |
| abort(400) |
| set_password(row[0], new_password)''', |
| elsewhere = head + '''def apply_invite(token): |
| uid = _consume(token) |
| if uid is None: |
| abort(400) |
| activate(uid) |
| |
| def apply_reset(token, new_password): |
| uid = db.query("SELECT user_id FROM resets WHERE token = %s", (token,))[0][0] |
| set_password(uid, new_password)''') |
|
|
| @pattern |
| def dict_merge(_): |
| cls = "mass assignment" |
| head = '''PROTECTED = {"is_admin", "org_id", "plan", "__class__"} |
| |
| def _merge_safe(target, patch): |
| for k, v in patch.items(): |
| if k in PROTECTED: |
| continue |
| if isinstance(v, dict) and isinstance(target.get(k), dict): |
| _merge_safe(target[k], v) |
| else: |
| target[k] = v |
| return target |
| |
| ''' |
| return cls, dict( |
| none = head + '''def update_settings(user, patch): |
| return _deep_merge(user.settings, patch)''', |
| covers = head + '''def update_settings(user, patch): |
| return _merge_safe(user.settings, patch)''', |
| covers_alt = head + '''def update_settings(user, patch): |
| clean = {k: v for k, v in patch.items() if k not in PROTECTED} |
| return _merge_safe(user.settings, clean)''', |
| wrong_value = head + '''def update_settings(user, patch, defaults): |
| _merge_safe({}, defaults) |
| return _deep_merge(user.settings, patch)''', |
| irrelevant = head + '''def update_settings(user, patch): |
| if len(patch) > 50: |
| raise ValueError("too many keys") |
| return _deep_merge(user.settings, patch)''', |
| elsewhere = head + '''def update_org_settings(org, patch): |
| return _merge_safe(org.settings, patch) |
| |
| def update_settings(user, patch): |
| return _deep_merge(user.settings, patch)''') |
|
|
| @pattern |
| def arg_injection(_): |
| cls = "argument injection" |
| head = '''import subprocess |
| |
| def _as_operand(value): |
| """Stops a value beginning with '-' from being read as a flag.""" |
| if value.startswith("-"): |
| raise ValueError("operand may not start with a dash") |
| return value |
| |
| ''' |
| return cls, dict( |
| none = head + '''def count_matches(pattern, path): |
| return subprocess.run(["grep", "-c", pattern, path], capture_output=True).stdout''', |
| covers = head + '''def count_matches(pattern, path): |
| return subprocess.run(["grep", "-c", "-e", pattern, "--", path], |
| capture_output=True).stdout''', |
| covers_alt = head + '''def count_matches(pattern, path): |
| return subprocess.run(["grep", "-c", "--", _as_operand(pattern), _as_operand(path)], |
| capture_output=True).stdout''', |
| wrong_value = head + '''def count_matches(pattern, path): |
| _as_operand(path) |
| return subprocess.run(["grep", "-c", pattern, path], capture_output=True).stdout''', |
| irrelevant = head + '''def count_matches(pattern, path): |
| if ";" in pattern or "|" in pattern or "$" in pattern: |
| raise ValueError("shell metacharacter") |
| return subprocess.run(["grep", "-c", pattern, path], capture_output=True).stdout''', |
| elsewhere = head + '''def list_matches(pattern, path): |
| return subprocess.run(["grep", "-n", "-e", pattern, "--", path], |
| capture_output=True).stdout |
| |
| def count_matches(pattern, path): |
| return subprocess.run(["grep", "-c", pattern, path], capture_output=True).stdout''') |
|
|
| @pattern |
| def tar_symlink(_): |
| cls = "path traversal" |
| head = '''import tarfile, os |
| |
| def _safe_members(tar, root): |
| root = os.path.realpath(root) |
| for m in tar.getmembers(): |
| if m.issym() or m.islnk(): |
| continue |
| dest = os.path.realpath(os.path.join(root, m.name)) |
| if os.path.commonpath([dest, root]) != root: |
| raise ValueError("entry escapes destination") |
| yield m |
| |
| ''' |
| return cls, dict( |
| none = head + '''def unpack_bundle(path, dest): |
| with tarfile.open(path) as t: |
| t.extractall(dest)''', |
| covers = head + '''def unpack_bundle(path, dest): |
| with tarfile.open(path) as t: |
| t.extractall(dest, members=_safe_members(t, dest))''', |
| covers_alt = head + '''def unpack_bundle(path, dest): |
| with tarfile.open(path) as t: |
| t.extractall(dest, filter="data")''', |
| wrong_value = head + '''def unpack_bundle(path, dest, staging): |
| with tarfile.open(path) as t: |
| list(_safe_members(t, staging)) |
| t.extractall(dest)''', |
| irrelevant = head + '''def unpack_bundle(path, dest): |
| with tarfile.open(path) as t: |
| if sum(m.size for m in t.getmembers()) > 100 * 1024 * 1024: |
| raise ValueError("bundle too large") |
| t.extractall(dest)''', |
| elsewhere = head + '''def unpack_theme(path, dest): |
| with tarfile.open(path) as t: |
| t.extractall(dest, members=_safe_members(t, dest)) |
| |
| def unpack_bundle(path, dest): |
| with tarfile.open(path) as t: |
| t.extractall(dest)''') |
|
|
| @pattern |
| def jwt_audience(_): |
| cls = "authentication bypass" |
| head = '''import jwt |
| |
| ISSUER = "https://auth.example.com/" |
| AUDIENCE = "api.example.com" |
| |
| def _claims(token, key): |
| return jwt.decode(token, key, algorithms=["RS256"], |
| audience=AUDIENCE, issuer=ISSUER, |
| options={"require": ["exp", "iss", "aud", "sub"]}) |
| |
| ''' |
| return cls, dict( |
| none = head + '''def current_user(token, key): |
| claims = jwt.decode(token, key, algorithms=["RS256"]) |
| return User.get(claims["sub"])''', |
| covers = head + '''def current_user(token, key): |
| return User.get(_claims(token, key)["sub"])''', |
| covers_alt = head + '''def current_user(token, key): |
| claims = jwt.decode(token, key, algorithms=["RS256"], |
| audience=AUDIENCE, issuer=ISSUER, |
| options={"require": ["exp", "iss", "aud", "sub"]}) |
| return User.get(claims["sub"])''', |
| wrong_value = head + '''def current_user(token, refresh_token, key): |
| _claims(refresh_token, key) |
| claims = jwt.decode(token, key, algorithms=["RS256"]) |
| return User.get(claims["sub"])''', |
| irrelevant = head + '''def current_user(token, key): |
| claims = jwt.decode(token, key, algorithms=["RS256"]) |
| if claims.get("exp", 0) < time.time(): |
| abort(401) |
| return User.get(claims["sub"])''', |
| elsewhere = head + '''def service_account(token, key): |
| return Service.get(_claims(token, key)["sub"]) |
| |
| def current_user(token, key): |
| claims = jwt.decode(token, key, algorithms=["RS256"]) |
| return User.get(claims["sub"])''') |
|
|