summaryrefslogtreecommitdiffstats
path: root/peekaboo/sample.py
blob: c46d13c5fa223f473d3bb6ce6fb53e43cd5c4ede (plain)
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
###############################################################################
#                                                                             #
# Peekaboo Extended Email Attachment Behavior Observation Owl                 #
#                                                                             #
# sample.py                                                                   #
###############################################################################
#                                                                             #
# Copyright (C) 2016-2019  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 json
import random
import re
import shutil
import string
import logging
import tempfile
from datetime import datetime
from peekaboo.toolbox.files import guess_mime_type_from_file_contents, \
                                   guess_mime_type_from_filename
from peekaboo.toolbox.ms_office import has_office_macros
from peekaboo.ruleset import Result


logger = logging.getLogger(__name__)

class SampleFactory(object):
    """ A class for churning out loads of mostly identical sample objects.
    Contains all the global configuration data and object references each
    sample needs and thus serves as a registry of potential API breakage
    perhaps deserving looking into. """
    def __init__(self, cuckoo, base_dir, job_hash_regex,
                 keep_mail_data):
        # object references for interaction
        self.cuckoo = cuckoo

        # configuration
        self.base_dir = base_dir
        self.job_hash_regex = job_hash_regex
        self.keep_mail_data = keep_mail_data

    def make_sample(self, file_path, status_change=None, metainfo=None):
        """ Create a new Sample object based on the factory's configured
        defaults and variable parameters. """
        return Sample(file_path, self.cuckoo, status_change, metainfo,
                      self.base_dir, self.job_hash_regex, self.keep_mail_data)


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, cuckoo=None, status_change=None,
                 metainfo=None, base_dir=None, job_hash_regex=None,
                 keep_mail_data=False):
        self.__path = file_path
        self.__cuckoo = cuckoo
        self.__wd = None
        self.__filename = os.path.basename(self.__path)
        # A symlink that points to the actual file named
        # sha256sum.suffix
        self.__submit_path = None
        self.__cuckoo_job_id = -1
        self.__cuckoo_report = None
        self.__done = False
        self.__status_change = status_change
        self.__rule_results = []
        self.__result = Result.unchecked
        self.__reason = None
        self.__report = []  # Peekaboo's own report
        self.__internal_report = []
        # Additional attributes for a sample object (e. g. meta info)
        self.__attributes = {}
        self.__base_dir = base_dir
        self.__job_hash_regex = job_hash_regex
        self.__keep_mail_data = keep_mail_data
        self.initialized = False

        if metainfo:
            for field in metainfo:
                logger.debug('meta_info_%s = %s', field, metainfo[field])

                # JSON will transfer null/None values but we don't want them as
                # attributes in that case
                if metainfo[field] is not None:
                    self.set_attr('meta_info_' + field, metainfo[field])

    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")

        # create a symlink to submit the file with the correct file extension
        # to cuckoo via submit.py - but only if we can actually figure out an
        # extension. Otherwise the point is moot.
        self.__submit_path = self.__path
        file_ext = self.file_extension
        if file_ext:
            # create a temporary directory where mkdtemp makes sure that
            # creation is atomic, i.e. no other process is using it
            self.__wd = tempfile.mkdtemp(prefix = self.get_job_hash(),
                    dir = self.__base_dir)
            self.__submit_path = os.path.join(self.__wd,
                    '%s.%s' % (self.sha256sum, file_ext))

            logger.debug('ln -s %s %s' % (self.__path, self.__submit_path))
            os.symlink(self.__path, self.__submit_path)

        self.initialized = True

        message = "Datei \"%s\" %s wird analysiert" % (self.__filename,
                                                         self.sha256sum)
        self.__report.append(message)

        # log some additional info to report to aid debugging
        if self.has_attr('meta_info_name_declared'):
            self.__internal_report.append(
                "meta info: name_declared: %s" %
                self.get_attr('meta_info_name_declared'))

        if self.has_attr('meta_info_type_declared'):
            self.__internal_report.append(
                "meta info: type_declared: %s" %
                self.get_attr('meta_info_type_declared'))

    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_reason(self):
        return self.__reason

    @property
    def peekaboo_report(self):
        """ Return Peekaboo's report meant for the client, detailing what's
        been found on this sample.

        @type: List of strings.
        """
        return self.__report

    @property
    def internal_peekaboo_report(self):
        """ Return Peekaboo's internal report, some extra messages not meant
        for the client but useful for debugging.

        @type: List of strings.
        """
        return self.__internal_report

    @property
    def done(self):
        """ Tells whether the analysis of the sample is done, i.e. a final
        verdict has been reached and a result and reason are available. """
        return self.__done

    def mark_done(self):
        """ Mark this sample as done, i.e. fully analysed and verdict reached.
        """
        self.__done = True
        if self.__status_change:
            # notify whoever is interested that our status has changed
            self.__status_change.set()

    def generate_job_hash(self, size=8):
        """
        Generates a job hash (default: 8 characters).

        @param size: The amount of random characters to use for a job hash.
                     Defaults to 8.
        @return: a job hash consisting of a static prefix, a timestamp
                 representing the time when the method was invoked, and random
                 characters.
        """
        job_hash = 'peekaboo-run_analysis-'
        job_hash += '%s-' % datetime.now().strftime('%Y%m%dT%H%M%S')
        job_hash += ''.join(
            random.choice(string.digits + string.ascii_lowercase
                          + string.ascii_uppercase) for _ in range(size))
        return job_hash

    def get_job_hash(self):
        job_hash = re.sub(self.__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 = self.generate_job_hash()

        logger.debug("Job hash for this sample: %s" % job_hash)
        return job_hash

    def add_rule_result(self, res):
        logger.debug('Adding rule result %s' % str(res))
        self.__rule_results.append(res)

        logger.debug("Current overall result: %s, new rule result: %s",
                     self.__result, res.result)
        # check if result of this rule is worse than what we know so far
        if res.result >= self.__result:
            self.__result = res.result
            self.__reason = res.reason

    def dump_processing_info(self):
        """
        Saves the Cuckoo report as HTML + JSON
        to a directory named after the job hash.
        """
        job_hash = self.get_job_hash()
        dump_dir = os.path.join(os.environ['HOME'], 'malware_reports', job_hash)
        if not os.path.isdir(dump_dir):
            os.makedirs(dump_dir, 0o770)
        filename = self.__filename + '-' + self.sha256sum

        logger.debug('Dumping processing info to %s for sample %s',
                     dump_dir, self)

        # Peekaboo's report
        try:
            peekaboo_report = os.path.join(dump_dir, filename + '_report.txt')
            with open(peekaboo_report, 'w+') as f:
                f.write('\n'.join(self.__report))
                f.write('\n'.join(self.__internal_report))
        except IOError as ioerror:
            logger.exception(ioerror)

        # store malicious sample along with the reports
        if self.__result == Result.<