示例#1
0
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)
示例#2
0
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:
示例#3
0
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}
示例#4
0
                #
                # 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)
示例#5
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)
示例#6
0
文件: pantag.py 项目: TPLink32/spnk1
                              (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)
示例#8
0
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)
示例#9
0
文件: risk.py 项目: reza/es_eventgens
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)
示例#11
0
        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")
示例#12
0
        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)
示例#14
0
def do_nbtstat(argv,
               input_str=None,
               outputfile=sys.stdout,
               logger=logging.getLogger('dummy')):
    ## defaults
    nbtstat = None
    orig_sid = None
    orig_rid = None
    host = None
    host_field = None
    MAX_RESULTS = 1
    max_results = 1
    host_validation = '^([A-Za-z0-9\.\_\-]+)$'
    ip_rex = re.compile('^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$')

    the_time = util.mktimegm(time.gmtime())

    ## retrieve results and settings
    results, dummyresults, settings = splunk.Intersplunk.getOrganizedResults(
        input_str)
    logger.debug(settings)
    ## modular action hooks
    modaction_payload = {
        'sid': settings.get('sid', ''),
        'owner': settings.get('owner'),
        'app': settings.get('namespace')
    }
    modaction = ModularAction(json.dumps(modaction_payload),
                              logger,
                              action_name="nbtstat")

    ## override defaults w/ opts below
    if len(argv) > 1:
        for a in argv:
            if a.startswith('host=') or a.startswith('dest='):
                where = a.find('=')
                host = a[where + 1:len(a)]
            elif a.startswith('host_field=') or a.startswith('dest_field='):
                where = a.find('=')
                host_field = a[where + 1:len(a)]
            elif a.startswith('orig_sid='):
                where = a.find('=')
                orig_sid = a[where + 1:len(a)]
            elif a.startswith('orig_rid'):
                where = a.find('=')
                orig_rid = a[where + 1:len(a)]
            elif a.startswith('max_results'):
                where = a.find('=')
                max_results = a[where + 1:len(a)]
    try:
        if int(max_results) > 0:
            MAX_RESULTS = int(max_results)
    except:
        pass
    logger.info('max_results setting determined: %s', MAX_RESULTS)

    handleError = errorHandler(modaction, outputfile, logger)
    ## validate presence of host/host_field
    if not host and not host_field:
        signature = 'Must specify either host or host_field'
        handleError(signature)
        return
    ## set up single result
    if host:
        host_field = 'host'
        result = {'host': host}
        if orig_sid and orig_rid:
            result.update({'orig_sid': orig_sid, 'orig_rid': orig_rid})
        results = [result]
    ## process result(s)
    new_results = []
    rids = []
    results_processed = 0
    for num, result in enumerate(results):
        if results_processed >= MAX_RESULTS:
            break
        ## set result id
        result.setdefault('rid', str(num))
        ## update and invoke
        modaction.update(result)
        modaction.invoke()
        ## validate host_field is present in result
        if host_field not in result:
            signature = 'host_field not present in result set'
            handleError(signature)
            return
        else:
            ## handle MV
            hosts = result[host_field].split('\n')
        ## iterate hosts (as MV is a possibility)
        for host in hosts:
            if results_processed >= MAX_RESULTS:
                break
            results_processed += 1
            ## validate host value but don't exit
            if re.match(host_validation, host):
                ip_match = ip_rex.match(host)
                ## set up new result which will be sent back to splunk
                new_result = {
                    '_time': the_time,
                    'sid': modaction.sid,
                    'rid': modaction.rid,
                    'dest': host
                }
                if modaction.orig_sid and modaction.orig_rid:
                    new_result.update({
                        'orig_sid': modaction.orig_sid,
                        'orig_rid': modaction.orig_rid
                    })
                ## determine nbtstat_cmd
                if os.name == 'nt':
                    if ip_match:
                        nbtstat_cmd = ['nbtstat', '-A', host]
                    else:
                        nbtstat_cmd = ['nbtstat', '-a', host]
                elif sys.platform == 'darwin':
                    if ip_match:
                        nbtstat_cmd = None
                        modaction.message(
                            'Unable to perform reverse netbios lookup',
                            status='failure',
                            level=logging.WARN)
                    else:
                        nbtstat_cmd = ['smbutil', 'lookup', host]
                else:
                    if ip_match:
                        nbtstat_cmd = ['nmblookup', '-A', host]
                    else:
                        nbtstat_cmd = ['nmblookup', host]
                ## do nbtstat
                if nbtstat_cmd:
                    try:
                        nbtstat = subprocess.Popen(nbtstat_cmd,
                                                   stdout=subprocess.PIPE)
                        new_result['_raw'] = nbtstat.communicate()[0]
                    except Exception:
                        signature = 'Exception when executing nbtstat command'
                        handleError(signature)
                        return
                    ## add to successful rid list
                    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)
示例#15
0
                    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)
示例#16
0
文件: ping.py 项目: reza/es_eventgens
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)