forked from cyberket96/Static-Malware-Analysis-Using-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmalware_analyzer.py
More file actions
322 lines (263 loc) · 13.4 KB
/
malware_analyzer.py
File metadata and controls
322 lines (263 loc) · 13.4 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
# =================================================================================================
# Project: Static Malware Analysis using Python (Malysis)
#
# Description:
# This script performs a static analysis on a given file to identify potentially
# malicious characteristics by searching for known signatures, API calls, and strings.
# It generates a detailed report of its findings.
#
# Dev Team: Ketan Mote & Sourabh Pradhan
# =================================================================================================
# --- 1. IMPORTS ---
# Standard library imports
import sys
import os
import re
import string
import time
import hashlib
import tkinter as tk
# Third-party imports
import pyfiglet as fig
from colorama import Fore, Back, Style, init
# Initialize colorama to work on all platforms
init(autoreset=True)
# --- 2. SIGNATURE DEFINITIONS ---
# These lists contain strings and patterns to search for within the target file.
# Signatures for potentially suspicious or interesting function calls
INTERESTING_CALLS = [
"CreateMutex", "CopyFile", "CreateFile.*WRITE", "NtasdfCreateFile", "call shell32",
"advapi32.RegOpenKey", "KERNEL32.CreateProcess", "shdocvw", "gethostbyname",
"ws2_32.bind", "ws2_32.listen", "ws2_32.htons", "advapi32.RegCreate", "advapi32.RegSet",
"Socket", "OutputDebugString", "GetEnvironmentStrings", "LoadLibraryA", "WSASocketA",
"GetProcAddress", "FindWindow", "CreateProcess", "DuplicateTokenEx", "signal",
"IdDebuggerPresent", "STARTUPINFO()", "GetLogicalDriveStrings()",
".run([powershell code] stdout=subprocess.PIPE stderr=subprocess.STDOUT shell=True)",
"CommitSuicide()", "RunAsAdmin()", "IsPyExist()", "os.path.join(root, file)", " th.start()"
]
# Common Windows DLLs that malware often interacts with
DLL_CALLS = [
"KERNEL.DLL", "advapi32.dll", "comctl32.dll", "gdi32.dll", "ole32.dll",
"oleaut32.dll", "user32.dll", "wsock32.dll", "ntdll.dll", "win32api", "kernel32"
]
# System executables often used by malware for reconnaissance or anti-VM checks
SYS_CALLS = [
"ping.exe", "telnet.exe", "vmsrvc.exe", "vmusrvc.exe", "vboxtray.exe",
"vmtoolsd.exe", "df5serv.exe", "vboxservice.exe"
]
# Signatures related to IRC (Internet Relay Chat), often used for C2 communication
IRC_COMMANDS = [
"IRC", "Joined Channel", "Port", "Bot", "Login", "flood", "ddos", "NICK", "ECHO",
"ADMIN", "CONNECT", "PING", "SERVICE", "INFO", "WHO", "WHOIS", "VERSION",
"requests.packages.urllib3.disable_warnings()", ".com", "192.168.202.1", "4567",
"socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",
"client.recv(2048)", "socket.SO_REUSEADDR"
]
# Signatures for Windows Registry manipulation, a common persistence technique
REGISTRY_CALLS = [
"HKEY_CURRENT_USER", "HKEY_CLASSES_ROOT", "HKEY_LOCAL_MACHINE", "autorun.inf",
"REG ADD", "REG_DWORD", "DisableRegistryTools", "DisableTaskMgr", "DisableCMD",
"SintaRegistery", "addRegistery"
]
# Signatures for cryptographic functions, which could indicate ransomware
CRYPTO = [
"lstrcmpA", "CryptGetUserKey", "CryptExportKey", "CryptDestoryKey",
"CryptReleaseContext", "AES", "Crypto", "tool.encrypt(data)", "Fernet",
"cryptography.fernet", "base64", "hazmat.backends", "hazmat.primitives",
"PBKDF2HMAC", "hashes.SHA256()", "base64.urlsafe_b64encode(kdf.derive(password))",
"otp.decode()", "secret.decode()", "Fernet.generate_key()", "0.0.0.0", "4567"
]
# Signatures related to self-propagation, characteristic of worms
SPREAD = ["FindFirstFileA", "lstrcmpiA", "FindNextFileA", "FindClose", "text_generator"]
# Common file extensions malware might create or look for
EXTEN = ["txt", "exe", "php", "pl", "7z", "py"]
# File paths and registry locations often targeted by malware
LOC = [
"cipher /W:%s", "CurrentVersion", "Policies", "HKEY_LOCAL_MACHINE", "SYSTEM",
"Control", "Terminal Server", "c:/"
]
# --- 3. CORE ANALYSIS FUNCTIONS ---
def display_banner():
"""Prints the project banner and developer information to the console."""
print(Fore.YELLOW + "T.Y BSC (Cyber Security) | Semester-V")
print("Mini Project (Malware/Cryptography) | Course Code : CS-317")
print("Project Title : Static Malware Analysis using Python.\n")
banner = fig.figlet_format("||_Malysis_||")
print(Fore.GREEN + banner)
print(Fore.YELLOW + "Dev Team : A22 Ketan Mote & A63 Sourabh Pradhan")
print("Codename : Malysis")
print("Version : 0.0.1")
print("Contact : +91 9696699696 / ouremail@mail.com")
print("-" * 100)
def get_user_input():
"""Creates a GUI to get the target file path and report filename from the user."""
# This nested function is called when the "START" button is clicked
def process_input():
nonlocal malware_file, report_filename, file_content
malware_file = entry_file.get()
report_filename = entry_report.get()
# Set a default report name if one isn't provided
if not report_filename:
report_filename = "default_report.txt"
# Validate that the malware file exists before proceeding
try:
with open(malware_file, 'r', errors='ignore') as f:
file_content = f.readlines()
root.destroy() # Close the GUI window
except (IOError, FileNotFoundError):
print(Fore.RED + "\n[ERROR] Malware file not found or could not be opened.")
print("Please ensure the file path is correct and the file exists.")
print("\nExiting...")
sys.exit(1)
# Variables to hold the input from the GUI
malware_file = ""
report_filename = ""
file_content = []
# Setup the main GUI window
root = tk.Tk()
root.title("MALWARE ANALYZER (Malysis)")
# Create and pack the widgets for file input
label_file = tk.Label(root, text="Enter Target File Path", width=40, height=3)
label_file.pack()
entry_file = tk.Entry(root, width=50)
entry_file.pack()
# Create and pack the widgets for report name input
label_report = tk.Label(root, text="Enter Report Name (e.g., report.txt)", width=40, height=3)
label_report.pack()
entry_report = tk.Entry(root, width=50)
entry_report.pack()
# Create and pack the start button
button_start = tk.Button(root, text="START ANALYSIS", width=60, command=process_input)
button_start.pack(pady=10)
root.mainloop()
return malware_file, report_filename, file_content
def check_for_help_arg():
"""Checks if the script was run with a '--help' argument and exits if so."""
if "--help" in sys.argv:
print("\nUsage: python3 malysis.py")
print("A GUI window will open to select the file for analysis.")
sys.exit(0)
def scan_signatures(file_content, signature_list, category_name, message_template, results_list):
"""
Generic function to scan file content for a list of signatures.
Args:
file_content (list): The lines of the file to scan.
signature_list (list): The list of string patterns to search for.
category_name (str): The name of the signature category (for logging).
message_template (str): The message to print when a signature is found.
results_list (list): The list to append found signatures to.
Returns:
bool: True if any signature was found, False otherwise.
"""
found = False
print(Fore.RED + f"\n[!] SCANNING FOR {category_name}...\n")
for line in file_content:
for signature in signature_list:
if re.search(signature, line, re.IGNORECASE):
print(Fore.BLUE + message_template.format(signature))
results_list.append(signature)
found = True
print("-" * 100)
time.sleep(1)
return found
def check_pe_file(malware_file):
"""Checks if the file is a valid PE (Portable Executable) file by reading its header."""
print(Fore.RED + "\n[!] ANALYSING IF PE FILE...\n")
try:
with open(malware_file, "rb") as f:
header = f.read(2)
if header == b'MZ':
print(Fore.BLUE + "[+] VALID PE FILE DETECTED.")
else:
print(Fore.YELLOW + "[-] NOT A PE FILE (Missing 'MZ' header).")
except Exception as e:
print(Fore.RED + f"[ERROR] Could not read file to check PE header: {e}")
print("-" * 100)
time.sleep(1)
def generate_report(malware_file, report_filename, analysis_results):
"""Generates a text file report summarizing the analysis findings."""
print("Generating Report...")
time.sleep(1)
try:
with open(report_filename, "w") as f:
# Report Header
f.write("=" * 70 + "\n")
f.write("|| MALYSIS - STATIC MALWARE ANALYSIS REPORT ||\n")
f.write("=" * 70 + "\n\n")
# Basic File Information
f.write("# --- Basic File Information ---\n")
f.write(f"1. File Name: {os.path.basename(malware_file)}\n")
f.write(f"2. Full Path: {os.path.abspath(malware_file)}\n")
file_size = os.path.getsize(malware_file)
f.write(f"3. File Size: {file_size} bytes\n\n")
# File Hashes
f.write("# --- File Hashes ---\n")
with open(malware_file, "rb") as file_for_hash:
content = file_for_hash.read()
f.write(f"MD5: {hashlib.md5(content).hexdigest()}\n")
f.write(f"SHA256: {hashlib.sha256(content).hexdigest()}\n")
f.write(f"SHA512: {hashlib.sha512(content).hexdigest()}\n\n")
# Signature Analysis Results
f.write("# --- Signature Analysis Results ---\n")
for category, findings in analysis_results.items():
f.write(f"\n- {category.upper()} FOUND:\n")
if findings:
# Write each finding on a new line for better readability
for finding in sorted(list(set(findings))):
f.write(f" - {finding}\n")
else:
f.write(" - None\n")
f.write("\n" + "=" * 70)
f.write("\nEnd of Report.\n")
print(f"\n[SUCCESS] Report has been generated with name '{report_filename}'")
except Exception as e:
print(Fore.RED + f"[ERROR] Failed to generate report: {e}")
# --- 4. MAIN EXECUTION ---
def main():
"""Main function to orchestrate the malware analysis process."""
check_for_help_arg()
display_banner()
malware_file, report_filename, file_content = get_user_input()
# If the GUI was closed without starting, file_content will be empty
if not file_content:
print("\nAnalysis cancelled. Exiting.")
sys.exit(0)
print(f"\n[INFO] Starting analysis on file: {malware_file}")
time.sleep(2)
check_pe_file(malware_file)
# --- Run all signature scans ---
# Store results in a dictionary for cleaner reporting
analysis_results = {
"Interesting Calls": [],
"System Calls": [],
"IRC Commands": [],
"Cryptographic Functions": [],
"Worm-like Behavior": [],
"DLL Calls": [],
"Registry Calls": [],
"Targeted Locations": [],
"Targeted Extensions": []
}
# Use a list to track if any malicious indicators were found
malicious_indicators_found = []
malicious_indicators_found.append(scan_signatures(file_content, INTERESTING_CALLS, "INTERESTING CALLS", "[+] Found an INTERESTING CALL to {}", analysis_results["Interesting Calls"]))
malicious_indicators_found.append(scan_signatures(file_content, REGISTRY_CALLS, "REGISTRY MANIPULATION", "[+] Found REGISTRY CALL: {}", analysis_results["Registry Calls"]))
malicious_indicators_found.append(scan_signatures(file_content, IRC_COMMANDS, "ONLINE BEHAVIOR (IRC)", "[+] Found IRC-related signature: {}", analysis_results["IRC Commands"]))
malicious_indicators_found.append(scan_signatures(file_content, DLL_CALLS, "LOADED DLLS", "[+] Found loaded DLL: {}", analysis_results["DLL Calls"]))
malicious_indicators_found.append(scan_signatures(file_content, SYS_CALLS, "SYSTEM COMMANDS", "[+] Found SYSTEM COMMAND: {}", analysis_results["System Calls"]))
malicious_indicators_found.append(scan_signatures(file_content, EXTEN, "TARGETED EXTENSIONS", "[+] Found targeted EXTENSION: {}", analysis_results["Targeted Extensions"]))
malicious_indicators_found.append(scan_signatures(file_content, LOC, "TARGETED LOCATIONS", "[+] Found targeted LOCATION: {}", analysis_results["Targeted Locations"]))
malicious_indicators_found.append(scan_signatures(file_content, CRYPTO, "CRYPTOGRAPHIC FUNCTIONS", "[+] Found CRYPTOGRAPHIC function: {}", analysis_results["Cryptographic Functions"]))
malicious_indicators_found.append(scan_signatures(file_content, SPREAD, "WORM SIGNATURES", "[+] Found WORM-like signature: {}", analysis_results["Worm-like Behavior"]))
# --- Generate Report and Final Verdict ---
generate_report(malware_file, report_filename, analysis_results)
# Check if any of the scan functions returned True (found a signature)
if any(malicious_indicators_found):
print(Fore.RED + "\n[WARNING] FILE IS POTENTIALLY MALICIOUS. Please review the report and be careful.")
else:
print(Fore.GREEN + "\n[INFO] No suspicious signatures found. The file appears to be clean.")
print("\nAnalysis complete. Exiting...")
# Entry point of the script
if __name__ == "__main__":
main()