Exemple #1
0
def reload_new_conf(report_value, reg1, reg2):
    """"
    Return a new ossec configuration with a changed report_value

    Parameters
    ----------
    report_value: str
        Value that will be used for the report_changes option.
    reg1: str
        Registry path that will be written in the configuration for WINDOWS_REGISTRY_1.
    reg2: str
        Registry path that will be written in the configuration for WINDOWS_REGISTRY_2.
    """
    new_conf_params = {
        'WINDOWS_REGISTRY_1': reg1,
        'WINDOWS_REGISTRY_2': reg2,
        'REPORT_CHANGES_1': report_value,
        'REPORT_CHANGES_2': report_value
    }

    conf_params, conf_metadata = generate_params(extra_params=new_conf_params,
                                                 modes=['scheduled'])
    new_conf = load_wazuh_configurations(configurations_path,
                                         __name__,
                                         params=conf_params,
                                         metadata=conf_metadata)
    # Load the third configuration in the yaml
    restart_wazuh_with_new_conf(
        set_section_wazuh_conf(new_conf[2].get('sections')))
    # Wait for FIM scan to finish
    detect_initial_scan(wazuh_log_monitor)
def disable_report_changes(fim_mode):
    """Change the `report_changes` value in the `ossec.conf` file and then restart `Syscheck` to apply the changes."""
    new_conf = change_conf(report_value='no')
    new_ossec_conf = set_section_wazuh_conf(new_conf[0].get('sections'))
    restart_wazuh_with_new_conf(new_ossec_conf)
    # Wait for FIM scan to finish
    detect_fim_scan(wazuh_log_monitor, fim_mode)
def override_wazuh_conf(configuration, set_password):
    # Stop Wazuh
    control_service('stop', daemon='wazuh-authd')
    time.sleep(1)
    check_daemon_status(running=False, daemon='wazuh-authd')
    truncate_file(LOG_FILE_PATH)

    # Configuration for testing
    test_config = set_section_wazuh_conf(configuration.get('sections'))
    # Set new configuration
    write_wazuh_conf(test_config)

    # reset_client_keys
    clean_client_keys_file()
    # reset password
    reset_password(set_password)

    time.sleep(1)
    # Start Wazuh
    control_service('start', daemon='wazuh-authd')
    """Wait until agentd has begun"""
    def callback_agentd_startup(line):
        if 'Accepting connections on port 1515' in line:
            return line
        return None

    log_monitor = FileMonitor(LOG_FILE_PATH)
    log_monitor.start(timeout=30, callback=callback_agentd_startup)
    time.sleep(1)
Exemple #4
0
def configure_environment(get_configuration, request):
    """Configure a custom environment for testing. Restart Wazuh is needed for applying the configuration."""

    # Save current configuration
    backup_config = get_wazuh_conf()

    # Configuration for testing
    test_config = set_section_wazuh_conf(get_configuration.get('sections'))

    # Create test directories
    if hasattr(request.module, 'test_directories'):
        test_directories = getattr(request.module, 'test_directories')
        for test_dir in test_directories:
            os.makedirs(test_dir, exist_ok=True, mode=0o777)

    # Set new configuration
    write_wazuh_conf(test_config)

    # Change Windows Date format to ensure TimeMachine will work properly
    if sys.platform == 'win32':
        subprocess.call(
            'reg add "HKCU\\Control Panel\\International" /f /v sShortDate /t REG_SZ /d "dd/MM/yyyy" >nul',
            shell=True)

    # Call extra functions before yield
    if hasattr(request.module, 'extra_configuration_before_yield'):
        func = getattr(request.module, 'extra_configuration_before_yield')
        func()

    # Set current configuration
    global_parameters.current_configuration = get_configuration

    yield

    TimeMachine.time_rollback()

    # Remove created folders (parents)
    if sys.platform == 'win32':
        control_service('stop')

    if hasattr(request.module, 'test_directories'):
        for test_dir in test_directories:
            shutil.rmtree(test_dir, ignore_errors=True)

    if sys.platform == 'win32':
        control_service('start')

    # Restore previous configuration
    write_wazuh_conf(backup_config)

    # Call extra functions after yield
    if hasattr(request.module, 'extra_configuration_after_yield'):
        func = getattr(request.module, 'extra_configuration_after_yield')
        func()

    if hasattr(request.module, 'force_restart_after_restoring'):
        if getattr(request.module, 'force_restart_after_restoring'):
            control_service('restart')
Exemple #5
0
def test_skip_proc(get_configuration, configure_environment, restart_syscheckd,
                   wait_for_initial_scan):
    """Check if syscheckd skips /proc when setting 'skip_proc="yes"'."""
    check_apply_test({'skip_proc'}, get_configuration['tags'])
    trigger = get_configuration['metadata']['skip'] == 'no'

    if trigger:
        proc = subprocess.Popen([
            "python3",
            f"{os.path.dirname(os.path.abspath(__file__))}/data/proc.py"
        ])

        # Change configuration, monitoring the PID path in /proc
        # Monitor only /proc/PID to expect only these events. Otherwise, it will fail due to Timeouts since
        # integrity scans will take too long
        new_conf = change_conf(f'/proc/{proc.pid}')
        new_ossec_conf = []

        # Get new skip_proc configuration
        for conf in new_conf:
            if conf['metadata']['skip'] == 'no' and conf['tags'] == [
                    'skip_proc'
            ]:
                new_ossec_conf = set_section_wazuh_conf(conf.get('sections'))
        restart_wazuh_with_new_conf(new_ossec_conf)
        truncate_file(LOG_FILE_PATH)
        proc_monitor = FileMonitor(LOG_FILE_PATH)
        detect_initial_scan(proc_monitor)

        # Do not expect any 'Sending event'
        with pytest.raises(TimeoutError):
            proc_monitor.start(
                timeout=3,
                callback=callback_detect_event,
                error_message=
                'Did not receive expected "Sending FIM event: ..." event')

        check_time_travel(time_travel=True, monitor=wazuh_log_monitor)

        found_event = False
        while not found_event:
            event = proc_monitor.start(
                timeout=5,
                callback=callback_detect_event,
                error_message='Did not receive expected '
                '"Sending FIM event: ..." event').result()
            if f'/proc/{proc.pid}/' in event['data'].get('path'):
                found_event = True

        # Kill the process
        subprocess.Popen(["kill", "-9", str(proc.pid)])

    else:
        with pytest.raises(TimeoutError):
            event = wazuh_log_monitor.start(
                timeout=3, callback=callback_detect_integrity_state)
            raise AttributeError(f'Unexpected event {event}')
Exemple #6
0
    def apply_config(self,
                     config_yml_path: str,
                     dest_path: str = WAZUH_CONF,
                     clear_files: list = None,
                     restart_services: list = None):
        """Apply the configuration described in the config_yml_path to the environment.

        Parameters
        ----------
        config_yml_path : str
            Path to the yml file that contains the configuration to be applied
        dest_path : str
            Destination file
        clear_files : list
            List of files to be truncated
        restart_services : list
            List of services to be restarted
        """
        with open(config_yml_path, mode='r') as config_yml:
            config = yaml.safe_load(config_yml)

        parse_configurations = dict()
        for host, payload in config.items():
            template_ossec_conf = self.get_file_content(host,
                                                        dest_path).split('\n')
            parse_configurations[host] = set_section_wazuh_conf(
                sections=payload['sections'], template=template_ossec_conf)

        for host, configuration in parse_configurations.items():
            configuration = ''.join(configuration)
            dom = minidom.parseString(configuration)
            configuration = dom.toprettyxml().split('\n', 1)[1]
            self.modify_file_content(host, dest_path, configuration)

            if restart_services:
                for service in restart_services:
                    self.control_service(host=host,
                                         service=service,
                                         state='restarted')
            if clear_files:
                for log in clear_files:
                    self.clear_file(host=host, file_path=log)
def override_wazuh_conf(configuration):
    """Apply custom settings on ossec.conf file.

    Settings are obtained from values located under "configuration" section of tests found in a YAML file.
    For this purpose, it stops the wazuh-agentd service, applies the settings and starts it again.

    Args:
        configuration (dict): New parameters to be applied.

    Raises:
        ValueError: If wazuh-agentd daemon cannot be started again.
    """
    # Stop Wazuh
    control_service('stop', daemon='wazuh-agentd')

    # Configuration for testing
    temp = get_temp_yaml(configuration)
    conf = load_wazuh_configurations(
        temp,
        __name__,
    )
    os.remove(temp)

    test_config = set_section_wazuh_conf(conf[0]['sections'])
    # Set new configuration
    write_wazuh_conf(test_config)

    # reset_client_keys
    ag.clean_client_keys_file()
    clean_log_file()
    ag.clean_password_file()
    if configuration.get('password'):
        parser = ag.AgentAuthParser()
        parser.add_password(password=configuration['password']['value'],
                            isFile=True,
                            path=configuration.get('authorization_pass_path'))

    # Start Wazuh
    control_service('start', daemon='wazuh-agentd')