File size: 27,477 Bytes
27f6252 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 | #!/usr/bin/env python3
"""
CVE-KGRAG — Hybrid RAG System (Qdrant + BM25 sparse vectors)
Backends
--------
- Dense vectors : microsoft/harrier-oss-v1-270m (640-dim, MTEB 66.5)
- Sparse vectors: BM25 (built from corpus via BM25SparseEncoder)
- Retrieval : Qdrant RRF fusion (prefetch dense + sparse → rank)
- Collections : cve_chunks | mitre_techniques | capec_patterns | cwe_entries
Usage
-----
Build index (all collections):
python -m src.generators.rag_system --build
Search CVEs:
python -m src.generators.rag_system --search "Log4j JNDI injection"
Cross-collection search:
python -m src.generators.rag_system --search "T1059" --collection mitre
"""
from __future__ import annotations
import argparse
import gc
import json
import logging
import os
import uuid
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import torch
from sentence_transformers import SentenceTransformer
from tqdm import tqdm
from qdrant_client import QdrantClient
from qdrant_client.models import (
Distance, FieldCondition, Filter, Fusion, FusionQuery,
MatchValue, NamedSparseVector, NamedVector,
PointStruct, Prefetch, SparseVector,
SparseVectorParams, VectorParams, VectorsConfig,
)
from src.generators.rag_config import (
DENSE_VECTOR_NAME, DENSE_VECTOR_SIZE, DEVICE, EMBEDDING_BATCH_SIZE,
LOGGING_LEVEL, MAX_SEQ_LENGTH, EMBEDDING_MODEL_NAME,
QDRANT_API_KEY, QDRANT_COLLECTIONS, QDRANT_URL,
SPARSE_VECTOR_NAME, CVE_YEAR_PATHS,
CVE_CHUNKS_PATH, MITRE_CHUNKS_PATH, CAPEC_CHUNKS_PATH, CWE_CHUNKS_PATH,
)
from src.generators.sparse_encoder import BM25SparseEncoder
logging.basicConfig(level=LOGGING_LEVEL)
logger = logging.getLogger(__name__)
# ─────────────────────────────────────────────────────────────────────────────
# Utilities
# ─────────────────────────────────────────────────────────────────────────────
def _stable_uuid(chunk_id: str) -> str:
"""Deterministic UUID from a string chunk ID (Qdrant requires UUID or uint64)."""
return str(uuid.uuid5(uuid.NAMESPACE_DNS, chunk_id))
def _load_chunks(path: str) -> List[Dict[str, Any]]:
if not os.path.exists(path):
logger.error(f"Chunks file not found: {path}. Run export_kg_for_rag_direct.py first.")
return []
with open(path, encoding="utf-8") as f:
return json.load(f)
def _iter_chunks(path: str):
"""Streaming iterator over a JSON array file — avoids loading gigabytes into RAM."""
import ijson
if not os.path.exists(path):
logger.error(f"Chunks file not found: {path}")
return
with open(path, "rb") as f:
yield from ijson.items(f, "item")
# ─────────────────────────────────────────────────────────────────────────────
# Embedding generator
# ─────────────────────────────────────────────────────────────────────────────
class EmbeddingGenerator:
def __init__(self) -> None:
logger.info(f"Loading embedding model: {EMBEDDING_MODEL_NAME} on {DEVICE}")
self.model = SentenceTransformer(EMBEDDING_MODEL_NAME)
self.model.to(DEVICE)
self.model.max_seq_length = MAX_SEQ_LENGTH
def encode(self, texts: List[str], batch_size: int = EMBEDDING_BATCH_SIZE) -> np.ndarray:
all_embs: List[np.ndarray] = []
ctx = torch.cuda.amp.autocast() if DEVICE == "cuda" else torch.no_grad()
for i in tqdm(range(0, len(texts), batch_size), desc="Embedding"):
batch = texts[i : i + batch_size]
with ctx:
embs = self.model.encode(
batch,
convert_to_tensor=True,
show_progress_bar=False,
normalize_embeddings=True,
)
all_embs.append(embs.cpu().numpy())
if DEVICE == "cuda" and i % (batch_size * 10) == 0:
torch.cuda.empty_cache()
gc.collect()
return np.vstack(all_embs)
# ─────────────────────────────────────────────────────────────────────────────
# Qdrant search engine
# ─────────────────────────────────────────────────────────────────────────────
class QdrantSearchEngine:
"""Manages Qdrant collections and provides hybrid dense+sparse search."""
def __init__(self) -> None:
self.client = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY, timeout=30)
self._ensure_collections()
# ── collection management ─────────────────────────────────────────────────
def _ensure_collections(self) -> None:
existing = {c.name for c in self.client.get_collections().collections}
for col_name in QDRANT_COLLECTIONS.values():
if col_name not in existing:
self._create_collection(col_name)
def _create_collection(self, col_name: str) -> None:
self.client.create_collection(
collection_name=col_name,
vectors_config={
DENSE_VECTOR_NAME: VectorParams(
size=DENSE_VECTOR_SIZE,
distance=Distance.COSINE,
),
},
sparse_vectors_config={
SPARSE_VECTOR_NAME: SparseVectorParams(),
},
)
logger.info(f"Created Qdrant collection: {col_name}")
def recreate_collections(self) -> None:
"""Drop and recreate all collections (used on force rebuild)."""
for col_name in QDRANT_COLLECTIONS.values():
try:
self.client.delete_collection(col_name)
logger.info(f"Dropped collection: {col_name}")
except Exception:
pass
self._create_collection(col_name)
def collection_count(self, key: str) -> int:
col = QDRANT_COLLECTIONS.get(key, key)
try:
return self.client.get_collection(col).points_count or 0
except Exception:
return 0
# ── indexing ──────────────────────────────────────────────────────────────
def upsert(
self,
collection_key: str,
chunks: List[Dict[str, Any]],
dense_vecs: np.ndarray,
sparse_vecs: List[Dict[str, Any]],
batch_size: int = 2000,
) -> None:
col = QDRANT_COLLECTIONS[collection_key]
total = len(chunks)
logger.info(f"Upserting {total} points → {col}")
for start in tqdm(range(0, total, batch_size), desc=f"Upsert {col}"):
end = min(start + batch_size, total)
points = []
for i in range(start, end):
chunk = chunks[i]
d_vec = dense_vecs[i].tolist()
s_vec = sparse_vecs[i]
payload= chunk.get("payload", {})
# Sanitise payload: lists → JSON strings where needed for Qdrant
clean_payload: Dict[str, Any] = {}
for k, v in payload.items():
if isinstance(v, list):
clean_payload[k] = [str(x) for x in v]
elif v is None:
pass # drop nulls
else:
clean_payload[k] = v
points.append(
PointStruct(
id=_stable_uuid(chunk["id"]),
vector={
DENSE_VECTOR_NAME: d_vec,
SPARSE_VECTOR_NAME: SparseVector(
indices=s_vec["indices"],
values=s_vec["values"],
),
},
payload={**clean_payload, "chunk_id": chunk["id"], "text": chunk["text"]},
)
)
self.client.upsert(collection_name=col, points=points)
logger.info(f"Done upserting {total} points into {col}")
# ── search ────────────────────────────────────────────────────────────────
def search(
self,
collection_key: str,
dense_vec: List[float],
sparse_vec: Dict[str, Any],
k: int = 10,
filters: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
col = QDRANT_COLLECTIONS[collection_key]
qdrant_filter = None
if filters:
conditions = [
FieldCondition(key=fk, match=MatchValue(value=fv))
for fk, fv in filters.items()
if fv is not None
]
if conditions:
qdrant_filter = Filter(must=conditions)
results = self.client.query_points(
collection_name=col,
prefetch=[
Prefetch(
query=dense_vec,
using=DENSE_VECTOR_NAME,
limit=50,
),
Prefetch(
query=SparseVector(
indices=sparse_vec["indices"],
values=sparse_vec["values"],
),
using=SPARSE_VECTOR_NAME,
limit=50,
),
],
query=FusionQuery(fusion=Fusion.RRF),
query_filter=qdrant_filter,
limit=k,
with_payload=True,
)
formatted = []
for point in results.points:
payload = point.payload or {}
score = point.score
formatted.append({
"id": payload.get("chunk_id", str(point.id)),
"text": payload.get("text", ""),
"metadata": payload,
"score": score,
"distance": 1 - score,
})
return formatted
def get_stats(self) -> Dict[str, Any]:
return {
key: self.collection_count(key)
for key in QDRANT_COLLECTIONS
}
# ─────────────────────────────────────────────────────────────────────────────
# Main RAG system
# ─────────────────────────────────────────────────────────────────────────────
class CVERAGSystem:
"""
Orchestrates building and querying the hybrid Qdrant index.
Public API (same signatures as before for API compatibility):
build_vector_database(force_rebuild)
search_cves(query, n_results, severity_filter, vendor_filter) → list
get_similar_cves(cve_id, n_results) → list
get_vulnerability_summary(query) → dict
get_collection_stats() → dict
"""
def __init__(self) -> None:
self.engine = QdrantSearchEngine()
self._emb = None # lazy-loaded
self._sparse = None # lazy-loaded from disk
@property
def embedding_generator(self) -> EmbeddingGenerator:
if self._emb is None:
self._emb = EmbeddingGenerator()
return self._emb
@property
def sparse_encoder(self) -> Optional[BM25SparseEncoder]:
if self._sparse is None:
self._sparse = BM25SparseEncoder.load_or_none()
return self._sparse
# ── build ─────────────────────────────────────────────────────────────────
def build_vector_database(self, force_rebuild: bool = False) -> None:
"""
Build Qdrant index for all four collections with incremental checkpointing.
Strategy:
1. Load small collections (MITRE/CAPEC/CWE) into RAM — they're tiny.
2. Fit BM25 on those + a 250K sample of CVE texts, persist vocab to disk.
3. Upsert small collections (skipped if already present and not force).
4. Stream CVE chunks in batches of STREAM_BATCH: encode → upsert → checkpoint.
On restart, reads checkpoint to skip already-upserted chunks by position.
"""
STREAM_BATCH = 2_000 # chunks per encode+upsert cycle
CHECKPOINT_PATH = os.path.join(os.path.dirname(CVE_CHUNKS_PATH), ".cve_index_checkpoint")
chunk_sources_small = {
"mitre": MITRE_CHUNKS_PATH,
"capec": CAPEC_CHUNKS_PATH,
"cwe": CWE_CHUNKS_PATH,
}
# Drop + recreate collections on force rebuild (clears wrong vector dims etc.)
if force_rebuild:
self.engine.recreate_collections()
if os.path.exists(CHECKPOINT_PATH):
os.remove(CHECKPOINT_PATH)
logger.info("Removed CVE index checkpoint (force rebuild).")
# ── Step 1: load small collections ───────────────────────────────────
small: Dict[str, List[Dict[str, Any]]] = {}
small_texts: List[str] = []
for key, path in chunk_sources_small.items():
chunks = _load_chunks(path)
if not chunks:
logger.warning(f"No chunks for {key} — skipping.")
continue
seen: set = set()
unique = [c for c in chunks if c["id"] not in seen and not seen.add(c["id"])]
logger.info(f" {key}: {len(unique)} chunks")
small[key] = unique
small_texts.extend(c["text"] for c in unique)
# ── Step 2: fit BM25 (or reload from disk) ───────────────────────────
enc = BM25SparseEncoder.load_or_none() if not force_rebuild else None
if enc is None:
cve_sample: List[str] = []
max_cve_sample = max(0, 250_000 - len(small_texts))
if max_cve_sample > 0 and os.path.exists(CVE_CHUNKS_PATH):
logger.info(f"Sampling up to {max_cve_sample:,} CVE texts for BM25 fit …")
for chunk in _iter_chunks(CVE_CHUNKS_PATH):
cve_sample.append(chunk["text"])
if len(cve_sample) >= max_cve_sample:
break
corpus = small_texts + cve_sample
logger.info(f"Fitting BM25 on {len(corpus):,} texts …")
enc = BM25SparseEncoder()
enc.fit(corpus)
logger.info(f"BM25 vocab size: {len(enc.vocab):,}")
del cve_sample
self._sparse = enc
# ── Step 3: upsert small collections (skip if already indexed) ───────
for key, chunks in small.items():
if not force_rebuild and self.engine.collection_count(key) >= len(chunks):
logger.info(f" {key}: already indexed ({self.engine.collection_count(key)} pts), skipping.")
continue
texts = [c["text"] for c in chunks]
logger.info(f"Encoding + upserting {key} ({len(texts)} chunks) …")
dense = self.embedding_generator.encode(texts)
sparse = [enc.encode(t) for t in tqdm(texts, desc=f"BM25 {key}")]
self.engine.upsert(key, chunks, dense, sparse)
# ── Step 4: stream CVE collection with checkpoint ─────────────────────
if not os.path.exists(CVE_CHUNKS_PATH):
logger.warning("cve_chunks.json not found — skipping CVE index.")
else:
# Read checkpoint: number of stream positions already processed
resume_pos = 0
if os.path.exists(CHECKPOINT_PATH):
try:
with open(CHECKPOINT_PATH) as f:
resume_pos = int(f.read().strip())
logger.info(f"Resuming CVE index from position {resume_pos:,}")
except Exception:
resume_pos = 0
logger.info(f"Streaming CVE chunks (batch={STREAM_BATCH:,}, skip first {resume_pos:,}) …")
batch_chunks: List[Dict[str, Any]] = []
seen_ids: set = set()
total_upserted = resume_pos
stream_pos = 0
for chunk in _iter_chunks(CVE_CHUNKS_PATH):
stream_pos += 1
if stream_pos <= resume_pos:
continue # fast-forward past already-indexed items
cid = chunk.get("id", "")
if cid in seen_ids:
continue
seen_ids.add(cid)
batch_chunks.append(chunk)
if len(batch_chunks) >= STREAM_BATCH:
texts = [c["text"] for c in batch_chunks]
dense = self.embedding_generator.encode(texts)
sparse = [enc.encode(t) for t in texts]
self.engine.upsert("cve", batch_chunks, dense, sparse)
total_upserted += len(batch_chunks)
# Persist checkpoint after successful upsert
with open(CHECKPOINT_PATH, "w") as f:
f.write(str(stream_pos))
logger.info(f" … {total_upserted:,} CVE chunks upserted (pos {stream_pos:,})")
batch_chunks = []
if DEVICE == "cuda":
torch.cuda.empty_cache()
# Final partial batch
if batch_chunks:
texts = [c["text"] for c in batch_chunks]
dense = self.embedding_generator.encode(texts)
sparse = [enc.encode(t) for t in texts]
self.engine.upsert("cve", batch_chunks, dense, sparse)
total_upserted += len(batch_chunks)
with open(CHECKPOINT_PATH, "w") as f:
f.write(str(stream_pos))
logger.info(f"CVE indexing done: {total_upserted:,} chunks")
# Remove checkpoint on clean finish
if os.path.exists(CHECKPOINT_PATH):
os.remove(CHECKPOINT_PATH)
logger.info("Build complete. Stats: " + str(self.engine.get_stats()))
# ── search helpers ────────────────────────────────────────────────────────
def _encode_query(self, query: str) -> Tuple[List[float], Dict[str, Any]]:
dense_arr = self.embedding_generator.encode([query])
dense_vec = dense_arr[0].tolist()
enc = self.sparse_encoder
sparse_vec= enc.encode_query(query) if enc else {"indices": [], "values": []}
return dense_vec, sparse_vec
# ── public API ────────────────────────────────────────────────────────────
def search_cves(
self,
query: str,
n_results: int = 10,
severity_filter: Optional[str] = None,
vendor_filter: Optional[str] = None,
collection: str = "cve",
) -> List[Dict[str, Any]]:
dense, sparse = self._encode_query(query)
filters: Dict[str, Any] = {}
if severity_filter:
filters["severity"] = severity_filter
return self.engine.search(collection, dense, sparse, k=n_results, filters=filters or None)
def search(
self,
query: str,
n_results: int = 10,
collection: str = "cve",
filters: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
"""Generic search across any collection."""
dense, sparse = self._encode_query(query)
return self.engine.search(collection, dense, sparse, k=n_results, filters=filters)
def get_similar_cves(self, cve_id: str, n_results: int = 5) -> List[Dict[str, Any]]:
anchor = self.search_cves(f"CVE ID: {cve_id}", n_results=1)
if not anchor:
logger.warning(f"{cve_id} not found in index")
return []
anchor_text = anchor[0].get("text", f"CVE ID: {cve_id}")
results = self.search_cves(anchor_text, n_results=n_results + 1)
return [r for r in results if r["metadata"].get("cve_id") != cve_id][:n_results]
def get_vulnerability_summary(self, query: str) -> Dict[str, Any]:
results = self.search_cves(query, n_results=50)
if not results:
return {"error": "No vulnerabilities found"}
severities: Dict[str, int] = {}
vendors: set = set()
products: set = set()
cwes: set = set()
for r in results:
m = r.get("metadata", {})
sev = m.get("severity", "Unknown")
severities[sev] = severities.get(sev, 0) + 1
for p in (m.get("products") or []):
products.add(p)
for c in (m.get("cwe_refs") or []):
cwes.add(c)
return {
"query": query,
"total_results": len(results),
"severity_distribution":severities,
"top_products": list(products)[:10],
"common_weaknesses": list(cwes)[:10],
"sample_results": results[:5],
}
def get_collection_stats(self) -> Dict[str, Any]:
stats = self.engine.get_stats()
return {
"total_documents": sum(stats.values()),
"collections": stats,
"qdrant_url": QDRANT_URL,
}
# ── legacy (year-based scan fallback) ────────────────────────────────────
def search_cves_by_year(
self,
query: str,
years: List[str] | None = None,
n_results: int = 10,
vendor_terms: list | None = None,
product_terms: list | None = None,
) -> List[Dict[str, Any]]:
"""Fallback linear scan over year JSON files (no Qdrant)."""
import re as _re
years = years or ["2021", "2022", "2023", "2024"]
vendor_terms = vendor_terms or []
product_terms = product_terms or []
query_lower = query.lower()
all_results: List[Dict[str, Any]] = []
for year in years:
path = CVE_YEAR_PATHS.get(year)
if not path or not os.path.exists(path):
continue
with open(path, encoding="utf-8") as f:
docs = json.load(f)
for doc in docs:
doc_vendors = doc.get("affected_vendors", []) or []
doc_products = doc.get("affected_products", []) or []
if isinstance(doc_vendors, str): doc_vendors = [doc_vendors]
if isinstance(doc_products, str): doc_products = [doc_products]
vm = any(vt.lower() in v.lower() for vt in vendor_terms for v in doc_vendors)
pm = any(pt.lower() in p.lower() for pt in product_terms for p in doc_products)
if (vendor_terms or product_terms) and not (vm or pm):
continue
content = doc.get("content", "").lower()
if not (vendor_terms or product_terms) and query_lower not in content:
continue
score = content.count(query_lower) / max(1, len(content))
all_results.append({
"id": doc.get("id"),
"text": doc.get("content", "")[:1000],
"metadata": {
"cve_id": doc.get("id"),
"year": year,
"severity": doc.get("cvss_v3", {}).get("base_severity", "Unknown"),
"cvss_score": doc.get("cvss_v3", {}).get("base_score"),
},
"score": score,
"distance": 1 - score,
})
all_results.sort(key=lambda x: x["score"], reverse=True)
return all_results[:n_results]
# ─────────────────────────────────────────────────────────────────────────────
# CLI
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="CVE-KGRAG Hybrid RAG System")
parser.add_argument("--build", action="store_true", help="Build / rebuild index")
parser.add_argument("--force", action="store_true", help="Force full rebuild")
parser.add_argument("--search", type=str, help="Search query")
parser.add_argument("--collection", type=str, default="cve",
choices=list(QDRANT_COLLECTIONS.keys()), help="Collection to search")
parser.add_argument("--n_results", type=int, default=5)
parser.add_argument("--summary", type=str, help="Vulnerability summary query")
args = parser.parse_args()
rag = CVERAGSystem()
if args.build:
rag.build_vector_database(force_rebuild=args.force)
elif args.search:
results = rag.search(args.search, n_results=args.n_results, collection=args.collection)
for i, r in enumerate(results, 1):
m = r.get("metadata", {})
print(f"{i}. [{m.get('cve_id', m.get('technique_id', m.get('cwe_id', r['id'])))}]"
f" severity={m.get('severity', '-')} score={r['score']:.4f}")
print(f" {r['text'][:200]}\n")
elif args.summary:
s = rag.get_vulnerability_summary(args.summary)
print(f"Query: {s['query']}")
print(f"Total: {s['total_results']}")
print(f"Severity: {s['severity_distribution']}")
print(f"Products: {s['top_products']}")
print(f"CWEs: {s['common_weaknesses']}")
else:
stats = rag.get_collection_stats()
print("Collection stats:", json.dumps(stats, indent=2))
parser.print_help()
|