示例#1
0
文件: rootcheck.py 项目: zWaR/wazuh
def clear(agent_list=None):
    """Clear the rootcheck database for a list of agents.

    Parameters
    ----------
    agent_list : list
        List of agent ids.

    Returns
    -------
    result : AffectedItemsWazuhResult
        JSON containing the affected agents.
    """
    result = AffectedItemsWazuhResult(
        all_msg='Rootcheck database was cleared on returned agents',
        some_msg='Rootcheck database was not cleared on some agents',
        none_msg="No rootcheck database was cleared")

    wdb_conn = WazuhDBConnection()
    for agent_id in agent_list:
        if agent_id not in get_agents_info():
            result.add_failed_item(id_=agent_id,
                                   error=WazuhResourceNotFound(1701))
        else:
            try:
                wdb_conn.execute(f"agent {agent_id} rootcheck delete",
                                 delete=True)
                result.affected_items.append(agent_id)
            except WazuhError as e:
                result.add_failed_item(id_=agent_id, error=e)

    result.affected_items.sort(key=int)
    result.total_affected_items = len(result.affected_items)

    return result
示例#2
0
def last_scan(agent_id):
    """Get the last rootcheck scan of an agent.

    :param agent_id: Agent ID.
    :return: Dictionary: end, start.
    """
    Agent(agent_id).get_basic_information()
    wdb_conn = WazuhDBConnection()

    # end time
    result = wdb_conn.execute(
        f"agent {agent_id} sql SELECT max(date_last) FROM pm_event WHERE "
        "log = 'Ending rootcheck scan.'")
    time = list(result[0].values())[0] if result else None
    end = datetime.utcfromtimestamp(time).strftime(
        date_format) if time is not None else None

    # start time
    result = wdb_conn.execute(
        f"agent {agent_id} sql SELECT max(date_last) FROM pm_event "
        "WHERE log = 'Starting rootcheck scan.'")
    time = list(result[0].values())[0] if result else None
    start = datetime.utcfromtimestamp(time).strftime(
        date_format) if time is not None else None

    return {
        'start':
        start,
        'end':
        None if start is None else None if end is None or end < start else end
    }
示例#3
0
def test_execute(send_mock, socket_send_mock, connect_mock):
    mywdb = WazuhDBConnection()
    mywdb.execute('agent 000 sql delete from test', delete=True)
    mywdb.execute("agent 000 sql update test set value = 'test' where key = 'test'", update=True)
    with patch("wazuh.core.wdb.WazuhDBConnection._send", return_value=[{'total':5}]):
        mywdb.execute("agent 000 sql select test from test offset 1 limit 1")
        mywdb.execute("agent 000 sql select test from test offset 1 limit 1", count=True)
        mywdb.execute("agent 000 sql select test from test offset 1 count")
示例#4
0
def test_failed_execute(send_mock, connect_mock, error_query, error_type, expected_exception, delete, update):
    mywdb = WazuhDBConnection()
    if not error_type:
        with pytest.raises(exception.WazuhException, match=f'.* {expected_exception} .*'):
            mywdb.execute(error_query, delete=delete, update=update)
    else:
        with patch("wazuh.core.wdb.WazuhDBConnection._send", return_value=[{'total': 5}]):
            with patch("wazuh.core.wdb.range", side_effect=error_type):
                with pytest.raises(exception.WazuhException, match=f'.* {expected_exception} .*'):
                    mywdb.execute(error_query, delete=delete, update=update)
示例#5
0
def test_execute(send_mock, socket_send_mock, connect_mock):
    def send_mock(obj, msg, raw=False):
        return ['ok', '{"total": 5}'] if raw else [{"total": 5}]

    mywdb = WazuhDBConnection()
    mywdb.execute('agent 000 sql delete from test', delete=True)
    mywdb.execute("agent 000 sql update test set value = 'test' where key = 'test'", update=True)
    with patch("wazuh.core.wdb.WazuhDBConnection._send", new=send_mock):
        mywdb.execute("agent 000 sql select test from test offset 1 limit 1")
        mywdb.execute("agent 000 sql select test from test offset 1 limit 1", count=True)
        mywdb.execute("agent 000 sql select test from test offset 1 count")
示例#6
0
def test_execute_pagination(socket_send_mock, connect_mock):
    mywdb = WazuhDBConnection()

    # Test pagination
    with patch("wazuh.core.wdb.WazuhDBConnection._send",
               side_effect=[[{'total': 5}], exception.WazuhInternalError(2009), ['ok', '{"total": 5}'],
                            ['ok', '{"total": 5}']]):
        mywdb.execute("agent 000 sql select test from test offset 1 limit 500")

    # Test pagination error
    with patch("wazuh.core.wdb.WazuhDBConnection._send",
               side_effect=[[{'total': 5}], exception.WazuhInternalError(2009)]):
        with pytest.raises(exception.WazuhInternalError, match=".* 2009 .*"):
            mywdb.execute("agent 000 sql select test from test offset 1 limit 1")
示例#7
0
文件: __init__.py 项目: ggbg/wazuh
    def _initialize(self):
        """
        Calculates all Wazuh installation metadata
        """
        # info DB if possible
        try:
            wdb_conn = WazuhDBConnection()
            open_ssl = wdb_conn.execute("global sql SELECT value FROM info WHERE key = 'openssl_support'")[0]['value']
            self.openssl_support = open_ssl
        except Exception:
            self.openssl_support = "N/A"

        # Ruleset version
        ruleset_version_file = os.path.join(self.path, 'ruleset', 'VERSION')
        try:
            with open(ruleset_version_file, 'r') as f:
                line_regex = re.compile(r'(^\w+)="(.+)"')
                for line in f:
                    match = line_regex.match(line)
                    if match and len(match.groups()) == 2:
                        self.ruleset_version = match.group(2)
        except:
            raise WazuhInternalError(1005, extra_message=ruleset_version_file)

        # Timezone info
        try:
            self.tz_offset = strftime("%z")
            self.tz_name = strftime("%Z")
        except Exception:
            self.tz_offset = None
            self.tz_name = None

        return self.to_dict()
示例#8
0
def get_manager_name():
    """This function read the manager name from global.db"""
    wdb_conn = WazuhDBConnection()
    manager_name = wdb_conn.execute(
        "global sql SELECT name FROM agent WHERE (id = 0)")[0]['name']
    wdb_conn.close()

    return manager_name
示例#9
0
def clear(agent_list=None):
    """Clear the syscheck database for a list of agents.

    :param agent_list: List of agent ids
    :return: AffectedItemsWazuhResult.
    """
    result = AffectedItemsWazuhResult(all_msg='Syscheck database was cleared on returned agents',
                                      some_msg='Syscheck database was not cleared on some agents',
                                      none_msg="No syscheck database was cleared")
    wdb_conn = WazuhDBConnection()
    for agent in agent_list:
        if agent not in get_agents_info():
            result.add_failed_item(id_=agent, error=WazuhResourceNotFound(1701))
        else:
            try:
                wdb_conn.execute("agent {} sql delete from fim_entry".format(agent), delete=True)
                # Update key fields which contains keys to value 000
                wdb_conn.execute("agent {} sql update metadata set value = '000' "
                                 "where key like 'fim_db%'".format(agent), update=True)
                wdb_conn.execute("agent {} sql update metadata set value = '000' "
                                 "where key = 'syscheck-db-completed'".format(agent), update=True)
                result.affected_items.append(agent)
            except WazuhError as e:
                result.add_failed_item(id_=agent, error=e)

    result.affected_items.sort(key=int)
    result.total_affected_items = len(result.affected_items)

    return result
示例#10
0
    def _initialize(self):
        """
        Calculates all Wazuh installation metadata
        """
        # info DB if possible
        try:
            wdb_conn = WazuhDBConnection()
            open_ssl = wdb_conn.execute("global sql SELECT value FROM info WHERE key = 'openssl_support'")[0]['value']
            self.openssl_support = open_ssl
        except Exception:
            self.openssl_support = "N/A"

        # Timezone info
        try:
            self.tz_offset = strftime("%z")
            self.tz_name = strftime("%Z")
        except Exception:
            self.tz_offset = None
            self.tz_name = None

        return self.to_dict()
示例#11
0
def rootcheck_delete_agent(agent: str, wdb_conn: WazuhDBConnection) -> None:
    wdb_conn.execute(f"agent {agent} rootcheck delete", delete=True)
示例#12
0
def test_query_lower_private(send_mock, connect_mock):
    mywdb = WazuhDBConnection()
    with pytest.raises(exception.WazuhException, match=".* 2004 .*"):
        mywdb.execute("Agent sql select 'test'")
示例#13
0
def test_query_input_validation_private(send_mock, connect_mock, error_query):
    mywdb = WazuhDBConnection()
    with pytest.raises(exception.WazuhException, match=".* 2004 .*"):
        mywdb.execute(error_query)
示例#14
0
文件: syscheck.py 项目: wisdark/wazuh
def syscheck_delete_agent(agent: str, wdb_conn: WazuhDBConnection) -> None:
    wdb_conn.execute(f"agent {agent} sql delete from fim_entry", delete=True)