Repository navigation
Expand file tree
/
Copy pathapi_aggregator.py
More file actions
1106 lines (1015 loc) · 51.3 KB
/
Copy pathapi_aggregator.py
File metadata and controls
1106 lines (1015 loc) · 51.3 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
# -*- coding: utf-8 -*-
"""
CyberCodex - 21-Source Zero-Cost Public OSINT, Breach/Leak & Threat Intel Engine
================================================================================
Queries 21 authoritative, free, NO-API-KEY public intelligence feeds & APIs:
1. Shodan InternetDB (`internetdb.shodan.io`) -> Open ports, CPEs, tags, CVEs
2. HaveIBeenPwned Breaches API (`haveibeenpwned`) -> Latest leak date, top leak size, leaked DataClasses & narrative
3. Hudson Rock Cavalier API (`cavalier.hudsonrock`) -> Real-world Infostealer (RedLine/Raccoon/Lumma) employee & user compromises
4. HIBP Pwned Passwords K-Anonymity API -> 850M+ breached password frequency check via SHA-1 prefix
5. HTTP Security Headers & RFC 9116 `security.txt` -> Live CSP, HSTS, XFO, Server banner & posture grade (A+ to F)
6. FIRST.org EPSS API (`api.first.org`) -> 30-day exploit probability score
7. MITRE CVE AWG v5 API (`cveawg.mitre.org`) -> Official CVE metadata & CVSS
8. CIRCL.lu CVE API (`cve.circl.lu`) -> Secondary CVE enrichment
9. GitHub Public Exploit/PoC Search API -> Live public PoC exploit repos & stars
10. CISA KEV Catalog -> Active exploitation & ransomware status
11. abuse.ch Feodo Tracker -> Active Botnet C2 IP blocklist
12. abuse.ch ThreatFox API -> IOC & Malware family attribution
13. CyberCodex Historical Malware Vault -> SHA256/MD5 famous APT implant attribution
14. Official Tor Project Bulk Exit List -> Active Tor Exit Node verification
15. ip-api / RDAP Network Telemetry -> ASN, ISP, Org, Reverse DNS, Hosting
16. RIPE NCC Stat BGP API (`stat.ripe.net`) -> BGP announced CIDR prefix & ASN routing
17. Cloudflare DoH JSON API (`cloudflare-dns`) -> Live MX, NS, TXT, SPF & DMARC Spoofing audit
18. Live TLS/SSL X.509 Socket Inspector -> SHA-256 cert fingerprint, TLS version, C2 check
19. crt.sh Certificate Transparency -> Subdomain & SSL discovery
20. Wayback Machine CDX API -> Archived endpoint discovery
21. Ransomware.live & PhishStats Public API -> Real-time global ransomware & phishing URLs
# TR: 21 farklı ücretsiz ve API anahtarsız istihbarat, veri sızıntısı (Leak/Breach),
# Infostealer logları ve altyapı kaynağını paralel sorgulayan motor.
"""
import hashlib
import html
import ipaddress
import json
import os
import re
import socket
import ssl
import time
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from typing import Dict, Any, List, Optional
from incident_codex import IncidentCodexEngine
from live_updater import LiveThreatUpdater, DATA_DIR
CACHE_FILE = os.path.join(DATA_DIR, "api_query_cache.json")
KNOWN_MALWARE_HASH_SEED: Dict[str, Dict[str, Any]] = {
"32519b85c0b422e4656de6e6c41878e95fd95026267daab4215ee59c107d6c77": {
"malware_family": "SUNBURST / Solorigate Backdoor (APT29)",
"file_name": "SolarWinds.BusinessLayer.dll",
"file_type": "PE32+ DLL (Signed Supply Chain Implant)",
"severity": "CRITICAL",
"linked_attack": "solarwinds",
},
"027cc450ef5f8c5f653329641ec1fed91f694e0d229928963b30f6b0d7d3a745": {
"malware_family": "NotPetya / ExPetr Destructive MBR/MFT Wiper (Sandworm)",
"file_name": "perfc.dat",
"file_type": "PE32 DLL Wiper + EternalBlue Worm",
"severity": "CRITICAL",
"linked_attack": "notpetya",
},
"ed01ebfbc9eb5bbea545af4d01bf5f1071661840480439c6e5babe8e080e41aa": {
"malware_family": "WannaCry / WannaCryptor 2.0 SMBv1 Cryptoworm (Lazarus)",
"file_name": "tasksche.exe / wcry.exe",
"file_type": "PE32 Executable Dropper",
"severity": "CRITICAL",
"linked_attack": "wannacry",
},
"816000dc5fb8d2b65c2ab4bd8fd2bb9b6ab5b8c25cfcc4ffbe3cd2cdcc82cd50": {
"malware_family": "Lazarus SWIFT Alliance Access Memory Patcher (Bangladesh Bank Heist)",
"file_name": "evtdiag.exe",
"file_type": "PE32 Financial Rootkit Implant",
"severity": "CRITICAL",
"linked_attack": "lazarus-swift",
},
"238dc9f5c22b4d936c30b6216f18691e23c9160a6c7b599d3b66f95f97b22201": {
"malware_family": "XZ Utils 5.6.1 Backdoored Release Archive (JiaT75 / CVE-2024-3094)",
"file_name": "xz-5.6.1.tar.gz",
"file_type": "POSIX tar archive (liblzma IFUNC SSHD backdoor)",
"severity": "CRITICAL",
"linked_attack": "xz-backdoor",
},
}
class ZeroCostAPIAggregator:
"""
21-Source Parallel Zero-Cost OSINT, Data Breach/Leak, Infostealer & Threat Intel
Aggregator with local TTL caching and automatic Incident Codex correlation.
"""
def __init__(self, updater: Optional[LiveThreatUpdater] = None, cache_ttl_seconds: int = 3600):
os.makedirs(DATA_DIR, exist_ok=True)
self.updater = updater or LiveThreatUpdater()
self.codex = IncidentCodexEngine()
self.cache_ttl = cache_ttl_seconds
self._cache: Dict[str, Dict[str, Any]] = self._load_cache()
def _load_cache(self) -> Dict[str, Dict[str, Any]]:
if os.path.exists(CACHE_FILE):
try:
with open(CACHE_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
return {}
def _save_cache(self) -> None:
try:
with open(CACHE_FILE, "w", encoding="utf-8") as f:
json.dump(self._cache, f, ensure_ascii=False, indent=2)
except Exception:
pass
def _get_cached(self, key: str) -> Optional[Dict[str, Any]]:
entry = self._cache.get(key)
if entry and (time.time() - entry.get("ts", 0)) < self.cache_ttl:
data = dict(entry["data"])
data["cache_hit"] = True
return data
return None
def _set_cached(self, key: str, data: Dict[str, Any]) -> None:
self._cache[key] = {"ts": time.time(), "data": data}
self._save_cache()
def _http_get_json(self, url: str, timeout: float = 5.5, extra_headers: Optional[Dict[str, str]] = None) -> Optional[Any]:
ctx = ssl.create_default_context()
headers = {
"User-Agent": "CyberCodex-OSINT-Aggregator/3.0 (+https://github.com/prox0959)",
"Accept": "application/json",
}
if extra_headers:
headers.update(extra_headers)
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
raw = resp.read().decode("utf-8", errors="replace")
return json.loads(raw)
except Exception:
return None
def _http_post_json(self, url: str, payload: Dict[str, Any], timeout: float = 5.5) -> Optional[Any]:
ctx = ssl.create_default_context()
body = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
url,
data=body,
headers={
"User-Agent": "CyberCodex-OSINT-Aggregator/3.0",
"Content-Type": "application/json",
"Accept": "application/json",
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
raw = resp.read().decode("utf-8", errors="replace")
return json.loads(raw)
except Exception:
return None
@staticmethod
def _strip_html(raw_html: str) -> str:
clean = re.sub(r"<[^>]+>", "", raw_html or "")
return html.unescape(clean).strip()
@staticmethod
def _is_ip(target: str) -> bool:
try:
ipaddress.ip_address(target)
return True
except ValueError:
return False
def _query_hibp_domain_breaches(self, domain: str) -> Dict[str, Any]:
"""
Queries HaveIBeenPwned (HIBP) v3 public breaches endpoint for a domain (zero API key!).
Extracts:
- Total breach count & cumulative compromised records (PwnCount)
- Most recent leak (latest BreachDate)
- Top / largest leak (highest PwnCount)
- Compromised data classes (Email addresses, Passwords, Phone numbers, etc.)
- Clean incident forensic description
"""
if not domain:
return {}
# Strip subdomains to apex domain while preserving multi-part country TLDs (.k12.tr, .com.tr, .co.uk, etc.)
parts = domain.lower().strip().split(".")
multi_tlds = ("co", "com", "org", "gov", "edu", "k12", "bel", "pol", "mil", "net", "ac", "sch", "av", "dr", "gen")
if len(parts) > 2:
if parts[-2] in multi_tlds and len(parts) >= 3:
apex = ".".join(parts[-3:])
else:
apex = ".".join(parts[-2:])
else:
apex = domain.lower().strip()
url = f"https://haveibeenpwned.com/api/v3/breaches?Domain={urllib.parse.quote(apex)}"
data = self._http_get_json(url, timeout=6.0)
if not isinstance(data, list) or not data:
return {
"breach_count": 0,
"total_pwn_count": 0,
"most_recent_leak": None,
"top_largest_leak": None,
"all_leaked_data_classes": [],
"breach_timeline": [],
}
normalized: List[Dict[str, Any]] = []
all_classes = set()
total_pwn = 0
for b in data:
if not isinstance(b, dict):
continue
pwn = int(b.get("PwnCount", 0) or 0)
total_pwn += pwn
dclasses = b.get("DataClasses", []) or []
for c in dclasses:
all_classes.add(c)
normalized.append({
"name": b.get("Name", ""),
"title": b.get("Title", ""),
"domain": b.get("Domain", apex),
"breach_date": b.get("BreachDate", "Unknown"),
"added_date": str(b.get("AddedDate", ""))[:10],
"pwn_count": pwn,
"data_classes": dclasses,
"description": self._strip_html(b.get("Description", "")),
"is_verified": bool(b.get("IsVerified", True)),
"is_stealer_log": bool(b.get("IsStealerLog", False)),
})
by_date = sorted(normalized, key=lambda x: x["breach_date"], reverse=True)
by_size = sorted(normalized, key=lambda x: x["pwn_count"], reverse=True)
return {
"breach_count": len(normalized),
"total_pwn_count": total_pwn,
"most_recent_leak": by_date[0] if by_date else None,
"top_largest_leak": by_size[0] if by_size else None,
"all_leaked_data_classes": sorted(all_classes),
"breach_timeline": by_date,
}
def _query_hudsonrock_stealers(self, target: str, mode: str = "domain") -> Dict[str, Any]:
"""
Queries Hudson Rock Cavalier Free Public Infostealer API (zero API key!).
Provides real-world RedLine, Raccoon, Lumma, Vidar, Azorult stealer log exposure,
compromised URLs + credential counts, and user/employee password complexity audits.
"""
if not target:
return {}
clean = target.strip().lower()
if mode == "domain":
url = f"https://cavalier.hudsonrock.com/api/json/v2/osint-tools/search-by-domain?domain={urllib.parse.quote(clean)}"
data = self._http_get_json(url, timeout=9.5)
if isinstance(data, dict) and ("total" in data or "employees" in data):
fams = dict(data.get("stealerFamilies") or {})
fams.pop("total", None)
top_fams = sorted(fams.items(), key=lambda x: x[1], reverse=True)[:8]
emp_pass = data.get("employeePasswords") or {}
usr_pass = data.get("userPasswords") or {}
raw_data_block = data.get("data") or {}
client_urls = []
for u in (raw_data_block.get("clients_urls") or [])[:50]:
if isinstance(u, dict) and u.get("url"):
client_urls.append({
"url": u.get("url", ""),
"occurrence": int(u.get("occurrence", 0) or 0),
"type": u.get("type", "User"),
})
emp_urls = []
for u in (raw_data_block.get("employees_urls") or [])[:50]:
if isinstance(u, dict) and u.get("url"):
emp_urls.append({
"url": u.get("url", ""),
"occurrence": int(u.get("occurrence", 0) or 0),
"type": u.get("type", "Employee"),
})
av_block = data.get("antiviruses") or {}
av_list = []
for av in (av_block.get("list") or [])[:15]:
if isinstance(av, dict) and av.get("name"):
av_list.append({"name": av.get("name"), "count": av.get("count", 0)})
tp_domains = []
for tp in (data.get("thirdPartyDomains") or [])[:20]:
if isinstance(tp, dict) and tp.get("domain"):
tp_domains.append({"domain": tp.get("domain"), "occurrence": tp.get("occurrence", 0)})
return {
"total_compromised": data.get("total", 0),
"employees_compromised": data.get("employees", 0),
"users_compromised": data.get("users", 0),
"third_parties_compromised": data.get("third_parties", 0),
"last_employee_compromised": str(data.get("last_employee_compromised") or "None")[:10],
"last_user_compromised": str(data.get("last_user_compromised") or "None")[:10],
"top_stealer_families": dict(top_fams),
"compromised_client_urls": client_urls,
"compromised_employee_urls": emp_urls,
"bypassed_antiviruses": av_list,
"third_party_domains": tp_domains,
"employee_password_audit": {
"total_audited": emp_pass.get("totalPass", 0),
"too_weak_qty": (emp_pass.get("too_weak") or {}).get("qty", 0),
"too_weak_pct": (emp_pass.get("too_weak") or {}).get("perc", 0),
"weak_qty": (emp_pass.get("weak") or {}).get("qty", 0),
"weak_pct": (emp_pass.get("weak") or {}).get("perc", 0),
"medium_qty": (emp_pass.get("medium") or {}).get("qty", 0),
"medium_pct": (emp_pass.get("medium") or {}).get("perc", 0),
"strong_qty": (emp_pass.get("strong") or {}).get("qty", 0),
"strong_pct": (emp_pass.get("strong") or {}).get("perc", 0),
},
"user_password_audit": {
"total_audited": usr_pass.get("totalPass", 0),
"too_weak_qty": (usr_pass.get("too_weak") or {}).get("qty", 0),
"too_weak_pct": (usr_pass.get("too_weak") or {}).get("perc", 0),
"weak_qty": (usr_pass.get("weak") or {}).get("qty", 0),
"weak_pct": (usr_pass.get("weak") or {}).get("perc", 0),
"medium_qty": (usr_pass.get("medium") or {}).get("qty", 0),
"medium_pct": (usr_pass.get("medium") or {}).get("perc", 0),
"strong_qty": (usr_pass.get("strong") or {}).get("qty", 0),
"strong_pct": (usr_pass.get("strong") or {}).get("perc", 0),
},
}
elif mode in ("email", "username", "ip"):
url = f"https://cavalier.hudsonrock.com/api/json/v2/osint-tools/search-by-{mode}?{mode}={urllib.parse.quote(clean)}"
data = self._http_get_json(url, timeout=6.0)
if isinstance(data, dict) and isinstance(data.get("stealers"), list):
stealers = []
for s in data["stealers"][:25]:
if isinstance(s, dict):
stealers.append({
"date_compromised": str(s.get("date_compromised", ""))[:19],
"computer_name": s.get("computer_name", "Redacted"),
"operating_system": s.get("operating_system", "Unknown"),
"malware_path": s.get("malware_path", "Unknown"),
"ip": s.get("ip", "Redacted"),
"antiviruses": s.get("antiviruses", []),
"top_passwords": s.get("top_passwords", []),
"top_logins": s.get("top_logins", []),
"total_corporate_services": s.get("total_corporate_services", 0),
"total_user_services": s.get("total_user_services", 0),
})
return {
"message": data.get("message", ""),
"stealer_count": len(data.get("stealers", [])),
"stealers": stealers,
}
return {}
def _query_proxynova_comb_leaks(self, query: str, limit: int = 100) -> Dict[str, Any]:
"""
Queries ProxyNova COMB (Compilation of Many Breaches - 3.2 Billion Records) public API.
Extracts actual leaked email:password lines matching the target domain, email, or username.
"""
if not query:
return {"total_count": 0, "leaked_lines": []}
q = urllib.parse.quote(query.strip())
url = f"https://api.proxynova.com/comb?query={q}&start=0&limit={limit}"
data = self._http_get_json(url, timeout=6.5)
if isinstance(data, dict) and "lines" in data:
lines = [str(line).strip() for line in (data.get("lines") or []) if str(line).strip()]
return {
"total_count": int(data.get("count", len(lines)) or 0),
"leaked_lines": lines,
}
return {"total_count": 0, "leaked_lines": []}
def _query_wayback_leak_snapshots(self, domain: str, limit: int = 40) -> List[Dict[str, str]]:
"""
Queries Internet Archive CDX API for historical archived URLs and generates direct
raw download links (https://web.archive.org/web/<timestamp>id_/<original_url>).
"""
if not domain:
return []
q = urllib.parse.quote(f"{domain}/*")
url = (
f"https://web.archive.org/cdx/search/cdx?url={q}"
f"&output=json&fl=timestamp,original,mimetype,statuscode&collapse=urlkey&limit={limit}"
)
data = self._http_get_json(url, timeout=6.0)
snapshots: List[Dict[str, str]] = []
if isinstance(data, list) and len(data) > 1:
for row in data[1:]:
if isinstance(row, list) and len(row) >= 2:
ts = str(row[0])
orig = str(row[1])
mime = str(row[2]) if len(row) > 2 else "unknown"
code = str(row[3]) if len(row) > 3 else "200"
snapshots.append({
"timestamp": ts,
"original_url": orig,
"mimetype": mime,
"status_code": code,
"direct_download_url": f"https://web.archive.org/web/{ts}id_/{orig}",
})
return snapshots
def _query_http_security_headers(self, domain: str) -> Dict[str, Any]:
"""
Inspects live HTTP response security headers (HSTS, CSP, X-Frame-Options,
X-Content-Type-Options, Server banner) and RFC 9116 /.well-known/security.txt.
"""
if not domain:
return {}
ctx = ssl.create_default_context()
headers_found: Dict[str, str] = {}
status_code = 0
for scheme in ("https", "http"):
try:
req = urllib.request.Request(
f"{scheme}://{domain}/",
headers={"User-Agent": "Mozilla/5.0 CyberCodex-SecurityAudit/3.0"},
method="GET",
)
with urllib.request.urlopen(req, timeout=4.0, context=ctx) as resp:
status_code = resp.status
for k, v in resp.headers.items():
headers_found[k.lower()] = v
break
except Exception:
continue
if not headers_found:
return {}
# Check RFC 9116 /.well-known/security.txt
sec_txt_found = False
try:
req_sec = urllib.request.Request(
f"https://{domain}/.well-known/security.txt",
headers={"User-Agent": "Mozilla/5.0 CyberCodex-SecurityAudit/3.0"},
)
with urllib.request.urlopen(req_sec, timeout=3.0, context=ctx) as resp_sec:
body = resp_sec.read(512).decode("utf-8", errors="replace")
if resp_sec.status == 200 and ("contact:" in body.lower() or "expires:" in body.lower()):
sec_txt_found = True
except Exception:
pass
hsts = "strict-transport-security" in headers_found
csp = "content-security-policy" in headers_found
xfo = "x-frame-options" in headers_found
xcto = "x-content-type-options" in headers_found
score = sum([hsts * 30, csp * 30, xfo * 15, xcto * 15, sec_txt_found * 10])
grade = "A+" if score >= 90 else ("A" if score >= 75 else ("B" if score >= 55 else ("C" if score >= 35 else "D/F")))
return {
"http_status": status_code,
"server_banner": headers_found.get("server", "Hidden / Not Disclosed"),
"hsts": hsts,
"csp": csp,
"x_frame_options": xfo,
"x_content_type_options": xcto,
"security_txt_rfc9116": sec_txt_found,
"posture_score": f"{score}/100 (Grade: {grade})",
}
def check_password_k_anonymity(self, password: str) -> Dict[str, Any]:
"""
Checks how many times a password has appeared in global data breaches
using HIBP Pwned Passwords K-Anonymity Range API (only first 5 SHA-1 hex chars sent).
"""
sha1_full = hashlib.sha1(password.encode("utf-8")).hexdigest().upper()
prefix, suffix = sha1_full[:5], sha1_full[5:]
url = f"https://api.pwnedpasswords.com/range/{prefix}"
ctx = ssl.create_default_context()
req = urllib.request.Request(url, headers={"User-Agent": "CyberCodex-KAnonymity/3.0"})
leak_count = 0
try:
with urllib.request.urlopen(req, timeout=5.0, context=ctx) as resp:
raw = resp.read().decode("utf-8", errors="replace")
for line in raw.splitlines():
if ":" in line:
h_suf, cnt = line.strip().split(":", 1)
if h_suf.upper() == suffix:
leak_count = int(cnt)
break
except Exception:
pass
return {
"sha1_prefix_sent": prefix,
"sha1_full_local": sha1_full,
"leak_count": leak_count,
"compromised": leak_count > 0,
}
def _query_shodan_internetdb(self, ip: str) -> Dict[str, Any]:
if not ip:
return {}
data = self._http_get_json(f"https://internetdb.shodan.io/{ip}", timeout=5.0)
if isinstance(data, dict) and "ports" in data:
return {
"ports": data.get("ports", []),
"cpes": data.get("cpes", []),
"hostnames": data.get("hostnames", []),
"tags": data.get("tags", []),
"vulns": data.get("vulns", []),
}
return {"ports": [], "cpes": [], "hostnames": [], "tags": [], "vulns": []}
def _query_network_asn(self, ip: str) -> Dict[str, Any]:
if not ip:
return {}
url = (
f"http://ip-api.com/json/{ip}"
"?fields=status,country,regionName,city,isp,org,as,asname,reverse,hosting,proxy"
)
data = self._http_get_json(url, timeout=4.5)
if isinstance(data, dict) and data.get("status") == "success":
return {
"country": data.get("country", "Unknown"),
"region": data.get("regionName", ""),
"city": data.get("city", ""),
"isp": data.get("isp", ""),
"org": data.get("org", ""),
"asn": data.get("as", ""),
"asname": data.get("asname", ""),
"reverse_dns": data.get("reverse", ""),
"is_datacenter_hosting": bool(data.get("hosting", False)),
"is_proxy_vpn": bool(data.get("proxy", False)),
}
return {}
def _query_ripe_bgp(self, ip: str) -> Dict[str, Any]:
if not ip:
return {}
url = f"https://stat.ripe.net/data/network-info/data.json?resource={urllib.parse.quote(ip)}"
data = self._http_get_json(url, timeout=4.5)
if isinstance(data, dict) and isinstance(data.get("data"), dict):
d = data["data"]
return {
"bgp_prefix": d.get("prefix", "Unknown"),
"origin_asns": d.get("asns", []),
}
return {}
def _query_dns_and_dmarc(self, domain: str) -> Dict[str, Any]:
if not domain:
return {}
def doh_lookup(qname: str, qtype: str) -> List[str]:
url = f"https://cloudflare-dns.com/dns-query?name={urllib.parse.quote(qname)}&type={qtype}"
res = self._http_get_json(url, timeout=4.0, extra_headers={"Accept": "application/dns-json"})
records: List[str] = []
if isinstance(res, dict) and isinstance(res.get("Answer"), list):
for ans in res["Answer"]:
val = str(ans.get("data", "")).strip('"')
if val:
records.append(val)
return records
mx_records = doh_lookup(domain, "MX")
ns_records = doh_lookup(domain, "NS")
txt_records = doh_lookup(domain, "TXT")
dmarc_records = doh_lookup(f"_dmarc.{domain}", "TXT")
spf_record = next((r for r in txt_records if "v=spf1" in r.lower()), None)
dmarc_record = next((r for r in dmarc_records if "v=dmarc1" in r.lower()), None)
spoofing_risk = "HIGH (No DMARC policy found - Vulnerable to Email Spoofing)"
if dmarc_record:
dl = dmarc_record.lower()
if "p=reject" in dl:
spoofing_risk = "LOW (Strict DMARC p=reject enforced)"
elif "p=quarantine" in dl:
spoofing_risk = "MODERATE (DMARC p=quarantine enforced)"
elif "p=none" in dl:
spoofing_risk = "HIGH (DMARC p=none monitoring only - Spoofing possible)"
return {
"mx_records": mx_records[:5],
"ns_records": ns_records[:5],
"spf_record": spf_record or "Missing",
"dmarc_record": dmarc_record or "Missing",
"email_spoofing_risk": spoofing_risk,
}
def _query_live_ssl_cert(self, host: str) -> Dict[str, Any]:
if not host:
return {}
ctx = ssl.create_default_context()
try:
with socket.create_connection((host, 443), timeout=3.5) as sock:
with ctx.wrap_socket(sock, server_hostname=host) as ssock:
der_cert = ssock.getpeercert(binary_form=True)
cert_dict = ssock.getpeercert()
tls_ver = ssock.version() or "Unknown"
cipher = ssock.cipher()
sha256_fp = hashlib.sha256(der_cert).hexdigest() if der_cert else ""
subject = dict(x[0] for x in cert_dict.get("subject", [])) if cert_dict else {}
issuer = dict(x[0] for x in cert_dict.get("issuer", [])) if cert_dict else {}
sans = [v for k, v in cert_dict.get("subjectAltName", []) if k == "DNS"] if cert_dict else []
c2_warning = "CLEAN (Standard CA Certificate)"
if sha256_fp.lower() == "87f2085c32b6a2cc709b365f55873e207a9caa10bffecf2fd16d3cf9d94d390c":
c2_warning = "CRITICAL: Default Cobalt Strike TeamServer Certificate Detected!"
elif not issuer.get("organizationName") and subject == issuer:
c2_warning = "SUSPICIOUS: Self-Signed TLS Certificate"
return {
"tls_version": tls_ver,
"cipher_suite": cipher[0] if cipher else "Unknown",
"subject_cn": subject.get("commonName", ""),
"issuer_org": issuer.get("organizationName", issuer.get("commonName", "")),
"serial_number": cert_dict.get("serialNumber", "") if cert_dict else "",
"not_after": cert_dict.get("notAfter", "") if cert_dict else "",
"sha256_fingerprint": sha256_fp,
"san_count": len(sans),
"c2_cert_heuristic": c2_warning,
}
except Exception:
return {}
def _query_crtsh_subdomains(self, domain: str) -> List[str]:
if not domain:
return []
q = urllib.parse.quote(f"%.{domain}")
data = self._http_get_json(f"https://crt.sh/?q={q}&output=json", timeout=6.0)
subs = set()
if isinstance(data, list):
for entry in data[:250]:
name_val = entry.get("name_value", "")
for line in str(name_val).splitlines():
clean = line.strip().lower().lstrip("*.")
if clean.endswith(domain.lower()) and clean != domain.lower():
subs.add(clean)
return sorted(subs)[:20]
def _query_wayback_cdx(self, domain: str) -> List[str]:
if not domain:
return []
q = urllib.parse.quote(f"{domain}/*")
url = f"https://web.archive.org/cdx/search/cdx?url={q}&output=json&fl=original&collapse=urlkey&limit=12"
data = self._http_get_json(url, timeout=5.0)
urls: List[str] = []
if isinstance(data, list) and len(data) > 1:
for row in data[1:]:
if isinstance(row, list) and row:
urls.append(str(row[0]))
return urls[:10]
def _query_phishstats(self, target: str) -> List[Dict[str, Any]]:
if not target:
return []
q = urllib.parse.quote(f"(url,like,~{target}~)")
url = f"https://phishstats.info:2096/api/phishing?_where={q}&_sort=-id&_size=5"
data = self._http_get_json(url, timeout=4.0)
hits: List[Dict[str, Any]] = []
if isinstance(data, list):
for row in data[:5]:
if isinstance(row, dict) and row.get("url"):
hits.append({
"url": row.get("url"),
"ip": row.get("ip"),
"score": row.get("score"),
"date": str(row.get("date", ""))[:19],
})
return hits
def _query_github_pocs(self, cve_id: str) -> List[Dict[str, Any]]:
cve_clean = cve_id.upper().strip()
q = urllib.parse.quote(cve_clean)
url = f"https://api.github.com/search/repositories?q={q}&sort=stars&order=desc&per_page=5"
data = self._http_get_json(url, timeout=5.5)
pocs: List[Dict[str, Any]] = []
if isinstance(data, dict) and isinstance(data.get("items"), list):
for item in data["items"][:5]:
pocs.append({
"full_name": item.get("full_name", ""),
"html_url": item.get("html_url", ""),
"stars": item.get("stargazers_count", 0),
"description": (item.get("description") or "No description")[:110],
"updated_at": str(item.get("updated_at", ""))[:10],
})
return pocs
def _query_first_epss(self, cve_id: str) -> Dict[str, Any]:
cve_clean = cve_id.upper().strip()
url = f"https://api.first.org/data/v1/epss?cve={urllib.parse.quote(cve_clean)}"
data = self._http_get_json(url, timeout=5.0)
if isinstance(data, dict) and isinstance(data.get("data"), list) and data["data"]:
row = data["data"][0]
try:
score = float(row.get("epss", 0.0))
pct = float(row.get("percentile", 0.0))
return {
"epss_score": round(score * 100, 2),
"epss_percentile": round(pct * 100, 2),
"date": row.get("date", ""),
}
except Exception:
pass
return {"epss_score": None, "epss_percentile": None, "date": ""}
def _query_mitre_cve_detail(self, cve_id: str) -> Dict[str, Any]:
cve_clean = cve_id.upper().strip()
data = self._http_get_json(f"https://cveawg.mitre.org/api/cve/{cve_clean}", timeout=5.5)
if isinstance(data, dict) and "containers" in data:
cna = data.get("containers", {}).get("cna", {})
descs = cna.get("descriptions", [])
summary = ""
for d in descs:
if d.get("lang", "").startswith("en"):
summary = d.get("value", "")
break
if not summary and descs:
summary = descs[0].get("value", "")
cvss_score = None
severity = "UNKNOWN"
for m in cna.get("metrics", []):
for key in ("cvssV3_1", "cvssV3_0", "cvssV4_0", "cvssV2_0"):
if key in m:
cvss_score = m[key].get("baseScore")
severity = m[key].get("baseSeverity", severity)
break
for adp in data.get("containers", {}).get("adp", []):
for m in adp.get("metrics", []):
if not cvss_score and "cvssV3_1" in m:
cvss_score = m["cvssV3_1"].get("baseScore")
severity = m["cvssV3_1"].get("baseSeverity", severity)
published = data.get("cveMetadata", {}).get("datePublished", "")[:10]
return {
"cve_id": cve_clean,
"summary": summary,
"cvss_score": cvss_score,
"severity": severity,
"published": published,
"source": "MITRE CVE AWG v5 API",
}
circl = self._http_get_json(f"https://cve.circl.lu/api/cve/{cve_clean}", timeout=5.0)
if isinstance(circl, dict) and circl.get("summary"):
return {
"cve_id": cve_clean,
"summary": circl.get("summary", ""),
"cvss_score": circl.get("cvss"),
"severity": "CRITICAL" if (circl.get("cvss") or 0) >= 9.0 else "HIGH",
"published": str(circl.get("Published", ""))[:10],
"source": "CIRCL.lu Public CVE API",
}
return {
"cve_id": cve_clean,
"summary": "",
"cvss_score": None,
"severity": "UNKNOWN",
"published": "",
"source": "Local CyberCodex Knowledge Base",
}
def investigate_target(self, target: str, use_cache: bool = True) -> Dict[str, Any]:
"""
Runs 21-source parallel zero-cost intelligence & breach gathering on an IP or Domain.
"""
clean_target = re.sub(r"^https?://", "", target.strip()).split("/")[0].split(":")[0]
cache_key = f"intel_v3:{clean_target.lower()}"
if use_cache:
cached = self._get_cached(cache_key)
if cached:
return cached
is_ip = self._is_ip(clean_target)
resolved_ip = clean_target if is_ip else ""
domain = "" if is_ip else clean_target
if domain:
try:
resolved_ip = socket.gethostbyname(domain)
except Exception:
resolved_ip = ""
with ThreadPoolExecutor(max_workers=11) as pool:
f_shodan = pool.submit(self._query_shodan_internetdb, resolved_ip)
f_net = pool.submit(self._query_network_asn, resolved_ip)
f_ripe = pool.submit(self._query_ripe_bgp, resolved_ip)
f_dns = pool.submit(self._query_dns_and_dmarc, domain)
f_ssl = pool.submit(self._query_live_ssl_cert, domain or resolved_ip)
f_hdr = pool.submit(self._query_http_security_headers, domain)
f_hibp = pool.submit(self._query_hibp_domain_breaches, domain)
f_hrock = pool.submit(self._query_hudsonrock_stealers, domain if domain else resolved_ip, "domain" if domain else "ip")
f_crt = pool.submit(self._query_crtsh_subdomains, domain)
f_wb = pool.submit(self._query_wayback_cdx, domain)
f_phish = pool.submit(self._query_phishstats, clean_target)
shodan_data = f_shodan.result()
net_data = f_net.result()
ripe_bgp = f_ripe.result()
dns_dmarc = f_dns.result()
ssl_cert = f_ssl.result()
http_headers = f_hdr.result()
hibp_breaches = f_hibp.result()
hudsonrock = f_hrock.result()
subdomains = f_crt.result()
wayback_urls = f_wb.result()
phish_hits = f_phish.result()
vulns = shodan_data.get("vulns", [])
kev_hits = []
for v in vulns[:15]:
kev = self.updater.check_cve_in_kev(v)
if kev:
kev_hits.append(kev)
feodo_c2 = self.updater.check_ip_in_feodo(resolved_ip) if resolved_ip else None
is_tor_exit = self.updater.check_ip_in_tor(resolved_ip) if resolved_ip else False
correlations = self.codex.correlate_findings(
cves=vulns,
ports=shodan_data.get("ports", []),
keywords=shodan_data.get("cpes", []) + shodan_data.get("tags", []),
)
result = {
"target": clean_target,
"target_type": "IP" if is_ip else "DOMAIN",
"resolved_ip": resolved_ip or "Unresolved",
"timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
"cache_hit": False,
"shodan_internetdb": shodan_data,
"network_asn": net_data,
"ripe_bgp": ripe_bgp,
"is_tor_exit_node": is_tor_exit,
"dns_dmarc": dns_dmarc,
"live_ssl_cert": ssl_cert,
"http_security_headers": http_headers,
"hibp_breaches": hibp_breaches,
"hudsonrock_stealers": hudsonrock,
"crtsh_subdomains": subdomains,
"wayback_endpoints": wayback_urls,
"phishstats_hits": phish_hits,
"cisa_kev_alerts": kev_hits,
"feodo_c2_alert": feodo_c2,
"codex_correlations": correlations,
}
self._set_cached(cache_key, result)
return result
def investigate_leak(self, query: str, is_password: bool = False) -> Dict[str, Any]:
"""
Dedicated deep-dive Data Breach, Leak History, Infostealer, COMB Credential Dump & K-Anonymity Password analyzer.
Supports:
1. Website / Domain (`adobe.com`, `cheatglobal.com`) -> Latest breach, Top breach, DataClasses, Infostealers, COMB lines, Wayback snapshots
2. Email Address (`user@domain.com`) -> Hudson Rock Stealer log check + COMB credentials + Domain breach check
3. Username (`user:admin`) -> Hudson Rock Username Stealer logs + COMB credentials
4. Password (`pass:123456` or `--password`) -> HIBP K-Anonymity 850M+ breached password check
"""
clean = query.strip()
if clean.lower().startswith("pass:"):
clean = clean[5:].strip()
is_password = True
if is_password:
return {
"query": "*" * len(clean),
"mode": "PASSWORD_K_ANONYMITY",
"timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
"password_audit": self.check_password_k_anonymity(clean),
}
if clean.lower().startswith("user:"):
uname = clean[5:].strip()
with ThreadPoolExecutor(max_workers=2) as pool:
f_usr = pool.submit(self._query_hudsonrock_stealers, uname, "username")
f_comb = pool.submit(self._query_proxynova_comb_leaks, uname, 100)
return {
"query": uname,
"mode": "USERNAME_STEALER_AND_COMB",
"timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
"username_stealer_hits": f_usr.result(),
"comb_leaks": f_comb.result(),
}
if "@" in clean:
email_domain = clean.split("@", 1)[1].lower()
with ThreadPoolExecutor(max_workers=4) as pool:
f_emp = pool.submit(self._query_hudsonrock_stealers, clean, "email")
f_comb = pool.submit(self._query_proxynova_comb_leaks, clean, 100)
f_dom = pool.submit(self._query_hibp_domain_breaches, email_domain)
f_hdom = pool.submit(self._query_hudsonrock_stealers, email_domain, "domain")
return {
"query": clean,
"mode": "EMAIL_AND_DOMAIN_LEAK",
"timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
"email_stealer_hits": f_emp.result(),
"comb_leaks": f_comb.result(),
"domain_breaches": f_dom.result(),
"domain_stealer_stats": f_hdom.result(),
}
domain_clean = re.sub(r"^https?://", "", clean.lower()).split("/")[0].split(":")[0]
if domain_clean.startswith("www."):
domain_clean = domain_clean[4:]
with ThreadPoolExecutor(max_workers=4) as pool:
f_hibp = pool.submit(self._query_hibp_domain_breaches, domain_clean)
f_hrock = pool.submit(self._query_hudsonrock_stealers, domain_clean, "domain")
f_comb = pool.submit(self._query_proxynova_comb_leaks, domain_clean, 100)
f_wb = pool.submit(self._query_wayback_leak_snapshots, domain_clean, 40)
return {
"query": domain_clean,
"mode": "DOMAIN_BREACH_AND_STEALER",
"timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
"domain_breaches": f_hibp.result(),
"domain_stealer_stats": f_hrock.result(),
"comb_leaks": f_comb.result(),
"wayback_snapshots": f_wb.result(),
}
def download_leak_bundle(
self,
leak_data: Dict[str, Any],
report_text: str = "",
custom_dir: Optional[str] = None,
) -> Dict[str, Any]:
"""
Downloads and saves all harvested leak artifacts to disk inside `exports/leaks_<target>/`:
1. `1_comb_leaked_credentials.txt` (Raw email:password lines from 3.2B COMB database)
2. `2_stealer_compromised_urls.csv` (All URLs where RedLine/Raccoon/Vidar stole logins + counts)
3. `3_full_breach_and_stealer_dump.json` (Complete JSON dump of HIBP, Hudson Rock, Password Audits & COMB)
4. `4_wayback_archived_snapshots.txt` (Direct web.archive.org raw file download links)
5. `5_FORENSIC_LEAK_REPORT.md` (Formatted Markdown forensic dossier)
"""
raw_q = str(leak_data.get("query", "target")).strip()
safe_q = re.sub(r"[^a-zA-Z0-9._-]", "_", raw_q)[:50] or "password_audit"
base_exports = os.path.join(os.path.dirname(os.path.abspath(__file__)), "exports")
bundle_dir = custom_dir or os.path.join(base_exports, f"leaks_{safe_q}")
os.makedirs(bundle_dir, exist_ok=True)
files_written: List[Dict[str, Any]] = []
# 1. Save COMB raw email:password lines
comb = leak_data.get("comb_leaks") or {}
comb_lines = comb.get("leaked_lines") or []
f1_path = os.path.join(bundle_dir, "1_comb_leaked_credentials.txt")
with open(f1_path, "w", encoding="utf-8") as f:
f.write(f"# CyberCodex Leak Harvester - ProxyNova COMB (3.2B Corpus)\n")
f.write(f"# Target: {raw_q} | Total Matches in Corpus: {comb.get('total_count', 0)}\n")
f.write(f"# Timestamp: {leak_data.get('timestamp', '')}\n")
f.write("# Format: email:password\n" + "=" * 70 + "\n")
if comb_lines:
for line in comb_lines:
f.write(f"{line}\n")
else:
f.write("# No unmasked plaintext email:password lines returned in public COMB sample for this query.\n")
files_written.append({
"name": "1_comb_leaked_credentials.txt",
"path": f1_path,
"records": len(comb_lines),
"description": f"COMB 3.2B Leaked Email:Password Combo Lines (Total Matches: {comb.get('total_count', 0):,})",
})
# 2. Save Infostealer Compromised URLs & Occurrence Counts CSV
hrock = leak_data.get("domain_stealer_stats") or {}
client_urls = hrock.get("compromised_client_urls") or []
emp_urls = hrock.get("compromised_employee_urls") or []
all_urls = emp_urls + client_urls
f2_path = os.path.join(bundle_dir, "2_stealer_compromised_urls.csv")
with open(f2_path, "w", encoding="utf-8") as f:
f.write("Account_Type,Stolen_Credentials_Count,Compromised_URL\n")
for u in all_urls:
clean_u = str(u.get("url", "")).replace('"', '""')
f.write(f"{u.get('type', 'User')},{u.get('occurrence', 0)},\"{clean_u}\"\n")
files_written.append({
"name": "2_stealer_compromised_urls.csv",
"path": f2_path,
"records": len(all_urls),
"description": "Infostealer Compromised Login/Portal URLs & Stolen Account Counts (CSV)",
})
# 3. Save Complete Raw Forensic JSON Dump
f3_path = os.path.join(bundle_dir, "3_full_breach_and_stealer_dump.json")
with open(f3_path, "w", encoding="utf-8") as f:
json.dump(leak_data, f, indent=2, ensure_ascii=False)
files_written.append({
"name": "3_full_breach_and_stealer_dump.json",
"path": f3_path,
"records": 1,
"description": "Complete Raw JSON Dump (HIBP Breaches + Stealer Telemetry + Password Audits)",
})
# 4. Save Wayback Archived Direct Download Links
snaps = leak_data.get("wayback_snapshots") or []
f4_path = os.path.join(bundle_dir, "4_wayback_archived_snapshots.txt")
with open(f4_path, "w", encoding="utf-8") as f:
f.write(f"# CyberCodex Historical Snapshot & Leaked Endpoint Direct Download Links\n")