AppSecBench / scripts /build.py
ismailtasdelen's picture
Upload folder using huggingface_hub
d38f080 verified
Raw
History Blame Contribute Delete
7.14 kB
#!/usr/bin/env python3
"""AppSecBench v1.0.0 build: generate train/validation/test JSONL splits.
Design:
- Enumerate every (vuln x language x framework x difficulty) combination that
is realistic per vuln_catalog.applicable_*.
- Render each with generators.build_case using a deterministic seed so the
dataset is fully reproducible (re-running yields identical records).
- Inject CVSS 3.1 vector+score.
- Assign ASB-000001 sequential ids.
- Split with a fixed seed: test 12%, validation 12%, rest train.
- Write JSONL + a manifest.
"""
from __future__ import annotations
import json
import os
import random
from collections import defaultdict
from vuln_catalog import (CATALOG, applicable_languages, applicable_frameworks,
DIFFICULTIES)
from generators import build_case
from ruby_scala_gen import generic_ruby_scala
from cvss import cvss_for
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATASET_DIR = os.path.join(ROOT, "dataset")
SEED = 42
VERSION = "1.1.0"
# How many (language/framework) variations to draw per vuln at each difficulty.
# v1.1.0 raises caps vs v1.0.0 and adds Ruby/Rails + Scala/Spring Boot + Angular/Vue,
# growing coverage to ~900 records while keeping the dataset balanced.
PER_VULN_PER_DIFFICULTY = {
"Beginner": 4,
"Intermediate": 4,
"Advanced": 3,
"Expert": 3,
"Real-world enterprise": 3,
}
def iter_combos():
for vuln, *_ in CATALOG:
langs = applicable_languages(vuln)
# Give each vuln a stable per-language framework rotation.
for lang in langs:
fws = applicable_frameworks(vuln, lang)
for fw in fws:
for diff in DIFFICULTIES:
yield vuln, lang, fw, diff
def main():
# Group combos by (vuln, difficulty) to apply per-vuln sampling counts.
groups = defaultdict(list)
for vuln, lang, fw, diff in iter_combos():
groups[(vuln, diff)].append((vuln, lang, fw, diff))
rng = random.Random(SEED)
selected = []
for (vuln, diff), combos in groups.items():
# shuffle deterministically then take a cap
c = list(combos)
rng.shuffle(c)
cap = PER_VULN_PER_DIFFICULTY.get(diff, 2)
selected.extend(c[:cap])
# Globally shuffle for id assignment determinism
rng.shuffle(selected)
records = []
gen_errors = []
for idx, (vuln, lang, fw, diff) in enumerate(selected, start=1):
bid = f"ASB-{idx:06d}"
try:
case = build_case(vuln, lang, fw, diff, seed=hash((bid, vuln, lang, fw, diff)) & 0xFFFF)
except Exception as e:
gen_errors.append(f"{vuln}|{lang}|{fw}|{diff}: {type(e).__name__}: {e}")
continue
vector, score = cvss_for(vuln, diff)
severity = _sev_label(vuln, diff, score)
rec = {
"benchmark_id": bid,
"title": case["title"],
"category": case["category"],
"language": lang,
"framework": case["framework"],
"application_type": case["application_type"],
"source_type": case["source_type"],
"vulnerability_name": case["vulnerability_name"],
"vulnerability_description": case["vulnerability_description"],
"vulnerable_code": case["vulnerable_code"],
"secure_code": case["secure_code"],
"exploit_example": case["exploit_example"],
"exploitability_explanation": case["exploitability_explanation"],
"attack_prerequisites": case["attack_prerequisites"],
"expected_llm_analysis": case["expected_llm_analysis"],
"expected_detection": case["expected_detection"],
"expected_fix": case["expected_fix"],
"expected_secure_code": case["expected_secure_code"],
"expected_severity": severity,
"expected_confidence": case["expected_confidence"],
"expected_cwe": case["expected_cwe"],
"expected_owasp": case["expected_owasp"],
"expected_owasp_api": case["expected_owasp_api"],
"expected_owasp_llm": case["expected_owasp_llm"],
"expected_cvss": vector,
"expected_cvss_score": score,
"expected_false_positive_probability": case["expected_false_positive_probability"],
"expected_false_negative_probability": case["expected_false_negative_probability"],
"evaluation_rubric": case["evaluation_rubric"],
"scoring_criteria": case["scoring_criteria"],
"tags": case["tags"],
"references": case["references"],
"metadata": {
"difficulty": diff,
"category": case["category"],
"owasp": case["expected_owasp"],
"owasp_api": case["expected_owasp_api"],
"owasp_llm": case["expected_owasp_llm"],
"cwe": case["expected_cwe"],
"cvss_vector": vector,
"cvss_score": score,
"generated_by": "AppSecBench generator v1.1.0",
"source": "original/synthetic",
"license": "MIT",
"schema_version": "1.1.0",
},
}
records.append(rec)
# Split
split_rng = random.Random(SEED + 1)
items = list(records)
split_rng.shuffle(items)
n = len(items)
n_test = max(1, round(n * 0.12))
n_val = max(1, round(n * 0.12))
test = items[:n_test]
val = items[n_test:n_test + n_val]
train = items[n_test + n_val:]
os.makedirs(DATASET_DIR, exist_ok=True)
for name, split in (("train", train), ("validation", val), ("test", test)):
path = os.path.join(DATASET_DIR, f"{name}.jsonl")
with open(path, "w", encoding="utf-8") as f:
for r in split:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print(f"Wrote {len(split):4d} -> {name}.jsonl")
if gen_errors:
print(f"\n=== GENERATION ERRORS ({len(gen_errors)}) ===")
for e in gen_errors:
print(" ", e)
manifest = {
"name": "AppSecBench",
"version": VERSION,
"total_records": n,
"splits": {"train": len(train), "validation": len(val), "test": len(test)},
"seed": SEED,
"languages": sorted({r["language"] for r in records}),
"frameworks": sorted({r["framework"] for r in records if r["framework"] != "None"}),
"vulnerabilities": sorted({r["vulnerability_name"] for r in records}),
"difficulties": DIFFICULTIES,
}
with open(os.path.join(ROOT, "manifest.json"), "w", encoding="utf-8") as f:
json.dump(manifest, f, indent=2)
print(f"Total {n} records. Manifest written.")
return manifest
def _sev_label(vuln, diff, score):
# Use the CVSS base score to derive severity, but keep a floor aligned with
# the weakness type (e.g. XSS is rarely Critical).
if score >= 9.0:
return "Critical"
if score >= 7.0:
return "High"
if score >= 4.0:
return "Medium"
return "Low"
if __name__ == "__main__":
main()