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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
|
###############################################################################
# #
# Peekaboo Extended Email Attachment Behavior Observation Owl #
# #
# sample.py #
###############################################################################
# #
# Copyright (C) 2016-2018 science + computing ag #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or (at #
# your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, but #
# WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #
# General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
###############################################################################
import os
import hashlib
import re
import errno
import shutil
import logging
from datetime import datetime
from peekaboo.config import get_config
from peekaboo.exceptions import CuckooReportPendingException, \
CuckooAnalysisFailedException
from peekaboo.toolbox.sampletools import SampleMetaInfo, ConnectionMap, next_job_hash
from peekaboo.toolbox.files import chown2me, guess_mime_type_from_file_contents
from peekaboo.toolbox.ms_office import has_office_macros
from peekaboo.toolbox.cuckoo import submit_to_cuckoo
import peekaboo.ruleset as ruleset
logger = logging.getLogger(__name__)
def make_sample(file, socket):
"""
Create a Sample object from a given file.
:param file: Path to the file to create a Sample object from.
:param socket: An optional socket to write the report to.
:return: A sample object representing the given file or None if the file does not exist.
"""
logger.debug("Looking at file %s" % file)
if not os.path.isfile(file):
logger.debug('%s is not a file' % file)
return None
s = Sample(file, socket)
logger.debug('Created sample %s' % s)
return s
class Sample(object):
"""
This class handles and describes samples to be analysed by Peekaboo.
A sample has attributes like:
filename, MIME type, sha256, ...
Those attributes are determined on demand kept in a dictionary, which is
accessible through the methods has_attr, get_attr, and set_attr.
The data structure works together with Cuckoo to run behavioral attributes.
@author: Felix Bauer
@author: Sebastian Deiss
"""
def __init__(self, file_path, sock=None):
self.__path = file_path
self.__config = get_config()
self.__db_con = self.__config.get_db_con()
self.__meta_info = None
self.__wd = None
self.__filename = os.path.basename(self.__path)
# A symlink that points to the actual file named
# sha256sum.suffix
self.__symlink = None
self.__result = ruleset.Result.unchecked
self.__report = [] # Peekaboo's own report
self.__socket = sock
# Additional attributes for a sample object (e. g. meta info)
self.__attributes = {}
self.initialized = False
self.meta_info_loaded = False
def init(self):
"""
Initialize the Sample object.
The actual initialization is done here, because the main thread should
not do the heavy lifting of e. g. parsing the meta info file to be able
to accept new connections as quickly as possible.
Instead, it only adds the sample objects to the queue and the workers
to the actual initialization.
"""
if self.initialized:
return
logger.debug("initializing sample")
job_hash = self.get_job_hash()
self.__wd = os.path.join(self.__config.sample_base_dir, job_hash)
chown2me()
meta_info_file = os.path.join(self.__wd, self.__filename + '.info')
self.set_attr('meta_info_file', meta_info_file)
self.load_meta_info(meta_info_file)
try:
self.__create_symlink()
except OSError:
pass
self.initialized = True
# Add sample to database with state 'inProgress' if the sample is unknown
# to avoid multiple concurrent analysis.
self.__result = ruleset.Result.inProgress
self.__db_con.analysis2db(self)
message = "Datei \"%s\" %s wird analysiert\n" % (self.__filename,
self.sha256sum)
self.__report.append(message)
self.__send_message(message)
def get_attr(self, key):
"""
Get a sample attribute by a specified key.
:param key: The identifier of the sample attribute to get.
"""
if self.has_attr(key):
return self.__attributes[key]
raise KeyError("Attribute for key '%s' not found." % key)
def set_attr(self, key, val, override=True):
"""
Add an attribute to a sample.
:param key: The identifier of the attribute.
:param val: The attribute to add.
:param override: Whether the existing attribute shall be overwritten or not.
"""
if self.has_attr(key) and override is False:
raise KeyError("Key '%s' already exists." % key)
self.__attributes[key] = val
def has_attr(self, key):
"""
Check if an attribute exists for this sample.
:param key: The identifier of the attribute.
"""
if key in self.__attributes.keys():
return True
return False
def remove_attr(self, key):
"""
Delete an attribute for this sample.
:param key: The identifier of the attribute
:raises ValueError if the given key was not found in
the attributes dictionary.
"""
if key in self.__attributes.keys():
del self.__attributes[key]
raise ValueError('No attribute named "%s" found.' % key)
def get_file_path(self):
return self.__path
def get_filename(self):
return self.__filename
def get_result(self):
return self.__result
def get_peekaboo_report(self):
return ''.join(self.__report)
def get_job_hash(self):
job_hash = re.sub(self.__config.job_hash_regex, r'\1',
self.__path)
if job_hash == self.__path:
# regex did not match.
# so we generate our own job hash and create the
# working directory.
job_hash = next_job_hash()
os.mkdir(os.path.join(self.__config.sample_base_dir,
job_hash))
logger.debug("Job hash for this sample: %s" % job_hash)
return job_hash
def load_meta_info(self, meta_info_file):
try:
self.__meta_info = SampleMetaInfo(meta_info_file)
logger.debug('Parsing meta info file %s for file %s' % (meta_info_file, self.__path))
# Add the information from the dump info file as attributes to the sample object.
for info in self.__meta_info.get_all().items('attachment'):
logger.debug('meta_info_%s = %s' % (info[0], info[1]))
self.set_attr('meta_info_' + info[0], info[1])
self.meta_info_loaded = True
except Exception:
logger.info('No metadata available for file %s' % self.__path)
def save_result(self):
if self.__db_con.known(self):
logger.debug('Known sample info not logged to database')
else:
logger.debug('Saving results to database')
self.__db_con.sample_info_update(self)
if self.__socket is not None:
ConnectionMap.remove(self.__socket, self)
if not ConnectionMap.has_connection(self.__socket):
self.__cleanup_temp_files()
self.__close_socket()
def add_rule_result(self, res):
logger.debug('Adding rule result %s' % str(res))
rule_results = []
if self.has_attr('rule_results'):
rule_results = self.get_attr('rule_results')
rule_results.append(res)
self.set_attr('rule_results', rule_results)
def determine_result(self):
for rule_result in self.get_attr('rule_results'):
logger.debug("Current result: %s, Rule result: %s"
% (self.__result, rule_result.result))
# check if result of this rule is worse than what we know so far
if rule_result.result > self.__result:
self.__result = rule_result.result
self.set_attr('reason', rule_result.reason)
def report(self):
"""
Create the report for this sample. The report is saved as a list of
strings and is available via get_peekaboo_report(). Also, if a socket connection was
supplied to the sample the report messages are also written to the socket.
"""
# TODO: move to rule processing engine.
self.determine_result()
for rule_result in self.get_attr('rule_results'):
message = "Datei \"%s\": %s\n" % (self.__filename, str(rule_result))
self.__report.append(message)
self.__send_message(message)
if self.__result == ruleset.Result.inProgress:
logger.warning('Ruleset result forces to unchecked.')
self.__result = ruleset.Result.unchecked
message = "Die Datei \"%s\" wurde als \"%s\" eingestuft\n\n" \
% (self.__filename, self.__result.name)
self.__report.append(message)
self.__send_message(message)
@property
def sha256sum(self):
if not self.has_attr('sha256sum'):
with open(self.__path, 'rb') as f:
checksum = hashlib.sha256(f.read()).hexdigest()
self.set_attr('sha256sum', checksum)
return checksum
return self.get_attr('sha256sum')
@property
def known(self):
_known = self.__db_con.known(self)
if _known:
self.set_attr('known', True)
return True
return False
@property
def file_extension(self):
if self.has_attr('meta_info_name_declared'):
file_ext = self.get_attr('meta_info_name_declared').spli
|