Files
ResearchMethods_Project/validation/export_sast_tools.py
T

677 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Export Bandit and Semgrep findings to raw, per-sample, and SPSS-ready files.
The per-sample "flagged" variable means: the tool produced at least one finding
that maps to one of the prompt's nine target categories. Raw findings are kept
separately, including out-of-scope rules, so the mapping can be audited.
Usage:
python3 validation/export_sast_tools.py
"""
from __future__ import annotations
import argparse
import csv
import json
import re
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parents[1]
DEFAULT_EXPECTED = BASE_DIR / "data" / "expectedresults-0.1.csv"
DEFAULT_BANDIT = BASE_DIR / "validation" / "bandit"
DEFAULT_SEMGREP = BASE_DIR / "validation" / "semgrep"
DEFAULT_OUTPUT = BASE_DIR / "validation" / "sast_tools"
CATEGORY_CODES = {
"None": 0,
"pathtraver": 1,
"sqli": 2,
"xpathi": 3,
"xxe": 4,
"cmdi": 5,
"deserialization": 6,
"xss": 7,
"weakrand": 8,
"trustbound": 9,
"hash": 10,
"codeinj": 11,
"securecookie": 12,
"redirect": 13,
"ldapi": 14,
}
OTHER_CATEGORY_CODE = 99
CWE_TO_CATEGORY = {
22: "pathtraver",
89: "sqli",
643: "xpathi",
611: "xxe",
78: "cmdi",
502: "deserialization",
79: "xss",
330: "weakrand",
501: "trustbound",
328: "hash",
94: "codeinj",
614: "securecookie",
601: "redirect",
90: "ldapi",
# Scanners commonly report CWE-327 for weak hash; the benchmark uses 328.
327: "hash",
}
CATEGORY_TO_CWE = {
"pathtraver": "CWE-22",
"sqli": "CWE-89",
"xpathi": "CWE-643",
"xxe": "CWE-611",
"cmdi": "CWE-78",
"deserialization": "CWE-502",
"xss": "CWE-79",
"weakrand": "CWE-330",
"trustbound": "CWE-501",
"hash": "CWE-328",
"codeinj": "CWE-94",
"securecookie": "CWE-614",
"redirect": "CWE-601",
"ldapi": "CWE-90",
}
# Bandit has no general taint engine, so rules are mapped explicitly rather than
# relying on issue_cwe (for example B102/B307/B404 all report CWE-78 but are not
# command-injection findings in the benchmark sense).
BANDIT_RULE_CATEGORY = {
"B608": "sqli",
"B301": "deserialization",
"B403": "deserialization",
"B506": "deserialization",
"B102": "codeinj",
"B307": "codeinj",
"B324": "hash",
"B311": "weakrand",
"B602": "cmdi",
"B603": "cmdi",
"B605": "cmdi",
"B607": "cmdi",
"B609": "cmdi",
"B610": "cmdi",
"B611": "cmdi",
"B313": "xxe",
"B314": "xxe",
"B315": "xxe",
"B316": "xxe",
"B317": "xxe",
"B318": "xxe",
"B319": "xxe",
"B320": "xxe",
"B701": "xss",
"B308": "xss",
}
BANDIT_SEVERITY = {"LOW": 1, "MEDIUM": 2, "HIGH": 3}
SEMGREP_SEVERITY = {"INFO": 1, "WARNING": 2, "ERROR": 3}
TOOLS = {
"bandit": {
"code": 0,
"label": "Bandit",
"original": "samples.json",
"obfuscated": "obfuscated_v2.json",
},
"semgrep": {
"code": 1,
"label": "Semgrep",
"original": "samples.json",
"obfuscated": "obfuscated_v2.json",
},
}
def category_code(value: str | None) -> int:
if value is None:
return 0
return CATEGORY_CODES.get(value, OTHER_CATEGORY_CODE)
def parse_cwes(values: list[str] | None) -> list[int]:
result: list[int] = []
for value in values or []:
match = re.search(r"CWE-(\d+)", str(value), re.IGNORECASE)
if match:
result.append(int(match.group(1)))
return result
def load_expected(path: Path) -> dict[str, dict[str, str]]:
labels: dict[str, dict[str, str]] = {}
with path.open("r", encoding="utf-8", newline="") as handle:
for row in csv.reader(handle):
if not row or not row[0].strip() or row[0].lstrip().startswith("#"):
continue
labels[row[0].strip()] = {
"expected_vuln": "Yes" if row[2].strip().lower() == "true" else "No",
"expected_category": row[1].strip(),
"expected_cwe": f"CWE-{row[3].strip()}" if row[3].strip().isdigit() else row[3].strip(),
}
return labels
def bandit_findings(path: Path, condition: int, condition_label: str) -> list[dict[str, object]]:
data = json.loads(path.read_text(encoding="utf-8"))
rows: list[dict[str, object]] = []
for item in data.get("results", []):
rule_id = str(item.get("test_id") or "")
category = BANDIT_RULE_CATEGORY.get(rule_id)
cwe_id = (item.get("issue_cwe") or {}).get("id")
rows.append(
{
"tool": "bandit",
"tool_label": "Bandit",
"condition": condition,
"condition_label": condition_label,
"sample_id": Path(item["filename"]).stem,
"rule_id": rule_id,
"rule_name": str(item.get("test_name") or ""),
"severity": str(item.get("issue_severity") or ""),
"confidence": str(item.get("issue_confidence") or ""),
"cwe": f"CWE-{cwe_id}" if cwe_id else "None",
"category": category or "None",
"categories": [category] if category else [],
"is_target": 1 if category else 0,
"message": str(item.get("issue_text") or ""),
"line": item.get("line_number"),
"path": str(item.get("filename") or ""),
"severity_rank": BANDIT_SEVERITY.get(
str(item.get("issue_severity") or "").upper(), 0
),
}
)
return rows
def semgrep_findings(path: Path, condition: int, condition_label: str) -> list[dict[str, object]]:
data = json.loads(path.read_text(encoding="utf-8"))
rows: list[dict[str, object]] = []
for item in data.get("results", []):
extra = item.get("extra") or {}
metadata = extra.get("metadata") or {}
cwes = parse_cwes(metadata.get("cwe"))
categories: list[str] = []
for cwe in cwes:
category = CWE_TO_CATEGORY.get(cwe)
if category and category not in categories:
categories.append(category)
rule_id = str(item.get("check_id") or "")
rows.append(
{
"tool": "semgrep",
"tool_label": "Semgrep",
"condition": condition,
"condition_label": condition_label,
"sample_id": Path(item["path"]).stem,
"rule_id": rule_id,
"rule_name": rule_id.rsplit(".", 1)[-1],
"severity": str(extra.get("severity") or ""),
"confidence": str(metadata.get("confidence") or ""),
"cwe": ";".join(f"CWE-{cwe}" for cwe in cwes) if cwes else "None",
"category": categories[0] if categories else "None",
"categories": categories,
"is_target": 1 if categories else 0,
"message": str(extra.get("message") or ""),
"line": (item.get("start") or {}).get("line"),
"path": str(item.get("path") or ""),
"severity_rank": SEMGREP_SEVERITY.get(
str(extra.get("severity") or "").upper(), 0
),
}
)
return rows
def write_csv(path: Path, rows: list[dict[str, object]], fieldnames: list[str]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(
handle,
fieldnames=fieldnames,
lineterminator="\n",
extrasaction="ignore",
)
writer.writeheader()
writer.writerows(rows)
def sample_rows(
findings: list[dict[str, object]],
labels: dict[str, dict[str, str]],
tool: str,
condition: int,
condition_label: str,
) -> list[dict[str, object]]:
by_sample: dict[str, list[dict[str, object]]] = {}
for finding in findings:
by_sample.setdefault(str(finding["sample_id"]), []).append(finding)
rows: list[dict[str, object]] = []
for sample_id in sorted(labels):
expected = labels[sample_id]
sample_findings = by_sample.get(sample_id, [])
target_findings = [f for f in sample_findings if f["is_target"] == 1]
categories: list[str] = []
for finding in target_findings:
for category in finding["categories"]:
if category not in categories:
categories.append(category)
flagged = 1 if target_findings else 0
expected_vuln = 1 if expected["expected_vuln"] == "Yes" else 0
tp = int(expected_vuln == 1 and flagged == 1)
fp = int(expected_vuln == 0 and flagged == 1)
tn = int(expected_vuln == 0 and flagged == 0)
fn = int(expected_vuln == 1 and flagged == 0)
correct = int(expected_vuln == flagged)
category_correct = int(
tp and expected["expected_category"] in categories
)
predicted_category = categories[0] if categories else "None"
predicted_cwe = CATEGORY_TO_CWE.get(predicted_category, "None")
cwe_correct = int(tp and predicted_cwe == expected["expected_cwe"])
strict_correct = int(correct and (expected_vuln == 0 or category_correct))
wrong_category_tp = int(tp and not category_correct)
rule_ids = sorted({str(f["rule_id"]) for f in target_findings})
severity_max = max((int(f["severity_rank"]) for f in target_findings), default=0)
rows.append(
{
"tool": TOOLS[tool]["code"],
"tool_label": TOOLS[tool]["label"],
"condition": condition,
"condition_label": condition_label,
"sample_id": sample_id,
"in_scope": 1 if expected["expected_category"] in CATEGORY_TO_CWE else 0,
"expected_vuln": expected_vuln,
"expected_category": expected["expected_category"],
"expected_category_code": category_code(expected["expected_category"]),
"expected_cwe": expected["expected_cwe"],
"flagged": flagged,
"correct_flag": correct,
"tp": tp,
"fp": fp,
"tn": tn,
"fn": fn,
"predicted_category": predicted_category,
"predicted_category_code": category_code(predicted_category),
"predicted_categories": ";".join(categories),
"predicted_cwe": predicted_cwe,
"category_correct": category_correct,
"cwe_correct": cwe_correct,
"strict_correct": strict_correct,
"wrong_category_tp": wrong_category_tp,
"target_finding_count": len(target_findings),
"all_finding_count": len(sample_findings),
"severity_max": severity_max,
"rule_ids": ";".join(rule_ids),
}
)
return rows
def summarize(rows: list[dict[str, object]]) -> list[dict[str, object]]:
groups: dict[tuple[int, int], list[dict[str, object]]] = {}
for row in rows:
groups.setdefault((int(row["tool"]), int(row["condition"])), []).append(row)
summary: list[dict[str, object]] = []
for (tool, condition), group in sorted(groups.items()):
selected = [row for row in group if int(row["in_scope"]) == 1]
tp = sum(int(row["tp"]) for row in selected)
fp = sum(int(row["fp"]) for row in selected)
tn = sum(int(row["tn"]) for row in selected)
fn = sum(int(row["fn"]) for row in selected)
n = tp + fp + tn + fn
accuracy = (tp + tn) / n if n else 0.0
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = (
2 * precision * recall / (precision + recall)
if precision + recall
else 0.0
)
fpr = fp / (fp + tn) if fp + tn else 0.0
tnr = tn / (tn + fp) if tn + fp else 0.0
balanced_accuracy = (recall + tnr) / 2
mcc_denominator = (
(tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)
) ** 0.5
mcc = (tp * tn - fp * fn) / mcc_denominator if mcc_denominator else 0.0
category_correct = sum(int(row["category_correct"]) for row in selected)
cwe_correct = sum(int(row["cwe_correct"]) for row in selected)
strict_correct = sum(int(row["strict_correct"]) for row in selected)
wrong_category_tp = sum(int(row["wrong_category_tp"]) for row in selected)
summary.append(
{
"tool": tool,
"tool_label": group[0]["tool_label"],
"condition": condition,
"condition_label": group[0]["condition_label"],
"n_all": len(group),
"n_in_scope": n,
"tp": tp,
"fp": fp,
"tn": tn,
"fn": fn,
"accuracy": round(accuracy, 6),
"strict_accuracy": round(strict_correct / n, 6) if n else 0.0,
"precision": round(precision, 6),
"recall": round(recall, 6),
"fpr": round(fpr, 6),
"tnr": round(tnr, 6),
"balanced_accuracy": round(balanced_accuracy, 6),
"f1": round(f1, 6),
"mcc": round(mcc, 6),
"category_accuracy_tp": round(category_correct / tp, 6) if tp else 0.0,
"cwe_accuracy_tp": round(cwe_correct / tp, 6) if tp else 0.0,
"wrong_category_tp": wrong_category_tp,
"target_findings": sum(int(row["target_finding_count"]) for row in group),
"all_findings": sum(int(row["all_finding_count"]) for row in group),
"mean_target_findings": round(
sum(int(row["target_finding_count"]) for row in group) / len(group), 4
) if group else 0.0,
}
)
return summary
def write_codebook(path: Path) -> None:
text = """# SAST tool export codebook
## Files
- `findings.csv` — every raw finding from both tools and all three conditions
- `bandit_findings.csv` / `semgrep_findings.csv` — per-tool raw findings
- `tools_long.csv` — one row per tool × condition × sample (1,200 rows)
- `tools_summary.csv` — aggregate metrics by tool and condition
- `sast_tools.sps` — SPSS import and crosstab syntax
- `codebook.md` — this file
## Per-sample flag definition
`flagged = 1` when the tool produced at least one finding that maps to one of
the benchmark's fourteen target categories:
- path traversal (CWE-22)
- SQL injection (CWE-89)
- XPath injection (CWE-643)
- XXE (CWE-611)
- command injection (CWE-78)
- insecure deserialization (CWE-502)
- XSS (CWE-79)
- weak randomness (CWE-330)
- trust boundary violation (CWE-501)
- weak hash (CWE-328)
- code injection (CWE-94)
- insecure cookie (CWE-614)
- open redirect (CWE-601)
- LDAP injection (CWE-90)
Raw findings that do not map to a target category are still present in
`findings.csv` and are counted in `all_finding_count`.
## Tool mapping
Bandit is mapped by rule ID because its `issue_cwe` metadata is not specific
enough for this benchmark. Important mappings:
- B608 → sqli
- B301/B403/B506 → deserialization
- B311 → weakrand
- B324 → hash
- B102/B307 → codeinj
- B602/B603/B605/B607/B609/B610/B611 → cmdi
- B313–B320 → xxe
- B701/B308 → xss
Semgrep is mapped from the CWE metadata attached to each rule. CWE-327 and
CWE-328 both map to the benchmark's `hash` category, because scanners commonly
report the broader CWE-327 while the benchmark labels weak hashes as CWE-328.
CWE-93 (CRLF) and other non-target CWEs are kept as raw findings but are not
treated as target-category flags.
## Strict correctness
`category_correct` means the benchmark category appears among the tool's mapped
categories on a true positive. `strict_correct` requires the vulnerable/safe
decision to be correct and, for vulnerable samples, `category_correct` to be 1.
`wrong_category_tp` counts vulnerable samples the tool flagged as vulnerable but
assigned the wrong category. This mirrors the LLM scoring and prevents a
wrong-category detection from being counted as a fully correct classification.
`predicted_cwe` is the benchmark CWE corresponding to the first mapped category;
the tool's raw reported CWE remains in `findings.csv`.
## Category codes
| Code | Category |
|---:|---|
| 0 | None |
| 1 | pathtraver |
| 2 | sqli |
| 3 | xpathi |
| 4 | xxe |
| 5 | cmdi |
| 6 | deserialization |
| 7 | xss |
| 8 | weakrand |
| 9 | trustbound |
| 10 | hash |
| 11 | codeinj |
| 12 | securecookie |
| 13 | redirect |
| 14 | ldapi |
| 99 | other |
## Important caveat
Bandit and Semgrep are pattern-based. They do not cover all fourteen categories
and they do not perform the same dataflow reasoning as the LLM. Low recall is
expected, especially for path traversal, XPath injection, XSS, trust boundary
violations, insecure cookies, open redirects, and LDAP injection.
"""
path.write_text(text, encoding="utf-8")
def spss_syntax() -> str:
return """* Import SAST tool results.
* Set the SPSS working directory to this folder before running.
GET DATA
/TYPE=TXT
/FILE='tools_long.csv'
/ENCODING='UTF8'
/DELIMITERS=","
/QUALIFIER='"'
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/VARIABLES=
tool F1.0
tool_label A10
condition F1.0
condition_label A20
sample_id A20
in_scope F1.0
expected_vuln F1.0
expected_category A20
expected_category_code F3.0
expected_cwe A10
flagged F1.0
correct_flag F1.0
tp F1.0
fp F1.0
tn F1.0
fn F1.0
predicted_category A20
predicted_category_code F3.0
predicted_categories A100
predicted_cwe A10
category_correct F1.0
cwe_correct F1.0
strict_correct F1.0
wrong_category_tp F1.0
target_finding_count F4.0
all_finding_count F4.0
severity_max F1.0
rule_ids A200
.
DATASET NAME sast_tools WINDOW=FRONT.
VARIABLE LABELS
tool 'SAST tool' tool_label 'SAST tool label'
condition 'Dataset condition' condition_label 'Dataset condition label'
sample_id 'Benchmark test identifier'
in_scope 'In prompt target scope'
expected_vuln 'Ground-truth vulnerability'
expected_category 'Ground-truth category'
expected_category_code 'Ground-truth category code'
expected_cwe 'Ground-truth CWE'
flagged 'Tool flagged sample' correct_flag 'Tool prediction correct'
tp 'True positive' fp 'False positive' tn 'True negative' fn 'False negative'
predicted_category 'First predicted target category'
predicted_category_code 'First predicted category code'
predicted_categories 'All predicted target categories'
predicted_cwe 'Canonical CWE for predicted category'
category_correct 'Expected category among predicted categories'
cwe_correct 'Predicted CWE matches ground truth among TP'
strict_correct 'Flag and category both correct'
wrong_category_tp 'Vulnerable but wrong category (TP)'
target_finding_count 'Target-category findings'
all_finding_count 'All findings'
severity_max 'Maximum target-finding severity rank'
rule_ids 'Target rule IDs'
.
VALUE LABELS
tool 0 'Bandit' 1 'Semgrep'
condition 0 'Original' 1 'Obfuscated v2' 2 'Comments removed'
in_scope expected_vuln flagged correct_flag tp fp tn fn
category_correct cwe_correct strict_correct wrong_category_tp
0 'No' 1 'Yes'
expected_category_code predicted_category_code
0 'None' 1 'pathtraver' 2 'sqli' 3 'xpathi' 4 'xxe' 5 'cmdi'
6 'deserialization' 7 'xss' 8 'weakrand' 9 'trustbound'
10 'hash' 11 'codeinj' 12 'securecookie' 13 'redirect'
14 'ldapi' 99 'other'
.
EXECUTE.
* Restrict analyses to the fourteen target categories.
SELECT IF (in_scope = 1).
EXECUTE.
SORT CASES BY tool condition.
SPLIT FILE LAYERED BY tool condition.
CROSSTABS
/TABLES=flagged BY expected_vuln
/STATISTICS=CHISQ
/CELLS=COUNT ROW COLUMN.
SPLIT FILE OFF.
MEANS TABLES=target_finding_count all_finding_count BY tool condition
/CELLS=MEAN COUNT SUM.
"""
def main() -> int:
parser = argparse.ArgumentParser(description="Export Bandit and Semgrep results.")
parser.add_argument("--expected-csv", default=str(DEFAULT_EXPECTED))
parser.add_argument("--bandit-dir", default=str(DEFAULT_BANDIT))
parser.add_argument("--semgrep-dir", default=str(DEFAULT_SEMGREP))
parser.add_argument("--output-dir", default=str(DEFAULT_OUTPUT))
args = parser.parse_args()
labels = load_expected(Path(args.expected_csv))
sample_ids = {path.stem for path in (BASE_DIR / "Samples").glob("*.py")}
labels = {name: label for name, label in labels.items() if name in sample_ids}
if not labels:
raise SystemExit("No expected labels matched the benchmark sample names")
bandit_dir = Path(args.bandit_dir)
semgrep_dir = Path(args.semgrep_dir)
output = Path(args.output_dir)
output.mkdir(parents=True, exist_ok=True)
bandit_orig = bandit_findings(bandit_dir / "samples.json", 0, "original")
bandit_obf = bandit_findings(bandit_dir / "obfuscated_v2.json", 1, "obfuscated_v2")
bandit_comments = bandit_findings(
bandit_dir / "comments_removed.json", 2, "comments_removed"
)
semgrep_orig = semgrep_findings(semgrep_dir / "samples.json", 0, "original")
semgrep_obf = semgrep_findings(semgrep_dir / "obfuscated_v2.json", 1, "obfuscated_v2")
semgrep_comments = semgrep_findings(
semgrep_dir / "comments_removed.json", 2, "comments_removed"
)
all_findings = (
bandit_orig
+ bandit_obf
+ bandit_comments
+ semgrep_orig
+ semgrep_obf
+ semgrep_comments
)
finding_fields = [
"tool", "tool_label", "condition", "condition_label", "sample_id",
"rule_id", "rule_name", "severity", "confidence", "cwe", "category",
"is_target", "message", "line", "path",
]
write_csv(output / "findings.csv", all_findings, finding_fields)
write_csv(
output / "bandit_findings.csv",
bandit_orig + bandit_obf + bandit_comments,
finding_fields,
)
write_csv(
output / "semgrep_findings.csv",
semgrep_orig + semgrep_obf + semgrep_comments,
finding_fields,
)
long_rows = (
sample_rows(bandit_orig, labels, "bandit", 0, "original")
+ sample_rows(bandit_obf, labels, "bandit", 1, "obfuscated_v2")
+ sample_rows(
bandit_comments, labels, "bandit", 2, "comments_removed"
)
+ sample_rows(semgrep_orig, labels, "semgrep", 0, "original")
+ sample_rows(semgrep_obf, labels, "semgrep", 1, "obfuscated_v2")
+ sample_rows(
semgrep_comments, labels, "semgrep", 2, "comments_removed"
)
)
long_fields = [
"tool", "tool_label", "condition", "condition_label", "sample_id",
"in_scope", "expected_vuln", "expected_category", "expected_category_code",
"expected_cwe", "flagged", "correct_flag", "tp", "fp", "tn", "fn",
"predicted_category", "predicted_category_code", "predicted_categories",
"predicted_cwe", "category_correct", "cwe_correct", "strict_correct",
"wrong_category_tp", "target_finding_count", "all_finding_count",
"severity_max", "rule_ids",
]
write_csv(output / "tools_long.csv", long_rows, long_fields)
summary = summarize(long_rows)
write_csv(output / "tools_summary.csv", summary, list(summary[0].keys()))
write_codebook(output / "codebook.md")
(output / "sast_tools.sps").write_text(spss_syntax(), encoding="utf-8")
print(f"Wrote SAST tool exports to {output}")
print(f" raw findings: {len(all_findings)}")
print(f" per-sample rows: {len(long_rows)}")
print("Summary:")
for row in summary:
print(
f" {row['tool_label']:<8} {row['condition_label']:<14} "
f"TP={row['tp']:>2} FP={row['fp']:>2} TN={row['tn']:>3} FN={row['fn']:>3} "
f"acc={row['accuracy']:.3f} rec={row['recall']:.3f}"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())