Ejemplo n.º 1
0
def pytest_runtest_setup(item):
    # Find if platform applies
    supported_platforms = PLATFORMS.intersection(mark.name for mark in item.iter_markers())
    plat = sys.platform

    if supported_platforms and plat not in supported_platforms:
        pytest.skip("Cannot run on platform {}".format(plat))

    host_type = 'agent' if 'agent' in get_service() else 'server'
    supported_types = HOST_TYPES.intersection(mark.name for mark in item.iter_markers())
    if supported_types and host_type not in supported_types:
        pytest.skip("Cannot run on wazuh {}".format(host_type))
    # Consider only first mark
    levels = [mark.kwargs['level'] for mark in item.iter_markers(name="tier")]
    if levels and len(levels) > 0:
        tiers = item.config.getoption("--tier")
        if tiers is not None and levels[0] not in tiers:
            pytest.skip(f"test requires tier level {levels[0]}")
        elif item.config.getoption("--tier-minimum") > levels[0]:
            pytest.skip(f"test requires a minimum tier level {levels[0]}")
        elif item.config.getoption("--tier-maximum") < levels[0]:
            pytest.skip(f"test requires a maximum tier level {levels[0]}")
Ejemplo n.º 2
0
def check_daemon_status(daemon=None, running=True, timeout=10, extra_sockets=None):
    """Check Wazuh daemon status.

    Args:
        daemon (str, optional):  Wazuh daemon to check. Default `None`
        running (bool, optional): True if the daemon is expected to be running False if it is expected to be stopped.
            Default `True`
        timeout (int, optional): Timeout value for the check. Default `10`
        extra_sockets (list, optional): Additional sockets to check. They may not be present in default configuration

    Raises:
        TimeoutError: If the daemon status is wrong after timeout seconds.
    """
    if extra_sockets is None:
        extra_sockets = []
    for _ in range(3):
        # Check specified daemon/s status
        daemon_status = subprocess.run(['service', get_service(), 'status'], stdout=subprocess.PIPE).stdout.decode()
        if f"{daemon if daemon is not None else ''} {'not' if running else 'is'} running" not in daemon_status:
            # Construct set of socket paths to check
            if daemon is None:
                socket_set = {path for array in WAZUH_SOCKETS.values() for path in array}
            else:
                socket_set = {path for path in WAZUH_SOCKETS[daemon]}
            # We remove optional sockets and add extra sockets to the set to check
            socket_set.difference_update(WAZUH_OPTIONAL_SOCKETS)
            socket_set.update(extra_sockets)
            # Check specified socket/s status
            for socket in socket_set:
                if os.path.exists(socket) is not running:
                    break
            else:
                # Finish main for loop if both daemon and socket checks are ok
                break

        time.sleep(timeout / 3)
    else:
        raise TimeoutError(f"{'wazuh-service' if daemon is None else daemon} "
                           f"{'is not' if running else 'is'} running")
test_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                              'data')
configurations_path = os.path.join(test_data_path,
                                   'wazuh_basic_configuration.yaml')

if sys.platform == 'win32':
    location = r'C:\testing\files*'
    wazuh_configuration = 'ossec.conf'
    prefix = AGENT_DETECTOR_PREFIX

else:
    prefix = LOG_COLLECTOR_DETECTOR_PREFIX
    location = '/tmp/testing/files*'
    wazuh_configuration = 'etc/ossec.conf'

wazuh_component = get_service()

parameters = [{
    'LOCATION': f'{location}',
    'LOG_FORMAT': 'syslog',
    'IGNORE_BINARIES': 'yes'
}, {
    'LOCATION': f'{location}',
    'LOG_FORMAT': 'syslog',
    'IGNORE_BINARIES': 'no'
}, {
    'LOCATION': f'{location}',
    'LOG_FORMAT': 'syslog',
    'IGNORE_BINARIES': 'yesTesting'
}, {
    'LOCATION': f'{location}',
Ejemplo n.º 4
0
def control_service(action, daemon=None, debug_mode=False):
    """Perform the stop, start and restart operation with Wazuh.

    It takes care of the current OS to interact with the service and the type of installation (agent or manager).

    Args:
        action ({'stop', 'start', 'restart'}): Action to be done with the service/daemon.
        daemon (str, optional): Name of the daemon to be controlled. None for the whole Wazuh service. Default `None`
        debug_mode (bool, optional) : Run the specified daemon in debug mode. Default `False`
    Raises:
        ValueError: If `action` is not contained in {'start', 'stop', 'restart'}.
        ValueError: If the result is not equal to 0.
    """
    valid_actions = ('start', 'stop', 'restart')
    if action not in valid_actions:
        raise ValueError(f'action {action} is not one of {valid_actions}')

    if sys.platform == 'win32':
        if action == 'restart':
            control_service('stop')
            control_service('start')
            result = 0
        else:
            command = subprocess.run(["net", action, "WazuhSvc"], stderr=subprocess.PIPE)
            result = command.returncode
            if command.returncode != 0:
                if action == 'stop' and 'The Wazuh service is not started.' in command.stderr.decode():
                    result = 0
                print(command.stderr.decode())
    else:  # Default Unix
        if daemon is None:
            if sys.platform == 'darwin' or sys.platform == 'sunos5':
                result = subprocess.run([f'{WAZUH_PATH}/bin/wazuh-control', action]).returncode
            else:
                result = subprocess.run(['service', get_service(), action]).returncode
            action == 'stop' and delete_sockets()
        else:
            if action == 'restart':
                control_service('stop', daemon=daemon)
                control_service('start', daemon=daemon)
            elif action == 'stop':
                processes = []

                for proc in psutil.process_iter():
                    if daemon in proc.name():
                        try:
                            processes.append(proc)
                        except psutil.NoSuchProcess:
                            pass
                try:
                    for proc in processes:
                        proc.terminate()

                    _, alive = psutil.wait_procs(processes, timeout=5)

                    for proc in alive:
                        proc.kill()
                except psutil.NoSuchProcess:
                    pass

                delete_sockets(WAZUH_SOCKETS[daemon])
            else:
                daemon_path = os.path.join(WAZUH_PATH, 'bin')
                subprocess.check_call([f'{daemon_path}/{daemon}', '' if not debug_mode else '-dd'])
            result = 0

    if result != 0:
        raise ValueError(f"Error when executing {action} in daemon {daemon}. Exit status: {result}")