mvd001/cyberset / scripts /make_manifest.py
mvd001's picture
download
raw
6.85 kB
"""Build sources.yaml from download receipts; re-verify sha256 on disk; record upstream checksum checks."""
import json, os, glob, hashlib, subprocess, yaml, datetime, sys
sys.path.insert(0, os.path.dirname(__file__))
from hubcommon import ROOT, RAW
IST = datetime.timezone(datetime.timedelta(hours=5, minutes=30))
CVELIST_GH_DIGEST = "4f49db8050d42a895158657b102fe3b45a63f5c863912fd7776b9177394a9d60" # GitHub release asset digest (API)
def sha256(p):
h = hashlib.sha256()
with open(p, "rb") as f:
for b in iter(lambda: f.read(1 << 20), b""): h.update(b)
return h.hexdigest()
recs = {}
for line in open(f"{ROOT}/logs/downloads.jsonl"):
r = json.loads(line); recs[os.path.basename(r["path"]) + "|" + r["dataset"]] = r # last write wins (re-downloads)
nvd_checks = {json.loads(l)["feed"]: json.loads(l) for l in open(f"{ROOT}/logs/nvd_meta_checks.jsonl")}
mitre = json.load(open(f"{ROOT}/processed/_intermediate/mitre_meta.json"))
misc = json.load(open(f"{ROOT}/processed/_intermediate/misc_meta.json"))
files = []
for key, r in sorted(recs.items(), key=lambda kv: (kv[1]["dataset"], kv[1]["path"])):
base = os.path.basename(r["path"])
hits = [p for p in glob.glob(f"{RAW}/{r['dataset'] if r['dataset']!='attack_enterprise' else 'attack'}/*/{base}")]
if len(hits) != 1: raise SystemExit(f"cannot locate {key}: {hits}")
p = hits[0]; rel = os.path.relpath(p, ROOT)
got = sha256(p)
e = dict(path=rel, version=rel.split("/")[2], url=r["url"], final_url=(r["final_url"].split("?")[0] if r["final_url"].split("?")[0] != r["url"] else None),
downloaded_ist=datetime.datetime.fromisoformat(r["downloaded_at"]).astimezone(IST).strftime("%Y-%m-%d %H:%M IST"),
size_bytes=os.path.getsize(p), sha256=got, sha256_verified_on_disk=(got == r["sha256"]),
upstream_last_modified=r.get("last_modified"), license=r["license"], upstream_checks=[])
if r.get("checks", {}).get("gcs_md5") == "ok": e["upstream_checks"].append("md5 matches GCS x-goog-hash")
if r["dataset"] == "nvd" and base.endswith(".json.gz"):
feed = base.replace("nvdcve-2.0-", "").replace(".json.gz", "")
c = nvd_checks.get(feed)
e["upstream_checks"].append(f"uncompressed sha256 vs NVD .meta: {c['status'] if c else 'missing'}")
if r["dataset"] == "cvelistV5":
e["upstream_checks"].append("sha256 matches GitHub release asset digest" if got == CVELIST_GH_DIGEST else "MISMATCH vs GitHub digest")
if base == "emerging.rules.tar.gz":
md5 = open(p.replace(".tar.gz", ".tar.gz.md5")).read().split()[0]
e["upstream_checks"].append("md5 matches published .md5" if hashlib.md5(open(p, "rb").read()).hexdigest() == md5 else "MD5 MISMATCH")
files.append((r["dataset"], e))
# GHSA shallow git clone (directory, content-addressed by git)
gdir = glob.glob(f"{RAW}/ghsa/*/advisory-database")[0]
git = lambda *a: subprocess.check_output(["git", "-C", gdir, *a], text=True).strip()
lstree = subprocess.check_output(["git", "-C", gdir, "ls-tree", "-r", "HEAD"])
apparent = int(subprocess.check_output(["du", "-s", "--apparent-size", "-B1", gdir]).split()[0])
ondisk = int(subprocess.check_output(["du", "-s", "-B1", gdir]).split()[0])
ghsa = dict(path=os.path.relpath(gdir, ROOT), version=os.path.relpath(gdir, ROOT).split("/")[2],
url="https://github.com/github/advisory-database.git", method="git clone --depth 1 --single-branch",
git_commit=git("rev-parse", "HEAD"), git_commit_date=git("log", "-1", "--format=%cI"), git_tree=git("rev-parse", "HEAD^{tree}"),
n_files=int(git("ls-files").count("\n") + 1), size_bytes_apparent=apparent, size_bytes_on_disk=ondisk,
sha256=hashlib.sha256(lstree).hexdigest(), sha256_of="output of `git ls-tree -r HEAD` (content-addresses every blob)",
upstream_checks=["git object integrity (git fsck --connectivity-only)"], license="CC-BY-4.0")
subprocess.check_call(["git", "-C", gdir, "fsck", "--connectivity-only", "--no-progress"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
DS = {
"cvelistV5": dict(name="CVE List V5 (CVE Program)", license="CVE Program Terms of Use", attribution="CVE® records © MITRE Corporation / CVE Program; see https://www.cve.org/Legal/TermsOfUse", form_required=False),
"nvd": dict(name="NVD CVE JSON 2.0 feeds (yearly 2002-current + modified)", license="Public (US Government)", attribution="This product uses data from the NVD API but is not endorsed or certified by the NVD.", form_required=False),
"osv": dict(name="OSV.dev all ecosystems (all.zip)", license="Varies per ecosystem (CC-BY-4.0/CC0/Apache-2.0/MIT; Ubuntu CC-BY-SA-4.0)", form_required=False),
"ghsa": dict(name="GitHub Advisory Database (shallow clone)", license="CC-BY-4.0", form_required=False),
"cwe": dict(name=f"MITRE CWE v{mitre['cwe_version']}", license="MITRE CWE Terms of Use (royalty-free, keep copyright notice)", form_required=False),
"capec": dict(name=f"MITRE CAPEC v{mitre['capec_version']}", license="MITRE CAPEC Terms of Use (royalty-free, keep copyright notice)", form_required=False),
"attack_enterprise": dict(name=f"MITRE ATT&CK Enterprise STIX 2.1 v{mitre['attack_version']}", license="MITRE ATT&CK Terms of Use (royalty-free)", form_required=False),
"cisa_kev": dict(name=f"CISA KEV catalog {misc['kev_catalog_version']} ({misc['kev_count']} entries)", license="US Government public data", form_required=False),
"epss": dict(name=f"FIRST EPSS scores {misc['epss_score_date']} (model {misc['epss_model_version']})", license="FIRST EPSS usage terms (free; attribute EPSS)", form_required=False),
"exploitdb": dict(name="Exploit-DB files_exploits.csv (index only, no exploit code)", license="GPL-2.0-or-later", form_required=False),
"et_open": dict(name="Proofpoint Emerging Threats Open rules for Suricata 7.0.3", license="Mixed: BSD (sids 2000000-2799999), GPLv2 (sids 1-3464, 100000000-100000908)", form_required=False),
}
out = {"manifest_version": 1, "generated_ist": datetime.datetime.now(IST).strftime("%Y-%m-%d %H:%M IST"),
"notes": "raw/<dataset>/<version>/ files are immutable (read-only). sha256 is of the file as stored. Versions: upstream release id where one exists, else download date (IST).",
"sources": {}}
for ds, meta in DS.items():
entry = dict(meta)
entry["files"] = [e for d, e in files if d == ds] if ds != "ghsa" else [ghsa]
entry["total_bytes"] = sum(f.get("size_bytes", f.get("size_bytes_on_disk", 0)) for f in entry["files"])
out["sources"][ds] = entry
yaml.safe_dump(out, open(f"{ROOT}/sources.yaml", "w"), sort_keys=False, width=200, allow_unicode=True)
bad = [e["path"] for _, e in files if not e["sha256_verified_on_disk"] or any("MISMATCH" in c or "missing" in c for c in e["upstream_checks"])]
print("files:", len(files) + 1, "verification problems:", bad)

Xet Storage Details

Size:
6.85 kB
·
Xet hash:
55c68e1482811f9ac188add108891e506fd10d051ae404bb439b8e1c188b0011

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