forked from ZorgeR/perfctl-ioc-detector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinux_compromise_detector.py
More file actions
460 lines (410 loc) · 17.2 KB
/
linux_compromise_detector.py
File metadata and controls
460 lines (410 loc) · 17.2 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
#!/usr/bin/env python3
import contextlib
import os
import subprocess
import hashlib
import re
import json
from datetime import datetime
from pathlib import Path
class CompromiseDetector:
def __init__(self):
self.findings = []
# Directories to check (must end with /)
self.suspicious_dirs = [
"/tmp/.xdiag/",
"/tmp/.perf.c/",
"/usr/bin/.atmp/tmp/.applocal.xdiag/",
"/dev/shm/.dmesg/pds/"
]
self.malicious_libs = [
"/lib/libfsnldev.so",
"/lib/libgcwrap.so",
"/lib/libpprocps.so",
"/usr/lib/libfsnldev.so",
"/usr/lib/libgcwrap.so",
"/usr/lib/libpprocps.so",
]
# Files to check
self.suspicious_files = self.malicious_libs + [
"/tmp/wttwe",
"/tmp/kubeupd",
"/bin/kkbush",
"/bin/perfcc",
"/usr/bin/perfcc",
"/usr/bin/wizlmsh",
"/dev/shm/libfsnldev.so",
"/dev/shm/libpprocps.so"
"/root/.config/cron/perfcc",
]
self.suspicious_processes = [
"perfctl",
"perfcc",
"kubeupd",
"kkbush",
"xmrig" # Common cryptominer
]
def direct_directory_check(self, path):
"""Try to detect directory using direct syscalls via find command"""
try:
# Use find command which might bypass userspace hooks
cmd = f"find {path.rstrip('/')} -maxdepth 0 2>/dev/null"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.returncode == 0 and result.stdout.strip() != ""
except:
return False
def check_with_find(self, path):
"""Use find command which might bypass some rootkit hooks"""
try:
cmd = f"find {path} -maxdepth 0 2>/dev/null"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.returncode == 0 and result.stdout.strip() != ""
except:
return False
def check_with_ls(self, path):
"""Use ls command which might use different syscalls"""
try:
cmd = f"ls -la {path} 2>/dev/null"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.returncode == 0 and result.stdout.strip() != ""
except:
return False
def check_with_dir(self, path):
"""Try to open directory directly"""
try:
if os.path.isdir(path):
os.listdir(path)
return True
except:
return False
return False
def check_suspicious_files(self):
"""Check for known malicious files and directories using multiple methods"""
# Check directories
for path in self.suspicious_dirs:
path = path.rstrip('/') # Remove trailing slash for exists check
print(f"[DEBUG] Checking directory: {path}")
# Try multiple detection methods
methods = {
'direct': self.direct_directory_check(path),
'find': self.check_with_find(path),
'ls': self.check_with_ls(path),
'dir': self.check_with_dir(path)
}
print(f"[DEBUG] Detection methods results: {methods}")
if any(methods.values()):
self.findings.append({
"type": "suspicious_directory",
"severity": "CRITICAL",
"details": f"Found suspicious directory: {path}/ (detected by: {[k for k,v in methods.items() if v]})",
"timestamp": datetime.now().isoformat()
})
# Check files using multiple methods
for path in self.suspicious_files:
if self.check_with_find(path) or self.check_with_ls(path):
self.findings.append({
"type": "malicious_file",
"severity": "CRITICAL",
"details": f"Found suspicious file: {path}",
"timestamp": datetime.now().isoformat()
})
def check_for_rootkit(self):
"""Check for signs of rootkit presence"""
# Check for hidden processes using different ps commands
try:
ps_aux = subprocess.check_output(["ps", "aux"], text=True)
ps_ef = subprocess.check_output(["ps", "-ef"], text=True)
if len(ps_aux.splitlines()) != len(ps_ef.splitlines()):
self.findings.append({
"type": "rootkit_indicator",
"severity": "CRITICAL",
"details": "Process hiding detected (different process counts between ps commands)",
"timestamp": datetime.now().isoformat()
})
except:
pass
# Check for common rootkit files
rootkit_libs = [
"/lib/libgcwrap.so",
"/lib/libprocesshider.so",
"/lib/libnss_files.so.2",
]
for lib in rootkit_libs:
if self.check_with_find(lib) or self.check_with_ls(lib):
self.findings.append({
"type": "rootkit_indicator",
"severity": "CRITICAL",
"details": f"Potential rootkit library found: {lib}",
"timestamp": datetime.now().isoformat()
})
def check_processes(self):
"""Check for suspicious running processes"""
try:
ps_output = subprocess.check_output(["ps", "aux"], text=True)
for proc in self.suspicious_processes:
if proc in ps_output:
self.findings.append({
"type": "suspicious_process",
"severity": "HIGH",
"details": f"Found suspicious process: {proc}",
"timestamp": datetime.now().isoformat()
})
except subprocess.SubProcessError:
self.findings.append({
"type": "error",
"severity": "MEDIUM",
"details": "Unable to check processes",
"timestamp": datetime.now().isoformat()
})
def check_crontabs(self):
"""Check for suspicious cron jobs"""
try:
crontab_output = subprocess.check_output(["crontab", "-l"], text=True)
suspicious_patterns = [
r"/tmp/",
r"curl.*wget",
r"bash.*-c",
r"exec.*3<>/dev/tcp"
]
for pattern in suspicious_patterns:
if re.search(pattern, crontab_output):
self.findings.append({
"type": "suspicious_crontab",
"severity": "HIGH",
"details": f"Found suspicious crontab entry matching: {pattern}",
"timestamp": datetime.now().isoformat()
})
except subprocess.SubProcessError:
pass # Ignore if no crontab exists
def check_systemd_services(self):
"""Check for suspicious systemd services"""
try:
services = subprocess.check_output(["systemctl", "list-units", "--type=service", "--all"], text=True)
suspicious_patterns = [
"KubeUpdate",
"ExecStart=/tmp",
"perfctl"
]
for pattern in suspicious_patterns:
if pattern in services:
self.findings.append({
"type": "suspicious_service",
"severity": "HIGH",
"details": f"Found suspicious systemd service matching: {pattern}",
"timestamp": datetime.now().isoformat()
})
except subprocess.SubProcessError:
self.findings.append({
"type": "error",
"severity": "MEDIUM",
"details": "Unable to check systemd services",
"timestamp": datetime.now().isoformat()
})
def check_docker_containers(self):
"""Check for suspicious Docker containers"""
try:
containers = subprocess.check_output(["docker", "ps", "-a"], text=True)
suspicious_patterns = [
"xmrig",
"monero",
"crypto",
"proxy"
]
for pattern in suspicious_patterns:
if pattern in containers.lower():
self.findings.append({
"type": "suspicious_container",
"severity": "HIGH",
"details": f"Found suspicious Docker container matching: {pattern}",
"timestamp": datetime.now().isoformat()
})
except (subprocess.SubProcessError, FileNotFoundError):
pass # Docker might not be installed
def check_portainer_exposure(self):
"""Check if Portainer agent is exposed"""
try:
netstat = subprocess.check_output(["netstat", "-tulpn"], text=True)
if ":9001" in netstat:
self.findings.append({
"type": "exposed_service",
"severity": "HIGH",
"details": "Portainer agent port (9001) is exposed",
"timestamp": datetime.now().isoformat()
})
except subprocess.SubProcessError:
self.findings.append({
"type": "error",
"severity": "MEDIUM",
"details": "Unable to check network ports",
"timestamp": datetime.now().isoformat()
})
def check_ssh_backdoors(self):
"""Check for potential SSH backdoors"""
ssh_paths = [
os.path.expanduser("~/.ssh/authorized_keys"),
"/root/.ssh/authorized_keys"
]
for path in ssh_paths:
if os.path.exists(path):
try:
with open(path, 'r') as f:
content = f.read()
if len(content.splitlines()) > 10: # Arbitrary threshold
self.findings.append({
"type": "suspicious_ssh",
"severity": "MEDIUM",
"details": f"Large number of SSH keys in {path}",
"timestamp": datetime.now().isoformat()
})
except PermissionError:
pass
def check_ld_preload(self):
"""Check for LD_PRELOAD hijacking"""
try:
env = subprocess.check_output(["env"], text=True)
if "LD_PRELOAD" in env:
self.findings.append({
"type": "suspicious_env",
"severity": "HIGH",
"details": "LD_PRELOAD environment variable is set",
"timestamp": datetime.now().isoformat()
})
except subprocess.SubProcessError:
pass
def check_lib_presence_with_ldd(self):
"""Check for malicious libraries loaded by system binaries"""
# Run ldd with LD_PRELOAD unset to avoid hooks
result = subprocess.run(
["env", "--unset=LD_PRELOAD", "ldd", "/sbin/fsck.ext4"],
capture_output=True,
text=True
)
# Check for malicious libraries in dependencies
for lib in self.malicious_libs:
if lib in result.stdout:
self.findings.append({
"type": "malicious_library_loaded",
"severity": "CRITICAL",
"details": f"Found malicious library in ldd output (without LD_PRELOAD): {lib}",
"timestamp": datetime.now().isoformat()
})
def check_libs_in_maps(self):
"""Check for malicious libraries mapped into process memory"""
for pid in filter(lambda x: x.isdigit, os.listdir("/proc")):
maps_file_path = f"/proc/{pid}/maps"
with contextlib.suppress(PermissionError):
if not os.path.exists(maps_file_path):
continue
with open(maps_file_path, 'r') as maps_file:
for line in maps_file:
for lib in self.malicious_libs:
if lib in line:
self.findings.append({
"type": "malicious_library_mapped",
"severity": "CRITICAL",
"details": f"Found malicious library {lib} mapped in PID {pid}: {line.strip()}",
"timestamp": datetime.now().isoformat()
})
return
def check_file_descryptors(self):
"""Check for suspicious .xdiag file descriptor links in processes"""
for pid in filter(lambda x: x.isdigit, os.listdir("/proc")):
fd_path = f"/proc/{pid}/fd"
if not os.path.exists(fd_path):
continue
with contextlib.suppress(PermissionError):
for fd in os.listdir(fd_path):
with contextlib.suppress(OSError):
link = os.readlink(os.path.join(fd_path, fd))
if ".xdiag" in link:
self.findings.append({
"type": "malicious_fd_link",
"severity": "HIGH",
"details": f"Found .xdiag file descriptor link in PID {pid}: {link}",
"timestamp": datetime.now().isoformat()
})
return
def run_all_checks(self):
"""Run all available checks"""
checks = [
self.check_suspicious_files,
self.check_for_rootkit, # Add rootkit detection
self.check_processes,
self.check_crontabs,
self.check_systemd_services,
self.check_docker_containers,
self.check_portainer_exposure,
self.check_ssh_backdoors,
self.check_ld_preload,
self.check_lib_presence_with_ldd,
self.check_libs_in_maps,
self.check_file_descryptors,
]
for check in checks:
try:
check()
except Exception as e:
self.findings.append({
"type": "error",
"severity": "LOW",
"details": f"Error running {check.__name__}: {str(e)}",
"timestamp": datetime.now().isoformat()
})
def generate_report(self):
"""Generate a JSON report of findings"""
report = {
"scan_time": datetime.now().isoformat(),
"findings": self.findings,
"total_findings": len(self.findings)
}
# Generate JSON report
json_report = json.dumps(report, indent=2)
# Generate ASCII table summary
summary = self._generate_summary_table()
return f"{json_report}\n\nSummary:\n{summary}"
def _generate_summary_table(self):
"""Generate ASCII table with findings summary"""
# Count findings by type and severity
summary = {}
for finding in self.findings:
type_sev = (finding['type'], finding['severity'])
summary[type_sev] = summary.get(type_sev, 0) + 1
if not summary:
return "No findings."
# Get unique types and severities
types = sorted(set(t for t, _ in summary.keys()))
severities = sorted(set(s for _, s in summary.keys()))
# Calculate column widths
type_width = max(len("Type"), max(len(t) for t in types))
sev_widths = {sev: len(sev) for sev in severities}
# Generate header
header = "+" + "-" * (type_width + 2)
for sev in severities:
header += "+" + "-" * (sev_widths[sev] + 2)
header += "+\n"
# Generate title row
row = f"| {'Type':<{type_width}} "
for sev in severities:
row += f"| {sev:<{sev_widths[sev]}} "
row += "|\n"
# Generate separator
separator = header
# Generate data rows
table = header + row + separator
for type_ in types:
row = f"| {type_:<{type_width}} "
for sev in severities:
count = summary.get((type_, sev), 0)
row += f"| {str(count):<{sev_widths[sev]}} "
row += "|\n"
table += row
# Add bottom border
table += header
return table
def main():
print("[*] Starting Linux compromise detection...")
detector = CompromiseDetector()
detector.run_all_checks()
print(detector.generate_report())
if __name__ == "__main__":
main()