-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathutils.py
242 lines (184 loc) · 6.01 KB
/
utils.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
238
239
240
241
242
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2016 Fedele Mantuano (https://www.linkedin.com/in/fmantuano/)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import hashlib
import logging
import magic
import os
import patoolib
import six
import ssdeep
import tempfile
from collections import namedtuple
try:
from functools import lru_cache
except ImportError:
from backports.functools_lru_cache import lru_cache
try:
from modules import urls_extractor
except ImportError:
from ...modules import urls_extractor
log = logging.getLogger(__name__)
@lru_cache()
def fingerprints(data):
"""This function return the fingerprints of data.
Args:
data (string): raw data
Returns:
namedtuple: fingerprints md5, sha1, sha256, sha512, ssdeep
"""
Hashes = namedtuple('Hashes', "md5 sha1 sha256 sha512 ssdeep")
if six.PY2:
if not isinstance(data, str):
data = data.encode("utf-8")
elif six.PY3:
if not isinstance(data, bytes):
data = data.encode("utf-8")
# md5
md5 = hashlib.md5()
md5.update(data)
md5 = md5.hexdigest()
# sha1
sha1 = hashlib.sha1()
sha1.update(data)
sha1 = sha1.hexdigest()
# sha256
sha256 = hashlib.sha256()
sha256.update(data)
sha256 = sha256.hexdigest()
# sha512
sha512 = hashlib.sha512()
sha512.update(data)
sha512 = sha512.hexdigest()
# ssdeep
ssdeep_ = ssdeep.hash(data)
return Hashes(md5, sha1, sha256, sha512, ssdeep_)
def check_archive(data, write_sample=False):
"""Check if data is an archive.
Args:
data (string): raw data
write_sample (boolean): if True it writes sample on disk
Returns:
boolean: only True is archive (False otherwise)
if write_sample is False
tuple (boolean, string): True is archive (False otherwise) and
sample path
"""
is_archive = True
temp = tempfile.mkstemp()[-1]
try:
with open(temp, 'wb') as f:
f.write(data)
except UnicodeEncodeError:
with open(temp, 'wb') as f:
f.write(data.encode("utf-8"))
try:
patoolib.test_archive(temp, verbosity=-1)
except Exception:
is_archive = False
finally:
if not write_sample:
os.remove(temp)
temp = None
return is_archive, temp
@lru_cache()
def contenttype(payload):
mime = magic.Magic(mime=True)
return mime.from_buffer(payload)
def extension(filename):
ext = os.path.splitext(filename)
return ext[-1].lower()
def reformat_virustotal(report):
"""This function replace the VirusTotal report standard with a
new one. The new report has only detected antivirus with scans in list
and not in a dict (more readable in Elasticsearch)
Args:
report (dict): standard VirusTotal report
Returns:
This function changes the given report
"""
if report:
scans = []
try:
for k, v in report["results"]["scans"].items():
if v["detected"]:
v["antivirus"] = k
scans.append(v)
v.pop("detected")
except KeyError:
pass
else:
report["results"]["scans"] = scans
def write_sample(binary, payload, path, filename, hash_):
"""
This function writes a sample on file system.
Args:
binary (bool): True if it's a binary file
payload: payload of sample, in base64 if it's a binary
path (string): path of file
filename (string): name of file
hash_ (string): file hash
"""
if not os.path.exists(path):
os.makedirs(path)
try:
sample = os.path.join(path, "{}_{}".format(hash_, filename))
if binary:
with open(sample, "wb") as f:
f.write(payload.decode("base64"))
else:
with open(sample, "w") as f:
f.write(payload.encode("utf-8"))
except (UnicodeError, IOError):
log.warning("UnicodeError/IOError for sample {!r}".format(hash_))
# Remove old file failed
try:
remove_file(sample)
except UnboundLocalError:
pass
try:
sample = os.path.join(path, hash_)
if binary:
with open(sample, "wb") as f:
f.write(payload.decode("base64"))
else:
with open(sample, "w") as f:
f.write(payload.encode("utf-8"))
except UnicodeError:
log.warning("UnicodeError for sample {!r}".format(hash_))
# Remove old file failed
remove_file(sample)
# content_transfer_encoding': u'x-uuencode'
# it's not binary with strange encoding
with open(sample + "_failed_write.txt", "w") as f:
f.write("UnicodeError - Search sample on output report")
def remove_file(file_path):
try:
os.remove(file_path)
except OSError:
pass
def get_urls_tika(attachments, faup):
"""
This function extracts the urls from Apache Tika analysis
Args:
attachments (list): attachments list from SpamScope analysis
faup: Faup object
Returns:
a dict with a key for every second-level domain and
value a list of disassembled urls (output Faup tool).
"""
for i in attachments:
if i.get("tika", False):
content = i["tika"].get("X-TIKA:content", six.text_type())
return urls_extractor(content, faup)