-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.py
More file actions
executable file
·3209 lines (2901 loc) · 150 KB
/
runner.py
File metadata and controls
executable file
·3209 lines (2901 loc) · 150 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
"""
DeepProbe Volatility Analysis Runner
Tested with: Volatility 3 (2.26.x). Python 3.10+.
Usage:
python runner.py --image memory.raw --case case1 \
--detections detections.yaml --baseline detections.yaml --outdir out \
--api-key YOUR_IP_ENRICHMENT_API_KEY
Notes:
- Keeps stdout very chatty so you can see exactly what runs.
- Handles Win7 limitations gracefully (skips unsupported plugins).
- Places “-r csv” BEFORE plugin name when format=csv (Vol3 quirk).
"""
import argparse, json, os, re, shutil, subprocess, sys, time, textwrap
from pathlib import Path
from datetime import datetime, UTC
from typing import Dict, List, Any, Tuple
import requests
import ipaddress
from io import StringIO
import traceback
print("[DEBUG] runner.py has started. All imports successful.")
try:
import yaml
except Exception as e:
print("Please: pip install pyyaml", file=sys.stderr)
sys.exit(2)
# ---------------------------
# Helpers
# ---------------------------
def sh(cmd: List[str], capture=True, cwd=None) -> Tuple[int, str]:
"""Run a shell command. Returns (rc, output)."""
try:
proc = subprocess.run(
cmd,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.STDOUT if capture else None,
cwd=cwd,
text=True
)
return proc.returncode, (proc.stdout or "")
except FileNotFoundError:
return 127, f"[ENOENT] {cmd[0]} not found on PATH"
except Exception as e:
return 1, f"[ERROR] {' '.join(cmd)} :: {e}"
def find_vol_binary(prefer_list: List[str]) -> str:
for name in prefer_list:
rc, _ = sh(["which", name])
if rc == 0:
return name
return ""
def ensure_dirs(outdir: Path):
print(f"[DEBUG] Ensuring output directories exist at: {outdir}")
(outdir / "artifacts").mkdir(parents=True, exist_ok=True)
(outdir / "logs").mkdir(exist_ok=True)
print(f"[DEBUG] Directories created/exist.")
def write_file(path: Path, data: str):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8", errors="ignore")
def now_iso() -> str:
return datetime.now(UTC).isoformat() + "Z"
def compile_any_contains_to_regex(parts: List[str]) -> re.Pattern:
escaped = []
for p in parts:
escaped.append(re.escape(p))
regex = "(" + "|".join(escaped) + ")"
return re.compile(regex, re.IGNORECASE)
def in_cidrs(ip: str, cidrs: List[str]) -> bool:
try:
addr = ipaddress.ip_address(ip)
for block in cidrs:
if addr in ipaddress.ip_network(block, strict=False):
return True
except Exception:
return False
return False
# ---------------------------------------------------------------------------
# Free OSINT IP reputation feeds (no API key required)
# ---------------------------------------------------------------------------
# Three sources are used:
# Feodo Tracker — C2 botnet IPs (Dridex, Emotet, TrickBot, etc.)
# SSLBL — IPs hosting malicious SSL certificates
# ThreatFox — IOC feed (malware, C2, stealers)
#
# Feeds are downloaded once and cached in memory for FEED_TTL seconds.
# A lookup returns a scoring dict compatible with the existing get_ip_info()
# output format. Scores are additive — an IP can appear in multiple feeds.
# ---------------------------------------------------------------------------
_FEED_URLS = {
"feodo": "https://feodotracker.abuse.ch/downloads/ipblocklist.csv",
"sslbl": "https://sslbl.abuse.ch/blacklist/sslipblacklist.csv",
"threatfox": "https://threatfox.abuse.ch/export/json/recent/",
}
_FEED_SCORES = {"feodo": 10, "sslbl": 8, "threatfox": 8}
FEED_TTL = 6 * 3600 # 6 hours between refreshes
# Disk cache path — lives next to the script so it survives container restarts
# as long as the ./out volume is mounted. Falls back to /tmp if that dir is
# not writable (e.g. read-only container filesystem).
_FEED_DISK_CACHE = Path(__file__).parent / "out" / ".osint_feed_cache.json"
_feed_cache: Dict[str, set] = {} # source_name -> set of IP strings
_feed_last_updated: float = 0.0 # unix timestamp of last successful refresh
def _load_feed_cache_from_disk() -> bool:
"""
Try to load the OSINT feed cache from the on-disk JSON file.
Returns True if the cache was loaded and is still fresh enough to use.
"""
global _feed_cache, _feed_last_updated
try:
if not _FEED_DISK_CACHE.exists():
return False
with _FEED_DISK_CACHE.open("r", encoding="utf-8") as fh:
data = json.load(fh)
saved_ts = float(data.get("timestamp", 0))
if (time.time() - saved_ts) >= FEED_TTL:
print("[i] Disk OSINT cache exists but is expired — will re-download")
return False
feeds = data.get("feeds", {})
_feed_cache = {k: set(v) for k, v in feeds.items()}
_feed_last_updated = saved_ts
total = sum(len(s) for s in _feed_cache.values())
print(f"[i] Loaded OSINT feed cache from disk — {total} IPs, age {int(time.time()-saved_ts)}s")
return True
except Exception as e:
print(f"[warn] Could not load OSINT disk cache: {e}", file=sys.stderr)
return False
def _save_feed_cache_to_disk() -> None:
"""Persist the in-memory feed cache to disk for use across restarts."""
try:
_FEED_DISK_CACHE.parent.mkdir(parents=True, exist_ok=True)
data = {
"timestamp": _feed_last_updated,
"feeds": {k: sorted(v) for k, v in _feed_cache.items()},
}
tmp = _FEED_DISK_CACHE.with_suffix(".tmp")
tmp.write_text(json.dumps(data, separators=(",", ":")), encoding="utf-8")
tmp.replace(_FEED_DISK_CACHE) # atomic replace
print(f"[i] OSINT cache persisted to disk: {_FEED_DISK_CACHE}")
except Exception as e:
print(f"[warn] Could not save OSINT disk cache: {e}", file=sys.stderr)
def _refresh_osint_feeds(force: bool = False) -> None:
"""
Download/refresh the three OSINT feeds. Thread-safe enough for the
single-process runner (no locking needed). Silently tolerates network
failures — if a feed can't be fetched the cache entry stays empty.
"""
global _feed_last_updated
# ── Short-circuit 1: in-memory cache is still fresh ─────────────────────
if not force and (time.time() - _feed_last_updated) < FEED_TTL:
return
# ── Short-circuit 2: try loading from disk before hitting the network ───
if not force and _load_feed_cache_from_disk():
return # disk cache was fresh enough
print("[i] Refreshing OSINT reputation feeds …")
new_cache: Dict[str, set] = {"feodo": set(), "sslbl": set(), "threatfox": set()}
ip_re = re.compile(r"\b(\d{1,3}(?:\.\d{1,3}){3})\b")
any_downloaded = False
# ── Feodo Tracker & SSLBL (CSV / plain-text) ────────────────────────────
for name in ("feodo", "sslbl"):
try:
r = requests.get(_FEED_URLS[name], timeout=15)
r.raise_for_status()
for line in r.text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
# Feodo CSV: "dst_ip,dst_port,date_added,…" SSLBL: "IP,Port,…"
m = ip_re.search(line)
if m:
try:
ipaddress.ip_address(m.group(1)) # validate
new_cache[name].add(m.group(1))
except ValueError:
pass
print(f"[i] {name}: {len(new_cache[name])} IPs loaded")
any_downloaded = True
except Exception as e:
print(f"[warn] OSINT feed '{name}' unavailable: {e}", file=sys.stderr)
# Keep existing in-memory data for this source if available
if name in _feed_cache:
new_cache[name] = _feed_cache[name]
print(f"[i] {name}: using stale in-memory cache ({len(new_cache[name])} IPs)")
# ── ThreatFox (JSON) ────────────────────────────────────────────────────
try:
r = requests.get(_FEED_URLS["threatfox"], timeout=20)
r.raise_for_status()
payload = r.json()
# Response is {"query_status": "ok", "data": [{"ioc": "1.2.3.4:PORT", ...}, …]}
data = payload.get("data") or []
if isinstance(data, dict):
data = list(data.values()) # older API returned dict keyed by id
for item in (data if isinstance(data, list) else []):
ioc = item.get("ioc", "") if isinstance(item, dict) else str(item)
# IOC may be "1.2.3.4" or "1.2.3.4:4444"
m = ip_re.search(ioc)
if m:
try:
ipaddress.ip_address(m.group(1))
new_cache["threatfox"].add(m.group(1))
except ValueError:
pass
print(f"[i] threatfox: {len(new_cache['threatfox'])} IPs loaded")
any_downloaded = True
except Exception as e:
print(f"[warn] OSINT feed 'threatfox' unavailable: {e}", file=sys.stderr)
if "threatfox" in _feed_cache:
new_cache["threatfox"] = _feed_cache["threatfox"]
print(f"[i] threatfox: using stale in-memory cache ({len(new_cache['threatfox'])} IPs)")
_feed_cache.update(new_cache)
_feed_last_updated = time.time()
total = sum(len(s) for s in _feed_cache.values())
print(f"[i] OSINT feeds ready — {total} total IPs across all sources")
# Persist to disk only when we actually downloaded fresh data
if any_downloaded:
_save_feed_cache_to_disk()
def osint_lookup(ip: str) -> Dict[str, Any]:
"""
Look up an IP against the cached OSINT feeds.
Returns a dict:
{
"reputation": "Malicious" | "Suspicious" | "Unknown",
"osint_score": <int>,
"osint_sources": ["feodo", …]
}
Never treats missing data as 'safe' — Unknown is the default.
Results are deterministic: same IP always gets the same score for a
given cache snapshot.
"""
_refresh_osint_feeds() # no-op if cache is fresh
score = 0
sources = []
for name, ip_set in _feed_cache.items():
if ip in ip_set:
score += _FEED_SCORES[name]
sources.append(name)
if score >= 10:
reputation = "Malicious"
elif score >= 5:
reputation = "Suspicious"
else:
reputation = "Unknown"
return {
"reputation": reputation,
"osint_score": score,
"osint_sources": sources,
}
def get_ip_info(ip: str, api_key: str) -> Dict[str, str]:
# ── Step 1: free OSINT lookup (always runs, no key needed) ──────────────
osint = osint_lookup(ip)
info = {
"country": "N/A",
"isp": "N/A",
"reputation": osint["reputation"],
"osint_score": osint["osint_score"],
"osint_sources": ", ".join(osint["osint_sources"]) if osint["osint_sources"] else "none",
}
# ── Step 2: enrich with AbuseIPDB if a key was provided ─────────────────
if not api_key:
# No API key — augment with ipinfo.io geo data only, keep OSINT reputation
geo = _ipinfo_fallback(ip)
info["country"] = geo.get("country", "N/A")
info["isp"] = geo.get("isp", "N/A")
# Keep OSINT reputation — don't downgrade to "Unknown"
if info["reputation"] == "Unknown":
info["reputation"] = geo.get("reputation", "Unknown")
return info
abuseipdb_url = f"https://api.abuseipdb.com/api/v2/check"
headers = {
'Key': api_key,
'Accept': 'application/json'
}
params = {
'ipAddress': ip,
'maxAgeInDays': 90
}
try:
print(f"[info] Querying AbuseIPDB for IP: {ip}…")
response = requests.get(abuseipdb_url, headers=headers, params=params, timeout=5)
response.raise_for_status()
data = response.json().get("data", {})
info["country"] = data.get("countryCode", "N/A")
info["isp"] = data.get("isp", "N/A")
info["abuse_reports"] = data.get("totalReports", 0)
info["last_reported"] = data.get("lastReportedAt", "N/A")
# Merge AbuseIPDB confidence score with OSINT score
# AbuseIPDB score is 0-100; map it to the same 0-26 range so both
# sources contribute proportionally.
abuse_conf = data.get("abuseConfidenceScore", 0)
combined_score = osint["osint_score"] + round(abuse_conf * 26 / 100)
if combined_score >= 10 or abuse_conf > 60:
info["reputation"] = "Malicious"
elif combined_score >= 5 or abuse_conf > 20:
info["reputation"] = "Suspicious"
elif osint["osint_score"] == 0:
info["reputation"] = "Clean"
# else keep OSINT reputation (e.g. Malicious from OSINT even if AbuseIPDB shows low score)
print(
f"[info] {ip}: country={info['country']}, osint={osint['osint_score']} "
f"(sources: {osint['osint_sources']}), abuse={abuse_conf}% → {info['reputation']}",
file=sys.stderr
)
except requests.exceptions.HTTPError as e:
print(f"[WARN] AbuseIPDB HTTP {e.response.status_code} for {ip} — geo fallback (OSINT score kept)", file=sys.stderr)
geo = _ipinfo_fallback(ip)
info["country"] = geo.get("country", "N/A")
info["isp"] = geo.get("isp", "N/A")
except requests.exceptions.ConnectionError:
print(f"[WARN] AbuseIPDB unreachable for {ip} — geo fallback (OSINT score kept)", file=sys.stderr)
geo = _ipinfo_fallback(ip)
info["country"] = geo.get("country", "N/A")
info["isp"] = geo.get("isp", "N/A")
except requests.exceptions.Timeout:
print(f"[WARN] AbuseIPDB timed out for {ip} — geo fallback (OSINT score kept)", file=sys.stderr)
geo = _ipinfo_fallback(ip)
info["country"] = geo.get("country", "N/A")
info["isp"] = geo.get("isp", "N/A")
except Exception as e:
print(f"[WARN] AbuseIPDB error for {ip}: {e} — geo fallback (OSINT score kept)", file=sys.stderr)
geo = _ipinfo_fallback(ip)
info["country"] = geo.get("country", "N/A")
info["isp"] = geo.get("isp", "N/A")
return info
def _ipinfo_fallback(ip: str) -> Dict[str, str]:
"""Fallback IP enrichment using ipinfo.io (free tier, no reputation scoring)."""
info = {"country": "N/A", "isp": "N/A", "reputation": "Unknown (AbuseIPDB failed — ipinfo.io fallback)"}
try:
response = requests.get(f"https://ipinfo.io/{ip}/json", timeout=3)
if response.status_code == 200:
data = response.json()
info["country"] = data.get("country", "N/A")
info["isp"] = data.get("org", "N/A")
info["reputation"] = "Unknown (ipinfo.io fallback — no AbuseIPDB key or API failed)"
except Exception as e:
print(f"[warn] ipinfo.io fallback also failed for {ip}: {e}", file=sys.stderr)
return info
# ---------------------------
# Volatility Runner
# ---------------------------
def run_plugin(vol: str, image: str, plugin: str, fmt: str, outdir: Path) -> str:
base = [vol, "-f", image, "--quiet"]
if fmt == "csv":
cmd = base + ["-r", "csv", plugin]
else:
cmd = base + [plugin]
safe_plugin_name = plugin.replace(".", "_")
ext = "csv" if fmt == "csv" else "txt"
raw_path = outdir / "artifacts" / f"{safe_plugin_name}.{ext}"
print(f"[DEBUG] Attempting to run Volatility command: {' '.join(cmd)}")
try:
proc = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
check=True,
errors="replace"
)
out = proc.stdout
print(f"[DEBUG] Raw output from {plugin} (first 500 chars):\n{out[:500]}...")
write_file(raw_path, out)
return out
except subprocess.CalledProcessError as e:
error_message = f"[ERROR] Plugin '{plugin}' failed with exit code {e.returncode}. Output:\n{e.stdout}"
print(error_message, file=sys.stderr)
return error_message
except Exception as e:
error_message = f"[ERROR] Plugin '{plugin}' failed unexpectedly: {e}"
print(error_message, file=sys.stderr)
return error_message
def try_plugin_with_fallbacks(vol: str, image: str, name: str, fmt: str, fallbacks: List[str], outdir: Path) -> Tuple[str, str]:
content = run_plugin(vol, image, name, fmt, outdir)
if "invalid choice" in content or "not supported" in content or "Traceback" in content or "Unsatisfied requirement" in content:
print(f"[DEBUG] Plugin {name} failed or gave invalid output. Trying fallbacks: {fallbacks}")
for alt in fallbacks or []:
alt_content = run_plugin(vol, image, alt, fmt, outdir)
if "invalid choice" not in alt_content and "Traceback" not in alt_content and "Unsatisfied requirement" not in alt_content:
print(f"[DEBUG] Fallback {alt} successful.")
return alt, alt_content
return name, content
def detect_os(info_text: str) -> str:
if "NtSystemRoot" in info_text or "IsPAE" in info_text:
return "windows"
if "Linux" in info_text or "linux" in info_text:
return "linux"
if "Darwin" in info_text or "Mac" in info_text:
return "macos"
return "windows"
# ---------------------------
# Parsers
# ---------------------------
def parse_csv(text: str) -> List[Dict[str, str]]:
lines = [l for l in text.splitlines() if l.strip()]
if not lines:
print("[DEBUG] parse_csv received empty text or only whitespace lines.")
return []
header_idx = 0
for i, l in enumerate(lines[:10]):
if "," in l and not l.lower().startswith("volatility 3"):
header_idx = i
break
hdr = [h.strip() for h in lines[header_idx].split(",")]
rows = []
for l in lines[header_idx+1:]:
parts = l.split(",", len(hdr)-1)
parts += [""] * (len(hdr)-len(parts))
rows.append({hdr[i]: parts[i].strip() for i in range(len(hdr))})
print(f"[DEBUG] parse_csv parsed {len(rows)} rows with headers: {hdr}")
return rows
def kv_parse(text: str) -> Dict[str, str]:
d = {}
for line in text.splitlines():
if "\t" in line:
k, v = line.split("\t", 1)
d[k.strip()] = v.strip()
elif ":" in line:
k, v = line.split(":", 1)
d[k.strip()] = v.strip()
return d
# ---------------------------
# Engines
# ---------------------------
def eng_process_pid_match(pslist_rows: List[Dict[str, str]], target_pid: int):
findings = []
for r in pslist_rows:
try:
if int(r.get("PID","")) == target_pid:
findings.append({"pid": target_pid, "name": r.get("ImageFileName","") or r.get("Name","")})
break
except (ValueError, TypeError):
continue
return findings
def eng_unknown_process_name(pslist_rows, baseline, oskey="windows"):
wl = set((baseline.get("process_whitelist", {}).get(oskey, [])) or [])
findings = []
for r in pslist_rows:
name = r.get("ImageFileName", "") or r.get("Name", "")
pid = r.get("PID", "")
if name and (name.lower() not in [n.lower() for n in wl]):
findings.append({"pid": pid, "name": name, "path": r.get("Path","")})
return findings
def eng_psxview_hidden(rows):
findings = []
for r in rows:
try:
if r.get("pslist","").lower() == "false" and (
r.get("psscan","").lower() == "true" or
r.get("thrdscan","").lower() == "true" or
r.get("csrss","").lower() == "true"
):
findings.append({
"pid": r.get("PID",""),
"name": r.get("Name",""),
"pslist_present": r.get("pslist",""),
"psscan_present": r.get("psscan",""),
"thrdscan_present": r.get("thrdscan",""),
"csrss_present": r.get("csrss",""),
})
except:
pass
return findings
def eng_suspicious_connection(rows, baseline):
print(f"[DEBUG] eng_suspicious_connection: Received {len(rows)} rows.")
allow_cidrs = baseline.get("network", {}).get("allow_cidrs", []) or []
allow_ports = set(str(p) for p in (baseline.get("network", {}).get("allow_ports", []) or []))
findings = []
for r in rows:
faddr = r.get("ForeignAddr","") or r.get("ForeignIP","")
fport = r.get("ForeignPort","") or r.get("ForeignPortNumber","")
if not faddr or faddr in ("0.0.0.0","::","*"):
continue
ok_cidr = in_cidrs(faddr, allow_cidrs)
ok_port = str(fport) in allow_ports
print(f"[DEBUG] Suspicious_connection check for {faddr}:{fport}. OK CIDR: {ok_cidr}, OK Port: {ok_port}")
if not (ok_cidr or ok_port):
findings.append({
"pid": r.get("PID",""),
"owner": r.get("Owner","") or r.get("Process",""),
"ForeignAddr": faddr,
"ForeignPort": fport,
"LocalAddr": r.get("LocalAddr",""),
"LocalPort": r.get("LocalPort",""),
"State": r.get("State",""),
})
print(f"[DEBUG] eng_suspicious_connection: Found {len(findings)} findings.")
return findings
def eng_network_enrichment_master(netstat_rows: List[Dict[str, Any]], detection_rules: List[Dict[str, Any]], baseline: Dict[str, Any], api_key: str) -> List[Dict[str, Any]]:
findings = []
processed_ips = {}
if not netstat_rows:
print("[DEBUG] eng_network_enrichment_master: Received no rows.")
return findings
print("[info] Running network enrichment master engine...")
allow_cidrs = baseline.get("network", {}).get("allow_cidrs", []) or []
unique_ips_to_process = set()
for row in netstat_rows:
foreign_ip = row.get("ForeignAddr", "").strip()
try:
ip_obj = ipaddress.ip_address(foreign_ip)
if ip_obj.is_loopback or ip_obj.is_unspecified or ip_obj.is_private:
continue
if not in_cidrs(foreign_ip, allow_cidrs):
unique_ips_to_process.add(foreign_ip)
except ValueError:
continue
print(f"[DEBUG] eng_network_enrichment_master: Unique IPs to process: {unique_ips_to_process}")
for ip in unique_ips_to_process:
if ip in processed_ips:
enriched_data = processed_ips[ip]
else:
print(f"[info] Fetching enrichment for IP: {ip}")
enriched_data = get_ip_info(ip, api_key)
processed_ips[ip] = enriched_data
for ip, enriched_data in processed_ips.items():
for detection_rule in detection_rules:
if detection_rule.get('engine') != 'network_enrichment':
continue
is_suspicious_for_this_rule = False
reasons = []
rules_logic = detection_rule.get("logic", [])
for logic_rule in rules_logic:
rule_matched_locally = True
for match_criteria in logic_rule.get("match", []):
field = match_criteria.get("field")
value = match_criteria.get("value")
operator = match_criteria.get("operator", "==")
if field in enriched_data:
data_val = enriched_data[field]
if operator == "==":
if not (str(data_val).lower() == str(value).lower()):
rule_matched_locally = False
break
elif operator == "<":
try:
if not (float(data_val) < float(value)):
rule_matched_locally = False
break
except ValueError:
rule_matched_locally = False
break
if rule_matched_locally:
is_suspicious_for_this_rule = True
for match_criteria in logic_rule.get("match", []):
field = match_criteria.get("field")
if field in enriched_data:
reasons.append(f"Field '{field}' ({enriched_data[field]}) matches condition '{match_criteria.get('value')}'")
break
if is_suspicious_for_this_rule:
associated_connections = [conn for conn in netstat_rows if (conn.get("ForeignAddr", "") or conn.get("ForeignIP", "")) == ip]
pids = list(set([c.get("Pid", c.get("PID", "N/A")) for c in associated_connections]))
owners = list(set([c.get("Owner", c.get("Process", "N/A")) for c in associated_connections]))
pids_display = ", ".join(p for p in pids if p and p != "N/A") or "N/A"
owners_display = ", ".join(o for o in owners if o and o != "N/A") or "N/A"
finding_evidence = {
"pid": pids_display, "owner": owners_display, "ip": ip,
"country": enriched_data.get("country", "N/A"), "isp": enriched_data.get("isp", "N/A"),
"reputation": enriched_data.get("reputation", "N/A"), "notes": "; ".join(reasons)
}
findings.append({
"id": detection_rule["id"], "title": detection_rule["title"], "narrative": detection_rule["narrative"],
"mitre": detection_rule.get("mitre", []), "weight": detection_rule["weight"],
"evidence": [finding_evidence]
})
return findings
def eng_suspicious_port_activity(rows, suspicious_ports: List[int]):
findings = []
susp_ports = {str(p) for p in suspicious_ports}
for r in rows:
local_port = r.get("LocalPort", "")
foreign_port = r.get("ForeignPort", "")
if (local_port and str(local_port).strip() != '0' and local_port in susp_ports) or \
(foreign_port and str(foreign_port).strip() != '0' and foreign_port in susp_ports):
findings.append({
"pid": r.get("PID",""), "owner": r.get("Owner","") or r.get("Process",""),
"Proto": r.get("Proto",""), "LocalPort": local_port,
"ForeignPort": foreign_port, "Notes": "Connection found on a known suspicious port."
})
return findings
def _ev_pid(ev: Dict[str, Any]) -> str:
"""
Normalise the PID out of an evidence dict.
Different engine functions store the PID under different key names:
- 'pid' — most process-centric engines (lowercase)
- 'Pid' — eng_services_suspicious (mixed-case from svcscan CSV)
- 'requestor_pid' — eng_handles_general (the handle-holder PID)
Returns a stripped string, or "" if none found.
"""
raw = ev.get("pid") or ev.get("Pid") or ev.get("requestor_pid") or ""
return str(raw).strip() if raw and str(raw).strip() not in ("", "N/A", "None") else ""
def eng_correlated_findings(all_findings: List[Dict[str, Any]], correlation_pairs: List[Dict[str, Any]]):
"""
Correlate findings that share a common process PID.
Two categories of evidence:
• PID-bearing — evidence items that contain a process PID (most engine outputs).
• System-wide — evidence items with NO PID (e.g. scheduled-task lines, file-scan
paths, registry key values). These are attached as context to
every chain that fires, because they represent host-wide
persistence/execution indicators that are relevant regardless of
which process triggered the chain.
A correlation chain is only emitted when at least one PID appears in BOTH the
primary finding set AND the secondary finding set. Empty chains (where PID
normalisation failed for every evidence item) are never emitted.
"""
results = []
# ── Pre-pass: build a global PID → PPID map from ALL findings ────────────
# Findings from eng_unusual_parent_child and eng_wmi_suspicious_spawn carry
# "parent_pid" / "ppid" in their evidence items, letting us detect
# parent→child process relationships across the whole image.
pid_to_ppid: Dict[str, str] = {}
for f in all_findings:
for ev in f.get("evidence", []):
child_pid = _ev_pid(ev)
parent_pid = str(
ev.get("parent_pid") or ev.get("ppid") or ev.get("PPID") or
ev.get("ParentPID") or ""
).strip()
if (child_pid and parent_pid
and parent_pid not in ("", "N/A", "None", "0", "nan")):
pid_to_ppid[child_pid] = parent_pid
for pair in correlation_pairs:
primary_ids = set(pair.get("primary_ids", []))
secondary_ids = set(pair.get("secondary_ids", []))
all_ids = primary_ids | secondary_ids
# ── Step 1: classify each referenced finding as PID-bearing or system-wide ──
pid_bearing: Dict[str, List[Dict]] = {} # finding_id -> list of evidence items with a PID
system_wide: List[Dict] = [] # evidence items from PID-less findings (all IDs combined)
for f in all_findings:
if f["id"] not in all_ids:
continue
ev_with_pid = [ev for ev in f.get("evidence", []) if _ev_pid(ev)]
ev_no_pid = [ev for ev in f.get("evidence", []) if not _ev_pid(ev)]
if ev_with_pid:
pid_bearing[f["id"]] = ev_with_pid
elif ev_no_pid:
system_wide.append({
"finding_id": f["id"],
"title": f.get("title", f["id"]),
"evidence": ev_no_pid[:5],
"time_utc": f.get("time_utc", "unknown"),
})
# ── Step 2: build PID sets for primary and secondary ──
def _pids_for(ids):
s = set()
for fid in ids:
for ev in pid_bearing.get(fid, []):
p = _ev_pid(ev)
if p:
s.add(p)
return s
primary_pids = _pids_for(primary_ids)
secondary_pids = _pids_for(secondary_ids)
correlated_pids = primary_pids & secondary_pids
pair_results: List[Dict] = [] # chains produced for this pair
# ── Step 3 (STRONG): same PID in both primary and secondary ──────────
for pid in sorted(correlated_pids):
chain = []
for f in all_findings:
if f["id"] not in all_ids:
continue
pid_ev = [ev for ev in pid_bearing.get(f["id"], []) if _ev_pid(ev) == pid]
if pid_ev:
chain.append({
"finding_id": f["id"],
"title": f.get("title", f["id"]),
"evidence": pid_ev,
"time_utc": f.get("time_utc", "unknown"),
})
chain.extend(system_wide)
if chain:
pair_results.append({
"correlated_pid": pid,
"correlated_findings": chain,
"correlated_rule_ids": list(all_ids),
"confidence": "strong",
"correlation_type": "same_pid",
})
# ── Step 4 (MEDIUM): parent-child PID relationship ───────────────────
# Primary finding's PID is a parent (or child) of a secondary PID.
# Uses the pid_to_ppid map built from parent_pid / ppid evidence fields.
if not pair_results:
pc_seen: set = set() # avoid duplicate chains for the same pair
for p_pid in sorted(primary_pids):
for s_pid in sorted(secondary_pids):
# Direct parent → child or child → parent
is_p_parent = pid_to_ppid.get(s_pid) == p_pid
is_s_parent = pid_to_ppid.get(p_pid) == s_pid
if not (is_p_parent or is_s_parent):
continue
pair_key = (min(p_pid, s_pid), max(p_pid, s_pid))
if pair_key in pc_seen:
continue
pc_seen.add(pair_key)
parent_pid_label = p_pid if is_p_parent else s_pid
child_pid_label = s_pid if is_p_parent else p_pid
chain = []
for f in all_findings:
if f["id"] not in all_ids:
continue
for target_pid in (p_pid, s_pid):
pid_ev = [
ev for ev in pid_bearing.get(f["id"], [])
if _ev_pid(ev) == target_pid
]
if pid_ev:
chain.append({
"finding_id": f["id"],
"title": f.get("title", f["id"]),
"evidence": pid_ev,
"time_utc": f.get("time_utc", "unknown"),
"process_role": (
"parent" if target_pid == parent_pid_label
else "child"
),
})
chain.extend(system_wide)
if chain:
pair_results.append({
"correlated_pid": parent_pid_label,
"correlated_findings": chain,
"correlated_rule_ids": list(all_ids),
"confidence": "medium",
"correlation_type": "parent_child",
"note": (
f"Parent-child correlation: PID {parent_pid_label} "
f"spawned PID {child_pid_label}. "
"Suspicious activity spans a process spawn boundary."
),
})
# ── Step 5 (WEAK): behavioral co-presence fallback ───────────────────
# Both primary AND secondary findings exist in the image but share no
# PID or parent-child link. Still meaningful — co-occurring indicators
# suggest a multi-stage attack even when individual stages used separate
# processes (e.g. certutil download finished before netstat snapshot).
if not pair_results:
secondary_present = any(
f["id"] in secondary_ids and f.get("evidence")
for f in all_findings
)
if secondary_present and primary_pids:
for pid in sorted(primary_pids):
chain = []
for f in all_findings:
if f["id"] not in primary_ids:
continue
pid_ev = [ev for ev in pid_bearing.get(f["id"], []) if _ev_pid(ev) == pid]
if pid_ev:
chain.append({
"finding_id": f["id"],
"title": f.get("title", f["id"]),
"evidence": pid_ev,
"time_utc": f.get("time_utc", "unknown"),
})
for f in all_findings:
if f["id"] not in secondary_ids or not f.get("evidence"):
continue
chain.append({
"finding_id": f["id"],
"title": f.get("title", f["id"]),
"evidence": f.get("evidence", [])[:5],
"time_utc": f.get("time_utc", "unknown"),
"co_presence": True,
})
chain.extend(system_wide)
if chain:
pair_results.append({
"correlated_pid": pid,
"correlated_findings": chain,
"correlated_rule_ids": list(all_ids),
"confidence": "weak",
"correlation_type": "co_presence",
"note": (
"Behavioral co-presence: primary and secondary findings "
"both detected in this image with no shared PID or "
"process-spawn relationship. Indicates a multi-stage "
"pattern across separate processes."
),
})
results.extend(pair_results)
return results
def eng_malfind_injection(text, keywords: List[str]):
findings = []
if not text.strip(): return findings
blocks = text.splitlines()
acc = []
for line in blocks:
if line.strip(): acc.append(line)
if not acc: return findings
blob = "\n".join(acc)
matches = re.finditer(r"^PID:\s*(\d+).*?Process:\s*([^\s]+).*?Start:\s*([0-9xa-fA-F]+).*?Protection:\s*([^\r\n]+)", blob, re.I|re.M|re.S)
for m in matches:
item = {
"pid": m.group(1), "process": m.group(2), "Start": m.group(3),
"Protection": m.group(4).strip(), "PrivateMemory": "", "Notes": ""
}
if keywords:
kblob = blob[max(0, m.start()-400): m.end()+400]
for kw in keywords:
if re.search(kw, kblob, re.I):
item["Notes"] = f"Keyword hit: {kw}"
break
findings.append(item)
return findings
def eng_hollowed_process(text, keywords: List[str]):
findings = []
if not text.strip(): return findings
for line in text.splitlines():
if "Hollowed" in line or "hollow" in line.lower():
row = {"Details": line.strip()}
if keywords:
for kw in keywords:
if re.search(kw, line, re.I):
row["Details"] += f" [kw:{kw}]"
break
findings.append(row)
return findings
def eng_ldr_unlinked_module(text, temp_like_paths: List[str]):
findings = []
if not text.strip(): return findings
rx_temp = compile_any_contains_to_regex(temp_like_paths) if temp_like_paths else None
for line in text.splitlines():
low = line.lower()
flag = ("false" in low and ("inload" in low or "ininit" in low or "inmem" in low))
if not flag and rx_temp:
flag = bool(rx_temp.search(low))
if flag:
findings.append({"Details": line.strip()})
return findings
def eng_handles_general(text, access_regex: str, target_regex: str = None, lsass_special=False):
findings = []
if not text.strip(): return findings
re_access = re.compile(access_regex, re.I) if access_regex else None
re_target = re.compile(target_regex, re.I) if target_regex else None
for line in text.splitlines():
low = line.lower()
if re_access and not re_access.search(low): continue
if re_target and not re_target.search(low): continue
m = re.search(r"(?i)PID\s+(\d+).*?(?i)Process\s+([^\s]+)", line)
req_pid = m.group(1) if m else ""
req_name = m.group(2) if m else ""
tgt = ""
if "lsass" in low: tgt = "lsass.exe"
findings.append({
"requestor_pid": req_pid, "requestor_name": req_name, "target_pid": "",
"target_name": tgt, "GrantedAccess": line.strip()
})
return findings
def eng_services_suspicious(rows: List[Dict[str, str]], temp_like_paths: List[str], baseline) -> List[Dict[str, Any]]:
findings = []
if not rows or not temp_like_paths:
return findings
rx = compile_any_contains_to_regex(temp_like_paths)
allowlist = baseline.get('service_path_allowlist', [])
for r in rows:
image_path = r.get("ImagePath", "")
service_name = r.get("ServiceName", "")
is_allowed = False
for entry in allowlist:
if entry.get('service_name') == service_name:
regex = entry.get('image_path_regex')
if regex and re.search(regex, image_path, re.I):
is_allowed = True
break
if not is_allowed and image_path and rx.search(image_path.lower()):
findings.append({
"ServiceName": service_name, "ServiceType": r.get("Type", "N/A"),
"ImagePath": image_path, "Start": r.get("Start", "N/A"), "Pid": r.get("Pid", "N/A")
})
return findings
def eng_scheduled_tasks(text, temp_like_paths: List[str], risky_exts: List[str]):
findings = []
if not text.strip(): return findings
rx_path = compile_any_contains_to_regex(temp_like_paths) if temp_like_paths else None
rx_ext = re.compile(r"\.(" + "|".join([re.escape(e) for e in risky_exts]) + r")(\.|$)", re.I) if risky_exts else None
for line in text.splitlines():
low = line.lower()
if (rx_path and rx_path.search(low)) or (rx_ext and rx_ext.search(low)):
findings.append({"TaskLine": line.strip()})
return findings
def eng_filescan_path_match(text, any_path_contains: List[str], any_file_ext: List[str], any_name_contains: List[str], baseline: Dict[str, Any]):
findings = []
if not text.strip(): return findings
rx_path = compile_any_contains_to_regex(any_path_contains) if any_path_contains else None
rx_names = compile_any_contains_to_regex(any_name_contains) if any_name_contains else None
rx_ext = None
if any_file_ext:
rx_ext = re.compile(r"\.(" + "|".join([re.escape(e) for e in any_file_ext]) + r")(\.|$)", re.I)
allowlist = baseline.get('file_path_allowlist', [])