{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# CVE-KEV Snapshot — Offline Quickstart\n", "\n", "Audience: security ML/RAG practitioners and analysts. Runs fully offline; no network calls.\n", "\n", "- What this does:\n", " - Loads Parquet tables and shows quick triage and retrieval examples\n", " - Surfaces integrity and validation signals (accuracy)\n", " - Skips RAG if the embedding model isn't cached locally\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "HF_DATASET_URL = 'https://huggingface.co/datasets/NostromoHub/cve-kev-snapshot-90d-2025-09-04/resolve/main' # used only in hosted runtimes for optional installs\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Running in Colab or Kaggle?\n", "\n", "- This offline notebook does not install dependencies by default.\n", "- If you're in an online runtime (Colab/Kaggle), you can opt-in to install deps below.\n", "- Local/offline users should pre-install packages (see demo/requirements-colab.txt).\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Optional: install dependencies when running in Colab/Kaggle (online only)\n", "# By default, offline users should pre-install packages and skip this cell.\n", "try:\n", " import os\n", " IN_COLAB = 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ\n", " IN_KAGGLE = 'KAGGLE_URL_BASE' in os.environ\n", " if IN_COLAB or IN_KAGGLE:\n", " if not HF_DATASET_URL:\n", " raise RuntimeError('HF_DATASET_URL is empty; set it at the top of the notebook to enable online install.')\n", " url = HF_DATASET_URL.rstrip('/') + '/demo/requirements-colab.txt'\n", " print('Detected hosted runtime. Installing from:', url)\n", " import subprocess, sys\n", " subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r', url])\n", " else:\n", " print('Hosted runtime not detected; skipping online install.')\n", "except Exception as e:\n", " print('Dependency install skipped or failed:', e)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Optional: dependency check (offline-safe). Set ENABLE_AUTO_INSTALL=True to pip install.\n", "import importlib, sys, subprocess\n", "\n", "ENABLE_AUTO_INSTALL = False # change to True to auto-install missing deps\n", "REQUIRED_PACKAGES = [\"duckdb\", \"pandas\", \"pyarrow\"]\n", "missing = []\n", "for pkg in REQUIRED_PACKAGES:\n", " try:\n", " importlib.import_module(pkg)\n", " except Exception:\n", " missing.append(pkg)\n", "\n", "if missing:\n", " print(\"Missing packages:\", missing)\n", " if ENABLE_AUTO_INSTALL:\n", " try:\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", *missing])\n", " # Re-validate imports\n", " for pkg in list(missing):\n", " importlib.import_module(pkg)\n", " print(\"Installed successfully.\")\n", " except Exception as install_err:\n", " print(\"Auto-install failed:\", install_err)\n", " print(\"Run manually:\", \"pip install \" + \" \".join(missing))\n", " else:\n", " print(\"Set ENABLE_AUTO_INSTALL=True above or run:\")\n", " print(\"pip install \" + \" \".join(missing))\n", "else:\n", " print(\"All required packages are present.\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Artifacts (click to view): [Validation Report](../docs/VALIDATION.json) · [Integrity Check](../docs/INTEGRITY.txt) · [Build Manifest](../docs/BUILD_MANIFEST.json)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "import json\n", "\n", "BASE = Path('..').resolve()\n", "PARQ = BASE / 'parquet'\n", "DOCS = BASE / 'docs'\n", "RAG = BASE / 'rag'\n", "\n", "assert PARQ.exists() and DOCS.exists(), 'Missing required directories. Ensure you are running the notebook from the snapshot \"demo\" directory.'\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Snapshot metadata\n", "manifest = json.loads((DOCS / 'BUILD_MANIFEST.json').read_text())\n", "print('snapshot_as_of:', manifest.get('snapshot_as_of'))\n", "# Prefer manifest-provided window; fallback to parsing README if absent\n", "window_days = manifest.get('nvd_window_days')\n", "if window_days is None:\n", " try:\n", " txt = (BASE / 'README.md').read_text(encoding='utf-8')\n", " marker = 'NVD window (days): '\n", " i = txt.find(marker)\n", " if i != -1:\n", " j = i + len(marker)\n", " k = j\n", " while k < len(txt) and txt[k].isdigit():\n", " k += 1\n", " window_days = int(txt[j:k]) if k > j else None\n", " except Exception:\n", " window_days = None\n", "print('nvd_window_days:', window_days)\n", "print('model:', manifest.get('model_name'), 'dim:', manifest.get('model_dim'))\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Integrity spot-check (first 5 entries)\n", "import hashlib\n", "\n", "def sha256(path: Path) -> str:\n", " h = hashlib.sha256()\n", " with path.open('rb') as f:\n", " for chunk in iter(lambda: f.read(1024*1024), b''):\n", " h.update(chunk)\n", " return h.hexdigest()\n", "\n", "lines = (DOCS / 'INTEGRITY.txt').read_text().splitlines()\n", "# Parse lines robustly on whitespace: ' '\n", "pairs = []\n", "for ln in lines:\n", " if not ln.strip():\n", " continue\n", " parts = ln.split()\n", " digest_expected, rel = parts[0], ' '.join(parts[1:])\n", " pairs.append((rel, digest_expected))\n", "\n", "subset = [rel for rel, _ in pairs[:5]]\n", "issues = []\n", "for rel in subset:\n", " digest_expected = next(d for r, d in pairs if r == rel)\n", " actual = sha256(BASE / rel)\n", " if actual != digest_expected:\n", " issues.append(rel)\n", "print('integrity_spotcheck_mismatches:', issues)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Load with DuckDB; fallback to pandas if needed\n", "try:\n", " import duckdb as dd\n", " con = dd.connect()\n", " con.execute('PRAGMA threads=4')\n", " engine = 'duckdb'\n", "except Exception as e:\n", " import pandas as pd\n", " engine = 'pandas'\n", " print('DuckDB unavailable, using pandas:', e)\n", "\n", "if engine == 'duckdb':\n", " total_cve = con.execute(\"SELECT COUNT(*) FROM read_parquet(?)\", [str(PARQ/'cve.parquet')]).fetchone()[0]\n", " total_kev = con.execute(\"SELECT COUNT(*) FROM read_parquet(?)\", [str(PARQ/'kev.parquet')]).fetchone()[0]\n", "else:\n", " import pandas as pd\n", " total_cve = len(pd.read_parquet(PARQ/'cve.parquet'))\n", " total_kev = len(pd.read_parquet(PARQ/'kev.parquet'))\n", "print('rows:', {'cve': total_cve, 'kev': total_kev})\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Accuracy panel\n", "import os\n", "val_path = DOCS / 'VALIDATION.json'\n", "if val_path.exists():\n", " validation = json.loads(val_path.read_text())\n", " keys = [\n", " 'counts',\n", " 'cvss_v3_presence_ratio',\n", " 'cwe_presence_ratio',\n", " 'kev_cve_coverage_ratio',\n", " 'kev_cve_coverage_ratio_within_window',\n", " 'kev_rows_total_fetched',\n", " 'kev_rows_within_window',\n", " 'kev_rows_filtered_out',\n", " 'kev_within_window_over_global_ratio',\n", " 'url_shape_failures',\n", " 'http_head_failures_hard',\n", " 'http_head_failures_flaky',\n", " 'dead_reference_links',\n", " 'duplicate_edges_dropped',\n", " 'snapshot_as_of',\n", " ]\n", " summary = {k: validation.get(k) for k in keys}\n", " print(summary)\n", "else:\n", " # Minimal local signal if validation omitted\n", " if engine == 'duckdb':\n", " cvss_ratio = con.execute(\"\"\"\n", " WITH t AS (\n", " SELECT COUNT(*) AS n, SUM(CASE WHEN cvss_v3_score IS NOT NULL THEN 1 ELSE 0 END) AS v\n", " FROM read_parquet(?)\n", " ) SELECT CAST(v AS DOUBLE)/n FROM t\n", " \"\"\", [str(PARQ/'nvd_meta.parquet')]).fetchone()[0]\n", " else:\n", " import pandas as pd\n", " m = pd.read_parquet(PARQ/'nvd_meta.parquet')\n", " cvss_ratio = float((m['cvss_v3_score'].notnull()).mean())\n", " print({'cvss_v3_presence_ratio': cvss_ratio})\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Provenance proof (sample rows)\n", "if engine == 'duckdb':\n", " df = con.execute(\"\"\"\n", " SELECT c.cve_id, c.source, c.source_url, c.retrieved_at, c.source_record_hash\n", " FROM read_parquet(?) c\n", " ORDER BY c.cve_id\n", " LIMIT 5\n", " \"\"\", [str(PARQ/'cve.parquet')]).df()\n", "else:\n", " import pandas as pd\n", " c = pd.read_parquet(PARQ/'cve.parquet', columns=['cve_id','source','source_url','retrieved_at','source_record_hash'])\n", " df = c.sort_values('cve_id').head(5)\n", "from IPython.display import display\n", "display(df)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# KEV triage (top 20 by CVSS)\n", "if engine == 'duckdb':\n", " df = con.execute(\"\"\"\n", " SELECT c.cve_id, m.cvss_v3_score, k.date_added, k.notes\n", " FROM read_parquet(?) k\n", " JOIN read_parquet(?) c ON c.cve_id = k.cve_id\n", " LEFT JOIN read_parquet(?) m ON m.cve_id = c.cve_id\n", " ORDER BY (m.cvss_v3_score IS NULL) ASC, m.cvss_v3_score DESC, k.date_added DESC\n", " LIMIT 20\n", " \"\"\", [str(PARQ/'kev.parquet'), str(PARQ/'cve.parquet'), str(PARQ/'nvd_meta.parquet')]).df()\n", "else:\n", " import pandas as pd\n", " k = pd.read_parquet(PARQ/'kev.parquet')\n", " c = pd.read_parquet(PARQ/'cve.parquet')\n", " m = pd.read_parquet(PARQ/'nvd_meta.parquet')\n", " df = k.merge(c, on='cve_id').merge(m[['cve_id','cvss_v3_score']], on='cve_id', how='left')\n", " df = df.sort_values(['cvss_v3_score','date_added'], ascending=[False, False]).head(20)\n", "from IPython.display import display\n", "# Export first CVE id for downstream default in citations\n", "try:\n", " DEFAULT_CVE_FOR_CITATIONS = df['cve_id'].iloc[0] if len(df) else None\n", "except Exception:\n", " DEFAULT_CVE_FOR_CITATIONS = None\n", "display(df)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# CWE pivot (top 20)\n", "if engine == 'duckdb':\n", " df = con.execute(\"\"\"\n", " SELECT u.cwe, COUNT(*) AS cnt\n", " FROM read_parquet(?) t, UNNEST(t.cwe_ids) AS u(cwe)\n", " GROUP BY 1\n", " ORDER BY cnt DESC\n", " LIMIT 20\n", " \"\"\", [str(PARQ/'nvd_meta.parquet')]).df()\n", "else:\n", " import pandas as pd\n", " m = pd.read_parquet(PARQ/'nvd_meta.parquet')\n", " rows = []\n", " for _, r in m.iterrows():\n", " for c in (r['cwe_ids'] or []):\n", " rows.append(c)\n", " import collections\n", " cc = collections.Counter(rows)\n", " df = pd.DataFrame({'cwe': list(cc.keys()), 'cnt': list(cc.values())}).sort_values('cnt', ascending=False).head(20)\n", "from IPython.display import display\n", "display(df)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Citations for a specific CVE\n", "# Default: take the first CVE from KEV triage if available; otherwise use the placeholder below.\n", "try:\n", " TARGET\n", "except NameError:\n", " try:\n", " TARGET = DEFAULT_CVE_FOR_CITATIONS # set by KEV triage cell\n", " except NameError:\n", " TARGET = None\n", " if TARGET is None:\n", " TARGET = 'CVE-2021-44228' # change as desired\n", "print('TARGET:', TARGET, '(set TARGET to override)')\n", "\n", "if engine == 'duckdb':\n", " df = con.execute(\"\"\"\n", " SELECT dst_id AS reference_url\n", " FROM read_parquet(?)\n", " WHERE src_type='cve' AND src_id=? AND edge_type='cve_ref_url'\n", " ORDER BY reference_url\n", " \"\"\", [str(PARQ/'edges.parquet'), TARGET]).df()\n", "else:\n", " import pandas as pd\n", " e = pd.read_parquet(PARQ/'edges.parquet')\n", " df = (\n", " e[(e['src_type']=='cve') & (e['src_id']==TARGET) & (e['edge_type']=='cve_ref_url')]\n", " [['dst_id']].rename(columns={'dst_id':'reference_url'})\n", " .sort_values('reference_url')\n", " )\n", "from IPython.display import display\n", "display(df)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# RAG config and retrieval (offline-only if model cached)\n", "import pandas as pd\n", "\n", "# Read meta and print config\n", "meta = pd.read_parquet(RAG/'meta.parquet')\n", "assert bool(meta['normalize'][0]) and meta['metric'][0] == 'IP'\n", "model_name = meta['model_name'][0]\n", "dim = int(meta['dim'][0])\n", "texts_count = int(meta.get('texts_count', pd.Series([None]))[0])\n", "print({'model_name': model_name, 'dim': dim, 'normalize': True, 'metric': 'IP', 'texts_count': texts_count})\n", "\n", "# Enforce offline HF/Transformers and guard imports\n", "import os\n", "os.environ['HF_HUB_OFFLINE'] = '1'\n", "os.environ['TRANSFORMERS_OFFLINE'] = '1'\n", "\n", "rag_enabled = True\n", "try:\n", " from sentence_transformers import SentenceTransformer\n", " import faiss, numpy as np\n", "except Exception as e:\n", " print('RAG disabled (missing sentence-transformers or faiss):', e)\n", " rag_enabled = False\n", "\n", "if rag_enabled:\n", " try:\n", " model = SentenceTransformer(model_name)\n", " index = faiss.read_index(str(RAG/'index.faiss'))\n", " id_map = pd.read_parquet(RAG/'mapping.parquet')\n", "\n", " query = 'recent OpenSSL remote exploit'\n", " qvec = model.encode([query], normalize_embeddings=True)\n", " D, I = index.search(np.asarray(qvec, dtype='float32'), 10)\n", " print('scores:', D[0].tolist())\n", " from IPython.display import display\n", " hits = id_map[id_map['row_index'].isin(I[0].tolist())].merge(\n", " pd.DataFrame({'row_index': I[0].tolist()}), on='row_index', how='right'\n", " )\n", " display(hits)\n", " except Exception as e:\n", " print('RAG skipped (model not cached or index missing):', e)\n", " print('Tip: pre-cache once online, then re-run offline:')\n", " print(\"from sentence_transformers import SentenceTransformer; SentenceTransformer('BAAI/bge-small-en-v1.5')\")\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Consistency checks (fast)\n", "if engine == 'duckdb':\n", " kev_total = con.execute(\"SELECT COUNT(*) FROM read_parquet(?)\", [str(PARQ/'kev.parquet')]).fetchone()[0]\n", " kev_without_cve = con.execute(\"\"\"\n", " SELECT COUNT(*) FROM read_parquet(?) k\n", " LEFT JOIN read_parquet(?) c ON c.cve_id = k.cve_id\n", " WHERE c.cve_id IS NULL\n", " \"\"\", [str(PARQ/'kev.parquet'), str(PARQ/'cve.parquet')]).fetchone()[0]\n", "\n", " edges_with_missing_cve = con.execute(\"\"\"\n", " SELECT COUNT(*) FROM read_parquet(?) e\n", " LEFT JOIN read_parquet(?) c ON c.cve_id = e.src_id\n", " WHERE e.src_type='cve' AND c.cve_id IS NULL\n", " \"\"\", [str(PARQ/'edges.parquet'), str(PARQ/'cve.parquet')]).fetchone()[0]\n", "\n", " sample_missing = [r[0] for r in con.execute(\"\"\"\n", " SELECT k.cve_id\n", " FROM read_parquet(?) k\n", " LEFT JOIN read_parquet(?) c ON c.cve_id = k.cve_id\n", " WHERE c.cve_id IS NULL\n", " ORDER BY k.cve_id\n", " LIMIT 5\n", " \"\"\", [str(PARQ/'kev.parquet'), str(PARQ/'cve.parquet')]).fetchall()]\n", "\n", " kev_with_cve = int(kev_total) - int(kev_without_cve)\n", " coverage_ratio = (kev_with_cve / kev_total) if kev_total else 0.0\n", "\n", " print({\n", " 'kev_total': int(kev_total),\n", " 'kev_with_cve': int(kev_with_cve),\n", " 'kev_without_cve': int(kev_without_cve),\n", " 'kev_cve_coverage_ratio': coverage_ratio,\n", " 'edges_with_missing_cve': int(edges_with_missing_cve),\n", " 'sample_missing_cves': sample_missing,\n", " })\n", "else:\n", " print('Consistency checks require DuckDB for speed; skipped.')\n" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 }