File size: 7,144 Bytes
8df6aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d38f080
8df6aa0
 
 
 
 
d38f080
8df6aa0
 
d38f080
 
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
#!/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()