-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrules.py
More file actions
403 lines (341 loc) · 15.1 KB
/
Copy pathrules.py
File metadata and controls
403 lines (341 loc) · 15.1 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
import os
from loader import KernelModule, Finding, Severity
class Rule:
name: str = ""
description: str = ""
def analyze(self, module: KernelModule) -> list[Finding]:
try:
return self._analyze(module)
except Exception:
return []
def _analyze(self, module: KernelModule) -> list[Finding]:
raise NotImplementedError
def get_call_graph(self, module: KernelModule):
if not hasattr(module, "_call_graph"):
from cfg import CallGraph
module._call_graph = CallGraph(module)
return module._call_graph
class MetadataRule(Rule):
name = "metadata"
description = "Checks module metadata for structural and naming anomalies."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
if "author" not in module.modinfo:
findings.append(Finding(
rule=self.name,
severity=Severity.INFO,
title="Missing module author."
))
if "description" not in module.modinfo:
findings.append(Finding(
rule=self.name,
severity=Severity.INFO,
title="Missing module description."
))
base_name = os.path.splitext(os.path.basename(module.path))[0]
if "name" in module.modinfo and module.modinfo["name"] != base_name:
findings.append(Finding(
rule=self.name,
severity=Severity.SUSPICIOUS,
title="Module name differs from filename.",
details={
"Internal": module.modinfo["name"],
"File": f"{base_name}.ko"
}
))
return findings
class SyscallHookRule(Rule):
name = "syscall_hook"
description = "Checks for syscall table imports and write protection overrides."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
if "sys_call_table" in module.imported_symbols:
findings.append(Finding(
rule=self.name,
severity=Severity.CRITICAL,
title="Direct sys_call_table import",
details={"Symbol": "sys_call_table"},
reason="Bypasses symbol lookup protections to read/write system calls."
))
if module.arch == "arm64":
for func in module.functions:
for ins in func["disasm"]:
combined_instr = f"{ins['mnemonic']} {ins['op_str']}".lower()
if "sctlr_el1" in combined_instr:
findings.append(Finding(
rule=self.name,
severity=Severity.CRITICAL,
title="Write protection bypass detected",
details={
"Function": func["name"],
"Offset": hex(ins["addr"]),
"Instruction": combined_instr
},
reason="Disables write protection to modify write-protected page mappings."
))
if module.arch == "x86_64":
for func in module.functions:
for ins in func["disasm"]:
if ins["mnemonic"].lower().startswith("mov") and "cr0" in ins["op_str"].lower():
findings.append(Finding(
rule=self.name,
severity=Severity.CRITICAL,
title="Write protection bypass detected",
details={
"Function": func["name"],
"Offset": hex(ins["addr"]),
"Instruction": f"{ins['mnemonic']} {ins['op_str']}"
},
reason="Disables write protection to modify write-protected page mappings."
))
# Dynamic sys_call_table query
rodata_sec = module.elf.get_section_by_name('.rodata')
if rodata_sec and "kallsyms_lookup_name" in module.imported_symbols:
data = rodata_sec.data()
if b"sys_call_table" in data:
findings.append(Finding(
rule=self.name,
severity=Severity.CRITICAL,
title="Dynamic sys_call_table resolution",
details={
"Imports": "kallsyms_lookup_name",
"Target": "sys_call_table"
},
reason="Dynamically queries the system call table pointer."
))
return findings
class HookFrameworkRule(Rule):
name = "hook_framework"
description = "Checks for dynamic function hooking framework usages."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
hook_apis = [
"register_ftrace_function", "register_kprobe",
"register_kretprobe", "register_kprobes",
"register_jprobe", "kprobe_lookup_name"
]
for api in hook_apis:
if api in module.imported_symbols:
findings.append(Finding(
rule=self.name,
severity=Severity.HIGH,
title="Dynamic function tracing hook detected",
details={"Function": api},
reason="Registers callback functions to intercept or trace execution of kernel routines."
))
return findings
class SelfHidingRule(Rule):
name = "self_hiding"
description = "Checks for module self-hiding behaviors."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
cg = self.get_call_graph(module)
for api in ["list_del", "kobject_del"]:
if cg.reachable_from_init(api):
findings.append(Finding(
rule=self.name,
severity=Severity.CRITICAL,
title="Self-hiding behavior in initialization",
details={"Function": f"{api} in init path"},
reason="Attempts to unlink itself from modules or sysfs list structures."
))
return findings
class ProcHidingRule(Rule):
name = "proc_hiding"
description = "Checks for directory list filtering and file system iteration overrides."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
cg = self.get_call_graph(module)
# Identify custom directory iteration/fill callbacks
iter_funcs = []
for func in module.functions:
fname = func["name"].lower()
if "iterate" in fname or "filldir" in fname:
iter_funcs.append(func["name"])
for fn in iter_funcs:
# Check if iterate function performs string comparisons to filter outputs
for cmp_api in ["strcmp", "strncmp", "memcmp"]:
if cg.chain_exists(fn, cmp_api):
findings.append(Finding(
rule=self.name,
severity=Severity.HIGH,
title="Directory iteration filtering detected",
details={"Function": fn, "Filter": cmp_api},
reason="Filters directory entry listings to hide specific filenames or process directories."
))
break # Avoid duplicate warnings per function
return findings
class CredAbuseRule(Rule):
name = "cred_abuse"
description = "Checks for privilege escalation and credentials updates."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
cg = self.get_call_graph(module)
# Check standard credentials modification APIs
cred_apis = ["prepare_creds", "commit_creds", "prepare_kernel_cred", "override_creds", "revert_creds"]
found_apis = [api for api in cred_apis if api in module.imported_symbols]
if found_apis:
findings.append(Finding(
rule=self.name,
severity=Severity.HIGH,
title="Credentials manipulation APIs imported",
details={"Symbols": ", ".join(sorted(found_apis))},
reason="Prepares or commits credentials blocks to change running process capabilities."
))
# Trace CallGraph from user-land interface targets to credential committer
user_gateways = ["ioctl", "write", "read"]
commit_targets = ["commit_creds", "override_creds"]
for gate in user_gateways:
gate_nodes = [node for node in cg.graph if gate in node.lower()]
for gate_node in gate_nodes:
for commit in commit_targets:
if cg.chain_exists(gate_node, commit):
findings.append(Finding(
rule=self.name,
severity=Severity.CRITICAL,
title="Privilege escalation control flow",
details={"Path": f"{gate_node} -> {commit}"},
reason="Exposes process privilege escalation capability to userland interfaces."
))
return findings
class BackdoorInterfaceRule(Rule):
name = "backdoor_interface"
description = "Checks for creation of backdoor interfaces."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
backdoor_apis = ["proc_create", "debugfs_create_file", "debugfs_create_dir"]
found_apis = [api for api in backdoor_apis if api in module.imported_symbols]
if found_apis:
findings.append(Finding(
rule=self.name,
severity=Severity.SUSPICIOUS,
title="User-space control gateway",
details={"Symbols": ", ".join(sorted(found_apis))},
reason="Registers file entries enabling userland configuration/control signals."
))
return findings
class NetfilterHookRule(Rule):
name = "netfilter_hook"
description = "Checks for Netfilter hooks that intercept packets."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
netfilter_apis = [
"nf_register_net_hook", "nf_register_net_hooks",
"nf_register_hook", "nf_register_hooks"
]
for api in netfilter_apis:
if api in module.imported_symbols:
findings.append(Finding(
rule=self.name,
severity=Severity.HIGH,
title="Network packet interceptor hook",
details={"Import": api},
reason="Registers callbacks to intercept, drop, or modify network packets."
))
return findings
class SuspiciousCallbackRule(Rule):
name = "suspicious_callbacks"
description = "Checks for notifier callback registrations monitor system state changes."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
apis = [
"register_reboot_notifier", "register_keyboard_notifier",
"register_netdevice_notifier", "register_module_notifier"
]
for api in apis:
if api in module.imported_symbols:
findings.append(Finding(
rule=self.name,
severity=Severity.SUSPICIOUS,
title="Suspicious callback notifier registered",
details={"Callback": api},
reason="Registers notification hooks to trigger module code on system events."
))
return findings
class StringIntelRule(Rule):
name = "string_intel"
description = "Scans read-only sections for sensitive configuration paths."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
suspicious_strings = [
(b"/bin/sh", "Execution of shell commands"),
(b"/etc/passwd", "Accessing password files"),
(b"/etc/shadow", "Accessing shadow password files"),
]
rodata_sec = module.elf.get_section_by_name('.rodata')
if rodata_sec:
data = rodata_sec.data()
for pattern, desc in suspicious_strings:
if pattern in data:
findings.append(Finding(
rule=self.name,
severity=Severity.HIGH,
title="Embedded sensitive file path reference",
details={"Path": pattern.decode('utf-8', errors='ignore')},
reason="References restricted system directories or configuration targets."
))
return findings
class EntropyRule(Rule):
name = "entropy"
description = "Checks for entropy obfuscation markers."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
for sec_name in module.sections:
sec = module.elf.get_section_by_name(sec_name)
if not sec:
continue
data = sec.data()
if not data:
continue
import math
entropy = 0.0
for x in range(256):
p_x = data.count(x) / len(data)
if p_x > 0:
entropy += - p_x * math.log2(p_x)
if entropy > 7.2:
findings.append(Finding(
rule=self.name,
severity=Severity.SUSPICIOUS,
title="High entropy section detected",
details={
"Section": sec_name,
"Entropy": f"{entropy:.2f}"
},
reason="Indicates section contains packed or compressed data payloads."
))
return findings
class IoctlAnalysisRule(Rule):
name = "ioctl_analysis"
description = "Scans for custom IOCTL unlocked/compat registration and handlers."
def _analyze(self, module: KernelModule) -> list[Finding]:
findings = []
ioctl_funcs = []
for func in module.functions:
fname = func["name"].lower()
if "ioctl" in fname and not fname.startswith("__pfx_"):
ioctl_funcs.append(func["name"])
for fn in ioctl_funcs:
findings.append(Finding(
rule=self.name,
severity=Severity.HIGH,
title="Custom IOCTL interface detected",
details={"Function": fn},
reason="User-space control interface."
))
return findings
ALL_RULES: list[Rule] = [
MetadataRule(),
SyscallHookRule(),
HookFrameworkRule(),
SelfHidingRule(),
ProcHidingRule(),
CredAbuseRule(),
BackdoorInterfaceRule(),
NetfilterHookRule(),
SuspiciousCallbackRule(),
StringIntelRule(),
EntropyRule(),
IoctlAnalysisRule(),
]
RULE_MAP: dict[str, Rule] = {r.name: r for r in ALL_RULES}