def check_cluster_config(config): iv = InputValidator() reservated_ips = {'localhost', 'NODE_IP', '0.0.0.0', '127.0.1.1'} if len(config['key']) == 0: raise WazuhException(3004, 'Unspecified key') elif not iv.check_name(config['key']) or not iv.check_length( config['key'], 32, eq): raise WazuhException( 3004, 'Key must be 32 characters long and only have alphanumeric characters' ) elif config['node_type'] != 'master' and config['node_type'] != 'worker': raise WazuhException( 3004, 'Invalid node type {0}. Correct values are master and worker'. format(config['node_type'])) elif not 1024 < config['port'] < 65535: raise WazuhException( 3004, "Port must be higher than 1024 and lower than 65535.") if len(config['nodes']) > 1: logger.warning( "Found more than one node in configuration. Only master node should be specified. Using {} as master." .format(config['nodes'][0])) invalid_elements = list(reservated_ips & set(config['nodes'])) if len(invalid_elements) != 0: raise WazuhException( 3004, "Invalid elements in node fields: {0}.".format( ', '.join(invalid_elements)))
def check_cluster_config(config): iv = InputValidator() if not 'key' in config.keys(): raise WazuhException(3004, 'Unspecified key') elif not iv.check_name(config['key']) or not iv.check_length( config['key'], 32, eq): raise WazuhException( 3004, 'Key must be 32 characters long and only have alphanumeric characters' ) if config['node_type'] != 'master' and config['node_type'] != 'client': raise WazuhException( 3004, 'Invalid node type {0}. Correct values are master and client'. format(config['node_type'])) if config['node_type'] == 'master' and not re.compile("\d+[m|s]").match( config['interval']): raise WazuhException( 3004, 'Invalid interval specification. Please, specify it with format <number>s or <number>m' ) if config['nodes'][0] == 'localhost' and len(config['nodes']) == 1: raise WazuhException(3004, 'Please specify IPs of all cluster nodes')
def check_cluster_config(config): iv = InputValidator() reservated_ips = {'localhost', 'NODE_IP', '0.0.0.0', '127.0.1.1'} if not 'key' in config.keys(): raise WazuhException(3004, 'Unspecified key') elif not iv.check_name(config['key']) or not iv.check_length( config['key'], 32, eq): raise WazuhException( 3004, 'Key must be 32 characters long and only have alphanumeric characters' ) if config['node_type'] != 'master' and config['node_type'] != 'client': raise WazuhException( 3004, 'Invalid node type {0}. Correct values are master and client'. format(config['node_type'])) if not re.compile("\d+[m|s]").match(config['interval']): raise WazuhException( 3004, 'Invalid interval specification. Please, specify it with format <number>s or <number>m' ) if len(config['nodes']) == 0: raise WazuhException(3004, 'No nodes defined in cluster configuration.') invalid_elements = list(reservated_ips & set(config['nodes'])) if len(invalid_elements) != 0: raise WazuhException( 3004, "Invalid elements in node fields: {0}.".format( ', '.join(invalid_elements)))
def test_check_length(self): result = InputValidator().check_length('test') self.assertEqual(result, True) result = InputValidator().check_length('test', 3) self.assertEqual(result, False) result = InputValidator().check_length('test', 4, operator.eq) self.assertEqual(result, True)
def test_check_name(self): result = InputValidator().check_name('test') self.assertEqual(result, True) result = InputValidator().check_name('test', '') self.assertEqual(result, False) result = InputValidator().check_name('?') self.assertEqual(result, False)
def test_group(self): result = InputValidator().group('test') self.assertEqual(result, True) result = InputValidator().group(['test1', 'test2']) self.assertEqual(result, True) result = InputValidator().group('test') self.assertEqual(result, True) result = InputValidator().group(['test1', 'test2']) self.assertEqual(result, True)
def create_group(group_id): """ Creates a group. :param group_id: Group ID. :return: Confirmation message. """ # Input Validation of group_id if not InputValidator().group(group_id): raise WazuhException(1722) group_path = "{0}/{1}".format(common.shared_path, group_id) if group_id.lower() == "default" or path.exists(group_path): raise WazuhException(1711, group_id) # Create group in /etc/shared group_def_path = "{0}/default".format(common.shared_path) try: copytree(group_def_path, group_path) chown_r(group_path, common.ossec_uid, common.ossec_gid) chmod_r(group_path, 0o660) chmod(group_path, 0o770) msg = "Group '{0}' created.".format(group_id) except Exception as e: raise WazuhException(1005, str(e)) return msg
def group_exists_sql(group_id): """ Checks if the group exists :param group_id: Group ID. :return: True if group exists, False otherwise """ # Input Validation of group_id if not InputValidator().group(group_id): raise WazuhException(1722) db_global = glob(common.database_path_global) if not db_global: raise WazuhException(1600) conn = Connection(db_global[0]) query = "SELECT `group` FROM agent WHERE `group` = :group_id LIMIT 1" request = {'group_id': group_id} conn.execute(query, request) for tuple in conn: if tuple[0] != None: return True else: return False
def remove_group(group_id): """ Remove the group in every agent. :param group_id: Group ID. :return: Confirmation message. """ # Input Validation of group_id if not InputValidator().group(group_id): raise WazuhException(1722) failed_ids = [] ids = [] affected_agents = [] if isinstance(group_id, list): for id in group_id: if id.lower() == "default": raise WazuhException(1712) try: removed = _remove_single_group(id) ids.append(id) affected_agents += removed['affected_agents'] except WazuhException as e: failed_ids.append(create_exception_dic(id, e)) except Exception as e: raise WazuhException(1728, str(e)) else: if group_id.lower() == "default": raise WazuhException(1712) try: removed = _remove_single_group(group_id) ids.append(group_id) affected_agents += removed['affected_agents'] except WazuhException as e: failed_ids.append(create_exception_dic(group_id, e)) except Exception as e: raise WazuhException(1728, str(e)) final_dict = {} if not failed_ids: message = 'All selected groups were removed' final_dict = { 'msg': message, 'ids': ids, 'affected_agents': affected_agents } else: message = 'Some groups were not removed' final_dict = { 'msg': message, 'failed_ids': failed_ids, 'ids': ids, 'affected_agents': affected_agents } return final_dict
def check_cluster_config(config): iv = InputValidator() reservated_ips = {'localhost', 'NODE_IP', '0.0.0.0', '127.0.1.1'} if not 'key' in config: raise WazuhException(3004, 'Unspecified key') elif not iv.check_name(config['key']) or not iv.check_length( config['key'], 32, eq): raise WazuhException( 3004, 'Key must be 32 characters long and only have alphanumeric characters' ) if 'node_type' not in config: raise WazuhException(3004, "Node type not present in cluster configuration") elif config['node_type'] != 'master' and config['node_type'] != 'worker': raise WazuhException( 3004, 'Invalid node type {0}. Correct values are master and worker'. format(config['node_type'])) if 'nodes' not in config or len(config['nodes']) == 0: raise WazuhException(3004, 'No nodes defined in cluster configuration.') if 'disabled' not in config: config['disabled'] = 'yes' if config['disabled'] != 'yes' and config['disabled'] != 'no': raise WazuhException( 3004, 'Invalid value for disabled option {}. Allowed values are yes and no' .format(config['disabled'])) if len(config['nodes']) > 1: logger.warning( "Found more than one node in configuration. Only master node should be specified. Using {} as master." .format(config['nodes'][0])) invalid_elements = list(reservated_ips & set(config['nodes'])) if len(invalid_elements) != 0: raise WazuhException( 3004, "Invalid elements in node fields: {0}.".format( ', '.join(invalid_elements)))
def group_exists(group_id): """ Checks if the group exists :param group_id: Group ID. :return: True if group exists, False otherwise """ # Input Validation of group_id if not InputValidator().group(group_id): raise WazuhException(1722) if path.exists("{0}/{1}".format(common.shared_path, group_id)): return True else: return False
def set_group(agent_id, group_id, force=False): """ Set a group to an agent. :param agent_id: Agent ID. :param group_id: Group ID. :param force: No check if agent exists :return: Confirmation message. """ # Input Validation of group_id if not InputValidator().group(group_id): raise WazuhException(1722) agent_id = agent_id.zfill(3) if agent_id == "000": raise WazuhException(1703) # Check if agent exists if not force: Agent(agent_id).get_basic_information() # Assign group in /queue/agent-groups agent_group_path = "{0}/{1}".format(common.groups_path, agent_id) try: new_file = False if path.exists(agent_group_path) else True f_group = open(agent_group_path, 'w') f_group.write(group_id) f_group.close() if new_file: ossec_uid = getpwnam("ossec").pw_uid ossec_gid = getgrnam("ossec").gr_gid chown(agent_group_path, ossec_uid, ossec_gid) chmod(agent_group_path, 0o660) except Exception as e: raise WazuhException(1005, str(e)) # Create group in /etc/shared if not group_exists(group_id): create_group(group_id) return "Group '{0}' set to agent '{1}'.".format(group_id, agent_id)
# Set framework path path.append(dirname(argv[0]) + '/../framework') # It is necessary to import Wazuh package child_pid = 0 # Import framework try: from wazuh import Wazuh from wazuh.common import * from wazuh.cluster import * from wazuh.exception import WazuhException from wazuh.InputValidator import InputValidator from wazuh.utils import send_request from wazuh.pyDaemonModule import pyDaemon, create_pid, delete_pid iv = InputValidator() except Exception as e: print("Error importing 'Wazuh' package.\n\n{0}\n".format(e)) exit() class WazuhClusterHandler(asyncore.dispatcher_with_send): def __init__(self, sock, addr): asyncore.dispatcher_with_send.__init__(self, sock) self.addr = addr def handle_close(self): self.close() def handle_read(self): error = 0