File size: 10,796 Bytes
8df6aa0 d38f080 8df6aa0 d38f080 8df6aa0 d38f080 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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | #!/usr/bin/env python3
"""AppSecBench v1.1.0 validation + QA report.
Checks (full list documented in the dataset card / docs/methodology.md):
- JSON validity & duplicate ids
- All required fields present & non-empty
- Enums: language, framework, severity, difficulty, confidence, source_type
- CWE / OWASP / OWASP-API / OWASP-LLM format
- CVSS 3.1 vector format + recomputed score consistency vs expected_cvss_score
- Reference URLs well-formed
- Tag list non-empty; vulnerable != secure; label consistency vs catalog
- Metadata completeness & internal consistency
- Syntax checks per language via compile_check
Emits validation_report.md + validation_summary.json under validation/.
"""
from __future__ import annotations
import json
import os
import re
from collections import Counter
import compile_check
from vuln_catalog import CATALOG_BY_NAME
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATASET_DIR = os.path.join(ROOT, "dataset")
VALID_DIR = os.path.join(ROOT, "validation")
REQUIRED = [
"benchmark_id", "title", "category", "language", "framework", "application_type",
"source_type", "vulnerability_name", "vulnerability_description", "vulnerable_code",
"secure_code", "exploit_example", "exploitability_explanation", "attack_prerequisites",
"expected_llm_analysis", "expected_detection", "expected_fix", "expected_secure_code",
"expected_severity", "expected_confidence", "expected_cwe", "expected_owasp",
"expected_cvss", "expected_cvss_score", "expected_false_positive_probability",
"expected_false_negative_probability", "evaluation_rubric", "scoring_criteria",
"tags", "references", "metadata",
]
LANGUAGES = {"Python", "Java", "JavaScript", "TypeScript", "Go", "Rust", "PHP",
"C#", "Kotlin", "Swift", "C", "C++", "Ruby", "Scala", "YAML", "Dockerfile", "Bash"}
FRAMEWORKS = {"Flask", "FastAPI", "Django", "Spring Boot", "Express", "NestJS",
"Next.js", "Laravel", "ASP.NET Core", "Gin", "Echo", "Fiber",
"Android", "iOS", "Rails", "Angular", "Vue", "None", ""}
SEVERITIES = {"Low", "Medium", "High", "Critical"}
DIFFICULTIES = {"Beginner", "Intermediate", "Advanced", "Expert", "Real-world enterprise"}
CONFIDENCES = {"Low", "Medium", "High"}
SOURCE_TYPES = {"synthetic", "recreated", "educational"}
CVSS_RE = re.compile(r"^CVSS:3\.1/AV:[NALP]/AC:[LH]/PR:[NLH]/UI:[NR]/S:[CU]/C:[NLH]/I:[NLH]/A:[NLH]$")
CWE_RE = re.compile(r"^CWE-\d+$")
OWASP_RE = re.compile(r"^A\d{2}:2021$")
OWASP_API_RE = re.compile(r"^API\d{1,2}:2023$")
OWASP_LLM_RE = re.compile(r"^LLM\d{2}:2025$")
URL_RE = re.compile(r"^https?://[^\s]+$")
SPLITS = ("train", "validation", "test")
def recompute_cvss_score(vector: str) -> float:
from cvss import compute_base_vector
parts = dict(p.split(":") for p in vector.split("/")[1:])
_, score = compute_base_vector(av=parts["AV"], ac=parts["AC"], pr=parts["PR"],
ui=parts["UI"], s=parts["S"], c=parts["C"],
i=parts["I"], a=parts["A"])
return score
def main():
errors, warnings = [], []
all_ids, all_recs = Counter(), []
for name in SPLITS:
path = os.path.join(DATASET_DIR, f"{name}.jsonl")
with open(path, encoding="utf-8") as f:
for i, line in enumerate(f, 1):
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
except json.JSONDecodeError as e:
errors.append(f"{name}:{i}: bad JSON {e}")
continue
all_recs.append(obj)
rid = obj.get("benchmark_id", f"<no-id:{name}:{i}>")
all_ids[rid] += 1
for fld in REQUIRED:
v = obj.get(fld)
if isinstance(v, str) and not v.strip():
errors.append(f"{rid}: empty {fld}")
elif v is None:
errors.append(f"{rid}: missing {fld}")
if obj.get("language") not in LANGUAGES:
errors.append(f"{rid}: bad language {obj.get('language')}")
if obj.get("framework") not in FRAMEWORKS:
errors.append(f"{rid}: bad framework {obj.get('framework')}")
if obj.get("expected_severity") not in SEVERITIES:
errors.append(f"{rid}: bad severity {obj.get('expected_severity')}")
diff = obj.get("metadata", {}).get("difficulty")
if diff not in DIFFICULTIES:
errors.append(f"{rid}: bad difficulty {diff}")
if obj.get("expected_confidence") not in CONFIDENCES:
errors.append(f"{rid}: bad confidence {obj.get('expected_confidence')}")
if obj.get("source_type") not in SOURCE_TYPES:
errors.append(f"{rid}: bad source_type {obj.get('source_type')}")
if not CWE_RE.match(obj.get("expected_cwe", "")):
errors.append(f"{rid}: bad cwe {obj.get('expected_cwe')}")
if not OWASP_RE.match(obj.get("expected_owasp", "")):
errors.append(f"{rid}: bad owasp {obj.get('expected_owasp')}")
owl = obj.get("expected_owasp_llm", "")
if owl and not OWASP_LLM_RE.match(owl):
warnings.append(f"{rid}: odd owasp_llm {owl}")
oapi = obj.get("expected_owasp_api", "")
if oapi and not OWASP_API_RE.match(oapi):
warnings.append(f"{rid}: odd owasp_api {oapi}")
cvss = obj.get("expected_cvss", "")
if not CVSS_RE.match(cvss):
errors.append(f"{rid}: bad cvss vector {cvss}")
else:
try:
recomputed = recompute_cvss_score(cvss)
stated = float(obj.get("expected_cvss_score", -1))
if abs(recomputed - stated) > 0.05:
errors.append(f"{rid}: cvss score mismatch recomputed={recomputed} stated={stated}")
except Exception as e:
errors.append(f"{rid}: cvss recompute failed {e}")
refs = obj.get("references", [])
if not isinstance(refs, list) or not refs:
errors.append(f"{rid}: references must be non-empty list")
else:
for u in refs:
if not URL_RE.match(str(u)):
warnings.append(f"{rid}: odd reference {u}")
if not isinstance(obj.get("tags"), list) or not obj["tags"]:
errors.append(f"{rid}: tags must be non-empty list")
if obj.get("vulnerable_code") == obj.get("secure_code"):
errors.append(f"{rid}: vulnerable_code equals secure_code")
cat = CATALOG_BY_NAME.get(obj.get("vulnerability_name", ""))
if cat:
if obj.get("expected_cwe") != cat["cwe"]:
errors.append(f"{rid}: cwe mismatch catalog")
if obj.get("expected_owasp") != cat["owasp"]:
errors.append(f"{rid}: owasp mismatch catalog")
else:
errors.append(f"{rid}: unknown vulnerability_name {obj.get('vulnerability_name')}")
md = obj.get("metadata", {})
if md.get("cwe") != obj.get("expected_cwe"):
errors.append(f"{rid}: metadata.cwe mismatch")
if md.get("cvss_vector") != cvss:
errors.append(f"{rid}: metadata.cvss_vector mismatch")
if not isinstance(md.get("cvss_score"), (int, float)):
errors.append(f"{rid}: metadata.cvss_score missing")
for fld in ("vulnerable_code", "secure_code"):
code = obj.get(fld, "")
ok, detail = compile_check.check(obj.get("language"), code)
if ok is False:
errors.append(f"{rid}: {fld} [{obj.get('language')}] {detail}")
elif ok is None:
warnings.append(f"{rid}: {fld} [{obj.get('language')}] unchecked ({detail})")
for rid, c in all_ids.items():
if c > 1:
errors.append(f"duplicate id {rid} x{c}")
stats = {
"total_records": len(all_recs),
"by_language": dict(Counter(r["language"] for r in all_recs)),
"by_framework": dict(Counter(r["framework"] for r in all_recs if r["framework"] != "None")),
"by_severity": dict(Counter(r["expected_severity"] for r in all_recs)),
"by_cwe": dict(Counter(r["expected_cwe"] for r in all_recs)),
"by_owasp": dict(Counter(r["expected_owasp"] for r in all_recs)),
"by_category": dict(Counter(r["category"] for r in all_recs)),
"by_difficulty": dict(Counter(r["metadata"]["difficulty"] for r in all_recs)),
"by_vulnerability": dict(Counter(r["vulnerability_name"] for r in all_recs)),
"unique_cwe": sorted({r["expected_cwe"] for r in all_recs}),
"unique_owasp": sorted({r["expected_owasp"] for r in all_recs}),
"unique_vulnerabilities": sorted({r["vulnerability_name"] for r in all_recs}),
}
os.makedirs(VALID_DIR, exist_ok=True)
with open(os.path.join(VALID_DIR, "validation_summary.json"), "w", encoding="utf-8") as f:
json.dump({"errors": errors, "warnings": warnings, "stats": stats}, f, indent=2, ensure_ascii=False)
status = "PASS" if not errors else "FAIL"
report_lines = (
["# AppSecBench Validation Report", "", f"**Status:** {status}",
f"**Records:** {stats['total_records']}",
f"**Errors:** {len(errors)} | **Warnings:** {len(warnings)}", "",
"## Distributions", "",
f"- Languages: {len(stats['by_language'])}", f"- Frameworks: {len(stats['by_framework'])}",
f"- CWEs: {len(stats['unique_cwe'])}", f"- OWASP: {len(stats['unique_owasp'])}",
f"- Vulnerabilities: {len(stats['unique_vulnerabilities'])}", "",
"## Errors"]
+ ([f"- {e}" for e in errors] or ["(none)"]) + [""]
+ ["## Warnings (sample)"]
+ ([f"- {w}" for w in warnings[:50]] or ["(none)"])
)
with open(os.path.join(VALID_DIR, "validation_report.md"), "w", encoding="utf-8") as f:
f.write("\n".join(report_lines))
print(status)
print(f"records={stats['total_records']} errors={len(errors)} warnings={len(warnings)}")
for e in errors[:30]:
print(" ERR", e)
return 0 if status == "PASS" else 1
if __name__ == "__main__":
raise SystemExit(main())
|