def allOffense2Alert(timerange): """ Get all openned offense created within the last <timerange> minutes and creates alerts for them in TheHive """ logger = logging.getLogger(__name__) logger.info('%s.allOffense2Alert starts', __name__) report = dict() report['success'] = True report['offenses'] = list() try: cfg = getConf() qradarConnector = QRadarConnector(cfg) theHiveConnector = TheHiveConnector(cfg) offensesList = qradarConnector.getOffenses(timerange) #each offenses in the list is represented as a dict #we enrich this dict with additional details for offense in offensesList: #searching if the offense has already been converted to alert q = dict() q['sourceRef'] = str(offense['id']) logger.info('Looking for offense %s in TheHive alerts', str(offense['id'])) results = theHiveConnector.findAlert(q) if len(results) == 0: logger.info( 'Offense %s not found in TheHive alerts, creating it', str(offense['id'])) offense_report = dict() enrichedOffense = enrichOffense(qradarConnector, offense) try: theHiveAlert = qradarOffenseToHiveAlert( theHiveConnector, enrichedOffense) theHiveEsAlertId = theHiveConnector.createAlert( theHiveAlert)['id'] offense_report['raised_alert_id'] = theHiveEsAlertId offense_report['qradar_offense_id'] = offense['id'] offense_report['success'] = True except Exception as e: logger.error('%s.allOffense2Alert failed', __name__, exc_info=True) offense_report['success'] = False if isinstance(e, ValueError): errorMessage = json.loads(str(e))['message'] offense_report['message'] = errorMessage else: offense_report['message'] = str( e) + ": Couldn't raise alert in TheHive" offense_report['offense_id'] = offense['id'] # Set overall success if any fails report['success'] = False report['offenses'].append(offense_report) else: logger.info('Offense %s already imported as alert', str(offense['id'])) except Exception as e: logger.error( 'Failed to create alert from QRadar offense (retrieving offenses failed)', exc_info=True) report['success'] = False report['message'] = "%s: Failed to create alert from offense" % str(e) return report
def phishingAlert(): report = dict() report['success'] = bool() tempAttachment = None cfg = getConf() ewsConnector = EwsConnector(cfg) folder_name = cfg.get('EWS', 'folder_name') unread = ewsConnector.scan(folder_name) theHiveConnector = TheHiveConnector(cfg) for email in unread: conversationId = email.conversation_id.id alertTitle = str(email.subject) alertDescription = ('```\n' + 'Alert created by Synapse\n' + 'conversation_id: "' + str(email.conversation_id.id) + '"\n' + '```') alertArtifacts = [] alertTags = ['CAT 7'] for msg in email.attachments: try: #print(type(msg)) q = dict() q['sourceRef'] = str(conversationId) esAlertId = theHiveConnector.findAlert(q) tempAttachment = TempAttachment(msg) if not tempAttachment.isInline: #print('here') tmpFilepath = tempAttachment.writeFile() with open(tmpFilepath, 'rb') as fhdl: raw_email = fhdl.read() parsed_eml = eml_parser.eml_parser.decode_email_b( raw_email) #print(parsed_eml['header']['header']['to']) #print(json.dumps(parsed_eml, default=json_serial, indent=4, sort_keys=True)) alertArtifacts.append( theHiveConnector.craftAlertArtifact( dataType='file', message="Phishing Email", data=tmpFilepath, tags=['Synapse'])) alertArtifacts.append( theHiveConnector.craftAlertArtifact( dataType='other', message="Message Id", data=parsed_eml['header']['header']['message-id'] [0], tags=['Synapse'])) for i in parsed_eml['header']['received_ip']: alertArtifacts.append( theHiveConnector.craftAlertArtifact( dataType='ip', message="Source IP", data=i, tags=['Synapse'])) alertArtifacts.append( theHiveConnector.craftAlertArtifact( dataType='mail_subject', message="Phishing Email Subject", data=parsed_eml['header']['subject'], tags=['Synapse'])) for i in parsed_eml['header']['to']: alertArtifacts.append( theHiveConnector.craftAlertArtifact( dataType='mail', message="Recipients", data=i, tags=['Synapse'])) for i in parsed_eml['header']['header']['return-path']: alertArtifacts.append( theHiveConnector.craftAlertArtifact( dataType='mail', message="Return Path", data=i, tags=['Synapse'])) if 'x-originating-ip' in parsed_eml['header']['header']: alertArtifacts.append( theHiveConnector.craftAlertArtifact( dataType='mail', message="Origin IP", data=parsed_eml['header']['header'] ['x-originating-ip'], tags=['Synapse'])) alert = theHiveConnector.craftAlert( alertTitle, alertDescription, severity=2, tlp=2, status="New", date=(int(time.time() * 1000)), tags=alertTags, type="Phishing", source="Phishing Mailbox", sourceRef=email.conversation_id.id, artifacts=alertArtifacts, caseTemplate="Category 7 - Phishing") theHiveEsAlertId = theHiveConnector.createAlert( alert)['id'] except Exception as e: #msg_obj = msg_parser.msg_parser.Message(msg) #print(msg_obj.get_message_as_json()) #msg_properties_dict = msg_obj.get_properties() print('Failed to create alert from attachment') readMsg = ewsConnector.markAsRead(email)
def allOffense2Alert(timerange): """ Get all openned offense created within the last <timerange> minutes and creates alerts for them in TheHive """ logger = logging.getLogger(__name__) logger.info('%s.allOffense2Alert starts', __name__) report = dict() report['success'] = True report['offenses'] = list() try: cfg = getConf() qradarConnector = QRadarConnector(cfg) theHiveConnector = TheHiveConnector(cfg) offensesList = qradarConnector.getOffenses(timerange) #each offenses in the list is represented as a dict #we enrich this dict with additional details for offense in offensesList: #searching if the offense has already been converted to alert logger.info('Looking for offense %s in TheHive alerts', str(offense['id'])) # Update only new Alerts, as Ignored it will be closed on QRadar and should not be updated, # as Imported we will do a responder to fetch latest info in the case results = theHiveConnector.findAlert( Eq("sourceRef", str(offense['id']))) offense_report = dict() try: if len(results) == 0: logger.info( 'Offense %s not found in TheHive alerts, creating it', str(offense['id'])) enrichedOffense = enrichOffense(qradarConnector, offense) theHiveAlert = qradarOffenseToHiveAlert( theHiveConnector, enrichedOffense) theHiveEsAlertId = theHiveConnector.createAlert( theHiveAlert)['id'] offense_report['type'] = "Creation" offense_report['raised_alert_id'] = theHiveEsAlertId offense_report['qradar_offense_id'] = offense['id'] offense_report['success'] = True report['offenses'].append(offense_report) elif results[0]['status'] not in ['Ignored', 'Imported']: # update alert if alert is not imported and not dimissed # will only update 'lastEventCount' and 'lastUpdatedTime' custom fields logger.info('Updating offense %s', str(offense['id'])) alert = Alert(json=results[0]) cf = CustomFieldHelper() alert.title = offense['description'] if 'lastEventCount' not in alert.customFields: alert.customFields['lastEventCount'] = {} if 'lastUpdated' not in alert.customFields: alert.customFields['lastUpdated'] = {} if 'offenseSource' not in alert.customFields: alert.customFields['offenseSource'] = {} alert.customFields['lastEventCount']['number'] = offense[ 'event_count'] alert.customFields['lastUpdated']['date'] = offense[ 'last_updated_time'] alert.customFields['offenseSource']['string'] = offense[ 'offense_source'] # updated maybe ? # should improve TheHiveConnector.updateAlert() rather than using this updatedAlert = theHiveConnector.theHiveApi.update_alert( results[0]['id'], alert, fields=['customFields', 'title']) if not updatedAlert.ok: raise ValueError(json.dumps(updatedAlert.json())) offense_report['type'] = "Update" offense_report['updated_alert_id'] = updatedAlert.json( )['id'] offense_report['qradar_offense_id'] = offense['id'] offense_report['success'] = True report['offenses'].append(offense_report) else: logger.info("Offense already exists") except Exception as e: logger.error('%s.allOffense2Alert failed', __name__, exc_info=True) offense_report['success'] = False if isinstance(e, ValueError): errorMessage = json.loads(str(e))['message'] offense_report['message'] = errorMessage else: offense_report['message'] = str( e) + ": Couldn't raise alert in TheHive" offense_report['offense_id'] = offense['id'] # Set overall success if any fails report['success'] = False except Exception as e: logger.error( 'Failed to create alert from QRadar offense (retrieving offenses failed)', exc_info=True) report['success'] = False report['message'] = "%s: Failed to create alert from offense" % str(e) return report