-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSRE.py
More file actions
350 lines (313 loc) · 16.6 KB
/
SRE.py
File metadata and controls
350 lines (313 loc) · 16.6 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
#!/usr/bin/python3
# coding: utf-8
__version__ = "v1.0"
__author__ = "malsearchs"
__email__ = "malsearchs [at] gmail [dot] com"
__url__ = "https://github.com/malsearchs/Static-Reverse-Engineering-SRE"
show_license = """\
Copyright (C) 2023 @malsearchs"""
import os, sys
import hashlib
import argparse
import time
import magic
from datetime import timedelta
#colors courtesy: https://gist.github.com/vratiu/9780109
# Get the start time
start_time = time.time()
# Create the argument parser and define the required input parameter
class CustomFormatter(argparse.RawDescriptionHelpFormatter):
def _format_action(self, action):
if action.option_strings:
default_metavar = self._metavar_formatter(action, action.dest)(1)
help_text = self._expand_help(action)
return f"{' '.join(action.option_strings)}\t {help_text}\n"
else:
return super()._format_action(action)
# Check for incorrect options
def invalid_options(option):
return f"\033[32;5m\033[1;31mError:\033[0m invalid option '{option}'\nTry 'SRE.py -h' for more information."
# Create the ArgumentParser object with the custom formatter
parser = argparse.ArgumentParser(prog='SRE.py', usage='%(prog)s [options] [filename]', description='\033[0;101m\033[1;97m >>> \033[40mS\033[0;101m\033[1;97mtatic \033[40mR\033[0;101m\033[1;97meverse \033[40mE\033[0;101m\033[1;97mngineering [\033[40mSRE\033[0;101m\033[1;97m] <<< \033[0m\n \033[1;96m Dissecting malware for static analysis\033[0m\033[1;97m', formatter_class=CustomFormatter)
if '-vv' in sys.argv or '-f' in sys.argv:
parser.add_argument('filename', nargs='?', help="~state file path [to scan single file] \033[1;32\033[4;32mor\033[0m\033[1;97m state folder path [to scan multiple files]\n")
else:
parser.add_argument('filename', nargs='?', help="~state file path [to scan single file] \033[1;32\033[4;32mor\033[0m\033[1;97m state folder path [to scan multiple files]\n")
parser.add_argument(f'-V', '--verbose',action='store_true', help='enable verbose terminal output')
parser.add_argument('-f', '--file', action="store_true", help='check the file type only (before analyse)')
parser.add_argument('-v', '--version', action="version", help="show version info", version=f"\033[0;101m\nSRE {__version__}\033[0m\n2023 Release")
parser.add_argument('-i', '--info', action="store_true", help='show author, email and url info')
parser.add_argument('-l', '--license', action="store_true", help='show license info')
args = parser.parse_args()
parser.error = invalid_options
# Parameter check
if len(sys.argv) == 1:
parser.print_help()
sys.exit()
# Requried argument for verbose mode
if args.verbose:
if not args.filename:
print("\n\033[32;5m\033[1;31mError:\033[0m the following arguments are required: \033[0;92mfilename\033[0m")
sys.exit()
# Print author info
if args.info:
print(f"\n\033[1;96mAuthor: \033[0;37m{__author__}, Copyright (C) 2023 \033[0m")
print(f"\033[1;96mEmail: \033[0m\033[0;37m{__email__}\033[0m")
print(f"\033[1;96mWebsite: \033[0m\033[0;37m{__url__} \033[0m\n\n")
sys.exit()
# Print license info
if args.license:
print(f"\n\033[0;107m\033[1;35m === Creative Commons Zero [CCO] v1.0 Universal License ===\033[0m")
print(f"\033[1;93m \t {show_license}\033[0m\n")
sys.exit()
# Check if the provided input is a file or folder
if args.filename:
if os.path.isfile(args.filename):
files_to_analyze = [args.filename]
elif os.path.isdir(args.filename):
files_to_analyze = [os.path.join(args.filename, file) for file in os.listdir(args.filename)]
else:
print("\n\t\033[0;107m\033[1;31mInvalid Path. Give a valid file / folder path. Try '--help' to know more!\033[0m")
exit(1)
# Print file type and MIME
if args.file:
if not args.filename:
print("\n\033[32;5m\033[1;31mError:\033[0m the following arguments are required: \033[0;92mfilename\033[0m")
sys.exit(1)
else:
for filename in args.filename:
file_type = magic.from_file(args.filename)
file_mime = magic.from_file(args.filename, mime = True)
file_type_parts = file_type.split(",")
try:
if "PE32" in file_type or "PE32+" in file_type or "DLL" in file_type:
print(f"\n\033[0;33mIdentifying filetype\033[0m\033[1;91m\033[32;5m _\033[0m ")
for part in file_type_parts:
if "PE32" in part or "Intel" in part:
print(f" \033[0;33mFile Type \033[0;96m>> \033[0m {part.strip()}")
print(f" \033[0;33mMIME Type \033[0;96m>> \033[0m {file_mime}")
print(f" \033[1;32mSupported File Type! Proceed to SRE.\033[0m\n")
sys.exit(1)
else:
print(f"\n\033[0;33mIdentifying filetype\033[0m\033[1;91m\033[32;5m _\033[0m")
print(f" \033[0;33mFile Type \033[0;96m>> \033[0m {file_type}")
print(f" \033[0;33mMIME Type \033[0;96m>>\033[0m {file_mime}")
print(f" \033[47m \033[1;91mUnsupported File Type! \033[0m")
sys.exit(1)
except Exception as e:
print("\n\t\033[0;107m\033[1;31mInvalid Path. Give a valid file / folder path. Try '--help' to know more!\033[0m")
sys.exit(1)
# Create a directory to store the analysis results
output_dir = f"analysis_result_{os.path.splitext(os.path.basename(args.filename))[0]}"
os.makedirs(output_dir, exist_ok=True)
# Iterate over the files and perform analysis
for file_path in files_to_analyze:
file_name = os.path.splitext(os.path.basename(file_path))[0]
# verbose check
if args.verbose:
try:
file_type = magic.from_file(file_path)
print(f"\nIdentifying Filetype\033[4;33m\033[0m...", end=" ", flush=True)
if "PE32" in file_type or "PE32+" in file_type or "DLL" in file_type:
print("\033[0;92mDone!\033[0m")
print(f"\nAnalysing \033[4;33m{file_name}\033[0m\033[1;91m\033[32;5m _\033[0m")
from integrity_analyse import calculate_file_hashes
from metadata_analyse import analyze_metadata
from strings_analyse import analyze_strings
from api_analyse import analyze_apis
from packer_detections import detect_packers
from ioc_extracts import extract_iocs
from malicious_behavior_analyse import analyze_malicious_behavior
from disasm_extracts import extract_disassembly
from vt_checks import check_virustotal
from vt_check_json import check_vt_advanced
from vt_check_adv import extract_vt_details
# Perform file integrity analysis
try:
print(" Extracting Hashes...", end=" ", flush=True)
integrity_output = os.path.join(output_dir, f"{file_name}_integrity_hashes.txt")
calculate_file_hashes(file_path, integrity_output)
print("\033[0;92mDone!\033[0m")
except Exception as e:
print(f"An error occurred: {e}")
# Perform metadata analysis
try:
print(" Extracting Metadata...", end=" ", flush=True)
metadata_output = os.path.join(output_dir, f"{file_name}_metadata.txt")
analyze_metadata(file_path, metadata_output)
print("\033[0;92mDone!\033[0m")
except Exception as e:
print(f"An error occurred: {e}")
# Perform string analysis
try:
print(" Extracting Strings...", end=" ", flush=True)
string_output = os.path.join(output_dir, f"{file_name}_strings.txt")
analyze_strings(file_path, string_output)
print("\033[0;92mDone!\033[0m")
except Exception as e:
print(f"An error occurred: {e}")
# Perform API analysis
try:
print(" Extracting APIs...", end=" ", flush=True)
api_output = os.path.join(output_dir, f"{file_name}_apis.txt")
analyze_apis(file_path, api_output)
print("\033[0;92mDone!\033[0m")
except Exception as e:
print(f"An error occurred: {e}")
# Perform packer detection
try:
print(" Extracting Packer Data...", end=" ", flush=True)
packer_output = os.path.join(output_dir, f"{file_name}_packer_detection.txt")
detect_packers(file_path, packer_output)
print("\033[0;92mDone!\033[0m")
except Exception as e:
print(f"An error occurred: {e}")
# Perform IOC extraction
try:
print(" Extracting IOCs...", end=" ", flush=True)
ioc_output = os.path.join(output_dir, f"{file_name}_iocs.txt")
extract_iocs(file_path, ioc_output)
print("\033[0;92mDone!\033[0m")
except Exception as e:
print(f"An error occurred: {e}")
# Perform malicious behavior analysis
try:
print(" Extracting Malicious Behaviours...", end=" ", flush=True)
malicious_behavior_output = os.path.join(output_dir, f"{file_name}_malicious_behavior.txt")
analyze_malicious_behavior(file_path, malicious_behavior_output)
print("\033[0;92mDone!\033[0m")
except Exception as e:
print(f"An error occurred: {e}")
# Perform Disassembly Code Extraction
try:
print(" Extracting Disassembly...", end=" ", flush=True)
disasm_output = os.path.join(output_dir, f"{file_name}_disassembly_code.txt")
extract_disassembly(file_path, disasm_output)
print("\033[0;92mDone!\033[0m")
except Exception as e:
print(f"An error occurred: {e}")
# Perform VirusTotal Check
try:
print(" Checking with VirusTotal...", end=" ", flush=True)
vt_output = os.path.join(output_dir, f"{file_name}_virustotal_check.txt")
check_virustotal(hashlib.sha256(open(file_path, "rb").read()).hexdigest(), vt_output)
print("\033[0;92mDone!\033[0m")
except Exception as e:
print(f"An error occurred: {e}")
# Import VT advanced JSON data (behaviours)
try:
vt_output = os.path.join(output_dir, f"{file_name}_virustotal_adv.json")
check_vt_advanced(hashlib.sha256(open(file_path, "rb").read()).hexdigest(), vt_output)
except Exception as e:
print(f"An error occurred: {e}")
# Extract JSON into readable TXT format
try:
vt_txt_output = os.path.join(output_dir, f"{file_name}_virustotal_check.txt")
extract_vt_details(vt_output, vt_txt_output)
except Exception as e:
print(f"An error occurred: {e}")
else:
print(f" \033[47m \033[1;91mUnsupported!\033[0m\n\n \033[1;97mOnly PE32/Executable & DLL file formates Supported.\033[0m\n\n")
sys.exit()
except Exception as e:
print(f"An error occurred: {e}")
sys.exit()
else:
try:
file_type = magic.from_file(file_path)
if "PE32" in file_type or "PE32+" in file_type or "DLL" in file_type:
print(f"\nAnalysing \033[4;33m{file_name}\033[0m\033[1;91m\033[32;5m _\033[0m")
from integrity_analyse import calculate_file_hashes
from metadata_analyse import analyze_metadata
from strings_analyse import analyze_strings
from api_analyse import analyze_apis
from packer_detections import detect_packers
from ioc_extracts import extract_iocs
from malicious_behavior_analyse import analyze_malicious_behavior
from disasm_extracts import extract_disassembly
from vt_checks import check_virustotal
from vt_check_json import check_vt_advanced
from vt_check_adv import extract_vt_details
# Perform file integrity analysis
try:
integrity_output = os.path.join(output_dir, f"{file_name}_integrity_hashes.txt")
calculate_file_hashes(file_path, integrity_output)
except Exception as e:
print(f"An error occurred: {e}")
# Perform metadata analysis
try:
metadata_output = os.path.join(output_dir, f"{file_name}_metadata.txt")
analyze_metadata(file_path, metadata_output)
except Exception as e:
print(f"An error occurred: {e}")
# Perform string analysis
try:
string_output = os.path.join(output_dir, f"{file_name}_strings.txt")
analyze_strings(file_path, string_output)
except Exception as e:
print(f"An error occurred: {e}")
# Perform API analysis
try:
api_output = os.path.join(output_dir, f"{file_name}_apis.txt")
analyze_apis(file_path, api_output)
except Exception as e:
print(f"An error occurred: {e}")
# Perform packer detection
try:
packer_output = os.path.join(output_dir, f"{file_name}_packer_detection.txt")
detect_packers(file_path, packer_output)
except Exception as e:
print(f"An error occurred: {e}")
# Perform IOC extraction
try:
ioc_output = os.path.join(output_dir, f"{file_name}_iocs.txt")
extract_iocs(file_path, ioc_output)
except Exception as e:
print(f"An error occurred: {e}")
# Perform malicious behavior analysis
try:
malicious_behavior_output = os.path.join(output_dir, f"{file_name}_malicious_behavior.txt")
analyze_malicious_behavior(file_path, malicious_behavior_output)
except Exception as e:
print(f"An error occurred: {e}")
# Perform Disassembly Code Extraction
try:
disasm_output = os.path.join(output_dir, f"{file_name}_disassembly_code.txt")
extract_disassembly(file_path, disasm_output)
except Exception as e:
print(f"An error occurred: {e}")
# Perform VirusTotal Check
try:
vt_output = os.path.join(output_dir, f"{file_name}_virustotal_check.txt")
check_virustotal(hashlib.sha256(open(file_path, "rb").read()).hexdigest(), vt_output)
except Exception as e:
print(f"An error occurred: {e}")
# Import VT advanced JSON data (behaviours)
try:
vt_output = os.path.join(output_dir, f"{file_name}_virustotal_adv.json")
check_vt_advanced(hashlib.sha256(open(file_path, "rb").read()).hexdigest(), vt_output)
except Exception as e:
print(f"An error occurred: {e}")
# Extract JSON into text format
try:
vt_txt_output = os.path.join(output_dir, f"{file_name}_virustotal_check.txt")
extract_vt_details(vt_output, vt_txt_output)
except Exception as e:
print(f"An error occurred: {e}")
else:
print(f"\nIdentifying Filetype\033[4;33m\033[0m...", end=" ", flush=True)
print(f" \033[47m \033[1;91mUnsupported!\033[0m\n\n \033[1;97mOnly PE32/Executable & DLL file formates Supported.\033[0m\n\n")
sys.exit()
except Exception as e:
print(f"An error occurred: {e}")
sys.exit()
for i in range(1000000):
pass
end_time = time.time()
# Calculate the total execution time
total_time_count = end_time - start_time
total_time = str(timedelta(seconds=total_time_count)).split('.')[0]
# Print the total execution time in a readable format
print(f"\n\033[0;36m >> Extracted in [HH:MM:SS]: {total_time} \033[0m")
print(f"\nAnalysis \033[33;5m\033[1;32mcompleted\033[0m & the outcome placed in\033[1;33m 'analysis_result_{os.path.splitext(os.path.basename(args.filename))[0]}'\033[0m folder.\n")
print(f"\t\t\033[0;101m \033[1;97m >>> Happy \033[40mS\033[0;101m\033[1;97mtatic \033[40mR\033[0;101m\033[1;97meverse \033[40mE\033[0;101m\033[1;97mngineering <<< \033[0m\n")