File size: 6,346 Bytes
8df6aa0 | 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 | #!/usr/bin/env python3
"""AppSecBench v1.0.0 evaluator.
Usage:
python scripts/evaluate.py dataset/test.jsonl --predictions predictions.jsonl
predictions.jsonl: one JSON per line:
{"benchmark_id": "ASB-000001", "output": "<free-text model/tool response>",
"secure_code": "<optional generated fix>"}
Scoring (weighted rubric, max 100):
- Vulnerability correctly identified (15)
- CWE correctly identified (10)
- OWASP correctly mapped (10)
- Severity correctly estimated (10)
- Exploit explained correctly (10)
- Secure fix generated (20)
- Secure code quality (10)
- Explanation quality (10)
- False-positive avoidance (5)
A simple, transparent grader is included (substring/keyword matching plus an
LLM-callable hook). Replace `grade_response` with your own scorer (e.g. an LLM
judge) for production use. Output: per-record scores + aggregate leaderboard
written to evaluation/results.json.
"""
from __future__ import annotations
import argparse
import json
import os
import re
from collections import defaultdict
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EVAL_DIR = os.path.join(ROOT, "evaluation")
def norm(s: str) -> str:
return (s or "").lower()
def grade_response(rec: dict, pred: dict, verbose: bool = False) -> dict:
"""Transparent keyword/format-based grader. Swap for an LLM judge in prod."""
out = norm(pred.get("output", ""))
vname = rec["vulnerability_name"]
cwe = rec["expected_cwe"]
owasp = rec["expected_owasp"]
sev = rec["expected_severity"]
scores = {}
# 1. Vulnerability identified (substring of the vuln name tokens)
tokens = [t for t in re.split(r"[^a-z0-9+]", vname.lower()) if len(t) > 3]
hit = any(t in out for t in tokens) or vname.lower() in out
scores["vuln_identified"] = 15 if hit else 0
# 2. CWE
scores["cwe"] = 10 if cwe.lower() in out else 0
# 3. OWASP
scores["owasp"] = 10 if owasp.lower() in out else 0
# 4. Severity
scores["severity"] = 10 if sev.lower() in out else 0
# 5. Exploit explained (mentions attack prereq keywords)
prereq = norm(rec["attack_prerequisites"])
kw = [w for w in re.findall(r"[a-z]{4,}", prereq) if w not in ("this", "with", "from", "able")]
scores["exploit"] = 10 if sum(k in out for k in kw[:5]) >= 2 else 0
# 6. Secure fix generated (a code-looking block present and differs from vuln)
gen = norm(pred.get("secure_code", ""))
has_code = ("def " in gen or "function" in gen or "func " in gen or "public" in gen
or "void" in gen or "```" in norm(pred.get("output", "")))
scores["fix_generated"] = 20 if has_code else 0
# 7. Secure code quality (heuristic: fix mentions a safe primitive)
safe_kw = ["parameter", "prepared", "allowlist", "allow-list", "escape", "verify",
"hash", "bcrypt", "hmac", "aes-gcm", "gcm", "sanitiz", "canonical",
"owner", "authoriz", "rate", "limit", "csrf", "nonce", "https", "secure"]
scores["fix_quality"] = 10 if sum(k in gen for k in safe_kw) >= 1 else 0
# 8. Explanation quality (length + structure)
scores["explanation"] = 10 if len(out.split()) >= 25 else (5 if len(out.split()) >= 10 else 0)
# 9. False-positive avoidance (has a 'secure' / 'not vulnerable' acknowledgement ability)
scores["fp_avoidance"] = 5 if ("not vulnerable" in out or "no issue" in out or "secure" in out) else 0
total = sum(scores.values())
if verbose:
print(f" {rec['benchmark_id']}: {total}/100 {scores}")
return {"total": total, "breakdown": scores}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("dataset")
ap.add_argument("--predictions", required=True)
ap.add_argument("--out", default=os.path.join(EVAL_DIR, "results.json"))
ap.add_argument("--verbose", action="store_true")
args = ap.parse_args()
recs = {}
with open(args.dataset, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
r = json.loads(line)
recs[r["benchmark_id"]] = r
preds = {}
with open(args.predictions, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
p = json.loads(line)
preds[p["benchmark_id"]] = p
results = []
agg = defaultdict(list)
for bid, rec in recs.items():
pred = preds.get(bid)
if not pred:
continue
g = grade_response(rec, pred, args.verbose)
results.append({"benchmark_id": bid, "score": g["total"], "breakdown": g["breakdown"]})
agg[rec["language"]].append(g["total"])
agg[rec["vulnerability_name"]].append(g["total"])
agg[rec["metadata"]["difficulty"]].append(g["total"])
overall = sum(r["score"] for r in results) / max(len(results), 1)
per_lang = {k: round(sum(v) / len(v), 1) for k, v in agg.items() if k in recs_langs(recs)}
per_lang = {k: round(sum(v) / len(v), 1) for k, v in
{kk: vv for kk, vv in agg.items() if kk in {r["language"] for r in recs.values()}}.items()}
per_vuln = {k: round(sum(v) / len(v), 1) for k, v in
{kk: vv for kk, vv in agg.items() if kk in {r["vulnerability_name"] for r in recs.values()}}.items()}
per_diff = {k: round(sum(v) / len(v), 1) for k, v in
{kk: vv for kk, vv in agg.items() if kk in {r["metadata"]["difficulty"] for r in recs.values()}}.items()}
os.makedirs(EVAL_DIR, exist_ok=True)
with open(args.out, "w", encoding="utf-8") as f:
json.dump({
"overall_score": round(overall, 2),
"n_scored": len(results),
"per_language": per_lang,
"per_vulnerability": per_vuln,
"per_difficulty": per_diff,
"results": results,
}, f, indent=2)
print(f"Scored {len(results)}/{len(recs)} records.")
print(f"Overall: {overall:.1f}/100")
print(f"By language: {per_lang}")
print(f"By difficulty: {per_diff}")
print(f"Written -> {args.out}")
def recs_langs(recs):
return {r["language"] for r in recs.values()}
if __name__ == "__main__":
main()
|