mvd001/cyberset / scripts /make_stats.py
mvd001's picture
download
raw
8.12 kB
"""processed/STATS.md: row counts, sizes, coverage."""
import os, json, duckdb, datetime, subprocess
ROOT = "/workspace/security-dataset"; P = f"{ROOT}/processed"
IST = datetime.timezone(datetime.timedelta(hours=5, minutes=30))
con = duckdb.connect(); con.execute("SET memory_limit='3GB'; SET threads=4")
one = lambda s: con.execute(s).fetchone()
V = f"'{P}/vuln_kb.parquet'"
def human(n):
for u in ["B", "KB", "MB", "GB"]:
if n < 1024: return f"{n:.1f} {u}"
n /= 1024
return f"{n:.2f} TB"
def du(path): return int(subprocess.check_output(["du", "-s", "-B1", path]).split()[0])
pct = lambda a, b: f"{100*a/b:.1f}%" if b else "n/a"
L = []
L.append(f"# Knowledge hub statistics\n\n*Generated {datetime.datetime.now(IST):%Y-%m-%d %H:%M} IST by `scripts/make_stats.py`.*\n")
L.append("## Tables (Parquet, zstd)\n\n| Table | Rows | Size |\n|---|---:|---:|")
for t in ["vuln_kb", "weakness_kb", "capec_kb", "attack_kb", "taxonomy_map", "ids_rules"]:
f = f"{P}/{t}.parquet"
L.append(f"| `{t}` | {one(f'SELECT count(*) FROM read_parquet(\"{f}\")')[0]:,} | {human(os.path.getsize(f))} |")
L.append("")
tot, pub, rej = one(f"SELECT count(*), count(*) FILTER (WHERE cve_state='PUBLISHED' OR (cve_state IS NULL AND nvd_vuln_status<>'Rejected')), count(*) FILTER (WHERE cve_state='REJECTED' OR (cve_state IS NULL AND nvd_vuln_status='Rejected')) FROM {V}")
L.append("## vuln_kb coverage\n\nPercentages are of **non-rejected** CVEs unless stated. Rejected records are kept with `cve_state='REJECTED'`.\n")
L.append(f"| Metric | Count | % |\n|---|---:|---:|\n| CVE rows (all) | {tot:,} | |\n| non-rejected | {pub:,} | |\n| rejected | {rej:,} | |")
NR = "(coalesce(cve_state,'') <> 'REJECTED' AND coalesce(nvd_vuln_status,'') <> 'Rejected')"
def row(label, cond):
n = one(f"SELECT count(*) FROM {V} WHERE {NR} AND ({cond})")[0]
L.append(f"| {label} | {n:,} | {pct(n, pub)} |"); return n
row("in cvelistV5 snapshot", "list_contains(sources,'cvelistV5')")
row("in NVD feeds", "list_contains(sources,'nvd')")
row("has description", "description IS NOT NULL")
row("≥1 CWE (CWE-n, excluding NVD-CWE-Other/noinfo)", "len(cwe_ids)>0")
row("≥1 CAPEC via CWE closure", "len(capec_ids)>0")
row("≥1 ATT&CK technique via CWE→CAPEC closure", "len(attack_techniques)>0")
row("CVSS v2", "cvss_v2 IS NOT NULL"); row("CVSS v3.x", "cvss_v3 IS NOT NULL"); row("CVSS v4.0", "cvss_v4 IS NOT NULL")
row("≥1 NVD CPE match", "len(cpe_matches)>0")
row("in OSV", "list_contains(sources,'osv')"); row("in GHSA (any, incl. unreviewed mirror of NVD)", "list_contains(sources,'ghsa')")
row("in GHSA github-reviewed", "ghsa_reviewed")
row("≥1 package ecosystem (OSV/GHSA)", "len(ecosystems)>0")
L.append("")
L.append("## Fix commits\n")
L.append("Sources: NVD references tagged `Patch` that point at a single commit; OSV `GIT` ranges (`fixed` events) and commit-URL references; same for the GHSA clone. "
"`score` is a heuristic confidence: 0.95 structured GIT-range `fixed`, 0.9 NVD Patch tag, 0.85 OSV/GHSA `FIX` ref, 0.5 `WEB`/`ADVISORY` ref, 0.3–0.4 other ref types.\n")
L.append("| Metric | Count | % of non-rejected |\n|---|---:|---:|")
row("CVEs with ≥1 fix commit (any source)", "len(fix_commits)>0")
row("CVEs with ≥1 fix commit, score ≥ 0.85", "len(list_filter(fix_commits, x -> x.score>=0.85))>0")
for s in ["nvd", "osv", "ghsa"]:
row(f"CVEs with ≥1 fix commit from `{s}`", f"len(list_filter(fix_commits, x -> x.source='{s}'))>0")
L.append("")
n_entries, n_pairs, n_repos = one(f"SELECT count(*), count(DISTINCT (cve_id, f.repo_url, f.sha)), count(DISTINCT f.repo_url) FROM (SELECT cve_id, unnest(fix_commits) f FROM {V})")
n_commits = one(f"SELECT count(DISTINCT (f.repo_url, f.sha)) FROM (SELECT unnest(fix_commits) f FROM {V})")[0]
L.append(f"- fix_commit entries (CVE × repo × sha × source): {n_entries:,}\n- distinct (CVE, repo, sha): {n_pairs:,}\n- distinct (repo, sha) commits: {n_commits:,}\n- distinct repos: {n_repos:,}")
gh = one(f"SELECT count(DISTINCT (f.repo_url, f.sha)) FROM (SELECT unnest(fix_commits) f FROM {V}) WHERE f.repo_url LIKE 'https://github.com/%'")[0]
L.append(f"- of which on github.com: {gh:,} ({pct(gh, n_commits)})\n")
L.append("| evidence | entries |\n|---|---:|")
for ev, n in con.execute(f"SELECT f.evidence, count(*) FROM (SELECT unnest(fix_commits) f FROM {V}) GROUP BY 1 ORDER BY 2 DESC").fetchall():
L.append(f"| `{ev}` | {n:,} |")
L.append("")
L.append("## Exploitation signals\n\n| Metric | Count | % of non-rejected |\n|---|---:|---:|")
kev_n = row("in CISA KEV", "in_kev")
row("has EPSS score", "epss IS NOT NULL")
row("EPSS ≥ 0.1", "epss.score >= 0.1")
edb = row("≥1 Exploit-DB entry", "len(exploit_refs)>0")
et = row("≥1 ET Open rule (reference:cve; excl. emerging-deleted.rules)", "len(ids_signatures)>0")
row("≥1 *enabled* ET Open rule", "len(list_filter(ids_signatures, x -> x.enabled))>0")
row("Exploit-DB **or** ET Open link", "len(exploit_refs)>0 OR len(ids_signatures)>0")
row("Exploit-DB **and** ET Open link", "len(exploit_refs)>0 AND len(ids_signatures)>0")
L.append("")
kev_total = one(f"SELECT count(*) FROM '{P}/_intermediate/kev.parquet'")[0]
kev_join = one(f"SELECT count(*) FROM {V} WHERE in_kev")[0]
epss_total = one(f"SELECT count(*) FROM '{P}/_intermediate/epss.parquet'")[0]
epss_join = one(f"SELECT count(*) FROM {V} WHERE epss IS NOT NULL")[0]
L.append(f"- KEV catalog entries: {kev_total:,}; matched to vuln_kb rows: {kev_join:,} ({pct(kev_join, kev_total)})")
L.append(f"- EPSS rows: {epss_total:,}; matched to vuln_kb rows: {epss_join:,} ({pct(epss_join, epss_total)})")
edb_rows = one(f"SELECT count(*), count(DISTINCT edb_id) FROM '{P}/_intermediate/edb.parquet'")
L.append(f"- Exploit-DB: {edb_rows[1]:,} distinct EDB-IDs carry ≥1 CVE code ({edb_rows[0]:,} CVE×EDB pairs). `metasploit_module` and `nuclei_template` are null (not in this CSV); `is_metasploit` flags Metasploit-authored entries.")
etr = one(f"SELECT count(*), count(*) FILTER (WHERE len(cve_ids)>0), count(*) FILTER (WHERE enabled) FROM '{P}/ids_rules.parquet'")
L.append(f"- ET Open: {etr[0]:,} rules parsed ({etr[2]:,} enabled), {etr[1]:,} with ≥1 `reference:cve`.\n")
L.append("## Taxonomy\n")
tm = con.execute(f"SELECT family_type, count(*), count(*) FILTER (WHERE len(capec_ids)>0), count(*) FILTER (WHERE len(attack_techniques)>0) FROM '{P}/taxonomy_map.parquet' GROUP BY 1").fetchall()
L.append("| family_type | rows | with CAPEC | with ATT&CK |\n|---|---:|---:|---:|")
for r in tm: L.append(f"| {r[0]} | {r[1]:,} | {r[2]:,} | {r[3]:,} |")
cap = one(f"SELECT count(*), count(*) FILTER (WHERE len(attack_techniques_direct)>0), count(*) FILTER (WHERE len(attack_techniques)>0) FROM '{P}/capec_kb.parquet'")
L.append(f"\n- CAPEC patterns: {cap[0]:,}; with a direct ATT&CK mapping: {cap[1]:,}; with ATT&CK after inheriting from the nearest CAPEC parent: {cap[2]:,}.")
fams = con.execute(f"SELECT family FROM '{P}/taxonomy_map.parquet' WHERE family_type='attack_family' ORDER BY 1").fetchall()
L.append(f"- Attack families ({len(fams)}): " + ", ".join(f"`{f[0]}`" for f in fams) + "\n")
L.append("## Top CWEs (non-rejected CVEs)\n\n| CWE | CVEs |\n|---|---:|")
for c, n in con.execute(f"SELECT c, count(*) FROM (SELECT unnest(cwe_ids) c FROM {V} WHERE {NR}) GROUP BY 1 ORDER BY 2 DESC LIMIT 15").fetchall():
L.append(f"| {c} | {n:,} |")
L.append("\n## CVEs per publication year (cve_year from ID)\n\n| Year | CVEs | with fix commit | in KEV |\n|---|---:|---:|---:|")
for y, n, f, k in con.execute(f"SELECT cve_year, count(*), count(*) FILTER (WHERE len(fix_commits)>0), count(*) FILTER (WHERE in_kev) FROM {V} WHERE {NR} GROUP BY 1 ORDER BY 1").fetchall():
L.append(f"| {y} | {n:,} | {f:,} | {k:,} |")
raw_b, proc_b, total_b = du(f"{ROOT}/raw"), du(P), du(ROOT)
L.append(f"\n## Disk\n\n| Path | On disk |\n|---|---:|\n| raw/ | {human(raw_b)} |\n| processed/ (incl. _intermediate) | {human(proc_b)} |\n| processed/_intermediate | {human(du(P + '/_intermediate'))} |\n| whole security-dataset/ (incl. .venv, scratch) | {human(total_b)} |\n")
open(f"{P}/STATS.md", "w").write("\n".join(L) + "\n")
print("\n".join(L))

Xet Storage Details

Size:
8.12 kB
·
Xet hash:
8f65d5428ff95ef5e3f106d0af9fa23e48e8c6518bfbc0da52662464e2c38c54

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.