def _fn_aws_iam_update_access_key_function(self, event, *args, **kwargs):
        """Function: Update status of an IAM user access key.
        Change the status of an access key from Active to Inactive, or vice versa.

        param aws_iam_user_name: An IAM user name.
        param aws_iam_access_key_id: An IAM user access key id.
        param aws_iam_status: An IAM user access key taget status.
        """
        try:
            params = transform_kwargs(kwargs) if kwargs else {}
            # Instantiate result payload object
            rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)
            # Get the function parameters:
            aws_iam_user_name = kwargs.get("aws_iam_user_name")  # text
            aws_iam_access_key_id = kwargs.get("aws_iam_access_key_id")  # text
            aws_iam_status = \
                self.get_select_param(kwargs.get("aws_iam_status"))  # select, values: "Active", "Inactive"

            LOG.info("aws_iam_user_name: %s", aws_iam_user_name)
            LOG.info("aws_iam_access_key_id: %s", aws_iam_access_key_id)
            LOG.info("aws_iam_status: %s", aws_iam_status)

            validate_fields(["aws_iam_user_name", "aws_iam_access_key_id", "aws_iam_status"], kwargs)

            iam_cli = AwsIamClient(self.options)

            rtn = iam_cli.post("update_access_key", **params)
            results = rp.done(True, rtn)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)

        except Exception as aws_err:
            LOG.exception("ERROR with Exception '%s' in Resilient Function for AWS IAM.", aws_err.__repr__())
            yield FunctionError()
Beispiel #2
0
    def _greynoise_ip_query_function(self, event, *args, **kwargs):
        """Function: Perform IP Address analysis"""
        try:
            # Get the function parameters:
            greynoise_value = kwargs.get("greynoise_value")  # text
            greynoise_type = self.get_select_param(kwargs.get("greynoise_type"))  # select

            log = logging.getLogger(__name__)
            log.info("greynoise_value: %s", greynoise_value)
            log.info("greynoise_type: %s", greynoise_type)

            # validate input
            validate_fields(("greynoise_type", "greynoise_value"), kwargs)
            validate_fields(("api_key"), self.options)

            yield StatusMessage("starting...")

            # build result
            result_payload = ResultPayload(SECTION_HEADER, **kwargs)

            greynoise_result = call_greynoise(self.opts, self.options, greynoise_type, greynoise_value)

            results = result_payload.done(True, greynoise_result)

            yield StatusMessage("done...")

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Beispiel #3
0
    def _panorama_get_address_groups_function(self, event, *args, **kwargs):
        """Function: Panorama get address groups returns the list of address groups """
        try:
            yield StatusMessage("Getting list of Address Groups")
            rp = ResultPayload("fn_pa_panorama", **kwargs)

            validate_fields(["panorama_name_parameter"], kwargs)

            # Get the function parameters:
            location = self.get_select_param(
                kwargs.get("panorama_location"))  # select
            vsys = kwargs.get("panorama_vsys")  # text
            name = kwargs.get(
                "panorama_name_parameter")  # text (optional parameter)

            # Log inputs
            if location is None:
                raise ValueError("panorama_location needs to be set.")
            log.info("panorama_location: {}".format(location))
            log.info("panorama_vsys: {}".format(vsys))
            log.info("panorama_name_parameter: {}".format(name))

            panorama_util = PanoramaClient(self.opts, location, vsys)
            response = panorama_util.get_address_groups(name)

            yield StatusMessage("{} groups returned.".format(
                response["result"]["@count"]))
            results = rp.done(True, response)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            yield FunctionError(e)
    def _create_a_schedule_function(self, event, *args, **kwargs):
        incident_id = kwargs.get("incident_id")  # number
        log.info("incident_id: %s", incident_id)

        try:
            rc = ResultPayload(SECTION_SCHEDULER, **kwargs)

            # Produce a FunctionResult with the results
            scheduler = ResilientScheduler.get_scheduler()
            jobs = scheduler.get_jobs()

            list_jobs = []

            for job in jobs:
                job_json = ResilientScheduler.sanitize_job(job)
                params = list(job_json['args'])

                if incident_id is None or incident_id == 0 or \
                    incident_id == params[0]:
                    list_jobs.append(job_json)

            log.debug(list_jobs)
            if not list_jobs:
                yield StatusMessage("No scheduled jobs")

            result = rc.done(True, list_jobs)
            yield FunctionResult(result)
        except Exception:
            yield FunctionError()
    def _mitre_tactic_information_function(self, event, *args, **kwargs):
        """Function: Get information about MITRE tactic"""
        try:
            # Get the function parameters:
            mitre_tactic_id = kwargs.get("mitre_tactic_id")  # text
            mitre_tactic_name = kwargs.get("mitre_tactic_name")  # text

            log = logging.getLogger(__name__)
            log.info("mitre_tactic_id: %s", mitre_tactic_id)
            log.info("mitre_tactic_name: %s", mitre_tactic_name)

            if not mitre_tactic_id and not mitre_tactic_name:
                raise ValueError("Neither name nor id is provided for getting tactic information.")

            result_payload = ResultPayload("fn_mitre_integration", mitre_tactic_id=mitre_tactic_id,
                                           mitre_tactic_name=mitre_tactic_name)
            yield StatusMessage("starting...")
            yield StatusMessage("query MITRE STIX TAXII server, and it can take several minutes....")

            tactics = mitre_attack_utils.get_tactics_and_techniques(tactic_names=mitre_tactic_name,
                                                                    tactic_ids=mitre_tactic_id, opts=self.opts,
                                                                    function_opts=self.options)
            yield StatusMessage("done...")

            results = {
                "mitre_tactics": tactics
            }
            # Produce a FunctionResult with the results
            yield FunctionResult(result_payload.done(True, results))
        except Exception as e:
            log.exception(str(e))
            yield FunctionError()
Beispiel #6
0
    def _fn_proofpoint_trap_get_incident_details_function(
            self, event, *args, **kwargs):
        """Function: Fetch Incident Details from Proofpoint TRAP"""

        try:
            params = transform_kwargs(kwargs) if kwargs else {}
            rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)
            # Get the function parameters:
            trap_incident_id = kwargs.get("trap_incident_id")  # number

            LOG.info("trap_incident_id: %s", trap_incident_id)

            validate_fields(["trap_incident_id"], kwargs)

            pptr = PPTRClient(self.opts, self.options)
            rtn = pptr.get_incident_details(**params)
            if isinstance(rtn, dict) and "error" in rtn:
                results = rtn
            else:
                results = rp.done(True, rtn)
                results["data"] = rtn["data"]
                results["href"] = rtn["href"]

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            LOG.exception(
                "Exception in Resilient Function for Proofpoint TRAP.")
            yield FunctionError()
Beispiel #7
0
    def _fn_aws_iam_delete_login_profile_function(self, event, *args, **kwargs):
        """Function: Delete the password for the specified IAM user, which terminates the user's ability
        to access AWS services through the AWS Management Console.

        param aws_iam_user_name: An IAM user name.
        """
        try:
            params = transform_kwargs(kwargs) if kwargs else {}
            # Instantiate result payload object
            rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)
            # Get the function parameters:
            aws_iam_user_name = kwargs.get("aws_iam_user_name")  # text

            LOG.info("aws_iam_user_name: %s", aws_iam_user_name)

            validate_fields(["aws_iam_user_name"], kwargs)

            iam_cli = AwsIamClient(self.options)

            rtn = iam_cli.post("delete_login_profile", **params)
            results = rp.done(True, rtn)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)

        except Exception as aws_err:
            LOG.exception("ERROR with Exception '%s' in Resilient Function for AWS IAM.", aws_err.__repr__())
            yield FunctionError()
Beispiel #8
0
    def _fn_aws_iam_delete_user_function(self, event, *args, **kwargs):
        """Function: Delete the specified IAM user.

        Note: When deleting an IAM user programmatically, you must delete the items attached
        to the user or the deletion fails.

        param aws_iam_user_name: An IAM user name.
        """
        try:
            params = transform_kwargs(kwargs) if kwargs else {}
            # Instantiate result payload object
            rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)
            # Get the function parameters:
            aws_iam_user_name = kwargs.get("aws_iam_user_name")  # text

            LOG.info("aws_iam_user_name: %s", aws_iam_user_name)

            validate_fields(["aws_iam_user_name"], kwargs)

            iam_cli = AwsIamClient(self.options)

            rtn = iam_cli.post("delete_user", **params)
            results = rp.done(True, rtn)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)

        except Exception as aws_err:
            LOG.exception(
                "ERROR with Exception '%s' in Resilient Function for AWS IAM.",
                aws_err.__repr__())
            yield FunctionError()
Beispiel #9
0
    def _url_to_dns_function(self, event, *args, **kwargs):
        """Function: url_to_dns parses a URL string and returns a string containing DNS value"""
        try:
            # Initialize the results payload
            rp = ResultPayload(PACKAGE_NAME, **kwargs)

            # Validate fields
            validate_fields(['urltodns_url'], kwargs)

            # Get the function parameters:
            urltodns_url = kwargs.get("urltodns_url")  # text

            LOG.info("urltodns_url: %s", urltodns_url)

            yield StatusMessage("starting...")
            url = urlparse(urltodns_url)
            dns = "{}".format(url.netloc)
            yield StatusMessage("Integration Complete")

            content = {"dns": dns}

            results = rp.done(True, content)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)

        except Exception as err:
            LOG.error(err)
            yield FunctionError(err)
    def _incident_utils_close_incident_function(self, event, *args, **kwargs):
        """Function: Function that takes a JSON String of field and value pairs to close an Incident."""
        try:
            # Get the function parameters:
            incident_id = kwargs.get("incident_id")  # number
            close_fields = kwargs.get("close_fields")  # text

            # Check JSON string and convert it to dict
            if close_fields is None:
                close_fields = {}
            else:
                close_fields = json.loads(close_fields)

            log = logging.getLogger(__name__)
            log.info("incident_id: %s", incident_id)
            log.info("close_fields: %s", close_fields)

            rp = ResultPayload(PACKAGE_NAME, **kwargs)

            yield StatusMessage("starting...")
            # Instansiate new Resilient API object
            res_client = self.rest_client()

            # API call to Close an Incident
            response = close_incident(res_client, incident_id, close_fields)

            results = rp.done(True, response.json())

            yield StatusMessage("done...")

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Beispiel #11
0
    def _fn_sep_get_file_content_as_base64_function(self, event, *args, **kwargs):
        """Function: Get the contents of an uploaded binary file, in base64 format."""
        try:
            params = transform_kwargs(kwargs) if kwargs else {}
            # Instantiate result payload object.
            rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)

            # Get the function parameters:
            sep_file_id = kwargs.get("sep_file_id")  # text

            LOG.info("sep_file_id: %s", sep_file_id)

            validate_fields(["sep_file_id"], kwargs)

            yield StatusMessage("Running Symantec SEP Get File Content as Base64 ...")

            sep = Sepclient(self.options, params)

            rtn = base64.b64encode(sep.get_file_content(**params)).decode("utf-8")

            results = rp.done(True, rtn)

            yield StatusMessage("Returning 'Symantec SEP Get File Content as Base64' results")

            LOG.debug(json.dumps(results["content"]))

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            LOG.exception("Exception in Resilient Function for Symantec SEP.")
            yield FunctionError()
Beispiel #12
0
    def _pt_integration_c_process_added_artifact_function(
            self, event, *args, **kwargs):
        """Function: Processes the Artifact added. Just returns a success = True"""
        try:
            log = logging.getLogger(__name__)

            # Instansiate ResultPayload
            rp = ResultPayload(PACKAGE_NAME, **kwargs)

            mandatory_fields = [
                "pt_int_artifact_id", "pt_int_artifact_description",
                "pt_int_artifact_value"
            ]

            # Get the function inputs:
            fn_inputs = validate_fields(mandatory_fields, kwargs)

            log.info("Processing Artifact: %s",
                     fn_inputs.get("pt_int_artifact_id"))

            results_content = {
                "artifact_description":
                fn_inputs.get("pt_int_artifact_description")
            }

            results = rp.done(True, results_content)

            log.info("Returning results to post-process script")

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Beispiel #13
0
    def _fn_proofpoint_trap_get_list_members_function(self, event, *args,
                                                      **kwargs):
        """Function: Retrieve all the members of a Threat Response list."""
        try:
            params = transform_kwargs(kwargs) if kwargs else {}
            rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)
            # Get the function parameters:
            trap_list_id = kwargs.get("trap_list_id")  # number
            trap_member_id = kwargs.get("trap_member_id ")  # number
            trap_members_type = self.get_select_param(
                kwargs.get(
                    "trap_members_type"))  # select, values: "members.json"

            LOG.info("trap_list_id: %s", trap_list_id)
            LOG.info("trap_member_id: %s", trap_member_id)
            LOG.info("trap_members_type: %s", trap_members_type)

            validate_fields(["trap_list_id", "trap_members_type"], kwargs)

            pptr = PPTRClient(self.opts, self.options)
            rtn = pptr.get_list_members(**params)

            results = rp.done(True, rtn)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            LOG.exception(
                "Exception in Resilient Function for Proofpoint TRAP.")
            yield FunctionError()
Beispiel #14
0
    def _exchange_online_delete_email_function(self, event, *args, **kwargs):
        """Function: Delete a message in the specified user's mailbox."""
        try:
            # Initialize the results payload
            rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)

            # Validate fields
            validate_fields(['exo_email_address', 'exo_messages_id'], kwargs)

            # Get the function parameters
            email_address = kwargs.get('exo_email_address')  # text
            mailfolders_id = kwargs.get('exo_mailfolders_id')  # text
            messages_id = kwargs.get('exo_messages_id')  # text

            LOG.info(u"exo_email_address: %s", email_address)
            LOG.info(u"exo_mailfolders_id: %s", mailfolders_id)
            LOG.info(u"exo_messages_id: %s", messages_id)

            yield StatusMessage(
                u"Starting delete message for email address: {}".format(
                    email_address))

            # Get the MS Graph helper class
            MS_graph_helper = MSGraphHelper(
                self.options.get("microsoft_graph_token_url"),
                self.options.get("microsoft_graph_url"),
                self.options.get("tenant_id"), self.options.get("client_id"),
                self.options.get("client_secret"),
                self.options.get("max_messages"),
                self.options.get("max_users"),
                self.options.get("max_retries_total", MAX_RETRIES_TOTAL),
                self.options.get("max_retries_backoff_factor",
                                 MAX_RETRIES_BACKOFF_FACTOR),
                self.options.get("max_batched_requests", MAX_BATCHED_REQUESTS),
                RequestsCommon(self.opts, self.options).get_proxies())

            # Call MS Graph API to get the user profile
            response = MS_graph_helper.delete_message(email_address,
                                                      mailfolders_id,
                                                      messages_id)

            # If message was deleted a 204 code is returned.
            if response.status_code == 204:
                success = True
                response_json = {'value': success}
            else:
                success = False
                response_json = response.json()

            results = rp.done(success, response_json)

            yield StatusMessage(
                u"Returning delete results for email address: {}".format(
                    email_address))

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as err:
            LOG.error(err)
            yield FunctionError(err)
    def _fn_proofpoint_trap_delete_list_member_function(
            self, event, *args, **kwargs):
        """Function: Delete the member of a list."""
        try:
            params = transform_kwargs(kwargs) if kwargs else {}

            rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)

            # Get the function parameters:
            trap_list_id = kwargs.get("trap_list_id")  # number
            trap_member_id = kwargs.get("trap_member_id")  # number

            LOG.info("trap_list_id: %s", trap_list_id)
            LOG.info("trap_member_id: %s", trap_member_id)

            validate_fields(["trap_list_id", "trap_member_id"], kwargs)

            pptr = PPTRClient(self.opts, self.options)
            rtn = pptr.delete_list_member(**params)

            results = rp.done(True, rtn)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            LOG.exception(
                "Exception in Resilient Function for Proofpoint TRAP.")
            yield FunctionError()
Beispiel #16
0
    def _urlhaus_submission(self, event, *args, **kwargs):
        """Function: Takes a url and submits it to urlhaus as distributing malware"""
        try:
            # Get the function parameters:
            artifact_url = kwargs.get("urlhaus_artifact_value")  # text

            log = logging.getLogger(__name__)
            log.info("artifact_value: %s", artifact_url)

            payload_builder = ResultPayload(FunctionComponent.INTEGRATION_NAME,
                                            **self.options)

            jsonData = {
                'token': self.api_key,
                'anonymous': '0',
                'submission': [{
                    'url': artifact_url,
                    'threat': 'malware_download'
                }]
            }

            rc = requests.post(self.submit_url,
                               json=jsonData,
                               headers=FunctionComponent.JSON_HEADERS)

            if rc.status_code != 200:
                raise FunctionError(rc.status)

            results_payload = payload_builder.done(True, rc.text)

            # Produce a FunctionResult with the results
            yield FunctionResult(results_payload)
        except Exception:
            yield FunctionError()
    def _url_void_function(self, event, *args, **kwargs):
        """Function: Retrieves information of a URL from the  URL Void database."""
        try:
            yield StatusMessage("URL Void function started...")
            rp = ResultPayload("fn_url_void", **kwargs)

            # Add support for Requests Common
            req_common = RequestsCommon(self.opts, self.options)

            api_key = self.options.get("api_key")
            identifier = self.options.get("identifier", "api1000")

            # Get the function parameters:
            artifact_value = kwargs.get("artifact_value")  # text
            url_void_endpoint = self.get_select_param(kwargs.get("url_void_endpoint", "Retrieve"))  # select
            validate_fields(["artifact_value", "url_void_endpoint"], kwargs)

            log.info("artifact_value: %s", artifact_value)
            log.info("url_void_endpoint: %s", url_void_endpoint)

            response = call_url_void_api(req_common, artifact_value, identifier, api_key, url_void_endpoint)

            yield StatusMessage("URL Void function completed successfully...")
            results = rp.done(True, response)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            yield FunctionError(e)
Beispiel #18
0
    def _urlhaus_lookup(self, event, *args, **kwargs):
        """Function: Takes different artifacts such as URLs, domain names, IP addresses and hashes and sends it to urlhaus for analysis"""
        try:
            # Get the function parameters:
            artifact_value = kwargs.get("urlhaus_artifact_value")  # text
            artifact_type = kwargs.get("urlhaus_artifact_type")  # text

            log = logging.getLogger(__name__)
            log.info("artifact_value: %s", artifact_value)
            log.info("artifact_type: %s", artifact_type)

            # build a std payload
            payload_builder = ResultPayload(FunctionComponent.INTEGRATION_NAME,
                                            **self.options)

            submission_url, submission_payload = self.build_submission_payload(
                artifact_type, artifact_value)

            rc = requests.post(submission_url,
                               submission_payload,
                               headers=FunctionComponent.HTTP_HEADERS)
            if rc.status_code != 200:
                raise FunctionError(rc.status)

            yield StatusMessage("Query Status: {}".format(
                rc.json()["query_status"]))

            results_payload = payload_builder.done(True, rc.json())

            # Produce a FunctionResult with the results
            yield FunctionResult(results_payload)
        except Exception:
            yield FunctionError()
    def _network_device_config_function(self, event, *args, **kwargs):
        """Function: function to connect with firewalls via ssh to perform configuration changes.
         This integration uses the netMiko library to access the hosts.
        """
        try:
            # Get the function parameters:
            netdevice_ids = kwargs.get("netdevice_ids")  # text
            netdevice_config = kwargs.get("netdevice_config_cmd")  # text

            log = logging.getLogger(__name__)
            log.info("netdevice_ids: %s", netdevice_ids)
            log.info("netdevice_config: %s", netdevice_config)

            if not netdevice_config:
                raise ValueError("Specify netdevice_config_cmd")

            yield StatusMessage("starting...")

            result_payload = ResultPayload(FunctionComponent.SECTION_HDR,
                                           **kwargs)

            rc, result = self._run_netdevice(netdevice_ids, None,
                                             netdevice_config, False)

            status = result_payload.done(rc, result)

            yield StatusMessage("done")

            # Produce a FunctionResult with the results
            yield FunctionResult(status)
        except Exception:
            yield FunctionError()
Beispiel #20
0
    def _funct_zia_get_url_categories_function(self, event, *args, **kwargs):
        """Function: None"""
        try:
            rp = ResultPayload(PACKAGE_NAME, **kwargs)

            # Get the wf_instance_id of the workflow this Function was called in
            wf_instance_id = event.message["workflow_instance"][
                "workflow_instance_id"]

            yield StatusMessage(
                "Starting '{0}' running in workflow '{1}'".format(
                    FN_NAME, wf_instance_id))

            # Get and validate required function inputs:
            fn_inputs = validate_fields([], kwargs)

            LOG.info("'{0}' inputs: %s", fn_inputs)

            if fn_inputs.get("zia_category_id") and fn_inputs.get(
                    "zia_custom_only").lower() == "false":
                raise ValueError(
                    "If parameter '{0}' is set then parameter '{1}' should be set to '{2}'."
                    .format("zia_category_id", "zia_custom_only", "true"))

            # Test any enabled filters to ensure they are valid regular expressions.
            for f in ["zia_name_filter", "zia_url_filter"]:
                patt = fn_inputs.get(f)
                if patt and not is_regex(patt):
                    raise ValueError(
                        "The query filter '{}' does not have a valid regular expression."
                        .format(repr(f)))

            # Remove 'zia_' prefix from function parameters.
            fn_inputs = dict(
                (k.split('_', 1)[1], v) for k, v in fn_inputs.items())

            yield StatusMessage(
                "Validations complete. Starting business logic")

            ziacli = ZiaClient(self.opts, self.fn_options)
            result = ziacli.get_url_categories(**fn_inputs)

            yield StatusMessage(
                "Finished '{0}' that was running in workflow '{1}'".format(
                    FN_NAME, wf_instance_id))

            results = rp.done(True, result)

            LOG.info("'%s' complete", FN_NAME)

            yield StatusMessage(
                "Returning results for function '{}' with parameters '{}'.".
                format(
                    FN_NAME, ", ".join("{!s}={!r}".format(k, v)
                                       for (k, v) in fn_inputs.items())))

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            yield FunctionError(e)
    def _have_i_been_pwned_get_breaches_function(self, event, *args, **kwargs):
        """Function: Get all breaches of an email address from Have I Been Pwned."""
        try:
            yield StatusMessage("starting...")

            result_payload = ResultPayload("hibp", **kwargs)

            log = logging.getLogger(__name__)

            # Get the function parameters:
            email_address = kwargs.get("email_address")  # text
            if email_address is not None:
                log.info("email_address: %s", email_address)
            else:
                raise ValueError(
                    "email_address is required to run this function")

            breach_url = "{0}/{1}".format(HAVE_I_BEEN_PWNED_BREACH_URL,
                                          email_address)
            try:
                breach_results = self.hibp.execute_call(breach_url)
            except IntegrationError as err:
                yield FunctionError(err)

            results = {"Breaches": breach_results}

            yield StatusMessage("done...")
            # Produce a FunctionResult with the results
            yield FunctionResult(result_payload.done(True, results))
        except Exception as e:
            yield FunctionError(e)
Beispiel #22
0
    def _mcafee_epo_find_a_system_function(self, event, *args, **kwargs):
        """Function: Find an ePO system based on property such as system name, tag, IP address, MAC address, etc."""
        try:
            # Get the function parameters:
            validate_fields(["mcafee_epo_systems"], kwargs)
            mcafee_epo_systems = kwargs.get("mcafee_epo_systems")  # text
            client = init_client(self.opts, self.options)

            log = logging.getLogger(__name__)
            log.info("mcafee_epo_systems: %s", mcafee_epo_systems)

            yield StatusMessage("Starting")

            rc = ResultPayload(PACKAGE_NAME, **kwargs)

            params = {"searchText": mcafee_epo_systems.strip()}
            response = client.request("system.find", params)

            yield StatusMessage("Finished")

            results = rc.done(True, response)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
    def _fn_sep_move_endpoint_function(self, event, *args, **kwargs):
        """Function: Checks and moves a client computer to a specified group."""
        try:
            params = transform_kwargs(kwargs) if kwargs else {}
            # Instantiate result payload object.
            rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)

            # Get the function parameters:
            sep_groupid = kwargs.get("sep_groupid")  # text
            sep_hardwarekey = kwargs.get("sep_hardwarekey")  # text

            LOG.info("sep_groupid: %s", sep_groupid)
            LOG.info("sep_hardwarekey: %s", sep_hardwarekey)

            validate_fields(["sep_groupid", "sep_hardwarekey"], kwargs)

            yield StatusMessage("Running Symantec SEP Move Endpoint action...")

            sep = Sepclient(self.options, params)
            rtn = sep.move_endpoint(**params)

            results = rp.done(True, rtn)
            yield StatusMessage(
                "Returning 'Symantec SEP Move Endpoint' results")

            LOG.debug(json.dumps(results["content"]))

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            LOG.exception("Exception in Resilient Function for Symantec SEP.")
            yield FunctionError()
Beispiel #24
0
    def _query_staxx_indicator(self, event, *args, **kwargs):
        """Function: """
        try:
            validate_fields(['staxx_ip', 'staxx_port', 'staxx_user', 'staxx_password'], self.options)
            validate_fields(["staxx_indicator"], kwargs)

            rc = ResultPayload(STAXX_SECTION, **kwargs)
            # Get the function parameters:
            staxx_indicator = kwargs.get("staxx_indicator")  # text
            staxx_max_results = kwargs.get("staxx_max_results", DEFAULT_MAX_RESULTS)  # text

            log = logging.getLogger(__name__)

            yield StatusMessage(u"Querying for indicator {}".format(staxx_indicator))

            staxx = StaxxClient("https://{}:{}".format(self.staxx_ip,self.staxx_port),
                                self.staxx_user,
                                self.staxx_password,
                                RequestsCommon(self.opts, self.options)
                                )

            query = u"value = '{}'".format(staxx_indicator)

            try:
                staxx_response = staxx.query(query=query, size=staxx_max_results)
            except Exception as err:
                err = "Error Staxx query: {}".format(str(err))
                raise FunctionError(err)

            results = rc.done(True, staxx_response, reason=None)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
    def _panorama_edit_address_group_function(self, event, *args, **kwargs):
        """Function: Panorama edit address group edits an address group,
        ie: add or remove ip addresses from the group"""
        try:
            yield StatusMessage("Editing address group...")
            rp = ResultPayload("fn_pa_panorama", **kwargs)

            validate_fields(["panorama_name_parameter", "panorama_request_body"], kwargs)

            # Get the function parameters:
            location = self.get_select_param(kwargs.get("panorama_location"))  # select
            vsys = kwargs.get("panorama_vsys")  # text
            name = kwargs.get("panorama_name_parameter")  # text
            body = self.get_textarea_param(kwargs.get("panorama_request_body"))  # textarea

            # Log inputs
            if location is None:
                raise ValueError("panorama_location needs to be set.")
            log.info("panorama_location: {}".format(location))
            log.info("panorama_vsys: {}".format(vsys))
            log.info("panorama_name_parameter: {}".format(name))
            log.info("panorama_request_body: {}".format(body))

            panorama_util = PanoramaClient(self.opts, location, vsys)
            response = panorama_util.edit_address_groups(name, body)

            yield StatusMessage("Address Group Updated")
            results = rp.done(True, response)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            yield FunctionError(e)
Beispiel #26
0
    def _mitre_groups_technique_intersection_function(self, event, *args,
                                                      **kwargs):
        """Function: For given Techniques return the Groups that are know to use all of them."""
        try:
            # Get the wf_instance_id of the workflow this Function was called in
            wf_instance_id = event.message["workflow_instance"][
                "workflow_instance_id"]

            # Get the function parameters:
            mitre_technique_name = kwargs.get("mitre_technique_name")  # text
            mitre_technique_id = kwargs.get("mitre_technique_id")  # text

            log = logging.getLogger(__name__)
            log.info("mitre_technique_name: %s", mitre_technique_name)
            log.info("mitre_technique_id: %s", mitre_technique_id)

            result_payload = ResultPayload(
                "fn_mitre_integration",
                mitre_technique_name=mitre_technique_name,
                mitre_technique_id=mitre_technique_id)

            if not mitre_technique_id and not mitre_technique_name:
                raise ValueError(
                    "At least one of the inputs(mitre_technique_name or mitre_technique_id) "
                    "should be provided.")

            yield StatusMessage("Getting technique information...")

            mitre_conn = mitre_attack.MitreAttackConnection()

            techniques = mitre_attack_utils.get_multiple_techniques(
                mitre_conn,
                mitre_technique_ids=mitre_technique_id,
                mitre_technique_names=mitre_technique_name)

            intersection_query = ",".join([t.id for t in techniques])

            yield StatusMessage("Getting group intersection information...")
            groups = mitre_attack.MitreAttackGroup.get_by_technique_intersection(
                mitre_conn, techniques)

            if len(groups) == 0:
                yield StatusMessage(
                    "No groups were found using all of the given techniques. Done"
                )
            else:
                yield StatusMessage("Done. Returning results.")

            # Storing the techniques specified to query this group
            for group in groups:
                group.technique_id = intersection_query

            groups = [x.dict_form()
                      for x in groups]  # prepare the data for viewing

            results = {"mitre_groups": groups}
            # Produce a FunctionResult with the results
            yield FunctionResult(result_payload.done(True, results))
        except Exception as e:
            yield FunctionError(e)
    def _ansible_tower_list_job_templates_function(self, event, *args,
                                                   **kwargs):
        """Function: List available job templates"""
        try:
            # validate key app.config settings
            validate_fields(("url"), self.options)

            # Get the function parameters:
            tower_project = kwargs.get("tower_project")  # text
            template_pattern = kwargs.get("tower_template_pattern")  # text

            log = logging.getLogger(__name__)
            log.info("tower_project: %s", tower_project)
            log.info("tower_template_pattern: %s", template_pattern)

            result = ResultPayload(SECTION_HDR, **kwargs)

            # PUT YOUR FUNCTION IMPLEMENTATION CODE HERE
            yield StatusMessage("starting...")
            json_templates = get_job_template_by_project(
                self.opts, self.options, tower_project, template_pattern)

            result_payload = result.done(True, json_templates)
            yield StatusMessage("done...")

            # Produce a FunctionResult with the results
            yield FunctionResult(result_payload)
        except Exception:
            yield FunctionError()
    def _fn_aws_iam_list_user_access_key_ids_function(self, event, *args,
                                                      **kwargs):
        """Function: Get information about the access key IDs associated with the specified IAM user.

        param aws_iam_user_name: An IAM user name.
        """
        try:
            params = transform_kwargs(kwargs) if kwargs else {}
            # Instantiate result payload object
            rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)
            # Get the function parameters:
            aws_iam_user_name = kwargs.get("aws_iam_user_name")  # text

            LOG.info("aws_iam_user_name: %s", aws_iam_user_name)

            validate_fields(["aws_iam_user_name"], kwargs)

            iam_cli = AwsIamClient(self.options)

            rtn = iam_cli.get("list_access_keys", paginate=True, **params)
            for j in range(len(rtn)):
                rtn[j]["key_last_used"] = \
                    iam_cli.get("get_access_key_last_used",
                                AccessKeyId=rtn[j]['AccessKeyId'])
            results = rp.done(True, rtn)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)

        except Exception as aws_err:
            LOG.exception(
                "ERROR with Exception '%s' in Resilient Function for AWS IAM.",
                aws_err.__repr__())
            yield FunctionError()
Beispiel #29
0
    def _fn_aws_iam_list_signing_certs_function(self, event, *args, **kwargs):
        """Function: List the signing certificates associated with an IAM user.

        param aws_iam_user_name: An IAM user name.
        """
        try:
            params = transform_kwargs(kwargs) if kwargs else {}
            # Instantiate result payload object
            rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)

            aws_iam_user_name = kwargs.get("aws_iam_user_name")  # text

            LOG.info("aws_iam_user_name: %s", aws_iam_user_name)

            validate_fields(["aws_iam_user_name"], kwargs)

            iam_cli = AwsIamClient(self.options)

            rtn = iam_cli.get("list_signing_certificates",
                              paginate=True,
                              **params)

            results = rp.done(True, rtn)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)

        except Exception as aws_err:
            LOG.exception(
                "ERROR with Exception '%s' in Resilient Function for AWS IAM.",
                aws_err.__repr__())
            yield FunctionError()
    def _isitphishing_url_function(self, event, *args, **kwargs):
        """Function: isitphishing_url
        This function takes URL string as a required parameter.  It
        queries the Vade Secure isiphishing API to analyze the
        URL to determine if it is PHISHING or SPAM.
        The results contain the result of the query in 'contents' and the
        URL input parameter to the function.
        """
        try:
            rp = ResultPayload(PACKAGE_NAME, **kwargs)

            # Get the function parameters:
            isitphishing_url = kwargs.get("isitphishing_url")  # text

            log = logging.getLogger(__name__)
            log.info("isitphishing_url: %s", isitphishing_url)

            # Form the URL for API request.
            API_URL = u"{0}/url".format(self.options["isitphishing_api_url"])

            # Get the license key to access the API endpoint.
            auth_token = get_license_key(self.options["isitphishing_name"],
                                         self.options["isitphishing_license"])

            # Build the header and the data payload.
            headers = {
                "Authorization": u'Bearer {}'.format(auth_token),
                "Content-type": "application/json",
            }

            payload = {
                "url": isitphishing_url,
                "force": False,
                "smart": True,
                "timeout": 8000
            }

            yield StatusMessage(
                "Query IsItPhishing.org endpoint for status of URL {0}.".
                format(isitphishing_url))

            # Make URL request
            rc = RequestsCommon(self.opts, self.options)
            response = rc.execute_call_v2("post",
                                          API_URL,
                                          json=payload,
                                          headers=headers,
                                          proxies=rc.get_proxies())
            if response.status_code == 200:
                success = True
            else:
                success = False

            response_json = response.json()
            results = rp.done(success, response_json)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as err:
            yield FunctionError(err)