/
malware-analyses.py
237 lines (173 loc) · 8.43 KB
/
malware-analyses.py
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
#!/usr/bin/env python
import sys, getopt, hashlib, subprocess, simplejson, urllib, urllib2, os, pefile, math, datetime
from create_html import createFile, closeFile, insertSeperator
# Change here your VirusTotal API Key *Public API limited to 4 requests per minute*
vtapikey = ''
# VirusTotal URL
vturl = "https://www.virustotal.com/vtapi/v2/file/report"
# VirusTotal Analysis URL
vtanalysisurl = "https://www.virustotal.com/file/"
# Current path
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
def getList(filename):
fname = open(filename, 'r')
wlist = fname.read().split('\n')
fname.close
return wlist
def calcChecksum(f):
md5 = hashlib.md5()
sha1 = hashlib.sha1()
sha256 = hashlib.sha256()
sha512 = hashlib.sha512()
while True:
data = f.read(128)
if not data:
break
md5.update(data)
sha1.update(data)
sha256.update(data)
sha512.update(data)
return md5.hexdigest(), sha1.hexdigest(), sha256.hexdigest(), sha512.hexdigest()
def queryVT(md5):
parameters = {"resource": md5, "apikey": vtapikey}
data = urllib.urlencode(parameters)
req = urllib2.Request(vturl, data)
response = urllib2.urlopen(req)
json = response.read()
return simplejson.loads(json)
def getEntropy(data):
"""Ripped from Immunity Debugger"""
if not data:
return 0
entropy = 0
for x in range(256):
p_x = float(data.count(chr(x))) / len(data)
if p_x > 0:
entropy += - p_x * math.log(p_x, 2)
return entropy
def startAnalyses():
version()
try:
opts, args = getopt.getopt(sys.argv[1:], "hf:", ["help", "file="])
except getopt.GetoptError:
help()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
help()
sys.exit()
elif opt in ("-f", "--file"):
filePath = arg
f = open(filePath)
html = createFile(filePath)
pe = pefile.PE(filePath)
# get the filetype by calling the external program file
filetype = subprocess.check_output(["file", "-b", filePath])
html.write("File Size: %s<br>\nFile Type: %s<br>\n" % (os.path.getsize(filePath), filetype))
html.write(
"Compilation timestamp: %s<br>\n" % (datetime.datetime.fromtimestamp(pe.FILE_HEADER.TimeDateStamp)))
insertSeperator(html)
html.write("<br><b><a id='version'>File Version Info:</a></b>\n<br>\n")
# from Ero Carrera's blog
for fileinfo in pe.FileInfo:
if fileinfo.Key == 'StringFileInfo':
for st in fileinfo.StringTable:
for entry in st.entries.items():
html.write("%s: %s<br>\n" % (entry[0], entry[1]))
if fileinfo.Key == 'VarFileInfo':
for var in fileinfo.Var:
html.write("%s: %s<br>\n" % var.entry.items()[0])
insertSeperator(html)
# calculate some Checksums
md5, sha1, sha256, sha512 = calcChecksum(f)
html.write(
"<br><b><a id='checksums'>File Checksums:</a></b>\n<br>\nMD5: %s<br>\nSHA1: %s<br>\nSHA256: %s<br>\nSHA512: %s<br>\n" % (
md5, sha1, sha256, sha512))
insertSeperator(html)
# create Virustotal Analysis Link
vtlink = vtanalysisurl + sha256 + "/analysis"
# request Results from Virustotal
try:
response_dict = queryVT(md5)
html.write("<br><b><a id='virus'>VirusTotal Results:</a></b><br>%s / %s<br><br><a href='%s' target='_blank'>VirusTotal Analysis Link</a><br>\n" % (
response_dict.get("positives"), response_dict.get("total"), vtlink))
except:
html.write("<br><b><a id='virus'>VirusTotal Results:</a></b><br>Error!<br>\n")
insertSeperator(html)
html.write("<br><b><a id='sections'>Sections:</a></b><br>\n")
html.write("Entrypoint: %s<br>Number of Sections: %i<br><br>\n" % (
hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint), len(pe.sections)))
html.write("<table><tr><th>Name</th> <th>Virtual address</th> <th>Virtual size</th> <th>Raw size</th> <th>Entropy</th></tr>\n")
for section in pe.sections:
e = getEntropy(section.get_data())
if e < 6.0:
a = "Not packed"
elif e < 7.0:
a = "Maybe packed"
else: # 7.0 .. 8.0
a = "Packed"
html.write("<tr><td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%.2f (%s)</td></tr>\n" % (
section.Name, hex(section.VirtualAddress), hex(section.Misc_VirtualSize), section.SizeOfRawData, e, a))
html.write("</table>\n")
insertSeperator(html)
susp_api = []
apis = getList(BASE_DIR + "/api.txt")
pe.parse_data_directories()
html.write("<br><b><a id='imports'>Imports:</a></b><br>\n")
for entry in pe.DIRECTORY_ENTRY_IMPORT:
html.write("<b>%s</b><br>\n" % entry.dll)
for imp in entry.imports:
html.write("%s %s<br>\n" % (hex(imp.address), imp.name))
if (imp.name != None) and (imp.name != ""):
for api in apis:
if imp.name.startswith(api):
susp_api.append(imp)
insertSeperator(html)
html.write("<br><b><a id='suspicious'>Suspicious APIs:</a></b><br>\n")
for imp in susp_api:
html.write("%s %s<br>\n" % (hex(imp.address), imp.name))
insertSeperator(html)
html.write("<br><b><a id='exports'>Exports:</a></b><br>\n")
try:
for exp in pe.DIRECTORY_ENTRY_EXPORT.symbols:
html.write("%s %s<br>\n" % (hex(pe.OPTIONAL_HEADER.ImageBase + exp.address), exp.name))
except:
html.write("No Exports found!<br>\n")
insertSeperator(html)
html.write("<br><b><a id='resources'>Resources:</a></b><br>\n")
html.write("<table><tr><th>Name</th> <th>Virtual address</th> <th>Virtual size</th> <th>Raw size</th> <th>Entropy</th></tr>\n")
for resource_type in pe.DIRECTORY_ENTRY_RESOURCE.entries:
if resource_type.name is not None:
name = "%s" % resource_type.name
print name
else:
name = "%s" % pefile.RESOURCE_TYPE.get(resource_type.struct.Id)
if name == None:
name = "%d" % resource_type.struct.Id
for resource_id in resource_type.directory.entries:
if hasattr(resource_type, 'directory'):
for resource_id in resource_type.directory.entries:
if hasattr(resource_id, 'directory'):
for resource_lang in resource_id.directory.entries:
data = pe.get_data(resource_lang.data.struct.OffsetToData, resource_lang.data.struct.Size)
lang = pefile.LANG.get(resource_lang.data.lang)
sublang = pefile.get_sublang_name_for_lang(resource_lang.data.lang, resource_lang.data.sublang)
html.write("<tr><td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td></tr>\n" % (name, hex(resource_lang.data.struct.OffsetToData), hex(resource_lang.data.struct.Size), lang, sublang))
html.write("</table>\n")
insertSeperator(html)
# get printable strings in the binary file by calling the external program strings
strings = subprocess.check_output(["strings", filePath])
html.write("<br><b><a id='strings'>Strings:</a></b><br>\n")
html.write("<br>\n".join(strings.split()))
def version():
sys.stdout.write("\nStatic Malware Analyses Script 0.5\n")
sys.stdout.write("Python script for Static Analyses of Malware\n")
sys.stdout.write("Author: Johannes Schroeter - www.devwerks.net\n\n")
def help():
sys.stdout.write("malware-analyses.py -f/--file FILEPATH\n")
sys.stdout.write("Example: malware-analyses.py -f test.exe\n")
def main():
startAnalyses()
sys.exit()
if __name__ == "__main__":
main()