예제 #1
0
def execute(event):

    sourcetype = "bro_dns"

    print("Checking Splunk for events..."),

    sys.stdout.flush()

    sp = Splunk(
        host=SPLUNK_SEARCH_HEAD,
        port=SPLUNK_SEARCH_HEAD_PORT,
        username=SPLUNK_SEARCH_HEAD_USERNAME,
        password=SPLUNK_SEARCH_HEAD_PASSWORD,
        scheme=SPLUNK_SEARCH_HEAD_SCHEME,
    )

    if not event.adHoc:
        if hasattr(event, "ip_address"):
            event._include = 'id_orig_h="%s" OR id_resp_h="%s"' % (event.ip_address, event.ip_address)

    cirtaDT = epochToDatetime(event.cirta_id.split(".")[0])

    timedelta = (datetime.date(event._DT) - datetime.date(cirtaDT)).days

    earliest = timedelta - event._daysBefore

    latest = timedelta + 1 + event._daysAfter

    if earliest >= 0:
        earliest = "+" + str(earliest)

    if latest >= 0:
        latest = "+" + str(latest)

    query = """search eventtype="%s" earliest_time="%sd@d" latest_time="%sd@d" %s | table _raw""" % (
        sourcetype,
        earliest,
        latest,
        event._include,
    )

    log.debug('''msg="raw event query" query="%s"''' % query)

    results = sp.search(query)

    print("Done")

    if not results:
        log.warn("No %s events exist in Splunk" % sourcetype)
        return

    raw = [x["_raw"] for x in results]

    if raw:
        with open("%s.%s" % (event._baseFilePath, confVars.outputExtension), "w") as outFile:
            for row in raw:
                outFile.write(row + "\n")
        print("%s file: %s%s.%s" % (sourcetype, colors.OKGREEN, event._baseFilePath, confVars.outputExtension))

    event._splunk.push(sourcetype=confVars.splunkSourcetype, eventList=raw)
예제 #2
0
def execute(event):
    
    sp = Splunk(host=SPLUNK_SEARCH_HEAD, port=SPLUNK_SEARCH_HEAD_PORT, username=SPLUNK_SEARCH_HEAD_USERNAME, password=SPLUNK_SEARCH_HEAD_PASSWORD, scheme=SPLUNK_SEARCH_HEAD_SCHEME)
        
    query = '''search index=cirta level=INFO msg="quarantine hosts" | head 1 | table _time hosts'''

    print('\nChecking Splunk...'),
        
    results = sp.search(query)

    print('Done\n')
    
     
    if not results:
        log.warn("Unable to retrieve previous quarantine hosts from Splunk")
        exit()
    else:
        hosts = set([x.strip() for x in results[0]['hosts'].split(',')])

    toRemove = getUserMultiChoice("Quarantine Hosts", "Hosts to Unquarantine", hosts, 2)     
    
    remainingHosts = [host for host in hosts if host not in toRemove]
    
    print('')
    print(colors.BOLDON + "Hosts before:     " + colors.BOLDOFF + ' '.join(['"%s"' % x for x in hosts]))
    print(colors.BOLDON + "Hosts to remove:  " + colors.BOLDOFF + ' '.join(['"%s"' % x for x in toRemove]))
    print(colors.BOLDON + "Hosts after:      " + colors.BOLDOFF + ' '.join(['"%s"' % x for x in remainingHosts]))
       
    event.setAttribute('unquarantine_hosts', ' '.join(['"%s"' % x for x in remainingHosts]))
                            
    groupMods = '''config vdom
edit vd-inet
config firewall addrgrp
edit "grp-infosec-blacklist-hosts"
set member %s
next
end
end''' % (event.unquarantine_hosts)

    printStatusMsg('Final FW Change', 22, '>', color=colors.HEADER2)
    print groupMods
    printStatusMsg('Final FW Change', 22, '<', color=colors.HEADER2)
    
    
    if getUserIn('Commit final changes to quarantine state? (y/n)') in YES:
        #print '''msg="quarantine hosts" hosts="%s"''' % (','.join(event.quarantine_hosts.strip('"').split('" "')))
        log.info('''msg="quarantine hosts" hosts="%s"''' % (','.join(event.unquarantine_hosts.strip('"').split('" "'))))
        
예제 #3
0
def execute(event):

    sp = Splunk(host=SPLUNK_SEARCH_HEAD, port=SPLUNK_SEARCH_HEAD_PORT, username=SPLUNK_SEARCH_HEAD_USERNAME, password=SPLUNK_SEARCH_HEAD_PASSWORD, scheme=SPLUNK_SEARCH_HEAD_SCHEME)


    cirtaDT = epochToDatetime(event.cirta_id.split('.')[0])

    timedelta = (event._DT - cirtaDT).days

    earliest = timedelta - 20

    latest = timedelta + 10

    if earliest >= 0:
        earliest = '+' + str(earliest)

    if latest >= 0:
        latest = '+' + str(latest)

    rawQuery = '''search index=mcafee src_ip="%s" OR dest_ip="%s" earliest_time="%sd@d" latest_time="%sd@d" \
                | eval mcafee_id = "mc".substr(detected_timestamp, -5, 2).".".AutoID \
                | sort 0 _time | table _raw''' % (event.ip_address, event.ip_address, earliest, latest)

    print('Checking Splunk Raw...'),

    sys.stdout.flush()

    raw = [x['_raw'] + '\n' for x in sp.search(rawQuery)]
    
    print('Done')

    if not raw:
        print("No results")
        return


    with open("%s.%s" % (event._baseFilePath, 'mc'), 'w') as orf:
        for row in raw:
            orf.write(row)

    #event._splunk.push(sourcetype=confVars.splunkSourcetype, eventList=results)

    query = '''search index=mcafee category!="ops*" threat_type!="none" src_ip="%s" OR dest_ip="%s" earliest_time="%sd@d" latest_time="now" \
               | eval timedelta = _time - %s | eval position = if(timedelta < 0, "before", "after") \
               | eval abstimedelta = abs(timedelta) | sort 0 abstimedelta \
               | head 20 | sort 0 _time | eval mcafee_id = "mc".substr(detected_timestamp, -5, 2).".".AutoID \
               | table _time threat_type vendor_action user src_ip dest_ip signature file_name''' % (event.ip_address, 
                                                                                                                                event.ip_address, 
                                                                                                                                earliest, 
                                                                                                                                datetimeToEpoch(event._DT))

    print('\nChecking Splunk...'),

    sys.stdout.flush()

    results = [x for x in sp.search(query)]

    print('Done')

    if results:
        print("\n_time\t\t\ttype\taction\tuser\tsrc_ip\t\tdest_ip\t\tsignature\t\tfile_name")
        print("-" * 115)
        for result in results:
            print(result['_time'].split('.')[0] + "\t" + '\t'.join(result.values()[1:]))


    event._splunk.push(sourcetype=confVars.splunkSourcetype, eventList=raw)
예제 #4
0
def execute(event):


    sp = Splunk(host=SPLUNK_SEARCH_HEAD, port=SPLUNK_SEARCH_HEAD_PORT, username=SPLUNK_SEARCH_HEAD_USERNAME, password=SPLUNK_SEARCH_HEAD_PASSWORD, scheme=SPLUNK_SEARCH_HEAD_SCHEME)

    if hasattr(event, 'mcAfeeID'):
        event.setAttribute('mcAfeeID', prompt='McAfee ID', header= '', force=True)
    else:
        event.setAttribute('mcAfeeID', prompt='McAfee ID', header="McAfee Initial Indicator")

    event.setAttribute('alertID', event.mcAfeeID, force=True)
    event.setAttribute('alertType', 'McAfee', force=True)

    query = '''search index=mcafee earliest=-30d@d | eval mcafee_id = "mc".substr(detected_timestamp, -5, 2).".".AutoID | search mcafee_id="%s" | head 1 | table detected_timestamp src_ip src_mac dest_ip dest_mac signature category''' % (event.mcAfeeID)

    print('\nChecking Splunk...'),

    sys.stdout.flush()

    results = sp.search(query)

    print('Done')

    try:
        result = results.next()
    except(StopIteration):
        log.warn("Error: unable to pull McAfee ID event details from Splunk")
        exit()

    event.setOutPath(event.mcAfeeID)

    timestamp = epochToDatetime(result['detected_timestamp'][:-3])

    srcIP = result['src_ip']
    srcMAC = result['src_mac']
    dstIP = result['dest_ip']
    dstMAC = result['dest_mac']
    secondaryName = result['signature']
    name = result['category']
    signature = '%s %s' % (name, secondaryName)


    # Note the utc offset for the US will always be -x so by adding the offset you are adding a negative, i.e. subtracting
    # This is very important for accurate time conversion.  You should always add the offset if the time is in UTC and
    # subtract the offset if the time is local.  If the reverse makes more sense to you, event._absUTCOffsetTimeDelta
    # is available
    # Also note, setEventDateTime is called twice to initialize utcOffsetTimeDelta then adjust.
    #event.setEventDateTime(datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S'))
    event.setEventDateTime(timestamp)
    event.setEventDateTime(event._DT)

    print('\nLocal Timestamp      Source IP        Destination IP   Signature')
    print('-' * 80)
    print('%-20s %-16s %-16s %s\n' % (event._DT.strftime('%Y-%m-%d %H:%M:%S'), srcIP, dstIP, signature))

    event.setAttribute('Event_Date/Time', event._DT.strftime('%Y-%m-%d %H:%M:%S'))

    ans = getUserInWithDef('Track source or destination (s/d)', 's')
    if 's' in ans:
        if srcIP:
            event.setAttribute('ip_address', srcIP)
        else:
            event.setAttribute('ip_address', prompt="\nIP Address")
        #if srcMAC:
        #    event.setAttribute('mac_address', srcMAC)
    elif 'd' in ans:
        if dstIP:
            event.setAttribute('ip_address', dstIP)
        else:
            event.setAttribute('ip_address', prompt="\nIP Address")
        #if dstMAC:
        #    event.setAttribute('mac_address', dstMAC)
    else:
        event.setAttribute('ip_address', prompt='IP Address', default=ans, description='Neither the source or destination was chosen, please confirm.')

    print('')

    event.setAttribute('description', prompt='Description', default=signature)
    event.setDateRange()
예제 #5
0
def execute(event):
    
    sp = Splunk(host=SPLUNK_SEARCH_HEAD, port=SPLUNK_SEARCH_HEAD_PORT, username=SPLUNK_SEARCH_HEAD_USERNAME, password=SPLUNK_SEARCH_HEAD_PASSWORD, scheme=SPLUNK_SEARCH_HEAD_SCHEME)
    
    rawQuery = '''search index=fireeye | spath alert.src.ip | spath alert.dst.ip | search alert.src.ip="%s" OR alert.dst.ip="%s" | sort 0 _time | table _raw''' % (event.ip_address, event.ip_address)

    print('Checking Splunk Raw...'),
    
    sys.stdout.flush()

    results = sp.search(rawQuery)
    #print results
    #except(error):
    #    print('Warning: Splunk query failed.\n')
    #    raise error
    
    print('Done')
    
    if not results:
        print("No results")
        return
    
    with open("%s.%s" % (event._baseFilePath, 'fe'), 'w') as orf:
        for log in results:
            orf.write(log['_raw'])
    
    query = '''search index=fireeye | spath alert.id | spath alert.product | spath alert.sensor | spath alert.occurred | spath alert.src.ip | spath alert.src.mac | spath alert.dst.ip | spath alert.dst.mac | spath alert.name | spath output="malware.names" "alert.explanation.malware-detected.malware{}.name" | search alert.src.ip="%s" OR alert.dst.ip="%s" | sort 0 _time | table alert.occurred alert.product alert.sensor alert.id alert.src.ip alert.src.mac alert.dst.ip alert.dst.mac alert.name malware.names''' % (event.ip_address, event.ip_address)

    print('\nChecking Splunk...'),
    #try:
    #print query
        
    sys.stdout.flush()

    results = [x for x in sp.search(query)]
    #print results
    #except(error):
    #    print('Warning: Splunk query failed.\n')
    #    raise error
    
    print('Done')
    
    if not results:
        print("No results")
        return
    
    headers = ['alert.occurred', 'alert.sensor', 'alert.id',
               'alert.src.ip', 'alert.dst.ip',  
               'alert.name', 'malware.names']

    event.__fireeyeIDs__ = [x['alert.id'] for x in results]
    
    with open("%s.%s" % (event._baseFilePath, 'fef'), 'w') as orf:
        orf.write("%s\t\t%s" % (headers[0], '\t'.join(headers[1:]) + '\n'))
        print("\n%s\t\t%s" % (headers[0], '\t'.join(headers[1:])))
        print('-'*120)
        for log in results:
            entry = []
            for header in headers:
                if header in log:
                    if 'malware.names' in header:
                        if isinstance(log[header], list):
                            entry.append('|'.join(log[header]))
                        else:
                            entry.append(log[header])
                    else:
                        entry.append(log[header])
                else:
                    entry.append('')
            orf.write('\t'.join(entry) + '\n')
            print('\t'.join(entry))

    mac = ''                
    if event.ip_address == results[0].get('alert.src.ip', ''):
        mac = results[0].get('alert.src.mac', '')
    elif event.ip_address == results[0].get('alert.dst.ip', ''):
        mac = results[0].get('alert.dst.mac', '')
        
    if mac and '84:78:ac' not in mac:
        event.setAttribute('mac_address', mac)
예제 #6
0
def execute(event):

    print('Checking Splunk for events...'),


    sys.stdout.flush()

    sp = Splunk(host=SPLUNK_SEARCH_HEAD, port=SPLUNK_SEARCH_HEAD_PORT, username=SPLUNK_SEARCH_HEAD_USERNAME, password=SPLUNK_SEARCH_HEAD_PASSWORD, scheme=SPLUNK_SEARCH_HEAD_SCHEME)

    if not event.adHoc:
        if hasattr(event, 'mac_address'):
            event._include = 'EndPointMACAddress="%s"' % (event.mac_address.replace(":", "-"))

    cirtaDT = epochToDatetime(event.cirta_id.split('.')[0])

    timedelta = (datetime.date(event._DT) - datetime.date(cirtaDT)).days

    earliest = timedelta - event._daysBefore

    latest = timedelta + 1 + event._daysAfter

    if earliest >= 0:
        earliest = '+' + str(earliest)

    if latest >= 0:
        latest = '+' + str(latest)

    log.debug('DT="%s" cirtaDT="%s" timedelta="%s" daysBefore="%s" daysAfter="%s" earliest="%s" latest="%s"' % (event._DT, cirtaDT, (event._DT - cirtaDT).days, event._daysBefore, event._daysAfter, earliest, latest))

    query = '''search index=cisco_ise earliest_time="%sd@d" latest_time="%sd@d" %s | table _raw''' % (earliest,
                                                                                                     latest,
                                                                                                     event._include)

    log.debug('''msg="raw event query" query="%s"''' % query)

    results = sp.search(query)

    print('Done')

    if not results:
        log.warn("No Infoblox events exist in Splunk")
        return

    raw = [x['_raw'] for x in results]

    with open('%s.%s' % (event._baseFilePath, confVars.outputExtension), 'w') as outFile:
        for row in raw:
            outFile.write(row + '\n')

    event._splunk.push(sourcetype=confVars.splunkSourcetype, eventList=raw)

    print('\nChecking Splunk for Hostname and MAC...'),

    sys.stdout.flush()

    query = '''search index=cisco_ise earliest_time="%sd@d" latest_time="%sd@d" %s | eval timedelta = abs(_time - %s) | sort 0 timedelta | where isnotnull(AD_User_Resolved_Identities) | rex field=AD_User_Resolved_Identities "(?<user>.+)@" | head 1 | rename NetworkDeviceGroups AS network_device_groups Location AS location EndPointMatchedProfile AS device_type AD_Domain as domain | table user network_device_groups location device_type domain''' % (earliest, latest, event._include, datetimeToEpoch(event._DT))

    log.debug('''msg="raw event query" query="%s"''' % query)

    results = [x for x in sp.search(query)]

    print('Done')
    '''
예제 #7
0
def execute(event):
    
    print('\nChecking Splunk for events...'),

    sys.stdout.flush()

    sp = Splunk(host=SPLUNK_SEARCH_HEAD, port=SPLUNK_SEARCH_HEAD_PORT, username=SPLUNK_SEARCH_HEAD_USERNAME, password=SPLUNK_SEARCH_HEAD_PASSWORD, scheme=SPLUNK_SEARCH_HEAD_SCHEME)
    
    if not event.adHoc:
        if hasattr(event, 'ip_address'):
            event._include = 'src="%s" OR dest="%s"' % (event.ip_address, event.ip_address)

    cirtaDT = epochToDatetime(event.cirta_id.split('.')[0])

    timedelta = (datetime.date(event._DT) - datetime.date(cirtaDT)).days

    earliest = timedelta - event._daysBefore

    latest = timedelta + 1 + event._daysAfter

    if earliest >= 0:
        earliest = '+' + str(earliest)

    if latest >= 0:
        latest = '+' + str(latest)

    
    query = '''search index=fortinet earliest_time="%sd@d" latest_time="%sd@d" %s | table _raw''' % (earliest, 
                                                                                                     latest, 
                                                                                                     event._include)
    
    log.debug('''msg="raw event query" query="%s"''' % query)

    results = sp.search(query)
    
    print('Done')
    
    if not results:
        log.warn("No Juniper events exist in Splunk")
        return
    
    raw = [x['_raw'] for x in results]
    
    with open('%s.%s' % (event._baseFilePath, confVars.outputExtension), 'w') as outFile:
        for row in raw:
            outFile.write(row + '\n')
    
    event._splunk.push(sourcetype=confVars.splunkSourcetype, eventList=raw)


    sid = sp.getLatestSID()

    print('\nChecking Splunk for user...'),
    
    query = '''search index=juniper earliest_time="%sd@d" latest_time="%sd@d" %s | eval timedelta = abs(_time - %s) | sort 0 timedelta | where isnotnull(user) | head 1 | table user''' % (earliest, latest, event._include, datetimeToEpoch(event._DT))
                
    results = sp.search(query)
        
    print('Done')
        
    if results and 'user' in results[0]:
        event.setAttribute('username', results[0]['user'].lower())
    else:
        log.warn("Warning: unable to pull Fortinet user from Splunk")

    print('\nChecking Splunk for surrounding events...'),

    query = '''search index=fortinet earliest_time="%sd@d" latest_time="%sd@d" %s | eval timedelta = abs(_time - %s) | sort 0 timedelta | search type=utm | head 500 | eval uri = coalesce(hostname, dstip) + url | dedup uri | head 50 | sort 0 -_time | table _time srcip user status uri''' % (earliest, latest, event._include, datetimeToEpoch(event._DT))
    query = '''search index=fortinet type=utm earliest_time="%sd@d" latest_time="%sd@d" %s | regex url!="\.jpg$|\.png$|\.gif$|\.crl$" | eval timedelta = _time - %s | eval position = if(timedelta < 0, "before", "after") | eval abstimedelta = abs(timedelta) | sort 0 abstimedelta | dedup hostname url | streamstats count AS row by position | where row <= 25 | eval uri = coalesce(hostname, dstip) + url | sort 0 _time | table _time srcip user status uri''' % (earliest, latest, event._include, datetimeToEpoch(event._DT))

    log.debug('''msg="raw event query" query="%s"''' % query)
        
    results = sp.search(query)
        
    print('Done')
        
    if not results:
        log.warn("Warning: unable to pull surrounding Fortinet events from Splunk")
        return

    if hasattr(event, '_vturls'):
        event._vturls.extend([x['uri'] for x in results])
    else:
        event._vturls = [x['uri'] for x in results]
    print('')
예제 #8
0
def execute(event):
    def normMV(prompt, result, field):
        if result.get(field):
            value = result[field]
            if isinstance(value, list):
                if len(set(value)) > 1:
                    return ", ".join(
                        getUserMultiChoice(
                            prompt, "Selection", list(set(value)), numCols=1, default=[value[-1]], allowMultiple=False
                        )
                    )
                else:
                    return value[0]
            elif value:
                return value

        return ""

    sp = Splunk(
        host=SPLUNK_SEARCH_HEAD,
        port=SPLUNK_SEARCH_HEAD_PORT,
        username=SPLUNK_SEARCH_HEAD_USERNAME,
        password=SPLUNK_SEARCH_HEAD_PASSWORD,
        scheme=SPLUNK_SEARCH_HEAD_SCHEME,
    )

    if not sp.connected:
        log.warn(
            "FireEye initializer requires the Splunk API, please ensure your Splunk instance is available for API connections"
        )
        exit()

    if hasattr(event, "fireID"):
        event.setAttribute("fireID", prompt="FireEye ID", header="", force=True)
    else:
        event.setAttribute("fireID", prompt="FireEye ID", header="FireEye Initial Indicator")

    event.setAttribute("alertID", event.fireID, force=True)
    event.setAttribute("alertType", "FireEye", force=True)

    query = """search index=fireeye earliest_time=-60d 
| spath output="alert_id" alert.id 
| spath output="alert_id_mv" "alert{}.id" 
| eval alert_id = coalesce(alert_id, alert_id_mv)
| spath output="alert_product" alert.product 
| spath output="alert_product_mv" "alert{}.product" 
| eval  alert_product = coalesce(alert_product, alert_product_mv)
| spath output="alert_sensor" alert.sensor 
| spath output="alert_sensor_mv" "alert{}.sensor" 
| eval  alert_sensor = coalesce(alert_sensor, alert_sensor_mv)
| spath output="alert_occurred" alert.occurred 
| spath output="alert_occurred_mv" "alert{}.occurred" 
| eval  alert_occurred = coalesce(alert_occurred, alert_occurred_mv)
| spath output="alert_src_ip" alert.src.ip 
| spath output="alert_src_ip_mv" "alert{}.src.ip" 
| eval  alert_src_ip = coalesce(alert_src_ip, alert_src_ip_mv)
| spath output="alert_src_mac" alert.src.mac 
| spath output="alert_src_mac_mv" "alert{}.src.mac" 
| eval  alert_src_mac = coalesce(alert_src_mac, alert_src_mac_mv)
| spath output="alert_dst_ip" alert.dst.ip 
| spath output="alert_dst_ip_mv" "alert{}.dst.ip" 
| eval  alert_dst_ip = coalesce(alert_dst_ip, alert_dst_ip_mv)
| spath output="alert_dst_mac" alert.dst.mac 
| spath output="alert_dst_mac_mv" "alert{}.dst.mac" 
| eval  alert_dst_mac = coalesce(alert_dst_mac, alert_dst_mac_mv)
| spath output="alert_name" alert.name 
| spath output="alert_name_mv" "alert{}.name" 
| eval  alert_name = coalesce(alert_name, alert_name_mv)
| spath output="malware_names" "alert.explanation.malware-detected.malware{}.name" 
| spath output="malware_names_mv" "alert{}.explanation.malware-detected.malware{}.name" 
| eval  malware_names = coalesce(malware_names, malware_names_mv)
| search alert_id="%s"
| table alert_occurred alert_product alert_sensor alert_id alert_src_ip alert_src_mac alert_dst_ip alert_dst_mac alert_name malware_names""" % (
        event.fireID
    )

    print("\nChecking Splunk..."),

    sys.stdout.flush()

    results = sp.search(query)

    print("Done")

    try:
        result = results.next()
    except (StopIteration):
        log.warn("Error: unable to pull FireEye ID event details from Splunk")
        exit()

    event.setOutPath(event.fireID)

    product = normMV("Product", result, "alert_product")
    sensor = normMV("Sensor", result, "alert_sensor")

    printStatusMsg("%s - %s" % (product, sensor))

    occurred = normMV("Occurred", result, "alert_occurred")
    if "T" in occurred:
        timestamp = datetime.datetime.strptime(occurred, "%Y-%m-%dT%H:%M:%SZ").strftime("%Y-%m-%d %H:%M:%S")
    else:
        timestamp = occurred.split("+")[0]

    srcIP = normMV("Source IP", result, "alert_src_ip")
    srcMAC = normMV("Source Mac", result, "alert_src_mac")
    dstIP = normMV("Destination IP", result, "alert_dst_ip")
    dstMAC = normMV("Destination Mac", result, "alert_dst_mac")
    secondaryName = normMV("Secondary Alert Name", result, "malware_names")
    name = normMV("Alert Name", result, "alert_name")
    signature = "%s %s" % (name, secondaryName)

    """
    if isinstance(malwareNames, list):
        secondaryName = ', '.join(getUserMultiChoice('Secondary Alert Name', 'Selection', malwareNames, numCols=1, default=[malwareNames[-1]], allowMultiple=False))
    else:
        secondaryName = malwareNames
    """

    # Note the utc offset for the US will always be -x so by adding the offset you are adding a negative, i.e. subtracting
    # This is very important for accurate time conversion.  You should always add the offset if the time is in UTC and
    # subtract the offset if the time is local.  If the reverse makes more sense to you, event._absUTCOffsetTimeDelta
    # is available
    # Also note, setEventDateTime is called twice to initialize utcOffsetTimeDelta then adjust.
    event.setEventDateTime(datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S"))
    event.setEventDateTime(event._DT + event._utcOffsetTimeDelta)

    print("\nLocal Timestamp      Source IP        Destination IP   Signature")
    print("-" * 80)
    print("%-20s %-16s %-16s %s\n" % (event._DT.strftime("%Y-%m-%d %H:%M:%S"), srcIP, dstIP, signature))

    event.setAttribute("Event_Date/Time", event._DT.strftime("%Y-%m-%d %H:%M:%S"))

    if "CMS" in product:
        event.setAttribute("ip_address", prompt="IP Address")
    else:
        ans = getUserInWithDef("Track source or destination (s/d)", "s")
        if "s" in ans:
            if srcIP:
                event.setAttribute("ip_address", srcIP)
            else:
                event.setAttribute("ip_address", prompt="\nIP Address")
            # if srcMAC:
            #    event.setAttribute('mac_address', srcMAC)
        elif "d" in ans:
            if dstIP:
                event.setAttribute("ip_address", dstIP)
            else:
                event.setAttribute("ip_address", prompt="\nIP Address")
            # if dstMAC:
            #    event.setAttribute('mac_address', dstMAC)
        else:
            event.setAttribute(
                "ip_address",
                prompt="IP Address",
                default=ans,
                description="Neither the source or destination was chosen, please confirm.",
            )

    print("")

    event.setAttribute("description", prompt="Description", default=signature)
    event.setDateRange()
예제 #9
0
def execute(event):

    print('Checking Splunk for events...'),


    sys.stdout.flush()

    sp = Splunk(host=SPLUNK_SEARCH_HEAD, port=SPLUNK_SEARCH_HEAD_PORT, username=SPLUNK_SEARCH_HEAD_USERNAME, password=SPLUNK_SEARCH_HEAD_PASSWORD, scheme=SPLUNK_SEARCH_HEAD_SCHEME)

    if not event.adHoc:
        if hasattr(event, 'ip_address'):
            event._include = 'src="%s"' % (event.ip_address)

    cirtaDT = epochToDatetime(event.cirta_id.split('.')[0])

    timedelta = (datetime.date(event._DT) - datetime.date(cirtaDT)).days

    earliest = timedelta - event._daysBefore

    latest = timedelta + 1 + event._daysAfter

    if earliest >= 0:
        earliest = '+' + str(earliest)

    if latest >= 0:
        latest = '+' + str(latest)

    log.debug('DT="%s" cirtaDT="%s" timedelta="%s" daysBefore="%s" daysAfter="%s" earliest="%s" latest="%s"' % (event._DT, cirtaDT, (event._DT - cirtaDT).days, event._daysBefore, event._daysAfter, earliest, latest))

    query = '''search index=infoblox earliest_time="%sd@d" latest_time="%sd@d" %s | table _raw''' % (earliest,
                                                                                                     latest,
                                                                                                     event._include)

    log.debug('''msg="raw event query" query="%s"''' % query)

    results = sp.search(query)

    print('Done')

    if not results:
        log.warn("No Infoblox events exist in Splunk")
        return

    raw = [x['_raw'] for x in results]

    with open('%s.%s' % (event._baseFilePath, confVars.outputExtension), 'w') as outFile:
        for row in raw:
            outFile.write(row + '\n')

    event._splunk.push(sourcetype=confVars.splunkSourcetype, eventList=raw)

    print('\nChecking Splunk for Hostname and MAC...'),

    sys.stdout.flush()


    if event.adHoc:
        query = '''search index=infoblox earliest_time="%sd@d" latest_time="%sd@d" %s | stats first(hostname) AS hostname first(src_mac) AS src_mac''' % (earliest, latest, event._include)
    else:
        query = '''search index=infoblox earliest_time="%sd@d" latest_time="%sd@d" %s | eval timedelta = %s -_time | where timedelta >= 0 | sort 0 timedelta | stats first(hostname) AS hostname first(src_mac) AS src_mac''' % (earliest, latest, event._include, datetimeToEpoch(event._DT))

    log.debug('''msg="raw event query" query="%s"''' % query)

    results = [x for x in sp.search(query)]

    print('Done')

    if results and 'src_mac' in results[0]:
        event.setAttribute('mac_address', results[0]['src_mac'].lower())
    else:
        log.warn("Warning: unable to pull Infoblox MAC from Splunk")

    if results and 'hostname' in results[0]:
        event.setAttribute('hostname', results[0]['hostname'].lower())
    else:
        log.warn("Warning: unable to pull Infoblox hostname from Splunk")


    print('')