summaryrefslogtreecommitdiffstats
path: root/peekaboo/config.py
blob: af5b81f982c770c81a8a3efc9a61ab1381f904a4 (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
###############################################################################
#                                                                             #
# Peekaboo Extended Email Attachment Behavior Observation Owl                 #
#                                                                             #
# config.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/>.       #
#                                                                             #
###############################################################################

""" The configuration for the main program as well as the ruleset. Handles
defaults as well as reading a configuration file. """


import re
import sys
import logging
import configparser
from peekaboo.exceptions import PeekabooConfigException


logger = logging.getLogger(__name__)

class PeekabooConfigParser( # pylint: disable=too-many-ancestors
        configparser.ConfigParser):
    """ A config parser that gives error feedback if a required file does not
    exist or cannot be opened. """
    LOG_LEVEL = object()
    RELIST = object()
    IRELIST = object()

    def __init__(self, config_file):
        # super() does not work here because ConfigParser uses old-style
        # classes in python 2
        configparser.ConfigParser.__init__(self)

        try:
            self.read_file(open(config_file))
        except IOError as ioerror:
            raise PeekabooConfigException(
                'Configuration file "%s" can not be opened for reading: %s' %
                (config_file, ioerror))
        except configparser.Error as cperror:
            raise PeekabooConfigException(
                'Configuration file "%s" can not be parsed: %s' %
                (config_file, cperror))

        self.lists = {}
        self.relists = {}

    def getlist(self, section, option, raw=False, vars=None, fallback=None):
        """ Special getter where multiple options in the config file
        distinguished by a .<no> suffix form a list. Matches the signature for
        configparser getters. """
        # cache results because the following is somewhat inefficient
        if section not in self.lists:
            self.lists[section] = {}

        if option in self.lists[section]:
            return self.lists[section][option]

        if section not in self:
            self.lists[section][option] = fallback
            return fallback

        # Go over all options in this section we want to allow "holes" in
        # the lists, i.e setting.1, setting.2 but no setting.3 followed by
        # setting.4. We use here that ConfigParser retains option order from
        # the file.
        value = []
        for setting in self[section]:
            if not setting.startswith(option):
                continue

            # Parse 'setting' into (key) and 'setting.subscript' into
            # (key, subscript) and use it to determine if this setting is a
            # list. Note how we do not use the subscript at all here.
            name_parts = setting.split('.')
            key = name_parts[0]
            is_list = len(name_parts) > 1

            if key != option:
                continue

            if not is_list:
                raise PeekabooConfigException(
                    'Option %s in section %s is supposed to be a list '
                    'but given as individual setting' % (setting, section))

            # Potential further checks:
            # - There are no duplicate settings with ConfigParser. The last
            #   one always wins.

            value.append(self[section].get(setting, raw=raw, vars=vars))

        # it's not gonna get any better on the next call, so cache even the
        # default
        if not value:
            value = fallback

        self.lists[section][option] = value
        return value

    def getirelist(self, section, option, raw=False, vars=None, fallback=None, flags=None):
        """ Special getter for lists of regular expressions that are compiled to match
        case insesitive (IGNORECASE). Returns the compiled expression objects in a
        list ready for matching and searching.
        """
        return self.getrelist(section, option, raw=raw, vars=vars, fallback=fallback, flags=re.IGNORECASE)

    def getrelist(self, section, option, raw=False, vars=None, fallback=None, flags=0):
        """ Special getter for lists of regular expressions. Returns the
        compiled expression objects in a list ready for matching and searching.
        """
        if section not in self.relists:
            self.relists[section] = {}

        if option in self.relists[section]:
            return self.relists[section][option]

        if section not in self:
            self.relists[section][option] = fallback
            return fallback

        strlist = self[section].getlist(option, raw=raw, vars=vars,
                                        fallback=fallback)
        if strlist is None:
            self.relists[section][option] = None
            return None

        compiled_res = []
        for regex in strlist:
            try:
                compiled_res.append(re.compile(regex, flags))
            except (ValueError, TypeError) as error:
                raise PeekabooConfigException(
                    'Failed to compile regular expression "%s" (section %s, '
                    'option %s): %s' % (re, section, option, error))

        # it's not gonna get any better on the next call, so cache even the
        # default
        if not compiled_res:
            compiled_res = fallback

        self.relists[section][option] = compiled_res
        return compiled_res

    def get_log_level(self, section, option, raw=False, vars=None,
                      fallback=None):
        """ Get the log level from the configuration file and parse the string
        into a logging loglevel such as logging.CRITICAL. Raises config
        exception if the log level is unknown. Options identical to get(). """
        levels = {
            'CRITICAL': logging.CRITICAL,
            'ERROR': logging.ERROR,
            'WARNING': logging.WARNING,
            'INFO': logging.INFO,
            'DEBUG': logging.DEBUG
        }

        level = self.get(section, option, raw=raw, vars=vars, fallback=None)
        if level is None:
            return fallback

        if level not in levels:
            raise PeekabooConfigException('Unknown log level %s' % level)

        return levels[level]

    def get_by_type(self, section, option, fallback=None, option_type=None):
        """ Get an option from the configuration file parser. Automatically
        detects the type from the type of the default if given and calls the
        right getter method to coerce the value to the correct type.

        @param section: Which section to look for option in.
        @type section: string
        @param option: The option to read.
        @type option: string
        @param fallback: (optional) Default value to return if option is not
                         found. Defaults itself to None so that the method will
                         return None if the option is not found.
        @type fallback: int, bool, str or None.
        @param option_type: Override the option type.
        @type option_type: int, bool, str or None. """
        if option_type is None and fallback is not None:
            option_type = type(fallback)

        getter = {
            int: self.getint,
            float: self.getfloat,
            bool: self.getboolean,
            list: self.getlist,
            tuple: self.getlist,
            str: self.get,
            None: self.get,

            # these only work when given explicitly as option_type
            self.LOG_LEVEL: self.get_log_level,
            self.RELIST: self.getrelist,
            self.IRELIST: self.getirelist,
        }

        return getter[option_type](section, option, fallback=fallback)

    def check_config(self, known_options):
        """ Check this configuration against a list of known options. Raise an
        exception if any unknown options are found.

        @param known_options: A dict of sections and options, the key being the
                              section name and the value a list of option names.
        @type known_options: dict

        @returns: None
        @raises PeekabooConfigException: if any unknown sections or options are
                                         found.
        """
        known_sections = known_options.keys()
        self.check_sections(known_sections)

        # go over sections both allowed and in the config
        for section in known_sections:
            self.check_section_options(section, known_options[section])

    def check_sections(self, known_sections):
        """ Check a list of known section names against this configuration

        @param known_sections: names of known sections
        @type known_sections: list(string)

        @returns: None
        @raises PeekabooConfigException: if any unknown sections are found in
                                         the configuration.
        """
        section_diff = set(self.sections()) - set(known_sections)
        if section_diff:
            raise PeekabooConfigException(
                'Unknown section(s) found in config: %s'
                % ', '.join(section_diff))

    def check_section_options(self, section, known_options):
        """ Check a config section for unknown options.

        @param section: name of section to check
        @type section: string
        @param known_options: list of names of known options to check against
        @type known_options: list(string)

        @returns: None
        @raises PeekabooConfigException: if any unknown options are found. """
        try:
            section_options = map(
                # account for option.1 list syntax
                lambda x: x.split('.')[0],
                self.options(section))
        except configparser.NoSectionError:
            # a non-existant section can have no non-allowed options :)
            return

        option_diff = set(section_options) - set(known_options)
        if option_diff:
            raise PeekabooConfigException(
                'Unknown config option(s) found in section %s: %s'
                % (section, ', '.join(option_diff)))


class PeekabooConfig(PeekabooConfigParser):
    """ This class represents the Peekaboo configuration. """
    def __init__(self, config_file=None, log_level=None):
        """ Initialise the configuration with defaults, overwrite with command
        line options and finally read the configuration file. """
        # hard defaults: The idea here is that every config option has a
        # default that would in principle enable Peekaboo to run. Code using
        # the option should still cope with no or an empty value being handed
        # to it.
        self.user = 'peekaboo'
        self.group = 'peekaboo'
        self.pid_file = '/var/run/peekaboo/peekaboo.pid'
        self.sock_file = '/var/run/peekaboo/peekaboo.sock'
        self.log_level = logging.INFO
        self.log_format = '%(asctime)s - %(name)s - (%(threadName)s) - ' \
                          '%(levelname)s - %(message)s'
        self.interpreter = '/usr/bin/python2 -u'
        self.worker_count = 3
        self.sample_base_dir = '/tmp'
        self.job_hash_regex = '/amavis/tmp/([^/]+)/parts/'
        self.use_debug_module = False
        self.keep_mail_data = False
        self.processing_info_dir = '/var/lib/peekaboo/malware_reports'
        self.report_locale = None
        self.db_url = 'sqlite:////var/lib/peekaboo/peekaboo.db'
        self.db_log_level = logging.WARNING
        self.config_file = '/opt/peekaboo/etc/peekaboo.conf'
        self.ruleset_config = '/opt/peekaboo/etc/ruleset.conf'
        self.cuckoo_mode = "api"
        self.cuckoo_url = 'http://127.0.0.1:8090'
        self.cuckoo_api_token = ''
        self.cuckoo_poll_interval = 5
        self.cuckoo_storage = '/var/lib/peekaboo/.cuckoo/storage'
        self.cuckoo_exec = '/opt/cuckoo/bin/cuckoo'
        self.cuckoo_submit = '/opt/cuckoo/bin/cuckoo submit'
        self.cluster_instance_id = 0
        self.cluster_stale_in_flight_threshold = 15*60
        self.cluster_duplicate_check_interval = 60

        # section and option names for the configuration file. key is the above
        # variable name whose value will be ove