-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyzer.py
More file actions
211 lines (159 loc) · 5.7 KB
/
Copy pathanalyzer.py
File metadata and controls
211 lines (159 loc) · 5.7 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
import hashlib
import json
import os
import re
import sys
from pathlib import Path
from datetime import datetime
try:
import magic
except ImportError:
magic = None
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from pe_analyzer import analyze_pe
from yara_scanner import scan_with_yara
from risk_score import calculate_risk
from html_report import generate_html_report
console = Console()
def calculate_hashes(file_path):
hashers = {
"md5": hashlib.md5(),
"sha1": hashlib.sha1(),
"sha256": hashlib.sha256()
}
with open(file_path, "rb") as file:
while chunk := file.read(8192):
for hasher in hashers.values():
hasher.update(chunk)
return {name: hasher.hexdigest() for name, hasher in hashers.items()}
def get_file_type(file_path):
if magic:
return magic.from_file(str(file_path))
return "python-magic not installed"
def extract_strings(file_path, min_length=5):
with open(file_path, "rb") as file:
data = file.read()
pattern = rb"[ -~]{" + str(min_length).encode() + rb",}"
found = re.findall(pattern, data)
return [item.decode(errors="ignore") for item in found[:1000]]
def find_suspicious_strings(strings):
indicators = [
"cmd.exe",
"powershell",
"wscript",
"cscript",
"schtasks",
"reg add",
"http://",
"https://",
"CreateRemoteThread",
"VirtualAlloc",
"VirtualProtect",
"WriteProcessMemory",
"GetProcAddress",
"LoadLibrary",
"URLDownloadToFile",
"InternetOpen",
"password",
"token",
"wallet",
"keylogger"
]
findings = []
for string in strings:
lowered = string.lower()
for indicator in indicators:
if indicator.lower() in lowered:
findings.append({
"indicator": indicator,
"string": string
})
return findings
def analyze_file(file_path):
file_path = Path(file_path)
if not file_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
strings = extract_strings(file_path)
report = {
"analysis_time": datetime.now().isoformat(),
"file_name": file_path.name,
"file_size": os.path.getsize(file_path),
"file_type": get_file_type(file_path),
"hashes": calculate_hashes(file_path),
"suspicious_strings": find_suspicious_strings(strings),
"sample_strings": strings[:100],
"pe_analysis": analyze_pe(str(file_path)),
"yara_matches": scan_with_yara(str(file_path))
}
report["risk"] = calculate_risk(report)
return report
def save_report(report):
reports_dir = Path("reports")
reports_dir.mkdir(exist_ok=True)
output_name = report["hashes"]["sha256"] + ".json"
output_path = reports_dir / output_name
with open(output_path, "w") as file:
json.dump(report, file, indent=2)
return output_path
def print_report(report, output_path):
risk = report["risk"]
pe = report["pe_analysis"]
title = f"MalwareScope Analysis Report - {report['file_name']}"
console.print(Panel(title, style="bold cyan"))
summary = Table(title="File Summary")
summary.add_column("Field", style="bold")
summary.add_column("Value")
summary.add_row("File Name", report["file_name"])
summary.add_row("File Size", f"{report['file_size']} bytes")
summary.add_row("File Type", report["file_type"])
summary.add_row("MD5", report["hashes"]["md5"])
summary.add_row("SHA1", report["hashes"]["sha1"])
summary.add_row("SHA256", report["hashes"]["sha256"])
summary.add_row("Report Path", str(output_path))
console.print(summary)
risk_table = Table(title="Risk Assessment")
risk_table.add_column("Metric", style="bold")
risk_table.add_column("Result")
risk_table.add_row("Score", f"{risk['score']}/100")
risk_table.add_row("Verdict", risk["verdict"])
if risk["reasons"]:
risk_table.add_row("Reasons", "\n".join(risk["reasons"]))
else:
risk_table.add_row("Reasons", "No major suspicious indicators detected")
console.print(risk_table)
yara_table = Table(title="YARA Matches")
yara_table.add_column("Rule File", style="bold")
yara_table.add_column("Rule Name")
if report["yara_matches"]:
for match in report["yara_matches"]:
yara_table.add_row(
match.get("rule_file", "N/A"),
match.get("rule_name", match.get("error", "N/A"))
)
else:
yara_table.add_row("None", "No YARA matches")
console.print(yara_table)
pe_table = Table(title="PE Analysis")
pe_table.add_column("Field", style="bold")
pe_table.add_column("Value")
if pe.get("is_pe"):
pe_table.add_row("PE File", "Yes")
pe_table.add_row("Entry Point", pe.get("entry_point", "N/A"))
pe_table.add_row("Image Base", pe.get("image_base", "N/A"))
pe_table.add_row("Sections", str(pe.get("number_of_sections", "N/A")))
pe_table.add_row("Imports Count", str(len(pe.get("imports", []))))
else:
pe_table.add_row("PE File", "No")
pe_table.add_row("Reason", pe.get("error", "Not a Windows PE file"))
console.print(pe_table)
if __name__ == "__main__":
if len(sys.argv) != 2:
console.print("[bold red]Usage:[/bold red] python analyzer.py <file_path>")
sys.exit(1)
result = analyze_file(sys.argv[1])
output = save_report(result)
html_output = generate_html_report(result)
print_report(result, output)
console.print(f"\n[bold green]HTML report saved to:[/bold green] {html_output}")