-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic_analysis_sandbox.py
More file actions
2094 lines (1778 loc) · 71.3 KB
/
dynamic_analysis_sandbox.py
File metadata and controls
2094 lines (1778 loc) · 71.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
"""
Dynamic Malware Analysis Sandbox Script (Windows VM)
What this script does:
1) Executes a specified executable sample (the file under analysis).
2) Monitors and logs newly created processes from that sample's process tree.
3) Monitors and logs file create/modify/delete events under C:\\Users\\.
4) Exports all findings as a clean JSON IOC report.
Why extra packages are used:
- psutil: reliable process inspection on Windows.
- watchdog: real-time filesystem event monitoring.
- yara-python (optional): YARA scanning support for dropped files.
Install dependencies inside the isolated VM:
pip install psutil watchdog
pip install yara-python # optional for YARA integration
Example run:
python dynamic_analysis_sandbox.py --sample "C:\\\\path\\\\to\\\\sample.exe" --duration 120 --output "ioc_report.json"
Safety notes:
- Run ONLY in an isolated analysis VM.
- Prefer snapshots so you can revert quickly after each run.
- Do not run unknown samples on host or production systems.
"""
from __future__ import annotations
import argparse
import ctypes
import csv
import hashlib
import ipaddress
import json
import math
import os
import shutil
import subprocess
import sys
import threading
import time
import xml.etree.ElementTree as ET
from collections import defaultdict
from dataclasses import dataclass, asdict
from datetime import datetime, timezone, timedelta
from socket import SOCK_DGRAM, SOCK_STREAM
from typing import Any, Dict, List, Set, Tuple
try:
import winreg # type: ignore
except Exception:
winreg = None
from ctypes import wintypes
# Third-party dependencies (install with: pip install psutil watchdog)
import psutil
from watchdog.events import FileSystemEvent, FileSystemEventHandler
from watchdog.observers import Observer
try:
import yara # type: ignore
except Exception:
yara = None
try:
import mss # type: ignore
except Exception:
mss = None
try:
from PIL import ImageGrab # type: ignore
except Exception:
ImageGrab = None
VM_REGISTRY_PATH = r"SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters"
KNOWN_VM_ARTIFACT_PATHS = [
r"C:\Windows\System32\drivers\vmmouse.sys",
r"C:\Windows\System32\drivers\vmhgfs.sys",
r"C:\Windows\System32\drivers\VBoxMouse.sys",
r"C:\Windows\System32\drivers\VBoxGuest.sys",
]
JOB_OBJECT_LIMIT_ACTIVE_PROCESS = 0x00000008
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS = 9
CREATE_SUSPENDED = 0x00000004
CREATE_NEW_PROCESS_GROUP = 0x00000200
DEBUG_PROCESS = 0x00000001
class IO_COUNTERS(ctypes.Structure):
_fields_ = [
("ReadOperationCount", ctypes.c_uint64),
("WriteOperationCount", ctypes.c_uint64),
("OtherOperationCount", ctypes.c_uint64),
("ReadTransferCount", ctypes.c_uint64),
("WriteTransferCount", ctypes.c_uint64),
("OtherTransferCount", ctypes.c_uint64),
]
class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
_fields_ = [
("PerProcessUserTimeLimit", ctypes.c_longlong),
("PerJobUserTimeLimit", ctypes.c_longlong),
("LimitFlags", wintypes.DWORD),
("MinimumWorkingSetSize", ctypes.c_size_t),
("MaximumWorkingSetSize", ctypes.c_size_t),
("ActiveProcessLimit", wintypes.DWORD),
("Affinity", ctypes.c_size_t),
("PriorityClass", wintypes.DWORD),
("SchedulingClass", wintypes.DWORD),
]
class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
_fields_ = [
("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION),
("IoInfo", IO_COUNTERS),
("ProcessMemoryLimit", ctypes.c_size_t),
("JobMemoryLimit", ctypes.c_size_t),
("PeakProcessMemoryUsed", ctypes.c_size_t),
("PeakJobMemoryUsed", ctypes.c_size_t),
]
class STARTUPINFOW(ctypes.Structure):
_fields_ = [
("cb", wintypes.DWORD),
("lpReserved", wintypes.LPWSTR),
("lpDesktop", wintypes.LPWSTR),
("lpTitle", wintypes.LPWSTR),
("dwX", wintypes.DWORD),
("dwY", wintypes.DWORD),
("dwXSize", wintypes.DWORD),
("dwYSize", wintypes.DWORD),
("dwXCountChars", wintypes.DWORD),
("dwYCountChars", wintypes.DWORD),
("dwFillAttribute", wintypes.DWORD),
("dwFlags", wintypes.DWORD),
("wShowWindow", wintypes.WORD),
("cbReserved2", wintypes.WORD),
("lpReserved2", ctypes.POINTER(ctypes.c_ubyte)),
("hStdInput", wintypes.HANDLE),
("hStdOutput", wintypes.HANDLE),
("hStdError", wintypes.HANDLE),
]
class PROCESS_INFORMATION(ctypes.Structure):
_fields_ = [
("hProcess", wintypes.HANDLE),
("hThread", wintypes.HANDLE),
("dwProcessId", wintypes.DWORD),
("dwThreadId", wintypes.DWORD),
]
class WindowsProcessHandle:
"""Small helper around native Windows process/thread handles."""
def __init__(self, process_handle: int, thread_handle: int, pid: int) -> None:
self.process_handle = int(process_handle)
self.thread_handle = int(thread_handle)
self.pid = int(pid)
def poll(self) -> int | None:
if os.name != "nt":
return None
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
wait_result = kernel32.WaitForSingleObject(wintypes.HANDLE(self.process_handle), wintypes.DWORD(0))
WAIT_OBJECT_0 = 0
WAIT_TIMEOUT = 0x00000102
if wait_result == WAIT_TIMEOUT:
return None
if wait_result == WAIT_OBJECT_0:
exit_code = wintypes.DWORD()
kernel32.GetExitCodeProcess(wintypes.HANDLE(self.process_handle), ctypes.byref(exit_code))
return int(exit_code.value)
return None
def close_handles(self) -> None:
if os.name != "nt":
return
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
if self.thread_handle:
kernel32.CloseHandle(wintypes.HANDLE(self.thread_handle))
self.thread_handle = 0
if self.process_handle:
kernel32.CloseHandle(wintypes.HANDLE(self.process_handle))
self.process_handle = 0
def launch_windows_process_suspended(sample_path: str, debug_process: bool) -> WindowsProcessHandle:
"""Launch a Windows process suspended so Job Object assignment can happen before execution."""
if os.name != "nt":
raise RuntimeError("Suspended launch is only supported on Windows.")
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
create_process = kernel32.CreateProcessW
create_process.argtypes = [
wintypes.LPCWSTR,
wintypes.LPWSTR,
ctypes.c_void_p,
ctypes.c_void_p,
wintypes.BOOL,
wintypes.DWORD,
ctypes.c_void_p,
wintypes.LPCWSTR,
ctypes.POINTER(STARTUPINFOW),
ctypes.POINTER(PROCESS_INFORMATION),
]
create_process.restype = wintypes.BOOL
creationflags = CREATE_NEW_PROCESS_GROUP | CREATE_SUSPENDED
if debug_process:
creationflags |= DEBUG_PROCESS
startup_info = STARTUPINFOW()
startup_info.cb = ctypes.sizeof(STARTUPINFOW)
proc_info = PROCESS_INFORMATION()
command_line_buffer = ctypes.create_unicode_buffer(subprocess.list2cmdline([sample_path]))
current_dir = os.path.dirname(sample_path) or None
ok = create_process(
sample_path,
command_line_buffer,
None,
None,
False,
creationflags,
None,
current_dir,
ctypes.byref(startup_info),
ctypes.byref(proc_info),
)
if not ok:
code = ctypes.get_last_error()
raise RuntimeError(f"CreateProcessW failed with code {code}.")
return WindowsProcessHandle(
process_handle=int(proc_info.hProcess),
thread_handle=int(proc_info.hThread),
pid=int(proc_info.dwProcessId),
)
def resume_windows_process(proc: WindowsProcessHandle) -> None:
"""Resume primary thread of a suspended Windows process."""
if os.name != "nt":
return
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
resume_thread = kernel32.ResumeThread
resume_thread.argtypes = [wintypes.HANDLE]
resume_thread.restype = wintypes.DWORD
result = resume_thread(wintypes.HANDLE(proc.thread_handle))
if result == 0xFFFFFFFF:
code = ctypes.get_last_error()
raise RuntimeError(f"ResumeThread failed with code {code}.")
def utc_now_iso() -> str:
"""Return current UTC timestamp in ISO-8601 format."""
return datetime.now(timezone.utc).isoformat()
def safe_process_name(proc: psutil.Process) -> str:
"""
Read a process name safely.
Malware or short-lived processes can disappear at any time,
so we guard against common psutil exceptions.
"""
try:
return proc.name()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
return "<unavailable>"
def safe_process_cmdline(proc: psutil.Process) -> List[str]:
"""
Read a process command line safely.
Returns an empty list if unavailable.
"""
try:
return proc.cmdline()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
return []
def safe_ppid(proc: psutil.Process) -> int:
"""Read a process parent PID safely."""
try:
return proc.ppid()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
return -1
def safe_process_exe(proc: psutil.Process) -> str | None:
"""Read a process executable path safely."""
try:
return proc.exe()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
return None
def sha256_file(path: str, chunk_size: int = 1024 * 1024) -> str | None:
"""Compute SHA256 for a file path with streaming reads."""
try:
hasher = hashlib.sha256()
with open(path, "rb") as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
hasher.update(chunk)
return hasher.hexdigest()
except (OSError, PermissionError):
return None
def compute_file_hashes(path: str, chunk_size: int = 1024 * 1024) -> Dict[str, str | None]:
"""Compute common file hashes used in threat intelligence sharing."""
try:
md5_hasher = hashlib.md5()
sha1_hasher = hashlib.sha1()
sha256_hasher = hashlib.sha256()
with open(path, "rb") as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
md5_hasher.update(chunk)
sha1_hasher.update(chunk)
sha256_hasher.update(chunk)
return {
"md5": md5_hasher.hexdigest(),
"sha1": sha1_hasher.hexdigest(),
"sha256": sha256_hasher.hexdigest(),
}
except (OSError, PermissionError):
return {"md5": None, "sha1": None, "sha256": None}
def is_public_ip(value: str) -> bool:
"""Return True for routable public IPs, False for local/reserved ranges."""
if not value:
return False
try:
ip = ipaddress.ip_address(value)
return not (
ip.is_private
or ip.is_loopback
or ip.is_link_local
or ip.is_multicast
or ip.is_reserved
or ip.is_unspecified
)
except ValueError:
return False
def calculate_shannon_entropy(data: bytes) -> float:
"""
Calculate Shannon entropy for a byte sequence.
Returns a value 0.0-8.0 indicating randomness/compression.
High entropy (>7.0) suggests encryption or compression.
"""
if not data:
return 0.0
byte_counts: Dict[int, int] = defaultdict(int)
for byte in data:
byte_counts[byte] += 1
entropy = 0.0
length = len(data)
for count in byte_counts.values():
probability = count / length
entropy -= probability * math.log2(probability)
return entropy
class TTLNetworkCache:
"""
TTL-based cache for deduplicating network connections by time window.
Stores (timestamp, pid, protocol, local_ip, local_port, remote_ip, remote_port)
tuples and expires entries older than ttl_seconds.
"""
def __init__(self, ttl_seconds: float = 30.0):
self.ttl_seconds = ttl_seconds
self.entries: Dict[Tuple, float] = {}
def should_log(self, key: Tuple, current_time: float) -> bool:
"""Return True if key should be logged (not in cache or expired)."""
if key in self.entries:
entry_age = current_time - self.entries[key]
if entry_age < self.ttl_seconds:
return False
# Cleanup old entries periodically
if len(self.entries) > 1000:
expired_keys = [k for k, t in self.entries.items()
if current_time - t >= self.ttl_seconds]
for k in expired_keys:
del self.entries[k]
self.entries[key] = current_time
return True
def capture_desktop_screenshot(output_dir: str, prefix: str = "screenshot") -> Dict[str, str]:
"""
Capture a screenshot of the desktop for visual forensics.
Tries PIL.ImageGrab first, then falls back to mss if available.
Returns metadata dict with capture method and status.
"""
if not os.path.isdir(output_dir):
return {
"method": "screenshot",
"status": "error",
"note": f"Output directory does not exist: {output_dir}",
}
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
filename = f"{prefix}_{timestamp}.png"
filepath = os.path.join(output_dir, filename)
try:
if ImageGrab is not None:
try:
img = ImageGrab.grab()
img.save(filepath)
return {
"method": "screenshot",
"status": "ok",
"note": f"Captured with PIL.ImageGrab: {filepath}",
}
except Exception as e:
pass
if mss is not None:
try:
with mss.mss() as sct:
monitor = sct.monitors[1]
screenshot = sct.grab(monitor)
mss.tools.to_png(screenshot.rgb, screenshot.size, output=filepath)
return {
"method": "screenshot",
"status": "ok",
"note": f"Captured with mss: {filepath}",
}
except Exception as e:
pass
return {
"method": "screenshot",
"status": "unavailable",
"note": "Neither PIL nor mss available. Install with: pip install Pillow mss",
}
except Exception as e:
return {
"method": "screenshot",
"status": "error",
"note": f"Screenshot capture failed: {e}",
}
def calculate_process_risk_score(event: ProcessEvent) -> float:
"""
Calculate risk score for a process event (0.0-100.0).
Considers: parent-child relationship, suspicious names, encoded commands.
"""
score = 10.0
suspicious_exes = {
"powershell.exe", "pwsh.exe", "cmd.exe", "wscript.exe", "cscript.exe",
"mshta.exe", "rundll32.exe", "regsvr32.exe", "certutil.exe",
"bitsadmin.exe", "schtasks.exe", "tasksched.exe"
}
if (event.name or "").lower() in suspicious_exes:
score += 25.0
cmdline_text = " ".join(event.cmdline).lower()
if "-enc" in cmdline_text or "frombase64string" in cmdline_text:
score += 30.0
if "http://" in cmdline_text or "https://" in cmdline_text:
score += 20.0
return min(score, 100.0)
def calculate_file_risk_score(event: FileEventRecord) -> float:
"""
Calculate risk score for a file event (0.0-100.0).
Considers: event type, file extension, entropy, suspicious paths.
"""
score = 5.0
suspicious_exts = {".exe", ".dll", ".ps1", ".vbs", ".js", ".hta", ".bat", ".cmd", ".scr"}
path_lower = (event.path or "").lower()
if any(path_lower.endswith(ext) for ext in suspicious_exts):
score += 30.0
if event.entropy is not None and event.entropy > 7.0:
score += 20.0
startup_markers = [
"\\appdata\\roaming\\microsoft\\windows\\start menu\\programs\\startup",
"\\programdata\\microsoft\\windows\\start menu\\programs\\startup"
]
if any(marker in path_lower for marker in startup_markers):
score += 40.0
return min(score, 100.0)
def calculate_network_risk_score(event: NetworkEventRecord) -> float:
"""
Calculate risk score for a network event (0.0-100.0).
Considers: public IP, suspicious ports, DNS tunneling indicators.
"""
score = 5.0
if is_public_ip(event.remote_ip):
score += 25.0
suspicious_ports = {21, 22, 23, 25, 4444, 5555, 8080, 1337, 443, 8443}
if event.remote_port in suspicious_ports:
score += 20.0
if event.is_dns_related and is_public_ip(event.remote_ip):
score += 30.0
return min(score, 100.0)
def detect_c2_beaconing(network_events: List[NetworkEventRecord]) -> Dict[str, Any]:
"""
Detect potential C2 beaconing patterns from network events.
Looks for: high-frequency DNS queries, repeated connections to same host,
connection persistence patterns.
Returns dict with detected patterns and confidence scores.
"""
beaconing_indicators = {
"high_frequency_dns": [],
"repeated_connections": [],
"connection_persistence": [],
"confidence_score": 0.0,
}
# Group by (pid, protocol, remote_ip, remote_port)
connection_groups: Dict[Tuple, List[NetworkEventRecord]] = defaultdict(list)
for event in network_events:
key = (event.pid, event.protocol, event.remote_ip, event.remote_port)
connection_groups[key].append(event)
dns_query_counts: Dict[Tuple[int, str], int] = defaultdict(int)
for event in network_events:
if event.is_dns_related:
key = (event.pid, event.remote_ip)
dns_query_counts[key] += 1
# Detect high-frequency DNS queries (>10 unique queries to same IP)
for (pid, dns_ip), count in dns_query_counts.items():
if count > 10:
beaconing_indicators["high_frequency_dns"].append({
"pid": pid,
"remote_dns_ip": dns_ip,
"query_count": count,
"confidence": min(count / 50.0, 1.0),
})
# Detect repeated connections (same remote host multiple times)
for (pid, protocol, remote_ip, remote_port), events in connection_groups.items():
if len(events) > 5 and protocol == "tcp":
event_times = [datetime.fromisoformat(e.timestamp_utc) for e in events]
event_times.sort()
if len(event_times) >= 3:
intervals = []
for i in range(len(event_times) - 1):
delta = (event_times[i+1] - event_times[i]).total_seconds()
intervals.append(delta)
avg_interval = sum(intervals) / len(intervals)
if 5 < avg_interval < 3600:
beaconing_indicators["repeated_connections"].append({
"pid": pid,
"remote_ip": remote_ip,
"remote_port": remote_port,
"connection_count": len(events),
"avg_interval_seconds": avg_interval,
"confidence": min(len(events) / 20.0, 1.0),
})
# Calculate overall confidence
if beaconing_indicators["high_frequency_dns"]:
beaconing_indicators["confidence_score"] += 0.4
if beaconing_indicators["repeated_connections"]:
beaconing_indicators["confidence_score"] += 0.6
beaconing_indicators["confidence_score"] = min(beaconing_indicators["confidence_score"], 1.0)
return beaconing_indicators
@dataclass
class ProcessEvent:
"""Represents a process creation IOC record."""
timestamp_utc: str
pid: int
ppid: int
name: str
cmdline: List[str]
exe_path: str | None = None
sha256: str | None = None
risk_score: float = 0.0
@dataclass
class FileEventRecord:
"""Represents a filesystem IOC record."""
timestamp_utc: str
event_type: str
path: str
is_directory: bool
destination_path: str | None = None
entropy: float | None = None
risk_score: float = 0.0
@dataclass
class NetworkEventRecord:
"""Represents a network IOC record tied to tracked processes."""
timestamp_utc: str
pid: int
process_name: str
protocol: str
local_ip: str
local_port: int
remote_ip: str
remote_port: int
status: str
is_dns_related: bool
risk_score: float = 0.0
beacon_confidence: float = 0.0
@dataclass
class RegistryEventRecord:
"""Represents a registry IOC from Sysmon event log entries."""
timestamp_utc: str
event_id: int
event_type: str
process_id: str | None
image: str | None
target_object: str | None
details: str | None
risk_score: float = 0.0
@dataclass
class SysmonApiEventRecord:
"""Represents high-signal Sysmon events tied to code injection or remote thread behavior."""
timestamp_utc: str
event_id: int
event_type: str
process_id: str | None
image: str | None
target_process_id: str | None
target_image: str | None
source_process_guid: str | None
target_process_guid: str | None
start_address: str | None
details: str | None
risk_score: float = 0.0
@dataclass
class SecurityAlertRecord:
"""High-signal heuristic alert derived from observed telemetry."""
timestamp_utc: str
category: str
severity: str
message: str
mitre_attack_techniques: List[str]
context: Dict[str, Any]
@dataclass
class YaraMatchRecord:
"""Represents a YARA detection hit on a dropped file."""
timestamp_utc: str
file_path: str
rule: str
namespace: str
tags: List[str]
def check_vm_isolation() -> Tuple[bool, Dict[str, Any]]:
"""Return whether host appears to be a VM using registry key + artifact checks."""
evidence: Dict[str, Any] = {
"registry_key_found": False,
"artifact_paths_found": [],
}
if os.name != "nt":
return False, {"status": "unsupported_platform", **evidence}
if winreg is not None:
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, VM_REGISTRY_PATH):
evidence["registry_key_found"] = True
except OSError:
pass
found_artifacts = [path for path in KNOWN_VM_ARTIFACT_PATHS if os.path.exists(path)]
evidence["artifact_paths_found"] = found_artifacts
is_vm = bool(evidence["registry_key_found"] or found_artifacts)
return is_vm, {"status": "ok", **evidence}
def sanitize_csv_field(value: str) -> str:
"""Mitigate CSV formula injection by neutralizing risky leading characters."""
if value and value[0] in {"=", "+", "-", "@"}:
return "'" + value
return value
def validate_rules_path(yara_rules_path: str, allowed_directory: str) -> str:
"""Constrain YARA rule files to a trusted directory root."""
candidate = os.path.abspath(yara_rules_path)
allowed_root = os.path.abspath(allowed_directory)
common = os.path.commonpath([candidate, allowed_root])
if common != allowed_root:
raise ValueError(
f"YARA rules path is outside allowed directory. path={candidate}, allowed={allowed_root}"
)
return candidate
def terminate_process_tree(root_pid: int, timeout_seconds: int) -> None:
"""Terminate tracked root process and descendants with bounded wait time."""
try:
root = psutil.Process(root_pid)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
return
descendants = root.children(recursive=True)
for proc in descendants:
try:
proc.terminate()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
try:
root.terminate()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
gone, alive = psutil.wait_procs(descendants + [root], timeout=max(1, timeout_seconds))
_ = gone
for proc in alive:
try:
proc.kill()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
def create_and_assign_job_object(
process_handle: int,
max_active_processes: int,
) -> Tuple[int | None, Dict[str, str]]:
"""Create a Windows Job Object and assign the process for kernel-enforced containment."""
if os.name != "nt":
return None, {
"method": "windows_job_object",
"status": "unsupported_platform",
"note": "Job Objects are Windows-only.",
}
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
create_job_object = kernel32.CreateJobObjectW
set_information = kernel32.SetInformationJobObject
assign_process = kernel32.AssignProcessToJobObject
close_handle = kernel32.CloseHandle
create_job_object.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
create_job_object.restype = wintypes.HANDLE
set_information.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]
set_information.restype = wintypes.BOOL
assign_process.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
assign_process.restype = wintypes.BOOL
close_handle.argtypes = [wintypes.HANDLE]
close_handle.restype = wintypes.BOOL
job_handle = create_job_object(None, None)
if not job_handle:
code = ctypes.get_last_error()
return None, {
"method": "windows_job_object",
"status": "error",
"note": f"CreateJobObjectW failed with code {code}.",
}
limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
limits.BasicLimitInformation.LimitFlags = (
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_ACTIVE_PROCESS
)
limits.BasicLimitInformation.ActiveProcessLimit = max(1, int(max_active_processes))
ok = set_information(
job_handle,
JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS,
ctypes.byref(limits),
ctypes.sizeof(limits),
)
if not ok:
code = ctypes.get_last_error()
close_handle(job_handle)
return None, {
"method": "windows_job_object",
"status": "error",
"note": f"SetInformationJobObject failed with code {code}.",
}
ok = assign_process(job_handle, wintypes.HANDLE(process_handle))
if not ok:
code = ctypes.get_last_error()
close_handle(job_handle)
return None, {
"method": "windows_job_object",
"status": "error",
"note": f"AssignProcessToJobObject failed with code {code}.",
}
return int(job_handle), {
"method": "windows_job_object",
"status": "ok",
"note": f"Assigned process to Job Object with ActiveProcessLimit={max_active_processes} and KillOnJobClose.",
}
def close_job_object(job_handle: int | None) -> None:
"""Close job handle to trigger KILL_ON_JOB_CLOSE behavior."""
if not job_handle:
return
if os.name != "nt":
return
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.CloseHandle(wintypes.HANDLE(job_handle))
def maybe_dump_process_memory(
pid: int,
output_dir: str,
enabled: bool,
procdump_path: str,
) -> Dict[str, str]:
"""Optionally capture a full process memory dump using procdump if available."""
if not enabled:
return {
"method": "procdump",
"status": "disabled",
"note": "Memory dump disabled by CLI option.",
}
resolved_proc_dump = shutil.which(procdump_path) or procdump_path
if not os.path.exists(resolved_proc_dump):
return {
"method": "procdump",
"status": "unavailable",
"note": f"ProcDump executable not found: {procdump_path}",
}
os.makedirs(output_dir, exist_ok=True)
dump_path = os.path.join(output_dir, f"sample_{pid}.dmp")
cmd = [resolved_proc_dump, "-accepteula", "-ma", str(pid), dump_path]
try:
completed = subprocess.run(cmd, capture_output=True, text=True, check=False, timeout=45)
except subprocess.TimeoutExpired:
return {
"method": "procdump",
"status": "timeout",
"note": "ProcDump timed out while collecting memory.",
}
except Exception as exc:
return {
"method": "procdump",
"status": "error",
"note": f"ProcDump execution failed: {exc}",
}
if completed.returncode != 0:
message = completed.stderr.strip() or completed.stdout.strip() or "Unknown ProcDump error"
return {
"method": "procdump",
"status": "error",
"note": message,
}
return {
"method": "procdump",
"status": "ok",
"note": f"Memory dump written to: {dump_path}",
}
def collect_sysmon_events(
event_ids: List[int],
start_time_utc: datetime,
end_time_utc: datetime,
timeout_seconds: int = 30,
) -> Tuple[List[ET.Element], Dict[str, str]]:
"""Collect Sysmon XML event nodes for requested event IDs in time window."""
start_str = start_time_utc.strftime("%Y-%m-%dT%H:%M:%S.000Z")
end_str = end_time_utc.strftime("%Y-%m-%dT%H:%M:%S.999Z")
id_clause = " or ".join(f"EventID={event_id}" for event_id in event_ids)
query = (
"*[System[(" + id_clause + ") and "
f"TimeCreated[@SystemTime>='{start_str}' and @SystemTime<='{end_str}']]]"
)
cmd = [
"wevtutil",
"qe",
"Microsoft-Windows-Sysmon/Operational",
"/q:" + query,
"/f:xml",
]
try:
completed = subprocess.run(
cmd,
capture_output=True,
text=True,
check=False,
timeout=timeout_seconds,
)
except FileNotFoundError:
return [], {"status": "unavailable", "note": "wevtutil was not found on this system."}
except subprocess.TimeoutExpired:
return [], {"status": "timeout", "note": "Timed out while querying Sysmon event log."}
if completed.returncode != 0:
note = completed.stderr.strip() or completed.stdout.strip() or "Unknown wevtutil error."
return [], {"status": "unavailable", "note": note}
xml_text = completed.stdout.strip()
if not xml_text:
return [], {"status": "ok", "note": "No Sysmon events matched the time window."}
wrapped = "<Events>" + xml_text + "</Events>"
try:
root = ET.fromstring(wrapped)
except ET.ParseError as exc:
return [], {"status": "parse_error", "note": f"Failed to parse Sysmon XML output: {exc}"}
ns = {"ev": "http://schemas.microsoft.com/win/2004/08/events/event"}
nodes = root.findall("ev:Event", ns)
return nodes, {"status": "ok", "note": "Sysmon events collected."}
class UsersDirEventHandler(FileSystemEventHandler):
"""
Custom watchdog event handler.
Each filesystem event is converted into a serializable record.
"""
def __init__(self, events: List[FileEventRecord], lock: threading.Lock) -> None:
super().__init__()
self._events = events
self._lock = lock