forked from cuckoosandbox/cuckoo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic.py
More file actions
347 lines (294 loc) · 12.2 KB
/
Copy pathstatic.py
File metadata and controls
347 lines (294 loc) · 12.2 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
# Copyright (C) 2010-2015 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import datetime
import logging
import os
import re
try:
import magic
HAVE_MAGIC = True
except ImportError:
HAVE_MAGIC = False
try:
import pefile
import peutils
HAVE_PEFILE = True
except ImportError:
HAVE_PEFILE = False
try:
import M2Crypto
HAVE_MCRYPTO = True
except ImportError:
HAVE_MCRYPTO = False
from lib.cuckoo.common.abstracts import Processing
from lib.cuckoo.common.constants import CUCKOO_ROOT
from lib.cuckoo.common.objects import File
from lib.cuckoo.common.utils import convert_to_printable
log = logging.getLogger(__name__)
# Partially taken from
# http://malwarecookbook.googlecode.com/svn/trunk/3/8/pescanner.py
class PortableExecutable(object):
"""PE analysis."""
def __init__(self, file_path):
"""@param file_path: file path."""
self.file_path = file_path
self.pe = None
def _get_filetype(self, data):
"""Gets filetype, uses libmagic if available.
@param data: data to be analyzed.
@return: file type or None.
"""
if not HAVE_MAGIC:
return None
try:
ms = magic.open(magic.MAGIC_NONE)
ms.load()
file_type = ms.buffer(data)
except:
try:
file_type = magic.from_buffer(data)
except Exception:
return None
finally:
try:
ms.close()
except:
pass
return file_type
def _get_peid_signatures(self):
"""Gets PEID signatures.
@return: matched signatures or None.
"""
try:
sig_path = os.path.join(CUCKOO_ROOT, "data",
"peutils", "UserDB.TXT")
signatures = peutils.SignatureDatabase(sig_path)
return signatures.match(self.pe, ep_only=True)
except:
return None
def _get_imported_symbols(self):
"""Gets imported symbols.
@return: imported symbols dict or None.
"""
imports = []
if hasattr(self.pe, "DIRECTORY_ENTRY_IMPORT"):
for entry in self.pe.DIRECTORY_ENTRY_IMPORT:
try:
symbols = []
for imported_symbol in entry.imports:
symbol = {}
symbol["address"] = hex(imported_symbol.address)
symbol["name"] = imported_symbol.name
symbols.append(symbol)
imports_section = {}
imports_section["dll"] = convert_to_printable(entry.dll)
imports_section["imports"] = symbols
imports.append(imports_section)
except:
continue
return imports
def _get_exported_symbols(self):
"""Gets exported symbols.
@return: exported symbols dict or None.
"""
exports = []
if hasattr(self.pe, "DIRECTORY_ENTRY_EXPORT"):
for exported_symbol in self.pe.DIRECTORY_ENTRY_EXPORT.symbols:
symbol = {}
symbol["address"] = hex(self.pe.OPTIONAL_HEADER.ImageBase +
exported_symbol.address)
symbol["name"] = exported_symbol.name
symbol["ordinal"] = exported_symbol.ordinal
exports.append(symbol)
return exports
def _get_sections(self):
"""Gets sections.
@return: sections dict or None.
"""
sections = []
for entry in self.pe.sections:
try:
section = {}
section["name"] = convert_to_printable(entry.Name.strip("\x00"))
section["virtual_address"] = "0x{0:08x}".format(entry.VirtualAddress)
section["virtual_size"] = "0x{0:08x}".format(entry.Misc_VirtualSize)
section["size_of_data"] = "0x{0:08x}".format(entry.SizeOfRawData)
section["entropy"] = entry.get_entropy()
sections.append(section)
except:
continue
return sections
def _get_resources(self):
"""Get resources.
@return: resources dict or None.
"""
resources = []
if hasattr(self.pe, "DIRECTORY_ENTRY_RESOURCE"):
for resource_type in self.pe.DIRECTORY_ENTRY_RESOURCE.entries:
try:
resource = {}
if resource_type.name is not None:
name = str(resource_type.name)
else:
name = str(pefile.RESOURCE_TYPE.get(resource_type.struct.Id))
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 = self.pe.get_data(resource_lang.data.struct.OffsetToData, resource_lang.data.struct.Size)
filetype = self._get_filetype(data)
language = pefile.LANG.get(resource_lang.data.lang, None)
sublanguage = pefile.get_sublang_name_for_lang(resource_lang.data.lang, resource_lang.data.sublang)
resource["name"] = name
resource["offset"] = "0x{0:08x}".format(resource_lang.data.struct.OffsetToData)
resource["size"] = "0x{0:08x}".format(resource_lang.data.struct.Size)
resource["filetype"] = filetype
resource["language"] = language
resource["sublanguage"] = sublanguage
resources.append(resource)
except:
continue
return resources
def _get_versioninfo(self):
"""Get version info.
@return: info dict or None.
"""
infos = []
if hasattr(self.pe, "VS_VERSIONINFO"):
if hasattr(self.pe, "FileInfo"):
for entry in self.pe.FileInfo:
try:
if hasattr(entry, "StringTable"):
for st_entry in entry.StringTable:
for str_entry in st_entry.entries.items():
entry = {}
entry["name"] = convert_to_printable(str_entry[0])
entry["value"] = convert_to_printable(str_entry[1])
infos.append(entry)
elif hasattr(entry, "Var"):
for var_entry in entry.Var:
if hasattr(var_entry, "entry"):
entry = {}
entry["name"] = convert_to_printable(var_entry.entry.keys()[0])
entry["value"] = convert_to_printable(var_entry.entry.values()[0])
infos.append(entry)
except:
continue
return infos
def _get_imphash(self):
"""Gets imphash.
@return: imphash string or None.
"""
try:
return self.pe.get_imphash()
except AttributeError:
return None
def _get_timestamp(self):
"""Get compilation timestamp.
@return: timestamp or None.
"""
try:
pe_timestamp = self.pe.FILE_HEADER.TimeDateStamp
except AttributeError:
return None
dt = datetime.datetime.fromtimestamp(pe_timestamp)
return dt.strftime("%Y-%m-%d %H:%M:%S")
def _get_pdb_path(self):
"""Get the path to any available debugging symbols."""
try:
for entry in getattr(self.pe, "DIRECTORY_ENTRY_DEBUG", []):
raw_offset = entry.struct.PointerToRawData
size_data = entry.struct.SizeOfData
debug_data = self.pe.__data__[raw_offset:raw_offset+size_data]
if debug_data.startswith("RSDS"):
return debug_data[24:].strip("\x00")
except:
log.exception("Exception parsing PDB path")
def _get_signature(self):
"""If this executable is signed, get its signature(s)."""
dir_index = pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_SECURITY"]
if len(self.pe.OPTIONAL_HEADER.DATA_DIRECTORY) < dir_index:
return []
dir_entry = self.pe.OPTIONAL_HEADER.DATA_DIRECTORY[dir_index]
if not dir_entry or not dir_entry.VirtualAddress or not dir_entry.Size:
return []
if not HAVE_MCRYPTO:
log.critical("You do not have the m2crypto library installed "
"preventing certificate extraction: "
"pip install m2crypto")
return []
signatures = self.pe.write()[dir_entry.VirtualAddress+8:]
bio = M2Crypto.BIO.MemoryBuffer(signatures)
if not bio:
return []
pkcs7_obj = M2Crypto.m2.pkcs7_read_bio_der(bio.bio_ptr())
if not pkcs7_obj:
return []
ret = []
p7 = M2Crypto.SMIME.PKCS7(pkcs7_obj)
for cert in p7.get0_signers(M2Crypto.X509.X509_Stack()) or []:
subject = cert.get_subject()
ret.append({
"serial_number": "%032x" % cert.get_serial_number(),
"common_name": subject.CN,
"country": subject.C,
"locality": subject.L,
"organization": subject.O,
"email": subject.Email,
"sha1": "%040x" % int(cert.get_fingerprint("sha1"), 16),
"md5": "%032x" % int(cert.get_fingerprint("md5"), 16),
})
if subject.GN and subject.SN:
ret[-1]["full_name"] = "%s %s" % (subject.GN, subject.SN)
elif subject.GN:
ret[-1]["full_name"] = subject.GN
elif subject.SN:
ret[-1]["full_name"] = subject.SN
return ret
def run(self):
"""Run analysis.
@return: analysis results dict or None.
"""
if not os.path.exists(self.file_path):
return {}
try:
self.pe = pefile.PE(self.file_path)
except pefile.PEFormatError:
return {}
results = {}
results["peid_signatures"] = self._get_peid_signatures()
results["pe_imports"] = self._get_imported_symbols()
results["pe_exports"] = self._get_exported_symbols()
results["pe_sections"] = self._get_sections()
results["pe_resources"] = self._get_resources()
results["pe_versioninfo"] = self._get_versioninfo()
results["pe_imphash"] = self._get_imphash()
results["pe_timestamp"] = self._get_timestamp()
results["pdb_path"] = self._get_pdb_path()
results["signature"] = self._get_signature()
results["imported_dll_count"] = len([x for x in results["pe_imports"] if x.get("dll")])
return results
class Static(Processing):
"""Static analysis."""
PUBKEY_RE = "(-----BEGIN PUBLIC KEY-----[a-zA-Z0-9\\n\\+/]+-----END PUBLIC KEY-----)"
PRIVKEY_RE = "(-----BEGIN RSA PRIVATE KEY-----[a-zA-Z0-9\\n\\+/]+-----END RSA PRIVATE KEY-----)"
def run(self):
"""Run analysis.
@return: results dict.
"""
self.key = "static"
static = {}
if self.task["category"] == "file" and os.path.exists(self.file_path):
if HAVE_PEFILE:
if "PE32" in File(self.file_path).get_type():
static.update(PortableExecutable(self.file_path).run())
static["keys"] = self._get_keys()
return static
def _get_keys(self):
"""Get any embedded plaintext public and/or private keys."""
buf = open(self.file_path).read()
ret = set()
ret.update(re.findall(self.PUBKEY_RE, buf))
ret.update(re.findall(self.PRIVKEY_RE, buf))
return list(ret)