summaryrefslogtreecommitdiffstats
path: root/peekaboo/sample.py
blob: 35c661da8ea907b7244749dd3162b3f6a874c3ef (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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
###############################################################################
#                                                                             #
# 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
# python 3's open with encoding parameter and implicit usage of the system
# locale-specified encoding
from builtins import open
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, processing_info_dir):
        # 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
        self.processing_info_dir = processing_info_dir

    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,
                      self.processing_info_dir)


class Sample(object):
    """
    This class handles and describes samples to be analysed by Peekaboo.

    A sample has properties like filename, MIME type, checksum or file size.
    These are accessible as properties. Most properties determine their value
    on first access, especially if that determination is somewhat expensive
    such as the file checksum.

    The data structure works together with Cuckoo to run behavioral analysis.
    """
    def __init__(self, file_path, cuckoo=None, status_change=None,
                 metainfo=None, base_dir=None, job_hash_regex=None,
                 keep_mail_data=False, processing_info_dir=None):
        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.__result = Result.unchecked
        self.__reason = None
        self.__report = []  # Peekaboo's own report
        self.__internal_report = []
        self.__file_stat = None
        self.__sha256sum = None
        self.__mimetypes = None
        self.__file_extension = None
        self.__office_macros = None
        self.__base_dir = base_dir
        self.__job_hash = None
        self.__job_hash_regex = job_hash_regex
        self.__keep_mail_data = keep_mail_data
        self.__processing_info_dir = processing_info_dir

        # Additional attributes for a sample object (i.e. meta info)
        # We do not make these private for the following reasons:
        # - this way they still somewhat resemble the previous arbitrary
        #   attribute dictionary idea
        # - we'd have to implement the name mangling for setting blow
        #
        # Security: Add more below to allow them to be accepted from the
        # client. We don't want anyone to be able to pollute our sample
        # objects from the outside. This also serves as a registry of what we
        # actually use and know how to deal with.
        self.meta_info_name_declared = None
        self.meta_info_type_declared = None

        self.initialized = False

        if metainfo:
            member_variables = vars(self)
            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
                member = 'meta_info_%s' % field
                if member in member_variables and metainfo[field] is not None:
                    member_variables[member] = 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 True

        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
            try:
                self.__wd = tempfile.mkdtemp(
                    prefix=self.job_hash, dir=self.__base_dir)
            except OSError as oserr:
                logger.error('Error creating working directory: %s', oserr)
                return False

            logger.debug('Working directory %s created', self.__wd)

            self.__submit_path = os.path.join(
                self.__wd, '%s.%s' % (self.sha256sum, file_ext))

            try:
                os.symlink(self.__path, self.__submit_path)
            except OSError as oserr:
                logger.error('Error linking sample from %s to working '
                             'directory as %s',
                             self.__path, self.__submit_path)
                self.cleanup()
                return False

            logger.debug('Sample symlinked from %s to %s',
                         self.__path, self.__submit_path)

        self.initialized = True

        self.__report.append(_("File \"%s\" %s is being analyzed")
                             % (self.__filename, self.sha256sum))

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

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

        return True

    @property
    def file_path(self):
        """ Returns the path to the sample given on creation including
        directories and filename. """
        return self.__path

    @property
    def filename(self):
        """ Returns the name of the sample file, i.e. the basename without path
        but including the file extension. """
        return self.__filename

    @property
    def result(self):
        """ Returns the overall evaluation result for this sample.

        @returns: peekaboo.ruleset.Result """
        return self.__result

    @property
    def reason(self):
        """ Gets the reason given by the rule determining the result which
        ended up as the overall evaluation result of this sample.

        @returns: string """
        return self.__reason

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

        @returns: List of strings.
        """
        # This message used to be:
        # "Die Datei \"%s\" wurde als \"%s\" eingestuft\n\n"
        # Changed intentionally to not trigger configured god/bad matching
        # patterns in clients (e.g. AMaViS) any more since we switched to
        # reporting an overall analysis batch result.
        return self.__report + [_("File \"%s\" is considered \"%s\"")
                                % (self.__filename, self.__result.name)]

    @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

    @property
    def job_hash(self):
        """ Returns a job identifier extracted from the file path using a
        configurable regular expression for use in other temporary or permanent
        (dump) path names to keep correlation to the original input job. """
        if self.__job_hash:
            return self.__job_hash

        match = re.search(self.__job_hash_regex, self.__path)
        if match is not None:
            job_hash = match.group(1)
        else:
            # 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)
        self.__job_hash = job_hash
        return job_hash

    def add_rule_result(self, res):
        """ Add a rule result to the sample. This also adds a message about
        this to the report and updates the overall analysis result (so far).
        """
        logger.debug('Adding rule result %s', res)
        self.__report.append(_("File \"%s\": %s") % (self.__filename, 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(