def test2log_no_line_event(self):
        """In this test case the EventHandler receives no lines from the test class."""
        description = "Test2StreamPrinterEventHandler"
        match_context = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element = fixed_dme.get_match_element("match", match_context)

        match_context = MatchContext(self.pid)
        fixed_dme2 = FixedDataModelElement('s2', self.pid)
        match_element2 = fixed_dme2.get_match_element("match", match_context)
        self.analysis_context.register_component(self, description)
        t = time()
        log_atom = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element), t,
                           self)

        self.stream_printer_event_handler.receive_event(
            self.test % self.__class__.__name__, self.new_val %
            (self.match_s1, self.match_s2, repr(match_element.match_object)),
            [], None, log_atom, self)

        self.assertEqual(
            self.output_stream.getvalue(), self.__expectedString %
            (datetime.fromtimestamp(t).strftime("%Y-%m-%d %H:%M:%S"),
             match_element.get_path() + ", " + match_element2.get_path(),
             match_element.get_match_object(), self.__class__.__name__,
             description, 0, ""))
Beispiel #2
0
    def test7get_match_element_match_context_input_validation(self):
        """Check if an exception is raised, when other classes than MatchContext are used in get_match_element."""
        model_element = FixedDataModelElement(self.id_, self.data)
        data = self.data
        model_element.get_match_element(self.path, DummyMatchContext(data))
        model_element.get_match_element(self.path, MatchContext(data))

        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, MatchElement(self.path, data, None, None))
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, data)
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, data.decode())
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, True)
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, 123)
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, 123.22)
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, True)
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, None)
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, [])
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, {"key": MatchContext(data)})
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, set())
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, ())
        self.assertRaises(AttributeError, model_element.get_match_element,
                          self.path, model_element)
Beispiel #3
0
    def test7_receive_atom_list_without_match_element(self):
        """This test case checks if the ReceiveAtom controls the list of MatchElements and responds correctly, when a value is missing."""
        description = "Test7MissingMatchPathValueDetector"
        match_context_fixed_dme = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element_fixed_dme = fixed_dme.get_match_element(
            "match1", match_context_fixed_dme)
        match_context_decimal_integer_value_me = MatchContext(self.string)
        decimal_integer_value_me = DecimalIntegerValueModelElement(
            'd1', DecimalIntegerValueModelElement.SIGN_TYPE_NONE,
            DecimalIntegerValueModelElement.PAD_TYPE_NONE)
        match_element_decimal_integer_value_me = decimal_integer_value_me.get_match_element(
            "match2", match_context_decimal_integer_value_me)

        match_context_fixed_dme = MatchContext(self.pid)
        matchElementFixedDME2 = fixed_dme.get_match_element(
            "match3", match_context_fixed_dme)
        missing_match_path_list_value_detector = MissingMatchPathListValueDetector(
            self.aminer_config, [
                match_element_fixed_dme.get_path(),
                match_element_decimal_integer_value_me.get_path()
            ], [self.stream_printer_event_handler], 'Default', False,
            self.__default_interval, self.__realert_interval)
        self.analysis_context.register_component(
            missing_match_path_list_value_detector, description)
        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data,
                                     ParserMatch(matchElementFixedDME2), 1,
                                     missing_match_path_list_value_detector)
        self.assertFalse(
            missing_match_path_list_value_detector.receive_atom(
                log_atom_fixed_dme))
Beispiel #4
0
    def test1log_multiple_lines_event(self):
        """
        In this test case multiple lines should be received, before sending an email to root@localhost.
        Make sure no mail notifications are in /var/spool/mail/root, before running this test. This test case must wait some time to
        ensure, that the mail can be read.
        """
        description = "Test1DefaultMailNotificationEventHandler"
        match_context = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element = fixed_dme.get_match_element("match", match_context)

        match_context = MatchContext(self.pid)
        fixed_dme2 = FixedDataModelElement('s2', self.pid)
        match_element2 = fixed_dme2.get_match_element("match", match_context)

        default_mail_notification_event_handler = DefaultMailNotificationEventHandler(self.analysis_context)
        self.analysis_context.register_component(self, description)

        t = time()
        log_atom = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element), t, self)
        default_mail_notification_event_handler.receive_event(
            self.test % self.__class__.__name__, 'New value for pathes %s, %s: %s' % (
                'match/s1', 'match/s2', repr(match_element.match_object)), [log_atom.raw_data, log_atom.raw_data], None, log_atom, self)

        t += 600
        log_atom = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element), t, self)
        # set the next_alert_time instead of sleeping 10 seconds
        default_mail_notification_event_handler.next_alert_time = time()
        default_mail_notification_event_handler.receive_event(
            self.test % self.__class__.__name__, 'New value for pathes %s, %s: %s' % (
                'match/s1', 'match/s2', repr(match_element.match_object)), [log_atom.raw_data, log_atom.raw_data], None, log_atom, self)
        sleep(2)
        # skipcq: PYL-W1510, BAN-B602
        result = subprocess.run(self.mail_call, shell=True, stdout=subprocess.PIPE)
        # skipcq: PYL-W1510, BAN-B602
        subprocess.run(self.mail_delete_call, shell=True, stdout=subprocess.PIPE)

        if datetime.fromtimestamp(t - 600).strftime(self.datetime_format_string) not in str(result.stdout, 'utf-8'):
            print("ERROR: %s t-600 not found in mail!" % description, file=sys.stderr)
        if datetime.fromtimestamp(t).strftime(self.datetime_format_string) not in str(result.stdout, 'utf-8'):
            print("ERROR: %s t not found in mail!" % description, file=sys.stderr)

        self.assertTrue(self.__expected_string % (
            "" + match_element.get_path() + ", " + match_element2.get_path(), repr(match_element.get_match_object()),
            self.__class__.__name__, description, 2, match_element.get_match_string().decode() + "\n  " +
            match_element2.get_match_string().decode()) in
            str(result.stdout, 'utf-8'), msg="%s vs \n %s" % (self.__expected_string % (
                match_element.get_path(), repr(match_element.get_match_object()), self.__class__.__name__, description, 1,
                match_element.get_match_string().decode() + "\n\n"), str(result.stdout, 'utf-8')))

        self.assertTrue(self.__expected_string % (
            "" + match_element.get_path() + ", " + match_element2.get_path(), repr(match_element.get_match_object()),
            self.__class__.__name__, description, 2, match_element.get_match_string().decode() + "\n  " +
            match_element2.get_match_string().decode() + "\n\n") in str(result.stdout, 'utf-8'))
 def test2_receive_atom_without_match_element(self):
     """This test case checks if the ReceiveAtom controls the MatchElement and responds correctly, when it is missing."""
     description = "Test2MissingMatchPathValueDetector"
     match_context_fixed_dme = MatchContext(self.pid)
     fixed_dme = FixedDataModelElement('s1', self.pid)
     match_element_fixed_dme = fixed_dme.get_match_element("match1", match_context_fixed_dme)
     match_context_fixed_dme = MatchContext(self.pid)
     matchElementFixedDME2 = fixed_dme.get_match_element("match2", match_context_fixed_dme)
     missing_match_path_value_detector = MissingMatchPathValueDetector(self.aminer_config, [match_element_fixed_dme.get_path()], [
         self.stream_printer_event_handler], 'Default', False, self.__default_interval, self.__realert_interval)
     self.analysis_context.register_component(missing_match_path_value_detector, description)
     log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(matchElementFixedDME2), 1, missing_match_path_value_detector)
     self.assertFalse(missing_match_path_value_detector.receive_atom(log_atom_fixed_dme))
    def test1match_found(self):
        """This test case checks if valid inputs are recognized."""
        description = "Test1WhitelistViolationDetector"
        path_exists_match_rule = PathExistsMatchRule('match/s1', None)
        path_exists_match_rule2 = PathExistsMatchRule('match/s2', None)

        t = time.time()
        whitelist_violation_detector = WhitelistViolationDetector(
            self.aminer_config,
            [path_exists_match_rule, path_exists_match_rule2],
            [self.stream_printer_event_handler],
            output_log_line=False)
        self.analysis_context.register_component(whitelist_violation_detector,
                                                 description)

        fixed_dme = FixedDataModelElement('s1', self.fixed_string)
        match_context = MatchContext(self.fixed_string)
        match_element = fixed_dme.get_match_element('match', match_context)
        log_atom = LogAtom(match_context.match_data,
                           ParserMatch(match_element), t,
                           whitelist_violation_detector)

        self.assertTrue(whitelist_violation_detector.receive_atom(log_atom))
        self.assertEqual(self.output_stream.getvalue(), '')

        fixed_dme = FixedDataModelElement('s2', self.fixed_string)
        match_context = MatchContext(self.fixed_string)
        match_element = fixed_dme.get_match_element('match', match_context)
        log_atom = LogAtom(match_element.match_object,
                           ParserMatch(match_element), t,
                           whitelist_violation_detector)

        self.assertTrue(whitelist_violation_detector.receive_atom(log_atom))
        self.assertEqual(self.output_stream.getvalue(), '')

        fixed_dme = FixedDataModelElement('s3', self.fixed_string)
        match_context = MatchContext(self.fixed_string)
        match_element = fixed_dme.get_match_element('match', match_context)
        log_atom = LogAtom(match_element.match_object,
                           ParserMatch(match_element), t,
                           path_exists_match_rule)

        self.assertTrue(
            not whitelist_violation_detector.receive_atom(log_atom))
        self.assertEqual(
            self.output_stream.getvalue(), self.__expected_string %
            (datetime.fromtimestamp(t).strftime("%Y-%m-%d %H:%M:%S"),
             whitelist_violation_detector.__class__.__name__, description, 1,
             "b'fixed String'"))
    def test3timestamp_higher_than_last_timestamp(self):
        """This test case checks if nothing happens, when the timestamp is, as expected, higher than the last one."""
        description = "Test3TimestampsUnsortedDetector"
        match_context_fixed_dme = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element_fixed_dme = fixed_dme.get_match_element(
            "match", match_context_fixed_dme)
        new_match_path_detector = NewMatchPathDetector(
            self.aminer_config, [self.stream_printer_event_handler], 'Default',
            False)
        self.analysis_context.register_component(new_match_path_detector,
                                                 description)

        t = time()
        log_atom = LogAtom(fixed_dme.fixed_data,
                           ParserMatch(match_element_fixed_dme), t,
                           new_match_path_detector)
        timestamp_unsorted_detector = TimestampsUnsortedDetector(
            self.aminer_config, [self.stream_printer_event_handler],
            False,
            output_log_line=False)
        self.analysis_context.register_component(timestamp_unsorted_detector,
                                                 description + "2")
        self.assertTrue(timestamp_unsorted_detector.receive_atom(log_atom))
        self.assertEqual(self.output_stream.getvalue(), '')

        log_atom.set_timestamp(t)
        self.assertTrue(timestamp_unsorted_detector.receive_atom(log_atom))
        self.assertEqual(self.output_stream.getvalue(), '')

        log_atom.set_timestamp(t + 10000)
        self.assertTrue(timestamp_unsorted_detector.receive_atom(log_atom))
        self.assertEqual(self.output_stream.getvalue(), '')
    def test1simple_monotonic_timestamp_adjust_test(self):
        """this test case checks if the timestamp is adjusted and logAtoms are forwarded correctly."""
        description = "Test1TimestampCorrectionFilter"
        match_context_fixed_dme = MatchContext(b' pid=')
        fixed_dme = FixedDataModelElement('s1', b' pid=')
        match_element_fixed_dme = fixed_dme.get_match_element(
            "match", match_context_fixed_dme)
        t = time()

        new_match_path_detector = NewMatchPathDetector(
            self.aminer_config, [self.stream_printer_event_handler],
            'Default',
            False,
            output_log_line=False)
        self.analysis_context.register_component(new_match_path_detector,
                                                 description)
        simple_monotonic_timstamp_adjust = SimpleMonotonicTimestampAdjust(
            [new_match_path_detector], False)
        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data,
                                     ParserMatch(match_element_fixed_dme), t,
                                     new_match_path_detector)
        self.assertEqual(
            simple_monotonic_timstamp_adjust.receive_atom(log_atom_fixed_dme),
            True)
        self.assertEqual(
            self.output_stream.getvalue(), self.__expected_string %
            (datetime.fromtimestamp(t).strftime("%Y-%m-%d %H:%M:%S"),
             new_match_path_detector.__class__.__name__, description, 1,
             self.match_path))
Beispiel #9
0
 def test4get_match_element_no_match(self):
     """Parse not matching substring from MatchContext and check if the MatchContext was not changed."""
     no_match_string = b"Hello World."
     match_context = DummyMatchContext(self.data)
     fixed_dme = FixedDataModelElement(self.id_, no_match_string)
     match_element = fixed_dme.get_match_element(self.path, match_context)
     self.compare_no_match_results(self.data, match_element, match_context)
    def test4_receive_atom_missing_value(self):
        """This test case checks if missing values are reported correctly."""
        description = "Test4MissingMatchPathValueDetector"
        t = time.time()
        match_context_fixed_dme = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element_fixed_dme = fixed_dme.get_match_element("match1", match_context_fixed_dme)
        missing_match_path_value_detector = MissingMatchPathValueDetector(self.aminer_config, [match_element_fixed_dme.get_path()], [
            self.stream_printer_event_handler], 'Default', True, self.__default_interval, self.__realert_interval)
        self.analysis_context.register_component(missing_match_path_value_detector, description)
        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element_fixed_dme), t, missing_match_path_value_detector)
        self.assertTrue(missing_match_path_value_detector.receive_atom(log_atom_fixed_dme))

        past_time = 4000
        missing_match_path_value_detector = MissingMatchPathValueDetector(self.aminer_config, [match_element_fixed_dme.get_path()], [
            self.stream_printer_event_handler], 'Default', True, missing_match_path_value_detector.default_interval - past_time,
            self.__realert_interval, output_log_line=False)
        self.analysis_context.register_component(missing_match_path_value_detector, description + "2")

        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element_fixed_dme), t + past_time,
                                     missing_match_path_value_detector)
        self.assertTrue(missing_match_path_value_detector.receive_atom(log_atom_fixed_dme))
        self.assertEqual(self.output_stream.getvalue(), self.__expected_string % (
            datetime.fromtimestamp(t + past_time).strftime(self.datetime_format_string),
            missing_match_path_value_detector.__class__.__name__, description + "2", 1, self.match1_s1_overdue))
Beispiel #11
0
 def test1_valid_input_with_match_element_found(self):
     """This testmethod is part of the Basis Path Testing / Decision Coverage. It assures, that the intended usage of the
     FixedDataModelElement is working. (MatchElement found)"""
     match_context = MatchContext(self.pid)
     fixed_dme = FixedDataModelElement('s0', self.pid)
     match_element = fixed_dme.get_match_element("", match_context)
     self.assertNotEqual(match_element, None, "There should exist a MatchElement!")
Beispiel #12
0
    def test3_receive_atom_no_missing_value(self):
        """This test case checks whether the class returns wrong positives, when the time limit is not passed."""
        description = "Test3MissingMatchPathValueDetector"
        match_context_fixed_dme = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element_fixed_dme = fixed_dme.get_match_element(
            "match1", match_context_fixed_dme)
        missing_match_path_value_detector = MissingMatchPathValueDetector(
            self.aminer_config, match_element_fixed_dme.get_path(),
            [self.stream_printer_event_handler], 'Default', True,
            self.__default_interval, self.__realert_interval)
        self.analysis_context.register_component(
            missing_match_path_value_detector, description)
        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data,
                                     ParserMatch(match_element_fixed_dme),
                                     time.time(),
                                     missing_match_path_value_detector)
        self.assertTrue(
            missing_match_path_value_detector.receive_atom(log_atom_fixed_dme))

        past_time = 3200
        missing_match_path_value_detector = MissingMatchPathValueDetector(
            self.aminer_config, match_element_fixed_dme.get_path(),
            [self.stream_printer_event_handler], 'Default', True,
            missing_match_path_value_detector.default_interval - past_time,
            self.__realert_interval)

        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data,
                                     ParserMatch(match_element_fixed_dme),
                                     time.time() + past_time,
                                     missing_match_path_value_detector)
        self.assertTrue(
            missing_match_path_value_detector.receive_atom(log_atom_fixed_dme))
        self.assertEqual(self.output_stream.getvalue(), '')
Beispiel #13
0
    def test6_receive_atom_list(self):
        """This test case checks, whether a missing value is created by a list without using the
        auto_include_flag. (should not be the case)"""
        description = "Test6MissingMatchPathValueDetector"
        match_context_fixed_dme = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element_fixed_dme = fixed_dme.get_match_element(
            "match1", match_context_fixed_dme)
        match_context_decimal_integer_value_me = MatchContext(self.string)
        decimal_integer_value_me = DecimalIntegerValueModelElement(
            'd1', DecimalIntegerValueModelElement.SIGN_TYPE_NONE,
            DecimalIntegerValueModelElement.PAD_TYPE_NONE)
        match_element_decimal_integer_value_me = decimal_integer_value_me.get_match_element(
            "match2", match_context_decimal_integer_value_me)

        missing_match_path_list_value_detector = MissingMatchPathListValueDetector(
            self.aminer_config, [
                match_element_fixed_dme.get_path(),
                match_element_decimal_integer_value_me.get_path()
            ], [self.stream_printer_event_handler], 'Default', False,
            self.__default_interval, self.__realert_interval)
        self.analysis_context.register_component(
            missing_match_path_list_value_detector, description)
        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data,
                                     ParserMatch(match_element_fixed_dme), 1,
                                     missing_match_path_list_value_detector)
        self.assertTrue(
            missing_match_path_list_value_detector.receive_atom(
                log_atom_fixed_dme))
    def test5_missing_value_on_persisted(self):
        """Persisting elements is tested in this test case."""
        description = "Test5MissingMatchPathValueDetector"
        t = time.time()
        match_context_fixed_dme = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element_fixed_dme = fixed_dme.get_match_element("match1", match_context_fixed_dme)
        missing_match_path_value_detector = MissingMatchPathValueDetector(self.aminer_config, [match_element_fixed_dme.get_path()], [
            self.stream_printer_event_handler], 'Default', True, self.__default_interval, self.__realert_interval)
        self.analysis_context.register_component(missing_match_path_value_detector, description)
        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element_fixed_dme), round(t),
                                     missing_match_path_value_detector)
        self.assertTrue(missing_match_path_value_detector.receive_atom(log_atom_fixed_dme))
        missing_match_path_value_detector.do_persist()

        past_time = 4000
        other_missing_match_path_value_detector = MissingMatchPathValueDetector(self.aminer_config, [match_element_fixed_dme.get_path()], [
            self.stream_printer_event_handler], 'Default', True, self.__default_interval, self.__realert_interval)
        self.analysis_context.register_component(other_missing_match_path_value_detector, description + "2")
        other_missing_match_path_value_detector.set_check_value(other_missing_match_path_value_detector.get_channel_key(
            log_atom_fixed_dme)[1], self.__default_interval - past_time, match_element_fixed_dme.get_path())

        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element_fixed_dme), round(t) + past_time,
                                     other_missing_match_path_value_detector)
        self.assertTrue(other_missing_match_path_value_detector.receive_atom(log_atom_fixed_dme))
        # skipcq: PYL-R1714
        self.assertTrue((self.output_stream.getvalue() == self.__expected_string % (
            datetime.fromtimestamp(t + past_time).strftime(self.datetime_format_string),
            other_missing_match_path_value_detector.__class__.__name__, description + "2", 1, self.match1_s1_overdue)) or (
                        self.output_stream.getvalue() == self.__expected_string % (
                            datetime.fromtimestamp(t + past_time + 1).strftime(self.datetime_format_string),
                            other_missing_match_path_value_detector.__class__.__name__, description + "2", 1, self.match1_s1_overdue)))
    def test8_receive_atom_list_no_missing_value(self):
        """This test case checks whether the class returns wrong positives on lists, when the time limit should not be passed."""
        description = "Test8MissingMatchPathValueDetector"
        t = time.time()
        match_context_fixed_dme = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element_fixed_dme = fixed_dme.get_match_element("match1", match_context_fixed_dme)

        match_context_decimal_integer_value_me = MatchContext(self.string)
        decimal_integer_value_me = DecimalIntegerValueModelElement('d1', DecimalIntegerValueModelElement.SIGN_TYPE_NONE,
                                                                   DecimalIntegerValueModelElement.PAD_TYPE_NONE)
        match_element_decimal_integer_value_me = decimal_integer_value_me.get_match_element(
            "match2", match_context_decimal_integer_value_me)

        missing_match_path_list_value_detector = MissingMatchPathListValueDetector(self.aminer_config, [
            match_element_fixed_dme.get_path(), match_element_decimal_integer_value_me.get_path()], [self.stream_printer_event_handler],
            'Default', True, self.__default_interval, self.__realert_interval)
        self.analysis_context.register_component(missing_match_path_list_value_detector, description)
        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element_fixed_dme), round(t),
                                     missing_match_path_list_value_detector)
        self.assertTrue(missing_match_path_list_value_detector.receive_atom(log_atom_fixed_dme))

        past_time = 3200
        missing_match_path_list_value_detector = MissingMatchPathListValueDetector(self.aminer_config, [
            match_element_fixed_dme.get_path(), match_element_decimal_integer_value_me.get_path()], [self.stream_printer_event_handler],
            'Default', True, missing_match_path_list_value_detector.default_interval - past_time, self.__realert_interval)
        self.analysis_context.register_component(missing_match_path_list_value_detector, description + "2")
        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element_fixed_dme), round(t) + past_time,
                                     missing_match_path_list_value_detector)
        self.assertTrue(missing_match_path_list_value_detector.receive_atom(log_atom_fixed_dme))
        self.assertEqual(self.output_stream.getvalue(), '')
    def test7constraint_list(self):
        """Test the allowlisting of paths."""
        description = 'test7eventCorrelationDetectorTest'
        ecd = EventCorrelationDetector(self.aminer_config,
                                       [self.stream_printer_event_handler],
                                       check_rules_flag=True,
                                       p0=0.7,
                                       alpha=0.1,
                                       auto_include_flag=True)
        self.analysis_context.register_component(ecd, description)
        self.assertEqual([], ecd.constraint_list)

        match_context_fixed_dme = MatchContext(b' pid=')
        fixed_dme = FixedDataModelElement('s1', b' pid=')
        match_element_fixed_dme = fixed_dme.get_match_element(
            "", match_context_fixed_dme)

        # unknown path
        ecd.allowlist_event(self.analysis % ecd.__class__.__name__,
                            match_element_fixed_dme.get_path(), None)
        self.assertEqual(['/s1'], ecd.constraint_list)

        # known path
        ecd.allowlist_event(self.analysis % ecd.__class__.__name__,
                            match_element_fixed_dme.get_path(), None)
        self.assertEqual(['/s1'], ecd.constraint_list)
Beispiel #17
0
 def test4_fuzzing_path_is_none(self):
     """This testmethod is part of the Fuzz Testing and it assures, that the path-input is validated. In this case a path is not
     needed, because FixedDataModelElement has no child elements."""
     match_context = MatchContext(self.pid)
     fixed_dme = FixedDataModelElement('s0', self.pid)
     match_element = fixed_dme.get_match_element(None, match_context)
     self.assertNotEqual(match_element, None, "There should exist a MatchElement!")
    def test1log_multiple_lines_event(self):
        """In this test case the EventHandler receives multiple lines from the test class."""
        description = "Test1SyslogWriterEventHandler"
        match_context = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element = fixed_dme.get_match_element("match", match_context)

        match_context = MatchContext(self.pid)
        fixed_dme2 = FixedDataModelElement('s2', self.pid)
        match_element2 = fixed_dme2.get_match_element("match", match_context)

        syslog_writer_event_handler = SyslogWriterEventHandler(
            self.analysis_context, 'aminer')
        self.analysis_context.register_component(self, description)

        t = time()
        log_atom = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element), t,
                           self)

        syslog_writer_event_handler.receive_event(
            self.test % self.__class__.__name__, self.new_val %
            (self.match_s1, self.match_s2, repr(match_element.match_object)),
            [log_atom.raw_data, log_atom.raw_data], None, log_atom, self)
        string = ''

        sleep(0.2)
        with open("/var/log/syslog") as search:
            for line in search:
                line = line.rstrip()  # remove '\n' at end of line
                if 'aminer[' + str(os.getpid()) + ']' in line:
                    line = line.split("]: ")
                    string += (line[1]) + '\n'
        found = False
        string = string.split('Syslog logger initialized\n')
        expected = self.__expected_string % (
            datetime.fromtimestamp(t).strftime("%Y-%m-%d %H:%M:%S"),
            match_element.get_path(), match_element2.get_path(),
            repr(match_element.get_match_object()), self.__class__.__name__,
            description, 2, match_element.get_match_string().decode(),
            match_element2.get_match_string().decode())

        for log in string:
            if expected in log:
                found = True
        self.assertTrue(found)
 def test4get_match_element_no_match(self):
     """Parse not matching substring from MatchContext and check if the MatchContext was not changed."""
     no_match_string = b"Hello World."
     match_context = DummyMatchContext(self.data)
     fixed_dme = FixedDataModelElement("s0", no_match_string)
     match_element = fixed_dme.get_match_element("fixed", match_context)
     self.assertIsNone(match_element, None)
     self.assertEqual(match_context.match_data, self.data)
     self.assertEqual(match_context.match_string, b"")
Beispiel #20
0
 def test3get_match_element_valid_match(self):
     """Parse matching substring from MatchContext and check if the MatchContext was updated with the fixed string."""
     fixed_string = b"fixed data."
     fixed_dme = FixedDataModelElement(self.id_, fixed_string)
     match_context = DummyMatchContext(self.data)
     match_element = fixed_dme.get_match_element(self.path, match_context)
     self.compare_match_results(self.data, match_element, match_context,
                                self.id_, self.path, fixed_string,
                                fixed_string, None)
 def test3get_match_element_valid_match(self):
     """Parse matching substring from MatchContext and check if the MatchContext was updated accordingly."""
     fixed_string = b'fixed data.'
     match_context = DummyMatchContext(self.data)
     fixed_dme = FixedDataModelElement("s0", fixed_string)
     match_element = fixed_dme.get_match_element("fixed", match_context)
     self.assertEqual(match_element.path, "fixed/s0")
     self.assertEqual(match_element.match_string, fixed_string)
     self.assertEqual(match_element.match_object, fixed_string)
     self.assertIsNone(match_element.children, None)
     self.assertEqual(match_context.match_string, fixed_string)
 def test1_receive_atom(self):
     """This test case checks whether a missing value is created without using the auto_include_flag (should not be the case)."""
     description = "Test1MissingMatchPathValueDetector"
     match_context_fixed_dme = MatchContext(self.pid)
     fixed_dme = FixedDataModelElement('s1', self.pid)
     match_element_fixed_dme = fixed_dme.get_match_element("match1", match_context_fixed_dme)
     missing_match_path_value_detector = MissingMatchPathValueDetector(self.aminer_config, [match_element_fixed_dme.get_path()], [
         self.stream_printer_event_handler], 'Default', False, self.__default_interval, self.__realert_interval)
     self.analysis_context.register_component(missing_match_path_value_detector, description)
     log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element_fixed_dme), 1, missing_match_path_value_detector)
     self.assertTrue(missing_match_path_value_detector.receive_atom(log_atom_fixed_dme))
Beispiel #23
0
    def test2do_timer(self):
        """In this test case the functionality of the timer is tested. The eventCollectTime must not be 0."""
        description = "Test2DefaultMailNotificationEventHandler"
        default_mail_notification_event_handler = DefaultMailNotificationEventHandler(self.analysis_context)
        self.analysis_context.register_component(self, description)

        t = time()
        match_context = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s3', self.pid)
        match_element = fixed_dme.get_match_element("match", match_context)

        log_atom = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element), t, self)
        default_mail_notification_event_handler.receive_event(
            self.test % self.__class__.__name__, 'New value for pathes %s: %s' % (
                'match/s3', repr(match_element.match_object)), [log_atom.raw_data], None, log_atom, self)

        t = 0
        default_mail_notification_event_handler.do_timer(t)
        # skipcq: PYL-W1510, BAN-B602
        result = subprocess.run(self.mail_call, shell=True, stdout=subprocess.PIPE)

        self.assertFalse(self.__expected_string % (
            match_element.get_path(), repr(match_element.get_match_object()), self.__class__.__name__, description, 1,
            match_element.get_match_string().decode() + "\n\n") in str(result.stdout, 'utf-8'))

        t = time()
        default_mail_notification_event_handler.next_alert_time = t + 500
        default_mail_notification_event_handler.do_timer(t)

        # skipcq: PYL-W1510, BAN-B602
        result = subprocess.run(self.mail_call, shell=True, stdout=subprocess.PIPE)
        self.assertFalse(self.__expected_string % (
            match_element.get_path(), repr(match_element.get_match_object()), self.__class__.__name__, description, 1,
            match_element.get_match_string().decode() + "\n\n") in str(result.stdout, 'utf-8'))

        default_mail_notification_event_handler.next_alert_time = t
        default_mail_notification_event_handler.do_timer(t)

        sleep(2)
        # skipcq: PYL-W1510, BAN-B602
        result = subprocess.run(self.mail_call, shell=True, stdout=subprocess.PIPE)
        # skipcq: PYL-W1510, BAN-B602
        subprocess.run(self.mail_delete_call, shell=True, stdout=subprocess.PIPE)

        if datetime.fromtimestamp(t).strftime(self.datetime_format_string) not in str(result.stdout, 'utf-8'):
            print("ERROR: %s t not found in mail!" % description, file=sys.stderr)

        self.assertTrue(self.__expected_string % (
            match_element.get_path(), repr(match_element.get_match_object()), self.__class__.__name__, description, 1,
            match_element.get_match_string().decode() + "\n\n") in str(result.stdout, 'utf-8'), msg="%s vs \n %s" % (
            self.__expected_string % (
                match_element.get_path(), repr(match_element.get_match_object()), self.__class__.__name__, description, 1,
                match_element.get_match_string().decode() + "\n\n"), str(result.stdout, 'utf-8')))
Beispiel #24
0
    def test2normal_complete_overlong_line(self):
        """A complete, overlong line is tested as Input of the Class."""
        match_context_fixed_dme = MatchContext(self.illegal_access1)
        fixed_dme = FixedDataModelElement('s1', self.illegal_access1)
        _match_element_fixed_dme = fixed_dme.get_match_element(
            "match1", match_context_fixed_dme)

        byte_stream_line_atomizer = ByteStreamLineAtomizer(
            fixed_dme, [], [self.stream_printer_event_handler],
            sys.getsizeof(match_context_fixed_dme.match_data) - 1, [])
        self.assertGreater(
            byte_stream_line_atomizer.consume_data(
                b'WARNING: All illegal access operations will be denied in a future release\n',
                True), 0)
        self.assertEqual(
            self.output_stream.getvalue(),
            'Overlong line detected (1 lines)\n  %s' % self.illegal_access2)
Beispiel #25
0
    def test3normal_incomplete_overlong_line_stream_not_ended(self):
        """A incomplete, overlong line, with the stream NOT ended, is tested as Input of the Class."""
        match_context_fixed_dme = MatchContext(self.illegal_access1)
        fixed_dme = FixedDataModelElement('s1', self.illegal_access1)
        _match_element_fixed_dme = fixed_dme.get_match_element(
            "match1", match_context_fixed_dme)

        byte_stream_line_atomizer = ByteStreamLineAtomizer(
            fixed_dme, [], [self.stream_printer_event_handler],
            sys.getsizeof(match_context_fixed_dme.match_data) - 1, [])
        self.assertGreater(
            byte_stream_line_atomizer.consume_data(self.illegal_access1,
                                                   False), 0)
        self.assertEqual(
            self.output_stream.getvalue(),
            'Start of overlong line detected (1 lines)\n  %s' %
            self.illegal_access2)
    def test3event_data_not_log_atom(self):
        """In this test case the EventHandler receives no logAtom from the test class and the method should raise an exception."""
        description = "Test3StreamPrinterEventHandler"
        match_context = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element = fixed_dme.get_match_element("match", match_context)
        self.analysis_context.register_component(self, description)
        t = time()
        log_atom = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element), t,
                           self)

        self.assertRaises(
            Exception, self.stream_printer_event_handler.receive_event,
            self.test % self.__class__.__name__, self.new_val %
            (self.match_s1, self.match_s2, repr(match_element.match_object)),
            [log_atom.raw_data, log_atom.raw_data],
            log_atom.get_parser_match(), self)
    def test3event_data_not_log_atom(self):
        """In this test case the EventHandler receives no logAtom from the test class and the output should not contain the log time."""
        volatile_logarithmic_backoff_event_history = VolatileLogarithmicBackoffEventHistory(10)

        match_context = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element = fixed_dme.get_match_element("match", match_context)

        t = time()
        log_atom = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element), t, self)
        message = self.new_val % (self.match_s1, self.match_s2, repr(match_element.match_object))

        volatile_logarithmic_backoff_event_history.receive_event(self.test % self.__class__.__name__, message, [
            log_atom.raw_data, log_atom.raw_data], None, log_atom.get_parser_match(), self)
        self.assertEqual(
            volatile_logarithmic_backoff_event_history.get_history(), [
                (0, self.test % self.__class__.__name__, message, [
                    log_atom.raw_data, log_atom.raw_data], None, log_atom.get_parser_match(), self)])
    def test10_missing_value_on_persisted(self):
        """Persisting lists is tested in this test case."""
        description = "Test91MissingMatchPathValueDetector"
        t = time.time()
        match_context_fixed_dme = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s2', self.pid)
        match_element_fixed_dme = fixed_dme.get_match_element("match3", match_context_fixed_dme)

        match_context_decimal_integer_value_me = MatchContext(self.string)
        decimal_integer_value_me = DecimalIntegerValueModelElement('d2', DecimalIntegerValueModelElement.SIGN_TYPE_NONE,
                                                                   DecimalIntegerValueModelElement.PAD_TYPE_NONE)
        match_element_decimal_integer_value_me = decimal_integer_value_me.get_match_element(
            "match4", match_context_decimal_integer_value_me)
        missing_match_path_list_value_detector = MissingMatchPathListValueDetector(self.aminer_config, [
            match_element_fixed_dme.get_path(), match_element_decimal_integer_value_me.get_path()], [self.stream_printer_event_handler],
            'Default', True, self.__default_interval, self.__realert_interval)
        self.analysis_context.register_component(missing_match_path_list_value_detector, description)
        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element_fixed_dme), round(t),
                                     missing_match_path_list_value_detector)
        self.assertTrue(missing_match_path_list_value_detector.receive_atom(log_atom_fixed_dme))
        missing_match_path_list_value_detector.do_persist()

        past_time = 4000
        other_missing_match_path_list_value_detector = MissingMatchPathListValueDetector(self.aminer_config, [
            match_element_fixed_dme.get_path(), match_element_decimal_integer_value_me.get_path()], [self.stream_printer_event_handler],
            'Default', True, self.__default_interval, self.__realert_interval)
        self.analysis_context.register_component(other_missing_match_path_list_value_detector, description + "2")
        other_missing_match_path_list_value_detector.set_check_value(other_missing_match_path_list_value_detector.get_channel_key(
            log_atom_fixed_dme)[1], self.__default_interval - past_time, match_element_fixed_dme.get_path())

        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element_fixed_dme), round(t) + past_time,
                                     other_missing_match_path_list_value_detector)
        self.assertTrue(other_missing_match_path_list_value_detector.receive_atom(log_atom_fixed_dme))
        # skipcq: PYL-R1714
        self.assertTrue((self.output_stream.getvalue() == self.__expected_string % (
            datetime.fromtimestamp(t + past_time).strftime(self.datetime_format_string),
            other_missing_match_path_list_value_detector.__class__.__name__, description + "2", 1,
            "match3/s2, match4/d2: ' pid=' overdue 400s (interval -400)")) or (self.output_stream.getvalue() == self.__expected_string % (
              datetime.fromtimestamp(t + past_time + 1).strftime(self.datetime_format_string),
              other_missing_match_path_list_value_detector.__class__.__name__, description + "2", 1,
              "match3/s2, match4/d2: ' pid=' overdue 400s (interval -400)")))
    def test9_receive_atom_list_missing_value(self):
        """This test case checks if missing values are reported correctly."""
        description = "Test90MissingMatchPathValueDetector"
        t = time.time()
        match_context_fixed_dme = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element_fixed_dme = fixed_dme.get_match_element("match1", match_context_fixed_dme)
        match_context_decimal_integer_value_me = MatchContext(self.string)
        decimal_integer_value_me = DecimalIntegerValueModelElement('d1', DecimalIntegerValueModelElement.SIGN_TYPE_NONE,
                                                                   DecimalIntegerValueModelElement.PAD_TYPE_NONE)
        match_element_decimal_integer_value_me = decimal_integer_value_me.get_match_element(
            "match2", match_context_decimal_integer_value_me)

        missing_match_path_list_value_detector = MissingMatchPathListValueDetector(self.aminer_config, [
            match_element_fixed_dme.get_path(), match_element_decimal_integer_value_me.get_path()], [self.stream_printer_event_handler],
            'Default', True, self.__default_interval, self.__realert_interval)
        self.analysis_context.register_component(missing_match_path_list_value_detector, description)

        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element_fixed_dme), round(t),
                                     missing_match_path_list_value_detector)
        self.assertTrue(missing_match_path_list_value_detector.receive_atom(log_atom_fixed_dme))

        past_time = 4000
        missing_match_path_list_value_detector = MissingMatchPathListValueDetector(self.aminer_config, [
            match_element_fixed_dme.get_path(), match_element_decimal_integer_value_me.get_path()], [self.stream_printer_event_handler],
            'Default', True, missing_match_path_list_value_detector.default_interval - past_time, self.__realert_interval)
        self.analysis_context.register_component(missing_match_path_list_value_detector, description + "2")

        log_atom_fixed_dme = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element_fixed_dme), round(t) + past_time,
                                     missing_match_path_list_value_detector)
        self.assertTrue(missing_match_path_list_value_detector.receive_atom(log_atom_fixed_dme))
        # skipcq: PYL-R1714
        self.assertTrue((self.output_stream.getvalue() == self.__expected_string % (
            datetime.fromtimestamp(t + past_time).strftime(self.datetime_format_string),
            missing_match_path_list_value_detector.__class__.__name__, description + "2", 1,
            "match1/s1, match2/d1: ' pid=' overdue 400s (interval -400)")) or (self.output_stream.getvalue() == self.__expected_string % (
              datetime.fromtimestamp(t + past_time + 1).strftime(self.datetime_format_string),
              missing_match_path_list_value_detector.__class__.__name__, description + "2", 1,
              "match1/s1, match2/d1: ' pid=' overdue 400s (interval -400)")))
    def test1add_multiple_objects(self):
        """In this test case multiple events are received by the VolatileLogarithmicBackoffEventHistory."""
        volatile_logarithmic_backoff_event_history = VolatileLogarithmicBackoffEventHistory(10)

        match_context = MatchContext(self.pid)
        fixed_dme = FixedDataModelElement('s1', self.pid)
        match_element = fixed_dme.get_match_element("match", match_context)

        t = time()
        log_atom = LogAtom(fixed_dme.fixed_data, ParserMatch(match_element), t, self)
        message = self.new_val % (self.match_s1, self.match_s2, repr(match_element.match_object))

        volatile_logarithmic_backoff_event_history.receive_event(self.test % self.__class__.__name__, message, [
            log_atom.raw_data, log_atom.raw_data], None, log_atom, self)
        self.assertEqual(volatile_logarithmic_backoff_event_history.get_history(), [
            (0, self.test % self.__class__.__name__, message, [log_atom.raw_data, log_atom.raw_data], None, log_atom, self)])

        volatile_logarithmic_backoff_event_history.receive_event(self.test % self.__class__.__name__, message, [
            log_atom.raw_data, log_atom.raw_data], None, log_atom, self)
        self.assertEqual(volatile_logarithmic_backoff_event_history.get_history(), [
            (0, self.test % self.__class__.__name__, message, [log_atom.raw_data, log_atom.raw_data], None, log_atom, self),
            (1, self.test % self.__class__.__name__, message, [log_atom.raw_data, log_atom.raw_data], None, log_atom, self)])