def get_linked_assets(): """ Get assets Returns: Dictionary with linked assets Raises: APICannotGetLinkedAssets """ assets_ids = {} query = "SELECT ha.host_id AS host_id, ha.sensor_id AS sensor_id, ha.agent_id FROM hids_agents ha WHERE ha.host_id is not NULL" try: asset_list = db.session.connection(mapper=Hids_Agents).execute(query) for asset in asset_list: ha_id = asset.agent_id ha_sensor_id = asset.sensor_id ha_host_id = asset.host_id ha_host_id = get_uuid_string_from_bytes(ha_host_id) assets_ids[ha_host_id] = { 'ha_id': ha_id, 'sensor_id': get_uuid_string_from_bytes(ha_sensor_id) } except Exception as msg: api_log.error("[get_linked_assets]: %s" % str(msg)) raise APICannotGetLinkedAssets() return assets_ids
def get_asset_ids_in_group(group_id, user): """ Return the list of asset ids in the group that are visible for the user. Args: group_id (UUID): Id of the asset group user (proxy object): User proxy object Returns: success (bool): True if successful, False elsewhere assets ([UUID]): List of member asset ids. """ if not group_id or not user: return False, "Invalid parameters" assets = [] try: data = db.session.query(Host, Host_Ip, Host_Group_Reference).filter(and_(Host.id == Host_Ip.host_id, Host.id == Host_Group_Reference.host_id, Host_Group_Reference.host_group_id == get_bytes_from_uuid( group_id))).all() assets = [get_uuid_string_from_bytes(i[0].id) for i in data if user.is_allowed(get_uuid_string_from_bytes(i[0].id).replace('-', ''))] success = True except Exception: success = False return success, assets
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 get_asset_ids_in_group(group_id, user): """ Return the list of asset ids in the group that are visible for the user. Args: group_id (UUID): Id of the asset group user (proxy object): User proxy object Returns: success (bool): True if successful, False elsewhere assets ([UUID]): List of member asset ids. """ if not group_id or not user: return False, "Invalid parameters" assets = [] try: data = db.session.query(Host, Host_Ip, Host_Group_Reference).filter( and_( Host.id == Host_Ip.host_id, Host.id == Host_Group_Reference.host_id, Host_Group_Reference.host_group_id == get_bytes_from_uuid( group_id))).all() assets = [ get_uuid_string_from_bytes(i[0].id) for i in data if user.is_allowed( get_uuid_string_from_bytes(i[0].id).replace('-', '')) ] success = True except Exception: success = False return success, assets
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 serialize(self): return { 'cnt': self.cnt, 'ctx': get_uuid_string_from_bytes(self.ctx), 'src_net': get_uuid_string_from_bytes(self.src_net), 'day': self.day, 'dst_host': get_uuid_string_from_bytes(self.dst_host), 'dst_net': get_uuid_string_from_bytes(self.dst_net), 'plugin_id': self.plugin_id, 'device_id': self.device_id, 'plugin_sid': self.plugin_sid, 'src_host': get_uuid_string_from_bytes(self.src_host), }
def serialize(self): return { 'cnt':self.cnt, 'ctx':get_uuid_string_from_bytes(self.ctx), 'src_net':get_uuid_string_from_bytes(self.src_net), 'day':self.day, 'dst_host':get_uuid_string_from_bytes(self.dst_host), 'dst_net':get_uuid_string_from_bytes(self.dst_net), 'plugin_id':self.plugin_id, 'device_id':self.device_id, 'plugin_sid':self.plugin_sid, 'src_host':get_uuid_string_from_bytes(self.src_host), }
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 get_sensor_ctx_by_sensor_id(sensor_id, output='str'): """ Returns a sensor CTX given a sensor ID """ sensor_ctx = None try: if sensor_id: sensor_id_bin = get_bytes_from_uuid(sensor_id) query = db.session.query(Acl_Sensors.entity_id).filter( Acl_Sensors.sensor_id == sensor_id_bin) sensor = query.join( Acl_Entities, Acl_Entities.id == Acl_Sensors.entity_id).filter( Acl_Entities.entity_type == 'context').one() sensor_ctx = sensor.entity_id else: return False, "Sensor ID could not be empty" except NoResultFound: return True, sensor_ctx except Exception as msg: msg = str(msg) api_log.error(msg) return False, msg if output == 'str': return True, get_uuid_string_from_bytes(sensor_ctx) else: return True, sensor_ctx
def serialize(self): return { 'event_id': get_uuid_string_from_bytes(self.event_id), 'username': self.username, 'domain': self.domain, 'from_src': self.from_src, }
def serialize(self): return { 'plugin_id':self.plugin_id, 'ctx':get_uuid_string_from_bytes(self.ctx), 'plugin_sid':self.plugin_sid, 'ref_id':self.ref_id, }
def serialize(self): return { 'event_id':get_uuid_string_from_bytes(self.event_id), 'username':self.username, 'domain':self.domain, 'from_src':self.from_src, }
def serialize(self): component_dict = self.host or self.net or self.sensor or self.user or self.system if len(component_dict.keys()) > 0: (component_name, component_ip) = component_dict.keys()[0] else: (component_name, component_ip) = (None, None) if self.message is None: print "This status_message (%s) doesn't have a related status_messsage...that's wierd! " % ( get_uuid_string_from_bytes(self.id)) message_level = Status_Message.get_message_level_str( self.message.level) if self.message is not None else "" message_title = self.message.title if self.message is not None else "" message_description = self.message.description if self.message is not None else "" message_type = self.message.type if self.message is not None else "" message_expire = self.message.expire if self.message is not None else "" message_actions = self.message.actions if self.message is not None else "" message_role = self.message.message_role if self.message is not None else "" message_action_role = self.message.action_role if self.message is not None else "" message_alternative_actions = self.message.alternative_actions if self.message is not None else "" message_source = self.message.source if self.message is not None else "" additional_info_json = {} try: if self.additional_info is not None and self.additional_info != "": additional_info_json = json.loads(self.additional_info) except Exception, e: additional_info_json = json.loads( '{"error": "Invalid json object for this message"}')
def serialize(self): return { 'plugin_id': self.plugin_id, 'ctx': get_uuid_string_from_bytes(self.ctx), 'plugin_sid': self.plugin_sid, 'ref_id': self.ref_id, }
def get_host_id_by_ip_ctx(ip, ctx, output='str'): """ Returns an Asset ID given an IP address and context """ host_id = None try: if ip and ctx: ip_bin = get_ip_bin_from_str(ip) ctx_bin = get_bytes_from_uuid(ctx) query = db.session.query(Host.id).filter(Host.ctx == ctx_bin) host = query.join(Host_Ip, Host_Ip.host_id == Host.id).filter(Host_Ip.ip == ip_bin).one() host_id = host.id else: return False, "IP address and/or context could not be empty" except NoResultFound: return True, host_id except Exception as msg: msg = str(msg) api_log.error(msg) return False, "Asset ID not found in the system" if output == 'str': return True, get_uuid_string_from_bytes(host_id) else: return True, host_id
def get_sensor_ctx_by_sensor_id(sensor_id, output='str'): """ Returns a sensor CTX given a sensor ID """ sensor_ctx = None try: if sensor_id: sensor_id_bin = get_bytes_from_uuid(sensor_id) query = db.session.query(Acl_Sensors.entity_id).filter(Acl_Sensors.sensor_id == sensor_id_bin) sensor = query.join(Acl_Entities, Acl_Entities.id == Acl_Sensors.entity_id).filter( Acl_Entities.entity_type == 'context').one() sensor_ctx = sensor.entity_id else: return False, "Sensor ID could not be empty" except NoResultFound: return True, sensor_ctx except Exception as msg: msg = str(msg) api_log.error(msg) return False, msg if output == 'str': return True, get_uuid_string_from_bytes(sensor_ctx) else: return True, sensor_ctx
def __build_sensor_from_alchemy_object(self, alchemy_sensor_object): sensor_id = get_uuid_string_from_bytes(alchemy_sensor_object.id) _, sensor_ip = get_sensor_ip_from_sensor_id(sensor_id) sensor_platform = self._platform_repository.get_platform(sensor_ip) sensor_connected = sensor_platform is not None return self._sensor_constructor( sensor_id, alchemy_sensor_object.name, alchemy_sensor_object.descr, sensor_platform and sensor_platform.name, sensor_ip, self.__get_software_version(alchemy_sensor_object.id), sensor_platform and sensor_platform.threat_intelligence_version, sensor_connected)
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 { '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): """ 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_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: return False, "More than one sensor with the same sensor ip" except Exception as msg: api_log.error(str(msg)) return False, msg return True, sensor_id
def get_sensor_id_from_system_id(system_id): try: system_id_binary = get_bytes_from_uuid(system_id.lower()) sensor_id = db.session.query(System).filter( System.id == system_id_binary).one() sensor_id_str = get_uuid_string_from_bytes(sensor_id.sensor_id) except NoResultFound: return False, "No sensor id found for the given system id" except MultipleResultsFound: return False, "More than one sensor id for the same system id" except Exception as msg: return False, msg return True, sensor_id_str
def serialize(self): return { 'monitor_id': self.monitor_id, 'timestamp': self.timestamp, 'component_id': get_uuid_string_from_bytes(self.component_id) if self.component_id else '', 'data': self.data, 'component_type': self.component_type }
def serialize(self): """Returns a serialized object from Status_Message object""" return { 'id': get_uuid_string_from_bytes(self.id) if self.id else '', 'level': Status_Message.get_message_level_str(self.level), 'title': self.title, 'description': self.description, 'type': self.type, 'expire': self.expire, 'actions': self.actions, 'alternative_actions': self.alternative_actions, 'message_role': self.message_role, 'action_role': self.action_role, 'source': self.source }
def serialize(self): return { 'username': self.username, 'userdata2': self.userdata2, 'userdata1': self.userdata1, 'userdata6': self.userdata6, 'userdata7': self.userdata7, 'userdata4': self.userdata4, 'userdata3': self.userdata3, 'event_id': get_uuid_string_from_bytes(self.event_id), 'userdata8': self.userdata8, 'userdata5': self.userdata5, 'data_payload': self.data_payload, 'filename': self.filename, 'userdata9': self.userdata9, 'password': self.password, 'binary_data': self.binary_data, }
def get_system_id_from_system_ip(system_ip, output='str'): """ Return the system id of an appliance using its ip. """ system_ip_bin = get_ip_bin_from_str(system_ip) try: system_id = None if output == 'str': system_id = get_uuid_string_from_bytes( db.session.query(System).filter( or_(System.admin_ip == system_ip_bin, System.vpn_ip == system_ip_bin)).one().id) elif output == 'bin': system_id = db.session.query(System).filter( or_(System.admin_ip == system_ip_bin, System.vpn_ip == system_ip_bin)).one().id except NoResultFound, msg: return False, "No system found with ip address '%s'" % str(system_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
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 - data will contain the data in case the operation was successful, or the error string otherwise """ try: hosts = db.session.query(Host).all() except NoResultFound: return True, None except Exception as err_detail: return False, "Error captured while querying for hosts': %s" % ( str(err_detail)) host_ids = [] if hosts is not None: host_ids = [get_uuid_string_from_bytes(x.id) for x in hosts] return True, host_ids
server_id_bin = get_bytes_from_uuid(server_id) try: system_id = db.session.query(System).filter(System.server_id == server_id_bin).first().id except NoResultFound, msg: return (False, "No system id found with server id '%s'" % str(server_id)) except MultipleResultsFound, msg: return (False, "More than one system id 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: system_id_str = get_uuid_string_from_bytes(system_id) except Exception, msg: return (False, "Cannot convert supposed system id '%s' to its string form: %s" % (str(system_id), str(msg))) return (True, system_id_str) return (True, system_id) @require_db(accept_local=True) @accepted_values([], ['str', 'bin']) def get_server_ip_from_server_id(server_id, output='str', local_loopback=True): """ Return the ip of a server using the server_id """ try:
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\*
class Current_Status (Base): __tablename__ = 'current_status' id = Column('id', BINARY(16), primary_key=True) message_id = Column('message_id', BINARY(16), ForeignKey(Status_Message.id)) component_id = Column('component_id', BINARY(16), primary_key=False) component_type = Column('component_type', ENUM('net', 'host', 'user', 'sensor', 'server', 'system', 'external'), primary_key=False) creation_time = Column('creation_time', TIMESTAMP, primary_key=False) viewed = Column('viewed', TINYINT, primary_key=False) suppressed = Column('suppressed', TINYINT, primary_key=False) suppressed_time = Column('suppressed_time', TIMESTAMP, primary_key=False) additional_info = Column('additional_info', TEXT, primary_key=False) message = relationship(Status_Message) # Sonar warning @staticmethod def _get_value_string(s): return s if s is not None else '' @staticmethod def _get_value_uuid(s): return str(uuid.UUID(bytes=s)) if s is not None else '' @property def serialize(self): component_dict = self.host or self.net or self.sensor or self.user or self.system if len(component_dict.keys()) > 0: (component_name, component_ip) = component_dict.keys()[0] else: (component_name, component_ip) = (None, None) if self.message is None: print "This status_message (%s) doesn't have a related status_messsage...that's wierd! " % (get_uuid_string_from_bytes(self.id)) message_level = Status_Message.get_message_level_str(self.message.level) if self.message is not None else "" message_title = self.message.title if self.message is not None else "" message_description = self.message.description if self.message is not None else "" message_type = self.message.type if self.message is not None else "" message_expire = self.message.expire if self.message is not None else "" message_actions = self.message.actions if self.message is not None else "" message_role = self.message.message_role if self.message is not None else "" message_action_role = self.message.action_role if self.message is not None else "" message_alternative_actions = self.message.alternative_actions if self.message is not None else "" message_source = self.message.source if self.message is not None else "" additional_info_json = {} try: if self.additional_info is not None and self.additional_info != "": additional_info_json = json.loads(self.additional_info) except Exception, e: additional_info_json = json.loads('{"error": "Invalid json object for this message"}') return { 'id': get_uuid_string_from_bytes(self.id), 'message_id': get_uuid_string_from_bytes(self.message_id), 'component_id': self._get_value_uuid(self.component_id) if self.component_id is not None else "", 'component_type': self.component_type, 'component_name': self._get_value_string(component_name), 'component_ip': self._get_value_string(component_ip), 'suppressed_time': self.suppressed_time, 'creation_time': self.creation_time, 'suppressed': self.suppressed, 'viewed': self.viewed, 'additional_info': additional_info_json, 'message_level': message_level, 'message_title': message_title, 'message_description': message_description, 'message_type': message_type, 'message_expire': message_expire, 'message_actions': message_actions, 'message_role': message_role, 'message_action_role': message_action_role, 'message_alternative_actions': message_alternative_actions, 'message_source': message_source }
except NoResultFound, msg: return (True, None) except Exception, msg: db.session.rollback() return (False, "Error captured while querying for host id '%s': %s" % (str(host_id), str(msg))) # 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:
def serialize(self): return {'component_id': get_uuid_string_from_bytes(self.component_id), 'login': self.login}
db.session.rollback() return (False, "Cannot retrieve status message") if viewed is not None: status_message.viewed = viewed delete_status_message = False if suppressed is not None: status_message.suppressed = suppressed status_message.suppressed_time = datetime.utcnow() if status_message.component_type == "external": delete_status_message = True try: db.session.begin() if delete_status_message: db.session.delete(status_message) cmd = "delete from status_message where id=0x%s" % get_uuid_string_from_bytes( status_message.message_id).replace('-', '').upper() db.session.connection(mapper=Status_Message).execute(cmd) else: db.session.merge(status_message) db.session.commit() except Exception as msg: db.session.rollback() api_log.error( "message: put_status_message: Cannot commit status_message: %s" % str(msg)) return (False, "Cannot update status message") return (True, None) @require_db def set_current_status_message_as_viewed(current_status_id, viewed=False):
except NoResultFound, msg: return (True, None) except Exception, msg: return (False, "Error captured while querying for host id '%s': %s" % (str(host_id), str(msg))) # 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:
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
def then_select_random_server(context, var_name): result = db.session.query(System).all() server = random.choice(result) context.alienvault[var_name] = get_uuid_string_from_bytes(server.id)