def test_remove_and_read_folder(tags_to_apply, folder, get_configuration,
                                configure_environment, restart_syscheckd,
                                wait_for_fim_start):
    """Remove folder which is monitored with auditd and then create it again.

    Args:
        tags_to_apply (set): Run test if matches with a configuration identifier, skip otherwise.
        folder (str): The folder to remove and read.
        get_configuration (fixture): Gets the current configuration of the test.
        configure_environment (fixture): Configure the environment for the execution of the test.
        restart_syscheckd (fixture): Restarts syscheck.
        wait_for_fim_start (fixture): Waits until the first FIM scan is completed.

    Raises:
        TimeoutError: If an expected event couldn't be captured.
    """

    check_apply_test(tags_to_apply, get_configuration['tags'])

    shutil.rmtree(folder, ignore_errors=True)
    wazuh_log_monitor.start(
        timeout=global_parameters.default_timeout,
        callback=fim.callback_audit_removed_rule,
        error_message=f'Did not receive expected "removed" event '
        f'removing the folder {folder}')

    os.makedirs(folder, mode=0o777)
    fim.wait_for_audit(True, wazuh_log_monitor)
    wazuh_log_monitor.start(
        timeout=global_parameters.default_timeout,
        callback=fim.callback_audit_added_rule,
        error_message='Did not receive expected "added" event')
Esempio n. 2
0
def test_remove_rule_five_times(tags_to_apply, folder, audit_key,
                                get_configuration, configure_environment,
                                restart_syscheckd, wait_for_initial_scan):
    """Remove auditd rule using auditctl five times and check Wazuh ignores folder.

    Parameters
    ----------
    tags_to_apply : set
        Configuration tag to apply in the test
    folder : str
        The folder to remove and read
    audit_key : str
        The key which Wazuh put.
    """

    check_apply_test(tags_to_apply, get_configuration['tags'])

    for _ in range(0, 5):
        subprocess.run(["auditctl", "-W", folder, "-p", "wa", "-k", audit_key],
                       check=True)
        wazuh_log_monitor.start(timeout=20,
                                callback=callback_audit_rules_manipulation,
                                error_message='Did not receive expected '
                                '"Detected Audit rules manipulation" event')

    wazuh_log_monitor.start(
        timeout=20,
        callback=callback_audit_deleting_rule,
        error_message='Did not receive expected "Deleting Audit rules" event')
Esempio n. 3
0
def test_disk_quota_disabled(tags_to_apply, filename, folder, size, get_configuration, configure_environment,
                             restart_syscheckd, wait_for_fim_start):
    """
    Check that the disk_quota option is disabled correctly.

    Creates a file that, when compressed, is larger than the configured disk_quota limit and checks that the message
    about reaching the limit does not appear in the log.

    Parameters
    ----------
    filename : str
        Name of the file to be created.
    folder : str
        Directory where the files are being created.
    size : int
        Size of each file in bytes.
    tags_to_apply : set
        Run test if matches with a configuration identifier, skip otherwise.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])
    scheduled = get_configuration['metadata']['fim_mode'] == 'scheduled'

    to_write = generate_string(size, '0')
    create_file(REGULAR, folder, filename, content=to_write)

    check_time_travel(scheduled)

    with pytest.raises(TimeoutError):
        wazuh_log_monitor.start(timeout=global_parameters.default_timeout, callback=callback_disk_quota_limit_reached)
def test_ambiguous_tags(folders, tags_to_apply, get_configuration,
                        configure_environment, restart_syscheckd,
                        wait_for_initial_scan):
    """Check if syscheck detects the event property 'tags' for each event.

    This test validates both situations, making sure that if tags='no', there won't be a
    tags event property.

    Parameters
    ----------
    folders : list
        Monitored directories
    tags_to_apply : set
        Run test if matches with a configuration identifier, skip otherwise
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])
    scheduled = get_configuration['metadata']['fim_mode'] == 'scheduled'

    # Check that events inside folder[0] do not contain the key 'tags'.
    regular_file_cud(folders[0],
                     wazuh_log_monitor,
                     time_travel=scheduled,
                     min_timeout=global_parameters.default_timeout,
                     validators_after_cud=[no_tag_validator])

    # Check that events inside folder[1] do contain the key 'tags'.
    regular_file_cud(folders[1],
                     wazuh_log_monitor,
                     time_travel=scheduled,
                     min_timeout=global_parameters.default_timeout,
                     validators_after_cud=[tag_validator])
def test_bruteforce_blocking_system(tags_to_apply, get_configuration,
                                    configure_api_environment, restart_api,
                                    wait_for_start, get_api_details):
    """Check that the blocking time for IPs detected as brute-force attack works.

    Provoke a block, make a request before the blocking
    time finishes and one after the blocking time.

    Parameters
    ----------
    tags_to_apply : set
        Run test if match with a configuration identifier, skip otherwise.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])
    block_time = get_configuration['configuration']['access']['block_time']
    max_login_attempts = get_configuration['configuration']['access'][
        'max_login_attempts']

    # Provoke a block from an unknown IP ('max_login_attempts' attempts with incorrect credentials).
    for _ in range(max_login_attempts):
        with pytest.raises(Exception):
            get_api_details(user='******', password='******')

    # Request with correct credentials before blocking time expires.
    with pytest.raises(Exception) as login_exc:
        get_api_details()
    assert 'Error obtaining login token' in login_exc.value.args[0], f'An error getting the token was expected, but ' \
                                                                     f'it was not obtained. \nFull response: ' \
                                                                     f'{login_exc.value}'

    # Request after time expires.
    time.sleep(block_time)  # 300 = default blocking time
Esempio n. 6
0
def test_scan_time(tags_to_apply, get_configuration, configure_environment,
                   restart_syscheckd, wait_for_fim_start):
    """
    Check if there is a scan at a certain time

    scan_time option makes sure there is only one scan every 24 hours, at a certain time.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])

    # Reformat given time to a readable format since it can be writen in several ways in ossec.conf
    scan_time = reformat_time(get_configuration['metadata']['scan_time'])
    current_time = datetime.now()

    # Calculate how much time we need to travel in time to make sure there hasn't been any scan until it is the given
    # time
    time_difference = (scan_time - current_time) if (scan_time - current_time).days == 0 else \
        ((scan_time - current_time) + timedelta(days=2))
    check_time_travel(time_travel=True,
                      interval=time_difference + timedelta(minutes=-30))
    with pytest.raises(TimeoutError):
        event = wazuh_log_monitor.start(
            timeout=global_parameters.default_timeout,
            callback=callback_detect_end_scan)
        raise AttributeError(f'Unexpected event {event}')

    check_time_travel(time_travel=True, interval=timedelta(minutes=31))
    wazuh_log_monitor.start(timeout=global_parameters.default_timeout,
                            callback=callback_detect_end_scan,
                            error_message='Did not receive expected '
                            '"File integrity monitoring scan ended" event')
Esempio n. 7
0
def test_providers_no_os(clean_vuln_tables, get_configuration, configure_environment):
    """
    Check if modulesd downloads the feeds without specifing the os version.
    """
    check_apply_test({'test_providers_no_os'}, get_configuration['tags'])
    provider_name = get_configuration['metadata']['provider_name']

    # Those providers that aren't expected to work without the <os> tag.
    try:
        control_service('restart')
    except ValueError:
        assert 'error' in get_configuration['metadata']

    if 'error' in get_configuration['metadata']:
        wazuh_log_monitor.start(timeout=vd.VULN_DETECTOR_GLOBAL_TIMEOUT,
                                callback=vd.make_vuln_callback(r".* \(\d+\): Configuration error at.*",
                                                               prefix='.*wazuh-modulesd.*'),
                                error_message=f"Error log 'Configuration error at '/var/ossec/etc/ossec.conf'.' "
                                              f"not found")
    else:
        for os in get_configuration['metadata']['os']:
            if os != '':
                os_name = f"{provider_name} {os}"
            else:
                os_name = f"JSON {provider_name}" if 'Red Hat' in provider_name else f"{provider_name}"

            wazuh_log_monitor.start(
                timeout=80 if 'Red Hat' in os_name else VULN_DETECTOR_GLOBAL_TIMEOUT,
                callback=make_vuln_callback(f"Starting '{os_name}' database update"),
                error_message=f"Could not find {os_name} update starting log",
            )
Esempio n. 8
0
def test_multiple_dirs(dir_list, tags_to_apply, get_configuration,
                       configure_environment, restart_syscheckd,
                       wait_for_initial_scan):
    """
    Check if syscheck can detect every event when adding, modifying and deleting a file within multiple monitored
    directories.

    These directories will be added in one single entry like so:
        <directories>testdir0, testdir1, ..., testdirn</directories>

    Parameters
    ----------
    dir_list : list
        List with all the directories to be monitored.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])

    file = 'regular'
    scheduled = get_configuration['metadata']['fim_mode'] == 'scheduled'

    try:
        multiple_dirs_test(dir_list=dir_list,
                           file=file,
                           scheduled=scheduled,
                           log_monitor=wazuh_log_monitor,
                           timeout=2 * global_parameters.default_timeout)
    except TimeoutError as e:
        if get_configuration['metadata']['fim_mode'] == 'whodata':
            pytest.xfail(
                reason=
                'Xfailed due to issue: https://github.com/wazuh/wazuh/issues/4731'
            )
        else:
            raise e
Esempio n. 9
0
def test_check_others(path, checkers, get_configuration, configure_environment,
                      restart_syscheckd, wait_for_initial_scan):
    """
    Test the behaviour of several combinations of Check options over the same directory with Check_all disabled to
    avoid using the default check_all configuration. The order of the checks (including check_all="no") will be
    different on each case to test the behaviour of check_all="no".

    Example:
        check_all: "no" check_size: "yes" check_sum: "yes"
        check_all: "no" check_md5sum: "yes" check_mtime: "yes" check_group: "yes"
        check_md5sum: "yes" check_all: "no" check_mtime: "yes" check_group: "yes"
        ...

    Parameters
    ----------
    path : str
        Directory where the file is being created and monitored.
    checkers : dict
        Check options to be used.
    """
    check_apply_test({'test_check_others'}, get_configuration['tags'])

    regular_file_cud(
        path,
        wazuh_log_monitor,
        min_timeout=15,
        options=checkers,
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled')
Esempio n. 10
0
def test_remove_rule_five_times(tags_to_apply, folder, audit_key,
                                get_configuration, configure_environment,
                                restart_syscheckd, wait_for_fim_start):
    """Remove auditd rule using auditctl five times and check Wazuh ignores folder.

    Args:
        tags_to_apply (set): Run test if matches with a configuration identifier, skip otherwise.
        folder (str): Path whose rule will be removed.
        audit_key (str): Name of the configured audit key.
        get_configuration (fixture): Gets the current configuration of the test.
        uninstall_install_audit (fixture): Uninstall auditd before the test and install auditd again after the test is
                                           executed.
        configure_environment (fixture): Configure the environment for the execution of the test.
        restart_syscheckd (fixture): Restarts syscheck.
        wait_for_fim_start (fixture): Waits until the first FIM scan is completed.

    Raises:
        TimeoutError: If an expected event couldn't be captured.
    """

    check_apply_test(tags_to_apply, get_configuration['tags'])

    for _ in range(0, 5):
        subprocess.run(["auditctl", "-W", folder, "-p", "wa", "-k", audit_key],
                       check=True)
        wazuh_log_monitor.start(timeout=20,
                                callback=fim.callback_audit_rules_manipulation,
                                error_message='Did not receive expected '
                                '"Detected Audit rules manipulation" event')

    wazuh_log_monitor.start(
        timeout=20,
        callback=fim.callback_audit_deleting_rule,
        error_message='Did not receive expected "Deleting Audit rules" event')
def test_events_from_existing_files(filename, tags_to_apply, get_configuration,
                                    configure_environment, restart_syscheckd,
                                    wait_for_fim_start):
    """Check if syscheck generates modified alerts for files that exists when starting the agent"""
    check_apply_test(tags_to_apply, get_configuration['tags'])
    scheduled = get_configuration['metadata']['fim_mode'] == 'scheduled'
    mode = get_configuration['metadata']['fim_mode']

    # Modify file
    modify_file_content(testdir1, filename, new_content='Sample content')

    # Expect modified event
    check_time_travel(scheduled, monitor=wazuh_log_monitor)
    modified_event = wazuh_log_monitor.start(
        timeout=timeout,
        callback=callback_detect_event,
        error_message='Did not receive expected '
        '"Sending FIM event: ..." event').result()
    assert 'modified' in modified_event['data']['type'] and \
           os.path.join(testdir1, filename) in modified_event['data']['path']
    validate_event(modified_event, mode=mode)

    # Delete file
    delete_file(testdir1, filename)

    # Expect deleted event
    check_time_travel(scheduled, monitor=wazuh_log_monitor)
    deleted_event = wazuh_log_monitor.start(
        timeout=timeout,
        callback=callback_detect_event,
        error_message='Did not receive expected '
        '"Sending FIM event: ..." event').result()
    assert 'deleted' in deleted_event['data']['type'] and \
           os.path.join(testdir1, filename) in deleted_event['data']['path']
    validate_event(deleted_event, mode=mode)
Esempio n. 12
0
def test_skip_nfs(modify_inode_mock, directory, tags_to_apply, configure_nfs, get_configuration, configure_environment,
                  restart_syscheckd, wait_for_fim_start):
    """Check if syscheckd skips nfs directories when setting 'skip_nfs="yes"'.

    This test assumes you have a nfs directory mounted on '/nfs-mount-point'. If you do not have one, use the fixture
    `configure_nfs`.

    Parameters
    ----------
    directory : str
        Directory that will be monitored.
    """

    def custom_callback(filename):
        def callback(line):
            match = callback_detect_event(line)
            if match and filename in match['data']['path']:
                return match

        return callback

    file = str(uuid.uuid1())
    check_apply_test(tags_to_apply, get_configuration['tags'])
    trigger = get_configuration['metadata']['skip'] == 'no'

    try:
        regular_file_cud(directory, wazuh_log_monitor, file_list=[file], time_travel=True, min_timeout=3,
                         triggers_event=trigger, callback=custom_callback(file))

    finally:
        delete_file(directory, file)
Esempio n. 13
0
def test_skip_sys(get_configuration, configure_environment, restart_syscheckd, wait_for_fim_start):
    """Check if syscheckd skips /sys when setting 'skip_sys="yes"'."""
    check_apply_test({'skip_sys'}, get_configuration['tags'])
    trigger = get_configuration['metadata']['skip'] == 'no'

    if trigger:
        # If /sys/module/isofs does not exist, use 'modprobe isofs'
        assert os.path.exists('/sys/module/isofs'), f'/sys/module/isofs does not exist'

        # Do not expect any 'Sending event'
        with pytest.raises(TimeoutError):
            event = wazuh_log_monitor.start(timeout=5, callback=callback_detect_event)
            raise AttributeError(f'Unexpected event {event}')

        # Remove module isofs and travel to future to check alerts
        subprocess.Popen(["modprobe", "-r", "isofs"])
        TimeMachine.travel_to_future(timedelta(hours=13))

        # Detect at least one 'delete' event in /sys/module/isofs path
        event = wazuh_log_monitor.start(timeout=5, callback=callback_detect_event,
                                        error_message='Did not receive expected '
                                                      '"Sending FIM event: ..." event').result()
        assert event['data'].get('type') == 'deleted' and '/sys/module/isofs' in event['data'].get('path'), \
            f'Sys event not detected'

        # Restore module isofs
        subprocess.Popen(["modprobe", "isofs"])
    else:
        with pytest.raises(TimeoutError):
            event = wazuh_log_monitor.start(timeout=3, callback=callback_detect_integrity_state)
            raise AttributeError(f'Unexpected event {event}')
def test_reconnect_to_audit(tags_to_apply, get_configuration,
                            configure_environment, restart_syscheckd,
                            wait_for_fim_start):
    """Restart auditd and check Wazuh reconnect to auditd

    Args:
        tags_to_apply (set): Run test if matches with a configuration identifier, skip otherwise.
        get_configuration (fixture): Gets the current configuration of the test.
        configure_environment (fixture): Configure the environment for the execution of the test.
        restart_syscheckd (fixture): Restarts syscheck.
        wait_for_fim_start (fixture): Waits until the first FIM scan is completed.

    Raises:
        TimeoutError: If an expected event couldn't be captured.
    """

    check_apply_test(tags_to_apply, get_configuration['tags'])

    restart_command = ["service", "auditd", "restart"]
    subprocess.run(restart_command, check=True)

    wazuh_log_monitor.start(
        timeout=20,
        callback=fim.callback_audit_connection_close,
        error_message='Did not receive expected "audit connection close" event'
    )
    wazuh_log_monitor.start(
        timeout=20,
        callback=fim.callback_audit_connection,
        error_message='Did not receive expected "audit connection" event')
Esempio n. 15
0
def test_readded_rules(tags_to_apply, get_configuration, configure_environment,
                       restart_syscheckd):
    """Check if the removed rules are added to Audit rules list."""
    logger.info('Applying the test configuration')
    check_apply_test(tags_to_apply, get_configuration['tags'])

    # Remove added rules
    for dir_ in (testdir1, testdir2, testdir3):
        command = f"auditctl -W {dir_} -p wa -k wazuh_fim"
        os.system(command)

        wazuh_log_monitor.start(
            timeout=20,
            callback=callback_audit_rules_manipulation,
            error_message=
            f'Did not receive expected "manipulation" event with the '
            f'command {command}')

        events = wazuh_log_monitor.start(
            timeout=10,
            callback=callback_audit_reloaded_rule,
            error_message=
            'Did not receive expected "reload" event with the rule '
            'modification').result()

        assert dir_ in events, f'{dir_} not in {events}'
Esempio n. 16
0
def test_check_others_individually(path, checkers, get_configuration,
                                   configure_environment, restart_syscheckd,
                                   wait_for_initial_scan):
    """
    Test the behaviour of every Check option individually without using the Check_all option. Check_all option will
    be set to "no" in order to avoid using the default check_all configuration.

    Example:
        check_all="no" check_sum="yes"
        check_all="no" check_mtime="yes"
        ...

    Parameters
    ----------
    path : str
        Directory where the file is being created and monitored.
    checkers : dict
        Check options to be used.
    """
    check_apply_test({'test_check_others_individually'},
                     get_configuration['tags'])

    regular_file_cud(
        path,
        wazuh_log_monitor,
        min_timeout=15,
        options=checkers,
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled')
def test_regular_file_changes(folder, name, encoding, checkers, tags_to_apply,
                              get_configuration, configure_environment,
                              restart_syscheckd, wait_for_initial_scan):
    """
    Check if syscheckd detects regular file changes (add, modify, delete)

    Parameters
    ----------
    folder : str
        Directory where the files will be created.
    checkers : dict
        Syscheck checkers (check_all).
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])

    if encoding is not None:
        name = name.encode(encoding)
        folder = folder.encode(encoding)

    regular_file_cud(
        folder,
        wazuh_log_monitor,
        file_list=[name],
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled',
        min_timeout=global_parameters.default_timeout,
        options=checkers,
        encoding=encoding,
        triggers_event=True)
Esempio n. 18
0
def test_drop_privileges(tags_to_apply, get_configuration,
                         configure_api_environment, restart_api,
                         wait_for_start, get_api_details):
    """Check if drop_privileges affects the user of the API process.

    In this test, the PID of the API process is obtained. After that,
    it gets the user (root or ossec) and checks if it matches the
    drop_privileges setting.

    Parameters
    ----------
    tags_to_apply : set
        Run test if match with a configuration identifier, skip otherwise.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])
    drop_privileges = get_configuration['configuration']['drop_privileges']

    # Get wazuh-apid process info
    api_process = get_process_cmd('/api/scripts/wazuh-apid.py')
    if not api_process:
        pytest.fail(
            "The process '/api/scripts/wazuh-apid.py' could not be found")

    # Get current user of the process
    proc_stat_file = os.stat("/proc/%d" % api_process.pid)
    uid = proc_stat_file.st_uid
    username = pwd.getpwuid(uid)[0]

    if drop_privileges:
        assert username == 'ossec', f'Expected user was "ossec", but the real one is {username}'
    else:
        assert username == 'root', f'Expected user was "root", but the real one is {username}'
def test_ignore_over_restrict_key(key, subkey, key_name, arch,
                                  get_configuration, configure_environment,
                                  restart_syscheckd, wait_for_fim_start):
    """
    Check registry values are ignored according to configuration.

    Parameters
    ----------
    key : str
        Root key (HKEY_*)
    subkey : str
        path of the registry where the test will be executed.
    arch : str
        Architecture of the registry.
    """
    check_apply_test({"ambiguous_ignore_restrict_key"},
                     get_configuration['tags'])

    # Test registry keys.
    registry_key_cud(key,
                     subkey,
                     wazuh_log_monitor,
                     arch=arch,
                     key_list=[key_name],
                     min_timeout=global_parameters.default_timeout,
                     time_travel=True,
                     triggers_event=False)
Esempio n. 20
0
def test_max_eps_on_start(get_configuration, create_files,
                          configure_environment, restart_syscheckd,
                          delete_files):
    """
    Check that max_eps is respected when a big quantity of synchronization events are generated

    Before starting the service, a number of files is created thanks to fixture create_files.
    After that, syscheck is launched and starts generating synchronization events.
    """
    check_apply_test({'max_eps_synchronization'}, get_configuration['tags'])
    max_eps = int(get_configuration['metadata']['max_eps'])

    #  Find integrity start before attempting to read max_eps
    wazuh_log_monitor.start(
        timeout=15,
        callback=callback_integrity_message,
        error_message="Didn't receive integrity_check_global").result()

    n_results = max_eps * 5
    result = wazuh_log_monitor.start(
        timeout=120,
        accum_results=n_results,
        callback=callback_integrity_message,
        error_message=f'Received less results than expected ({n_results})'
    ).result()

    counter = Counter([date_time for date_time, _ in result])
    error_margin = (max_eps * 0.1)

    for date_time, n_occurrences in counter.items():
        assert n_occurrences <= round(
            max_eps + error_margin
        ), f'Sent {n_occurrences} but a maximum of {max_eps} was set'
Esempio n. 21
0
def test_windows_audit_modify_sacl(tags_to_apply, get_configuration,
                                   configure_environment, restart_syscheckd,
                                   wait_for_fim_start):
    """Check that Wazuh detects a SACL change every 'windows_audit_interval' and sets monitoring to real-time if so."""
    check_apply_test(tags_to_apply, get_configuration['tags'])

    with Privilege('SeSecurityPrivilege'):
        # Assert that Wazuh rules are added
        lfss = get_file_security_descriptor(testdir_modify)
        dir_rules = get_sacl(lfss)
        assert dir_rules is not None, 'No SACL rules were applied to the monitored directory.'
        for rule in WAZUH_RULES:
            assert rule in dir_rules, f'{rule} not found in {dir_rules}'

        # Delete one of them and assert that after the 'windows_audit_interval' thread, Wazuh is set to real-time
        # monitoring
        modify_sacl(lfss, 'delete', mask=next(iter(WAZUH_RULES)))
        dir_rules = get_sacl(lfss)
        assert next(
            iter(WAZUH_RULES)
        ) not in dir_rules, f'{next(iter(WAZUH_RULES))} found in {dir_rules}'

    event = wazuh_log_monitor.start(
        timeout=windows_audit_interval,
        callback=callback_sacl_changed,
        error_message='Did not receive expected "The SACL '
        'of \'...\' has been restored correctly" event').result()
    assert testdir_modify in event, f'{testdir_modify} not detected in SACL modification event'
def test_multiple_entries(tags_to_apply, get_configuration,
                          configure_environment, restart_syscheckd,
                          wait_for_fim_start):
    """
    Check if syscheck can detect every event when adding, modifying and deleting a subkey/value within multiple
    monitored registry keys.

    These registry keys will be added using a new entry for every one of them:
        &lt;windows_registry&gt;testkey0&lt;/windows_registry&gt;
        ...
        &lt;windows_registry&gt;testkeyn&lt;/windows_registry&gt;
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])

    multiple_keys_and_entries_keys(n_regs,
                                   subkeys,
                                   wazuh_log_monitor,
                                   KEY,
                                   timeout=global_parameters.default_timeout)
    time.sleep(
        2
    )  # These 2 seconds are needed to avoid overlapping between keys and values
    multiple_keys_and_entries_values(n_regs,
                                     subkeys,
                                     wazuh_log_monitor,
                                     KEY,
                                     timeout=global_parameters.default_timeout)
Esempio n. 23
0
def test_ambiguous_check(dirname, checkers, tags_to_apply, get_configuration,
                         configure_environment, restart_syscheckd,
                         wait_for_initial_scan):
    """Check if syscheck detects every check set in the configuration.

    Check are read from left to right, overwriting any ambiguous configuration.

    If we set check_all='yes' and then check_inode='no' for the same directory, syscheck must send an event
    containing every possible check without inode.

    Parameters
    ----------
    dirname : string
        Name of the monitored directory
    checkers : set
        Checks to be compared to the actual event check list (the one we get from the event)
    tags_to_apply : set
        Run test if matches with a configuration identifier, skip otherwise
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])
    scheduled = get_configuration['metadata']['fim_mode'] == 'scheduled'

    regular_file_cud(dirname,
                     wazuh_log_monitor,
                     min_timeout=global_parameters.default_timeout,
                     options=checkers,
                     time_travel=scheduled)
Esempio n. 24
0
def test_checkers(key, subkey, arch, key_attrs, value_attrs, tags_to_apply, triggers_modification,
                  get_configuration, configure_environment, restart_syscheckd, wait_for_fim_start):
    """
    Test the functionality of `check_all` option is activated/desactivated alone and together with other
    `check_*` options.

    Example:
        <windows_registry check_all="yes">HKEY_SOME_KEY</windows_registry>.
    Parameters
    ----------
    key: str
        Root key (HKEY_* constants).
    subkey: str
        Path of the key.
    arch: int
        Architecture of the key.
    key_attrs: set
        Attributes for the key events.
    value_attrs: set
        Attributes for the value events.
    tags_to_apply: set
        Configuration that will be applied for every case.
    triggers_modification: boolean
        True if the given attributes trigger modification events.
    """

    check_apply_test(tags_to_apply, get_configuration['tags'])

    # Test registry keys.
    registry_key_cud(key, subkey, wazuh_log_monitor, arch=arch, min_timeout=global_parameters.default_timeout,
                     options=key_attrs, triggers_event_modified=triggers_modification, time_travel=True)

    # Test registry values.
    registry_value_cud(key, subkey, wazuh_log_monitor, min_timeout=global_parameters.default_timeout,
                       options=value_attrs, triggers_event_modified=triggers_modification, time_travel=True)
def test_symlink_within_dir(tags_to_apply, checkers, get_configuration,
                            configure_environment, restart_syscheckd,
                            wait_for_fim_start):
    """Monitor a link within a monitored directory.

    The link configuration should prevail over the monitored directory (checks, follow_symbolic_link, etc...).

    Args:
        tags_to_apply (set): Run test if matches with a configuration identifier, skip otherwise.
        checkers (dict): Check options to be used.
        get_configuration (fixture): Gets the current configuration of the test.
        configure_environment (fixture): Configure the environment for the execution of the test.
        restart_syscheckd (fixture): Restarts syscheck.
        wait_for_fim_start (fixture): Waits until the first FIM scan is completed.

    Raises:
        TimeoutError: If a expected event wasn't triggered.
        AttributeError: If a unexpected event was captured.
        ValueError: If the event's type and path are not the expected.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])
    scheduled = get_configuration['metadata']['fim_mode'] == 'scheduled'

    # Alerts from the pointed directory should have all checks except size
    fim.regular_file_cud(testdir_target,
                         wazuh_log_monitor,
                         min_timeout=global_parameters.default_timeout,
                         options=checkers,
                         time_travel=scheduled)
    # Alerts from the main directory should have all checks
    fim.regular_file_cud(testdir,
                         wazuh_log_monitor,
                         min_timeout=global_parameters.default_timeout,
                         time_travel=scheduled)
Esempio n. 26
0
def test_readded_rules_on_restart(tags_to_apply, get_configuration,
                                  configure_environment, restart_syscheckd):
    """Check if the rules are added to Audit when it restarts."""
    logger.info('Applying the test configuration')
    check_apply_test(tags_to_apply, get_configuration['tags'])

    # Restart Audit
    restart_command = ["service", "auditd", "restart"]
    p = subprocess.Popen(restart_command)
    p.wait()

    wazuh_log_monitor.start(
        timeout=10,
        callback=callback_audit_connection,
        error_message=
        f'Did not receive expected "connect" event with the command '
        f'{" ".join(restart_command)}')

    events = wazuh_log_monitor.start(
        timeout=30,
        callback=callback_audit_reloaded_rule,
        accum_results=3,
        error_message=f'Did not receive expected "load" event with the command '
        f'{" ".join(restart_command)}').result()

    assert testdir1 in events, f'{testdir1} not in {events}'
    assert testdir2 in events, f'{testdir2} not in {events}'
    assert testdir3 in events, f'{testdir3} not in {events}'
Esempio n. 27
0
def test_duplicate_entries(get_configuration, configure_environment,
                           restart_syscheckd, wait_for_initial_scan):
    """Check if syscheckd ignores duplicate entries.
       For instance:
           - The second entry should prevail over the first one.
            <directories realtime="yes">/home/user</directories> (IGNORED)
            <directories whodata="yes">/home/user</directories>
        OR
           - Just generate one event.
            <directories realtime="yes">/home/user,/home/user</directories>
    """
    logger.info('Applying the test configuration')
    check_apply_test({'ossec_conf_duplicate_simple'},
                     get_configuration['tags'])
    file = 'hello'
    mode2 = get_configuration['metadata']['fim_mode2']

    scheduled = mode2 == 'scheduled'
    mode2 = "real-time" if mode2 == "realtime" else mode2

    logger.info(f'Adding file {os.path.join(testdir1, file)}, content: " "')
    create_file(REGULAR, testdir1, file, content=' ')

    logger.info(f'Time travel: {scheduled}')
    check_time_travel(scheduled)
    logger.info('Checking the event...')
    event1 = wazuh_log_monitor.start(
        timeout=global_parameters.default_timeout,
        callback=callback_detect_event,
        error_message=f'Did not receive expected event for file '
        f'{os.path.join(testdir1, file)}').result()

    # Check for a second event
    event2 = check_event(previous_mode=mode2, previous_event=event1, file=file)
    assert event2 is None, "Multiple events created"
Esempio n. 28
0
def test_move_rules_realtime(tags_to_apply, get_configuration,
                             configure_environment, restart_syscheckd):
    """Check if the rules are changed to realtime when Audit stops."""
    logger.info('Applying the test configuration')
    check_apply_test(tags_to_apply, get_configuration['tags'])

    # Stop Audit
    stop_command = ["service", "auditd", "stop"]
    p = subprocess.Popen(stop_command)
    p.wait()

    events = wazuh_log_monitor.start(
        timeout=30,
        callback=callback_realtime_added_directory,
        accum_results=3,
        error_message=
        f'Did not receive expected "directory added" for monitoring '
        f'with the command {" ".join(stop_command)}').result()

    assert testdir1 in events, f'{testdir1} not detected in scan'
    assert testdir2 in events, f'{testdir2} not detected in scan'
    assert testdir3 in events, f'{testdir3} not detected in scan'

    # Start Audit
    p = subprocess.Popen(["service", "auditd", "start"])
    p.wait()
Esempio n. 29
0
def test_ambiguous_complex(tags_to_apply, get_configuration,
                           configure_environment, restart_syscheckd,
                           wait_for_fim_start):
    """Automatic test for each configuration given in the yaml.

    The main purpose of this test is to check that syscheck will apply different configurations between subdirectories
    properly. Example:

    <directories realtime='yes' report_changes='yes' check_all='yes' check_owner='no'> /testdir </directories>
    <directories realtime='yes' report_changes='no' check_sum='no' check_owner='yes'> /testdir/subdir </directories>
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])

    # Standard params for each test
    file_list = ['example.csv']
    min_timeout = global_parameters.default_timeout
    scheduled = get_configuration['metadata']['fim_mode'] == 'scheduled'

    for section in get_configuration['sections']:
        conf_list, check_list = get_dir_and_attributes(section['elements'])
        param = (file_list, min_timeout, scheduled)
        # For every directory, apply each test depending of its attributes.
        # We assume we've set restrict attribute so it should not expect events
        # For further functionality with restrict, run ../test_restrict tests
        for directory, checkers in zip(conf_list, check_list):
            for path, attributes in directory.items():
                trigger = False if 'restrict' in attributes else True
                apply_test(path, attributes, trigger, checkers, param)
def test_update_interval(get_configuration, configure_environment,
                         restart_modulesd):
    """
    Check if the provider database update is triggered after the set interval time has passed
    """
    check_apply_test({'test_providers_update_interval'},
                     get_configuration['tags'])

    provider = get_configuration['metadata']['provider_name']
    interval_update_time = get_configuration['metadata']['interval']
    seconds_to_travel = time_to_seconds(interval_update_time) + 5

    # Check that the update has not started prematurely
    with pytest.raises(TimeoutError):
        wazuh_log_monitor.start(timeout=8,
                                callback=callback_provider_database_updating)
        raise AttributeError(f'Unexpected event {provider} database updating')

    # Travels the time set in the update interval parameter
    check_time_travel(time_travel=True,
                      interval=timedelta(seconds=seconds_to_travel))

    # Check that the feed is downloaded after the set update interval
    # (10s for vuln thread refresh + 5s to wait callback)
    wazuh_log_monitor.start(
        timeout=50,
        callback=callback_provider_database_updating,
        error_message=
        f"Could not find the provider {provider} updating feed log after \
                                            the interval update")