def run(): """Execute the block.""" try: if len(sys.argv) < 2 or sys.argv[1] != "--execute": print("FATAL Unsupported execution mode (expected --execute flag)", file=sys.stderr) sys.exit(1) logger = ModularAction.setup_logger("greynoise_context_modworkflow") # Initialize the alert action class class alert_base = GreyNoiseContextCheck(sys.stdin.read(), logger, "greynoise_context_check") # fetch context information alert_base.fetch_context() # This is standard chrome for outer exception handling except Exception as error: # adding additional logging since adhoc search invocations do not write to stderr try: alert_base.message(str(error), status='failure', level=logging.CRITICAL) except Exception: logger.critical(error) print("ERROR: %s" % str(error), file=sys.stderr) sys.exit(3)
import re, os import traceback ## Importing the cim_actions.py library ## A. Import make_splunkhome_path ## B. Append your library path to sys.path ## C. Import ModularAction from cim_actions ## D. Import ModularActionTimer from cim_actions from splunk.clilib.bundle_paths import make_splunkhome_path sys.path.append(make_splunkhome_path(["etc", "apps", "Splunk_SA_CIM", "lib"])) from cim_actions import ModularAction, ModularActionTimer ## Retrieve a logging instance from ModularAction ## It is required that this endswith _modalert logger = ModularAction.setup_logger('databricks_modalert') ## Subclass ModularAction for purposes of implementing ## a script specific dowork() method class NotebookModularAction(ModularAction): ## This method will initialize NotebookModularAction def __init__(self, settings, logger, action_name=None): ## Call ModularAction.__init__ super(NotebookModularAction, self).__init__(settings, logger, action_name) ## Initialize param.limit try: self.limit = int(self.configuration.get('limit', 1)) if self.limit < 1 or self.limit > 30:
import csv import gzip import json import logging import re import splunk.rest as rest import sys import time from splunk.clilib.bundle_paths import make_splunkhome_path from splunk.util import mktimegm sys.path.append(make_splunkhome_path(['etc', 'apps', 'Splunk_TA_ueba', 'lib'])) from cim_actions import ModularAction logger = ModularAction.setup_logger('send2uba_modalert') ipv4_re = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\/\d{1,2})?$') # http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses ipv6_re = re.compile( r"""^( ([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| ([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}| ([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}| ([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}| ([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}| ([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}| [0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})| :((:[0-9a-fA-F]{1,4}){1,7}|:)| [fF][eE]80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}| ::([fF]{4}(:0{1,4}){0,1}:){0,1}
# # process guid was not running on sensor # logger.info("Guid: {0} was NOT found on sensor".format(guid)) self.addevent("Guid: {0} was NOT found on sensor".format(guid), sourcetype="bit9.carbonblack:action") return False if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] != "--execute": print >> sys.stderr, "FATAL Unsupported execution mode (expected --execute flag)" sys.exit(1) try: logger = ModularAction.setup_logger('killprocess_modalert') modaction = KillProcessAction(sys.stdin.read(), logger, 'killprocess') except Exception as e: logger.critical(str(e)) sys.exit(3) try: session_key = modaction.session_key modaction.addinfo() ## process results if not os.path.exists(modaction.results_file): logger.info( "No results available to process: %s does not exist, exiting." % modaction.results_file) sys.exit(0)
self.wfapi.submit(url=url) except pan.wfapi.PanWFapiError as e: if str(e).startswith("HTTP Error 422: Unprocessable Entities") \ or str(e).startswith("HTTP Error 418: Unsupport File Type"): self.logger.debug("URL is not a file that can be processed by WildFire: %s" % url) else: raise e self.resultcount += 1 if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] != "--execute": print("FATAL Unsupported execution mode (expected --execute flag)", file=sys.stderr) sys.exit(1) logger = ModularAction.setup_logger('panwildfiresubmit_modalert') try: modaction = PanWildFireSubmitModularAction(sys.stdin.read(), logger, 'panwildfiresubmit') session_key = modaction.session_key if logger.isEnabledFor(logging.DEBUG): logger.debug('%s', json.dumps(modaction.settings, sort_keys=True, indent=4, separators=(',', ': '))) ## process results with gzip.open(modaction.results_file, 'rb') as fh: for num, result in enumerate(csv.DictReader(fh)): ## set rid to row # (0->n) if unset result.setdefault('rid', str(num)) modaction.update(result) modaction.invoke() modaction.apply(result)
(self.device, ip, self.tags)) self.firewall.userid.register(ip, self.tags) else: self.logger.debug("Unregistering tags on firewall %s: %s - %s" % (self.device, ip, self.tags)) self.firewall.userid.unregister(ip, self.tags) self.resultcount += 1 if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] != "--execute": print >> sys.stderr, "FATAL Unsupported execution mode (expected --execute flag)" sys.exit(1) logger = ModularAction.setup_logger('pantag_modalert') try: modaction = PantagModularAction(sys.stdin.read(), logger, 'pantag') session_key = modaction.session_key if logger.isEnabledFor(logging.DEBUG): logger.debug( '%s', json.dumps(modaction.settings, sort_keys=True, indent=4, separators=(',', ': '))) ## process results with gzip.open(modaction.results_file, 'rb') as fh: for num, result in enumerate(csv.DictReader(fh)): modaction.start()
# modaction.message('Failed to create splunk event: ' + str(e), status='failure',rids=modaction.rids,level=logging.ERROR) #modaction.message('RESULT: ' + str(result), level=logging.ERROR) self.error("Could not isolate sensor: {0}".format(str(e))) logger.exception("Detailed error message") return False if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] != "--execute": print >> sys.stderr, "FATAL Unsupported execution mode (expected --execute flag)" sys.exit(1) try: logger = ModularAction.setup_logger('isolate_modalert') modaction = IsolateSensorAction(sys.stdin.read(), logger, 'isolatesensor') except Exception as e: logger.critical(str(e)) sys.exit(3) try: session_key = modaction.session_key modaction.addinfo() ## process results if not os.path.exists(modaction.results_file): logger.info( "No results available to process: %s does not exist, exiting." % modaction.results_file)
import csv import gzip import json import logging import sys from splunk.clilib.bundle_paths import make_splunkhome_path sys.path.append(make_splunkhome_path(["etc", "apps", "Splunk_SA_CIM", "lib"])) from cim_actions import ModularAction logger = ModularAction.setup_logger('notable_modalert') class NotableModularAction(ModularAction): NOTABLE_MAPS = [ '_time', '_raw', 'splunk_server', 'index', 'source', 'sourcetype', 'host', 'linecount', 'timestartpos', 'timeendpos', 'eventtype', 'tag', 'search_name', 'event_hash', 'event_id' ] def get_notable_mapexp(self): mapfields = self.configuration.get('mapfields', '') ## If it's a pure adhoc case, turn off notable maps. if not mapfields: return None else: self.NOTABLE_MAPS.extend(mapfields.split(',')) return lambda x: (x.startswith('tag::') or x in self.NOTABLE_MAPS)
import csv import gzip import json import logging import splunk.rest as rest import sys import urllib from splunk.clilib.bundle_paths import make_splunkhome_path sys.path.append(make_splunkhome_path(["etc", "apps", "Splunk_SA_CIM", "lib"])) from cim_actions import ModularAction logger = ModularAction.setup_logger('risk_modalert') def normalize_risk_param(modaction, param, default='unknown'): ## configuration will have _param config_param = '_%s' % param ## try result first val = result.get(param) ## next try modular action param if not val: val = modaction.configuration.get(config_param) ## if risk_object val represents key in result if val and param=='risk_object': val = result.get(val) ## next try legacy param if not val: try: r, c = rest.simpleRequest('saved/searches/%s' % urllib.quote_plus(modaction.search_name), sessionKey=modaction.session_key,
# Standard modules specific to this action import ansible_runner # Importing the cim_actions.py library # A. Import make_splunkhome_path # B. Append your library path to sys.path # C. Import ModularAction from cim_actions # D. Import ModularActionTimer from cim_actions from splunk.clilib.bundle_paths import make_splunkhome_path sys.path.append( make_splunkhome_path(["etc", "apps", "TA-haveibeenpwned", "lib"])) from cim_actions import ModularAction, ModularActionTimer # Retrieve a logging instance from ModularAction # It is required that this endswith _modalert logger = ModularAction.setup_logger('haveibeenpwned_modalert') # Subclass ModularAction for purposes of implementing # a script specific dowork() method class AnsibleRunnerModularAction(ModularAction): # This method will initialize AnsibleRunnerModularAction def __init__(self, settings, logger, action_name=None): # Call ModularAction.__init__ super(AnsibleRunnerModularAction, self).__init__(settings, logger, action_name) # Initialize params self.hostpattern = self.configuration.get('hostpattern', 'localhost') self.playbook = self.configuration.get('playbook', None) self.verbose = self.configuration.get('verbose', False)
from splunk.clilib.bundle_paths import make_splunkhome_path else: from splunk.appserver.mrsparkle.lib.util import make_splunkhome_path except ImportError as e: raise ImportError("Import splunk sub libraries failed\n") sys.path.append( make_splunkhome_path(["etc", "apps", "TA-Demisto", "bin", "lib"])) try: from cim_actions import ModularAction except: sys.exit(3) logger = DemistoConfig.get_logger("DEMISTOALERT") modular_action_logger = ModularAction.setup_logger('demisto_modalert') class DemistoAction(ModularAction): def create_demisto_incident(self, result, authkey, verify, search_query="", search_url="", ssl_cert_loc="", search_name=None, proxies=None, url=None): try: logger.info("create_demisto_incident called")
try: return self.do_ban(cb, md5sum) except Exception as e: self.error("Could not ban hash: {0}".format(str(e))) logger.exception("Detailed error message") return False if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] != "--execute": print >> sys.stderr, "FATAL Unsupported execution mode (expected --execute flag)" sys.exit(1) try: logger = ModularAction.setup_logger('banhash_modalert') logger.info("Calling BanHashAction.__init__") modaction = BanHashAction(sys.stdin.read(), logger, 'banhash') logger.info("Returned BanHashAction.__init__") except Exception as e: logger.critical(str(e)) sys.exit(3) try: session_key = modaction.session_key modaction.addinfo() ## process results if not os.path.exists(modaction.results_file): logger.info( "No results available to process: %s does not exist, exiting."
self.wfapi.submit(url=url) except pan.wfapi.PanWFapiError as e: if str(e).startswith("HTTP Error 422: Unprocessable Entities") \ or str(e).startswith("HTTP Error 418: Unsupport File Type"): self.logger.debug("URL is not a file that can be processed by WildFire: %s" % url) else: raise e self.resultcount += 1 if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] != "--execute": print >> sys.stderr, "FATAL Unsupported execution mode (expected --execute flag)" sys.exit(1) logger = ModularAction.setup_logger('panwildfiresubmit_modalert') try: modaction = PanWildFireSubmitModularAction(sys.stdin.read(), logger, 'panwildfiresubmit') session_key = modaction.session_key if logger.isEnabledFor(logging.DEBUG): logger.debug('%s', json.dumps(modaction.settings, sort_keys=True, indent=4, separators=(',', ': '))) ## process results with gzip.open(modaction.results_file, 'rb') as fh: for num, result in enumerate(csv.DictReader(fh)): ## set rid to row # (0->n) if unset result.setdefault('rid', str(num)) modaction.update(result) modaction.invoke() modaction.apply(result)
rids.append( modaction.rid_ntuple(modaction.orig_sid, modaction.rid, modaction.orig_rid)) ## add result for intersplunk output new_results.append(new_result) ## add result for event creation modaction.addevent(new_result['_raw'], 'nbtstat') else: modaction.message('Invalid characters detected in host input', status='failure', level=logging.WARN) if len(new_results) > 0: if modaction.writeevents(index='main', source='nbtstat'): modaction.message('Successfully created splunk event', status='success', rids=rids) else: modaction.message('Failed to create splunk event', status='failure', rids=rids, level=logging.ERROR) splunk.Intersplunk.outputResults(new_results, outputfile=outputfile) if __name__ == '__main__': logger = ModularAction.setup_logger('nbtstat_modworkflow') do_nbtstat(sys.argv, logger=logger)
import json import logging import os import re import splunk.Intersplunk import splunk.util as util import sys import subprocess import time from splunk.clilib.bundle_paths import make_splunkhome_path sys.path.append(make_splunkhome_path(['etc', 'apps', 'SA-Utils', 'lib'])) sys.path.append(make_splunkhome_path(['etc', 'apps', 'Splunk_SA_CIM', 'lib'])) from cim_actions import ModularAction, InvalidResultID logger = ModularAction.setup_logger('ping_modworkflow') def handleError(modaction, signature): modaction.message(signature, status='failure', level=logging.ERROR) results = splunk.Intersplunk.generateErrorResults(signature) splunk.Intersplunk.outputResults(results) sys.exit(1) if __name__ == '__main__': ## defaults ping = None if os.name == 'nt': ping_switch = '-n 4' else:
self.logger.debug("Registering tags on firewall %s: %s - %s" % (self.device, ip, self.tags)) self.firewall.userid.register(ip, self.tags) else: self.logger.debug("Unregistering tags on firewall %s: %s - %s" % (self.device, ip, self.tags)) self.firewall.userid.unregister(ip, self.tags) self.resultcount += 1 if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] != "--execute": print >> sys.stderr, "FATAL Unsupported execution mode (expected --execute flag)" sys.exit(1) logger = ModularAction.setup_logger('pantag_modalert') try: modaction = PantagModularAction(sys.stdin.read(), logger, 'pantag') session_key = modaction.session_key if logger.isEnabledFor(logging.DEBUG): logger.debug('%s', json.dumps(modaction.settings, sort_keys=True, indent=4, separators=(',', ': '))) ## process results with gzip.open(modaction.results_file, 'rb') as fh: for num, result in enumerate(csv.DictReader(fh)): modaction.start() ## set rid to row # (0->n) if unset result.setdefault('rid', str(num)) modaction.update(result) modaction.invoke()
try: return self.do_policychange(cb, device, policy_name, input_type) except Exception as e: self.error("Could not change policy for : {0}".format(str(e))) logger.exception("Detailed error message") return False if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] != "--execute": print >> sys.stderr, "FATAL Unsupported execution mode (expected --execute flag)" sys.exit(1) try: logger = ModularAction.setup_logger('changepolicy_modalert') modaction = ChangePolicyAction(sys.stdin.read(), logger, 'changepolicy') except Exception as e: logger.critical(str(e)) sys.exit(3) try: session_key = modaction.session_key modaction.addinfo() ## process results if not os.path.exists(modaction.results_file): logger.info( "No results available to process: %s does not exist, exiting." % modaction.results_file)