-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeed_sidecar.py
More file actions
1586 lines (1373 loc) · 54.4 KB
/
feed_sidecar.py
File metadata and controls
1586 lines (1373 loc) · 54.4 KB
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
ALdeci CVE Intelligence Feed Sidecar
=====================================
Production-grade threat-intelligence pipeline that fetches, correlates, and
pushes enriched CVE data into the ALdeci FAIL scoring engine.
Data sources:
* NIST NVD 2.0 API -- CVE details, CVSS scores, CWE IDs
* CISA KEV catalog -- Known Exploited Vulnerabilities
* FIRST EPSS API -- Exploit Prediction Scoring System probabilities
Modes:
continuous -- Loop every --interval seconds (default 3600)
once -- Single fetch-correlate-push cycle, then exit
demo -- Generate realistic synthetic CVE data (offline/demo)
health -- Probe all feed sources and the ALdeci API
Architecture:
NVD ──┐
KEV ──┼── Correlator ── FAIL /score/batch ── ALdeci DB
EPSS ─┘
Docker usage (via docker-compose):
python scripts/feed_sidecar.py continuous --interval 3600
"""
from __future__ import annotations
import argparse
import asyncio
import json
import logging
import os
import random
import signal
import sys
import time
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Set
# ---------------------------------------------------------------------------
# Logging -- structured JSON in production, human-readable in dev
# ---------------------------------------------------------------------------
LOG_FORMAT = os.getenv("LOG_FORMAT", "text") # "text" or "json"
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
class _JSONFormatter(logging.Formatter):
"""Structured JSON log formatter for container environments."""
def format(self, record: logging.LogRecord) -> str:
entry = {
"ts": datetime.fromtimestamp(record.created, tz=timezone.utc).isoformat(),
"level": record.levelname,
"logger": record.name,
"msg": record.getMessage(),
}
if record.exc_info and record.exc_info[0]:
entry["exception"] = self.formatException(record.exc_info)
return json.dumps(entry, default=str)
def _setup_logging() -> logging.Logger:
root = logging.getLogger()
root.setLevel(LOG_LEVEL)
handler = logging.StreamHandler(sys.stdout)
if LOG_FORMAT == "json":
handler.setFormatter(_JSONFormatter())
else:
handler.setFormatter(
logging.Formatter(
"%(asctime)s [%(levelname)-7s] %(name)s: %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
)
root.handlers = [handler]
# Suppress noisy third-party loggers
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
return logging.getLogger("feed_sidecar")
logger = _setup_logging()
# ---------------------------------------------------------------------------
# Lazy import -- httpx may not be installed in every environment
# ---------------------------------------------------------------------------
try:
import httpx
except ImportError:
logger.error("httpx is required: pip install httpx")
sys.exit(1)
# ---------------------------------------------------------------------------
# Configuration (env-driven, 12-factor)
# ---------------------------------------------------------------------------
BASE_URL: str = os.getenv("FIXOPS_BASE_URL", "http://localhost:8000")
API_TOKEN: str = os.getenv("FIXOPS_API_TOKEN", "")
NVD_API_KEY: str = os.getenv("NVD_API_KEY", "")
# Feed source URLs
NVD_API_URL = "https://services.nvd.nist.gov/rest/json/cves/2.0"
CISA_KEV_URL = (
"https://www.cisa.gov/sites/default/files/feeds/"
"known_exploited_vulnerabilities.json"
)
EPSS_API_URL = "https://api.first.org/data/v1/epss"
# Paths
DATA_DIR = Path(os.getenv("FEED_DATA_DIR", ""))
if not DATA_DIR.name:
# Resolve relative to the repo root (two levels up from scripts/)
DATA_DIR = Path(__file__).resolve().parent.parent / "data" / "feeds"
STATE_FILE = DATA_DIR / "feed_state.json"
NVD_CACHE_FILE = DATA_DIR / "nvd_cache.json"
KEV_CACHE_FILE = DATA_DIR / "kev_cache.json"
EPSS_CACHE_FILE = DATA_DIR / "epss_cache.json"
CORRELATED_FILE = DATA_DIR / "correlated_cves.json"
# Tuning
NVD_PAGE_SIZE = 2000 # NVD max per request
NVD_RATE_LIMIT_DELAY = 6.0 # seconds between NVD calls (no API key)
NVD_RATE_LIMIT_DELAY_WITH_KEY = 0.6 # seconds with API key
MAX_RETRIES = 3
RETRY_BASE_DELAY = 2.0 # exponential backoff base (seconds)
BATCH_PUSH_SIZE = 100 # findings per FAIL batch request
HTTP_TIMEOUT = 60.0
# ---------------------------------------------------------------------------
# Data model -- one record per correlated CVE
# ---------------------------------------------------------------------------
@dataclass
class EnrichedCVE:
"""A CVE record enriched with NVD + KEV + EPSS data."""
cve_id: str
# NVD fields
description: str = ""
cvss_v31_score: Optional[float] = None
cvss_v31_vector: str = ""
cvss_v31_severity: str = ""
cvss_v2_score: Optional[float] = None
cwe_ids: List[str] = field(default_factory=list)
published: str = ""
last_modified: str = ""
references: List[str] = field(default_factory=list)
# KEV fields
is_kev: bool = False
kev_vendor: str = ""
kev_product: str = ""
kev_date_added: str = ""
kev_due_date: str = ""
kev_description: str = ""
kev_required_action: str = ""
# EPSS fields
epss_score: Optional[float] = None
epss_percentile: Optional[float] = None
# Derived
has_exploit: bool = False
exploit_maturity: str = "unknown"
# Metadata
feed_timestamp: str = ""
source_feeds: List[str] = field(default_factory=list)
def to_fail_payload(self) -> Dict[str, Any]:
"""Convert to the FAIL engine batch scoring request schema."""
return {
"cve_id": self.cve_id,
"title": self.description[:200] if self.description else self.cve_id,
"cvss_score": self.cvss_v31_score or self.cvss_v2_score,
"epss_score": self.epss_score,
"is_kev": self.is_kev,
"has_exploit": self.has_exploit or self.is_kev,
"exploit_maturity": self.exploit_maturity,
"active_campaigns": 1 if self.is_kev else 0,
"asset_criticality": "unknown",
"data_classification": "none",
"is_reachable": False,
"is_internet_facing": False,
"has_compensating_controls": False,
"affected_assets": 1,
"affected_users": 0,
"compliance_frameworks": [],
"sla_hours": None,
"metadata": {
"cwe_ids": self.cwe_ids,
"cvss_vector": self.cvss_v31_vector,
"published": self.published,
"source_feeds": self.source_feeds,
"kev_due_date": self.kev_due_date,
"epss_percentile": self.epss_percentile,
},
}
# ---------------------------------------------------------------------------
# Feed state persistence (avoid duplicate processing)
# ---------------------------------------------------------------------------
class FeedState:
"""Tracks last-fetch timestamps and processed CVE IDs to avoid re-work."""
def __init__(self, state_path: Path = STATE_FILE):
self._path = state_path
self._data: Dict[str, Any] = {
"last_nvd_fetch": None,
"last_kev_fetch": None,
"last_epss_fetch": None,
"last_push": None,
"processed_cve_ids": [],
"total_pushed": 0,
"total_iterations": 0,
}
self._load()
def _load(self):
if self._path.exists():
try:
with open(self._path) as f:
stored = json.load(f)
self._data.update(stored)
except (json.JSONDecodeError, OSError) as exc:
logger.warning("Could not load feed state: %s", exc)
def save(self):
self._path.parent.mkdir(parents=True, exist_ok=True)
tmp = self._path.with_suffix(".tmp")
with open(tmp, "w") as f:
json.dump(self._data, f, indent=2, default=str)
tmp.replace(self._path)
def get(self, key: str) -> Any:
return self._data.get(key)
def set(self, key: str, value: Any):
self._data[key] = value
@property
def processed_ids(self) -> Set[str]:
return set(self._data.get("processed_cve_ids", []))
def mark_processed(self, cve_ids: List[str]):
existing = set(self._data.get("processed_cve_ids", []))
existing.update(cve_ids)
# Keep only the most recent 50_000 IDs to bound memory
if len(existing) > 50_000:
existing = set(list(existing)[-50_000:])
self._data["processed_cve_ids"] = list(existing)
def increment_pushed(self, count: int):
self._data["total_pushed"] = self._data.get("total_pushed", 0) + count
def increment_iterations(self):
self._data["total_iterations"] = self._data.get("total_iterations", 0) + 1
# ---------------------------------------------------------------------------
# HTTP helpers with retry + exponential backoff
# ---------------------------------------------------------------------------
async def _request_with_retry(
client: httpx.AsyncClient,
method: str,
url: str,
*,
max_retries: int = MAX_RETRIES,
base_delay: float = RETRY_BASE_DELAY,
**kwargs,
) -> httpx.Response:
"""Make an HTTP request with retries and exponential backoff.
Raises httpx.HTTPStatusError on persistent failure.
"""
last_exc: Optional[Exception] = None
for attempt in range(1, max_retries + 1):
try:
resp = await client.request(method, url, **kwargs)
# Retry on 429 (rate limited) and 5xx server errors
if resp.status_code == 429 or resp.status_code >= 500:
retry_after = float(resp.headers.get("Retry-After", 0))
delay = max(retry_after, base_delay * (2 ** (attempt - 1)))
logger.warning(
"HTTP %d from %s (attempt %d/%d), retrying in %.1fs",
resp.status_code,
url,
attempt,
max_retries,
delay,
)
await asyncio.sleep(delay)
continue
return resp
except (httpx.ConnectError, httpx.ReadTimeout, httpx.WriteTimeout) as exc:
last_exc = exc
delay = base_delay * (2 ** (attempt - 1))
logger.warning(
"Connection error to %s (attempt %d/%d): %s — retrying in %.1fs",
url,
attempt,
max_retries,
exc,
delay,
)
await asyncio.sleep(delay)
except httpx.HTTPError as exc:
last_exc = exc
delay = base_delay * (2 ** (attempt - 1))
logger.warning(
"HTTP error from %s (attempt %d/%d): %s — retrying in %.1fs",
url,
attempt,
max_retries,
exc,
delay,
)
await asyncio.sleep(delay)
raise httpx.ConnectError(
f"All {max_retries} retries exhausted for {url}: {last_exc}"
)
# ---------------------------------------------------------------------------
# NVD Feed Fetcher
# ---------------------------------------------------------------------------
async def fetch_nvd_cves(
client: httpx.AsyncClient,
days: int = 7,
nvd_api_key: str = "",
) -> List[Dict[str, Any]]:
"""Fetch CVEs published in the last `days` from the NVD 2.0 API.
Handles pagination and respects NVD rate limits:
- Without API key: 1 request per 6 seconds
- With API key: 1 request per 0.6 seconds
Returns the raw NVD "vulnerabilities" list.
"""
end_date = datetime.now(timezone.utc)
start_date = end_date - timedelta(days=days)
params: Dict[str, Any] = {
"pubStartDate": start_date.strftime("%Y-%m-%dT00:00:00.000"),
"pubEndDate": end_date.strftime("%Y-%m-%dT23:59:59.999"),
"resultsPerPage": NVD_PAGE_SIZE,
"startIndex": 0,
}
headers: Dict[str, str] = {}
if nvd_api_key:
headers["apiKey"] = nvd_api_key
rate_delay = NVD_RATE_LIMIT_DELAY_WITH_KEY if nvd_api_key else NVD_RATE_LIMIT_DELAY
all_vulns: List[Dict[str, Any]] = []
total_results = None
while True:
logger.info(
"NVD: fetching page at startIndex=%d (collected %d so far)",
params["startIndex"],
len(all_vulns),
)
try:
resp = await _request_with_retry(
client,
"GET",
NVD_API_URL,
params=params,
headers=headers,
timeout=httpx.Timeout(HTTP_TIMEOUT),
)
resp.raise_for_status()
data = resp.json()
except Exception as exc:
logger.error("NVD fetch failed at index %d: %s", params["startIndex"], exc)
break
vulns = data.get("vulnerabilities", [])
all_vulns.extend(vulns)
if total_results is None:
total_results = data.get("totalResults", 0)
logger.info("NVD: total results for query: %d", total_results)
# Check if we have all pages
if len(all_vulns) >= (total_results or 0):
break
params["startIndex"] += NVD_PAGE_SIZE
# Rate limit
await asyncio.sleep(rate_delay)
logger.info("NVD: fetched %d CVEs total", len(all_vulns))
return all_vulns
def parse_nvd_entry(entry: Dict[str, Any]) -> EnrichedCVE:
"""Parse a single NVD vulnerability entry into an EnrichedCVE."""
cve = entry.get("cve", {})
cve_id = cve.get("id", "UNKNOWN")
# Description (English preferred)
description = ""
for desc in cve.get("descriptions", []):
if desc.get("lang") == "en":
description = desc.get("value", "")
break
if not description:
descs = cve.get("descriptions", [])
description = descs[0].get("value", "") if descs else ""
# CVSS v3.1
cvss31_score = None
cvss31_vector = ""
cvss31_severity = ""
metrics = cve.get("metrics", {})
for metric_key in ("cvssMetricV31", "cvssMetricV30"):
metric_list = metrics.get(metric_key, [])
if metric_list:
primary = metric_list[0]
cvss_data = primary.get("cvssData", {})
cvss31_score = cvss_data.get("baseScore")
cvss31_vector = cvss_data.get("vectorString", "")
cvss31_severity = cvss_data.get("baseSeverity", "")
break
# CVSS v2 fallback
cvss2_score = None
v2_list = metrics.get("cvssMetricV2", [])
if v2_list:
cvss2_score = v2_list[0].get("cvssData", {}).get("baseScore")
# CWE IDs
cwe_ids: List[str] = []
for weakness in cve.get("weaknesses", []):
for desc_item in weakness.get("description", []):
val = desc_item.get("value", "")
if val.startswith("CWE-"):
cwe_ids.append(val)
# References
refs: List[str] = []
for ref in cve.get("references", [])[:10]:
url = ref.get("url", "")
if url:
refs.append(url)
# Detect exploit references
tags = ref.get("tags", [])
has_exploit = any(
t.lower() in ("exploit", "third party advisory") for t in tags
)
# Exploit maturity heuristic
exploit_maturity = "unknown"
if has_exploit:
exploit_maturity = "poc_public"
published = cve.get("published", "")
last_modified = cve.get("lastModified", "")
return EnrichedCVE(
cve_id=cve_id,
description=description,
cvss_v31_score=cvss31_score,
cvss_v31_vector=cvss31_vector,
cvss_v31_severity=cvss31_severity,
cvss_v2_score=cvss2_score,
cwe_ids=cwe_ids,
published=published,
last_modified=last_modified,
references=refs,
has_exploit=has_exploit,
exploit_maturity=exploit_maturity,
feed_timestamp=datetime.now(timezone.utc).isoformat(),
source_feeds=["nvd"],
)
# ---------------------------------------------------------------------------
# CISA KEV Feed Fetcher
# ---------------------------------------------------------------------------
async def fetch_kev_catalog(
client: httpx.AsyncClient,
) -> Dict[str, Dict[str, Any]]:
"""Fetch the full CISA KEV catalog.
Returns a dict keyed by CVE ID for O(1) correlation lookup.
"""
logger.info("KEV: fetching CISA Known Exploited Vulnerabilities catalog")
try:
resp = await _request_with_retry(
client,
"GET",
CISA_KEV_URL,
timeout=httpx.Timeout(HTTP_TIMEOUT),
)
resp.raise_for_status()
data = resp.json()
except Exception as exc:
logger.error("KEV fetch failed: %s", exc)
return {}
vulnerabilities = data.get("vulnerabilities", [])
kev_map: Dict[str, Dict[str, Any]] = {}
for vuln in vulnerabilities:
cve_id = vuln.get("cveID", "")
if cve_id:
kev_map[cve_id] = vuln
logger.info(
"KEV: loaded %d entries (catalog version: %s, released: %s)",
len(kev_map),
data.get("catalogVersion", "?"),
data.get("dateReleased", "?"),
)
return kev_map
# ---------------------------------------------------------------------------
# EPSS Feed Fetcher
# ---------------------------------------------------------------------------
async def fetch_epss_scores(
client: httpx.AsyncClient,
cve_ids: List[str],
) -> Dict[str, Dict[str, float]]:
"""Fetch EPSS scores for a list of CVE IDs.
The FIRST EPSS API accepts up to ~100 CVEs per request via the
`cve` query parameter (comma-separated).
Returns a dict keyed by CVE ID: {"score": float, "percentile": float}.
"""
if not cve_ids:
return {}
epss_map: Dict[str, Dict[str, float]] = {}
# Process in chunks of 100 (EPSS API limit)
chunk_size = 100
chunks = [cve_ids[i : i + chunk_size] for i in range(0, len(cve_ids), chunk_size)]
for i, chunk in enumerate(chunks):
cve_param = ",".join(chunk)
logger.info(
"EPSS: fetching scores for chunk %d/%d (%d CVEs)",
i + 1,
len(chunks),
len(chunk),
)
try:
resp = await _request_with_retry(
client,
"GET",
EPSS_API_URL,
params={"cve": cve_param},
timeout=httpx.Timeout(HTTP_TIMEOUT),
)
resp.raise_for_status()
data = resp.json()
for entry in data.get("data", []):
cve_id = entry.get("cve", "")
if cve_id:
try:
epss_map[cve_id] = {
"score": float(entry.get("epss", 0)),
"percentile": float(entry.get("percentile", 0)),
}
except (ValueError, TypeError):
pass
except Exception as exc:
logger.warning("EPSS fetch failed for chunk %d: %s", i + 1, exc)
# Small delay between EPSS requests to be polite
if i < len(chunks) - 1:
await asyncio.sleep(1.0)
logger.info("EPSS: retrieved scores for %d / %d CVEs", len(epss_map), len(cve_ids))
return epss_map
# ---------------------------------------------------------------------------
# Correlation Engine
# ---------------------------------------------------------------------------
def correlate_feeds(
nvd_cves: List[EnrichedCVE],
kev_map: Dict[str, Dict[str, Any]],
epss_map: Dict[str, Dict[str, float]],
) -> List[EnrichedCVE]:
"""Merge NVD + KEV + EPSS data per CVE ID.
Each CVE from NVD is enriched with KEV and EPSS data where available.
"""
correlated: List[EnrichedCVE] = []
for cve in nvd_cves:
# Enrich with KEV data
kev_entry = kev_map.get(cve.cve_id)
if kev_entry:
cve.is_kev = True
cve.kev_vendor = kev_entry.get("vendorProject", "")
cve.kev_product = kev_entry.get("product", "")
cve.kev_date_added = kev_entry.get("dateAdded", "")
cve.kev_due_date = kev_entry.get("dueDate", "")
cve.kev_description = kev_entry.get("shortDescription", "")
cve.kev_required_action = kev_entry.get("requiredAction", "")
cve.has_exploit = True
if cve.exploit_maturity in ("unknown", "theoretical"):
cve.exploit_maturity = "weaponized"
if "kev" not in cve.source_feeds:
cve.source_feeds.append("kev")
# Enrich with EPSS data
epss_entry = epss_map.get(cve.cve_id)
if epss_entry:
cve.epss_score = epss_entry.get("score")
cve.epss_percentile = epss_entry.get("percentile")
if "epss" not in cve.source_feeds:
cve.source_feeds.append("epss")
correlated.append(cve)
# Sort by risk: KEV first, then by EPSS desc, then by CVSS desc
correlated.sort(
key=lambda c: (
-(1 if c.is_kev else 0),
-(c.epss_score or 0),
-(c.cvss_v31_score or c.cvss_v2_score or 0),
)
)
kev_count = sum(1 for c in correlated if c.is_kev)
epss_count = sum(1 for c in correlated if c.epss_score is not None)
logger.info(
"Correlation: %d CVEs total, %d in KEV, %d with EPSS scores",
len(correlated),
kev_count,
epss_count,
)
return correlated
# ---------------------------------------------------------------------------
# FAIL API Push
# ---------------------------------------------------------------------------
async def push_to_fail_engine(
client: httpx.AsyncClient,
cves: List[EnrichedCVE],
batch_size: int = BATCH_PUSH_SIZE,
) -> Dict[str, int]:
"""Push enriched CVEs to ALdeci FAIL scoring endpoint in batches.
Uses POST /api/v1/fail/score/batch with up to `batch_size` findings
per request.
Returns {"pushed": int, "failed": int, "skipped": int}.
"""
stats = {"pushed": 0, "failed": 0, "skipped": 0, "total_score": 0.0}
if not cves:
logger.info("FAIL push: no CVEs to push")
return stats
# Build batches
payloads = [cve.to_fail_payload() for cve in cves]
batches = [
payloads[i : i + batch_size] for i in range(0, len(payloads), batch_size)
]
for i, batch in enumerate(batches):
logger.info(
"FAIL push: sending batch %d/%d (%d findings)",
i + 1,
len(batches),
len(batch),
)
body = {"findings": batch}
try:
resp = await _request_with_retry(
client,
"POST",
f"{BASE_URL}/api/v1/fail/score/batch",
json=body,
timeout=httpx.Timeout(120.0),
)
if resp.status_code in (200, 201):
result = resp.json()
batch_total = result.get("total", 0)
stats["pushed"] += batch_total
# Log grade distribution from response
resp_stats = result.get("stats", {})
grade_dist = resp_stats.get("grade_distribution", {})
if grade_dist:
logger.info(
"FAIL batch %d results: CRITICAL=%d HIGH=%d MEDIUM=%d LOW=%d INFO=%d",
i + 1,
grade_dist.get("CRITICAL", 0),
grade_dist.get("HIGH", 0),
grade_dist.get("MEDIUM", 0),
grade_dist.get("LOW", 0),
grade_dist.get("INFO", 0),
)
elif resp.status_code == 422:
logger.warning(
"FAIL batch %d rejected (422): %s",
i + 1,
resp.text[:500],
)
stats["failed"] += len(batch)
else:
logger.warning(
"FAIL batch %d returned %d: %s",
i + 1,
resp.status_code,
resp.text[:200],
)
stats["failed"] += len(batch)
except Exception as exc:
logger.error("FAIL batch %d push failed: %s", i + 1, exc)
stats["failed"] += len(batch)
logger.info(
"FAIL push complete: pushed=%d failed=%d skipped=%d",
stats["pushed"],
stats["failed"],
stats["skipped"],
)
return stats
# ---------------------------------------------------------------------------
# Cache helpers -- persist feed data to disk
# ---------------------------------------------------------------------------
def _save_cache(path: Path, data: Any):
"""Atomically write JSON cache to disk."""
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp")
with open(tmp, "w") as f:
json.dump(data, f, default=str)
tmp.replace(path)
def _load_cache(path: Path) -> Optional[Any]:
"""Load JSON cache from disk, return None if missing or corrupt."""
if not path.exists():
return None
try:
with open(path) as f:
return json.load(f)
except (json.JSONDecodeError, OSError):
return None
def save_correlated_cves(cves: List[EnrichedCVE]):
"""Save correlated CVE data to disk for offline access."""
records = [asdict(cve) for cve in cves]
_save_cache(CORRELATED_FILE, {
"timestamp": datetime.now(timezone.utc).isoformat(),
"count": len(records),
"cves": records,
})
logger.info("Saved %d correlated CVEs to %s", len(records), CORRELATED_FILE)
# ---------------------------------------------------------------------------
# Demo Mode -- synthetic data for offline / demo environments
# ---------------------------------------------------------------------------
# Realistic CVE templates based on real-world patterns
_DEMO_CVES = [
{
"cve_id": "CVE-2024-3094",
"description": "Malicious code was discovered in the upstream tarballs of xz-utils, starting with version 5.6.0. Through a series of complex obfuscations, the liblzma build process extracts a prebuilt object file that modifies specific functions in the code.",
"cvss_v31_score": 10.0,
"cvss_v31_severity": "CRITICAL",
"cwe_ids": ["CWE-506"],
"is_kev": True,
"epss_score": 0.97,
"epss_percentile": 0.999,
"exploit_maturity": "weaponized",
"kev_vendor": "Tukaani",
"kev_product": "xz-utils",
},
{
"cve_id": "CVE-2024-21762",
"description": "A out-of-bounds write vulnerability in Fortinet FortiOS versions 7.4.0 through 7.4.2, 7.2.0 through 7.2.6, 7.0.0 through 7.0.13 allows attacker to execute unauthorized code via specially crafted requests.",
"cvss_v31_score": 9.8,
"cvss_v31_severity": "CRITICAL",
"cwe_ids": ["CWE-787"],
"is_kev": True,
"epss_score": 0.94,
"epss_percentile": 0.998,
"exploit_maturity": "weaponized",
"kev_vendor": "Fortinet",
"kev_product": "FortiOS",
},
{
"cve_id": "CVE-2024-1709",
"description": "ConnectWise ScreenConnect 23.9.7 and prior are affected by an Authentication Bypass Using an Alternate Path or Channel vulnerability, which may allow an attacker direct access to confidential information or critical systems.",
"cvss_v31_score": 10.0,
"cvss_v31_severity": "CRITICAL",
"cwe_ids": ["CWE-288"],
"is_kev": True,
"epss_score": 0.96,
"epss_percentile": 0.998,
"exploit_maturity": "weaponized",
"kev_vendor": "ConnectWise",
"kev_product": "ScreenConnect",
},
{
"cve_id": "CVE-2023-44487",
"description": "The HTTP/2 protocol allows a denial of service (server resource consumption) because request cancellation can reset many streams quickly, as exploited in the wild in August through October 2023 (Rapid Reset Attack).",
"cvss_v31_score": 7.5,
"cvss_v31_severity": "HIGH",
"cwe_ids": ["CWE-400"],
"is_kev": True,
"epss_score": 0.82,
"epss_percentile": 0.98,
"exploit_maturity": "weaponized",
"kev_vendor": "IETF",
"kev_product": "HTTP/2",
},
{
"cve_id": "CVE-2024-23897",
"description": "Jenkins 2.441 and earlier, LTS 2.426.2 and earlier does not disable a feature of its CLI command parser that replaces an '@' character followed by a file path in an argument with the file's contents, allowing unauthenticated attackers to read arbitrary files.",
"cvss_v31_score": 9.8,
"cvss_v31_severity": "CRITICAL",
"cwe_ids": ["CWE-22"],
"is_kev": True,
"epss_score": 0.89,
"epss_percentile": 0.995,
"exploit_maturity": "poc_public",
"kev_vendor": "Jenkins",
"kev_product": "Jenkins",
},
{
"cve_id": "CVE-2024-6387",
"description": "A signal handler race condition was found in OpenSSH's server (sshd), where a client does not authenticate within LoginGraceTime seconds (120 by default, 600 in old OpenSSH versions), then sshd's SIGALRM handler is called asynchronously.",
"cvss_v31_score": 8.1,
"cvss_v31_severity": "HIGH",
"cwe_ids": ["CWE-362", "CWE-364"],
"is_kev": False,
"epss_score": 0.45,
"epss_percentile": 0.95,
"exploit_maturity": "poc_public",
"kev_vendor": "OpenSSH",
"kev_product": "OpenSSH",
},
{
"cve_id": "CVE-2024-27198",
"description": "In JetBrains TeamCity before 2023.11.4, authentication bypass was possible, allowing an attacker to perform admin actions.",
"cvss_v31_score": 9.8,
"cvss_v31_severity": "CRITICAL",
"cwe_ids": ["CWE-288"],
"is_kev": True,
"epss_score": 0.92,
"epss_percentile": 0.997,
"exploit_maturity": "weaponized",
"kev_vendor": "JetBrains",
"kev_product": "TeamCity",
},
{
"cve_id": "CVE-2024-4577",
"description": "In PHP versions 8.1.* before 8.1.29, 8.2.* before 8.2.20, 8.3.* before 8.3.8, when using Apache and PHP-CGI on Windows, if the system is set up to use certain code pages, Windows may use \"Best-Fit\" behavior to replace characters in command line given to Win32 API functions.",
"cvss_v31_score": 9.8,
"cvss_v31_severity": "CRITICAL",
"cwe_ids": ["CWE-78"],
"is_kev": True,
"epss_score": 0.88,
"epss_percentile": 0.994,
"exploit_maturity": "weaponized",
"kev_vendor": "PHP Group",
"kev_product": "PHP",
},
{
"cve_id": "CVE-2024-47575",
"description": "A missing authentication for critical function vulnerability in FortiManager fgfmd daemon may allow a remote unauthenticated attacker to execute arbitrary code or commands via specially crafted requests.",
"cvss_v31_score": 9.8,
"cvss_v31_severity": "CRITICAL",
"cwe_ids": ["CWE-306"],
"is_kev": True,
"epss_score": 0.91,
"epss_percentile": 0.996,
"exploit_maturity": "weaponized",
"kev_vendor": "Fortinet",
"kev_product": "FortiManager",
},
{
"cve_id": "CVE-2024-0012",
"description": "An authentication bypass in Palo Alto Networks PAN-OS software enables an unauthenticated attacker with network access to the management web interface to gain PAN-OS administrator privileges.",
"cvss_v31_score": 9.8,
"cvss_v31_severity": "CRITICAL",
"cwe_ids": ["CWE-306"],
"is_kev": True,
"epss_score": 0.87,
"epss_percentile": 0.993,
"exploit_maturity": "weaponized",
"kev_vendor": "Palo Alto Networks",
"kev_product": "PAN-OS",
},
{
"cve_id": "CVE-2024-20353",
"description": "A vulnerability in the management and VPN web servers for Cisco Adaptive Security Appliance (ASA) Software and Cisco Firepower Threat Defense (FTD) Software could allow an unauthenticated, remote attacker to cause the device to reload unexpectedly.",
"cvss_v31_score": 8.6,
"cvss_v31_severity": "HIGH",
"cwe_ids": ["CWE-835"],
"is_kev": True,
"epss_score": 0.74,
"epss_percentile": 0.97,
"exploit_maturity": "poc_public",
"kev_vendor": "Cisco",
"kev_product": "ASA",
},
{
"cve_id": "CVE-2024-29824",
"description": "An unspecified SQL Injection vulnerability in Core server of Ivanti EPM 2022 SU5 and prior allows an unauthenticated attacker within the same network to execute arbitrary code.",
"cvss_v31_score": 9.6,
"cvss_v31_severity": "CRITICAL",
"cwe_ids": ["CWE-89"],
"is_kev": True,
"epss_score": 0.85,
"epss_percentile": 0.99,
"exploit_maturity": "weaponized",
"kev_vendor": "Ivanti",
"kev_product": "EPM",
},
{
"cve_id": "CVE-2024-38812",
"description": "The vCenter Server contains a heap-overflow vulnerability in the implementation of the DCERPC protocol. A malicious actor with network access to vCenter Server may trigger this vulnerability by sending a specially crafted network packet.",
"cvss_v31_score": 9.8,
"cvss_v31_severity": "CRITICAL",
"cwe_ids": ["CWE-122"],
"is_kev": False,
"epss_score": 0.55,
"epss_percentile": 0.96,
"exploit_maturity": "poc_public",
"kev_vendor": "VMware",
"kev_product": "vCenter Server",
},
{
"cve_id": "CVE-2024-9474",
"description": "A privilege escalation vulnerability in Palo Alto Networks PAN-OS software allows a PAN-OS administrator with access to the management web interface to perform actions on the firewall with root privileges.",
"cvss_v31_score": 7.2,
"cvss_v31_severity": "HIGH",
"cwe_ids": ["CWE-78"],
"is_kev": True,
"epss_score": 0.67,
"epss_percentile": 0.97,
"exploit_maturity": "poc_public",
"kev_vendor": "Palo Alto Networks",
"kev_product": "PAN-OS",
},
{
"cve_id": "CVE-2024-50623",
"description": "In Cleo Harmony, VLTrader, and LexiCom before specified versions, there is unrestricted file upload and download that could lead to remote code execution.",
"cvss_v31_score": 9.8,
"cvss_v31_severity": "CRITICAL",
"cwe_ids": ["CWE-434"],
"is_kev": True,
"epss_score": 0.90,
"epss_percentile": 0.996,
"exploit_maturity": "weaponized",
"kev_vendor": "Cleo",
"kev_product": "Harmony/VLTrader/LexiCom",