AppSecBench / scripts /evaluate.py
ismailtasdelen's picture
Upload folder using huggingface_hub
8df6aa0 verified
Raw
History Blame Contribute Delete
6.35 kB
#!/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()