From 80bcd6a032c9e3eeb489df7c9132ba65967a9e74 Mon Sep 17 00:00:00 2001 From: Antonio Date: Thu, 3 Aug 2023 15:46:47 +0200 Subject: [PATCH] fix(#3278): returning to old sha --- .../wazuh_testing/fim_module/__init__.py | 72 ++++ .../wazuh_testing/fim_module/event_monitor.py | 37 ++ .../fim_module/fim_synchronization.py | 63 ++++ .../wazuh_testing/fim_module/fim_variables.py | 93 +++++ .../wazuh_testing/wazuh_variables.py | 20 ++ .../test_syscollector/data/syscollector.yaml | 325 ++++++++++++++++++ .../data/syscollector_rules.xml | 197 +++++++++++ .../test_syscollector_events.py | 152 ++++++++ .../data/wazuh_conf_ignore_restrict.yaml | 54 +++ .../wazuh_conf_ignore_restrict_win32.yaml | 83 +++++ ...h_conf_whodata_prevails_over_realtime.yaml | 35 ++ .../data/wazuh_conf_whodata_thread.yaml | 66 ++++ .../test_audit/data/wazuh_conf.yaml | 15 + .../test_env_variables/test_dir_win32.py | 142 ++++++++ .../test_max_eps_synchronization.py | 213 ++++++++++++ .../test_files/test_report_changes/common.py | 179 ++++++++++ .../data/wazuh_conf.yaml | 43 +++ .../test_registry_limit_capacity_alerts.py | 211 ++++++++++++ .../test_registry_limit_full.py | 178 ++++++++++ .../test_registry_limit_values.py | 171 +++++++++ .../data/configuration/wazuh_location.yaml | 24 ++ .../configuration/wazuh_configuration.yaml | 13 + .../roles/master-role/tasks/main.yaml | 108 ++++++ .../roles/worker-role/tasks/main.yaml | 108 ++++++ .../agent_initializing_synchronization.yml | 4 + .../manager_initializing_synchronization.yml | 4 + 26 files changed, 2610 insertions(+) create mode 100644 deps/wazuh_testing/wazuh_testing/fim_module/__init__.py create mode 100644 deps/wazuh_testing/wazuh_testing/fim_module/event_monitor.py create mode 100644 deps/wazuh_testing/wazuh_testing/fim_module/fim_synchronization.py create mode 100644 deps/wazuh_testing/wazuh_testing/fim_module/fim_variables.py create mode 100644 deps/wazuh_testing/wazuh_testing/wazuh_variables.py create mode 100644 tests/integration/test_analysisd/test_syscollector/data/syscollector.yaml create mode 100644 tests/integration/test_analysisd/test_syscollector/data/syscollector_rules.xml create mode 100644 tests/integration/test_analysisd/test_syscollector/test_syscollector_events.py create mode 100644 tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_ignore_restrict.yaml create mode 100644 tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_ignore_restrict_win32.yaml create mode 100644 tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_whodata_prevails_over_realtime.yaml create mode 100644 tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_whodata_thread.yaml create mode 100644 tests/integration/test_fim/test_files/test_audit/data/wazuh_conf.yaml create mode 100644 tests/integration/test_fim/test_files/test_env_variables/test_dir_win32.py create mode 100644 tests/integration/test_fim/test_files/test_max_eps/test_max_eps_synchronization.py create mode 100644 tests/integration/test_fim/test_files/test_report_changes/common.py create mode 100644 tests/integration/test_fim/test_registry/test_registry_file_limit/data/wazuh_conf.yaml create mode 100644 tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_capacity_alerts.py create mode 100644 tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_full.py create mode 100644 tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_values.py create mode 100644 tests/integration/test_logcollector/test_location/data/configuration/wazuh_location.yaml create mode 100644 tests/integration/test_logcollector/test_options/data/configuration/wazuh_configuration.yaml create mode 100644 tests/system/provisioning/four_manager_disconnected_node/roles/master-role/tasks/main.yaml create mode 100644 tests/system/provisioning/four_manager_disconnected_node/roles/worker-role/tasks/main.yaml create mode 100644 tests/system/test_fim/test_synchronization/data/agent_initializing_synchronization.yml create mode 100644 tests/system/test_fim/test_synchronization/data/manager_initializing_synchronization.yml diff --git a/deps/wazuh_testing/wazuh_testing/fim_module/__init__.py b/deps/wazuh_testing/wazuh_testing/fim_module/__init__.py new file mode 100644 index 0000000000..f1bb1d3658 --- /dev/null +++ b/deps/wazuh_testing/wazuh_testing/fim_module/__init__.py @@ -0,0 +1,72 @@ +# Copyright (C) 2015-2022, Wazuh Inc. +# Created by Wazuh, Inc. . +# This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + +''' +The purpose of this file is to contain all the variables necessary for FIM in order to be easier to +maintain if one of them changes in the future. +''' + +# Variables +SIZE_LIMIT_CONFIGURED_VALUE = 10240 +# Key variables +WINDOWS_HKEY_LOCAL_MACHINE = 'HKEY_LOCAL_MACHINE' +MONITORED_KEY = 'SOFTWARE\\random_key' +MONITORED_KEY_2 = "SOFTWARE\\Classes\\random_key_2" +WINDOWS_REGISTRY = 'WINDOWS_REGISTRY' + + +# Value key +SYNC_INTERVAL = 'SYNC_INTERVAL' +SYNC_INTERVAL_VALUE = MAX_EVENTS_VALUE = 20 + +# Folders variables +TEST_DIR_1 = 'testdir1' +TEST_DIRECTORIES = 'TEST_DIRECTORIES' +TEST_REGISTRIES = 'TEST_REGISTRIES' + +# FIM modules +SCHEDULE_MODE = 'scheduled' + +# Yaml Configuration +YAML_CONF_REGISTRY_RESPONSE = 'wazuh_conf_registry_responses_win32.yaml' +YAML_CONF_SYNC_WIN32 = 'wazuh_sync_conf_win32.yaml' + +# Synchronization options +SYNCHRONIZATION_ENABLED = 'SYNCHRONIZATION_ENABLED' +SYNCHRONIZATION_REGISTRY_ENABLED = 'SYNCHRONIZATION_REGISTRY_ENABLED' + +# Callbacks message +INTEGRITY_CONTROL_MESSAGE = r'.*Sending integrity control message: (.+)$' +REGISTRY_DBSYNC_NO_DATA = r'.*#!-fim_registry dbsync no_data (.+)' +CB_FILE_LIMIT_CAPACITY = r".*Sending DB (\d+)% full alert." +CB_FILE_LIMIT_BACK_TO_NORMAL = r".*(Sending DB back to normal alert)." +CB_COUNT_REGISTRY_FIM_ENTRIES = r".*Fim registry entries: (\d+)" +CB_DATABASE_FULL_COULD_NOT_INSERT = r".*Couldn't insert ('.*')? entry into DB\. The DB is full.*" +CB_DATABASE_FULL_COULD_NOT_INSERT_VALUE = r".*Couldn't insert ('.*')? value entry into DB\. The DB is full.*" +CB_FILE_LIMIT_VALUE = r".*Maximum number of entries to be monitored: '(\d+)'" +CB_FILE_SIZE_LIMIT_BIGGER_THAN_DISK_QUOTA = r".*Setting 'disk_quota' to (\d+), 'disk_quota' must be greater than 'file_size'" +CB_FILE_LIMIT_DISABLED = r".*(No limit set) to maximum number of entries to be monitored" +CB_INODE_ENTRIES_PATH_COUNT = r".*Fim inode entries: (\d+), path count: (\d+)" +CB_FIM_ENTRIES_COUNT =r".*Fim entries: (\d+)" +CB_DETECT_FIM_EVENT = r'.*Sending FIM event: (.+)$' + +#Error Messages +ERR_MSG_DATABASE_PERCENTAGE_FULL_ALERT = 'Did not receive expected "DEBUG: ...: Sending DB ...% full alert." event' +ERR_MSG_FIM_INODE_ENTRIES = 'Did not receive expected "Fim inode entries: ..., path count: ..." event' +ERR_MSG_DB_BACK_TO_NORMAL = 'Did not receive expected "DEBUG: ...: Sending DB back to normal alert." event' +ERR_MSG_DATABASE_FULL_ALERT_EVENT = 'Did not receive expected "DEBUG: ...: Sending DB 100% full alert." event' +ERR_MSG_DATABASE_FULL_COULD_NOT_INSERT = 'Did not receive expected "DEBUG: ...: Couldn\'t insert \'...\' entry into DB. The DB is full, ..." event' +ERR_MSG_FILE_LIMIT_VALUES = 'Did not receive expected "DEBUG: ...: Maximum number of entries to be monitored: ..." event' +ERR_MSG_WRONG_VALUE_FOR_DATABASE_FULL = 'Wrong value for full database alert.' +ERR_MSG_DISK_QUOTA_MUST_BE_GREATER = "Did not receive expected 'DEBUG: ... disk_quota must be greater than file_size message'" +ERR_MSG_CONTENT_CHANGES_EMPTY = "content_changes is empty" +ERR_MSG_CONTENT_CHANGES_NOT_EMPTY = "content_changes isn't empty" +ERR_MSG_FILE_LIMIT_DISABLED = 'Did not receive expected "DEBUG: ...: No limit set to maximum number of entries to be monitored" event' +ERR_MSG_NO_EVENTS_EXPECTED = 'No events should be detected.' +ERR_MSG_DELETED_EVENT_NOT_RECIEVED = 'Did not receive expected deleted event' +ERR_MSG_WRONG_NUMBER_OF_ENTRIES = 'Wrong number of entries counted.' +ERR_MSG_WRONG_INODE_PATH_COUNT = 'Wrong number of inodes and path count' +ERR_MSG_WRONG_FILE_LIMIT_VALUE ='Wrong value for file_limit.' +ERR_MSG_WRONG_DISK_QUOTA_VALUE ='Wrong value for disk_quota' +ERR_MSG_WRONG_CAPACITY_LOG_DB_LIMIT= 'Wrong capacity log for DB file_limit' diff --git a/deps/wazuh_testing/wazuh_testing/fim_module/event_monitor.py b/deps/wazuh_testing/wazuh_testing/fim_module/event_monitor.py new file mode 100644 index 0000000000..bb18dc7573 --- /dev/null +++ b/deps/wazuh_testing/wazuh_testing/fim_module/event_monitor.py @@ -0,0 +1,37 @@ +# Copyright (C) 2015-2022, Wazuh Inc. +# Created by Wazuh, Inc. . +# This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + + +import re +import json +from sys import platform +from wazuh_testing import logger +from wazuh_testing.fim_module import (CB_INODE_ENTRIES_PATH_COUNT, CB_FIM_ENTRIES_COUNT, CB_DETECT_FIM_EVENT) + + +def callback_detect_event(line): + msg = CB_DETECT_FIM_EVENT + match = re.match(msg, line) + if not match: + return None + + try: + json_event = json.loads(match.group(1)) + if json_event['type'] == 'event': + return json_event + except (json.JSONDecodeError, AttributeError, KeyError) as e: + logger.warning(f"Couldn't load a log line into json object. Reason {e}") + + +def callback_entries_path_count(line): + if platform != 'win32': + match = re.match(CB_INODE_ENTRIES_PATH_COUNT, line) + else: + match = re.match(CB_FIM_ENTRIES_COUNT, line) + + if match: + if platform != 'win32': + return match.group(1), match.group(2) + else: + return match.group(1), None diff --git a/deps/wazuh_testing/wazuh_testing/fim_module/fim_synchronization.py b/deps/wazuh_testing/wazuh_testing/fim_module/fim_synchronization.py new file mode 100644 index 0000000000..889d2b8c8a --- /dev/null +++ b/deps/wazuh_testing/wazuh_testing/fim_module/fim_synchronization.py @@ -0,0 +1,63 @@ +# Copyright (C) 2015-2021, Wazuh Inc. +# Created by Wazuh, Inc. . +# This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + +from wazuh_testing.fim import LOG_FILE_PATH, callback_detect_registry_integrity_state_event +from wazuh_testing import global_parameters +from wazuh_testing.fim_module.fim_variables import MAX_EVENTS_VALUE, CB_REGISTRY_DBSYNC_NO_DATA +from wazuh_testing.tools.monitoring import FileMonitor, generate_monitoring_callback + + +def get_sync_msgs(tout, new_data=True): + """Look for as many synchronization events as possible. + + This function will look for the synchronization messages until a Timeout is raised or 'max_events' is reached. + + Args: + tout (int): Timeout that will be used to get the dbsync_no_data message. + new_data (bool): Specifies if the test will wait the event `dbsync_no_data`. + + Returns: + A list with all the events in json format. + """ + wazuh_log_monitor = FileMonitor(LOG_FILE_PATH) + events = [] + if new_data: + wazuh_log_monitor.start(timeout=tout, + callback=generate_monitoring_callback(CB_REGISTRY_DBSYNC_NO_DATA), + error_message='Did not receive expected ' + '"db sync no data" event') + for _ in range(0, MAX_EVENTS_VALUE): + try: + sync_event = wazuh_log_monitor.start(timeout=global_parameters.default_timeout, + callback=callback_detect_registry_integrity_state_event, + accum_results=1, + error_message='Did not receive expected ' + 'Sending integrity control message"').result() + except TimeoutError: + break + + events.append(sync_event) + + return events + + +def find_value_in_event_list(key_path, value_name, event_list): + """Function that looks for a key path and value_name in a list of json events. + + Args: + path (str): Path of the registry key. + value_name (str): Name of the value. + event_list (list): List containing the events in JSON format. + + Returns: + The event that matches the specified path. None if no event was found. + """ + for event in event_list: + if 'value_name' not in event.keys(): + continue + + if event['path'] == key_path and event['value_name'] == value_name: + return event + + return None diff --git a/deps/wazuh_testing/wazuh_testing/fim_module/fim_variables.py b/deps/wazuh_testing/wazuh_testing/fim_module/fim_variables.py new file mode 100644 index 0000000000..d2b2f7ba3c --- /dev/null +++ b/deps/wazuh_testing/wazuh_testing/fim_module/fim_variables.py @@ -0,0 +1,93 @@ +# Copyright (C) 2015-2021, Wazuh Inc. +# Created by Wazuh, Inc. . +# This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + +''' +The purpose of this file is to contain all the variables necessary for FIM in order to be easier to +maintain if one of them changes in the future. + +UPDATE: This file is deprecated. Add new variables to de fim_module/__init__.py file. If this is used +in a test, refactor the imports to adhere to the new standard. +''' + +# Variables +SIZE_LIMIT_CONFIGURED_VALUE = 10 * 1024 + +# Key Variables +WINDOWS_HKEY_LOCAL_MACHINE = 'HKEY_LOCAL_MACHINE' +MONITORED_KEY = 'SOFTWARE\\random_key' +MONITORED_KEY_2 = "SOFTWARE\\Classes\\random_key_2" +WINDOWS_REGISTRY = 'WINDOWS_REGISTRY' + + +# Value Key +SYNC_INTERVAL = 'SYNC_INTERVAL' +SYNC_INTERVAL_VALUE = MAX_EVENTS_VALUE = 20 + + +# Folder Variables +TEST_DIR_1 = 'testdir1' +TEST_DIRECTORIES = 'TEST_DIRECTORIES' +TEST_REGISTRIES = 'TEST_REGISTRIES' + + +# Syscheck Attributes +REPORT_CHANGES = 'report_changes' +DIFF_SIZE_LIMIT = 'diff_size_limit' +FILE_SIZE_ENABLED = 'FILE_SIZE_ENABLED' +FILE_SIZE_LIMIT = 'FILE_SIZE_LIMIT' +DISK_QUOTA_ENABLED = 'DISK_QUOTA_ENABLED' +DISK_QUOTA_LIMIT = 'DISK_QUOTA_LIMIT' + +# Syscheck Values +DIFF_LIMIT_VALUE = 2 +DIFF_DEFAULT_LIMIT_VALUE = 51200 + + +# FIM Modes +SCHEDULE_MODE = 'scheduled' + +# Yaml Configuration +YAML_CONF_REGISTRY_RESPONSE = 'wazuh_conf_registry_responses_win32.yaml' +YAML_CONF_SYNC_WIN32 = 'wazuh_sync_conf_win32.yaml' +YAML_CONF_DIFF = 'wazuh_conf_diff.yaml' + +# Synchronization Options +SYNCHRONIZATION_ENABLED = 'SYNCHRONIZATION_ENABLED' +SYNCHRONIZATION_REGISTRY_ENABLED = 'SYNCHRONIZATION_REGISTRY_ENABLED' + +# Callback Messages +CB_INTEGRITY_CONTROL_MESSAGE = r'.*Sending integrity control message: (.+)$' +CB_REGISTRY_DBSYNC_NO_DATA = r'.*#!-fim_registry dbsync no_data (.+)' +CB_FILE_LIMIT_CAPACITY = r".*Sending DB (\d+)% full alert." +CB_FILE_LIMIT_BACK_TO_NORMAL = r".*(Sending DB back to normal alert)." +CB_COUNT_REGISTRY_FIM_ENTRIES = r".*Fim registry entries: (\d+)" +CB_DATABASE_FULL_COULD_NOT_INSERT = r".*Couldn't insert '.*' (value )?entry into DB\. The DB is full.*" +CB_FILE_LIMIT_VALUE = r".*Maximum number of entries to be monitored: '(\d+)'" +CB_FILE_SIZE_LIMIT_BIGGER_THAN_DISK_QUOTA = r".*Setting 'disk_quota' to (\d+), 'disk_quota' must be greater than 'file_size'" +CB_MAXIMUM_FILE_SIZE = r'.*Maximum file size limit to generate diff information configured to \'(\d+) KB\'.*' +CB_FILE_LIMIT_CAPACITY = r".*Sending DB (\d+)% full alert." +CB_FILE_LIMIT_BACK_TO_NORMAL = r".*(Sending DB back to normal alert)." +CB_COUNT_REGISTRY_FIM_ENTRIES = r".*Fim registry entries: (\d+)" +CB_DATABASE_FULL_COULD_NOT_INSERT = r".*Couldn't insert '.*' (value )?entry into DB\. The DB is full.*" +CB_FILE_LIMIT_VALUE = r".*Maximum number of entries to be monitored: '(\d+)'" +CB_FILE_SIZE_LIMIT_BIGGER_THAN_DISK_QUOTA = r".*Setting 'disk_quota' to (\d+), 'disk_quota' must be greater than 'file_size'" +CB_MAXIMUM_FILE_SIZE = r'.*Maximum file size limit to generate diff information configured to \'(\d+) KB\'.*' + + +#Error Messages +ERR_MSG_DATABASE_PERCENTAGE_FULL_ALERT = 'Did not receive expected "DEBUG: ...: Sending DB ...% full alert." event' +ERR_MSG_FIM_INODE_ENTRIES = 'Did not receive expected "Fim inode entries: ..., path count: ..." event' +ERR_MSG_DB_BACK_TO_NORMAL = 'Did not receive expected "DEBUG: ...: Sending DB back to normal alert." event' +ERR_MSG_WRONG_NUMBER_OF_ENTRIES = 'Wrong number of entries counted.' +ERR_MSG_WRONG_FILE_LIMIT_VALUE ='Wrong value for file_limit.' +ERR_MSG_WRONG_DISK_QUOTA_VALUE ='Wrong value for disk_quota' +ERR_MSG_DATABASE_FULL_ALERT_EVENT = 'Did not receive expected "DEBUG: ...: Sending DB 100% full alert." event' +ERR_MSG_DATABASE_FULL_COULD_NOT_INSERT = 'Did not receive expected "DEBUG: ...: Couldn\'t insert \'...\' entry into DB. The DB is full, ..." event' +ERR_MSG_FILE_LIMIT_VALUES = 'Did not receive expected "DEBUG: ...: Maximum number of entries to be monitored: ..." event' +ERR_MSG_WRONG_VALUE_FOR_DATABASE_FULL = 'Wrong value for full database alert.' +ERR_MSG_DISK_QUOTA_MUST_BE_GREATER = "Did not receive expected 'DEBUG: ... disk_quota must be greater than file_size message'" +ERR_MSG_CONTENT_CHANGES_EMPTY = "content_changes is empty" +ERR_MSG_CONTENT_CHANGES_NOT_EMPTY = "content_changes isn't empty" +ERR_MSG_MAXIMUM_FILE_SIZE = 'Did not receive expected "Maximum file size limit configured to \'... KB\'..." event' +ERR_MSG_WRONG_VALUE_MAXIMUM_FILE_SIZE = 'Wrong value for diff_size_limit' diff --git a/deps/wazuh_testing/wazuh_testing/wazuh_variables.py b/deps/wazuh_testing/wazuh_testing/wazuh_variables.py new file mode 100644 index 0000000000..7842698028 --- /dev/null +++ b/deps/wazuh_testing/wazuh_testing/wazuh_variables.py @@ -0,0 +1,20 @@ +# Copyright (C) 2015-2021, Wazuh Inc. +# Created by Wazuh, Inc. . +# This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + +''' +The purpose of this file is to contain all the variables necessary for Wazuh in order to be easier +to maintain if one of them changes in the future. +''' +# Local internal options +WINDOWS_DEBUG = 'windows.debug' +SYSCHECK_DEBUG = 'syscheck.debug' +VERBOSE_DEBUG_OUTPUT = 2 + +WAZUH_SERVICES_STOP = 'stop' +WAZUH_SERVICES_START = 'start' + + +# Configurations +DATA = 'data' +WAZUH_LOG_MONITOR = 'wazuh_log_monitor' diff --git a/tests/integration/test_analysisd/test_syscollector/data/syscollector.yaml b/tests/integration/test_analysisd/test_syscollector/data/syscollector.yaml new file mode 100644 index 0000000000..3db7441174 --- /dev/null +++ b/tests/integration/test_analysisd/test_syscollector/data/syscollector.yaml @@ -0,0 +1,325 @@ +- + name: Test syscollector events + rule_file: syscollector_rules.xml + event_header: '(myhostname) any->syscollector:' + test_case: + - + description: Process creation + event_payload: >- + {"data":{"argvs":"180","checksum":"343ed10dc637334a7400d01b8a28deb8db5cba28","cmd":"","egroup":"root", + "euser":"root","fgroup":"root","name":"sleep","nice":0,"nlwp":1,"pgrp":116167,"pid":"156102","ppid":116169, + "priority":20,"processor":3,"resident":129,"rgroup":"root","ruser":"root","scan_time":"2021/10/13 14:57:07", + "session":116167,"sgroup":"root","share":114,"size":2019,"start_time":5799612,"state":"S","stime":0, + "suser":"root","tgid":156102,"tty":0,"utime":0,"vm_size":8076},"operation":"INSERTED", + "type":"dbsync_processes"} + alert_expected_values: + rule.id: '100301' + data: >- + {"type":"dbsync_processes","process":{"pid":"156102","name":"sleep","state":"S","ppid":"116169","utime":"0", + "stime":"0","args":"180","euser":"root","ruser":"root","suser":"root","egroup":"root","rgroup":"root", + "sgroup":"root","fgroup":"root","priority":"20","nice":"0","size":"2019","vm_size":"8076","resident":"129", + "share":"114","start_time":"5799612","pgrp":"116167","session":"116167","nlwp":"1","tgid":"156102","tty":"0", + "processor":"3"},"operation_type":"INSERTED"} + - + description: Process modification + event_payload: >- + {"data":{"argvs":"180","checksum":"45cb0637a5b43ed1a819ac6cb4cf4d6d4f15f87","cmd":"","egroup":"root", + "euser":"root","fgroup":"root","name":"sleep","nice":0,"nlwp":1,"pgrp":116167,"pid":"156102","ppid":116169, + "priority":10,"processor":3,"resident":129,"rgroup":"root","ruser":"root","scan_time":"2021/10/13 14:57:08", + "session":116167,"sgroup":"root","share":114,"size":2019,"start_time":5799612,"state":"S","stime":0, + "suser":"root","tgid":156102,"tty":0,"utime":0,"vm_size":8076},"operation":"MODIFIED", + "type":"dbsync_processes"} + + alert_expected_values: + rule.id: '100302' + data: >- + {"type":"dbsync_processes","process":{"pid":"156102","name":"sleep","state":"S","ppid":"116169","utime":"0", + "stime":"0","args":"180","euser":"root","ruser":"root","suser":"root","egroup":"root","rgroup":"root", + "sgroup":"root","fgroup":"root","priority":"10","nice":"0","size":"2019","vm_size":"8076","resident":"129", + "share":"114","start_time":"5799612","pgrp":"116167","session":"116167","nlwp":"1","tgid":"156102","tty":"0", + "processor":"3"},"operation_type":"MODIFIED"} + - + description: Process deletion + event_payload: >- + {"data":{"argvs":"180","checksum":"45cb0637a5b43ed1a819ac6cb4cf4d6d4f15f87","cmd":"","egroup":"root", + "euser":"root","fgroup":"root","name":"sleep","nice":0,"nlwp":1,"pgrp":116167,"pid":"156102","ppid":116169, + "priority":10,"processor":3,"resident":129,"rgroup":"root","ruser":"root","scan_time":"2021/10/13 14:57:09", + "session":116167,"sgroup":"root","share":114,"size":2019,"start_time":5799612,"state":"S","stime":0, + "suser":"root","tgid":156102,"tty":0,"utime":0,"vm_size":8076},"operation":"DELETED", + "type":"dbsync_processes"} + alert_expected_values: + rule.id: '100303' + data: >- + {"type":"dbsync_processes","process":{"pid":"156102","name":"sleep","state":"S","ppid":"116169","utime":"0", + "stime":"0","args":"180","euser":"root","ruser":"root","suser":"root","egroup":"root","rgroup":"root", + "sgroup":"root","fgroup":"root","priority":"10","nice":"0","size":"2019","vm_size":"8076","resident":"129", + "share":"114","start_time":"5799612","pgrp":"116167","session":"116167","nlwp":"1","tgid":"156102","tty":"0", + "processor":"3"},"operation_type":"DELETED"} + - + description: Port creation + event_payload: >- + {"data":{"checksum":"eff13e52290143eb5b5b9b8c191902609f37c712","inode":494908, + "item_id":"e2c92964ad145a635139f6318057506e386e00a3","local_ip":"0.0.0.0","local_port":34340,"pid":0, + "process":null,"protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0, + "scan_time":"2021/10/13 14:40:02","state":"listening","tx_queue":0},"operation":"INSERTED", + "type":"dbsync_ports"} + alert_expected_values: + rule.id: '100311' + data: >- + {"type":"dbsync_ports","port":{"protocol":"tcp","local_ip":"0.0.0.0","local_port":"34340", + "remote_ip":"0.0.0.0","remote_port":"0","tx_queue":"0","rx_queue":"0","inode":"494908","state":"listening", + "pid":"0"},"operation_type":"INSERTED"} + - + description: Port modification + event_payload: >- + {"data":{"checksum":"eff13e52290143eb5b5b9b8c191902609f37c713","inode":494908, + "item_id":"e2c92964ad145a635139f6318057506e386e00a3","local_ip":"0.0.0.0","local_port":34340,"pid":0, + "process":null,"protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":1, + "scan_time":"2021/10/13 14:40:03","state":"listening","tx_queue":1},"operation":"MODIFIED", + "type":"dbsync_ports"} + alert_expected_values: + rule.id: '100312' + data: >- + {"type":"dbsync_ports","port":{"protocol":"tcp","local_ip":"0.0.0.0","local_port":"34340", + "remote_ip":"0.0.0.0","remote_port":"0","tx_queue":"1","rx_queue":"1","inode":"494908","state":"listening", + "pid":"0"},"operation_type":"MODIFIED"} + - + description: Port deletion + event_payload: >- + {"data":{"checksum":"eff13e52290143eb5b5b9b8c191902609f37c713","inode":494908, + "item_id":"e2c92964ad145a635139f6318057506e386e00a3","local_ip":"0.0.0.0","local_port":34340,"pid":0, + "process":null,"protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":1, + "scan_time":"2021/10/13 14:40:04","state":"listening","tx_queue":1},"operation":"DELETED", + "type":"dbsync_ports"} + alert_expected_values: + rule.id: '100313' + data: >- + {"type":"dbsync_ports","port":{"protocol":"tcp","local_ip":"0.0.0.0","local_port":"34340", + "remote_ip":"0.0.0.0","remote_port":"0","tx_queue":"1","rx_queue":"1","inode":"494908","state":"listening", + "pid":"0"},"operation_type":"DELETED"} + - + description: Osinfo creation + event_payload: >- + {"data":{"checksum":"1634140017886803554","architecture":"x86_64","hostname":"UBUNTU","os_build":"7601", + "os_major":"6","os_minor":"1","os_name":"Microsoft Windows 7","os_release":"sp1","os_version":"6.1.7601", + "os_display_version":"test"},"operation":"INSERTED","type":"dbsync_osinfo"} + alert_expected_values: + rule.id: '100321' + data: >- + {"type":"dbsync_osinfo","os":{"hostname":"UBUNTU","architecture":"x86_64","name":"Microsoft Windows 7", + "version":"6.1.7601","major":"6","minor":"1","build":"7601","os_release":"sp1","display_version":"test"}, + "operation_type":"INSERTED"} + - + description: Osinfo modification + event_payload: >- + {"data":{"checksum":"1634140017886803554","architecture":"x86_64","hostname":"UBUNTU","os_build":"7601", + "os_major":"6","os_minor":"1","os_name":"Microsoft Windows 7","os_release":"sp1","os_version":"6.1.7601", + "os_display_version":"test_text"},"operation":"MODIFIED","type":"dbsync_osinfo"} + alert_expected_values: + rule.id: '100322' + data: >- + {"type":"dbsync_osinfo","os":{"hostname":"UBUNTU","architecture":"x86_64","name":"Microsoft Windows 7", + "version":"6.1.7601","major":"6","minor":"1","build":"7601","os_release":"sp1","display_version":"test_text"}, + "operation_type":"MODIFIED"} + - + description: Hwinfo creation + event_payload: >- + {"data":{"scan_time":"2021/10/13 14:41:43","board_serial":"Intel Corporation", + "checksum":"af7b22eef8f5e06c04af4db49c9f8d1d28963918","cpu_MHz":2904,"cpu_cores":2, + "cpu_name":"Intel(R) Core(TM) i5-9400 CPU @ 2.90GHz","ram_free":2257872,"ram_total":4972208,"ram_usage":54}, + "operation":"INSERTED","type":"dbsync_hwinfo"} + alert_expected_values: + rule.id: '100331' + data: >- + {"type":"dbsync_hwinfo","hardware":{"serial":"Intel Corporation", + "cpu_name":"Intel(R) Core(TM) i5-9400 CPU @ 2.90GHz","cpu_cores":"2","cpu_mhz":"2904","ram_total":"4972208", + "ram_free":"2257872","ram_usage":"54"},"operation_type":"INSERTED"} + - + description: Hwinfo modification + event_payload: >- + {"data":{"scan_time":"2021/10/13 14:41:44","board_serial":"Intel Corporation", + "checksum":"af7b22eef8f5e06c04af4db49c9f8d1d28963919","cpu_MHz":2904,"cpu_cores":4, + "cpu_name":"Intel(R) Core(TM) i5-9400 CPU @ 2.90GHz","ram_free":2257872,"ram_total":4972208,"ram_usage":54}, + "operation":"MODIFIED","type":"dbsync_hwinfo"} + alert_expected_values: + rule.id: '100332' + data: >- + {"type":"dbsync_hwinfo","hardware":{"serial":"Intel Corporation", + "cpu_name":"Intel(R) Core(TM) i5-9400 CPU @ 2.90GHz","cpu_cores":"4","cpu_mhz":"2904","ram_total":"4972208", + "ram_free":"2257872","ram_usage":"54"},"operation_type":"MODIFIED"} + - + description: Package creation + event_payload: >- + {"data":{"architecture":"amd64","checksum":"1c1bf8bbc20caef77010f960461cc20fb9c67568", + "description":"Qt 5 OpenGL module","format":"deb","groups":"libs", + "item_id":"caa4868d177fbebc5b145a2a92497ebcf566838a","multiarch":"same","name":"libqt5opengl5", + "priority":"optional","scan_time":"2021/10/13 15:10:49","size":572,"source":"qtbase-opensource-src", + "vendor":"Ubuntu Developers ","version":"5.12.8+dfsg-0ubuntu1"}, + "operation":"INSERTED","type":"dbsync_packages"} + alert_expected_values: + rule.id: '100341' + data: >- + {"type":"dbsync_packages","program":{"format":"deb","name":"libqt5opengl5","priority":"optional", + "section":"libs","size":"572","vendor":"Ubuntu Developers ", + "version":"5.12.8+dfsg-0ubuntu1","architecture":"amd64","multiarch":"same","source":"qtbase-opensource-src", + "description":"Qt 5 OpenGL module"},"operation_type":"INSERTED"} + - + description: Package modification + event_payload: >- + {"data":{"architecture":"amd64","checksum":"1c1bf8bbc20caef77010f960461cc20fb9c67569", + "description":"Qt 5 OpenGL module","format":"deb","groups":"libs", + "item_id":"caa4868d177fbebc5b145a2a92497ebcf566838a","multiarch":"same","name":"libqt5opengl5", + "priority":"option","scan_time":"2021/10/13 15:10:50","size":572,"source":"qtbase-opensource-src", + "vendor":"Ubuntu Developers ","version":"5.12.8+dfsg-0ubuntu1"}, + "operation":"MODIFIED","type":"dbsync_packages"} + alert_expected_values: + rule.id: '100342' + data: >- + {"type":"dbsync_packages","program":{"format":"deb","name":"libqt5opengl5","priority":"option", + "section":"libs","size":"572","vendor":"Ubuntu Developers ", + "version":"5.12.8+dfsg-0ubuntu1","architecture":"amd64","multiarch":"same","source":"qtbase-opensource-src", + "description":"Qt 5 OpenGL module"},"operation_type":"MODIFIED"} + - + description: Package deletion + event_payload: >- + {"data":{"architecture":"amd64","checksum":"1c1bf8bbc20caef77010f960461cc20fb9c67569", + "description":"Qt 5 OpenGL module","format":"deb","groups":"libs", + "item_id":"caa4868d177fbebc5b145a2a92497ebcf566838a","multiarch":"same","name":"libqt5opengl5", + "priority":"option","scan_time":"2021/10/13 15:10:51","size":572,"source":"qtbase-opensource-src", + "vendor":"Ubuntu Developers ","version":"5.12.8+dfsg-0ubuntu1"}, + "operation":"DELETED","type":"dbsync_packages"} + alert_expected_values: + rule.id: '100343' + data: >- + {"type":"dbsync_packages","program":{"format":"deb","name":"libqt5opengl5","priority":"option", + "section":"libs","size":"572","vendor":"Ubuntu Developers ", + "version":"5.12.8+dfsg-0ubuntu1","architecture":"amd64","multiarch":"same","source":"qtbase-opensource-src", + "description":"Qt 5 OpenGL module"},"operation_type":"DELETED"} + - + description: Network interface creation + event_payload: >- + {"data":{"adapter":null,"checksum":"ce57e9ae697de4e427b67fea0d28c25e130249b7", + "item_id":"7ca46dd4c59f73c36a44ee5ebb0d0a37db4187a9","mac":"92:27:3b:ee:11:96","mtu":1500,"name":"dummy0", + "rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"scan_time":"2021/10/13 18:32:06","state":"down", + "tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0,"type":"ethernet"},"operation":"INSERTED", + "type":"dbsync_network_iface"} + alert_expected_values: + rule.id: '100351' + data: >- + {"type":"dbsync_network_iface","netinfo":{"iface":{"name":"dummy0","type":"ethernet","state":"down", + "mtu":"1500","mac":"92:27:3b:ee:11:96","tx_packets":"0","rx_packets":"0","tx_bytes":"0","rx_bytes":"0", + "tx_errors":"0","rx_errors":"0","tx_dropped":"0","rx_dropped":"0"}},"operation_type":"INSERTED"} + - + description: Network interface modification + event_payload: >- + {"data":{"adapter":null,"checksum":"ce57e9ae697de4e427b67fea0d28c25e130249b8", + "item_id":"7ca46dd4c59f73c36a44ee5ebb0d0a37db4187a9","mac":"92:27:3b:ee:11:96","mtu":1500,"name":"dummy0", + "rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"scan_time":"2021/10/13 18:32:07","state":"up", + "tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0,"type":"ethernet"},"operation":"MODIFIED", + "type":"dbsync_network_iface"} + alert_expected_values: + rule.id: '100352' + data: >- + {"type":"dbsync_network_iface","netinfo":{"iface":{"name":"dummy0","type":"ethernet","state":"up", + "mtu":"1500","mac":"92:27:3b:ee:11:96","tx_packets":"0","rx_packets":"0","tx_bytes":"0","rx_bytes":"0", + "tx_errors":"0","rx_errors":"0","tx_dropped":"0","rx_dropped":"0"}},"operation_type":"MODIFIED"} + - + description: Network protocol creation + event_payload: >- + {"data":{"checksum":"3d8855caa85501d22b40fa6616c0670f206b2c4e","gateway":" ","dhcp":"enabled","iface":"dummy0", + "item_id":"7ca46dd4c59f73c36a44ee5ebb0d0a37db4187a9","scan_time":"2021/10/13 18:32:06","type":"ethernet"}, + "operation":"INSERTED","type":"dbsync_network_protocol"} + alert_expected_values: + rule.id: '100361' + data: >- + {"type":"dbsync_network_protocol","netinfo":{"proto":{"iface":"dummy0","type":"ethernet","gateway":" ", + "dhcp":"enabled"}},"operation_type":"INSERTED"} + - + description: Network protocol modification + event_payload: >- + {"data":{"checksum":"3d8855caa85501d22b40fa6616c0670f206b2ca4","gateway":" ","dhcp":"disabled","iface":"dummy0", + "item_id":"7ca46dd4c59f73c36a44ee5ebb0d0a37db4187a9","scan_time":"2021/10/13 18:32:06","type":"ethernet"}, + "operation":"MODIFIED","type":"dbsync_network_protocol"} + alert_expected_values: + rule.id: '100362' + data: >- + {"type":"dbsync_network_protocol","netinfo":{"proto":{"iface":"dummy0","type":"ethernet","gateway":" ", + "dhcp":"disabled"}},"operation_type":"MODIFIED"} + - + description: Network protocol deletion + event_payload: >- + {"data":{"checksum":"3d8855caa85501d22b40fa6616c0670f206b2ca4","gateway":" ","dhcp":"disabled","iface":"dummy0", + "item_id":"7ca46dd4c59f73c36a44ee5ebb0d0a37db4187a9","scan_time":"2021/10/13 18:32:06","type":"ethernet"}, + "operation":"DELETED","type":"dbsync_network_protocol"} + alert_expected_values: + rule.id: '100363' + data: >- + {"type":"dbsync_network_protocol","netinfo":{"proto":{"iface":"dummy0","type":"ethernet","gateway":" ", + "dhcp":"disabled"}},"operation_type":"DELETED"} + - + description: Network interface deletion + event_payload: >- + {"data":{"adapter":null,"checksum":"ce57e9ae697de4e427b67fea0d28c25e130249b8", + "item_id":"7ca46dd4c59f73c36a44ee5ebb0d0a37db4187a9","mac":"92:27:3b:ee:11:96","mtu":1500,"name":"dummy0", + "rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"scan_time":"2021/10/13 18:32:07","state":"up", + "tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0,"type":"ethernet"},"operation":"DELETED", + "type":"dbsync_network_iface"} + alert_expected_values: + rule.id: '100353' + data: >- + {"type":"dbsync_network_iface","netinfo":{"iface":{"name":"dummy0","type":"ethernet","state":"up", + "mtu":"1500","mac":"92:27:3b:ee:11:96","tx_packets":"0","rx_packets":"0","tx_bytes":"0","rx_bytes":"0", + "tx_errors":"0","rx_errors":"0","tx_dropped":"0","rx_dropped":"0"}},"operation_type":"DELETED"} + - + description: Network address creation + event_payload: >- + {"data":{"address":"192.168.100.12","broadcast":"192.168.100.255", + "checksum":"ec5e14340b8ced5b39cbcfa9abecbfdbd1f2873f","dhcp":"unknown","iface":"enp0s3", + "item_id":"7b4e5f1da50834d71d895a3065a3bb098a0b8a5c","metric":"100","netmask":"255.255.255.0","proto":0, + "scan_time":"2021/10/13 16:46:37"},"operation":"INSERTED","type":"dbsync_network_address"} + alert_expected_values: + rule.id: '100371' + data: >- + {"type":"dbsync_network_address","netinfo":{"addr":{"iface":"enp0s3","proto":"ipv4","address":"192.168.100.12", + "netmask":"255.255.255.0","broadcast":"192.168.100.255"}},"operation_type":"INSERTED"} + - + description: Network address modification + event_payload: >- + {"data":{"address":"192.168.100.12","broadcast":"192.168.100.254", + "checksum":"ec5e14340b8ced5b39cbcfa9abecbfdbd1f2873f","dhcp":"unknown","iface":"enp0s3", + "item_id":"7b4e5f1da50834d71d895a3065a3bb098a0b8a5c","metric":"100","netmask":"255.255.255.0","proto":0, + "scan_time":"2021/10/13 16:46:38"},"operation":"MODIFIED","type":"dbsync_network_address"} + alert_expected_values: + rule.id: '100372' + data: >- + {"type":"dbsync_network_address","netinfo":{"addr":{"iface":"enp0s3","proto":"ipv4","address":"192.168.100.12", + "netmask":"255.255.255.0","broadcast":"192.168.100.254"}},"operation_type":"MODIFIED"} + - + description: Network address deletion + event_payload: >- + {"data":{"address":"192.168.100.12","broadcast":"192.168.100.254", + "checksum":"ec5e14340b8ced5b39cbcfa9abecbfdbd1f2873f","dhcp":"unknown","iface":"enp0s3", + "item_id":"7b4e5f1da50834d71d895a3065a3bb098a0b8a5c","metric":"100","netmask":"255.255.255.0","proto":0, + "scan_time":"2021/10/13 16:46:39"},"operation":"DELETED","type":"dbsync_network_address"} + alert_expected_values: + rule.id: '100373' + data: >- + {"type":"dbsync_network_address","netinfo":{"addr":{"iface":"enp0s3","proto":"ipv4","address":"192.168.100.12", + "netmask":"255.255.255.0","broadcast":"192.168.100.254"}},"operation_type":"DELETED"} + - + description: Hotfix creation + event_payload: >- + {"data":{"checksum":"ded25e55c93121675adcb8d429dc586cbb351e3a","hotfix":"KB5005539", + "scan_time":"2021/10/14 02:24:18"},"operation":"INSERTED","type":"dbsync_hotfixes"} + alert_expected_values: + rule.id: '100381' + data: >- + {"type":"dbsync_hotfixes","hotfix":"KB5005539","operation_type":"INSERTED"} + - + description: Hotfix deletion + event_payload: >- + {"data":{"hotfix":"KB5005539","scan_time":"2021/10/14 02:40:41"},"operation":"DELETED", + "type":"dbsync_hotfixes"} + alert_expected_values: + rule.id: '100383' + data: '{"type":"dbsync_hotfixes","hotfix":"KB5005539","operation_type":"DELETED"}' diff --git a/tests/integration/test_analysisd/test_syscollector/data/syscollector_rules.xml b/tests/integration/test_analysisd/test_syscollector/data/syscollector_rules.xml new file mode 100644 index 0000000000..336301ee18 --- /dev/null +++ b/tests/integration/test_analysisd/test_syscollector/data/syscollector_rules.xml @@ -0,0 +1,197 @@ + + + + + 221 + Syscollector event. + + + + 100221 + dbsync_processes + Syscollector process event. + + + 100300 + INSERTED + Syscollector process creation event. + + + 100300 + MODIFIED + Syscollector process modification event. + + + 100300 + DELETED + Syscollector process deletion event. + + + + 100221 + dbsync_ports + Syscollector ports event. + + + 100310 + INSERTED + Syscollector port creation event. + + + 100310 + MODIFIED + Syscollector port modification event. + + + 100310 + DELETED + Syscollector port deletion event. + + + + 100221 + dbsync_osinfo + Syscollector osinfo event. + + + 100320 + INSERTED + Syscollector osinfo creation event. + + + 100320 + MODIFIED + Syscollector osinfo modification event. + + + 100320 + DELETED + Syscollector osinfo deletion event. + + + + 100221 + dbsync_hwinfo + Syscollector hwinfo event. + + + 100330 + INSERTED + Syscollector hwinfo creation event. + + + 100330 + MODIFIED + Syscollector hwinfo modification event. + + + 100330 + DELETED + Syscollector hwinfo deletion event. + + + + 100221 + dbsync_packages + Syscollector packages event. + + + 100340 + INSERTED + Syscollector packages creation event. + + + 100340 + MODIFIED + Syscollector packages modification event. + + + 100340 + DELETED + Syscollector packages deletion event. + + + + 100221 + dbsync_network_iface + Syscollector network interface event. + + + 100350 + INSERTED + Syscollector network_iface creation event. + + + 100350 + MODIFIED + Syscollector network_iface modification event. + + + 100350 + DELETED + Syscollector network_iface deletion event. + + + + 100221 + dbsync_network_protocol + Syscollector network protocol event. + + + 100360 + INSERTED + Syscollector network protocol creation event. + + + 100360 + MODIFIED + Syscollector network protocol modification event. + + + 100360 + DELETED + Syscollector network protocol deletion event. + + + + 100221 + dbsync_network_address + Syscollector network address event. + + + 100370 + INSERTED + Syscollector network address creation event. + + + 100370 + MODIFIED + Syscollector network address modification event. + + + 100370 + DELETED + Syscollector network address deletion event. + + + + 100221 + dbsync_hotfixes + Syscollector hotfixes event. + + + 100380 + INSERTED + Syscollector hotfixes creation event. + + + 100380 + MODIFIED + Syscollector hotfixes modification event. + + + 100380 + DELETED + Syscollector hotfixes deletion event. + + diff --git a/tests/integration/test_analysisd/test_syscollector/test_syscollector_events.py b/tests/integration/test_analysisd/test_syscollector/test_syscollector_events.py new file mode 100644 index 0000000000..ade9bdf684 --- /dev/null +++ b/tests/integration/test_analysisd/test_syscollector/test_syscollector_events.py @@ -0,0 +1,152 @@ +''' +copyright: Copyright (C) 2015-2022, Wazuh Inc. + + Created by Wazuh, Inc. . + + This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + +type: integration + +brief: These tests will check if the Syscollector events, which are processed by + the `wazuh-analysisd` daemon, generates appropriate alerts based on the + information contained in the delta. + + +components: + - analysisd + +suite: syscollector + +targets: + - manager + +daemons: + - wazuh-analysisd + +os_platform: + - linux + +os_version: + - Arch Linux + - Amazon Linux 2 + - Amazon Linux 1 + - CentOS 8 + - CentOS 7 + - Debian Buster + - Red Hat 8 + - Ubuntu Focal + - Ubuntu Bionic + +references: + - https://documentation.wazuh.com/current/user-manual/capabilities/syscollector.html\ + #using-syscollector-information-to-trigger-alerts +''' +import os +import yaml +import pytest + +from wazuh_testing.tools import (ANALYSISD_QUEUE_SOCKET_PATH, ALERT_FILE_PATH) +from wazuh_testing.analysis import CallbackWithContext, callback_check_syscollector_alert + + +# Marks +pytestmark = [pytest.mark.linux, pytest.mark.tier(level=0), pytest.mark.server] + + +# Variables +receiver_sockets_params = [(ANALYSISD_QUEUE_SOCKET_PATH, 'AF_UNIX', 'UDP')] +receiver_sockets = None +alert_timeout = 10 +file_to_monitor = ALERT_FILE_PATH + +# Configurations +data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') +messages_path = os.path.join(data_dir, 'syscollector.yaml') +with open(messages_path) as f: + test_cases = yaml.safe_load(f) +local_internal_options = {'analysisd.debug': '2'} + + +# Fixtures +@pytest.fixture(scope='module', params=test_cases, ids=[test_case['name'] for test_case in test_cases]) +def get_configuration(request): + """Get configurations from the module.""" + return request.param + + +# Tests +@pytest.mark.parametrize('test_case', + list(test_cases), + ids=[test_case['name'] for test_case in test_cases]) +def test_syscollector_events(test_case, configure_local_internal_options_module, get_configuration, mock_agent_module, + configure_custom_rules, restart_analysisd, wait_for_analysisd_startup, + connect_to_sockets_function, file_monitoring): + ''' + description: Check if Analysisd handle Syscollector deltas properly by generating alerts. + + wazuh_min_version: 4.4.0 + + tier: 2 + + parameters: + - get_configuration: + type: fixture + brief: Get configurations from the module. + - mock_agent_module: + type: fixture + brief: Create mock agent and get agent_id + - configure_custom_rules: + type: fixture + brief: Copy custom rules to test. + - restart_analysisd: + type: fixture + brief: Restart analysisd daemon and truncate related log files. + - wait_for_analysisd_startup: + type: fixture + brief: Wait until analysisd is ready. + - connect_to_sockets_function: + type: fixture + brief: Connect to analysisd event queue. + - file_monitoring: + type: fixture + brief: Handle the monitoring of a specified file. + + assertions: + - Verify that specific syscollector deltas trigger specific custom alert with certain values. + + input_description: + Input dataset (defined as event_header + event_payload in syscollector.yaml) + cover, in most of the cases, INSERTED, MODIFIED and DELETED deltas + for each of the available scan; osinfo, hwinfo, processes, packages, network_interface, + network_address, network_protocol, ports and hotfixes. + + expected_output: + Expected output (defined as alert_expected_values in syscollector.yaml) + + tags: + - rules + ''' + + # Get mock agent_id to create syscollector header + agent_id = mock_agent_module + event_header = f"d:[{agent_id}] {test_case['event_header']}" + + for stage in test_case['test_case']: + + # Add agent_id alert check + alert_expected_values = stage['alert_expected_values'] + alert_expected_values['agent.id'] = agent_id + + # Create full message by header and payload concatenation + test_msg = event_header + stage['event_payload'] + + # Send delta to analysisd queue + receiver_sockets[0].send(test_msg) + + # Set callback according to stage parameters + alert_callback = CallbackWithContext(callback_check_syscollector_alert, alert_expected_values) + + # Find expected outputs + log_monitor.start(timeout=alert_timeout, + callback=alert_callback, + error_message=f"Timeout expecting {stage['description']} message.") diff --git a/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_ignore_restrict.yaml b/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_ignore_restrict.yaml new file mode 100644 index 0000000000..2de1a7afee --- /dev/null +++ b/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_ignore_restrict.yaml @@ -0,0 +1,54 @@ +--- +# Conf 1 +- tags: + - valid_no_regex + apply_to_modules: + - test_ignore_works_over_restrict + sections: + - section: syscheck + elements: + - disabled: + value: 'no' + - frequency: + value: 2 + - directories: + value: "/testdir1" + attributes: + - check_all: 'yes' + - restrict: "testfile$" + - FIM_MODE + - directories: + value: "/testdir2" + attributes: + - check_all: 'yes' + - FIM_MODE + - ignore: + value: "/testdir1/testfile" +# Conf 2 +- tags: + - valid_regex + apply_to_modules: + - test_ignore_works_over_restrict + sections: + - section: syscheck + elements: + - disabled: + value: 'no' + - frequency: + value: 2 + - directories: + value: "/testdir1" + attributes: + - check_all: 'yes' + - restrict: "testfile2$" + - FIM_MODE + - directories: + value: "/testdir2" + attributes: + - check_all: 'yes' + - restrict: "not_ignored_sregex$" + - FIM_MODE + - ignore: + value: "testfile2$" + attributes: + - type: sregex diff --git a/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_ignore_restrict_win32.yaml b/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_ignore_restrict_win32.yaml new file mode 100644 index 0000000000..91edff46fd --- /dev/null +++ b/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_ignore_restrict_win32.yaml @@ -0,0 +1,83 @@ +--- +# Conf 1 +- tags: + - valid_no_regex + apply_to_modules: + - test_ignore_works_over_restrict + sections: + - section: syscheck + elements: + - disabled: + value: 'no' + - frequency: + value: 2 + - directories: + value: "c:\\testdir1" + attributes: + - check_all: 'yes' + - restrict: "testfile$" + - FIM_MODE + - directories: + value: "c:\\testdir2" + attributes: + - check_all: 'yes' + - FIM_MODE + - ignore: + value: "c:\\testdir1\\testfile" + - section: sca + elements: + - enabled: + value: 'no' + - section: rootcheck + elements: + - disabled: + value: 'yes' + - section: wodle + attributes: + - name: 'syscollector' + elements: + - disabled: + value: 'yes' +# Conf 2 +- tags: + - valid_regex + apply_to_modules: + - test_ignore_works_over_restrict + sections: + - section: syscheck + elements: + - disabled: + value: 'no' + - frequency: + value: 2 + - directories: + value: "c:\\testdir1" + attributes: + - check_all: 'yes' + - restrict: "testfile2$" + - FIM_MODE + - directories: + value: "c:\\testdir2" + attributes: + - check_all: 'yes' + - restrict: "not_ignored_sregex$" + - FIM_MODE + - ignore: + value: "testfile2$" + attributes: + - type: sregex + - section: sca + elements: + - enabled: + value: 'no' + - section: rootcheck + elements: + - disabled: + value: 'yes' + - section: wodle + attributes: + - name: 'syscollector' + elements: + - disabled: + value: 'yes' + diff --git a/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_whodata_prevails_over_realtime.yaml b/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_whodata_prevails_over_realtime.yaml new file mode 100644 index 0000000000..26ff1fcb7e --- /dev/null +++ b/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_whodata_prevails_over_realtime.yaml @@ -0,0 +1,35 @@ +# conf 1 +- tags: + - ossec_conf + apply_to_modules: + - MODULE_NAME + sections: + - section: syscheck + elements: + - disabled: + value: 'no' + - directories: + value: TEST_DIR1 + attributes: + - realtime: 'yes' + - whodata: 'yes' + - directories: + value: TEST_DIR2 + attributes: + - whodata: 'yes' + - realtime: 'yes' + - section: sca + elements: + - enabled: + value: 'no' + - section: rootcheck + elements: + - disabled: + value: 'yes' + - section: wodle + attributes: + - name: 'syscollector' + elements: + - disabled: + value: 'yes' + diff --git a/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_whodata_thread.yaml b/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_whodata_thread.yaml new file mode 100644 index 0000000000..f24ee10ee0 --- /dev/null +++ b/tests/integration/test_fim/test_files/test_ambiguous_confs/data/wazuh_conf_whodata_thread.yaml @@ -0,0 +1,66 @@ +--- +# conf 1 +- tags: + - whodata_disabled_conf + apply_to_modules: + - test_ambiguous_whodata_thread + sections: + - section: syscheck + elements: + - disabled: + value: 'no' + - directories: + value: TEST_DIRECTORIES + attributes: + - whodata: 'yes' + - directories: + value: TEST_DIRECTORIES + attributes: + - whodata: 'no' + - section: sca + elements: + - enabled: + value: 'no' + - section: rootcheck + elements: + - disabled: + value: 'yes' + - section: wodle + attributes: + - name: 'syscollector' + elements: + - disabled: + value: 'yes' + +# conf 2 +- tags: + - whodata_enabled_conf + apply_to_modules: + - test_ambiguous_whodata_thread + sections: + - section: syscheck + elements: + - disabled: + value: 'no' + - directories: + value: TEST_DIRECTORIES + attributes: + - whodata: 'no' + - directories: + value: TEST_DIRECTORIES + attributes: + - whodata: 'yes' + - section: sca + elements: + - enabled: + value: 'no' + - section: rootcheck + elements: + - disabled: + value: 'yes' + - section: wodle + attributes: + - name: 'syscollector' + elements: + - disabled: + value: 'yes' diff --git a/tests/integration/test_fim/test_files/test_audit/data/wazuh_conf.yaml b/tests/integration/test_fim/test_files/test_audit/data/wazuh_conf.yaml new file mode 100644 index 0000000000..ccbe6bd4d2 --- /dev/null +++ b/tests/integration/test_fim/test_files/test_audit/data/wazuh_conf.yaml @@ -0,0 +1,15 @@ +--- +# conf 1 +- tags: + - config1 + apply_to_modules: + - test_remove_audit + sections: + - section: syscheck + elements: + - disabled: + value: 'no' + - directories: + value: "/testdir1,/testdir2,/testdir3" + attributes: + - whodata: 'yes' diff --git a/tests/integration/test_fim/test_files/test_env_variables/test_dir_win32.py b/tests/integration/test_fim/test_files/test_env_variables/test_dir_win32.py new file mode 100644 index 0000000000..c71ffec4f2 --- /dev/null +++ b/tests/integration/test_fim/test_files/test_env_variables/test_dir_win32.py @@ -0,0 +1,142 @@ +''' +copyright: Copyright (C) 2015-2022, Wazuh Inc. + + Created by Wazuh, Inc. . + + This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + +type: integration + +brief: File Integrity Monitoring (FIM) system watches selected files and triggering alerts + when these files are modified. Specifically, these tests will check if FIM events are + generated when environment variables are used to monitor directories in Windows systems. + The FIM capability is managed by the 'wazuh-syscheckd' daemon, which checks configured + files for changes to the checksums, permissions, and ownership. + +components: + - fim + +suite: files_env_variables + +targets: + - agent + +daemons: + - wazuh-syscheckd + +os_platform: + - windows + +os_version: + - Windows 10 + - Windows Server 2019 + - Windows Server 2016 + +references: + - https://documentation.wazuh.com/current/user-manual/capabilities/file-integrity/index.html + - https://documentation.wazuh.com/current/user-manual/reference/ossec-conf/syscheck.html#directories + +pytest_args: + - fim_mode: + realtime: Enable real-time monitoring on Linux (using the 'inotify' system calls) and Windows systems. + whodata: Implies real-time monitoring but adding the 'who-data' information. + - tier: + 0: Only level 0 tests are performed, they check basic functionalities and are quick to perform. + 1: Only level 1 tests are performed, they check functionalities of medium complexity. + 2: Only level 2 tests are performed, they check advanced functionalities and are slow to perform. + +tags: + - fim_env_variables +''' +import os +import sys + +import pytest +from wazuh_testing import global_parameters +from wazuh_testing.fim import LOG_FILE_PATH, generate_params, regular_file_cud +from wazuh_testing.tools import PREFIX +from wazuh_testing.tools.configuration import load_wazuh_configurations +from wazuh_testing.tools.monitoring import FileMonitor + +# Marks +pytestmark = [pytest.mark.win32, pytest.mark.tier(level=2)] + +# Variables and configuration +wazuh_log_monitor = FileMonitor(LOG_FILE_PATH) + +test_directories = [os.path.join(PREFIX, 'testdir1'), os.path.join(PREFIX, 'testdir1', 'subdir')] +dir1, subdir1 = test_directories + +environment_variables = [("TEST_ENV_VAR", dir1)] +test_env = "%TEST_ENV_VAR%" + +test_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') +configurations_path = os.path.join(test_data_path, 'wazuh_conf_dir.yaml') +mark_skip_agentWindows = pytest.mark.skipif(sys.platform == 'win32', reason="It will be blocked by wazuh/wazuh-qa#2174") + +conf_params = {'TEST_ENV_VARIABLES': test_env, 'MODULE_NAME': __name__} +p, m = generate_params(extra_params=conf_params) + +configurations = load_wazuh_configurations(configurations_path, __name__, params=p, metadata=m) + + +# Fixture +@pytest.fixture(scope='module', params=configurations) +def get_configuration(request): + """Get configurations from the module.""" + return request.param + + +# Test +@pytest.mark.parametrize('directory', [subdir1]) +@mark_skip_agentWindows +def test_tag_directories(directory, get_configuration, put_env_variables, configure_environment, + restart_syscheckd, wait_for_fim_start): + ''' + description: Check if the 'wazuh-syscheckd' daemon detects CUD events ('added', 'modified', and 'deleted') + when environment variables are used to monitor directories. For this purpose, the test + will monitor a directory that is defined in an environment variable. Then, different + operations will be performed on testing files, and finally, the test will verify + that the proper FIM events have been generated. + + wazuh_min_version: 4.2.0 + + tier: 2 + + parameters: + - directory: + type: str + brief: Path to the directory to be monitored. + - get_configuration: + type: fixture + brief: Get configurations from the module. + - put_env_variables: + type: fixture + brief: Create the environment variables. + - configure_environment: + type: fixture + brief: Configure a custom environment for testing. + - restart_syscheckd: + type: fixture + brief: Clear the 'ossec.log' file and start a new monitor. + - wait_for_fim_start: + type: fixture + brief: Wait for realtime start, whodata start, or end of initial FIM scan. + + assertions: + - Verify that FIM events are generated when environment variables are used to monitor directories. + + input_description: A test case (ossec_conf) is contained in external YAML file (wazuh_conf_dir.yaml) which + includes configuration settings for the 'wazuh-syscheckd' daemon and, it is combined + with the directory to be monitored defined as an environment variable in this module. + + expected_output: + - r'.*Sending FIM event: (.+)$' ('added', 'modified', and 'deleted' events) + + tags: + - scheduled + - time_travel + ''' + regular_file_cud(directory, wazuh_log_monitor, file_list=["testing_env_variables"], + min_timeout=global_parameters.default_timeout, + time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled') diff --git a/tests/integration/test_fim/test_files/test_max_eps/test_max_eps_synchronization.py b/tests/integration/test_fim/test_files/test_max_eps/test_max_eps_synchronization.py new file mode 100644 index 0000000000..68739fc4dc --- /dev/null +++ b/tests/integration/test_fim/test_files/test_max_eps/test_max_eps_synchronization.py @@ -0,0 +1,213 @@ +''' +copyright: Copyright (C) 2015-2022, Wazuh Inc. + + Created by Wazuh, Inc. . + + This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + +type: integration + +brief: File Integrity Monitoring (FIM) system watches selected files and triggering alerts + when these files are modified. Specifically, these tests will verify that FIM limits + the maximum synchronization message throughput, set in the 'max_eps' tag. + The FIM capability is managed by the 'wazuh-syscheckd' daemon, which checks configured + files for changes to the checksums, permissions, and ownership. + +components: + - fim + +suite: files_max_eps + +targets: + - agent + +daemons: + - wazuh-syscheckd + +os_platform: + - linux + - windows + +os_version: + - Arch Linux + - Amazon Linux 2 + - Amazon Linux 1 + - CentOS 8 + - CentOS 7 + - Debian Buster + - Red Hat 8 + - Ubuntu Focal + - Ubuntu Bionic + - Windows 10 + - Windows Server 2019 + - Windows Server 2016 + +references: + - https://documentation.wazuh.com/current/user-manual/capabilities/file-integrity/index.html + - https://documentation.wazuh.com/current/user-manual/reference/ossec-conf/syscheck.html#synchronization + +pytest_args: + - fim_mode: + realtime: Enable real-time monitoring on Linux (using the 'inotify' system calls) and Windows systems. + whodata: Implies real-time monitoring but adding the 'who-data' information. + scheduled: Implies scheduled scan + + - tier: + 0: Only level 0 tests are performed, they check basic functionalities and are quick to perform. + 1: Only level 1 tests are performed, they check functionalities of medium complexity. + 2: Only level 2 tests are performed, they check advanced functionalities and are slow to perform. + +tags: + - fim_max_eps_sync +''' +import os +import pytest + +from collections import Counter +from wazuh_testing import logger +from wazuh_testing.tools import PREFIX +from wazuh_testing.fim import LOG_FILE_PATH, generate_params +from wazuh_testing.tools.monitoring import FileMonitor +from wazuh_testing.tools.configuration import load_wazuh_configurations +from wazuh_testing.modules import DATA, TIER1, AGENT, WINDOWS, LINUX +from wazuh_testing.modules.fim import (TEST_DIR_1, TEST_DIRECTORIES, YAML_CONF_MAX_EPS_SYNC, + ERR_MSG_AGENT_DISCONNECT, ERR_MSG_INTEGRITY_CONTROL_MSG, + SCHEDULE_MODE, REALTIME_MODE, WHODATA_MODE) +from wazuh_testing.modules.fim import FIM_DEFAULT_LOCAL_INTERNAL_OPTIONS as local_internal_options +from wazuh_testing.modules.fim.event_monitor import callback_integrity_message, callback_connection_message +from wazuh_testing.tools.file import delete_path_recursively, write_file + +# Marks +pytestmark = [TIER1, AGENT, WINDOWS, LINUX] + +# Variables +wazuh_log_monitor = FileMonitor(LOG_FILE_PATH) + +test_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), DATA) +configurations_path = os.path.join(test_data_path, YAML_CONF_MAX_EPS_SYNC) + +test_directory = os.path.join(PREFIX, TEST_DIR_1) +conf_params = {TEST_DIRECTORIES: test_directory} + +ERR_MSG_MULTIPLE_FILES_CREATION = 'Multiple files could not be created.' + +TIMEOUT_CHECK_AGENT_CONNECT = 10 +TIMEOUT_CHECK_INTEGRATY_START = 30 +TIMEOUT_CHECK_EACH_INTEGRITY_MSG = 90 + +# Configurations + +# Test with the minimum, and the default value +eps_values = ['1', '100'] + +parameters, metadata = generate_params(extra_params=conf_params, + modes=[SCHEDULE_MODE, REALTIME_MODE, WHODATA_MODE], + apply_to_all=({'MAX_EPS': eps_value} for eps_value in eps_values)) +configurations = load_wazuh_configurations(configurations_path, __name__, params=parameters, metadata=metadata) +configuration_ids = [f"{x['fim_mode']}_mode_{x['max_eps']}_max_eps" for x in metadata] + +# Fixtures + +@pytest.fixture(scope='module', params=configurations, ids=configuration_ids) +def get_configuration(request): + """Get configurations from the module.""" + return request.param + + +@pytest.fixture(scope='module') +def create_multiple_files(get_configuration): + """Create multiple files of a specific type.""" + max_eps = get_configuration['metadata']['max_eps'] + mode = get_configuration['metadata']['fim_mode'] + os.makedirs(test_directory, exist_ok=True, mode=0o777) + try: + for i in range(int(max_eps) + 5): + file_name = f'file{i}_to_max_eps_{max_eps}_{mode}_mode' + path = os.path.join(test_directory, file_name) + write_file(path) + except OSError: + logger.info(ERR_MSG_MULTIPLE_FILES_CREATION) + +# Tests +def test_max_eps_sync_valid_within_range(configure_local_internal_options_module, get_configuration, + create_multiple_files, configure_environment, restart_wazuh): + ''' + description: Check if the 'wazuh-syscheckd' daemon applies the limit set in the 'max_eps' tag when + a lot of synchronization events are generated. For this purpose, the test will monitor + a folder and create multiple testing files in it. Once FIM is started, it will wait for + the agent to connect to the manager and generate an integrity message, for that reason + this test applies to scheduled mode. Then, the test will collect FIM 'integrity' events + generated and check if the number of events matches the testing files created. + Finally, it will verify the limit of events per second (eps) + is not exceeded by checking the creation time of the testing files. + + wazuh_min_version: 4.2.0 + + tier: 1 + + parameters: + - configure_local_internal_options_module: + type: fixture + brief: Configure the Wazuh local internal options. + - get_configuration: + type: fixture + brief: Get configurations from the module. + - create_multiple_file: + type: fixture + brief: Create the testing files to be monitored. + - configure_environment: + type: fixture + brief: Configure a custom environment for testing. + - restart_wazuh: + type: fixture + brief: Clear the 'ossec.log' file and start a new monitor. + - delete_files: + type: fixture + brief: Delete the testing files when the test ends. + + assertions: + - Verify that FIM 'integrity' events are generated for each testing file created. + - Verify that the eps limit set in the 'max_eps' tag has not been exceeded at generating FIM events. + + input_description: A test case (max_eps_synchronization) is contained in external YAML file + (wazuh_sync_conf_max_eps.yaml) which includes configuration settings for + the 'wazuh-syscheckd' daemon and, these are combined with the + testing directories to be monitored defined in the module. + expected_output: + - r'.* Connected to the server .*' + - r'.*Sending integrity control message' + + tags: + - scheduled + - realtime + - who_data + ''' + try: + max_eps = int(get_configuration['metadata']['max_eps']) + + # Wait until the agent connects to the manager. + wazuh_log_monitor.start(timeout=TIMEOUT_CHECK_AGENT_CONNECT, + callback=callback_connection_message, + error_message=ERR_MSG_AGENT_DISCONNECT).result() + + # Find integrity start before attempting to read max_eps. + wazuh_log_monitor.start(timeout=TIMEOUT_CHECK_INTEGRATY_START, + callback=callback_integrity_message, + error_message=ERR_MSG_INTEGRITY_CONTROL_MSG).result() + + # Find integrity message for each file created after read max_eps. + total_file_created = max_eps + 5 + result = wazuh_log_monitor.start(timeout=TIMEOUT_CHECK_EACH_INTEGRITY_MSG, + accum_results=total_file_created, + callback=callback_integrity_message, + error_message=f'Received less results than expected ({total_file_created})').result() + + # Collect by time received the messages. + counter = Counter([date_time for date_time, _ in result]) + + # Check the number of occurrences of received messages by time. + for _, total_occurrences in counter.items(): + assert total_occurrences <= max_eps, f'Sent {total_occurrences} but a maximum of {max_eps} was set' + finally: + # Delete all files created. + delete_path_recursively(test_directory) diff --git a/tests/integration/test_fim/test_files/test_report_changes/common.py b/tests/integration/test_fim/test_files/test_report_changes/common.py new file mode 100644 index 0000000000..51e644fb4a --- /dev/null +++ b/tests/integration/test_fim/test_files/test_report_changes/common.py @@ -0,0 +1,179 @@ +# Copyright (C) 2015-2021, Wazuh Inc. +# Created by Wazuh, Inc. . +# This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + +import os +import re +import sys + +from wazuh_testing.fim import WAZUH_PATH + + +def generate_string(stringLength=10, character='0'): + """Generate a string with line breaks. + + Parameters + ---------- + stringLength : int, optional + Number of characters to add in the string. Default `10` + character : str, optional + Character to be added. Default `'0'` + + Returns + ------- + random_str : str + String with line breaks. + """ + generated_string = '' + + for i in range(stringLength): + generated_string += character + + if i % 127 == 0: + generated_string += '\n' + + return generated_string + + +def translate_size(configured_size='1KB'): + """ + Translate the configured size from string to number in bytes. + + Parameters + ---------- + configured_size: str, optional + Configured size to translate. Default `'1KB'` + + Returns + ------- + translated_size: int + Configured value in bytes. + """ + translated_size = 0 + configured_value = int(configured_size[:-2]) # Store value ignoring the data unit + data_unit = str(configured_size[-2:]) + + if data_unit == 'KB': + translated_size = configured_value * 1024 + elif data_unit == 'MB': + translated_size = configured_value * 1024 * 1024 + elif data_unit == 'GB': + translated_size = configured_value * 1024 * 1024 * 1024 + + return translated_size + + +def disable_file_max_size(): + """ + Disable the syscheck.file_max_size option from the internal_options.conf file. + """ + new_content = '' + + if sys.platform == 'win32': + internal_options = os.path.join(WAZUH_PATH, 'internal_options.conf') + else: + internal_options = os.path.join(WAZUH_PATH, 'etc', 'internal_options.conf') + + with open(internal_options, 'r') as f: + lines = f.readlines() + + for line in lines: + new_line = line.replace('syscheck.file_max_size=1024', 'syscheck.file_max_size=0') + new_content += new_line + + with open(internal_options, 'w') as f: + f.write(new_content) + + +def restore_file_max_size(): + """ + Restore the syscheck.file_max_size option from the internal_options.conf file. + """ + new_content = '' + + if sys.platform == 'win32': + internal_options = os.path.join(WAZUH_PATH, 'internal_options.conf') + else: + internal_options = os.path.join(WAZUH_PATH, 'etc', 'internal_options.conf') + + with open(internal_options, 'r') as f: + lines = f.readlines() + + for line in lines: + new_line = line.replace('syscheck.file_max_size=0', 'syscheck.file_max_size=1024') + new_content += new_line + + with open(internal_options, 'w') as f: + f.write(new_content) + + +def disable_rt_delay(): + """ + Disable the syscheck.rt_delay option from the internal_options.conf file. + """ + new_content = '' + + if sys.platform == 'win32': + internal_options = os.path.join(WAZUH_PATH, 'internal_options.conf') + else: + internal_options = os.path.join(WAZUH_PATH, 'etc', 'internal_options.conf') + + with open(internal_options, 'r') as f: + lines = f.readlines() + + for line in lines: + new_line = line.replace('syscheck.rt_delay=5', 'syscheck.rt_delay=1000') + new_content += new_line + + with open(internal_options, 'w') as f: + f.write(new_content) + + +def restore_rt_delay(): + """ + Restore the syscheck.rt_delay option from the internal_options.conf file. + """ + new_content = '' + + if sys.platform == 'win32': + internal_options = os.path.join(WAZUH_PATH, 'internal_options.conf') + else: + internal_options = os.path.join(WAZUH_PATH, 'etc', 'internal_options.conf') + + with open(internal_options, 'r') as f: + lines = f.readlines() + + for line in lines: + new_line = line.replace('syscheck.rt_delay=1000', 'syscheck.rt_delay=5') + new_content += new_line + + with open(internal_options, 'w') as f: + f.write(new_content) + + +def make_diff_file_path(folder='/testdir1', filename='regular_0'): + """ + Generate diff file path. + + Parameters + ---------- + folder : str, optional + Containing folder. Default `/testdir1` + filename : str, optional + File name. Default `regular_0` + + Returns + ------- + diff_file_path : str + Path to compressed file. + """ + diff_file_path = os.path.join(WAZUH_PATH, 'queue', 'diff', 'local') + + if sys.platform == 'win32': + folder_components = re.match(r'^([a-zA-Z]):\\{1,2}(\w+)\\{0,2}$', folder) + diff_file_path = os.path.join(diff_file_path, folder_components.group(1).lower(), + folder_components.group(2).lower(), filename, 'last-entry.gz') + else: + diff_file_path = os.path.join(diff_file_path, folder.strip('/'), filename, 'last-entry.gz') + + return diff_file_path diff --git a/tests/integration/test_fim/test_registry/test_registry_file_limit/data/wazuh_conf.yaml b/tests/integration/test_fim/test_registry/test_registry_file_limit/data/wazuh_conf.yaml new file mode 100644 index 0000000000..2347b3f284 --- /dev/null +++ b/tests/integration/test_fim/test_registry/test_registry_file_limit/data/wazuh_conf.yaml @@ -0,0 +1,43 @@ +--- +#conf 1 +- tags: + - file_limit_registry_conf + apply_to_modules: + - test_registry_limit_capacity_alerts + - test_registry_limit_full + - test_registry_limit_values + sections: + - section: syscheck + elements: + - disabled: + value: 'no' + - frequency: + value: 5 + - windows_registry: + value: WINDOWS_REGISTRY + attributes: + - arch: '64bit' + - file_limit: + elements: + - enabled: + value: 'yes' + - entries: + value: FILE_LIMIT + - section: sca + elements: + - enabled: + value: 'no' + - section: rootcheck + elements: + - disabled: + value: 'yes' + - section: active-response + elements: + - disabled: + value: 'yes' + - section: wodle + attributes: + - name: 'syscollector' + elements: + - disabled: + value: 'yes' diff --git a/tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_capacity_alerts.py b/tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_capacity_alerts.py new file mode 100644 index 0000000000..718ddbc389 --- /dev/null +++ b/tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_capacity_alerts.py @@ -0,0 +1,211 @@ +''' +copyright: Copyright (C) 2015-2022, Wazuh Inc. + + Created by Wazuh, Inc. . + + This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + +type: integration + +brief: File Integrity Monitoring (FIM) system watches selected files and triggering alerts + when these files are modified. Specifically, these tests will check if the threshold + set in the 'file_limit' tag generates FIM events when the number of monitored entries + approaches this value. + The FIM capability is managed by the 'wazuh-syscheckd' daemon, which checks + configured files for changes to the checksums, permissions, and ownership. + +components: + - fim + +suite: registry_file_limit + +targets: + - agent + +daemons: + - wazuh-syscheckd + +os_platform: + - windows + +os_version: + - Windows 10 + - Windows 8 + - Windows 7 + - Windows Server 2019 + - Windows Server 2016 + - Windows Server 2012 + - Windows Server 2003 + - Windows XP + +references: + - https://documentation.wazuh.com/current/user-manual/capabilities/file-integrity/index.html + - https://documentation.wazuh.com/current/user-manual/reference/ossec-conf/syscheck.html#file-limit + +pytest_args: + - fim_mode: + realtime: Enable real-time monitoring on Linux (using the 'inotify' system calls) and Windows systems. + whodata: Implies real-time monitoring but adding the 'who-data' information. + - tier: + 0: Only level 0 tests are performed, they check basic functionalities and are quick to perform. + 1: Only level 1 tests are performed, they check functionalities of medium complexity. + 2: Only level 2 tests are performed, they check advanced functionalities and are slow to perform. + +tags: + - fim_registry_file_limit +''' +import os +from sys import platform +import pytest +from wazuh_testing import global_parameters +from wazuh_testing.fim import LOG_FILE_PATH, generate_params, modify_registry_value, wait_for_scheduled_scan, \ + delete_registry_value, registry_parser, KEY_WOW64_64KEY, callback_detect_end_scan, REG_SZ, KEY_ALL_ACCESS, \ + RegOpenKeyEx, RegCloseKey +from wazuh_testing.fim_module import (WINDOWS_HKEY_LOCAL_MACHINE, MONITORED_KEY, CB_FILE_LIMIT_CAPACITY, + ERR_MSG_DATABASE_PERCENTAGE_FULL_ALERT, ERR_MSG_FIM_INODE_ENTRIES, CB_FILE_LIMIT_BACK_TO_NORMAL, + ERR_MSG_DB_BACK_TO_NORMAL, CB_COUNT_REGISTRY_FIM_ENTRIES, ERR_MSG_WRONG_NUMBER_OF_ENTRIES) +from wazuh_testing.tools.configuration import load_wazuh_configurations +from wazuh_testing.tools.monitoring import FileMonitor, generate_monitoring_callback +if platform == 'win32': + import pywintypes + +# Marks + +pytestmark = [pytest.mark.win32, pytest.mark.tier(level=1)] + +# Variables + +test_regs = [os.path.join(WINDOWS_HKEY_LOCAL_MACHINE, MONITORED_KEY)] +test_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') +wazuh_log_monitor = FileMonitor(LOG_FILE_PATH) +scan_delay = 5 + +# Configurations + +file_limit_list = ['100'] + +conf_params = {'WINDOWS_REGISTRY': test_regs[0]} +params, metadata = generate_params(extra_params=conf_params, + apply_to_all=({'FILE_LIMIT': file_limit_elem} for file_limit_elem in file_limit_list), + modes=['scheduled']) + +configurations_path = os.path.join(test_data_path, 'wazuh_conf.yaml') +configurations = load_wazuh_configurations(configurations_path, __name__, params=params, metadata=metadata) + + +# Fixtures + + +@pytest.fixture(scope='module', params=configurations) +def get_configuration(request): + """Get configurations from the module.""" + return request.param + + +# Tests + + +@pytest.mark.parametrize('percentage', [(80), (90), (0)]) +def test_file_limit_capacity_alert(percentage, get_configuration, configure_environment, restart_syscheckd, + wait_for_fim_start): + ''' + description: Check if the 'wazuh-syscheckd' daemon generates events for different capacity thresholds limits when + using the 'schedule' monitoring mode. For this purpose, the test will monitor a key in which + several testing values will be created, corresponding to different percentages of the total limit. + Then, it will check if FIM events are generated when the number of values created exceeds 80% of + the total and when the number is less than that percentage. Finally, the test will verify that, in + the FIM 'entries' event, the entries number is one unit more than the number of monitored values. + + wazuh_min_version: 4.2.0 + + tier: 1 + + parameters: + - percentage: + type: int + brief: Percentage of testing values to be created. + - tags_to_apply: + type: set + brief: Run test if matches with a configuration identifier, skip otherwise. + - get_configuration: + type: fixture + brief: Get configurations from the module. + - configure_environment: + type: fixture + brief: Configure a custom environment for testing. + - restart_syscheckd: + type: fixture + brief: Clear the Wazuh logs file and start a new monitor. + - wait_for_fim_start: + type: fixture + brief: Wait for realtime start, whodata start, or end of initial FIM scan. + + assertions: + - Verify that FIM 'DB alert' events are generated when the number of values to be monitored + exceeds the established threshold and viceversa. + - Verify that FIM 'entries' events contain one unit more than the number of monitored values. + + input_description: A test case (file_limit_registry_conf) is contained in external YAML file (wazuh_conf.yaml) + which includes configuration settings for the 'wazuh-syscheckd' daemon. That is combined + with the percentages and the testing registry key to be monitored defined in this module. + + expected_output: + - r'.*Sending FIM event: (.+)$' ('added' events) + - r'.*Sending DB .* full alert.' + - r'.*Sending DB back to normal alert.' + - r'.*Fim registry entries' + + tags: + - scheduled + ''' + limit = int(get_configuration['metadata']['file_limit']) + + NUM_REGS = int(limit * (percentage / 100)) + 1 + + if percentage == 0: + NUM_REGS = 0 + + reg1_handle = RegOpenKeyEx(registry_parser[WINDOWS_HKEY_LOCAL_MACHINE], MONITORED_KEY, 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY) + + # Add registry values to fill the database up to alert generating percentage + if percentage >= 80: # Percentages 80 and 90 + for i in range(NUM_REGS): + modify_registry_value(reg1_handle, f'value_{i}', REG_SZ, 'added') + else: # Database back to normal + for i in range(limit - 10): + modify_registry_value(reg1_handle, f'value_{i}', REG_SZ, 'added') + + wait_for_scheduled_scan(wait_for_scan=True, interval=scan_delay, monitor=wazuh_log_monitor) + + wazuh_log_monitor.start(timeout=global_parameters.default_timeout, + callback=callback_detect_end_scan, + error_message=ERR_MSG_FIM_INODE_ENTRIES) + + for i in range(limit): + try: + delete_registry_value(reg1_handle, f'value_{i}') + except OSError: + break # Break out of the loop when all values have been deleted + except pywintypes.error: + break + + RegCloseKey(reg1_handle) + + wait_for_scheduled_scan(wait_for_scan=True, interval=scan_delay, monitor=wazuh_log_monitor) + + if percentage >= 80: # Percentages 80 and 90 + wazuh_log_monitor.start(timeout=global_parameters.default_timeout, + callback=generate_monitoring_callback(CB_FILE_LIMIT_CAPACITY), + error_message=ERR_MSG_DATABASE_PERCENTAGE_FULL_ALERT).result() + + else: # Database back to normal + wazuh_log_monitor.start(timeout=global_parameters.default_timeout, + callback=generate_monitoring_callback(CB_FILE_LIMIT_BACK_TO_NORMAL), + error_message=ERR_MSG_DB_BACK_TO_NORMAL).result() + + entries = wazuh_log_monitor.start(timeout=global_parameters.default_timeout, + callback=generate_monitoring_callback(CB_COUNT_REGISTRY_FIM_ENTRIES), + error_message=ERR_MSG_FIM_INODE_ENTRIES).result() + + # We add 1 because of the key created to hold the values + assert entries == str(NUM_REGS + 1), ERR_MSG_WRONG_NUMBER_OF_ENTRIES diff --git a/tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_full.py b/tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_full.py new file mode 100644 index 0000000000..c06a425d0e --- /dev/null +++ b/tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_full.py @@ -0,0 +1,178 @@ +''' +copyright: Copyright (C) 2015-2022, Wazuh Inc. + + Created by Wazuh, Inc. . + + This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + +type: integration + +brief: File Integrity Monitoring (FIM) system watches selected files and triggering alerts + when these files are modified. Specifically, these tests will check if FIM events are + generated while the database is in 'full database alert' mode for reaching the limit + of entries to monitor set in the 'file_limit' tag. + The FIM capability is managed by the 'wazuh-syscheckd' daemon, which checks + configured files for changes to the checksums, permissions, and ownership. + +components: + - fim + +suite: registry_file_limit + +targets: + - agent + +daemons: + - wazuh-syscheckd + +os_platform: + - windows + +os_version: + - Windows 10 + - Windows 8 + - Windows 7 + - Windows Server 2019 + - Windows Server 2016 + - Windows Server 2012 + - Windows Server 2003 + - Windows XP + +references: + - https://documentation.wazuh.com/current/user-manual/capabilities/file-integrity/index.html + - https://documentation.wazuh.com/current/user-manual/reference/ossec-conf/syscheck.html#file-limit + +pytest_args: + - fim_mode: + scheduled: file/registry changes are monitored only at the configured interval + - tier: + 0: Only level 0 tests are performed, they check basic functionalities and are quick to perform. + 1: Only level 1 tests are performed, they check functionalities of medium complexity. + 2: Only level 2 tests are performed, they check advanced functionalities and are slow to perform. + +tags: + - fim_registry_file_limit +''' +import os +import pytest +from wazuh_testing import global_parameters +from wazuh_testing.fim import LOG_FILE_PATH, generate_params, modify_registry_value, registry_parser, KEY_WOW64_64KEY, \ + REG_SZ, KEY_ALL_ACCESS, RegOpenKeyEx, RegCloseKey, create_registry +from wazuh_testing.fim_module import (WINDOWS_HKEY_LOCAL_MACHINE, MONITORED_KEY, CB_FILE_LIMIT_CAPACITY, + ERR_MSG_DATABASE_FULL_ALERT_EVENT, ERR_MSG_DATABASE_FULL_COULD_NOT_INSERT, CB_DATABASE_FULL_COULD_NOT_INSERT_VALUE, + CB_COUNT_REGISTRY_FIM_ENTRIES, ERR_MSG_FIM_INODE_ENTRIES, ERR_MSG_WRONG_VALUE_FOR_DATABASE_FULL, + ERR_MSG_WRONG_NUMBER_OF_ENTRIES) +from wazuh_testing.tools.configuration import load_wazuh_configurations +from wazuh_testing.tools.monitoring import FileMonitor, generate_monitoring_callback + +# Marks + +pytestmark = [pytest.mark.win32, pytest.mark.tier(level=1)] + +# Variables +test_reg = os.path.join(WINDOWS_HKEY_LOCAL_MACHINE, MONITORED_KEY) +test_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') +wazuh_log_monitor = FileMonitor(LOG_FILE_PATH) +NUM_REGS = 10 +EXPECTED_DATABES_STATE = "100" +monitor_timeout = 40 + +# Configurations + +file_limit_list = ['10'] +conf_params = {'WINDOWS_REGISTRY': test_reg} +params, metadata = generate_params(extra_params=conf_params, + apply_to_all=({'FILE_LIMIT': file_limit_elem} for file_limit_elem in file_limit_list), + modes=['scheduled']) + +configurations_path = os.path.join(test_data_path, 'wazuh_conf.yaml') +configurations = load_wazuh_configurations(configurations_path, __name__, params=params, metadata=metadata) + + +# Fixtures + +@pytest.fixture(scope='module', params=configurations) +def get_configuration(request): + """Get configurations from the module.""" + return request.param + + +# Functions + +def extra_configuration_before_yield(): + """Generate registry entries to fill database""" + reg1_handle = create_registry(registry_parser[WINDOWS_HKEY_LOCAL_MACHINE], MONITORED_KEY, KEY_WOW64_64KEY) + reg1_handle = RegOpenKeyEx(registry_parser[WINDOWS_HKEY_LOCAL_MACHINE], MONITORED_KEY, 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY) + + for i in range(0, NUM_REGS): + modify_registry_value(reg1_handle, f'value_{i}', REG_SZ, 'added') + + RegCloseKey(reg1_handle) + + +# Tests +def test_file_limit_full(get_configuration, configure_environment, restart_syscheckd): + ''' + description: Check if the 'wazuh-syscheckd' daemon generates proper events while the FIM database is in + 'full database alert' mode for reaching the limit of entries to monitor set in the 'file_limit' tag. + For this purpose, the test will monitor a key in which several testing values will be created + until the entry monitoring limit is reached. Then, it will check if the FIM event 'full' is generated + when a new testing value is added to the monitored key. Finally, the test will verify that, + in the FIM 'entries' event, the number of entries and monitored values match. + + wazuh_min_version: 4.2.0 + + tier: 1 + + parameters: + - tags_to_apply: + type: set + brief: Run test if matches with a configuration identifier, skip otherwise. + - get_configuration: + type: fixture + brief: Get configurations from the module. + - configure_environment: + type: fixture + brief: Configure a custom environment for testing. + - restart_syscheckd: + type: fixture + brief: Clear the Wazuh logs file and start a new monitor. + + assertions: + - Verify that the FIM database is in 'full database alert' mode + when the maximum number of values to monitor has been reached. + - Verify that proper FIM events are generated while the database + is in 'full database alert' mode. + + input_description: A test case (file_limit_registry_conf) is contained in external YAML file (wazuh_conf.yaml) + which includes configuration settings for the 'wazuh-syscheckd' daemon. That is combined + with the testing registry key to be monitored defined in this module. + + expected_output: + - r'.*Sending DB .* full alert.' + - r'.*The DB is full.*' + - r'.*Fim registry entries' + + tags: + - scheduled + ''' + database_state = wazuh_log_monitor.start(timeout=global_parameters.default_timeout, + callback=generate_monitoring_callback(CB_FILE_LIMIT_CAPACITY), + error_message=ERR_MSG_DATABASE_FULL_ALERT_EVENT).result() + + assert database_state == EXPECTED_DATABES_STATE, ERR_MSG_WRONG_VALUE_FOR_DATABASE_FULL + + reg1_handle = RegOpenKeyEx(registry_parser[WINDOWS_HKEY_LOCAL_MACHINE], MONITORED_KEY, 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY) + + modify_registry_value(reg1_handle, 'value_full', REG_SZ, 'added') + + RegCloseKey(reg1_handle) + + wazuh_log_monitor.start(timeout=monitor_timeout, callback=generate_monitoring_callback(CB_DATABASE_FULL_COULD_NOT_INSERT_VALUE), + error_message=ERR_MSG_DATABASE_FULL_COULD_NOT_INSERT) + + entries = wazuh_log_monitor.start(timeout=global_parameters.default_timeout, + callback=generate_monitoring_callback(CB_COUNT_REGISTRY_FIM_ENTRIES), + error_message=ERR_MSG_FIM_INODE_ENTRIES).result() + + assert entries == str(get_configuration['metadata']['file_limit']), ERR_MSG_WRONG_NUMBER_OF_ENTRIES \ No newline at end of file diff --git a/tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_values.py b/tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_values.py new file mode 100644 index 0000000000..211cc0326e --- /dev/null +++ b/tests/integration/test_fim/test_registry/test_registry_file_limit/test_registry_limit_values.py @@ -0,0 +1,171 @@ +''' +copyright: Copyright (C) 2015-2022, Wazuh Inc. + + Created by Wazuh, Inc. . + + This program is free software; you can redistribute it and/or modify it under the terms of GPLv2 + +type: integration + +brief: File Integrity Monitoring (FIM) system watches selected files and triggering alerts + when these files are modified. Specifically, these tests will check if the FIM event + 'maximum number of entries' has the correct value for the monitored entries limit of + the 'file_limit' option. + The FIM capability is managed by the 'wazuh-syscheckd' daemon, which checks configured + files for changes to the checksums, permissions, and ownership. + +components: + - fim + +suite: registry_file_limit + +targets: + - agent + +daemons: + - wazuh-syscheckd + +os_platform: + - windows + +os_version: + - Windows 10 + - Windows 8 + - Windows 7 + - Windows Server 2019 + - Windows Server 2016 + - Windows Server 2012 + - Windows Server 2003 + - Windows XP + +references: + - https://documentation.wazuh.com/current/user-manual/capabilities/file-integrity/index.html + - https://documentation.wazuh.com/current/user-manual/reference/ossec-conf/syscheck.html#file-limit + +pytest_args: + - fim_mode: + realtime: Enable real-time monitoring on Linux (using the 'inotify' system calls) and Windows systems. + whodata: Implies real-time monitoring but adding the 'who-data' information. + - tier: + 0: Only level 0 tests are performed, they check basic functionalities and are quick to perform. + 1: Only level 1 tests are performed, they check functionalities of medium complexity. + 2: Only level 2 tests are performed, they check advanced functionalities and are slow to perform. + +tags: + - fim_registry_file_limit +''' + +import os, sys +import pytest +from wazuh_testing import global_parameters +from wazuh_testing.fim import (LOG_FILE_PATH, generate_params, modify_registry_value, registry_parser, KEY_WOW64_64KEY, + REG_SZ, KEY_ALL_ACCESS, RegOpenKeyEx, RegCloseKey, create_registry) +from wazuh_testing.fim_module import (WINDOWS_HKEY_LOCAL_MACHINE, MONITORED_KEY, CB_FILE_LIMIT_VALUE, + ERR_MSG_FILE_LIMIT_VALUES, CB_COUNT_REGISTRY_FIM_ENTRIES, + ERR_MSG_FIM_INODE_ENTRIES, ERR_MSG_WRONG_NUMBER_OF_ENTRIES, + ERR_MSG_WRONG_FILE_LIMIT_VALUE) +from wazuh_testing.tools.configuration import load_wazuh_configurations +from wazuh_testing.tools.monitoring import FileMonitor, generate_monitoring_callback + +# Marks + +pytestmark = [pytest.mark.win32, pytest.mark.tier(level=1)] + +# Variables + +test_regs = [os.path.join(WINDOWS_HKEY_LOCAL_MACHINE, MONITORED_KEY)] +test_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') +wazuh_log_monitor = FileMonitor(LOG_FILE_PATH) +monitor_timeout = 40 + +# Configurations + +file_limit_list = ['1', '1000'] +conf_params = {'WINDOWS_REGISTRY': test_regs[0]} +params, metadata = generate_params(extra_params=conf_params, + apply_to_all=({'FILE_LIMIT': file_limit_elem} for file_limit_elem in file_limit_list), + modes=['scheduled']) + +configurations_path = os.path.join(test_data_path, 'wazuh_conf.yaml') +configurations = load_wazuh_configurations(configurations_path, __name__, params=params, metadata=metadata) + + +# Fixtures + +@pytest.fixture(scope='module', params=configurations) +def get_configuration(request): + """Get configurations from the module.""" + return request.param + + +# Functions + +def extra_configuration_before_yield(): + """Generate registry entries to fill database""" + reg1_handle = create_registry(registry_parser[WINDOWS_HKEY_LOCAL_MACHINE], MONITORED_KEY, KEY_WOW64_64KEY) + + RegCloseKey(reg1_handle) + + +# Tests +@pytest.mark.skip(reason="Blocked by issue wazuh/wazuh #11819") +def test_file_limit_values(get_configuration, configure_environment, restart_syscheckd): + ''' + description: Check if the 'wazuh-syscheckd' daemon detects the value of the 'entries' tag, which corresponds to + the maximum number of entries to monitor from the 'file_limit' option of FIM. For this purpose, + the test will monitor a key in which multiple testing values will be added. Then, it will check if + the FIM event 'maximum number of entries' is generated and has the correct value. Finally, the test + will verify that, in the FIM 'entries' event, the number of entries and monitored values match. + + wazuh_min_version: 4.2.0 + + tier: 1 + + parameters: + - tags_to_apply: + type: set + brief: Run test if matches with a configuration identifier, skip otherwise. + - get_configuration: + type: fixture + brief: Get configurations from the module. + - configure_environment: + type: fixture + brief: Configure a custom environment for testing. + - restart_syscheckd: + type: fixture + brief: Clear the Wazuh logs file and start a new monitor. + + assertions: + - Verify that the FIM event 'maximum number of entries' has the correct value + for the monitored entries limit of the 'file_limit' option. + + input_description: A test case (file_limit_registry_conf) is contained in external YAML file (wazuh_conf.yaml) + which includes configuration settings for the 'wazuh-syscheckd' daemon. That is combined + with the limits and the testing registry key to be monitored defined in this module. + + expected_output: + - r'.*Maximum number of entries to be monitored' + - r'.*Fim registry entries' + + tags: + - scheduled + ''' + file_limit = get_configuration['metadata']['file_limit'] + reg1_handle = RegOpenKeyEx(registry_parser[WINDOWS_HKEY_LOCAL_MACHINE], MONITORED_KEY, 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY) + # Add values to registry plus 10 values over the file limit + for i in range(0, int(file_limit) + 10): + modify_registry_value(reg1_handle, f'value_{i}', REG_SZ, 'added') + + # Look for the file limit value has been configured + file_limit_value = wazuh_log_monitor.start(timeout=global_parameters.default_timeout, + callback=generate_monitoring_callback(CB_FILE_LIMIT_VALUE), + error_message=ERR_MSG_FILE_LIMIT_VALUES).result() + # Compare that the value configured is correct + assert file_limit_value == get_configuration['metadata']['file_limit'], ERR_MSG_WRONG_FILE_LIMIT_VALUE + + # Get the ammount of entries monitored and assert they are the same as the limit and not over + entries = wazuh_log_monitor.start(timeout=monitor_timeout, + callback=generate_monitoring_callback(CB_COUNT_REGISTRY_FIM_ENTRIES), + error_message=ERR_MSG_FIM_INODE_ENTRIES).result() + + assert entries == str(get_configuration['metadata']['file_limit']), ERR_MSG_WRONG_NUMBER_OF_ENTRIES diff --git a/tests/integration/test_logcollector/test_location/data/configuration/wazuh_location.yaml b/tests/integration/test_logcollector/test_location/data/configuration/wazuh_location.yaml new file mode 100644 index 0000000000..bbea9eb78e --- /dev/null +++ b/tests/integration/test_logcollector/test_location/data/configuration/wazuh_location.yaml @@ -0,0 +1,24 @@ +- tags: + - test_location + apply_to_modules: + - test_location + - test_location_exclude + sections: + - section: localfile + attributes: + - name: 'testing files' + elements: + - log_format: + value: 'syslog' + - location: + value: LOCATION + - exclude: + value: EXCLUDE + - section: localfile + attributes: + - name: 'duplicated' + elements: + - log_format: + value: 'syslog' + - location: + value: PATH_2 \ No newline at end of file diff --git a/tests/integration/test_logcollector/test_options/data/configuration/wazuh_configuration.yaml b/tests/integration/test_logcollector/test_options/data/configuration/wazuh_configuration.yaml new file mode 100644 index 0000000000..f0b89052ff --- /dev/null +++ b/tests/integration/test_logcollector/test_options/data/configuration/wazuh_configuration.yaml @@ -0,0 +1,13 @@ +- tags: + - test_options + apply_to_modules: + - test_options_state_interval_no_file + sections: + - section: localfile + attributes: + - name: 'testing files' + elements: + - log_format: + value: 'syslog' + - location: + value: LOCATION diff --git a/tests/system/provisioning/four_manager_disconnected_node/roles/master-role/tasks/main.yaml b/tests/system/provisioning/four_manager_disconnected_node/roles/master-role/tasks/main.yaml new file mode 100644 index 0000000000..9dd425abf0 --- /dev/null +++ b/tests/system/provisioning/four_manager_disconnected_node/roles/master-role/tasks/main.yaml @@ -0,0 +1,108 @@ +--- +- name: "Check and update debian repositories" + shell: + cmd: apt-get update --allow-releaseinfo-change + +- name: "Installing dependencies using apt" + apt: + pkg: + - git + - gcc + - make + - cmake + - libc6-dev + - curl + - policycoreutils + - automake + - autoconf + - libtool + - sqlite3 + - libssl-dev + force_apt_get: yes + state: present + update_cache: yes + cache_valid_time: 3600 + +- name: "Clone wazuh repository" + git: + repo: "https://github.com/wazuh/wazuh" + dest: /wazuh + version: "{{ wazuh_branch }}" + when: wazuh_branch is defined + +- name: Install master + args: + chdir: /wazuh + creates: /var/ossec + environment: + USER_LANGUAGE: "en" + USER_NO_STOP: "y" + USER_INSTALL_TYPE: "server" + USER_DIR: "/var/ossec" + USER_ENABLE_EMAIL: "n" + USER_ENABLE_SYSCHECK: "n" + USER_ENABLE_ROOTCHECK: "n" + USER_ENABLE_OPENSCAP: "n" + USER_WHITE_LIST: "n" + USER_ENABLE_SYSLOG: "y" + USER_ENABLE_AUTHD: "y" + USER_AUTO_START: "y" + USER_UPDATE: "n" + shell: "./install.sh" + when: wazuh_branch is defined + +- name: "Get manager package" + ansible.builtin.get_url: + url: "https://{{package_repository}}.wazuh.com/{{repository}}/apt/pool/main/w/wazuh-manager/wazuh-manager_{{package_version}}-{{package_revision}}_amd64.deb" + dest: /tmp/wazuh-manager.deb + when: wazuh_branch is not defined + +- name: "Install manager package" + ansible.builtin.apt: + deb: /tmp/wazuh-manager.deb + when: wazuh_branch is not defined + +- name: Copy ossec.conf file + copy: + src: ../files/ossec.conf + dest: /var/ossec/etc/ossec.conf + owner: root + group: root + mode: '0644' + +- name: Set cluster key + lineinfile: + path: /var/ossec/etc/ossec.conf + regexp: '(KEY)' + line: "{{ cluster_key }}" + backrefs: yes + +- name: Set Wazuh Master IP + lineinfile: + path: /var/ossec/etc/ossec.conf + regexp: '(.*)' + line: "{{ master_hostname }}" + backrefs: yes + +- name: Stop Wazuh + command: /var/ossec/bin/wazuh-control stop + +- name: Remove client.keys + file: + path: /var/ossec/etc/client.keys + state: absent + +- name: enable authd and clusterd debug mode + blockinfile: + path: /var/ossec/etc/local_internal_options.conf + block: | + authd.debug=2 + wazuh_clusterd.debug=2 + wazuh_db.debug=2 + wazuh_modules.debug=2 + +- name: Start Wazuh + command: /var/ossec/bin/wazuh-control restart + +- name: "Install necessary dependencies" + command: /var/ossec/framework/python/bin/python3.9 -m pip install lockfile filetype certifi testinfra diff --git a/tests/system/provisioning/four_manager_disconnected_node/roles/worker-role/tasks/main.yaml b/tests/system/provisioning/four_manager_disconnected_node/roles/worker-role/tasks/main.yaml new file mode 100644 index 0000000000..d8daae427d --- /dev/null +++ b/tests/system/provisioning/four_manager_disconnected_node/roles/worker-role/tasks/main.yaml @@ -0,0 +1,108 @@ +--- +- name: "Check and update debian repositories" + shell: + cmd: apt-get update --allow-releaseinfo-change + +- name: "Installing dependencies using apt" + apt: + pkg: + - git + - gcc + - make + - cmake + - libc6-dev + - curl + - policycoreutils + - automake + - autoconf + - libtool + - python3-pytest + - sqlite3 + - libssl-dev + force_apt_get: yes + state: present + update_cache: yes + cache_valid_time: 3600 + +- name: "Clone wazuh repository" + git: + repo: "https://github.com/wazuh/wazuh" + dest: /wazuh + version: "{{ wazuh_branch }}" + when: wazuh_branch is defined + +- name: Install worker + args: + chdir: /wazuh + creates: /var/ossec + environment: + USER_LANGUAGE: "en" + USER_NO_STOP: "y" + USER_INSTALL_TYPE: "server" + USER_DIR: "/var/ossec" + USER_ENABLE_EMAIL: "n" + USER_ENABLE_SYSCHECK: "y" + USER_ENABLE_ROOTCHECK: "y" + USER_ENABLE_OPENSCAP: "y" + USER_WHITE_LIST: "n" + USER_ENABLE_SYSLOG: "y" + USER_ENABLE_AUTHD: "y" + USER_AUTO_START: "y" + USER_UPDATE: "n" + shell: "./install.sh" + when: wazuh_branch is defined + +- name: "Get manager package" + ansible.builtin.get_url: + url: "https://{{package_repository}}.wazuh.com/{{repository}}/apt/pool/main/w/wazuh-manager/wazuh-manager_{{package_version}}-{{package_revision}}_amd64.deb" + dest: /tmp/wazuh-manager.deb + when: wazuh_branch is not defined + +- name: "Install manager package" + ansible.builtin.apt: + deb: /tmp/wazuh-manager.deb + when: wazuh_branch is not defined + +- name: Copy ossec.conf file + copy: + src: ../files/ossec.conf + dest: /var/ossec/etc/ossec.conf + owner: root + group: root + mode: '0644' + +- name: Set cluster key + lineinfile: + path: /var/ossec/etc/ossec.conf + regexp: '(KEY)' + line: "{{ cluster_key }}" + backrefs: yes + +- name: Set Wazuh Worker name + lineinfile: + path: /var/ossec/etc/ossec.conf + regexp: '(.*)' + line: "{{ worker_name }}" + backrefs: yes + +- name: Set Wazuh Worker IP + lineinfile: + path: /var/ossec/etc/ossec.conf + regexp: '(.*)' + line: "{{ master_hostname }}" + backrefs: yes + +- name: enable authd and clusterd debug mode + blockinfile: + path: /var/ossec/etc/local_internal_options.conf + block: | + authd.debug=2 + wazuh_clusterd.debug=2 + wazuh_db.debug=2 + wazuh_modules.debug=2 + +- name: Restart Wazuh + command: "{{restart_command}}" + +- name: "Install necessary dependencies" + command: /var/ossec/framework/python/bin/python3.9 -m pip install lockfile filetype certifi testinfra diff --git a/tests/system/test_fim/test_synchronization/data/agent_initializing_synchronization.yml b/tests/system/test_fim/test_synchronization/data/agent_initializing_synchronization.yml new file mode 100644 index 0000000000..d5e627e9ef --- /dev/null +++ b/tests/system/test_fim/test_synchronization/data/agent_initializing_synchronization.yml @@ -0,0 +1,4 @@ +wazuh-agent1: + - regex: ".*Initializing FIM Integrity Synchronization check. (.+)$" + path: "/var/ossec/logs/ossec.log" + timeout: 60 \ No newline at end of file diff --git a/tests/system/test_fim/test_synchronization/data/manager_initializing_synchronization.yml b/tests/system/test_fim/test_synchronization/data/manager_initializing_synchronization.yml new file mode 100644 index 0000000000..804ea2a01d --- /dev/null +++ b/tests/system/test_fim/test_synchronization/data/manager_initializing_synchronization.yml @@ -0,0 +1,4 @@ +wazuh-manager: + - regex: ".*Initializing FIM Integrity Synchronization check. (.+)$" + path: "/var/ossec/logs/ossec.log" + timeout: 60 \ No newline at end of file