mvd001/cyberset / scripts /code /ingest_crossvul.py
mvd001's picture
download
raw
6.36 kB
#!/usr/bin/env python3
"""CrossVul 2.0 (Zenodo 4734050, CC-BY-4.0) -> staged rows.
CrossVul ships whole vulnerable ('bad_*') and patched ('good_*') files per fix commit. Files are split into functions with
tree-sitter; functions are matched by (name, occurrence). Changed functions -> bad version is_vulnerable (pair_role=vuln),
good version pair_role=fix; unchanged functions -> one row, pair_role=unrelated_in_commit, not vulnerable. Files in which no
function is found (e.g. top-level PHP/JSP scripts, unsupported languages) are kept at granularity=file. Non-code files
(json/xml/yml/html/css/conf/...) are skipped. label_source=nvd_patch_commit (CrossVul is mined from NVD references)."""
import sys, os, re, json, zipfile, collections, multiprocessing as mp
sys.path.insert(0, os.path.dirname(__file__)); import codecommon as C
ZIP = f"{C.ROOT}/raw/code/crossvul/2.0/dataset.zip"
LIC = "CC-BY-4.0 (CrossVul, Nikitopoulos et al. FSE'21)"
SKIP_EXT = {"json", "xml", "yml", "yaml", "html", "htm", "css", "scss", "less", "conf", "md", "txt", "rst", "lock", "svg", "csv",
"ini", "cfg", "properties", "sql", "po", "pot", "map", "jelly", "tpl", "tt", "ctp", "htaccess", "spec", "in", "am", "cmake", "toml", "gradle"}
_z = None; _index = None
def init():
global _z, _index
_z = zipfile.ZipFile(ZIP)
_index = {os.path.basename(n): n for n in _z.namelist() if re.search(r"/(bad|good)_\d+_\d+$", n)}
def read(dbname):
n = _index.get(dbname)
return (n, _z.read(n).decode("utf-8", "replace")) if n else (None, None)
def work(args):
wi, entries = args
w = C.StageWriter("crossvul", worker=wi, clear=False)
for idx, ent in entries:
url = ent.get("url") or ""; m = re.match(r"(https?://[^/]+/[^/]+/[^/]+)/commit/([0-9a-f]{7,40})", url)
repo, sha = (m.group(1), m.group(2)) if m else (url, None)
cve, cwe = C.cves(ent.get("cve")), C.cwes(ent.get("cwe"))
files = collections.defaultdict(dict)
for f in ent["files"]:
kind, a, b = f["database_name"].split("_"); files[b][kind] = (f["database_name"], f["original_name"])
changed_total = 0; pending = []
for fno, d in files.items():
orig = (d.get("bad") or d.get("good"))[1]
lang, detail, grammar = C.lang_from_path(orig)
ext = orig.rsplit(".", 1)[-1].lower() if "." in orig else ""
if ext in SKIP_EXT: continue
zb, bad = read(d["bad"][0]) if "bad" in d else (None, None)
zg, good = read(d["good"][0]) if "good" in d else (None, None)
if bad is None and good is None: continue
fb = C.split_functions(bad, grammar) if (grammar and bad) else []
fg = C.split_functions(good, grammar) if (grammar and good) else []
pid_base = f"crossvul:{idx}:{fno}"
if not fb and not fg: # file-level
if bad and good and C.normalize(bad, lang) == C.normalize(good, lang): continue
for kind, code in (("bad", bad), ("good", good)):
if code and len(code) < 1_000_000:
pending.append(dict(granularity="file", code=code, func=None, s=None, e=None, vul=kind == "bad",
role="vuln" if kind == "bad" else "fix", pid=pid_base, oid=d[kind][0], olabel=kind,
path=orig, lang=lang, detail=detail))
changed_total += 1; continue
def keyed(fl):
cnt = collections.Counter(); out = {}
for name, s, e, code in fl:
k = (name, cnt[name]); cnt[name] += 1; out[k] = (s, e, code)
return out
kb, kg = keyed(fb), keyed(fg)
for k in sorted(set(kb) | set(kg), key=lambda x: (str(x[0]), x[1])):
b, g = kb.get(k), kg.get(k)
nb = C.normalize(b[2], lang) if b else None; ng = C.normalize(g[2], lang) if g else None
pid = f"{pid_base}:{k[0]}:{k[1]}"
if b and g and nb == ng:
pending.append(dict(granularity="function", code=g[2], func=k[0], s=g[0], e=g[1], vul=False, role="unrelated_in_commit",
pid=None, oid=f"{d['good'][0]}::{k[0]}#{k[1]}", olabel="good_unchanged", path=orig, lang=lang, detail=detail))
continue
changed_total += 1
if b: pending.append(dict(granularity="function", code=b[2], func=k[0], s=b[0], e=b[1], vul=True, role="vuln", pid=pid,
oid=f"{d['bad'][0]}::{k[0]}#{k[1]}", olabel="bad", path=orig, lang=lang, detail=detail))
if g: pending.append(dict(granularity="function", code=g[2], func=k[0], s=g[0], e=g[1], vul=False, role="fix", pid=pid,
oid=f"{d['good'][0]}::{k[0]}#{k[1]}", olabel="good", path=orig, lang=lang, detail=detail))
for p in pending:
conf = C.confidence("nvd_patch_commit", p["role"], p["path"], single_func_commit=(changed_total == 1))
if p["granularity"] == "file": conf = round(conf - 0.15, 3) # whole-file labels are coarser
w.add(language=p["lang"], language_detail=p["detail"], granularity=p["granularity"], code=p["code"],
project=C.project_from_repo(repo), repo_url=repo, commit_sha=sha, file_path=p["path"], func_name=p["func"],
start_line=p["s"], end_line=p["e"], is_vulnerable=p["vul"], pair_id=C.sha256(p["pid"])[:32] if p["pid"] else None,
pair_role=p["role"], cve_ids=cve, cwe_ids=cwe, label_source="nvd_patch_commit", label_confidence=conf,
origin={"dataset": "crossvul_2.0", "original_id": p["oid"], "original_label": p["olabel"]},
source_dataset="crossvul", source_license=LIC, publishable_code=True, source_split=None,
extra=json.dumps({"commit_url": url, "changed_units_in_commit": changed_total}))
return w.close()
if __name__ == "__main__":
C.clear_stage("crossvul")
meta = json.load(zipfile.ZipFile(ZIP).open("dataset_final_sorted/metadata.json"))
ents = list(enumerate(meta)); n = 64
tasks = [(i, ents[i::n]) for i in range(n)]
with mp.Pool(7, initializer=init) as p: print("rows", sum(p.imap_unordered(work, tasks)), flush=True)

Xet Storage Details

Size:
6.36 kB
·
Xet hash:
96dca7db89ff981939fd525502bcd4a60e10235a4be881d2a2d432a813e36a95

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