Repository navigation
Expand file tree
/
Copy pathprocess_monitor.py
More file actions
137 lines (116 loc) · 4.36 KB
/
Copy pathprocess_monitor.py
File metadata and controls
137 lines (116 loc) · 4.36 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
"""
File: process_monitor.py
Description: Real-time Process Monitor using WMI
- Detects suspicious processes based on heuristics
- Triggers alerts for analysis
"""
import os
import time
import psutil
import logging
from datetime import datetime
from typing import List, Dict, Set
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("monitor.log"),
logging.StreamHandler()
]
)
class ProcessMonitor:
"""Monitors system processes for suspicious activity"""
def __init__(self, interval: int = 5):
self.interval = interval
self.known_pids: Set[int] = set()
self.suspicious_keywords = [
'powershell', 'cmd.exe', 'mshta', 'rundll32',
'regsvr32', 'wscript', 'cscript', 'bitsadmin',
'certutil', 'net.exe', 'net1.exe'
]
self.whitelisted_parents = [
'explorer.exe', 'services.exe', 'svchost.exe'
]
def get_process_info(self, proc: psutil.Process) -> Dict:
"""Extract process information safely"""
try:
return {
'pid': proc.pid,
'name': proc.name(),
'cmdline': " ".join(proc.cmdline()),
'parent': proc.parent().name() if proc.parent() else None,
'username': proc.username(),
'create_time': datetime.fromtimestamp(proc.create_time())
}
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
return {}
def is_suspicious(self, info: Dict) -> bool:
"""Heuristic analysis of process"""
if not info:
return False
name = info.get('name', '').lower()
cmdline = info.get('cmdline', '').lower()
# 1. Suspicious binary names
if any(kw in name for kw in self.suspicious_keywords):
# Exception for empty/basic cmd/powershell sessions (reduce noise)
if name in ['cmd.exe', 'powershell.exe'] and len(cmdline) < 50:
return False
return True
# 2. Suspicious command line arguments
risk_args = [
'-enc', 'base64', '-nop', '-hidden', # PowerShell
'http://', 'https://', # Network
'downloadstring', 'iex', # Download/Execute
'bypass', # Execution Policy
'c:\\windows\\temp', # Temp paths
'appdata' # User paths
]
if any(arg in cmdline for arg in risk_args):
return True
return False
def scan(self):
"""Scan running processes"""
current_pids = set()
for proc in psutil.process_iter(['pid', 'name']):
pid = proc.info['pid']
current_pids.add(pid)
# Skip if already analyzed
if pid in self.known_pids:
continue
# Analyze new process
info = self.get_process_info(proc)
if self.is_suspicious(info):
self._alert(info)
# Update known pids (remove terminated ones)
self.known_pids = current_pids
def _alert(self, info: Dict):
"""Trigger alert"""
alert_msg = f"""
🚨 SUSPICIOUS PROCESS DETECTED 🚨
--------------------------------
PID: {info['pid']}
Name: {info['name']}
Command: {info['cmdline'][:200]}...
Parent: {info['parent']}
User: {info['username']}
Time: {info['create_time']}
--------------------------------
"""
logging.warning(alert_msg)
# TODO: Trigger memory dump here
# dumper.dump_process(info['pid'])
def run(self):
"""Main monitoring loop"""
logging.info("🛡️ Argus Process Monitor Started...")
logging.info(f" Scan interval: {self.interval}s")
logging.info(" Press Ctrl+C to stop")
try:
while True:
self.scan()
time.sleep(self.interval)
except KeyboardInterrupt:
logging.info("Process Monitor stopped by user.")
if __name__ == '__main__':
monitor = ProcessMonitor(interval=2)
monitor.run()