コード例 #1
0
def _create_alert_config(rule, match):

    context = {'rule': rule, 'match': match}

    alert_config = {
        'artifacts': _create_artifacts(rule, match),
        'sourceRef': str(uuid.uuid4())[0:6],
        'title': '{rule[name]}'.format(**context)
    }

    alert_config.update(rule.get('hive_alert_config', {}))

    for alert_config_field, alert_config_value in alert_config.items():
        if alert_config_field == 'customFields':
            custom_fields = CustomFieldHelper()
            for cf_key, cf_value in alert_config_value.items():
                try:
                    func = getattr(custom_fields, 'add_{}'.format(cf_value['type']))
                except AttributeError:
                    raise Exception('unsupported custom field type {}'.format(cf_value['type']))
                value = cf_value['value'].format(**context)
                func(cf_key, value)
            alert_config[alert_config_field] = custom_fields.build()
        elif isinstance(alert_config_value, str):
            alert_config[alert_config_field] = alert_config_value.format(**context)
        elif isinstance(alert_config_value, (list, tuple)):
            formatted_list = []
            for element in alert_config_value:
                try:
                    formatted_list.append(element.format(**context))
                except (AttributeError, KeyError, IndexError):
                    formatted_list.append(element)
            alert_config[alert_config_field] = formatted_list

    return alert_config
コード例 #2
0
    def alert(self, matches):

        connection_details = self.rule['hive_connection']

        api = TheHiveApi(
            '{hive_host}:{hive_port}'.format(**connection_details),
            connection_details.get('hive_apikey',''),
            proxies=connection_details.get('hive_proxies', {'http': '', 'https': ''}),
            cert=connection_details.get('hive_verify', False))

        for match in matches:
            context = {'rule': self.rule, 'match': match}

            artifacts = []
            for mapping in self.rule.get('hive_observable_data_mapping', []):
                for observable_type, match_data_key in mapping.iteritems():
                    try:
                        match_data_keys = re.findall(r'\{match\[([^\]]*)\]', match_data_key)
                        if all([True for k in match_data_keys if k in context['match']]):
                            artifacts.append(AlertArtifact(dataType=observable_type, data=match_data_key.format(**context)))
                    except KeyError:
                        raise KeyError('\nformat string\n{}\nmatch data\n{}'.format(match_data_key, context))

            alert_config = {
                'artifacts': artifacts,
                'sourceRef': str(uuid.uuid4())[0:6],
                'title': '{rule[name]}'.format(**context)
            }
            alert_config.update(self.rule.get('hive_alert_config', {}))

            for alert_config_field, alert_config_value in alert_config.iteritems():
                if alert_config_field == 'customFields':
                    custom_fields = CustomFieldHelper()
                    for cf_key, cf_value in alert_config_value.iteritems():
                        try:
                            func = getattr(custom_fields, 'add_{}'.format(cf_value['type']))
                        except AttributeError:
                            raise Exception('unsupported custom field type {}'.format(cf_value['type']))
                        value = cf_value['value'].format(**context)
                        func(cf_key, value)
                    alert_config[alert_config_field] = custom_fields.build()
                elif isinstance(alert_config_value, basestring):
                    alert_config[alert_config_field] = alert_config_value.format(**context)
                elif isinstance(alert_config_value, (list, tuple)):
                    formatted_list = []
                    for element in alert_config_value:
                        try:
                            formatted_list.append(element.format(**context))
                        except:
                            formatted_list.append(element)
                    alert_config[alert_config_field] = formatted_list

            alert = Alert(**alert_config)

            response = api.create_alert(alert)

            if response.status_code != 201:
                raise Exception('alert not successfully created in TheHive\n{}'.format(response.text))
コード例 #3
0
    def create_alarm(self,
                     title,
                     source_ref=None,
                     description='N/A',
                     alert_type='external',
                     source='LogRhythm',
                     iocs=None,
                     additional_fields=None,
                     additional_tags=None,
                     tlp=TLP.AMBER,
                     pap=PAP.AMBER,
                     severity=HiveSeverity.MEDIUM):

        if source_ref is None:
            source_ref = str(uuid.uuid4())[0:6]

        alert_tags = self.alert_tags.copy()
        if additional_tags is not None:
            for additional_tag in additional_tags:
                alert_tags.append(additional_tag)

        custom_fields_helper = CustomFieldHelper()
        if additional_fields is not None:
            for field in additional_fields:
                custom_fields_helper.add_string(field['name'], field['value'])
        custom_fields = custom_fields_helper.build()

        artifacts = list()
        if iocs is not None:
            for ioc in iocs:
                artifacts.append(
                    AlertArtifact(dataType=ioc['type'].value,
                                  data=ioc['value']))

        hive_alert = Alert(title=title,
                           tlp=tlp.value,
                           tags=alert_tags,
                           description=description,
                           type=alert_type,
                           source=source,
                           sourceRef=source_ref,
                           pap=pap.value,
                           artifacts=artifacts,
                           customFields=custom_fields,
                           severity=severity.value)

        response = self.api.create_alert(hive_alert)
        if response.status_code == 201:
            print('Alerta Creada Exitosamente')
            print(json.dumps(response.json(), indent=4, sort_keys=True))
        else:
            print('Error')
            print(response.text)

        return response.json()
コード例 #4
0
def CreateHiveAlertFromSentinel(api, title, description, incidentnumber,
                                severity, source, artifacts, alertIds,
                                incidentURL):
    tags = []

    if severity == "Low":
        theHiveSeverity = 1
    elif severity == "Informational":
        theHiveSeverity = 1
    elif severity == "Medium":
        theHiveSeverity = 2
    elif severity == "High":
        theHiveSeverity = 3

    alertIdsStr = ' '.join(map(str, alertIds))

    customFields = CustomFieldHelper()
    customFields.add_number('sentinelIncidentNumber', incidentnumber)
    customFields.add_string('alertIds', alertIdsStr)
    customFields.add_string('incidentURL', incidentURL)

    customFields = customFields.build()
    alert = Alert(title=title,
                  tlp=2,
                  tags=tags,
                  description=description,
                  type='Sentinel',
                  severity=theHiveSeverity,
                  source='Sentinel:' + source,
                  customFields=customFields,
                  sourceRef="Sentinel" + str(incidentnumber),
                  artifacts=artifacts)

    # Create the Alert
    response = api.create_alert(alert)
    if response.status_code == 201:
        logging.info(
            'Alert created: ' + 'Sentinel' + str(incidentnumber) + ': ' +
            source + ': ' + title +
            '. StatusCode: {}/{}'.format(response.status_code, response.text))
    elif (response.status_code == 400
          and response.json()['type'] == "ConflictError"):
        logging.info(
            'Duplicate alert: ' + 'Sentinel' + str(incidentnumber) + ': ' +
            source + ': ' + title +
            '. StatusCode: {}/{}'.format(response.status_code, response.text))
    else:
        logging.error(
            'failed to create alert: ' + source + ' ' + title + ' Sentinel' +
            str(incidentnumber) +
            '. StatusCode: {}/{}'.format(response.status_code, response.text))
        sys.exit(0)
コード例 #5
0
    def create_case(self,
                    title,
                    tasks=None,
                    tlp=TLP.AMBER,
                    pap=PAP.AMBER,
                    severity=HiveSeverity.MEDIUM,
                    additional_fields=None,
                    additional_tags=None,
                    flag=False,
                    description='N/A'):

        case_tags = self.case_tags.copy()
        if additional_tags is not None:
            for additional_tag in additional_tags:
                case_tags.append(additional_tag)

        custom_fields_helper = CustomFieldHelper()
        if additional_fields is not None:
            for field in additional_fields:
                custom_fields_helper.add_string(field['name'], field['value'])
        custom_fields = custom_fields_helper.build()

        new_tasks = list()
        if tasks is not None:
            for task in tasks:
                new_tasks.append(CaseTask(title=task))

        hive_case = Case(title=title,
                         tlp=tlp.value,
                         pap=pap.value,
                         description=description,
                         tags=case_tags,
                         severity=severity.value,
                         flag=flag,
                         customFields=custom_fields,
                         tasks=new_tasks)

        response = self.api.create_case(hive_case)
        if response.status_code == 201:
            print('Caso Creada Exitosamente')
            print(json.dumps(response.json(), indent=4, sort_keys=True))
        else:
            print('Error')
            print(response.text)

        return response.json()
コード例 #6
0
 def build(fields: Dict) -> Dict:
     custom_field_helper = CustomFieldHelper()
     for key, field_value in fields.items():
         if ('time' in key.lower() or 'date' in key.lower()) and isinstance(field_value, int):
             custom_field_helper.add_date(key, field_value * 1000)
         elif isinstance(field_value, datetime):
             custom_field_helper.add_number(key, int(field_value.timestamp()) * 1000)
         elif isinstance(field_value, bool):
             custom_field_helper.add_boolean(key, field_value)
         elif isinstance(field_value, int):
             custom_field_helper.add_number(key, field_value)
         elif isinstance(field_value, str):
             custom_field_helper.add_string(key, field_value)
         else:
             try:
                 custom_field_helper.add_string(key, field_value)
             except (TypeError, ValueError):
                 pass
     return custom_field_helper.build()
コード例 #7
0
                                             'Open'))
            records = qr.get_aql_results(aql_id)
            if records:
                retval = parse_get_aql(records, 'username')
                if retval:
                    for item in retval:
                        if item != None:
                            username_list.append(item)
                            sl.update_record(enrichment_table, 'status',
                                             'Closed', 'enrichment_id', aql_id)

    # # Adding custom_fields values to the case - static mapping.
    custom_fields = CustomFieldHelper()
    custom_fields.add_number('qradar_id', offense_id)
    custom_fields.add_string('offense_source', offense_source)
    custom_fields.build()

    tlp = offense_severity_mapper(offense_magnitude)['sev']

    # #Case - Offense summary md.
    build_desc = """|Offense Summary:|\n|---|\n|Offense Description: {}|\n|Source NW: {}|\n|Destination NW: {}|\n|Source IPs: {}|\n|Local Destination IPs: {}|\n|Remote Destination IPs: {}|\n|Usernames: {}|\n---\nLink to the Offense: {}""".format(
        offense_desc, offense_src_nw, offense_dst_nw, source_address_list,
        local_dest_list, remote_dest_list, username_list, offense_link)

    # #Some sample tasks-response actions for posting in the case. Customize per your reqs.
    # #TODO: You can also utilize - thehive-playbook-creator - for dynamic task/playbook assignment using your QRadar Rule groups.
    tasks = [
        CaseTask(title='PB:- Phase:Identification'),
        CaseTask(title='PB: - Phase:Remediation'),
        CaseTask(title='PB: - Phase:Lessons Learned',
                 status='Waiting',