#!/usr/bin/env python3 """Build GuardBench items: 20 patterns x 6 shapes. Ground truth is set by the delta, not by judgement. The guard is always at distance from the sink - a helper above, a decorator, a module constant, or a branch several lines up - because a guard adjacent to its sink cannot be missed and that is exactly why FBE could not measure this. """ import json, ast, os, sys, hashlib from collections import Counter HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import build_items_v1 as V1 from patterns_v2 import P2 from covers_alt_v1 import COVERS_ALT SHAPES = ["none", "covers", "covers_alt", "wrong_value", "irrelevant", "elsewhere"] LABEL = {"none":"unsafe", "covers":"safe", "covers_alt":"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", "covers_alt": "a second correct implementation, defended a different way", "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() def add(name, cls, shape, code): h = hashlib.sha1(code.encode()).hexdigest()[:12] if h in seen: return seen.add(h) out.append({"id": f"{name}_{shape}", "pattern": name, "shape": shape, "label": LABEL[shape], "vuln_class": cls if LABEL[shape]=="unsafe" else None, "why": WHY[shape], "code": code}) for fn in V1.P: # 8 v1 patterns, 5 shapes + covers_alt cls, *variants = fn(None) for shape, code in zip(["none","covers","wrong_value","irrelevant","elsewhere"], variants): add(fn.__name__, cls, shape, code) alt = COVERS_ALT.get(fn.__name__) if alt: add(fn.__name__, cls, "covers_alt", alt) for fn in P2: # 12 v2 patterns, 6 shapes cls, d = fn(None) for shape in SHAPES: if shape in d: add(fn.__name__, cls, shape, d[shape]) 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.join(HERE, "items.jsonl") with open(p, "w") as fh: for r in rows: fh.write(json.dumps(r)+"\n") lab = Counter(r["label"] for r in rows) print(f"items: {len(rows)} -> {p}") print("patterns:", len({r['pattern'] for r in rows})) print("shape :", dict(Counter(r['shape'] for r in rows))) print("label :", dict(lab), f" safe share {lab['safe']/len(rows):.0%}") print(f"classes: {len({r['vuln_class'] for r in rows if r['vuln_class']})}") print(f"syntax errors: {len(bad)}") for i,e in bad[:6]: print(" ", i, e)