entropystrip 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- entropystrip/__init__.py +23 -0
- entropystrip/__main__.py +5 -0
- entropystrip/core.py +941 -0
- entropystrip-1.0.0.dist-info/METADATA +147 -0
- entropystrip-1.0.0.dist-info/RECORD +9 -0
- entropystrip-1.0.0.dist-info/WHEEL +5 -0
- entropystrip-1.0.0.dist-info/entry_points.txt +2 -0
- entropystrip-1.0.0.dist-info/licenses/LICENSE +21 -0
- entropystrip-1.0.0.dist-info/top_level.txt +1 -0
entropystrip/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""
|
|
2
|
+
EntropyStrip: Algorithmic PE De-obfuscator, Shannon Entropy Radar, and Incident Triage Engine.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
__version__ = "1.0.0"
|
|
6
|
+
__author__ = "dwexi"
|
|
7
|
+
|
|
8
|
+
from .core import (
|
|
9
|
+
calculate_entropy,
|
|
10
|
+
calculate_dilution_metrics,
|
|
11
|
+
analyze_single_file,
|
|
12
|
+
scan_directory,
|
|
13
|
+
main,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"calculate_entropy",
|
|
18
|
+
"calculate_dilution_metrics",
|
|
19
|
+
"analyze_single_file",
|
|
20
|
+
"scan_directory",
|
|
21
|
+
"main",
|
|
22
|
+
"__version__",
|
|
23
|
+
]
|
entropystrip/__main__.py
ADDED
entropystrip/core.py
ADDED
|
@@ -0,0 +1,941 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import math
|
|
3
|
+
import os
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import hashlib
|
|
8
|
+
import pefile
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
sys.stdout.reconfigure(encoding='utf-8')
|
|
12
|
+
except Exception:
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
import capstone
|
|
17
|
+
HAS_CAPSTONE = True
|
|
18
|
+
except ImportError:
|
|
19
|
+
HAS_CAPSTONE = False
|
|
20
|
+
|
|
21
|
+
from rich.console import Console
|
|
22
|
+
from rich.table import Table
|
|
23
|
+
from rich.panel import Panel
|
|
24
|
+
|
|
25
|
+
console = Console()
|
|
26
|
+
|
|
27
|
+
BANNER = r"""
|
|
28
|
+
___________ __ _________ __ .__
|
|
29
|
+
\_ _____/ _____/ |________ ____ ______ ___.__./ _____// |________|__|_____
|
|
30
|
+
| __)_ / \ __\_ __ \/ _ \\____ < | |\_____ \\ __\_ __ \ \____ \
|
|
31
|
+
| \ | \ | | | \( <_> ) |_> >___ |/ \| | | | \/ | |_> >
|
|
32
|
+
/_______ /___| /__| |__| \____/| __// ____/_______ /|__| |__| |__| __/
|
|
33
|
+
\/ \/ |__| \/ \/ |__|
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
SUSPICIOUS_APIS = {
|
|
37
|
+
"VirtualAlloc", "VirtualProtect", "WriteProcessMemory",
|
|
38
|
+
"CreateRemoteThread", "LoadLibraryA", "LoadLibraryW",
|
|
39
|
+
"GetProcAddress", "IsDebuggerPresent", "CreateProcessW",
|
|
40
|
+
"NtUnmapViewOfSection", "QueueUserAPC", "SetWindowsHookExA",
|
|
41
|
+
"CheckRemoteDebuggerPresent", "OutputDebugStringA", "FindWindowA"
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
ANTI_DEBUG_APIS = {
|
|
45
|
+
"IsDebuggerPresent", "CheckRemoteDebuggerPresent",
|
|
46
|
+
"OutputDebugStringA", "NtQueryInformationProcess", "FindWindowA"
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
KNOWN_PACKER_SECTIONS = {"upx0", "upx1", "upx2", ".aspack", ".mpress", "pecrypt", ".themida", ".vmp"}
|
|
50
|
+
|
|
51
|
+
URL_REGEX = re.compile(rb'https?://[a-zA-Z0-9_\-\./:]+')
|
|
52
|
+
IP_REGEX = re.compile(rb'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b')
|
|
53
|
+
|
|
54
|
+
def calculate_entropy(data):
|
|
55
|
+
if not data:
|
|
56
|
+
return 0.0
|
|
57
|
+
entropy = 0.0
|
|
58
|
+
length = len(data)
|
|
59
|
+
byte_counts = [0] * 256
|
|
60
|
+
for byte in data:
|
|
61
|
+
byte_counts[byte] += 1
|
|
62
|
+
for count in byte_counts:
|
|
63
|
+
if count > 0:
|
|
64
|
+
prob = count / length
|
|
65
|
+
entropy -= prob * math.log2(prob)
|
|
66
|
+
return entropy
|
|
67
|
+
|
|
68
|
+
def calculate_dilution_metrics(data):
|
|
69
|
+
"""Detects entropy dilution attacks where high-entropy payloads are padded with null bytes."""
|
|
70
|
+
if not data or len(data) < 1024:
|
|
71
|
+
return 0.0, 0.0, False
|
|
72
|
+
|
|
73
|
+
zero_count = data.count(0)
|
|
74
|
+
zero_ratio = zero_count / len(data)
|
|
75
|
+
|
|
76
|
+
# If zeros make up more than 35% of the data, calculate entropy of non-zero bytes
|
|
77
|
+
if zero_ratio >= 0.35:
|
|
78
|
+
non_zeros = bytes([b for b in data if b != 0])
|
|
79
|
+
if len(non_zeros) >= 256:
|
|
80
|
+
non_zero_ent = calculate_entropy(non_zeros)
|
|
81
|
+
# If the non-zero bytes alone have cryptographic entropy, it's a dilution evasion!
|
|
82
|
+
if non_zero_ent > 7.3:
|
|
83
|
+
return non_zero_ent, zero_ratio, True
|
|
84
|
+
|
|
85
|
+
return 0.0, zero_ratio, False
|
|
86
|
+
|
|
87
|
+
def get_entropy_heatmap_string(data, width=30):
|
|
88
|
+
if not data or len(data) == 0:
|
|
89
|
+
return "[dim]No Data (Unmapped)[/dim]"
|
|
90
|
+
|
|
91
|
+
chunk_size = max(1, len(data) // width)
|
|
92
|
+
heatmap = ""
|
|
93
|
+
for i in range(width):
|
|
94
|
+
start = i * chunk_size
|
|
95
|
+
end = len(data) if i == width - 1 else start + chunk_size
|
|
96
|
+
chunk = data[start:end]
|
|
97
|
+
if not chunk:
|
|
98
|
+
continue
|
|
99
|
+
ent = calculate_entropy(chunk)
|
|
100
|
+
if ent > 7.4:
|
|
101
|
+
color = "red"
|
|
102
|
+
elif ent > 6.6:
|
|
103
|
+
color = "yellow"
|
|
104
|
+
elif ent > 5.0:
|
|
105
|
+
color = "green"
|
|
106
|
+
elif ent > 1.0:
|
|
107
|
+
color = "blue"
|
|
108
|
+
else:
|
|
109
|
+
color = "bright_black"
|
|
110
|
+
heatmap += f"[{color}]█[/{color}]"
|
|
111
|
+
return heatmap
|
|
112
|
+
|
|
113
|
+
def compute_hashes(data):
|
|
114
|
+
return {
|
|
115
|
+
"md5": hashlib.md5(data).hexdigest(),
|
|
116
|
+
"sha256": hashlib.sha256(data).hexdigest()
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
def inspect_imports(pe):
|
|
120
|
+
total_imports = 0
|
|
121
|
+
flagged_apis = []
|
|
122
|
+
if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):
|
|
123
|
+
for entry in pe.DIRECTORY_ENTRY_IMPORT:
|
|
124
|
+
# Guard against malformed thunks where entry.imports is None
|
|
125
|
+
if not getattr(entry, 'imports', None):
|
|
126
|
+
continue
|
|
127
|
+
for imp in entry.imports:
|
|
128
|
+
total_imports += 1
|
|
129
|
+
if imp.name:
|
|
130
|
+
name = imp.name.decode('utf-8', errors='ignore')
|
|
131
|
+
if name in SUSPICIOUS_APIS:
|
|
132
|
+
flagged_apis.append(name)
|
|
133
|
+
return total_imports, list(set(flagged_apis))
|
|
134
|
+
|
|
135
|
+
def is_dotnet_assembly(pe):
|
|
136
|
+
try:
|
|
137
|
+
com_desc = pe.OPTIONAL_HEADER.DATA_DIRECTORY[14]
|
|
138
|
+
return com_desc.VirtualAddress != 0 and com_desc.Size != 0
|
|
139
|
+
except Exception:
|
|
140
|
+
return False
|
|
141
|
+
|
|
142
|
+
def check_authenticode_signature(pe):
|
|
143
|
+
try:
|
|
144
|
+
sec_dir = pe.OPTIONAL_HEADER.DATA_DIRECTORY[4]
|
|
145
|
+
return sec_dir.VirtualAddress != 0 and sec_dir.Size != 0
|
|
146
|
+
except Exception:
|
|
147
|
+
return False
|
|
148
|
+
|
|
149
|
+
def check_rich_header(pe):
|
|
150
|
+
"""Detects compiler toolchain anomalies in the MSVC Rich Header."""
|
|
151
|
+
try:
|
|
152
|
+
if hasattr(pe, 'RICH_HEADER') and pe.RICH_HEADER:
|
|
153
|
+
# Validate checksum if raw cleartext is present
|
|
154
|
+
if hasattr(pe.RICH_HEADER, 'checksum'):
|
|
155
|
+
return True, hex(pe.RICH_HEADER.checksum)
|
|
156
|
+
except Exception:
|
|
157
|
+
pass
|
|
158
|
+
return False, None
|
|
159
|
+
|
|
160
|
+
def detect_overlay(pe, file_size, file_data):
|
|
161
|
+
max_offset = 0
|
|
162
|
+
for section in pe.sections:
|
|
163
|
+
end = section.PointerToRawData + section.SizeOfRawData
|
|
164
|
+
if end > max_offset:
|
|
165
|
+
max_offset = end
|
|
166
|
+
|
|
167
|
+
if file_size > max_offset:
|
|
168
|
+
overlay_bytes = file_data[max_offset:]
|
|
169
|
+
return max_offset, overlay_bytes
|
|
170
|
+
return 0, b""
|
|
171
|
+
|
|
172
|
+
def harvest_indicators(data, max_scan_len=65536):
|
|
173
|
+
"""Exhaustively scans for plain and all 256 single-byte XORed URLs and IP indicators."""
|
|
174
|
+
indicators = []
|
|
175
|
+
chunk = data[:max_scan_len]
|
|
176
|
+
|
|
177
|
+
# 1. Plain text search
|
|
178
|
+
urls = URL_REGEX.findall(chunk)
|
|
179
|
+
for u in urls[:5]:
|
|
180
|
+
indicators.append(f"URL: {u.decode('utf-8', errors='ignore')}")
|
|
181
|
+
|
|
182
|
+
ips = IP_REGEX.findall(chunk)
|
|
183
|
+
for ip in ips[:5]:
|
|
184
|
+
indicators.append(f"IP: {ip.decode('utf-8', errors='ignore')}")
|
|
185
|
+
|
|
186
|
+
# 2. Exhaustive 256 single-byte XOR key hunt on high entropy blocks
|
|
187
|
+
if not indicators:
|
|
188
|
+
scan_buf = chunk[:4096]
|
|
189
|
+
for key in range(1, 256):
|
|
190
|
+
xored = bytes([b ^ key for b in scan_buf])
|
|
191
|
+
found = URL_REGEX.findall(xored)
|
|
192
|
+
for u in found[:2]:
|
|
193
|
+
indicators.append(f"XOR [0x{key:02X}] URL: {u.decode('utf-8', errors='ignore')}")
|
|
194
|
+
if len(indicators) >= 5:
|
|
195
|
+
break
|
|
196
|
+
|
|
197
|
+
return list(set(indicators))
|
|
198
|
+
|
|
199
|
+
def disassemble_entry_point(pe, file_data):
|
|
200
|
+
"""Disassembles initial instructions at the Entry Point or dumps raw hex if capstone is absent."""
|
|
201
|
+
try:
|
|
202
|
+
ep_rva = pe.OPTIONAL_HEADER.AddressOfEntryPoint
|
|
203
|
+
if ep_rva == 0:
|
|
204
|
+
return "[dim]No execution entry point (DLL resource/pure data)[/dim]"
|
|
205
|
+
|
|
206
|
+
ep_offset = pe.get_offset_from_rva(ep_rva)
|
|
207
|
+
if ep_offset is None or ep_offset >= len(file_data):
|
|
208
|
+
return f"[red]Entry point points outside file (RVA: {hex(ep_rva)} - Header anomaly)[/red]"
|
|
209
|
+
|
|
210
|
+
code_bytes = file_data[ep_offset:ep_offset + 32]
|
|
211
|
+
if not code_bytes:
|
|
212
|
+
return "[dim]Empty bytes at entry point[/dim]"
|
|
213
|
+
|
|
214
|
+
if HAS_CAPSTONE:
|
|
215
|
+
is_64 = pe.FILE_HEADER.Machine == pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']
|
|
216
|
+
mode = capstone.CS_MODE_64 if is_64 else capstone.CS_MODE_32
|
|
217
|
+
cs = capstone.Cs(capstone.CS_ARCH_X86, mode)
|
|
218
|
+
|
|
219
|
+
lines = []
|
|
220
|
+
for ins in cs.disasm(code_bytes, ep_rva):
|
|
221
|
+
lines.append(f"{hex(ins.address):<10} {ins.mnemonic:<7} {ins.op_str}")
|
|
222
|
+
if len(lines) >= 8:
|
|
223
|
+
break
|
|
224
|
+
return "\n".join(lines) if lines else code_bytes.hex(' ')
|
|
225
|
+
else:
|
|
226
|
+
hex_str = " ".join([f"{b:02x}" for b in code_bytes[:24]])
|
|
227
|
+
return f"{hex(ep_rva)}: {hex_str} [dim](install 'capstone' for asm disassembly)[/dim]"
|
|
228
|
+
except Exception as e:
|
|
229
|
+
return f"[dim]Disassembly unavailable: {e}[/dim]"
|
|
230
|
+
|
|
231
|
+
def map_mitre_techniques(anomalies, flagged_apis, has_wx, high_entropy, has_overlay, is_diluted):
|
|
232
|
+
"""Maps structural and behavioral findings to MITRE ATT&CK technique IDs."""
|
|
233
|
+
mitre_hits = []
|
|
234
|
+
if high_entropy or is_diluted:
|
|
235
|
+
mitre_hits.append(("T1027", "Obfuscated Files or Information", "Cryptographic entropy or null-byte dilution in payload"))
|
|
236
|
+
if has_overlay:
|
|
237
|
+
mitre_hits.append(("T1027.001", "Binary Padding / Steganography", "Unmapped trailing overlay appended to file"))
|
|
238
|
+
if has_wx:
|
|
239
|
+
mitre_hits.append(("T1055", "Process Injection (Memory)", "Self-modifying W+X memory permissions"))
|
|
240
|
+
|
|
241
|
+
inject_apis = {"VirtualAlloc", "WriteProcessMemory", "CreateRemoteThread", "QueueUserAPC"}
|
|
242
|
+
if inject_apis.intersection(set(flagged_apis)):
|
|
243
|
+
mitre_hits.append(("T1055.002", "Portable Executable Injection", f"Injection primitives: {', '.join(inject_apis.intersection(set(flagged_apis)))}"))
|
|
244
|
+
|
|
245
|
+
anti_debug = ANTI_DEBUG_APIS.intersection(set(flagged_apis))
|
|
246
|
+
if anti_debug:
|
|
247
|
+
mitre_hits.append(("T1497", "Virtualization/Sandbox Evasion", f"Anti-analysis APIs: {', '.join(anti_debug)}"))
|
|
248
|
+
|
|
249
|
+
for a in anomalies:
|
|
250
|
+
if "small import table" in a.lower():
|
|
251
|
+
mitre_hits.append(("T1129", "Shared Modules (Dynamic Resolution)", "Sparse IAT indicative of runtime dynamic API resolution"))
|
|
252
|
+
break
|
|
253
|
+
|
|
254
|
+
return mitre_hits
|
|
255
|
+
|
|
256
|
+
def generate_minimal_html_report(telemetry, output_path):
|
|
257
|
+
out_dir = os.path.dirname(os.path.abspath(output_path))
|
|
258
|
+
if out_dir:
|
|
259
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
260
|
+
|
|
261
|
+
status_color = "#e06c75" if telemetry["threat_score"] >= 70 else ("#e5c07b" if telemetry["threat_score"] >= 35 else "#98c379")
|
|
262
|
+
|
|
263
|
+
sha256_val = telemetry.get("hashes", {}).get("sha256", "-")
|
|
264
|
+
imphash_val = telemetry.get("imphash") or "-"
|
|
265
|
+
|
|
266
|
+
sections_html = ""
|
|
267
|
+
for s in telemetry["sections"]:
|
|
268
|
+
heatmap_blocks = ""
|
|
269
|
+
for char in s["raw_heatmap"]:
|
|
270
|
+
c = "#e06c75" if char == "R" else ("#e5c07b" if char == "Y" else ("#98c379" if char == "G" else ("#61afef" if char == "B" else "#3e4451")))
|
|
271
|
+
heatmap_blocks += f'<span style="color:{c};">■</span>'
|
|
272
|
+
|
|
273
|
+
sections_html += f"""
|
|
274
|
+
<tr>
|
|
275
|
+
<td style="font-family:ui-monospace,monospace; font-weight:600;">{s['name']}</td>
|
|
276
|
+
<td style="font-family:ui-monospace,monospace; text-align:right;">{s['virt_size']}</td>
|
|
277
|
+
<td style="font-family:ui-monospace,monospace; text-align:right;">{s['raw_size']}</td>
|
|
278
|
+
<td style="font-family:ui-monospace,monospace; text-align:right; font-weight:600;">{s['entropy']:.2f}</td>
|
|
279
|
+
<td style="text-align:center;"><span class="badge">{s['perms']}</span></td>
|
|
280
|
+
<td style="letter-spacing:1px;">{heatmap_blocks}</td>
|
|
281
|
+
<td style="text-align:center; font-family:ui-monospace,monospace; font-size:11px;">{s['status']}</td>
|
|
282
|
+
</tr>
|
|
283
|
+
"""
|
|
284
|
+
|
|
285
|
+
anomalies_html = "".join([f"<li>{a}</li>" for a in telemetry["anomalies"]]) if telemetry["anomalies"] else "<li>No anomalies detected.</li>"
|
|
286
|
+
indicators_html = "".join([f"<li>{i}</li>" for i in telemetry["indicators"]]) if telemetry["indicators"] else "<li>No network indicators extracted.</li>"
|
|
287
|
+
|
|
288
|
+
mitre_html = ""
|
|
289
|
+
if telemetry.get("mitre"):
|
|
290
|
+
for tid, tname, tdesc in telemetry["mitre"]:
|
|
291
|
+
mitre_html += f"<tr><td style='font-family:monospace; font-weight:600;'>{tid}</td><td style='font-weight:600;'>{tname}</td><td>{tdesc}</td></tr>"
|
|
292
|
+
|
|
293
|
+
html = f"""<!DOCTYPE html>
|
|
294
|
+
<html lang="en">
|
|
295
|
+
<head>
|
|
296
|
+
<meta charset="UTF-8">
|
|
297
|
+
<title>entropystrip - {telemetry['filename']}</title>
|
|
298
|
+
<style>
|
|
299
|
+
body {{
|
|
300
|
+
background: #0f141c;
|
|
301
|
+
color: #abb2bf;
|
|
302
|
+
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
|
303
|
+
margin: 0;
|
|
304
|
+
padding: 32px 20px;
|
|
305
|
+
line-height: 1.45;
|
|
306
|
+
font-size: 13px;
|
|
307
|
+
}}
|
|
308
|
+
.container {{
|
|
309
|
+
max-width: 900px;
|
|
310
|
+
margin: 0 auto;
|
|
311
|
+
}}
|
|
312
|
+
.header {{
|
|
313
|
+
border-bottom: 1px solid #282c34;
|
|
314
|
+
padding-bottom: 16px;
|
|
315
|
+
margin-bottom: 20px;
|
|
316
|
+
display: flex;
|
|
317
|
+
justify-content: space-between;
|
|
318
|
+
align-items: baseline;
|
|
319
|
+
}}
|
|
320
|
+
h1 {{
|
|
321
|
+
font-size: 16px;
|
|
322
|
+
margin: 0;
|
|
323
|
+
color: #e6edf3;
|
|
324
|
+
font-weight: 600;
|
|
325
|
+
letter-spacing: 0.5px;
|
|
326
|
+
}}
|
|
327
|
+
.target-path {{
|
|
328
|
+
color: #5c6370;
|
|
329
|
+
font-size: 12px;
|
|
330
|
+
margin-top: 4px;
|
|
331
|
+
word-break: break-all;
|
|
332
|
+
}}
|
|
333
|
+
.card {{
|
|
334
|
+
border: 1px solid #282c34;
|
|
335
|
+
background: #161b22;
|
|
336
|
+
padding: 16px;
|
|
337
|
+
margin-bottom: 16px;
|
|
338
|
+
}}
|
|
339
|
+
.score-card {{
|
|
340
|
+
border-left: 3px solid {status_color};
|
|
341
|
+
}}
|
|
342
|
+
.score-val {{
|
|
343
|
+
font-size: 20px;
|
|
344
|
+
font-weight: 700;
|
|
345
|
+
color: {status_color};
|
|
346
|
+
}}
|
|
347
|
+
.verdict {{
|
|
348
|
+
color: #e6edf3;
|
|
349
|
+
font-weight: 600;
|
|
350
|
+
margin: 4px 0 12px 0;
|
|
351
|
+
}}
|
|
352
|
+
.grid {{
|
|
353
|
+
display: grid;
|
|
354
|
+
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
|
355
|
+
gap: 12px;
|
|
356
|
+
margin-bottom: 16px;
|
|
357
|
+
}}
|
|
358
|
+
.cell {{
|
|
359
|
+
background: #161b22;
|
|
360
|
+
border: 1px solid #282c34;
|
|
361
|
+
padding: 10px 14px;
|
|
362
|
+
}}
|
|
363
|
+
.label {{
|
|
364
|
+
font-size: 11px;
|
|
365
|
+
color: #5c6370;
|
|
366
|
+
text-transform: uppercase;
|
|
367
|
+
}}
|
|
368
|
+
.val {{
|
|
369
|
+
color: #e6edf3;
|
|
370
|
+
font-weight: 600;
|
|
371
|
+
margin-top: 2px;
|
|
372
|
+
font-size: 12px;
|
|
373
|
+
word-break: break-all;
|
|
374
|
+
}}
|
|
375
|
+
table {{
|
|
376
|
+
width: 100%;
|
|
377
|
+
border-collapse: collapse;
|
|
378
|
+
background: #161b22;
|
|
379
|
+
border: 1px solid #282c34;
|
|
380
|
+
margin-bottom: 16px;
|
|
381
|
+
}}
|
|
382
|
+
th, td {{
|
|
383
|
+
padding: 8px 12px;
|
|
384
|
+
text-align: left;
|
|
385
|
+
border-bottom: 1px solid #282c34;
|
|
386
|
+
font-size: 12px;
|
|
387
|
+
}}
|
|
388
|
+
th {{
|
|
389
|
+
background: #1b2028;
|
|
390
|
+
color: #5c6370;
|
|
391
|
+
font-weight: 600;
|
|
392
|
+
text-transform: uppercase;
|
|
393
|
+
font-size: 11px;
|
|
394
|
+
}}
|
|
395
|
+
.badge {{
|
|
396
|
+
font-size: 11px;
|
|
397
|
+
padding: 1px 5px;
|
|
398
|
+
background: #21262d;
|
|
399
|
+
border: 1px solid #30363d;
|
|
400
|
+
color: #c9d1d9;
|
|
401
|
+
}}
|
|
402
|
+
ul {{
|
|
403
|
+
margin: 0;
|
|
404
|
+
padding-left: 18px;
|
|
405
|
+
}}
|
|
406
|
+
li {{
|
|
407
|
+
margin-bottom: 4px;
|
|
408
|
+
}}
|
|
409
|
+
pre {{
|
|
410
|
+
background: #10141b;
|
|
411
|
+
padding: 12px;
|
|
412
|
+
border: 1px solid #282c34;
|
|
413
|
+
overflow-x: auto;
|
|
414
|
+
font-size: 12px;
|
|
415
|
+
color: #98c379;
|
|
416
|
+
margin: 0;
|
|
417
|
+
}}
|
|
418
|
+
</style>
|
|
419
|
+
</head>
|
|
420
|
+
<body>
|
|
421
|
+
<div class="container">
|
|
422
|
+
<div class="header">
|
|
423
|
+
<div>
|
|
424
|
+
<h1>entropystrip report</h1>
|
|
425
|
+
<div class="target-path">{telemetry['path']}</div>
|
|
426
|
+
</div>
|
|
427
|
+
<div style="font-size:11px; color:#5c6370;">PE triage</div>
|
|
428
|
+
</div>
|
|
429
|
+
|
|
430
|
+
<div class="card score-card">
|
|
431
|
+
<div class="score-val">{telemetry['threat_score']} / 100</div>
|
|
432
|
+
<div class="verdict">{telemetry['verdict']}</div>
|
|
433
|
+
<ul>{anomalies_html}</ul>
|
|
434
|
+
</div>
|
|
435
|
+
|
|
436
|
+
<div class="grid">
|
|
437
|
+
<div class="cell">
|
|
438
|
+
<div class="label">SHA256</div>
|
|
439
|
+
<div class="val" style="font-size:11px;">{sha256_val}</div>
|
|
440
|
+
</div>
|
|
441
|
+
<div class="cell">
|
|
442
|
+
<div class="label">Imphash</div>
|
|
443
|
+
<div class="val" style="font-size:11px;">{imphash_val}</div>
|
|
444
|
+
</div>
|
|
445
|
+
<div class="cell">
|
|
446
|
+
<div class="label">Format</div>
|
|
447
|
+
<div class="val">{'Managed (.NET)' if telemetry['is_dotnet'] else 'Native PE'}</div>
|
|
448
|
+
</div>
|
|
449
|
+
<div class="cell">
|
|
450
|
+
<div class="label">Overlay</div>
|
|
451
|
+
<div class="val">{str(telemetry['overlay_size']) + ' bytes' if telemetry['has_overlay'] else 'None'}</div>
|
|
452
|
+
</div>
|
|
453
|
+
</div>
|
|
454
|
+
|
|
455
|
+
<table>
|
|
456
|
+
<thead>
|
|
457
|
+
<tr>
|
|
458
|
+
<th>Section</th>
|
|
459
|
+
<th style="text-align:right;">Virt Size</th>
|
|
460
|
+
<th style="text-align:right;">Raw Size</th>
|
|
461
|
+
<th style="text-align:right;">Entropy</th>
|
|
462
|
+
<th style="text-align:center;">Perms</th>
|
|
463
|
+
<th>Entropy Strip</th>
|
|
464
|
+
<th style="text-align:center;">Status</th>
|
|
465
|
+
</tr>
|
|
466
|
+
</thead>
|
|
467
|
+
<tbody>
|
|
468
|
+
{sections_html}
|
|
469
|
+
</tbody>
|
|
470
|
+
</table>
|
|
471
|
+
|
|
472
|
+
{f'''
|
|
473
|
+
<div class="card">
|
|
474
|
+
<div class="label" style="margin-bottom:8px;">MITRE ATT&CK Classification</div>
|
|
475
|
+
<table>
|
|
476
|
+
<thead><tr><th>Technique</th><th>Name</th><th>Context</th></tr></thead>
|
|
477
|
+
<tbody>{mitre_html}</tbody>
|
|
478
|
+
</table>
|
|
479
|
+
</div>
|
|
480
|
+
''' if mitre_html else ''}
|
|
481
|
+
|
|
482
|
+
{f'''
|
|
483
|
+
<div class="card">
|
|
484
|
+
<div class="label" style="margin-bottom:8px;">Entry Point Disassembly Stub</div>
|
|
485
|
+
<pre>{telemetry.get("ep_disasm", "")}</pre>
|
|
486
|
+
</div>
|
|
487
|
+
''' if telemetry.get("ep_disasm") else ''}
|
|
488
|
+
|
|
489
|
+
<div class="card">
|
|
490
|
+
<div class="label" style="margin-bottom:8px;">Extracted Indicators</div>
|
|
491
|
+
<ul>{indicators_html}</ul>
|
|
492
|
+
</div>
|
|
493
|
+
</div>
|
|
494
|
+
</body>
|
|
495
|
+
</html>"""
|
|
496
|
+
|
|
497
|
+
with open(output_path, "w", encoding="utf-8") as f:
|
|
498
|
+
f.write(html)
|
|
499
|
+
|
|
500
|
+
def analyze_single_file(file_path, dump_payloads=False, quiet=False, html_out=None, json_out=None, deep=False):
|
|
501
|
+
file_path = os.path.abspath(os.path.normpath(file_path.strip().strip('"\'')))
|
|
502
|
+
|
|
503
|
+
if not os.path.exists(file_path):
|
|
504
|
+
if not quiet:
|
|
505
|
+
console.print(f"[red]Error: File not found -> {file_path}[/red]")
|
|
506
|
+
return None
|
|
507
|
+
|
|
508
|
+
try:
|
|
509
|
+
with open(file_path, "rb") as f:
|
|
510
|
+
file_data = f.read()
|
|
511
|
+
file_size = len(file_data)
|
|
512
|
+
|
|
513
|
+
# Check ELF magic bytes (\x7fELF)
|
|
514
|
+
if file_data[:4] == b"\x7fELF":
|
|
515
|
+
return analyze_elf(file_path, file_data, quiet=quiet)
|
|
516
|
+
|
|
517
|
+
pe = pefile.PE(data=file_data)
|
|
518
|
+
except Exception as e:
|
|
519
|
+
if not quiet:
|
|
520
|
+
console.print(f"[dim]Skipping (Invalid PE or locked): {os.path.basename(file_path)}[/dim]")
|
|
521
|
+
return None
|
|
522
|
+
|
|
523
|
+
hashes = compute_hashes(file_data)
|
|
524
|
+
try:
|
|
525
|
+
imphash_val = pe.get_imphash()
|
|
526
|
+
except Exception:
|
|
527
|
+
imphash_val = None
|
|
528
|
+
|
|
529
|
+
anomalies = []
|
|
530
|
+
threat_score = 0
|
|
531
|
+
high_entropy_sections = []
|
|
532
|
+
has_wx = False
|
|
533
|
+
is_diluted = False
|
|
534
|
+
sections_telemetry = []
|
|
535
|
+
|
|
536
|
+
if not quiet:
|
|
537
|
+
console.print(f"\n[bold]Target:[/bold] {file_path}")
|
|
538
|
+
if deep:
|
|
539
|
+
console.print(f"[dim]SHA256: {hashes['sha256']}[/dim]")
|
|
540
|
+
if imphash_val:
|
|
541
|
+
console.print(f"[dim]Imphash: {imphash_val}[/dim]")
|
|
542
|
+
|
|
543
|
+
table = Table(title="Section Architecture & Entropy", show_header=True, header_style="bold")
|
|
544
|
+
table.add_column("Section", style="cyan", justify="center")
|
|
545
|
+
table.add_column("Virt Size", style="dim", justify="right")
|
|
546
|
+
table.add_column("Raw Size", style="dim", justify="right")
|
|
547
|
+
table.add_column("Entropy", justify="right")
|
|
548
|
+
table.add_column("Perms", justify="center")
|
|
549
|
+
table.add_column("Entropy Strip", justify="left")
|
|
550
|
+
table.add_column("Status", justify="center")
|
|
551
|
+
|
|
552
|
+
for section in pe.sections:
|
|
553
|
+
try:
|
|
554
|
+
name = section.Name.decode('utf-8').rstrip('\x00').lower()
|
|
555
|
+
except UnicodeDecodeError:
|
|
556
|
+
name = str(section.Name)
|
|
557
|
+
|
|
558
|
+
raw_data = section.get_data()
|
|
559
|
+
entropy = calculate_entropy(raw_data)
|
|
560
|
+
|
|
561
|
+
# Check for null-byte dilution evasion in section
|
|
562
|
+
non_zero_ent, zero_ratio, is_dilution_hit = calculate_dilution_metrics(raw_data)
|
|
563
|
+
if is_dilution_hit:
|
|
564
|
+
is_diluted = True
|
|
565
|
+
anomalies.append(f"Section '{name}': Evasion detected! Null-byte dilution masking high-entropy payload (Real Entropy: {non_zero_ent:.2f}, Zero Ratio: {zero_ratio*100:.0f}%).")
|
|
566
|
+
threat_score += 40
|
|
567
|
+
high_entropy_sections.append((name, raw_data, non_zero_ent))
|
|
568
|
+
|
|
569
|
+
is_exec = bool(section.Characteristics & 0x20000000)
|
|
570
|
+
is_write = bool(section.Characteristics & 0x80000000)
|
|
571
|
+
perms = ""
|
|
572
|
+
perms_raw = "R"
|
|
573
|
+
if is_write and is_exec:
|
|
574
|
+
perms = "[bold red]W+X[/bold red]"
|
|
575
|
+
perms_raw = "W+X"
|
|
576
|
+
has_wx = True
|
|
577
|
+
anomalies.append(f"Section '{name}' is Writable + Executable (W+X self-modifying code risk).")
|
|
578
|
+
threat_score += 25
|
|
579
|
+
elif is_exec:
|
|
580
|
+
perms = "[green]R+X[/green]"
|
|
581
|
+
perms_raw = "R+X"
|
|
582
|
+
elif is_write:
|
|
583
|
+
perms = "[blue]R+W[/blue]"
|
|
584
|
+
perms_raw = "R+W"
|
|
585
|
+
else:
|
|
586
|
+
perms = "[dim]R[/dim]"
|
|
587
|
+
|
|
588
|
+
if section.SizeOfRawData == 0 and section.Misc_VirtualSize > 0:
|
|
589
|
+
anomalies.append(f"Section '{name}' has 0 raw data on disk but reserves {hex(section.Misc_VirtualSize)} in RAM.")
|
|
590
|
+
threat_score += 25
|
|
591
|
+
|
|
592
|
+
if name in KNOWN_PACKER_SECTIONS:
|
|
593
|
+
anomalies.append(f"Known packer section name: '{name}'.")
|
|
594
|
+
threat_score += 30
|
|
595
|
+
|
|
596
|
+
raw_heatmap_chars = []
|
|
597
|
+
chunk_sz = max(1, len(raw_data) // 30) if raw_data else 1
|
|
598
|
+
for i in range(30):
|
|
599
|
+
st = i * chunk_sz
|
|
600
|
+
en = len(raw_data) if i == 29 else st + chunk_sz
|
|
601
|
+
chk = raw_data[st:en]
|
|
602
|
+
if chk:
|
|
603
|
+
c_ent = calculate_entropy(chk)
|
|
604
|
+
raw_heatmap_chars.append("R" if c_ent > 7.4 else ("Y" if c_ent > 6.6 else ("G" if c_ent > 5.0 else ("B" if c_ent > 1.0 else "D"))))
|
|
605
|
+
|
|
606
|
+
if entropy > 7.4:
|
|
607
|
+
entropy_str = f"[bold red]{entropy:.2f}[/bold red]"
|
|
608
|
+
status = "[red]HIGH[/red]"
|
|
609
|
+
high_entropy_sections.append((name, raw_data, entropy))
|
|
610
|
+
threat_score += 35
|
|
611
|
+
anomalies.append(f"Section '{name}' has high entropy ({entropy:.2f} / 8.00).")
|
|
612
|
+
elif is_dilution_hit:
|
|
613
|
+
entropy_str = f"[bold red]{entropy:.2f}*[/bold red]"
|
|
614
|
+
status = "[red]DILUTED[/red]"
|
|
615
|
+
elif entropy > 6.6:
|
|
616
|
+
entropy_str = f"[bold yellow]{entropy:.2f}[/bold yellow]"
|
|
617
|
+
status = "[yellow]SUSP[/yellow]"
|
|
618
|
+
threat_score += 10
|
|
619
|
+
else:
|
|
620
|
+
entropy_str = f"[bold green]{entropy:.2f}[/bold green]"
|
|
621
|
+
status = "[green]OK[/green]"
|
|
622
|
+
|
|
623
|
+
heatmap_visual = get_entropy_heatmap_string(raw_data)
|
|
624
|
+
|
|
625
|
+
table.add_row(
|
|
626
|
+
name,
|
|
627
|
+
hex(section.Misc_VirtualSize),
|
|
628
|
+
hex(section.SizeOfRawData),
|
|
629
|
+
entropy_str,
|
|
630
|
+
perms,
|
|
631
|
+
heatmap_visual,
|
|
632
|
+
status
|
|
633
|
+
)
|
|
634
|
+
|
|
635
|
+
sections_telemetry.append({
|
|
636
|
+
"name": name,
|
|
637
|
+
"virt_size": hex(section.Misc_VirtualSize),
|
|
638
|
+
"raw_size": hex(section.SizeOfRawData),
|
|
639
|
+
"entropy": entropy,
|
|
640
|
+
"perms": perms_raw,
|
|
641
|
+
"status": "HIGH" if entropy > 7.4 else ("DILUTED" if is_dilution_hit else ("SUSP" if entropy > 6.6 else "OK")),
|
|
642
|
+
"raw_heatmap": "".join(raw_heatmap_chars)
|
|
643
|
+
})
|
|
644
|
+
|
|
645
|
+
max_offset, overlay_data = detect_overlay(pe, file_size, file_data)
|
|
646
|
+
has_overlay = len(overlay_data) > 0
|
|
647
|
+
overlay_entropy = 0.0
|
|
648
|
+
if has_overlay:
|
|
649
|
+
overlay_entropy = calculate_entropy(overlay_data)
|
|
650
|
+
|
|
651
|
+
# Check for dilution evasion in overlay
|
|
652
|
+
ov_non_zero, ov_zero_ratio, ov_diluted = calculate_dilution_metrics(overlay_data)
|
|
653
|
+
if ov_diluted:
|
|
654
|
+
is_diluted = True
|
|
655
|
+
anomalies.append(f"Overlay evasion detected! Null-byte dilution masking high-entropy payload (Real Payload Entropy: {ov_non_zero:.2f}, Zero Ratio: {ov_zero_ratio*100:.0f}%).")
|
|
656
|
+
threat_score += 45
|
|
657
|
+
high_entropy_sections.append(("overlay", overlay_data, ov_non_zero))
|
|
658
|
+
status = "[red]DILUTED[/red]"
|
|
659
|
+
elif overlay_entropy > 7.2:
|
|
660
|
+
anomalies.append(f"Overlay detected ({len(overlay_data)} bytes) with high entropy ({overlay_entropy:.2f}). Steganography/Dropper risk.")
|
|
661
|
+
threat_score += 35
|
|
662
|
+
high_entropy_sections.append(("overlay", overlay_data, overlay_entropy))
|
|
663
|
+
status = "[red]HIGH[/red]"
|
|
664
|
+
else:
|
|
665
|
+
anomalies.append(f"Overlay detected ({len(overlay_data)} bytes, entropy {overlay_entropy:.2f}).")
|
|
666
|
+
threat_score += 10
|
|
667
|
+
status = "[yellow]SUSP[/yellow]"
|
|
668
|
+
|
|
669
|
+
raw_heatmap_chars = []
|
|
670
|
+
chunk_sz = max(1, len(overlay_data) // 30)
|
|
671
|
+
for i in range(30):
|
|
672
|
+
st = i * chunk_sz
|
|
673
|
+
en = len(overlay_data) if i == 29 else st + chunk_sz
|
|
674
|
+
chk = overlay_data[st:en]
|
|
675
|
+
if chk:
|
|
676
|
+
c_ent = calculate_entropy(chk)
|
|
677
|
+
raw_heatmap_chars.append("R" if c_ent > 7.4 else ("Y" if c_ent > 6.6 else ("G" if c_ent > 5.0 else ("B" if c_ent > 1.0 else "D"))))
|
|
678
|
+
|
|
679
|
+
table.add_row(
|
|
680
|
+
"[dim][OVERLAY][/dim]",
|
|
681
|
+
"-",
|
|
682
|
+
hex(len(overlay_data)),
|
|
683
|
+
f"{overlay_entropy:.2f}",
|
|
684
|
+
"[dim]DATA[/dim]",
|
|
685
|
+
get_entropy_heatmap_string(overlay_data),
|
|
686
|
+
status
|
|
687
|
+
)
|
|
688
|
+
|
|
689
|
+
sections_telemetry.append({
|
|
690
|
+
"name": "[OVERLAY]",
|
|
691
|
+
"virt_size": "-",
|
|
692
|
+
"raw_size": hex(len(overlay_data)),
|
|
693
|
+
"entropy": overlay_entropy,
|
|
694
|
+
"perms": "DATA",
|
|
695
|
+
"status": status.strip("[]").replace("red", "").replace("/", ""),
|
|
696
|
+
"raw_heatmap": "".join(raw_heatmap_chars)
|
|
697
|
+
})
|
|
698
|
+
|
|
699
|
+
is_dotnet = is_dotnet_assembly(pe)
|
|
700
|
+
is_signed = check_authenticode_signature(pe)
|
|
701
|
+
has_rich, rich_ck = check_rich_header(pe)
|
|
702
|
+
|
|
703
|
+
total_imports, flagged_apis = inspect_imports(pe)
|
|
704
|
+
if not is_dotnet:
|
|
705
|
+
if total_imports < 15 and file_size > 30000:
|
|
706
|
+
anomalies.append(f"Unusually small import table ({total_imports} functions).")
|
|
707
|
+
threat_score += 20
|
|
708
|
+
|
|
709
|
+
if flagged_apis:
|
|
710
|
+
anomalies.append(f"Sensitive APIs: {', '.join(flagged_apis)}")
|
|
711
|
+
threat_score += 15
|
|
712
|
+
|
|
713
|
+
indicators = []
|
|
714
|
+
for s_name, s_bytes, s_ent in high_entropy_sections:
|
|
715
|
+
indicators.extend(harvest_indicators(s_bytes))
|
|
716
|
+
indicators = list(set(indicators))
|
|
717
|
+
|
|
718
|
+
threat_score = min(100, threat_score)
|
|
719
|
+
|
|
720
|
+
if threat_score >= 70:
|
|
721
|
+
verdict_color = "red"
|
|
722
|
+
verdict_text = "[CRITICAL] High Risk (Packed / Obfuscated)"
|
|
723
|
+
elif threat_score >= 35:
|
|
724
|
+
verdict_color = "yellow"
|
|
725
|
+
verdict_text = "[WARNING] Suspicious (Anomalies Present)"
|
|
726
|
+
else:
|
|
727
|
+
verdict_color = "green"
|
|
728
|
+
verdict_text = "[OK] Clean / Low Risk"
|
|
729
|
+
|
|
730
|
+
mitre_techniques = map_mitre_techniques(anomalies, flagged_apis, has_wx, len(high_entropy_sections) > 0, has_overlay, is_diluted)
|
|
731
|
+
ep_disasm = disassemble_entry_point(pe, file_data) if deep else None
|
|
732
|
+
|
|
733
|
+
if not quiet:
|
|
734
|
+
console.print(table)
|
|
735
|
+
score_panel_text = (
|
|
736
|
+
f"[bold {verdict_color}]Score: {threat_score}/100[/bold {verdict_color}]\n"
|
|
737
|
+
f"[bold]Verdict:[/bold] [{verdict_color}]{verdict_text}[/{verdict_color}]\n"
|
|
738
|
+
f"[bold]Format:[/bold] {'Managed (.NET)' if is_dotnet else 'Native PE'} | "
|
|
739
|
+
f"[bold]Signature:[/bold] {'Signed' if is_signed else 'Unsigned'}\n\n"
|
|
740
|
+
f"[underline]Findings:[/underline]\n"
|
|
741
|
+
+ ("\n".join([f"• [{verdict_color}]{a}[/{verdict_color}]" for a in anomalies]) if anomalies else "• Clean structure.")
|
|
742
|
+
)
|
|
743
|
+
if indicators:
|
|
744
|
+
score_panel_text += "\n\n[underline]Extracted Indicators:[/underline]\n" + "\n".join([f"• [cyan]{ind}[/cyan]" for ind in indicators])
|
|
745
|
+
|
|
746
|
+
console.print("\n", Panel(score_panel_text, title="Triage Diagnostic", border_style=verdict_color))
|
|
747
|
+
|
|
748
|
+
if deep:
|
|
749
|
+
if mitre_techniques:
|
|
750
|
+
mitre_table = Table(title="MITRE ATT&CK Adversary Techniques", show_header=True, header_style="bold magenta")
|
|
751
|
+
mitre_table.add_column("Technique ID", style="bold cyan", justify="center")
|
|
752
|
+
mitre_table.add_column("Technique Name", style="bold")
|
|
753
|
+
mitre_table.add_column("Triggered By", style="dim")
|
|
754
|
+
for tid, tname, tdesc in mitre_techniques:
|
|
755
|
+
mitre_table.add_row(tid, tname, tdesc)
|
|
756
|
+
console.print(mitre_table)
|
|
757
|
+
|
|
758
|
+
if ep_disasm:
|
|
759
|
+
console.print("\n", Panel(ep_disasm, title="Entry Point Disassembly Stub", border_style="dim"))
|
|
760
|
+
|
|
761
|
+
if dump_payloads:
|
|
762
|
+
if high_entropy_sections:
|
|
763
|
+
out_dir = "extracted_payloads"
|
|
764
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
765
|
+
for s_name, data, ent in high_entropy_sections:
|
|
766
|
+
clean_name = "".join([c if c.isalnum() else "_" for c in s_name])
|
|
767
|
+
out_path = os.path.join(out_dir, f"{os.path.basename(file_path)}_{clean_name}.bin")
|
|
768
|
+
with open(out_path, "wb") as f:
|
|
769
|
+
f.write(data)
|
|
770
|
+
if not quiet:
|
|
771
|
+
console.print(f"[green][+] Carved payload ({len(data)} bytes) -> {out_path}[/green]")
|
|
772
|
+
|
|
773
|
+
telemetry_data = {
|
|
774
|
+
"filename": os.path.basename(file_path),
|
|
775
|
+
"path": file_path,
|
|
776
|
+
"hashes": hashes,
|
|
777
|
+
"imphash": imphash_val,
|
|
778
|
+
"threat_score": threat_score,
|
|
779
|
+
"verdict": verdict_text,
|
|
780
|
+
"color": verdict_color,
|
|
781
|
+
"is_dotnet": is_dotnet,
|
|
782
|
+
"is_signed": is_signed,
|
|
783
|
+
"has_overlay": has_overlay,
|
|
784
|
+
"overlay_size": len(overlay_data),
|
|
785
|
+
"total_imports": total_imports,
|
|
786
|
+
"anomalies": anomalies,
|
|
787
|
+
"mitre": mitre_techniques,
|
|
788
|
+
"ep_disasm": ep_disasm,
|
|
789
|
+
"indicators": indicators,
|
|
790
|
+
"sections": sections_telemetry,
|
|
791
|
+
"wx": has_wx
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
if json_out:
|
|
795
|
+
out_dir = os.path.dirname(os.path.abspath(json_out))
|
|
796
|
+
if out_dir:
|
|
797
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
798
|
+
with open(json_out, "w", encoding="utf-8") as f:
|
|
799
|
+
json.dump(telemetry_data, f, indent=2)
|
|
800
|
+
console.print(f"[green][+] JSON telemetry written:[/green] {os.path.abspath(json_out)}")
|
|
801
|
+
|
|
802
|
+
if html_out:
|
|
803
|
+
generate_minimal_html_report(telemetry_data, html_out)
|
|
804
|
+
console.print(f"[green][+] HTML report generated:[/green] {os.path.abspath(html_out)}")
|
|
805
|
+
|
|
806
|
+
return telemetry_data
|
|
807
|
+
|
|
808
|
+
def analyze_elf(file_path, file_data, quiet=False):
|
|
809
|
+
"""Basic cross-platform fallback for Linux ELF binaries."""
|
|
810
|
+
if not quiet:
|
|
811
|
+
console.print(f"\n[bold]Target:[/bold] {file_path}")
|
|
812
|
+
console.print("[dim]Format: Linux ELF Binary[/dim]")
|
|
813
|
+
|
|
814
|
+
entropy = calculate_entropy(file_data)
|
|
815
|
+
status = "[red]HIGH[/red]" if entropy > 7.4 else ("[yellow]SUSP[/yellow]" if entropy > 6.6 else "[green]OK[/green]")
|
|
816
|
+
|
|
817
|
+
table = Table(title="ELF Binary Entropy Summary", show_header=True, header_style="bold")
|
|
818
|
+
table.add_column("Type", style="cyan")
|
|
819
|
+
table.add_column("Size", justify="right")
|
|
820
|
+
table.add_column("Entropy", justify="right")
|
|
821
|
+
table.add_column("Entropy Strip", justify="left")
|
|
822
|
+
table.add_column("Status", justify="center")
|
|
823
|
+
|
|
824
|
+
table.add_row(
|
|
825
|
+
"ELF Full Image",
|
|
826
|
+
hex(len(file_data)),
|
|
827
|
+
f"{entropy:.2f}",
|
|
828
|
+
get_entropy_heatmap_string(file_data),
|
|
829
|
+
status
|
|
830
|
+
)
|
|
831
|
+
if not quiet:
|
|
832
|
+
console.print(table)
|
|
833
|
+
return {
|
|
834
|
+
"filename": os.path.basename(file_path),
|
|
835
|
+
"path": file_path,
|
|
836
|
+
"threat_score": 50 if entropy > 7.4 else 0,
|
|
837
|
+
"verdict": "[WARNING] High Entropy ELF" if entropy > 7.4 else "[OK] Clean ELF",
|
|
838
|
+
"color": "yellow" if entropy > 7.4 else "green",
|
|
839
|
+
"is_dotnet": False,
|
|
840
|
+
"is_signed": False,
|
|
841
|
+
"has_overlay": False,
|
|
842
|
+
"overlay_size": 0,
|
|
843
|
+
"total_imports": 0,
|
|
844
|
+
"anomalies": ["High entropy full image"] if entropy > 7.4 else [],
|
|
845
|
+
"indicators": [],
|
|
846
|
+
"sections": [],
|
|
847
|
+
"wx": False
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
def scan_directory(dir_path, recursive=False, dump_payloads=False):
|
|
851
|
+
dir_path = os.path.abspath(os.path.normpath(dir_path.strip().strip('"\'')))
|
|
852
|
+
if not os.path.isdir(dir_path):
|
|
853
|
+
console.print(f"[red]Error: Directory not found -> {dir_path}[/red]")
|
|
854
|
+
return
|
|
855
|
+
|
|
856
|
+
console.print(f"\n[bold]Scanning Directory:[/bold] {dir_path} (Recursive={recursive})")
|
|
857
|
+
|
|
858
|
+
executable_files = []
|
|
859
|
+
valid_exts = {".exe", ".dll", ".sys", ".scr"}
|
|
860
|
+
|
|
861
|
+
if recursive:
|
|
862
|
+
for root, _, files in os.walk(dir_path):
|
|
863
|
+
for f in files:
|
|
864
|
+
if os.path.splitext(f)[1].lower() in valid_exts:
|
|
865
|
+
executable_files.append(os.path.join(root, f))
|
|
866
|
+
else:
|
|
867
|
+
for f in os.listdir(dir_path):
|
|
868
|
+
p = os.path.join(dir_path, f)
|
|
869
|
+
if os.path.isfile(p) and os.path.splitext(f)[1].lower() in valid_exts:
|
|
870
|
+
executable_files.append(p)
|
|
871
|
+
|
|
872
|
+
if not executable_files:
|
|
873
|
+
console.print("[dim]No executable files found in directory.[/dim]")
|
|
874
|
+
return
|
|
875
|
+
|
|
876
|
+
console.print(f"[dim]Triaging {len(executable_files)} binaries...[/dim]\n")
|
|
877
|
+
|
|
878
|
+
results = []
|
|
879
|
+
for fp in executable_files:
|
|
880
|
+
res = analyze_single_file(fp, dump_payloads=dump_payloads, quiet=True)
|
|
881
|
+
if res:
|
|
882
|
+
results.append(res)
|
|
883
|
+
|
|
884
|
+
if not results:
|
|
885
|
+
console.print("[dim]No valid Windows PE binaries found.[/dim]")
|
|
886
|
+
return
|
|
887
|
+
|
|
888
|
+
results.sort(key=lambda x: x["threat_score"], reverse=True)
|
|
889
|
+
|
|
890
|
+
triage_table = Table(title="Incident Triage Leaderboard", show_header=True, header_style="bold")
|
|
891
|
+
triage_table.add_column("Rank", justify="center", style="dim")
|
|
892
|
+
triage_table.add_column("Filename", style="cyan")
|
|
893
|
+
triage_table.add_column("Score", justify="right")
|
|
894
|
+
triage_table.add_column("W+X", justify="center")
|
|
895
|
+
triage_table.add_column(".NET", justify="center")
|
|
896
|
+
triage_table.add_column("Overlay", justify="center")
|
|
897
|
+
triage_table.add_column("Verdict", justify="center")
|
|
898
|
+
triage_table.add_column("Primary Flag", style="dim")
|
|
899
|
+
|
|
900
|
+
for idx, r in enumerate(results, 1):
|
|
901
|
+
score_str = f"[{r['color']}]{r['threat_score']}[/{r['color']}]"
|
|
902
|
+
verdict_str = f"[{r['color']}]{r['verdict']}[/{r['color']}]"
|
|
903
|
+
wx_str = "[bold red]YES[/bold red]" if r["wx"] else "[dim]NO[/dim]"
|
|
904
|
+
dotnet_str = "[cyan]YES[/cyan]" if r["is_dotnet"] else "[dim]NO[/dim]"
|
|
905
|
+
overlay_str = "[bold red]YES[/bold red]" if r["has_overlay"] else "[dim]NO[/dim]"
|
|
906
|
+
top_anomaly = r["anomalies"][0] if r["anomalies"] else "None"
|
|
907
|
+
|
|
908
|
+
triage_table.add_row(
|
|
909
|
+
str(idx),
|
|
910
|
+
r["filename"],
|
|
911
|
+
score_str,
|
|
912
|
+
wx_str,
|
|
913
|
+
dotnet_str,
|
|
914
|
+
overlay_str,
|
|
915
|
+
verdict_str,
|
|
916
|
+
top_anomaly
|
|
917
|
+
)
|
|
918
|
+
|
|
919
|
+
console.print(triage_table)
|
|
920
|
+
console.print(f"\n[green][+] Completed:[/green] Triaged {len(results)} binaries.")
|
|
921
|
+
|
|
922
|
+
def main():
|
|
923
|
+
console.print(BANNER, style="cyan")
|
|
924
|
+
parser = argparse.ArgumentParser(description="entropystrip: PE De-obfuscator & Triage Engine")
|
|
925
|
+
parser.add_argument("target", help="Path to Windows executable (.exe / .dll) or directory")
|
|
926
|
+
parser.add_argument("-r", "--recursive", action="store_true", help="Recursively scan subdirectories")
|
|
927
|
+
parser.add_argument("--dump", action="store_true", help="Carve high-entropy payloads to extracted_payloads/")
|
|
928
|
+
parser.add_argument("--deep", action="store_true", help="Deep forensic triage: MITRE ATT&CK mapping, entry point disassembly, and hashes")
|
|
929
|
+
parser.add_argument("--html", help="Path to write HTML report")
|
|
930
|
+
parser.add_argument("--json", help="Path to write JSON telemetry")
|
|
931
|
+
args = parser.parse_args()
|
|
932
|
+
|
|
933
|
+
clean_target = os.path.abspath(os.path.normpath(args.target.strip().strip('"\'')))
|
|
934
|
+
|
|
935
|
+
if os.path.isdir(clean_target):
|
|
936
|
+
scan_directory(clean_target, recursive=args.recursive, dump_payloads=args.dump)
|
|
937
|
+
else:
|
|
938
|
+
analyze_single_file(clean_target, dump_payloads=args.dump, quiet=False, html_out=args.html, json_out=args.json, deep=args.deep)
|
|
939
|
+
|
|
940
|
+
if __name__ == "__main__":
|
|
941
|
+
main()
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: entropystrip
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Algorithmic PE de-obfuscator, Shannon entropy radar, and incident triage engine.
|
|
5
|
+
Author-email: dwexi <dwexi@users.noreply.github.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/dwexi/entropystrip
|
|
8
|
+
Project-URL: Repository, https://github.com/dwexi/entropystrip
|
|
9
|
+
Project-URL: Issues, https://github.com/dwexi/entropystrip/issues
|
|
10
|
+
Keywords: malware-analysis,reverse-engineering,pe,entropy,shannon-entropy,incident-response,security,dfir
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Information Technology
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Security
|
|
24
|
+
Classifier: Topic :: Software Development :: Disassemblers
|
|
25
|
+
Classifier: Topic :: Utilities
|
|
26
|
+
Requires-Python: >=3.8
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Requires-Dist: pefile>=2024.8.26
|
|
30
|
+
Requires-Dist: rich>=13.7.0
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# entropystrip
|
|
34
|
+
|
|
35
|
+
```text
|
|
36
|
+
___________ __ _________ __ .__
|
|
37
|
+
\_ _____/ _____/ |________ ____ ______ ___.__./ _____// |________|__|_____
|
|
38
|
+
| __)_ / \ __\_ __ \/ _ \\____ < | |\_____ \\ __\_ __ \ \____ \
|
|
39
|
+
| \ | \ | | | \( <_> ) |_> >___ |/ \| | | | \/ | |_> >
|
|
40
|
+
/_______ /___| /__| |__| \____/| __// ____/_______ /|__| |__| |__| __/
|
|
41
|
+
\/ \/ |__| \/ \/ |__|
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## What it does
|
|
48
|
+
|
|
49
|
+
Most modern malware hides behind packers (like UPX, VMProtect, or Themida) or stashes encrypted payloads in PE resource directories or trailing file overlays. Rather than relying on static byte signatures, `entropystrip` evaluates:
|
|
50
|
+
|
|
51
|
+
1. **Section Entropy:** Calculates block-level Shannon entropy across every PE section to locate encrypted or compressed buffers ($H > 7.20$).
|
|
52
|
+
2. **Memory Permissions:** Identifies sections marked simultaneously as Writable and Executable (`IMAGE_SCN_MEM_WRITE` and `IMAGE_SCN_MEM_EXECUTE`), which indicates self-modifying code or runtime unpackers.
|
|
53
|
+
3. **PE Overlays:** Measures trailing bytes appended past the end of the last mapped section.
|
|
54
|
+
4. **Import Table Size & Composition:** Flags binaries with unusually small IATs (e.g. only importing `LoadLibrary` / `GetProcAddress`) or sensitive process injection primitives (`VirtualAlloc`, `WriteProcessMemory`, `QueueUserAPC`).
|
|
55
|
+
5. **.NET Classification:** Inspects the COM descriptor directory to separate managed CLR assemblies from native binaries, avoiding false positives on standard C# applications.
|
|
56
|
+
6. **Payload Carving:** Extracts identified high-entropy sections or overlays straight to raw binary files on disk for further analysis.
|
|
57
|
+
7. **Directory Triage:** Walks directories or drives and ranks all found binaries by threat score.
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## Installation
|
|
62
|
+
|
|
63
|
+
Requirements: Python 3.8+ on Windows, Linux, or macOS.
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install entropystrip
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Or install directly from source:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
git clone https://github.com/dwexi/entropystrip.git
|
|
73
|
+
cd entropystrip
|
|
74
|
+
pip install -e .
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## Usage
|
|
80
|
+
|
|
81
|
+
```text
|
|
82
|
+
usage: main.py [-h] [-r] [--dump] [--deep] [--html HTML] [--json JSON] target
|
|
83
|
+
|
|
84
|
+
EntropyStrip: PE De-obfuscator & Triage Engine
|
|
85
|
+
|
|
86
|
+
positional arguments:
|
|
87
|
+
target Path to Windows executable (.exe / .dll) or directory to scan
|
|
88
|
+
|
|
89
|
+
options:
|
|
90
|
+
-h, --help show this help message and exit
|
|
91
|
+
-r, --recursive
|
|
92
|
+
recursively scan subdirectories if target is a folder
|
|
93
|
+
--dump carve and write high-entropy payloads to extracted_payloads/
|
|
94
|
+
--deep deep forensic triage: MITRE ATT&CK mapping, entry point disassembly, hashes
|
|
95
|
+
--html HTML write minimalist HTML report to specified path
|
|
96
|
+
--json JSON write machine-readable JSON telemetry to specified path
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Examples
|
|
100
|
+
|
|
101
|
+
**Analyze a single binary:**
|
|
102
|
+
```bash
|
|
103
|
+
python main.py target.exe
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
**Deep forensic triage with MITRE ATT&CK mapping & disassembly:**
|
|
107
|
+
```bash
|
|
108
|
+
python main.py suspicious.exe --deep
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
**Analyze and extract hidden payload buffers:**
|
|
112
|
+
```bash
|
|
113
|
+
python main.py suspicious.exe --dump
|
|
114
|
+
```
|
|
115
|
+
Carved payloads are written to `extracted_payloads/<target>_<section>.bin`.
|
|
116
|
+
|
|
117
|
+
**Export a standalone HTML report:**
|
|
118
|
+
```bash
|
|
119
|
+
python main.py sample.exe --html report.html
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
**Triage an entire directory of unknown files:**
|
|
123
|
+
```bash
|
|
124
|
+
python main.py "C:\IncidentTriage" -r
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## Entropy Scale Reference
|
|
130
|
+
|
|
131
|
+
Shannon entropy measures information density from 0.00 to 8.00 bits per byte:
|
|
132
|
+
|
|
133
|
+
$$H(X) = -\sum_{i=0}^{255} P(x_i) \log_2 P(x_i)$$
|
|
134
|
+
|
|
135
|
+
| Entropy Range | Expected Content | Notes |
|
|
136
|
+
|---|---|---|
|
|
137
|
+
| `0.00 - 2.00` | Zero-padding, sparse tables | Common in uninitialized data or alignment padding |
|
|
138
|
+
| `2.00 - 5.50` | Standard ASCII, configurations | Normal application metadata, strings |
|
|
139
|
+
| `5.50 - 6.60` | Native compiled machine code | Standard x86/x64 instructions (`.text`) |
|
|
140
|
+
| `6.60 - 7.30` | Compressed assets | Bitmaps, icons, zlib/deflate streams |
|
|
141
|
+
| `7.40 - 8.00` | Cryptographic ciphertext | AES/RC4 encrypted payloads or tightly packed shellcode |
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
## License
|
|
146
|
+
|
|
147
|
+
MIT License. See [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
entropystrip/__init__.py,sha256=nzUu1j-C-sGm0eh2W72NYhkpOtkJGPuewHXHu4ejM-g,434
|
|
2
|
+
entropystrip/__main__.py,sha256=C63rP_FwCHaSkxcmbkQ6gK3aKf_0hHm0Co9mCen6bmY,126
|
|
3
|
+
entropystrip/core.py,sha256=VnY9-THVUpfHJzh895Q-tQucVQjQdvRoWTRlumYQWes,35155
|
|
4
|
+
entropystrip-1.0.0.dist-info/licenses/LICENSE,sha256=H6fhhOFGvhAqnDiUNsXJzAMRSawrMwKZmoM6m2x_DWw,1082
|
|
5
|
+
entropystrip-1.0.0.dist-info/METADATA,sha256=TMg_B5bkvKJusJXmBV63NiPujpUtnxgX59mGlx8WI3g,5705
|
|
6
|
+
entropystrip-1.0.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
7
|
+
entropystrip-1.0.0.dist-info/entry_points.txt,sha256=Mt7n02JFCIB1MHkTKXrXHWIaBtvWtPggSxCJlk9HFMU,56
|
|
8
|
+
entropystrip-1.0.0.dist-info/top_level.txt,sha256=0iH1x9upvRPMm5ZwgUoKNdR9ykopRSGTWI_mYW1LRZs,13
|
|
9
|
+
entropystrip-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EntropyStrip Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
entropystrip
|