Ejemplo n.º 1
0
def test_no_diff_subdirectory(folder, filename, content, hidden_content,
                              tags_to_apply, get_configuration,
                              configure_environment, restart_syscheckd,
                              wait_for_fim_start):
    """
    Check files are ignored in the subdirectory according to configuration

    When using the nodiff option for a file in syscheck configuration, every time we get an event from this file,
    we won't be able to see its content. We'll see 'Diff truncated because nodiff option' instead.

    Parameters
    ----------
    folder : str
        Directory where the file is being created.
    filename : str
        Name of the file to be created.
    content : str, bytes
        Content to fill the new file.
    hidden_content : bool
        True if content must be truncated,, False otherwise.
    tags_to_apply : set
        Run test if matches with a configuration identifier, skip otherwise.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])

    files = {filename: content}

    def report_changes_validator(event):
        """Validate content_changes attribute exists in the event"""
        for file in files:
            diff_file = os.path.join(WAZUH_PATH, 'queue', 'diff', 'local')

            if sys.platform == 'win32':
                diff_file = os.path.join(diff_file, 'c')

            striped = folder.strip(
                os.sep) if sys.platform == 'darwin' else folder.strip(PREFIX)
            diff_file = os.path.join(diff_file, striped, file)

            assert os.path.exists(diff_file), f'{diff_file} does not exist'
            assert event['data'].get(
                'content_changes') is not None, f'content_changes is empty'

    def no_diff_validator(event):
        """Validate content_changes value is truncated if the file is set to no_diff"""
        if hidden_content:
            assert '<Diff truncated because nodiff option>' in event['data'].get('content_changes'), \
                f'content_changes is not truncated'
        else:
            assert '<Diff truncated because nodiff option>' not in event['data'].get('content_changes'), \
                f'content_changes is truncated'

    regular_file_cud(
        folder,
        wazuh_log_monitor,
        file_list=files,
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled',
        min_timeout=global_parameters.default_timeout,
        triggers_event=True,
        validators_after_update=[report_changes_validator, no_diff_validator])
Ejemplo n.º 2
0
def test_disabled(get_configuration, configure_environment, restart_syscheckd):
    """Check if syscheckd sends events when disabled="yes".

    Parameters
    ----------
    folder : str
        Path where files will be created.
    """
    # Expect a timeout when checking for syscheckd initial scan
    with pytest.raises(TimeoutError):
        event = wazuh_log_monitor.start(timeout=10,
                                        callback=callback_detect_end_scan)
        raise AttributeError(f'Unexpected event {event}')

    # Use `regular_file_cud` and don't expect any event
    scheduled = get_configuration['metadata']['fim_mode'] == 'scheduled'
    if scheduled:
        with pytest.raises(TimeoutError):
            wazuh_log_monitor.start(timeout=10,
                                    callback=callback_detect_end_scan)
    else:
        regular_file_cud(testdir,
                         wazuh_log_monitor,
                         time_travel=scheduled,
                         min_timeout=global_parameters.default_timeout,
                         triggers_event=False)
Ejemplo n.º 3
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')
Ejemplo n.º 4
0
def check_report_changes(directory, trigger, check_list, file_list, timeout,
                         scheduled):
    """Standard report_changes test"""
    def report_changes_validator(event):
        """Validate content_changes attribute exists in the event"""
        for file in file_list:
            diff_file = os.path.join(WAZUH_PATH, 'queue', 'diff', 'local')
            if sys.platform == 'win32':
                diff_file = os.path.join(diff_file, 'c')
                diff_file = os.path.join(diff_file, directory.strip('C:\\'),
                                         file)
            else:
                diff_file = os.path.join(diff_file, directory.strip('/'), file)
            assert os.path.exists(diff_file), f'{diff_file} does not exist'
            assert event['data'].get(
                'content_changes') is not None, f'content_changes is empty'

    regular_file_cud(directory,
                     wazuh_log_monitor,
                     file_list=file_list,
                     time_travel=scheduled,
                     min_timeout=timeout,
                     triggers_event=trigger,
                     options=get_checkers(check_list),
                     validators_after_update=[report_changes_validator])
Ejemplo n.º 5
0
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])
Ejemplo n.º 6
0
def test_tags(folder, name, content, get_configuration, configure_environment,
              restart_syscheckd, wait_for_initial_scan):
    """Checks the tags functionality by applying some tags an ensuring the events raised for the monitored directory has
    the expected tags.

    This test is intended to be used with valid configurations files. Each execution of this test will configure the
    environment properly, restart the service and wait for the initial scan.

    :param folder string Directory where the file is being created
    :param name string Name of the file to be created
    :param content string, bytes Content to fill the new file
    """
    defined_tags = get_configuration['metadata']['fim_tags']

    def tag_validator(event):
        assert defined_tags == event['data'][
            'tags'], f'defined_tags are not equal'

    files = {name: content}

    regular_file_cud(
        folder,
        wazuh_log_monitor,
        file_list=files,
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled',
        min_timeout=DEFAULT_TIMEOUT,
        validators_after_cud=[tag_validator])
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
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')
Ejemplo n.º 9
0
def test_check_all_single(path, checkers, get_configuration,
                          configure_environment, restart_syscheckd,
                          wait_for_initial_scan):
    """
    Test the functionality of `check_all` option when used in conjunction with another check on the same directory,
    having "check_all" to "yes" and the other check to "no".

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

    Parameters
    ----------
    path : str
        Directory where the file is being created and monitored.
    checkers : dict
        Check options to be used.
    """
    check_apply_test({'test_check_all_single'}, get_configuration['tags'])
    regular_file_cud(
        path,
        wazuh_log_monitor,
        min_timeout=15,
        options=checkers,
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled')
Ejemplo n.º 10
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)
Ejemplo n.º 11
0
def test_checksums_checkall(path, checkers, get_configuration,
                            configure_environment, restart_syscheckd,
                            wait_for_fim_start):
    """
    Test the behavior of check_all="yes" when using it with one or more check_sum options (checksum, sha1sum,
    sha256sum and md5sum) set to "no".

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

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

    regular_file_cud(
        path,
        wazuh_log_monitor,
        min_timeout=global_parameters.default_timeout,
        options=checkers,
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled')
Ejemplo n.º 12
0
def test_new_directory(tags_to_apply, get_configuration, configure_environment, restart_syscheckd,
                       wait_for_initial_scan):
    """
    Check that a new monitored directory generates events after the next scheduled scan.

    This test performs the following steps:
    - Monitor a directory that does not exist.
    - Create the directory with files inside. Check that this does not produce events in ossec.log.
    - Move time forward to the next scheduled scan.
    - Check that now creating files within the directory do generate events.

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

    if sys.platform != 'win32':
        # Create the monitored directory with files and check that events are not raised
        regular_file_cud(directory_str, wazuh_log_monitor, file_list=['file1', 'file2', 'file3'],
                         min_timeout=global_parameters.default_timeout, triggers_event=False)

        # Travel to the future to start next scheduled scan
        check_time_travel(True)
        detect_initial_scan(wazuh_log_monitor)
    else:
        os.makedirs(directory_str, exist_ok=True, mode=0o777)
        time.sleep(1)

    # Assert that events of new CUD actions are raised after next scheduled scan
    regular_file_cud(directory_str, wazuh_log_monitor, file_list=['file4', 'file5', 'file6'],
                     min_timeout=global_parameters.default_timeout, triggers_event=True)
Ejemplo n.º 13
0
def test_checksums(path, checkers, get_configuration, configure_environment,
                   restart_syscheckd, wait_for_fim_start):
    """
    Test the checksum options (checksum, sha1sum, sha256sum and md5sum)
    behavior when is used alone or in conjunction.
    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_sum: "yes" check_md5sum: "no"
        ...

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

    regular_file_cud(
        path,
        wazuh_log_monitor,
        min_timeout=global_parameters.default_timeout,
        options=checkers,
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled')
Ejemplo n.º 14
0
def test_tags(folder, name, content, get_configuration, configure_environment,
              restart_syscheckd, wait_for_fim_start):
    """
    Check the tags functionality by applying some tags an ensuring the events raised for the monitored directory has
    the expected tags.

    Parameters
    ----------
    folder : str
        Directory where the file is being created.
    name : str
        Name of the file to be created.
    content : str, bytes
        Content to fill the new file.
    """
    defined_tags = get_configuration['metadata']['fim_tags']

    def tag_validator(event):
        assert defined_tags == event['data'][
            'tags'], f'defined_tags are not equal'

    files = {name: content}

    regular_file_cud(
        folder,
        wazuh_log_monitor,
        file_list=files,
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled',
        min_timeout=global_parameters.default_timeout,
        validators_after_cud=[tag_validator])
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
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)
Ejemplo n.º 17
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"
        ...

    This test is intended to be used with valid configurations files. Each execution of this test will configure the
    environment properly, restart the service and wait for the initial scan.

    :param path: Directory where the file is being created and monitored
    :param checkers: Dict with all the 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')
Ejemplo n.º 18
0
def check_default(directory, trigger, check_list, file_list, timeout,
                  scheduled):
    """Standard default conf test"""
    regular_file_cud(directory,
                     wazuh_log_monitor,
                     file_list=file_list,
                     time_travel=scheduled,
                     options=get_checkers(check_list),
                     min_timeout=timeout,
                     triggers_event=trigger)
def test_reports_file_and_nodiff(folder, checkers, tags_to_apply,
                                 get_configuration, configure_environment,
                                 restart_syscheckd, wait_for_initial_scan):
    """
    Check if report_changes events and diff truncated files are correct

    The report_changes attribute adds a new event property to the 'modified' sent event: 'content_changes'
    It has information about what changed from the previous content. To do so, it duplicates the file in the diff
    directory. We call this duplicated file 'diff_file'.

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

    file_list = ['regular_file']
    is_truncated = folder == testdir_nodiff

    def report_changes_validator(event):
        """Validate content_changes attribute exists in the event"""
        for file in file_list:
            diff_file = os.path.join(WAZUH_PATH, 'queue', 'diff', 'local')
            if sys.platform == 'win32':
                diff_file = os.path.join(diff_file, 'c')
                diff_file = os.path.join(
                    diff_file,
                    re.match(r'^[a-zA-Z]:(\\){1,2}(\w+)(\\){0,2}$',
                             folder).group(2), file)
            else:
                diff_file = os.path.join(diff_file, folder.strip('/'), file)
            assert os.path.exists(diff_file), f'{diff_file} does not exist'
            assert event['data'].get(
                'content_changes') is not None, f'content_changes is empty'

    def no_diff_validator(event):
        """Validate content_changes value is truncated if the file is set to no_diff"""
        if is_truncated:
            assert '<Diff truncated because nodiff option>' in event['data'].get('content_changes'), \
                f'content_changes is not truncated'
        else:
            assert '<Diff truncated because nodiff option>' not in event['data'].get('content_changes'), \
                f'content_changes is truncated'

    regular_file_cud(
        folder,
        wazuh_log_monitor,
        file_list=file_list,
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled',
        min_timeout=global_parameters.default_timeout,
        triggers_event=True,
        validators_after_update=[report_changes_validator, no_diff_validator])
Ejemplo n.º 20
0
def test_tag_directories(directory, get_configuration, put_env_variables,
                         configure_environment, restart_syscheckd,
                         wait_for_fim_start):
    """
    Test alerts are generated when monitor environment variables
    """
    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')
Ejemplo n.º 21
0
def check_tags(directory, trigger, check_list, file_list, timeout, scheduled):
    """Standard tags attribute test"""
    def tag_validator(event):
        """Validate tag attribute exists in the event"""
        assert tag == event['data']['tags'], f'defined_tags are not equal'

    regular_file_cud(directory,
                     wazuh_log_monitor,
                     file_list=file_list,
                     time_travel=scheduled,
                     options=get_checkers(check_list),
                     min_timeout=timeout,
                     triggers_event=trigger,
                     validators_after_cud=[tag_validator])
Ejemplo n.º 22
0
def test_reports_file_and_nodiff(folder, checkers, tags_to_apply,
                                 get_configuration, configure_environment,
                                 restart_syscheckd, wait_for_initial_scan):
    """ Check if report_changes events and diff truncated files are correct

    The report_changes attribute adds a new event property to the 'modified' sent event: 'content_changes'
    It has information about what changed from the previous content. To do so, it duplicates the file in the diff
    directory. We call this duplicated file 'diff_file'.

    :param folder: Directory where the files will be created
    :param checkers: Dict of syscheck checkers (check_all)

    * This test is intended to be used with valid configurations files. Each execution of this test will configure
    the environment properly, restart the service and wait for the initial scan.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])

    file_list = ['regular_file']
    is_truncated = folder == testdir_nodiff

    def report_changes_validator(event):
        """ Validate content_changes attribute exists in the event """
        for file in file_list:
            diff_file = os.path.join(WAZUH_PATH, 'queue', 'diff', 'local')
            if sys.platform == 'win32':
                diff_file = os.path.join(diff_file, 'c')
                diff_file = os.path.join(diff_file, folder.strip('C:\\'), file)
            else:
                diff_file = os.path.join(diff_file, folder.strip('/'), file)
            assert os.path.exists(diff_file), f'{diff_file} does not exist'
            assert event['data'].get(
                'content_changes') is not None, f'content_changes is empty'

    def no_diff_validator(event):
        """ Validate content_changes value is truncated if the file is set to no_diff """
        if is_truncated:
            assert '<Diff truncated because nodiff option>' in event['data'].get('content_changes'), \
                f'content_changes is not truncated'
        else:
            assert '<Diff truncated because nodiff option>' not in event['data'].get('content_changes'), \
                f'content_changes is truncated'

    regular_file_cud(
        folder,
        wazuh_log_monitor,
        file_list=file_list,
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled',
        min_timeout=DEFAULT_TIMEOUT,
        triggers_event=True,
        validators_after_update=[report_changes_validator, no_diff_validator])
def test_readded_watches(removed, renamed, get_configuration,
                         configure_environment, restart_syscheckd_each_time):
    """
    Check if Wazuh delete watches when directory is removed or renamed, and add watches when directory is readded.

    Parameters
    ----------
    removed : Boolean
        Tells if the directory must be removed
    renamed : Boolean
        Tells if the directory must be renamed
    """

    # Check Wazuh add directory to realtime mode
    if sys.platform == 'win32':
        directory = wazuh_log_monitor.start(
            timeout=40,
            callback=callback_realtime_added_directory,
            error_message='Did not receive expected '
            '"Directory added for real time monitoring: ..." event').result()
        assert (directory == testdir), 'Unexpected path'

    # Remove/Rename folder and check Wazuh delete waches
    if removed:
        sh.rmtree(testdir, ignore_errors=True)
    elif renamed:
        os.rename(testdir, os.path.join(PREFIX, 'changed_name'))

    directory = wazuh_log_monitor.start(
        timeout=global_parameters.default_timeout,
        callback=callback_delete_watch,
        error_message='Did not receive expected "Delete watch ..." event'
    ).result()
    assert (directory == testdir), 'Unexpected path'

    # Create directories again and check Wazuh add watches
    os.mkdir(testdir)

    num_watches = wazuh_log_monitor.start(
        timeout=40,
        callback=callback_num_inotify_watches,
        error_message='Did not receive expected '
        '"Folders monitored with real-time engine: ..." event').result()
    assert (num_watches
            and num_watches != EXPECTED_WATCHES), 'Watches not added'
    regular_file_cud(testdir,
                     wazuh_log_monitor,
                     min_timeout=global_parameters.default_timeout,
                     triggers_event=True)
Ejemplo n.º 24
0
def test_no_diff_subdirectory(folder, filename, content, hidden_content,
                              tags_to_apply, get_configuration,
                              configure_environment, restart_syscheckd,
                              wait_for_initial_scan):
    """ Checks files are ignored in the subdirectory according to configuration

    When using the nodiff option for a file in syscheck configuration, every time we get an event from this file,
    we won't be able to see its content. We'll see 'Diff truncated because nodiff option' instead.

    :param folder: Directory where the file is being created
    :param filename: Name of the file to be created
    :param content: Content to fill the new file
    :param hidden_content: True if content must be truncated,, False otherwise
    :param tags_to_apply: Run test if matches with a configuration identifier, skip otherwise

    * This test is intended to be used with valid nodiff configurations. Each execution of this test will configure
    the environment properly, restart the service and wait for the initial scan.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])

    files = {filename: content}

    def report_changes_validator(event):
        """ Validate content_changes attribute exists in the event """
        for file in files:
            diff_file = os.path.join(WAZUH_PATH, 'queue', 'diff', 'local',
                                     folder.strip(PREFIX), file)
            assert os.path.exists(diff_file), f'{diff_file} does not exist'
            assert event['data'].get(
                'content_changes') is not None, f'content_changes is empty'

    def no_diff_validator(event):
        """ Validate content_changes value is truncated if the file is set to no_diff """
        if hidden_content:
            assert '<Diff truncated because nodiff option>' in event['data'].get('content_changes'), \
                f'content_changes is not truncated'
        else:
            assert '<Diff truncated because nodiff option>' not in event['data'].get('content_changes'), \
                f'content_changes is truncated'

    regular_file_cud(
        folder,
        wazuh_log_monitor,
        file_list=files,
        time_travel=get_configuration['metadata']['fim_mode'] == 'scheduled',
        min_timeout=DEFAULT_TIMEOUT,
        triggers_event=True,
        validators_after_update=[report_changes_validator, no_diff_validator])
Ejemplo n.º 25
0
def test_benchmark_regular_files(files, folder, tags_to_apply, get_configuration,
                                 configure_environment, restart_syscheckd,
                                 wait_for_initial_scan):
    """ Checks syscheckd detects a certain volume of file changes (add, modify, delete)

        :param files: List of regular files to be created
        :param folder: Monitored directory where files will be created

        * This test is intended to be used with valid configurations files. Each execution of this test will configure
          the environment properly, restart the service and wait for the initial scan.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])
    min_timeout = 30

    regular_file_cud(folder, wazuh_log_monitor, file_list=files,
                     min_timeout=min_timeout, triggers_event=True)
Ejemplo n.º 26
0
def _test_recursion_cud(ini,
                        fin,
                        path,
                        recursion_subdir,
                        scheduled,
                        min_timeout,
                        triggers_event,
                        validators_after_cud=None):
    """Apply `regular_file_cud` on different recursion levels.

    Iterate from `ini` recursion level to `fin` recursion level, creating the
    corresponding subdirectory and applying the `regular_file_cud` function on it.

    Parameters
    ----------
    ini : int
        Initial level of recursion.
    fin : int
        Final level of recursion.
    path : string
        Path over which subdirectories will be created.
    recursion_subdir : string
        Name for subdirectories.
    scheduled : bool
        Determine if there will be time travels or not
    min_timeout : int
        Minimum timeout
    triggers_event : bool
        determine if the event should be raised or not.
    validators_after_cud : list, optional
        functions that validate an event triggered when a new file is created, modified
    or deleted. Each function must accept a param to receive the event to be validated.

    Returns
    -------
    path : string
        Full path after adding all the subdirectories.
    """
    for n in range(ini, fin):
        path = os.path.join(path, recursion_subdir + str(n + 1))
        regular_file_cud(path,
                         wazuh_log_monitor,
                         time_travel=scheduled,
                         min_timeout=min_timeout,
                         triggers_event=triggers_event,
                         validators_after_cud=validators_after_cud)
    return path
Ejemplo n.º 27
0
def test_skip_dev(modify_inode_mock, directory, tags_to_apply, get_configuration, configure_environment,
                  restart_syscheckd,
                  wait_for_fim_start):
    """Check if syscheckd skips /dev when setting 'skip_dev="yes"'.

    /proc, /sys, /dev and nfs directories are special directories. Unless it is specified with skip_*='no', syscheck
    will skip these directories. If not, they will be monitored like a normal directory.

    Parameters
    ----------
    directory : str
        Directory that will be monitored.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])
    trigger = get_configuration['metadata']['skip'] == 'no'

    regular_file_cud(directory, wazuh_log_monitor, time_travel=True, min_timeout=3, triggers_event=trigger)
Ejemplo n.º 28
0
def test_new_directory(tags_to_apply, get_configuration, configure_environment,
                       restart_syscheckd):
    """
    Check that a new monitored directory generates events after the next scheduled scan.

    This test performs the following steps:
    - Monitor a directory that does not exist.
    - Create the directory with files inside. Check that this does not produce events in ossec.log.
    - Move time forward to the next scheduled scan.
    - Check that now creating files within the directory do generate events.

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

    if sys.platform != 'win32':
        detect_initial_scan(wazuh_log_monitor)

        # Create the monitored directory with files and check that events are not raised
        regular_file_cud(directory_str,
                         wazuh_log_monitor,
                         file_list=['file1', 'file2', 'file3'],
                         min_timeout=global_parameters.default_timeout,
                         triggers_event=False)

        detect_initial_scan(wazuh_log_monitor)
    else:
        detect_initial_scan(wazuh_log_monitor)

        # Wait for syscheck to realize the directories don't exist
        wazuh_log_monitor.start(
            timeout=10,
            callback=callback_non_existing_monitored_dir,
            error_message='Monitoring discarded message not found')
        os.makedirs(directory_str, exist_ok=True, mode=0o777)
        time.sleep(windows_audit_interval + 0.5)

    # Assert that events of new CUD actions are raised after next scheduled scan
    regular_file_cud(directory_str,
                     wazuh_log_monitor,
                     file_list=['file4', 'file5', 'file6'],
                     min_timeout=40,
                     triggers_event=True)
Ejemplo n.º 29
0
def test_benchmark_regular_files(files, folder, tags_to_apply, get_configuration,
                                 configure_environment, restart_syscheckd,
                                 wait_for_fim_start):
    """
    Check syscheckd detects a certain volume of file changes (add, modify, delete)

    Parameters
    ----------
    files: list
        List of regular files to be created.
    folder : str
        Monitored directory where files will be created.
    """
    check_apply_test(tags_to_apply, get_configuration['tags'])
    min_timeout = 30

    regular_file_cud(folder, wazuh_log_monitor, file_list=files,
                     min_timeout=min_timeout, triggers_event=True)
Ejemplo n.º 30
0
def test_create_after_delete(tags_to_apply, get_configuration,
                             configure_environment, restart_syscheckd,
                             wait_for_initial_scan):
    """
    Check that a monitored directory keeps reporting events after deleting and creating it again. It tests
    that under Windows systems the directory watcher is refreshed after directory re-creation 1 second after.

    This test performs the following steps:
    - Monitor a directory that exist.
    - Create some files inside. Check that it does produce events in ossec.log.
    - Delete the directory and wait for a second.
    - Create the directory again and wait for a second.
    - Check that creating files within the directory do generate events again.

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

    # Create the monitored directory with files and check that events are not raised
    regular_file_cud(directory_str,
                     wazuh_log_monitor,
                     file_list=['file1', 'file2', 'file3'],
                     min_timeout=global_parameters.default_timeout,
                     triggers_event=True)

    # Delete the directory
    os.rename(directory_str, f'{directory_str}_delete')
    shutil.rmtree(f'{directory_str}_delete', ignore_errors=True)
    time.sleep(5)

    # Re-create the directory
    os.makedirs(directory_str, exist_ok=True, mode=0o777)
    time.sleep(5)

    # Assert that events of new CUD actions are raised after next scheduled scan
    regular_file_cud(directory_str,
                     wazuh_log_monitor,
                     file_list=['file4', 'file5', 'file6'],
                     min_timeout=global_parameters.default_timeout,
                     triggers_event=True)