mvd001/cyberset / scripts /code /ingest_fixdb.py
mvd001's picture
download
raw
6.26 kB
#!/usr/bin/env python3
"""CVEfixes-schema fix databases (CVEfixes v1.0.8 and MoreFixes, which reuses the CVEfixes collector schema) -> staged rows.
Input is a slim SQLite DB (see load_cvefixes_sqlite.py / load_morefixes_pg.py). Each method_change row is a function touched by a
CVE fix commit: before_change='True' -> pre-fix version (is_vulnerable, pair_role=vuln), 'False' -> post-fix version (pair_role=fix).
Old/new versions are paired within a file_change by signature (then name). label_source=nvd_patch_commit; conf 0.65 (+0.05 if
the commit changed exactly one function; -0.30 for test/vendor/minified paths; MoreFixes: -0.25 if fixes.score < 65).
Usage: ingest_fixdb.py <source> <db> <dataset_tag> <license>"""
import sys, os, json, sqlite3, collections, multiprocessing as mp
sys.path.insert(0, os.path.dirname(__file__)); import codecommon as C
SRC, DB, TAG, LIC = sys.argv[1:5]
def ro(): return sqlite3.connect(f"file:{DB}?mode=ro", uri=True)
def cols(con, t): return [r[1] for r in con.execute(f"PRAGMA table_info({t})")]
def lookups():
con = ro(); fx = collections.defaultdict(lambda: {"cves": set(), "repos": set(), "score": None})
has_score = "score" in cols(con, "fixes")
for row in con.execute(f"SELECT hash, cve_id, repo_url{', score' if has_score else ''} FROM fixes"):
d = fx[row[0]]; d["cves"].add(row[1]); d["repos"].add(row[2])
if has_score and row[3] is not None:
try: d["score"] = max(float(row[3]), d["score"] or -1)
except ValueError: pass
cwe = collections.defaultdict(set)
for cve, cw in con.execute("SELECT cve_id, cwe_id FROM cwe_classification"): cwe[cve].add(cw)
cdate = {}
ccols = cols(con, "commits")
dcol = "author_date" if "author_date" in ccols else ("committer_date" if "committer_date" in ccols else None)
if dcol:
for h, rp, d in con.execute(f"SELECT hash, repo_url, {dcol} FROM commits"): cdate[h] = (str(d)[:10] if d else None)
pub = {}
if "cve" in [r[0] for r in con.execute("select name from sqlite_master where type='table'")]:
pc = "published_date" if "published_date" in cols(con, "cve") else None
if pc:
for c, d in con.execute(f"SELECT cve_id, {pc} FROM cve"): pub[c] = str(d)[:10] if d else None
return {k: {"cves": sorted(v["cves"]), "repos": sorted(x for x in v["repos"] if x), "score": v["score"]} for k, v in fx.items()}, \
{k: sorted(v) for k, v in cwe.items()}, cdate, pub
def init(l):
global LK; LK = l
def work(wi, rng):
fx, cwe, cdate, pub = LK
lo, hi = rng; con = ro(); w = C.StageWriter(SRC, worker=wi, clear=False)
q = """SELECT m.method_change_id, m.file_change_id, m.name, m.signature, m.start_line, m.end_line, m.code, m.before_change,
f.filename, f.new_path, f.old_path, f.programming_language, f.hash
FROM method_change m JOIN file_change_slim f ON f.file_change_id = m.file_change_id
WHERE m.rowid >= ? AND m.rowid < ?"""
by_fc = collections.defaultdict(list)
for r in con.execute(q, (lo, hi)): by_fc[r[1]].append(r)
# count changed functions per commit (approximate within this shard; shards are cut on method rowid ranges)
per_commit = collections.Counter()
for fc, rows in by_fc.items(): per_commit[rows[0][12]] += len({(x[3] or x[2]) for x in rows})
for fc, rows in by_fc.items():
h = rows[0][12]; meta = fx.get(h, {"cves": [], "repos": [], "score": None})
path = rows[0][9] if rows[0][9] not in (None, "None") else (rows[0][10] if rows[0][10] not in (None, "None") else rows[0][8])
lang, detail, _ = C.lang_from_path(path or "")
if lang == "other": lang = C.lang_from_name(rows[0][11])
repo = meta["repos"][0] if meta["repos"] else None
cw = sorted({c for cve in meta["cves"] for c in cwe.get(cve, [])})
date = cdate.get(h) or min([pub[c] for c in meta["cves"] if pub.get(c)] or [None])
groups = collections.defaultdict(dict)
for r in rows:
key = (r[3] or r[2]); kind = "before" if str(r[7]).lower() in ("true", "1") else "after"
groups[key][kind] = r
single = per_commit[h] == 1
for key, g in groups.items():
pid = C.sha256(f"{TAG}:{fc}:{key}")[:32]
for kind, r in g.items():
vul = kind == "before"; role = "vuln" if vul else "fix"
conf = C.confidence("nvd_patch_commit", role, path, single_func_commit=single, morefixes_score=meta["score"] if SRC == "morefixes" else None)
w.add(language=lang, language_detail=detail, code=r[6], project=C.project_from_repo(repo), repo_url=repo, commit_sha=h,
commit_date=date, file_path=path, func_name=r[2], start_line=r[4], end_line=r[5], is_vulnerable=vul,
pair_id=pid, pair_role=role, cve_ids=meta["cves"], cwe_ids=C.cwes(cw), label_source="nvd_patch_commit",
label_confidence=conf, origin={"dataset": TAG, "original_id": f"method_change:{r[0]}", "original_label": f"before_change={r[7]}"},
source_dataset=SRC, source_license=LIC, publishable_code=True, source_split=None,
extra=json.dumps({"fix_score": meta["score"]}) if meta["score"] is not None else None)
return w.close()
if __name__ == "__main__":
con = ro(); mx = con.execute("SELECT max(rowid) FROM method_change").fetchone()[0] or 0
# shard on rowid but cut at file_change boundaries so pairs stay together
cuts = [1]; step = 15000
while cuts[-1] <= mx:
nxt = cuts[-1] + step
row = con.execute("SELECT file_change_id FROM method_change WHERE rowid = ?", (nxt,)).fetchone()
if row:
r2 = con.execute("SELECT max(rowid) FROM method_change WHERE file_change_id = ?", (row[0],)).fetchone()[0]
nxt = max(nxt, (r2 or nxt) + 1)
cuts.append(nxt)
rngs = list(zip(cuts[:-1], cuts[1:])); print(len(rngs), "shards; max rowid", mx, flush=True)
lk = lookups(); print("lookups", [len(x) for x in lk], flush=True)
C.clear_stage(SRC)
with mp.Pool(6, initializer=init, initargs=(lk,)) as p:
n = sum(p.starmap(work, enumerate(rngs), chunksize=1))
print(f"[{SRC}] total rows {n}", flush=True)

Xet Storage Details

Size:
6.26 kB
·
Xet hash:
65af9d320511bb5d027dafe2a6db616f4b1089f0c80ec52ea9fbc7e17e01d2ab

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