#!/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", ""))
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 "