Example #1
0
def test_OssecSocket_receive(mock_recv, mock_unpack, mock_conn):
    """Tests OssecSocket.receive function works"""

    queue = OssecSocket('test_path')

    response = queue.receive()

    assert isinstance(response, MagicMock)
    mock_conn.assert_called_once_with('test_path')
Example #2
0
def test_OssecSocket_close(mock_close, mock_conn):
    """Tests OssecSocket.close function works"""

    queue = OssecSocket('test_path')

    queue.close()

    mock_conn.assert_called_once_with('test_path')
    mock_close.assert_called_once_with()
Example #3
0
def test_OssecSocket_send(mock_send, mock_conn):
    """Tests OssecSocket.send function works"""

    queue = OssecSocket('test_path')

    response = queue.send(b"\x00\x01")

    assert isinstance(response, MagicMock)
    mock_conn.assert_called_once_with('test_path')
Example #4
0
def test_OssecSocket_receive_ko(mock_recv, mock_conn):
    """Tests OssecSocket.receive function exception works"""

    queue = OssecSocket('test_path')

    with pytest.raises(WazuhException, match=".* 1014 .*"):
        queue.receive()

    mock_conn.assert_called_once_with('test_path')
Example #5
0
def get_daemons_stats_from_socket(agent_id, daemon):
    """Get a daemon stats from an agent or manager.

    Parameters
    ----------
    agent_id : string
        Id of the agent to get stats from.
    daemon : string
        Name of the service to get stats from.

    Returns
    -------
    Dict
        Object with daemon's stats.
    """
    if not agent_id or not daemon:
        raise WazuhError(1307)

    sockets_path = os.path.join(common.ossec_path, "queue", "sockets")

    if str(agent_id).zfill(3) == '000':
        # Some daemons do not exist in agent 000
        if daemon in {'agent'}:
            raise WazuhError(1310)
        dest_socket = os.path.join(sockets_path, daemon)
        command = "getstate"
    else:
        dest_socket = os.path.join(sockets_path, "request")
        command = f"{str(agent_id).zfill(3)} {daemon} getstate"

    # Socket connection
    try:
        s = OssecSocket(dest_socket)
    except Exception:
        raise WazuhInternalError(1121)

    # Send message
    s.send(command.encode())

    # Receive response
    try:
        rec_msg = s.receive().decode()
    except ValueError:
        raise WazuhInternalError(1118, extra_message="Data could not be received")

    s.close()

    # Format response
    try:
        return json.loads(rec_msg)['data']
    except Exception:
        rec_msg = rec_msg.split(" ", 1)[1]
        raise WazuhError(1117, extra_message=rec_msg)
Example #6
0
def test_OssecSocket_send_ko(mock_conn, msg, effect, send_effect, expected_exception):
    """Tests OssecSocket.send function exceptions works"""

    queue = OssecSocket('test_path')

    if effect == 'return_value':
        with patch('wazuh.core.wazuh_socket.socket.socket.send', return_value=send_effect):
            with pytest.raises(WazuhException, match=f'.* {expected_exception} .*'):
                queue.send(msg)
    else:
        with patch('wazuh.core.wazuh_socket.socket.socket.send', side_effect=send_effect):
            with pytest.raises(WazuhException, match=f'.* {expected_exception} .*'):
                queue.send(msg)

    mock_conn.assert_called_once_with('test_path')
Example #7
0
File: task.py Project: zWaR/wazuh
def send_to_tasks_socket(command):
    """Send command to task module

    Parameters
    ----------
    command : dict
        Command to be sent to task module

    Returns
    -------
    Message received from the socket
    """
    try:
        s = OssecSocket(common.TASKS_SOCKET)
    except Exception:
        raise WazuhInternalError(1121)
    s.send(dumps(command).encode())
    data = loads(s.receive().decode())
    s.close()

    return data
Example #8
0
def get_active_configuration(agent_id, component, configuration):
    """
    Reads agent loaded configuration in memory
    """
    if not component or not configuration:
        raise WazuhError(1307)

    components = {
        "agent", "agentless", "analysis", "auth", "com", "csyslog",
        "integrator", "logcollector", "mail", "monitor", "request", "syscheck",
        "wmodules"
    }

    # checks if the component is correct
    if component not in components:
        raise WazuhError(1101, f'Valid components: {", ".join(components)}')

    sockets_path = os_path.join(common.ossec_path, "queue", "ossec")

    if agent_id == '000':
        dest_socket = os_path.join(sockets_path, component)
        command = f"getconfig {configuration}"
    else:
        dest_socket = os_path.join(sockets_path, "request")
        command = f"{str(agent_id).zfill(3)} {component} getconfig {configuration}"

    # Socket connection
    try:
        s = OssecSocket(dest_socket)
    except Exception:
        raise WazuhInternalError(1121)

    # Send message
    s.send(command.encode())

    # Receive response
    try:
        # Receive data length
        rec_msg_ok, rec_msg = s.receive().decode().split(" ", 1)
    except ValueError:
        raise WazuhInternalError(1118,
                                 extra_message="Data could not be received")

    s.close()

    if rec_msg_ok.startswith('ok'):
        msg = json.loads(rec_msg)

        # Include password if auth->use_password enabled and authd.pass file exists
        if msg.get('auth', {}).get('use_password') == 'yes':
            try:
                with open(os_path.join(common.ossec_path, "etc", "authd.pass"),
                          'r') as f:
                    msg['authd.pass'] = f.read().rstrip()
            except IOError:
                pass

        return msg
    else:
        raise WazuhError(1117 if "No such file or directory" in rec_msg
                         or "Cannot send request" in rec_msg else 1116,
                         extra_message='{0}:{1}'.format(
                             component, configuration))
Example #9
0
def test_OssecSocket_protected_connect_ko(mock_conn):
    """Tests OssecSocket._connect function exceptions works"""

    with pytest.raises(WazuhException, match=".* 1013 .*"):
        OssecSocket('test_path')
Example #10
0
def test_OssecSocket_protected_connect(mock_conn):
    """Tests OssecSocket._connect function works"""

    OssecSocket('test_path')

    mock_conn.assert_called_with('test_path')
Example #11
0
def test_OssecSocket__init__(mock_conn):
    """Tests OssecSocket.__init__ function works"""

    OssecSocket('test_path')

    mock_conn.assert_called_once_with()