def serialize(self): return { 'ip_dst': get_ip_str_from_bytes(self.ip_dst), 'dst_hostname': self.dst_hostname, 'src_hostname': self.src_hostname, 'plugin_sid': self.plugin_sid, 'id': get_uuid_string_from_bytes(self.id), 'ip_src': get_ip_str_from_bytes(self.ip_src), 'ossim_asset_src': self.ossim_asset_src, 'layer4_sport': self.layer4_sport, 'ossim_asset_dst': self.ossim_asset_dst, 'plugin_id': self.plugin_id, 'src_mac': self.src_mac, 'dst_mac': self.dst_mac, 'ossim_reliability': self.ossim_reliability, 'layer4_dport': self.layer4_dport, 'timestamp': self.timestamp, 'tzone': self.tzone, 'src_net': get_uuid_string_from_bytes(self.src_net), 'ossim_correlation': self.ossim_correlation, 'ossim_priority': self.ossim_priority, 'dst_net': get_uuid_string_from_bytes(self.dst_net), 'device_id': self.device_id, 'ossim_risk_c': self.ossim_risk_c, 'ossim_risk_a': self.ossim_risk_a, 'ctx': get_uuid_string_from_bytes(self.ctx), 'dst_host': get_uuid_string_from_bytes(self.dst_host), 'ip_proto': self.ip_proto, 'src_host': get_uuid_string_from_bytes(self.src_host), 'device': self.device.serialize #'reputation_data': [i.serialize for i in self.reputation_data], #'idm_data': [i.serialize for i in self.idm_data], }
def serialize(self): return { 'ip_dst':get_ip_str_from_bytes(self.ip_dst), 'dst_hostname':self.dst_hostname, 'src_hostname':self.src_hostname, 'plugin_sid':self.plugin_sid, 'id':get_uuid_string_from_bytes(self.id), 'ip_src':get_ip_str_from_bytes(self.ip_src), 'ossim_asset_src':self.ossim_asset_src, 'layer4_sport':self.layer4_sport, 'ossim_asset_dst':self.ossim_asset_dst, 'plugin_id':self.plugin_id, 'src_mac':self.src_mac, 'dst_mac':self.dst_mac, 'ossim_reliability':self.ossim_reliability, 'layer4_dport':self.layer4_dport, 'timestamp':self.timestamp, 'tzone':self.tzone, 'src_net':get_uuid_string_from_bytes(self.src_net), 'ossim_correlation':self.ossim_correlation, 'ossim_priority':self.ossim_priority, 'dst_net':get_uuid_string_from_bytes(self.dst_net), 'device_id':self.device_id, 'ossim_risk_c':self.ossim_risk_c, 'ossim_risk_a':self.ossim_risk_a, 'ctx':get_uuid_string_from_bytes(self.ctx), 'dst_host':get_uuid_string_from_bytes(self.dst_host), 'ip_proto':self.ip_proto, 'src_host':get_uuid_string_from_bytes(self.src_host), 'device':self.device.serialize #'reputation_data': [i.serialize for i in self.reputation_data], #'idm_data': [i.serialize for i in self.idm_data], }
def get_system_info(system_id): """ Return all information related to system :param System ID """ system_info = {} try: system_id_bin = get_bytes_from_uuid(system_id) system = db.session.query(System).filter(System.id == system_id_bin).one() if system: system_info = { 'id': get_uuid_string_from_bytes(system.id), 'name': system.name, 'admin_ip': get_ip_str_from_bytes(system.admin_ip) if system.admin_ip is not None else None, 'vpn_ip': get_ip_str_from_bytes(system.vpn_ip) if system.vpn_ip is not None else None, 'profile': system.profile, 'sensor_id': get_uuid_string_from_bytes(system.sensor_id) if system.sensor_id is not None else None, 'server_id': get_uuid_string_from_bytes(system.server_id) if system.server_id is not None else None, 'database_id': get_uuid_string_from_bytes( system.database_id) if system.database_id is not None else None, 'host_id': get_uuid_string_from_bytes(system.host_id) if system.host_id is not None else None, 'ha_ip': get_ip_str_from_bytes(system.ha_ip) if system.ha_ip is not None else None, 'ha_name': system.ha_name, 'ha_role': system.ha_role } except Exception as err: db.session.rollback() return False, "Error while querying system {0}. Reason: {1}".format(system_id, err) return True, system_info
def serialize(self): return { 'rep_ip_dst':get_ip_str_from_bytes(self.rep_ip_dst), 'rep_rel_dst':self.rep_rel_dst, 'event_id':get_uuid_string_from_bytes(self.event_id), 'rep_rel_src':self.rep_rel_src, 'rep_prio_dst':self.rep_prio_dst, 'rep_act_dst':self.rep_act_dst, 'rep_ip_src':get_ip_str_from_bytes(self.rep_ip_src), 'rep_act_src':self.rep_act_src, 'rep_prio_src':self.rep_prio_src, }
def serialize(self): return { 'rep_ip_dst': get_ip_str_from_bytes(self.rep_ip_dst), 'rep_rel_dst': self.rep_rel_dst, 'event_id': get_uuid_string_from_bytes(self.event_id), 'rep_rel_src': self.rep_rel_src, 'rep_prio_dst': self.rep_prio_dst, 'rep_act_dst': self.rep_act_dst, 'rep_ip_src': get_ip_str_from_bytes(self.rep_ip_src), 'rep_act_src': self.rep_act_src, 'rep_prio_src': self.rep_prio_src, }
def get_system_info(system_id): """ Return all information related to system :param System ID """ system_info = {} try: system_id_bin = get_bytes_from_uuid(system_id) system = db.session.query(System).filter( System.id == system_id_bin).one() if system: system_info = { 'id': get_uuid_string_from_bytes(system.id), 'name': system.name, 'admin_ip': get_ip_str_from_bytes(system.admin_ip) if system.admin_ip is not None else None, 'vpn_ip': get_ip_str_from_bytes(system.vpn_ip) if system.vpn_ip is not None else None, 'profile': system.profile, 'sensor_id': get_uuid_string_from_bytes(system.sensor_id) if system.sensor_id is not None else None, 'server_id': get_uuid_string_from_bytes(system.server_id) if system.server_id is not None else None, 'database_id': get_uuid_string_from_bytes(system.database_id) if system.database_id is not None else None, 'host_id': get_uuid_string_from_bytes(system.host_id) if system.host_id is not None else None, 'ha_ip': get_ip_str_from_bytes(system.ha_ip) if system.ha_ip is not None else None, 'ha_name': system.ha_name, 'ha_role': system.ha_role } except Exception as err: db.session.rollback() return False, "Error while querying system {0}. Reason: {1}".format( system_id, err) return True, system_info
def db_get_systems(): system = db.session.query(System) ip_addresses = [] try: for machine in system: if machine.vpn_ip: ip_addresses.append(get_ip_str_from_bytes(machine.vpn_ip)) else: ip_addresses.append(get_ip_str_from_bytes(machine.admin_ip)) except Exception as e: api_log.error(str(e)) db.session.rollback() return False, 'Something wrong happened while retrieving system IPs from the database' return bool(ip_addresses), ip_addresses
def get_server(self, server_id): server_record = db.session.query(Server.descr, Server.ip).filter(Server.id == server_id).one() description = server_record[0] ip_str = get_ip_str_from_bytes(server_record[1]) return self._server_constructor(description, ip_str)
def get_server(self, server_id): server_record = db.session.query( Server.descr, Server.ip).filter(Server.id == server_id).one() description = server_record[0] ip_str = get_ip_str_from_bytes(server_record[1]) return self._server_constructor(description, ip_str)
def get_asset_ip_from_id(asset_id): """Returns a list of IPs for a given ASSET""" ips = [] try: data = db.session.query(Host_Ip).filter(Host_Ip.host_id == get_bytes_from_uuid(asset_id)).all() ips = [get_ip_str_from_bytes(i.ip) for i in data] except Exception: ips = [] return ips
def get_host_by_host_id(host_id): """ Returns a Host object given its host_id Args: host_id (uuid): Host ID Return: Tuple (boolean,data) - boolean indicates whether the operation was successful or not - data will contain the data in case the operation was successful, or the error string otherwise """ host_id_bin = get_bytes_from_uuid(host_id) try: host = db.session.query(Host).filter(Host.id == host_id_bin).one() except NoResultFound: return True, None except Exception as err_detail: return False, "Error captured while querying for host id '%s': %s" % (str(host_id), str(err_detail)) # Build the output host_output = {} if host is not None: host_dict = host.__dict__ for key, value in host_dict.iteritems(): if key in ('_sa_instance_state',): continue if key in ('ctx', 'id'): host_output[key] = get_uuid_string_from_bytes(value) continue if key == "permissions": host_output[key] = str(value) if key == 'asset': host_output['asset_value'] = value else: host_output[key] = value host_output['os'] = "" host_output['model'] = "" for host_property in host.host_properties: if host_property.property_ref == 3: host_output['os'] = host_property.value continue if host_property.property_ref == 14: host_output['model'] = host_property.value continue host_output['ips'] = [get_ip_str_from_bytes(x.ip) for x in host.host_ips] host_output['sensors'] = [get_uuid_string_from_bytes(x.sensor_id) for x in host.host_sensor_reference] host_output['services'] = [x.service for x in host.host_services] host_output['networks'] = [get_uuid_string_from_bytes(x.net_id) for x in host.host_net_reference] return True, host_output
def get_asset_ip_from_id(asset_id): """Returns a list of IPs for a given ASSET""" ips = [] try: data = db.session.query(Host_Ip).filter( Host_Ip.host_id == get_bytes_from_uuid(asset_id)).all() ips = [get_ip_str_from_bytes(i.ip) for i in data] except Exception: ips = [] return ips
def serialize(self): """ Converts the object in a serializable object :return: A dict object with all the row field. """ hash_table = { 'interface': str(self.interface), 'device_ip': get_ip_str_from_bytes(self.device_ip), 'sensor_id': get_uuid_string_from_bytes(self.sensor_id), 'id': str(self.id), } return hash_table
def serialize(self): """ Converts the object in a serializable object :return: A dict object with all the row field. """ hash_table = { 'interface':str(self.interface), 'device_ip': get_ip_str_from_bytes(self.device_ip), 'sensor_id': get_uuid_string_from_bytes(self.sensor_id), 'id': str(self.id), } return hash_table
def get_system(self): _, system_id = get_system_id_from_local() system_id_bin = get_bytes_from_uuid(system_id) system_info = db.session.query( System.name, System.admin_ip, System.vpn_ip, System.ha_ip ).filter(System.id == system_id_bin).one() system_name = system_info[0] system_admin_ip = get_ip_str_from_bytes(system_info[1]) system_vpn_ip = get_ip_str_from_bytes(system_info[2]) system_ha_ip = get_ip_str_from_bytes(system_info[3]) return self._system_constructor( system_id, system_name, system_admin_ip, system_vpn_ip, system_ha_ip )
def get_all_ip_systems(): """ Return a dict whose keys are the system id and each value is another dict with keys \*admin_ip\* always present and two optional keys \*ha_ip\* and \*vpn_ip\* Returns: A tuple whose first members indicates whether the operation was successful (true or false) and the second member is a dictionary is success or a text error if false """ result = {} try: system_list = db.session.query(System).all() for system in system_list: system_uuid = get_uuid_string_from_bytes(system.id) res = {'admin_ip': get_ip_str_from_bytes(system.admin_ip)} if system.vpn_ip: res['vpn_ip'] = get_ip_str_from_bytes(system.vpn_ip) if system.ha_ip: res['ha_ip'] = get_ip_str_from_bytes(system.ha_ip) result[system_uuid] = res except Exception as err: return False, "Error while querying systems. error: %s" % str(err) return True, result
if system: if system.ha_ip: sensor_ip = system.ha_ip elif system.vpn_ip: sensor_ip = system.vpn_ip else: sensor_ip = system.admin_ip else: return (False, "No system found with id '%s'" % str(sensor_id)) except Exception, msg: db.session.rollback() return (False, "Error captured while querying for system id '%s': %s" % (str(sensor_id), str(msg))) if output == 'str': try: sensor_ip_str = get_ip_str_from_bytes(sensor_ip) except Exception, msg: return (False, "Cannot convert supposed system ip '%s' to its string form: %s" % (str(sensor_ip), str(msg))) sensor_ip = sensor_ip_str return (True, sensor_ip) @require_db def get_sensor_id_from_sensor_ip(sensor_ip): try: sensor = db.session.query(Sensor).filter(Sensor.ip == get_ip_bin_from_str(sensor_ip)).one() sensor_id = get_uuid_string_from_bytes(sensor.id) except NoResultFound: return False, "No sensor id found for the given sensor ip" except MultipleResultsFound:
def get_host_by_host_id(host_id): """ Returns a Host object given its host_id Args: host_id (uuid): Host ID Return: Tuple (boolean,data) - boolean indicates whether the operation was successful or not - data will contain the data in case the operation was successful, or the error string otherwise """ host_id_bin = get_bytes_from_uuid(host_id) try: host = db.session.query(Host).filter(Host.id == host_id_bin).one() except NoResultFound: return True, None except Exception as err_detail: return False, "Error captured while querying for host id '%s': %s" % ( str(host_id), str(err_detail)) # Build the output host_output = {} if host is not None: host_dict = host.__dict__ for key, value in host_dict.iteritems(): if key in ('_sa_instance_state', ): continue if key in ('ctx', 'id'): host_output[key] = get_uuid_string_from_bytes(value) continue if key == "permissions": host_output[key] = str(value) if key == 'asset': host_output['asset_value'] = value else: host_output[key] = value host_output['os'] = "" host_output['model'] = "" for host_property in host.host_properties: if host_property.property_ref == 3: host_output['os'] = host_property.value continue if host_property.property_ref == 14: host_output['model'] = host_property.value continue host_output['ips'] = [ get_ip_str_from_bytes(x.ip) for x in host.host_ips ] host_output['sensors'] = [ get_uuid_string_from_bytes(x.sensor_id) for x in host.host_sensor_reference ] host_output['services'] = [x.service for x in host.host_services] host_output['networks'] = [ get_uuid_string_from_bytes(x.net_id) for x in host.host_net_reference ] return True, host_output
Config.value != '127.0.0.1')).one().value) except NoResultFound, msg: pass except Exception, msg: db.session.rollback() return False, "Error while querying for connected databases: '%s'" % str( msg) else: system_list = filter( lambda x: (x.admin_ip == database_ip or x.vpn_ip == database_ip ) or 'database' not in x.profile.lower(), system_list) if convert_to_dict: return True, dict([(get_uuid_string_from_bytes(x.id), get_ip_str_from_bytes(x.vpn_ip) if x.vpn_ip else get_ip_str_from_bytes(x.admin_ip)) for x in system_list]) return True, [(get_uuid_string_from_bytes(x.id), get_ip_str_from_bytes(x.vpn_ip) if x.vpn_ip else get_ip_str_from_bytes(x.admin_ip)) for x in system_list] @require_db def get_all_ip_systems(): """ Return a dict whose keys are the system id and each value is another dict with keys \*admin_ip\* always present and two optional keys \*ha_ip\* and \*vpn_ip\*
if key == 'asset': host_output['asset_value'] = value else: host_output[key] = value host_output['os'] = "" host_output['model'] = "" for host_property in host.host_properties: if host_property.property_ref == 3: host_output['os'] = host_property.value continue if host_property.property_ref == 14: host_output['model'] = host_property.value continue host_output['ips'] = [get_ip_str_from_bytes(x.ip) for x in host.host_ips] host_output['sensors'] = [get_uuid_string_from_bytes(x.sensor_id) for x in host.host_sensor_reference] host_output['services'] = [x.service for x in host.host_services] host_output['networks'] = [get_uuid_string_from_bytes(x.net_id) for x in host.host_net_reference] return (True, host_output) @require_db def get_all_hosts(): """ Returns a list of hosts currently existing in the db Args: Return: Tuple (boolean,data) - boolean indicates whether the operation was successful or not
('server' in x.profile.lower() and x.server_id in connected_servers and not system_type), system_list) if not system_type or system_type.lower() == 'database': try: database_ip = get_ip_bin_from_str(db.session.query(Config).filter(and_(Config.conf == 'snort_host', Config.value != '127.0.0.1')).one().value) except NoResultFound, msg: pass except Exception, msg: db.session.rollback() return False, "Error while querying for connected databases: '%s'" % str(msg) else: system_list = filter(lambda x: (x.admin_ip == database_ip or x.vpn_ip == database_ip) or 'database' not in x.profile.lower(), system_list) if convert_to_dict: return True, dict([(get_uuid_string_from_bytes(x.id), get_ip_str_from_bytes(x.vpn_ip) if x.vpn_ip else get_ip_str_from_bytes(x.admin_ip)) for x in system_list]) return True, [(get_uuid_string_from_bytes(x.id), get_ip_str_from_bytes(x.vpn_ip) if x.vpn_ip else get_ip_str_from_bytes(x.admin_ip)) for x in system_list] @require_db def get_all_ip_systems(): """ Return a dict whose keys are the system id and each value is another dict with keys \*admin_ip\* always present and two optional keys \*ha_ip\* and \*vpn_ip\* Returns: A tuple whose first members indicates whether the operation was successful (true or false) and the second member is a dictionary is success or a text error if false """ result = {}
host_output['asset_value'] = value else: host_output[key] = value host_output['os'] = "" host_output['model'] = "" for host_property in host.host_properties: if host_property.property_ref == 3: host_output['os'] = host_property.value continue if host_property.property_ref == 14: host_output['model'] = host_property.value continue host_output['ips'] = [ get_ip_str_from_bytes(x.ip) for x in host.host_ips ] host_output['sensors'] = [ get_uuid_string_from_bytes(x.sensor_id) for x in host.host_sensor_reference ] host_output['services'] = [x.service for x in host.host_services] host_output['networks'] = [ get_uuid_string_from_bytes(x.net_id) for x in host.host_net_reference ] return (True, host_output) @require_db
def ossec_win_deploy(sensor_id, asset_id, windows_ip, windows_username, windows_password, windows_domain, agent_id=None): """ Deploy HIDS agent on a Windows System Args: sensor_id(str): Sensor ID asset_id(str): Asset ID windows_ip(str) : Deployment IP (where we are going to deploy the HIDS Agent) windows_username(str) : Windows Username windows_password(str) : Windows Password windows_domain(str) : Windows Domain agent_id(str) : Agent ID Returns: True if HIDS agent was properly deployed Raises: APICannotResolveAssetID APICannotCreateHIDSAgent APICannotGetHIDSAgentByAsset APICannotResolveSensorID APICannotDeployHIDSAgent APIInvalidDeploymentIP APIInvalidWindowsUsername APIInvalidWindowsPassword APIInvalidAgentID """ # Setting default values agent_name = None sensor_ip = None sensor_name = None asset_name = None try: # Validate deployment parameters if not is_valid_uuid(asset_id): raise APICannotResolveAssetID(asset_id) if not is_valid_ipv4(windows_ip): raise APIInvalidDeploymentIP(windows_ip) if not is_valid_windows_user(windows_username): raise APIInvalidWindowsUsername(windows_username) if not is_valid_user_password(windows_password): raise APIInvalidWindowsPassword() if agent_id and not is_valid_ossec_agent_id(agent_id): raise APIInvalidAgentID(agent_id) # Getting Sensor Information (success, sensor) = get_sensor_by_sensor_id(sensor_id) if not success: raise APICannotResolveSensorID(sensor_id) sensor_id = get_uuid_string_from_bytes(sensor.id) sensor_id = sensor_id.replace('-', '').upper() sensor_ip = get_ip_str_from_bytes(sensor.ip) sensor_name = sensor.name # Getting agent related to assets hids_agents = get_hids_agents_by_asset(asset_id, sensor_id) # Getting asset info asset_name = get_name_by_host_id(asset_id) if len(hids_agents) == 0: # Creating agent if doesn't exists agent_name = asset_name (success, data) = apimethod_ossec_add_new_agent(sensor_id, agent_name, windows_ip, asset_id) if not success: raise APICannotCreateHIDSAgent(agent_name, sensor_id) else: agent_id = data else: # Getting agent information if agent_id: agent_key = sensor_id + '#' + agent_id else: agent_key = hids_agents.keys().pop(0) if agent_key in hids_agents: agent_name = hids_agents[agent_key].get('name') agent_id = hids_agents[agent_key].get('id') else: raise APICannotGetHIDSAgentByAsset(asset_id) # Deploy HIDS Agent ansible_result = ansible_ossec_win_deploy(sensor_ip, agent_name, windows_ip, windows_username, windows_domain, windows_password) if ansible_result[sensor_ip]['unreachable'] == 0 and ansible_result[ sensor_ip]['failures'] == 0: # No error, update agent status in database time.sleep(2) (success, data) = apimethod_ossec_get_agent_detail(sensor_id, agent_id) if success: agent_info = data[0].split(',') agent_status = agent_info[3] update_hids_agent_status(agent_id, sensor_id, agent_status) else: ans_last_error = "" if ansible_result[sensor_ip]['unreachable'] == 1: ans_last_error = "System is unreachable" elif 'msg' in ansible_result['alienvault']['lasterror'][ sensor_ip] and ansible_result['alienvault']['lasterror'][ sensor_ip]['msg'] != "": ans_last_error = ansible_result['alienvault']['lasterror'][ sensor_ip]['msg'] elif 'stderr' in ansible_result['alienvault']['lasterror'][ sensor_ip] and ansible_result['alienvault']['lasterror'][ sensor_ip]['stderr'] != "": ans_last_error = ansible_result['alienvault']['lasterror'][ sensor_ip]['stderr'] elif 'stdout' in ansible_result['alienvault']['lasterror'][ sensor_ip] and ansible_result['alienvault']['lasterror'][ sensor_ip]['stdout'] != "": ans_last_error = ansible_result['alienvault']['lasterror'][ sensor_ip]['stdout'] error_msg = 'HIDS Agent cannot be deployed. Reason: {0}'.format( ans_last_error) raise APICannotDeployHIDSAgent(error_msg) res = True message = 'HIDS agent successfully deployed' except APICannotDeployHIDSAgent as err: message = str(err) res = False except Exception as err: message = str(err) logger.error(message) res = False # Create message in Message Center mc_id = "00000000-0000-0000-0000-000000010033" if res is True else "00000000-0000-0000-0000-000000010031" additional_info = { "asset_id": asset_id, "sensor_id": sensor_id, "agent_id": agent_id, "asset_name": asset_name, "asset_ip": windows_ip, "sensor_ip": sensor_ip, "sensor_name": sensor_name, "agent_name": agent_name, "deploy_status": message } additional_info = json.dumps(additional_info) insert_current_status_message(mc_id, asset_id, "host", additional_info) return res, message
if system: if system.ha_ip: server_ip = system.ha_ip elif system.vpn_ip: server_ip = system.vpn_ip else: server_ip = system.admin_ip else: return (False, "No server ip address found with server id '%s'" % str(server_id)) except Exception, msg: db.session.rollback() return (False, "Error captured while querying for server id '%s': %s" % (str(server_id), str(msg))) if output == 'str': try: server_ip_str = get_ip_str_from_bytes(server_ip) except Exception, msg: return (False, "Cannot convert supposed server ip '%s' to its string form: %s" % (str(server_ip), str(msg))) return (True, server_ip_str) return (True, server_ip) @require_db @accepted_values([], ['str', 'bin']) def get_server_id_from_local(output='str'): """ Return the system id of the local machine """ try: server_id = db.session.query(Config).filter(Config.conf == 'server_id').one().value
def ossec_win_deploy(sensor_id, asset_id, windows_ip, windows_username, windows_password, windows_domain, agent_id=None): """ Deploy HIDS agent on a Windows System Args: sensor_id(str): Sensor ID asset_id(str): Asset ID windows_ip(str) : Deployment IP (where we are going to deploy the HIDS Agent) windows_username(str) : Windows Username windows_password(str) : Windows Password windows_domain(str) : Windows Domain agent_id(str) : Agent ID Returns: True if HIDS agent was properly deployed Raises: APICannotResolveAssetID APICannotCreateHIDSAgent APICannotGetHIDSAgentByAsset APICannotResolveSensorID APICannotDeployHIDSAgent APIInvalidDeploymentIP APIInvalidWindowsUsername APIInvalidWindowsPassword APIInvalidAgentID """ # Setting default values agent_name = None sensor_ip = None sensor_name = None asset_name = None try: # Validate deployment parameters if not is_valid_uuid(asset_id): raise APICannotResolveAssetID(asset_id) if not is_valid_ipv4(windows_ip): raise APIInvalidDeploymentIP(windows_ip) if not is_valid_windows_user(windows_username): raise APIInvalidWindowsUsername(windows_username) if not is_valid_user_password(windows_password): raise APIInvalidWindowsPassword() if agent_id and not is_valid_ossec_agent_id(agent_id): raise APIInvalidAgentID(agent_id) # Getting Sensor Information (success, sensor) = get_sensor_by_sensor_id(sensor_id) if not success: raise APICannotResolveSensorID(sensor_id) sensor_id = get_uuid_string_from_bytes(sensor.id) sensor_id = sensor_id.replace('-', '').upper() sensor_ip = get_ip_str_from_bytes(sensor.ip) sensor_name = sensor.name # Getting agent related to assets hids_agents = get_hids_agents_by_asset(asset_id, sensor_id) # Getting asset info asset_name = get_name_by_host_id(asset_id) if len(hids_agents) == 0: # Creating agent if doesn't exists agent_name = asset_name (success, data) = apimethod_ossec_add_new_agent(sensor_id, agent_name, windows_ip, asset_id) if not success: raise APICannotCreateHIDSAgent(agent_name, sensor_id) else: agent_id = data else: # Getting agent information if agent_id: agent_key = sensor_id + '#' + agent_id else: agent_key = hids_agents.keys().pop(0) if agent_key in hids_agents: agent_name = hids_agents[agent_key].get('name') agent_id = hids_agents[agent_key].get('id') else: raise APICannotGetHIDSAgentByAsset(asset_id) # Deploy HIDS Agent ansible_result = ansible_ossec_win_deploy(sensor_ip, agent_name, windows_ip, windows_username, windows_domain, windows_password) if ansible_result[sensor_ip]['unreachable'] == 0 and ansible_result[sensor_ip]['failures'] == 0: # No error, update agent status in database time.sleep(2) (success, data) = apimethod_ossec_get_agent_detail(sensor_id, agent_id) if success: agent_info = data[0].split(',') agent_status = agent_info[3] update_hids_agent_status(agent_id, sensor_id, agent_status) else: ans_last_error = "" if ansible_result[sensor_ip]['unreachable'] == 1: ans_last_error = "System is unreachable" elif 'msg' in ansible_result['alienvault']['lasterror'][sensor_ip] and ansible_result['alienvault']['lasterror'][sensor_ip]['msg']!="": ans_last_error = ansible_result['alienvault']['lasterror'][sensor_ip]['msg'] elif 'stderr' in ansible_result['alienvault']['lasterror'][sensor_ip] and ansible_result['alienvault']['lasterror'][sensor_ip]['stderr']!="": ans_last_error = ansible_result['alienvault']['lasterror'][sensor_ip]['stderr'] elif 'stdout' in ansible_result['alienvault']['lasterror'][sensor_ip] and ansible_result['alienvault']['lasterror'][sensor_ip]['stdout']!="": ans_last_error = ansible_result['alienvault']['lasterror'][sensor_ip]['stdout'] error_msg = 'HIDS Agent cannot be deployed. Reason: {0}'.format(ans_last_error) raise APICannotDeployHIDSAgent(error_msg) res = True message = 'HIDS agent successfully deployed' except APICannotDeployHIDSAgent as err: message = str(err) res = False except Exception as err: message = str(err) logger.error(message) res = False # Create message in Message Center mc_id = "00000000-0000-0000-0000-000000010033" if res is True else "00000000-0000-0000-0000-000000010031" additional_info = { "asset_id": asset_id, "sensor_id": sensor_id, "agent_id": agent_id, "asset_name": asset_name, "asset_ip": windows_ip, "sensor_ip": sensor_ip, "sensor_name": sensor_name, "agent_name": agent_name, "deploy_status": message } additional_info = json.dumps(additional_info) insert_current_status_message(mc_id, asset_id, "host", additional_info) return res, message
if system: if system.ha_ip: sensor_ip = system.ha_ip elif system.vpn_ip: sensor_ip = system.vpn_ip else: sensor_ip = system.admin_ip else: return (False, "No system found with id '%s'" % str(sensor_id)) except Exception, msg: return (False, "Error captured while querying for system id '%s': %s" % (str(sensor_id), str(msg))) if output == 'str': try: sensor_ip_str = get_ip_str_from_bytes(sensor_ip) except Exception, msg: return ( False, "Cannot convert supposed system ip '%s' to its string form: %s" % (str(sensor_ip), str(msg))) sensor_ip = sensor_ip_str return (True, sensor_ip) @require_db def get_sensor_id_from_sensor_ip(sensor_ip): try: sensor = db.session.query(Sensor).filter( Sensor.ip == get_ip_bin_from_str(sensor_ip)).one()