Repository navigation
Expand file tree
/
Copy pathsysmon_monitor.py
More file actions
299 lines (251 loc) · 11.6 KB
/
Copy pathsysmon_monitor.py
File metadata and controls
299 lines (251 loc) · 11.6 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
"""
File: sysmon_monitor.py
Description: Monitors Sysmon events (ID 1, 8, 22) and verifies with psutil
"""
import sys
import time
import json
import logging
import psutil
import threading
from datetime import datetime
from queue import Queue
try:
import win32evtlog
import xml.etree.ElementTree as ET
except ImportError:
print("❌ Error: pywin32 library not installed. Run: pip install pywin32")
sys.exit(1)
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("sysmon_monitor.log", encoding='utf-8'),
logging.StreamHandler()
]
)
class SysmonMonitor:
"""Monitor Sysmon events and verify suspicious processes"""
# Sysmon Event IDs
EVENT_PROCESS_CREATE = 1
EVENT_REMOTE_THREAD = 8
EVENT_DNS_QUERY = 22
def __init__(self, callback=None):
self.callback = callback # Function to call when suspicious activity detected
self.running = False
self.event_queue = Queue()
def get_process_details(self, pid: int) -> dict:
"""Verify process details using psutil (Dynamic Analysis)"""
try:
proc = psutil.Process(pid)
return {
'pid': pid,
'name': proc.name(),
'status': proc.status(),
'parent': proc.parent().name() if proc.parent() else None,
'cmdline': " ".join(proc.cmdline()),
'connections': len(proc.connections()),
'memory_mb': proc.memory_info().rss / 1024 / 1024,
'verified': True
}
except (psutil.NoSuchProcess, psutil.AccessDenied):
return {'pid': pid, 'verified': False, 'error': 'Process not found or access denied'}
def parse_event_xml(self, xml_content: str) -> dict:
"""Parse Sysmon XML event data using Regex (more robust than XML)"""
data = {}
try:
import re
# Extract EventID
eid_match = re.search(r'<EventID>(\d+)</EventID>', xml_content)
if eid_match:
data['EventID'] = int(eid_match.group(1))
else:
return {} # Invalid event
# Extract EventRecordID
rid_match = re.search(r'<EventRecordID>(\d+)</EventRecordID>', xml_content)
if rid_match:
data['EventRecordID'] = int(rid_match.group(1))
# Extract Data fields (Sysmon specific: <Data Name="X">Y</Data>)
# Use findall for all data items, handling single or double quotes
data_matches = re.findall(r'<Data Name=["\']([^"\']+)["\']>([^<]*)</Data>', xml_content)
for name, value in data_matches:
data[name] = value
return data
except Exception as e:
logging.error(f"Parse Error: {e}")
return {}
def analyze_event(self, event: dict):
"""Analyze event and trigger verification"""
event_id = event.get('EventID')
# Debug log to verify event flow
# logging.info(f" [Debug] Analyzing Event {event_id} (RecordID: {event.get('EventRecordID', '?')})")
# Use ProcessId from Data, fallback to attribute not supported in regex but usually in Data
pid = int(event.get('ProcessId', 0))
image = event.get('Image', 'Unknown')
alert = False
reason = ""
# 1. Process Create (Event 1)
if event_id == self.EVENT_PROCESS_CREATE:
command_line = event.get('CommandLine', '').lower()
if 'powershell' in command_line and ('-enc' in command_line or 'http' in command_line):
alert = True
reason = "Suspicious PowerShell arguments"
elif 'mshta' in image or 'rundll32' in image:
alert = True
reason = "LOLBin execution detected"
# Add a catch-all for debugging if needed, but keep it clean for now.
# print(f"DEBUG: Process Create: {image} | {command_line}")
# 2. Remote Thread / Injection (Event 8)
elif event_id == self.EVENT_REMOTE_THREAD:
target_image = event.get('TargetImage', '')
if target_image != image: # Injection into another process
alert = True
reason = f"Code injection detected from {image} to {target_image}"
pid = int(event.get('TargetProcessId', 0)) # Analyze target process
# 3. DNS Query (Event 22)
elif event_id == self.EVENT_DNS_QUERY:
query = event.get('QueryName', '')
# Simple heuristic
if len(query) > 50 or '.xyz' in query or '.top' in query:
alert = True
reason = f"Suspicious DNS query: {query}"
if alert:
logging.warning(f"🚨 [Sysmon] Suspicious Event {event_id}: {reason}")
logging.info(f" Image: {image} (PID: {pid})")
# Dynamic Verification via Psutil
proc_details = self.get_process_details(pid)
if proc_details.get('verified'):
logging.info(f" ✅ Verified running process: {proc_details['name']}")
else:
logging.info(f" ⚠️ Process {pid} ended, allowing alert based on Event Log.")
# Trigger callback regardless of current process state
# (Because Sysmon event is trustworthy evidence of execution)
if self.callback:
self.callback(pid, reason)
def monitor_loop(self):
"""Main loop to tail Sysmon event log using Polling (EvtQuery)"""
log_type = "Microsoft-Windows-Sysmon/Operational"
try:
logging.info(f"✅ Polling Sysmon events from {log_type}...")
# Track the latest EventRecordID
last_record_id = 0
# Initial pass to get current latest ID
try:
import re
handle = win32evtlog.EvtQuery(log_type, win32evtlog.EvtQueryChannelPath | win32evtlog.EvtQueryReverseDirection, "*")
events = win32evtlog.EvtNext(handle, 1)
if events:
xml = win32evtlog.EvtRender(events[0], win32evtlog.EvtRenderEventXml)
rid_match = re.search(r'<EventRecordID>(\d+)</EventRecordID>', xml)
if rid_match:
last_record_id = int(rid_match.group(1))
logging.info(f" Starting from EventRecordID: {last_record_id}")
else:
logging.info(" ⚠️ Could not extract EventRecordID from initial event (Regex).")
except Exception as e:
logging.info(f" Could not determine last EventID, starting fresh. {e}")
while self.running:
# Re-query recent events
query_handle = win32evtlog.EvtQuery(
log_type,
win32evtlog.EvtQueryChannelPath | win32evtlog.EvtQueryReverseDirection,
"*"
)
# Fetch top 10 newest events
events = win32evtlog.EvtNext(query_handle, 10, 1000, 0)
new_max_id = last_record_id
if events:
for event in events:
xml_content = win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventXml)
event_data = self.parse_event_xml(xml_content)
if event_data:
# Use the RecordID extracted by parse_event_xml
record_id = event_data.get('EventRecordID', 0)
if record_id > last_record_id:
self.analyze_event(event_data)
if record_id > new_max_id:
new_max_id = record_id
last_record_id = new_max_id
query_handle.close()
time.sleep(2)
except Exception as e:
logging.error(f"❌ Polling Error: {e}")
logging.info("Make sure Sysmon is installed and script is run as Administrator.")
def start(self):
self.running = True
self.thread = threading.Thread(target=self.monitor_loop, daemon=True)
self.thread.start()
def stop(self):
self.running = False
if hasattr(self, 'thread'):
self.thread.join(timeout=2)
if __name__ == '__main__':
# Auto-integration with API & Deep Analysis
def api_callback(pid, reason):
def _run_analysis(pid, reason):
try:
import requests
import psutil
from memory_dumper import MemoryDumper
from windbg_tool import WinDBGTool
# 1. Gather basic info
proc_info = {"pid": pid, "status": "unknown"}
proc_name = "unknown"
is_alive = False
try:
p = psutil.Process(pid)
proc_name = p.name()
proc_info = {
"pid": pid,
"name": proc_name,
"cmdline": " ".join(p.cmdline()),
"status": "running"
}
is_alive = True
except:
proc_info["status"] = "terminated"
report = None
# 2. Deep Analysis (if alive)
if is_alive:
logging.info(f" 🕵️ Starting Deep Analysis for PID {pid}...")
# A. Memory Dump
dumper = MemoryDumper()
dump_path = dumper.dump_process(pid, proc_name)
if dump_path:
# B. WinDBG Analysis
debugger = WinDBGTool()
report = debugger.analyze_dump(dump_path)
logging.info(" 🧠 Analysis Report Generated")
# 3. Send to API
payload = {
"source": "sysmon",
"event_id": 1,
"description": reason,
"process_info": proc_info,
"analysis_report": report
}
try:
res = requests.post("http://localhost:8000/alert", json=payload, timeout=10)
if res.status_code == 200:
logging.info(f" 🚀 Alert & Report sent to API (ID: {res.json().get('alert_id')})")
else:
logging.info(f" ⚠️ API returned {res.status_code}")
except Exception as e:
logging.error(f" ⚠️ API Error: {e}")
except Exception as e:
logging.error(f" ❌ Cleanup/Analysis Error: {e}")
# Run in thread to not block monitoring
threading.Thread(target=_run_analysis, args=(pid, reason)).start()
logging.info("Starting Monitor with API + Deep Analysis Integration...")
monitor = SysmonMonitor(callback=api_callback)
try:
monitor.start()
# Keep main thread alive
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
monitor.stop()
print("Monitor stopped.")