Ejemplo n.º 1
0
def test_failed_last_scan_key_error_agent_version(info_mock):
    """
    Test last_scan function when a ErrorKey appears
    """
    result = last_scan('001')

    assert isinstance(result, dict)
    assert set(result.keys()) == {'start', 'end'}
Ejemplo n.º 2
0
def test_syscheck_last_scan_internal_error(glob_mock, version):
    """Test function `last_scan` from syscheck module.

    It will expect a WazuhInternalError.

    Parameters
    ----------
    version : dict
        Dict with the Wazuh version to be applied.

    Raises
    ------
    WazuhInternalError
        Raised when there is not a valid database file.
    """
    with patch('wazuh.syscheck.Agent.get_basic_information', return_value=version):
        with pytest.raises(WazuhInternalError):
            last_scan(['001'])
Ejemplo n.º 3
0
def test_last_scan(wazuh_conn_mock, connec_mock, db_mock, version, agent_id):
    """
    Test last_scan function
    """
    with patch('wazuh.syscheck.Agent.get_basic_information', return_value=version):
        with patch("wazuh.syscheck.glob", return_value=[join(common.database_path_agents, agent_id)+".db"]):
            result = last_scan(agent_id)

            assert isinstance(result, dict)
            assert set(result.keys()) == {'start', 'end'}
Ejemplo n.º 4
0
def test_syscheck_last_scan(socket_mock, wdb_conn_mock, is_file_mock, db_mock, agent_id, wazuh_version):
    """Test function `last_scan` from syscheck module.

    Parameters
    ----------
    agent_id : list
        Agent ID.
    wazuh_version : dict
        Dict with the Wazuh version to be applied.
    """
    with patch('wazuh.syscheck.Agent.get_basic_information', return_value=wazuh_version):
        with patch('wazuh.syscheck.glob',
                   return_value=[os.path.join(common.database_path_agents, '{}.db'.format(agent_id[0]))]):
            result = last_scan(agent_id)
            assert isinstance(result, AffectedItemsWazuhResult)
            assert isinstance(result.affected_items, list)
            assert result.total_affected_items == 1
Ejemplo n.º 5
0
    def found_terminator(self):
        response = b''.join(self.received_data)
        error = 0
        cmd = self.f.decrypt(response[:common.cluster_sync_msg_size]).decode()
        self.command = cmd.split(" ")

        logging.debug("Command received: {0}".format(self.command))

        if not check_cluster_cmd(self.command, self.node_type):
            logging.error(
                "Received invalid cluster command {0} from {1}".format(
                    self.command[0], self.addr))
            error = 1
            res = "Received invalid cluster command {0}".format(
                self.command[0])

        if error == 0:
            if self.command[0] == list_requests_cluster['node']:
                res = get_node()
            elif self.command[0] == list_requests_cluster['zip']:
                zip_bytes = self.f.decrypt(
                    response[common.cluster_sync_msg_size:])
                res = extract_zip(zip_bytes)
                self.restart = res['restart']
            elif self.command[0] == list_requests_agents['RESTART_AGENTS']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                if (len(args) == 2):
                    agents = args[0].split("-")
                    restart_all = ast.literal_eval(args[1])
                else:
                    agents = None
                    restart_all = ast.literal_eval(args[0])
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                res = Agent.restart_agents(agents, restart_all, cluster_depth)
            elif self.command[0] == list_requests_agents[
                    'AGENTS_UPGRADE_RESULT']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                try:
                    agent = args[0]
                    timeout = args[1]
                    res = Agent.get_upgrade_result(agent, timeout)
                except Exception as e:
                    res = str(e)
            elif self.command[0] == list_requests_agents['AGENTS_UPGRADE']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                agent_id = args[0]
                wpk_repo = ast.literal_eval(args[1])
                version = ast.literal_eval(args[2])
                force = ast.literal_eval(args[3])
                chunk_size = ast.literal_eval(args[4])
                try:
                    res = Agent.upgrade_agent(agent_id, wpk_repo, version,
                                              force, chunk_size)
                except Exception as e:
                    res = str(e)
            elif self.command[0] == list_requests_agents[
                    'AGENTS_UPGRADE_CUSTOM']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                agent_id = args[0]
                file_path = ast.literal_eval(args[1])
                installer = ast.literal_eval(args[2])
                try:
                    res = Agent.upgrade_agent_custom(agent_id, file_path,
                                                     installer)
                except Exception as e:
                    res = str(e)
            elif self.command[0] == list_requests_syscheck[
                    'SYSCHECK_LAST_SCAN']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                agent = args.split(" ")
                res = syscheck.last_scan(agent[0])
            elif self.command[0] == list_requests_syscheck['SYSCHECK_RUN']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                if (len(args) == 2):
                    agents = args[0]
                    all_agents = ast.literal_eval(args[1])
                else:
                    agents = None
                    all_agents = ast.literal_eval(args[0])
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                res = syscheck.run(agents, all_agents, cluster_depth)
            elif self.command[0] == list_requests_syscheck['SYSCHECK_CLEAR']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                if (len(args) == 2):
                    agents = args[0]
                    all_agents = ast.literal_eval(args[1])
                else:
                    agents = None
                    all_agents = ast.literal_eval(args[0])
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                res = syscheck.clear(agents, all_agents, cluster_depth)
            elif self.command[0] == list_requests_rootcheck['ROOTCHECK_PCI']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                index = 0
                agents = None
                if (len(args) == 5):
                    agents = args[0]
                    index = index + 1
                offset = ast.literal_eval(args[index])
                index = index + 1
                limit = ast.literal_eval(args[index])
                index = index + 1
                sort = ast.literal_eval(args[index])
                index = index + 1
                search = ast.literal_eval(args[index])
                res = args
                res = rootcheck.get_pci(agents, offset, limit, sort, search)
            elif self.command[0] == list_requests_rootcheck['ROOTCHECK_CIS']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                index = 0
                agents = None
                if (len(args) == 5):
                    agents = args[0]
                    index = index + 1
                offset = ast.literal_eval(args[index])
                index = index + 1
                limit = ast.literal_eval(args[index])
                index = index + 1
                sort = ast.literal_eval(args[index])
                index = index + 1
                search = ast.literal_eval(args[index])
                res = args
                res = rootcheck.get_cis(agents, offset, limit, sort, search)
            elif self.command[0] == list_requests_rootcheck[
                    'ROOTCHECK_LAST_SCAN']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                agent = args.split(" ")
                res = rootcheck.last_scan(agent[0])
            elif self.command[0] == list_requests_rootcheck['ROOTCHECK_RUN']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                if (len(args) == 2):
                    agents = args[0]
                    all_agents = ast.literal_eval(args[1])
                else:
                    agents = None
                    all_agents = ast.literal_eval(args[0])
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                res = rootcheck.run(agents, all_agents, cluster_depth)
            elif self.command[0] == list_requests_rootcheck['ROOTCHECK_CLEAR']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                if (len(args) == 2):
                    agents = args[0]
                    all_agents = ast.literal_eval(args[1])
                else:
                    agents = None
                    all_agents = ast.literal_eval(args[0])
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                res = rootcheck.clear(agents, all_agents, cluster_depth)
            elif self.command[0] == list_requests_managers['MANAGERS_STATUS']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                res = manager.managers_status(cluster_depth=cluster_depth)
            elif self.command[0] == list_requests_managers['MANAGERS_LOGS']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                type_log = args[0]
                category = args[1]
                months = ast.literal_eval(args[2])
                offset = ast.literal_eval(args[3])
                limit = ast.literal_eval(args[4])
                sort = ast.literal_eval(args[5])
                search = ast.literal_eval(args[6])
                res = manager.managers_ossec_log(type_log=type_log,
                                                 category=category,
                                                 months=months,
                                                 offset=offset,
                                                 limit=limit,
                                                 sort=sort,
                                                 search=search,
                                                 cluster_depth=cluster_depth)
            elif self.command[0] == list_requests_managers[
                    'MANAGERS_LOGS_SUMMARY']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                months = ast.literal_eval(args[0])
                res = manager.managers_ossec_log_summary(
                    months=months, cluster_depth=cluster_depth)
            elif self.command[0] == list_requests_managers[
                    'MANAGERS_STATS_TOTALS']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                year = ast.literal_eval(args[0])
                month = ast.literal_eval(args[1])
                day = ast.literal_eval(args[2])
                res = stats.totals(year=year,
                                   month=month,
                                   day=day,
                                   cluster_depth=cluster_depth)
            elif self.command[0] == list_requests_managers[
                    'MANAGERS_STATS_HOURLY']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                res = stats.hourly(cluster_depth=cluster_depth)
            elif self.command[0] == list_requests_managers[
                    'MANAGERS_STATS_WEEKLY']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                res = stats.weekly(cluster_depth=cluster_depth)
            elif self.command[0] == list_requests_managers[
                    'MANAGERS_OSSEC_CONF']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                section = args[0]
                field = ast.literal_eval(args[1])
                res = manager.managers_get_ossec_conf(
                    section=section, field=field, cluster_depth=cluster_depth)
            elif self.command[0] == list_requests_managers['MANAGERS_INFO']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                res = myWazuh.managers_get_ossec_init(
                    cluster_depth=cluster_depth)
            elif self.command[0] == list_requests_cluster['CLUSTER_CONFIG']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                cluster_depth = ast.literal_eval(self.command[1]) - 1
                res = get_config_distributed(cluster_depth=cluster_depth)

            elif self.command[0] == list_requests_cluster['MASTER_FORW']:
                args = self.f.decrypt(response[common.cluster_sync_msg_size:])
                args = args.split(" ")
                args_list = []
                if args[0] in all_list_requests.values():
                    agent_id = None
                    request_type = args[0]
                    if (len(args) > 1):
                        args_list = args[1:]
                elif len(args) > 1 and args[1] in all_list_requests.values():
                    agent_id = args[0].split("-")
                    request_type = args[1]
                    if (len(args) > 2):
                        args_list = args[2:]
                res = distributed_api_request(request_type=request_type,
                                              agent_id=agent_id,
                                              args=args_list,
                                              cluster_depth=1,
                                              affected_nodes=None,
                                              from_cluster=True)

            elif self.command[0] == list_requests_cluster['ready']:
                res = "Starting to sync client's files"
                # execute an independent process to "crontab" the sync interval
                kill(child_pid, SIGUSR1)
            elif self.command[0] == list_requests_cluster['data']:
                res = "Saving data from actual master"
                actual_master_data = json.loads(
                    self.f.decrypt(
                        response[common.cluster_sync_msg_size:]).decode())
                if save_actual_master_data_on_db(actual_master_data):
                    restart_manager()

            logging.debug("Command {0} executed for {1}".format(
                self.command[0], self.addr))

        self.data = json.dumps({'error': error, 'data': res})

        self.handle_write()
Ejemplo n.º 6
0
def test_failed_last_scan_not_agent_db(glob_mock, info_mock):
    """Test failed last_scan function when agent don't exist."""
    with pytest.raises(exception.WazuhException, match=".* 1600 .*"):
        last_scan('001')