id stringlengths 8 29 | pattern stringclasses 20
values | shape stringclasses 6
values | label stringclasses 2
values | vuln_class stringclasses 19
values | why stringclasses 6
values | code stringlengths 189 918 |
|---|---|---|---|---|---|---|
xxe_none | xxe | none | unsafe | xml external entity | no guard is applied on this path | 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)
def import_feed(request):
return ET.fromstring(request.body) |
xxe_covers | xxe | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | 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)
def import_feed(request):
return SAFEET.fromstring(request.body) |
xxe_wrong_value | xxe | wrong_value | unsafe | xml external entity | the guard is applied to a sibling value, not the one that reaches the sink | 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)
def import_feed(request):
SAFEET.fromstring(request.headers.get("X-Manifest", "<m/>"))
return ET.fromstring... |
xxe_irrelevant | xxe | irrelevant | unsafe | xml external entity | a guard is applied to the right value but does not address this weakness | 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)
def import_feed(request):
if len(request.body) > 2_000_000:
raise ValueError("feed too large")
retu... |
xxe_elsewhere | xxe | elsewhere | unsafe | xml external entity | the guard exists and is used by a neighbouring function, not on this path | 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)
def import_manifest(request):
return SAFEET.fromstring(request.body)
def import_feed(request):
return _par... |
xxe_covers_alt | xxe | covers_alt | safe | null | a second correct implementation, defended a different way | 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)
def import_feed(request):
parser = ET.XMLParser()
parser.parser.DefaultHandlerExpand = None
parser.enti... |
ssti_none | ssti | none | unsafe | server-side template injection | no guard is applied on this path | from jinja2 import Environment, select_autoescape
from jinja2.sandbox import SandboxedEnvironment
SANDBOX = SandboxedEnvironment(autoescape=select_autoescape())
LOOSE = Environment(autoescape=select_autoescape())
def render_signature(user):
return LOOSE.from_string(user.signature_template).render(user=user) |
ssti_covers | ssti | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | from jinja2 import Environment, select_autoescape
from jinja2.sandbox import SandboxedEnvironment
SANDBOX = SandboxedEnvironment(autoescape=select_autoescape())
LOOSE = Environment(autoescape=select_autoescape())
def render_signature(user):
return SANDBOX.from_string(user.signature_template).render(user=user) |
ssti_wrong_value | ssti | wrong_value | unsafe | server-side template injection | the guard is applied to a sibling value, not the one that reaches the sink | from jinja2 import Environment, select_autoescape
from jinja2.sandbox import SandboxedEnvironment
SANDBOX = SandboxedEnvironment(autoescape=select_autoescape())
LOOSE = Environment(autoescape=select_autoescape())
def render_signature(user):
SANDBOX.from_string(user.display_name).render()
return LOOSE.from_str... |
ssti_irrelevant | ssti | irrelevant | unsafe | server-side template injection | a guard is applied to the right value but does not address this weakness | from jinja2 import Environment, select_autoescape
from jinja2.sandbox import SandboxedEnvironment
SANDBOX = SandboxedEnvironment(autoescape=select_autoescape())
LOOSE = Environment(autoescape=select_autoescape())
def render_signature(user):
if "<script" in user.signature_template.lower():
raise ValueError... |
ssti_elsewhere | ssti | elsewhere | unsafe | server-side template injection | the guard exists and is used by a neighbouring function, not on this path | from jinja2 import Environment, select_autoescape
from jinja2.sandbox import SandboxedEnvironment
SANDBOX = SandboxedEnvironment(autoescape=select_autoescape())
LOOSE = Environment(autoescape=select_autoescape())
def render_footer(org):
return SANDBOX.from_string(org.footer_template).render(org=org)
def render_s... |
ssti_covers_alt | ssti | covers_alt | safe | null | a second correct implementation, defended a different way | from jinja2 import Environment, select_autoescape
from jinja2.sandbox import SandboxedEnvironment
SANDBOX = SandboxedEnvironment(autoescape=select_autoescape())
LOOSE = Environment(autoescape=select_autoescape())
ALLOWED_VARS = ("name", "org", "title")
def render_signature(user):
tmpl = user.signature_template
... |
redos_none | redos | none | unsafe | regular expression denial of service | no guard is applied on this path | import re, regex
MAX_PATTERN_LEN = 200
def _compile_bounded(p):
"""regex module supports a match timeout; re does not."""
return regex.compile(p)
def search_logs(lines, user_pattern):
rx = re.compile(user_pattern)
return [l for l in lines if rx.search(l)] |
redos_covers | redos | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | import re, regex
MAX_PATTERN_LEN = 200
def _compile_bounded(p):
"""regex module supports a match timeout; re does not."""
return regex.compile(p)
def search_logs(lines, user_pattern):
rx = _compile_bounded(user_pattern)
return [l for l in lines if rx.search(l, timeout=0.25)] |
redos_wrong_value | redos | wrong_value | unsafe | regular expression denial of service | the guard is applied to a sibling value, not the one that reaches the sink | import re, regex
MAX_PATTERN_LEN = 200
def _compile_bounded(p):
"""regex module supports a match timeout; re does not."""
return regex.compile(p)
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)] |
redos_irrelevant | redos | irrelevant | unsafe | regular expression denial of service | a guard is applied to the right value but does not address this weakness | import re, regex
MAX_PATTERN_LEN = 200
def _compile_bounded(p):
"""regex module supports a match timeout; re does not."""
return regex.compile(p)
def search_logs(lines, user_pattern):
if len(user_pattern) > MAX_PATTERN_LEN:
raise ValueError("pattern too long")
rx = re.compile(user_pattern)
... |
redos_elsewhere | redos | elsewhere | unsafe | regular expression denial of service | the guard exists and is used by a neighbouring function, not on this path | import re, regex
MAX_PATTERN_LEN = 200
def _compile_bounded(p):
"""regex module supports a match timeout; re does not."""
return regex.compile(p)
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, u... |
redos_covers_alt | redos | covers_alt | safe | null | a second correct implementation, defended a different way | import re, regex
MAX_PATTERN_LEN = 200
def _compile_bounded(p):
"""regex module supports a match timeout; re does not."""
return regex.compile(p)
def search_logs(lines, user_pattern):
rx = regex.compile(regex.escape(user_pattern))
return [l for l in lines if rx.search(l)] |
host_header_none | host_header | none | unsafe | host header injection | no guard is applied on this path | 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
def send_reset(user, request, token):
link = "https://" + request.headers["Host"] + "/re... |
host_header_covers | host_header | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | 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
def send_reset(user, request, token):
mail(user.email, _origin(request) + "/reset?t=" + ... |
host_header_wrong_value | host_header | wrong_value | unsafe | host header injection | the guard is applied to a sibling value, not the one that reaches the sink | 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
def send_reset(user, request, token):
_origin(request)
link = "https://" + request.h... |
host_header_irrelevant | host_header | irrelevant | unsafe | host header injection | a guard is applied to the right value but does not address this weakness | 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
def send_reset(user, request, token):
host = request.headers.get("Host", "")
if len(... |
host_header_elsewhere | host_header | elsewhere | unsafe | host header injection | the guard exists and is used by a neighbouring function, not on this path | 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
def send_invite(user, request, token):
mail(user.email, _origin(request) + "/invite?t=" ... |
host_header_covers_alt | host_header | covers_alt | safe | null | a second correct implementation, defended a different way | 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
CANONICAL_ORIGIN = "https://app.example.com"
def send_reset(user, request, token):
mail... |
weak_token_none | weak_token | none | unsafe | insecure randomness | no guard is applied on this path | import random, secrets
TOKEN_BYTES = 32
def _strong_token():
return secrets.token_urlsafe(TOKEN_BYTES)
def new_reset_token(user):
t = "".join(random.choice("0123456789abcdef") for _ in range(32))
store(user, t); return t |
weak_token_covers | weak_token | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | import random, secrets
TOKEN_BYTES = 32
def _strong_token():
return secrets.token_urlsafe(TOKEN_BYTES)
def new_reset_token(user):
t = _strong_token()
store(user, t); return t |
weak_token_wrong_value | weak_token | wrong_value | unsafe | insecure randomness | the guard is applied to a sibling value, not the one that reaches the sink | import random, secrets
TOKEN_BYTES = 32
def _strong_token():
return secrets.token_urlsafe(TOKEN_BYTES)
def new_reset_token(user):
_strong_token()
t = "%d%d" % (int(time.time()), random.randint(0, 10**9))
store(user, t); return t |
weak_token_irrelevant | weak_token | irrelevant | unsafe | insecure randomness | a guard is applied to the right value but does not address this weakness | import random, secrets
TOKEN_BYTES = 32
def _strong_token():
return secrets.token_urlsafe(TOKEN_BYTES)
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 |
weak_token_elsewhere | weak_token | elsewhere | unsafe | insecure randomness | the guard exists and is used by a neighbouring function, not on this path | import random, secrets
TOKEN_BYTES = 32
def _strong_token():
return secrets.token_urlsafe(TOKEN_BYTES)
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 |
weak_token_covers_alt | weak_token | covers_alt | safe | null | a second correct implementation, defended a different way | import random, secrets
TOKEN_BYTES = 32
def _strong_token():
return secrets.token_urlsafe(TOKEN_BYTES)
def new_reset_token(user):
t = secrets.token_hex(TOKEN_BYTES)
store(user, t); return t |
csv_injection_none | csv_injection | none | unsafe | formula injection | no guard is applied on this path | DANGEROUS_PREFIX = ("=", "+", "-", "@", "\t", "\r")
def _neutralise(v):
s = "" if v is None else str(v)
return "'" + s if s.startswith(DANGEROUS_PREFIX) else s
def export_rows(rows, out):
w = csv.writer(out)
for r in rows:
w.writerow([r.name, r.note]) |
csv_injection_covers | csv_injection | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | DANGEROUS_PREFIX = ("=", "+", "-", "@", "\t", "\r")
def _neutralise(v):
s = "" if v is None else str(v)
return "'" + s if s.startswith(DANGEROUS_PREFIX) else s
def export_rows(rows, out):
w = csv.writer(out)
for r in rows:
w.writerow([_neutralise(r.name), _neutralise(r.note)]) |
csv_injection_wrong_value | csv_injection | wrong_value | unsafe | formula injection | the guard is applied to a sibling value, not the one that reaches the sink | DANGEROUS_PREFIX = ("=", "+", "-", "@", "\t", "\r")
def _neutralise(v):
s = "" if v is None else str(v)
return "'" + s if s.startswith(DANGEROUS_PREFIX) else s
def export_rows(rows, out):
w = csv.writer(out)
for r in rows:
w.writerow([_neutralise(r.name), r.note]) |
csv_injection_irrelevant | csv_injection | irrelevant | unsafe | formula injection | a guard is applied to the right value but does not address this weakness | DANGEROUS_PREFIX = ("=", "+", "-", "@", "\t", "\r")
def _neutralise(v):
s = "" if v is None else str(v)
return "'" + s if s.startswith(DANGEROUS_PREFIX) else s
def export_rows(rows, out):
w = csv.writer(out)
for r in rows:
w.writerow([html.escape(r.name), html.escape(r.note)]) |
csv_injection_elsewhere | csv_injection | elsewhere | unsafe | formula injection | the guard exists and is used by a neighbouring function, not on this path | DANGEROUS_PREFIX = ("=", "+", "-", "@", "\t", "\r")
def _neutralise(v):
s = "" if v is None else str(v)
return "'" + s if s.startswith(DANGEROUS_PREFIX) else s
def export_summary(rows, out):
w = csv.writer(out)
for r in rows:
w.writerow([_neutralise(r.label)])
def export_rows(rows, out):
... |
csv_injection_covers_alt | csv_injection | covers_alt | safe | null | a second correct implementation, defended a different way | DANGEROUS_PREFIX = ("=", "+", "-", "@", "\t", "\r")
def _neutralise(v):
s = "" if v is None else str(v)
return "'" + s if s.startswith(DANGEROUS_PREFIX) else s
def export_rows(rows, out):
w = csv.writer(out, quoting=csv.QUOTE_ALL)
for r in rows:
w.writerow([_neutralise(x) for x in (r.name, r.n... |
zip_bomb_none | zip_bomb | none | unsafe | resource exhaustion | no guard is applied on this path | 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
def unpack(path, dest):
with zipfile.ZipFile(path) as z:
z.extractal... |
zip_bomb_covers | zip_bomb | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | 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
def unpack(path, dest):
with zipfile.ZipFile(path) as z:
for info in... |
zip_bomb_wrong_value | zip_bomb | wrong_value | unsafe | resource exhaustion | the guard is applied to a sibling value, not the one that reaches the sink | 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
def unpack(path, dest):
with zipfile.ZipFile(path) as z:
list(_check... |
zip_bomb_irrelevant | zip_bomb | irrelevant | unsafe | resource exhaustion | a guard is applied to the right value but does not address this weakness | 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
def unpack(path, dest):
if os.path.getsize(path) > 20 * 1024 * 1024:
... |
zip_bomb_elsewhere | zip_bomb | elsewhere | unsafe | resource exhaustion | the guard exists and is used by a neighbouring function, not on this path | 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
def unpack_theme(path, dest):
with zipfile.ZipFile(path) as z:
for i... |
zip_bomb_covers_alt | zip_bomb | covers_alt | safe | null | a second correct implementation, defended a different way | 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
def unpack(path, dest):
written = 0
with zipfile.ZipFile(path) as z:
... |
ldap_injection_none | ldap_injection | none | unsafe | ldap injection | no guard is applied on this path | 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)
def find_user(conn, uid):
conn.search(BASE_DN, "(uid=%s)" % uid)
return conn.entries |
ldap_injection_covers | ldap_injection | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | 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)
def find_user(conn, uid):
conn.search(BASE_DN, _filter_for(uid))
return conn.entries |
ldap_injection_wrong_value | ldap_injection | wrong_value | unsafe | ldap injection | the guard is applied to a sibling value, not the one that reaches the sink | 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)
def find_user(conn, uid, dept):
_filter_for(dept)
conn.search(BASE_DN, "(&(uid=%s)(ou=%s))" % (uid, escape_filter_chars(dept)))
return conn.entri... |
ldap_injection_irrelevant | ldap_injection | irrelevant | unsafe | ldap injection | a guard is applied to the right value but does not address this weakness | 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)
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 c... |
ldap_injection_elsewhere | ldap_injection | elsewhere | unsafe | ldap injection | the guard exists and is used by a neighbouring function, not on this path | 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)
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(... |
ldap_injection_covers_alt | ldap_injection | covers_alt | safe | null | a second correct implementation, defended a different way | 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)
def find_user(conn, uid):
conn.search(BASE_DN, "(uid=%s)" % escape_filter_chars(uid))
return conn.entries |
ssrf_redirect_none | ssrf_redirect | none | unsafe | server-side request forgery | no guard is applied on this path | 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
def fetch_avatar(url):
return requests.get(url, timeout=5).content |
ssrf_redirect_covers | ssrf_redirect | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | 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
def fetch_avatar(url):
return requests.get(_checked(url), timeout=5, allow_redirects=Fals... |
ssrf_redirect_covers_alt | ssrf_redirect | covers_alt | safe | null | a second correct implementation, defended a different way | 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
def fetch_avatar(url):
r = requests.get(_checked(url), timeout=5, allow_redirects=True)
... |
ssrf_redirect_wrong_value | ssrf_redirect | wrong_value | unsafe | server-side request forgery | the guard is applied to a sibling value, not the one that reaches the sink | 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
def fetch_avatar(url, fallback):
_checked(fallback)
return requests.get(url, timeout=... |
ssrf_redirect_irrelevant | ssrf_redirect | irrelevant | unsafe | server-side request forgery | a guard is applied to the right value but does not address this weakness | 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
def fetch_avatar(url):
if not url.startswith("https://"):
raise ValueError("https... |
ssrf_redirect_elsewhere | ssrf_redirect | elsewhere | unsafe | server-side request forgery | the guard exists and is used by a neighbouring function, not on this path | 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
def fetch_manifest(url):
return requests.get(_checked(url), timeout=5, allow_redirects=Fa... |
csrf_missing_none | csrf_missing | none | unsafe | cross-site request forgery | no guard is applied on this path | 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
@app.post("/account/email")
def change_email(request):
request.user.em... |
csrf_missing_covers | csrf_missing | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | 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
@app.post("/account/email")
@require_csrf
def change_email(request):
r... |
csrf_missing_covers_alt | csrf_missing | covers_alt | safe | null | a second correct implementation, defended a different way | 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
@app.post("/account/email")
def change_email(request):
if request.head... |
csrf_missing_wrong_value | csrf_missing | wrong_value | unsafe | cross-site request forgery | the guard is applied to a sibling value, not the one that reaches the sink | 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
@app.post("/account/email")
def change_email(request):
if request.form... |
csrf_missing_irrelevant | csrf_missing | irrelevant | unsafe | cross-site request forgery | a guard is applied to the right value but does not address this weakness | 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
@app.post("/account/email")
def change_email(request):
if "@" not in r... |
csrf_missing_elsewhere | csrf_missing | elsewhere | unsafe | cross-site request forgery | the guard exists and is used by a neighbouring function, not on this path | 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
@app.post("/account/password")
@require_csrf
def change_password(request):... |
toctou_symlink_none | toctou_symlink | none | unsafe | time-of-check time-of-use | no guard is applied on this path | 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")
def save_upload(name, data):
path = os.path.join(SPOOL, name)
if os.path.exists(path):
raise FileExistsError(name)
... |
toctou_symlink_covers | toctou_symlink | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | 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")
def save_upload(name, data):
with _create_exclusive(os.path.join(SPOOL, name)) as fh:
fh.write(data) |
toctou_symlink_covers_alt | toctou_symlink | covers_alt | safe | null | a second correct implementation, defended a different way | 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")
def save_upload(name, data):
fd = os.open(os.path.join(SPOOL, name),
os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_... |
toctou_symlink_wrong_value | toctou_symlink | wrong_value | unsafe | time-of-check time-of-use | the guard is applied to a sibling value, not the one that reaches the sink | 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")
def save_upload(name, data, tmpname):
_create_exclusive(os.path.join(SPOOL, tmpname)).close()
with open(os.path.join(SPOOL, na... |
toctou_symlink_irrelevant | toctou_symlink | irrelevant | unsafe | time-of-check time-of-use | a guard is applied to the right value but does not address this weakness | 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")
def save_upload(name, data):
if "/" in name or name.startswith("."):
raise ValueError("bad name")
path = os.path.join(... |
toctou_symlink_elsewhere | toctou_symlink | elsewhere | unsafe | time-of-check time-of-use | the guard exists and is used by a neighbouring function, not on this path | 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")
def save_temp(name, data):
with _create_exclusive(os.path.join(SPOOL, name)) as fh:
fh.write(data)
def save_upload(name, ... |
unicode_bypass_none | unicode_bypass | none | unsafe | input validation bypass | no guard is applied on this path | import unicodedata, re
BLOCKED = re.compile(r"(?i)\b(admin|root|system)\b")
def _canonical(s):
return unicodedata.normalize("NFKC", s).casefold()
def register(username):
return create_user(username) |
unicode_bypass_covers | unicode_bypass | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | import unicodedata, re
BLOCKED = re.compile(r"(?i)\b(admin|root|system)\b")
def _canonical(s):
return unicodedata.normalize("NFKC", s).casefold()
def register(username):
canon = _canonical(username)
if BLOCKED.search(canon):
raise ValueError("reserved name")
return create_user(canon) |
unicode_bypass_covers_alt | unicode_bypass | covers_alt | safe | null | a second correct implementation, defended a different way | import unicodedata, re
BLOCKED = re.compile(r"(?i)\b(admin|root|system)\b")
def _canonical(s):
return unicodedata.normalize("NFKC", s).casefold()
def register(username):
canon = unicodedata.normalize("NFKC", username).casefold()
if BLOCKED.search(canon):
raise ValueError("reserved name")
retu... |
unicode_bypass_wrong_value | unicode_bypass | wrong_value | unsafe | input validation bypass | the guard is applied to a sibling value, not the one that reaches the sink | import unicodedata, re
BLOCKED = re.compile(r"(?i)\b(admin|root|system)\b")
def _canonical(s):
return unicodedata.normalize("NFKC", s).casefold()
def register(username, display):
if BLOCKED.search(_canonical(display)):
raise ValueError("reserved name")
return create_user(_canonical(username)) |
unicode_bypass_irrelevant | unicode_bypass | irrelevant | unsafe | input validation bypass | a guard is applied to the right value but does not address this weakness | import unicodedata, re
BLOCKED = re.compile(r"(?i)\b(admin|root|system)\b")
def _canonical(s):
return unicodedata.normalize("NFKC", s).casefold()
def register(username):
if len(username) > 32:
raise ValueError("too long")
return create_user(_canonical(username)) |
unicode_bypass_elsewhere | unicode_bypass | elsewhere | unsafe | input validation bypass | the guard exists and is used by a neighbouring function, not on this path | import unicodedata, re
BLOCKED = re.compile(r"(?i)\b(admin|root|system)\b")
def _canonical(s):
return unicodedata.normalize("NFKC", s).casefold()
def register_org(name):
canon = _canonical(name)
if BLOCKED.search(canon):
raise ValueError("reserved name")
return create_org(canon)
def register... |
cache_poisoning_none | cache_poisoning | none | unsafe | web cache poisoning | no guard is applied on this path | KEYED_HEADERS = ("Host", "Accept-Language")
def _cache_key(request):
parts = [request.path] + [request.headers.get(h, "") for h in KEYED_HEADERS]
return "|".join(parts)
def render_page(request):
key = request.path
if key in CACHE:
return CACHE[key]
body = build(request, base=request.header... |
cache_poisoning_covers | cache_poisoning | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | KEYED_HEADERS = ("Host", "Accept-Language")
def _cache_key(request):
parts = [request.path] + [request.headers.get(h, "") for h in KEYED_HEADERS]
return "|".join(parts)
def render_page(request):
key = _cache_key(request)
if key in CACHE:
return CACHE[key]
body = build(request, base=request... |
cache_poisoning_covers_alt | cache_poisoning | covers_alt | safe | null | a second correct implementation, defended a different way | KEYED_HEADERS = ("Host", "Accept-Language")
def _cache_key(request):
parts = [request.path] + [request.headers.get(h, "") for h in KEYED_HEADERS]
return "|".join(parts)
def render_page(request):
key = request.path + "|" + request.headers.get("Host", "")
if key in CACHE:
return CACHE[key]
b... |
cache_poisoning_wrong_value | cache_poisoning | wrong_value | unsafe | web cache poisoning | the guard is applied to a sibling value, not the one that reaches the sink | KEYED_HEADERS = ("Host", "Accept-Language")
def _cache_key(request):
parts = [request.path] + [request.headers.get(h, "") for h in KEYED_HEADERS]
return "|".join(parts)
def render_page(request):
key = _cache_key(request)
if key in CACHE:
return CACHE[key]
body = build(request, base=request... |
cache_poisoning_irrelevant | cache_poisoning | irrelevant | unsafe | web cache poisoning | a guard is applied to the right value but does not address this weakness | KEYED_HEADERS = ("Host", "Accept-Language")
def _cache_key(request):
parts = [request.path] + [request.headers.get(h, "") for h in KEYED_HEADERS]
return "|".join(parts)
def render_page(request):
if len(request.path) > 512:
raise ValueError("path too long")
key = request.path
if key in CACH... |
cache_poisoning_elsewhere | cache_poisoning | elsewhere | unsafe | web cache poisoning | the guard exists and is used by a neighbouring function, not on this path | KEYED_HEADERS = ("Host", "Accept-Language")
def _cache_key(request):
parts = [request.path] + [request.headers.get(h, "") for h in KEYED_HEADERS]
return "|".join(parts)
def render_asset(request):
key = _cache_key(request)
return CACHE.setdefault(key, build_asset(request))
def render_page(request):
... |
int_overflow_none | int_overflow | none | unsafe | integer overflow in size check | no guard is applied on this path | 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
def allocate_frames(count, unit):
return bytearray(count * unit) |
int_overflow_covers | int_overflow | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | 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
def allocate_frames(count, unit):
_fits(count, unit)
return bytearray(count * unit) |
int_overflow_covers_alt | int_overflow | covers_alt | safe | null | a second correct implementation, defended a different way | 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
def allocate_frames(count, unit):
if count < 0 or unit < 0 or count > MAX_TOTAL // max(unit, ... |
int_overflow_wrong_value | int_overflow | wrong_value | unsafe | integer overflow in size check | the guard is applied to a sibling value, not the one that reaches the sink | 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
def allocate_frames(count, unit, stride):
_fits(count, stride)
return bytearray(count * u... |
int_overflow_irrelevant | int_overflow | irrelevant | unsafe | integer overflow in size check | a guard is applied to the right value but does not address this weakness | 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
def allocate_frames(count, unit):
if count * unit > MAX_TOTAL:
raise ValueError("too ... |
int_overflow_elsewhere | int_overflow | elsewhere | unsafe | integer overflow in size check | the guard exists and is used by a neighbouring function, not on this path | 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
def allocate_tiles(count, unit):
_fits(count, unit)
return bytearray(count * unit)
def a... |
sig_skip_branch_none | sig_skip_branch | none | unsafe | missing signature verification | no guard is applied on this path | 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
... |
sig_skip_branch_covers | sig_skip_branch | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | 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
... |
sig_skip_branch_covers_alt | sig_skip_branch | covers_alt | safe | null | a second correct implementation, defended a different way | 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
... |
sig_skip_branch_wrong_value | sig_skip_branch | wrong_value | unsafe | missing signature verification | the guard is applied to a sibling value, not the one that reaches the sink | 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
... |
sig_skip_branch_irrelevant | sig_skip_branch | irrelevant | unsafe | missing signature verification | a guard is applied to the right value but does not address this weakness | 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
... |
sig_skip_branch_elsewhere | sig_skip_branch | elsewhere | unsafe | missing signature verification | the guard exists and is used by a neighbouring function, not on this path | 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
... |
reset_token_reuse_none | reset_token_reuse | none | unsafe | authentication bypass | no guard is applied on this path | 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
def apply_reset(token, new_password):
ui... |
reset_token_reuse_covers | reset_token_reuse | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | 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
def apply_reset(token, new_password):
ui... |
reset_token_reuse_covers_alt | reset_token_reuse | covers_alt | safe | null | a second correct implementation, defended a different way | 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
def apply_reset(token, new_password):
ro... |
reset_token_reuse_wrong_value | reset_token_reuse | wrong_value | unsafe | authentication bypass | the guard is applied to a sibling value, not the one that reaches the sink | 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
def apply_reset(token, confirm_token, new_pa... |
reset_token_reuse_irrelevant | reset_token_reuse | irrelevant | unsafe | authentication bypass | a guard is applied to the right value but does not address this weakness | 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
def apply_reset(token, new_password):
ro... |
reset_token_reuse_elsewhere | reset_token_reuse | elsewhere | unsafe | authentication bypass | the guard exists and is used by a neighbouring function, not on this path | 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
def apply_invite(token):
uid = _consume(... |
dict_merge_none | dict_merge | none | unsafe | mass assignment | no guard is applied on this path | 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
re... |
dict_merge_covers | dict_merge | covers | safe | null | the guard is applied to the tainted value and addresses the weakness | 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
re... |
dict_merge_covers_alt | dict_merge | covers_alt | safe | null | a second correct implementation, defended a different way | 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
re... |
dict_merge_wrong_value | dict_merge | wrong_value | unsafe | mass assignment | the guard is applied to a sibling value, not the one that reaches the sink | 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
re... |
GuardBench
A benchmark for one question: can the model follow a guard?
Every failure worth caring about that we measured on real code in August 2026 was a guard question, in one direction or the other:
- the base and LOREA Pilot announced disabled TLS in code that passes its SSL context correctly, a symlink escape in code with realpath+commonpath confinement ten lines above the call, and a spoofable forwarded header behind a loopback gate. Guard present, guard unread.
- Ginko v1 cleared a real timing attack because
startswith("Bearer ")sat on the tainted path. Guard present, guard irrelevant, cleared anyway.
FBE cannot see either. In a 50-token snippet the guard and the sink are adjacent and the example is too short to miss one, so FBE-safe reports about 3 percent false alarms while the same model gets three of four wrong on a 1,500-line file. GuardBench puts distance between the guard and the sink, because distance is what the failure needs.
The six shapes
120 items: 20 patterns across 19 vulnerability classes, six shapes each.
| shape | guard | correct verdict | what it catches |
|---|---|---|---|
none |
absent | VULNERABLE | baseline: can it find anything |
covers |
present, applied, sufficient | SAFE | false alarms on defended code |
covers_alt |
a second correct implementation, defended differently | SAFE | as above, so one wrong answer does not move the rate 12 points |
wrong_value |
present, applied to a sibling value | VULNERABLE | the tainted value slipped past |
irrelevant |
present, applied to the right value, does not address the weakness | VULNERABLE | mistaking a format check for a control |
elsewhere |
defined and used in this file, not on this path | VULNERABLE | helper exists, call site skips it |
irrelevant is the shape no existing corpus has and the one Ginko fails. covers is the shape
the base and Pilot fail.
Rules that make it scoreable
Distance is required. In every item the guard is a helper defined above, a decorator, a branch several lines up, or a constant declared at module scope. Never the line before the sink.
Verdicts are parsed, never matched. Every item requires a final VERDICT: VULNERABLE <class>
or VERDICT: SAFE line. A missing line is a scored failure, not a guess. The FBE grader counted
"does not contain any vulnerabilities" as claiming a vulnerability, and no benchmark here will
repeat that.
Three prompt phrasings per item. Ginko dropped its verdict line on 48 of 65 FBE items purely because the harness said "Analyze this code for security issues" where its training said "Review this code for security problems". A model that only works on one phrasing is not working, and the benchmark should show that rather than reward it.
Ground truth by construction. Each item is written as a base plus a delta that defines the label. Nothing here is labelled by a model or by judgement.
No overlap with anything a model here was trained or selected on. Checked by 7-gram shingle overlap against all 459 Cyber training seeds and all 169 FBE items: worst overlap 0 percent. One pattern was rewritten when its HMAC helper measured 29 percent against a training seed.
Scoring
Report four numbers, and never one alone:
accuracy over all items
false alarms on `covers` only - the base/Pilot failure
missed on `irrelevant` - the Ginko failure
no-verdict rate over all prompt variants - brittleness
Verified against degenerate strategies: always-VULNERABLE scores 67 percent raw and 50 percent balanced; always-SAFE scores 33 percent raw and 50 percent balanced. Raw accuracy is printed but should never be quoted alone.
Running it
python3 guardbench/run.py --tag <name> [--model <path>] [--adapter <path>] [--prompts 1|2|3]
Generations are appended to results/partial_<tag>.jsonl as they complete, and a re-run skips
what is already there. An interrupted run resumes rather than starting over. --prompts 1 drops
the brittleness measurement and cuts the run to a third.
To score a partial or finished run without generating anything:
python3 -c "import json,sys; sys.path.insert(0,'guardbench'); import run; \
rows=[json.loads(l) for l in open('guardbench/results/partial_<tag>.jsonl')]; \
run.report(rows,'<tag>')"
- Downloads last month
- 72