def _panorama_get_addresses_function(self, event, *args, **kwargs):
        """Function: Panorama get addresses returns a list of the address objects"""
        try:
            yield StatusMessage("Getting list of addresses")
            rp = ResultPayload("fn_pa_panorama", **kwargs)

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

            # 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))

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

            yield StatusMessage("{} addresses 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)
Exemplo n.º 2
0
    def _utilities_base64_to_attachment_function(self, event, *args, **kwargs):
        """Function: Creates a new attachment from a base64 string."""
        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:
            base64content = kwargs.get("base64content")  # text
            incident_id = kwargs.get("incident_id")  # number
            task_id = kwargs.get("task_id")  # number
            file_name = kwargs.get("file_name")  # text
            content_type = kwargs.get("content_type")  # text

            log = logging.getLogger(__name__)
            log.info("base64content: %s", base64content)
            log.info("incident_id: %s", incident_id)
            log.info("task_id: %s", task_id)
            log.info("file_name: %s", file_name)
            log.info("content_type: %s", content_type)

            # PUT YOUR FUNCTION IMPLEMENTATION CODE HERE
            #  yield StatusMessage("starting...")
            #  yield StatusMessage("done...")

            results = {"value": "xyz"}

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Exemplo n.º 3
0
    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)

            yield StatusMessage("starting...")
            yield StatusMessage("query MITRE STIX TAXII server, and it can take several minutes....")

            tactics = mitre_attack_utils.get_techniques(tactic_names=mitre_tactic_name,
                                                        tactic_ids=mitre_tactic_id)

            yield StatusMessage("done...")

            results = {
                "mitre_tactics": tactics
            }

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            log.exception(str(e))
            yield FunctionError()
    def _utilities_json2html_function(self, event, *args, **kwargs):
        """Function: Produces an HTML representation of JSON data. All data is converted into tables of key / value pairs or lists.

Provide an optional parameter `json2html_keys` to limit the JSON data to display."""
        try:

            # 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 'utilities_json2html' running in workflow '{0}'".format(wf_instance_id))

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

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

            ##############################################
            # PUT YOUR FUNCTION IMPLEMENTATION CODE HERE #
            ##############################################

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

            results = {
                "content": "xyz"
            }

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Exemplo n.º 5
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()
Exemplo n.º 6
0
    def _qradar_find_reference_sets_function(self, event, *args, **kwargs):
        """Function: Find reference sets that contain a given item value, together with information about this item in those reference sets. Information includes whether this item is added to the reference set manually or by a rule."""
        try:
            # Get the function parameters:
            qradar_reference_set_item_value = kwargs.get("qradar_reference_set_item_value")  # text

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

            qradar_verify_cert = True
            if "verify_cert" in self.options and self.options["verify_cert"] == "false":
                qradar_verify_cert = False

            log.debug("Connection to {} using {}".format(self.options["host"], self.options["username"]))

            yield StatusMessage("starting...")
            qradar_client = QRadarClient(host=self.options["host"],
                                         username=self.options.get("username", None),
                                         password=self.options.get("qradarpassword", None),
                                         token=self.options.get("qradartoken", None),
                                         cafile=qradar_verify_cert)

            r_items = qradar_client.find_all_ref_set_contains(qradar_reference_set_item_value)

            yield StatusMessage("done...")

            results = {
                "reference_items": r_items
            }

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            log.exception(e)
            yield FunctionError()
    def _utilities_xml_transformation_function(self, event, *args, **kwargs):
        """Function: Transforms an XML document using a preexisting `xsl` stylesheet. The resulting content is returned."""
        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:
            xml_source = kwargs.get("xml_source")  # text
            xml_stylesheet = kwargs.get("xml_stylesheet")  # text

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

            # PUT YOUR FUNCTION IMPLEMENTATION CODE HERE
            #  yield StatusMessage("starting...")
            #  yield StatusMessage("done...")

            results = {"value": "xyz"}

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
    def _mock_function_two_function(self, event, *args, **kwargs):
        """Function: mock description two"""
        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:
            mock_field_one = kwargs.get("mock_field_one")  # text
            mock_field_two = kwargs.get("mock_field_two")  # number

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

            # PUT YOUR FUNCTION IMPLEMENTATION CODE HERE
            #  yield StatusMessage("starting...")
            #  yield StatusMessage("done...")

            results = {"value": "xyz"}

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Exemplo n.º 9
0
    def _event_function(self, event, *args, **kwargs):
        """Function: This is a function implementation that uses the Cisco API to post a Malware event"""
        try:
            rp = ResultPayload(SECTION_NAME, **kwargs)

            url = '/'.join((self.options['url'], 'events?customerKey={}'))
            url = url.format(self.apikey)
            self.log.debug(url)

            data, cisco_dstdomain = self.createdataobject(kwargs)

            rc = RequestsCommon(self.opts, self.options)
            content, msg = rc.execute_call_v2("post",
                                              url,
                                              json=data,
                                              verify=False,
                                              headers=HEADERS,
                                              callback=callback)
            if msg:
                yield StatusMessage(msg)
            else:
                yield StatusMessage(
                    u"Add Domain for '{}' was successful".format(
                        cisco_dstdomain))

            results = rp.done(False if msg else True, None if msg else content,
                              msg)
            # backward compatibility
            results['value'] = None if msg else content

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as err:
            self.log.error(err)
            yield FunctionError(err)
Exemplo n.º 10
0
    def _utilities_attachment_hash_function(self, event, *args, **kwargs):
        """Function: Calculate hashes for a file attachment. Returns `md5`, `sha1`, `sha256` and other hashes of the file content. Those hashes can then be used as artifacts or in other parts of your workflows."""
        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:
            incident_id = kwargs.get("incident_id")  # number
            task_id = kwargs.get("task_id")  # number
            attachment_id = kwargs.get("attachment_id")  # number

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

            # PUT YOUR FUNCTION IMPLEMENTATION CODE HERE
            #  yield StatusMessage("starting...")
            #  yield StatusMessage("done...")

            results = {"value": "xyz"}

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Exemplo n.º 11
0
        def get_input_entity(client, incident_id, attachment_id, artifact_id):
          
          re_uri_match_pattern = r"""(?:(?:https?|ftp):\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?"""
          entity = {"incident_id": incident_id, "id": None, "type": "", "meta_data": None, "data": None}

          if (attachment_id):
            entity["id"] = attachment_id
            entity["type"] = "attachment"
            entity["meta_data"] = client.get("/incidents/{0}/attachments/{1}".format(entity["incident_id"], entity["id"]))
            entity["data"] = client.get_content("/incidents/{0}/attachments/{1}/contents".format(entity["incident_id"], entity["id"]))
          
          elif (artifact_id):
            entity["id"] = artifact_id
            entity["type"] = "artifact"
            entity["meta_data"] = client.get("/incidents/{0}/artifacts/{1}".format(entity["incident_id"], entity["id"]))

            # handle if artifact has attachment
            if (entity["meta_data"]["attachment"]):
              entity["data"] = client.get_content("/incidents/{0}/artifacts/{1}/contents".format(entity["incident_id"], entity["id"]))

            # else handle if artifact.value contains an URI using RegEx
            else:
              match = re.match(re_uri_match_pattern, entity["meta_data"]["value"])

              if (match):
                entity["uri"] = match.group()
            
              else:
                raise FunctionError("Artifact has no attachment or supported URI")
          
          else:
            raise ValueError('attachment_id AND artifact_id both None')

          return entity
    def _phish_ai_scan_url_function(self, event, *args, **kwargs):
        """Function: Scans URL against Phish.AI."""
        try:
            rp = ResultPayload(PACKAGE_NAME, **kwargs)

            yield StatusMessage("starting...")

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

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

            ph = PhishAI(self.opts, self.options)
            response_json = ph.scan_url(artifact_value)

            yield StatusMessage("done...")
            results = rp.done(True, response_json)

            # For backward compatibility with v1.0.0
            results["run_time"] = str(results['metrics']['execution_time_ms'] /
                                      1000)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            yield FunctionError(e)
def get_content(client, incident_id, attachment_id, artifact_id):
    entity = {
        "incident_id": incident_id,
        "id": None,
        "type": "",
        "meta_data": None,
        "data": None
    }

    if attachment_id:
        return client.get_content(
            "/incidents/{0}/attachments/{1}/contents".format(
                entity["incident_id"], attachment_id))

    elif artifact_id:
        entity["meta_data"] = client.get("/incidents/{0}/artifacts/{1}".format(
            entity["incident_id"], artifact_id))

        # handle if artifact has attachment
        if (entity["meta_data"].get("attachment")):
            return client.get_content(
                "/incidents/{0}/artifacts/{1}/contents".format(
                    entity["incident_id"], artifact_id))
        else:
            raise FunctionError("Artifact has no attachment or supported URI")

    else:
        raise ValueError('attachment_id AND artifact_id both None')
    def _utilities_string_to_attachment_function(self, event, *args, **kwargs):
        """Function: Creates a new file (.txt) attachment in the incident or task from a string that your workflow provides as input."""
        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:
            string_to_convert_to_attachment = kwargs.get(
                "string_to_convert_to_attachment")  # text
            attachment_name = kwargs.get("attachment_name")  # text
            incident_id = kwargs.get("incident_id")  # number
            task_id = kwargs.get("task_id")  # number

            log = logging.getLogger(__name__)
            log.info("string_to_convert_to_attachment: %s",
                     string_to_convert_to_attachment)
            log.info("attachment_name: %s", attachment_name)
            log.info("incident_id: %s", incident_id)
            log.info("task_id: %s", task_id)

            # PUT YOUR FUNCTION IMPLEMENTATION CODE HERE
            #  yield StatusMessage("starting...")
            #  yield StatusMessage("done...")

            results = {"value": "xyz"}

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Exemplo n.º 15
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 _bit9_approval_request_get_function(self, event, *args, **kwargs):
        """Function: Get an approval request by ID"""
        try:
            validate_fields(["bit9_approval_request_id"], kwargs)
            # Get the function parameters:
            bit9_approval_request_id = kwargs.get(
                "bit9_approval_request_id")  # number

            log.info(u"bit9_approval_request_id: %s", bit9_approval_request_id)

            bit9_client = CbProtectClient(self.options)
            results = bit9_client.get_approval_request(
                bit9_approval_request_id)

            results[
                "details_url"] = u"https://{}/approval-request-details.php?request_id={}".format(
                    bit9_client.server, bit9_approval_request_id)
            log.info(u"Request Status :%d", results.get("status"))
            log.debug(results)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as err:
            log.error(err)
            yield FunctionError(err)
Exemplo n.º 17
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()
Exemplo n.º 18
0
    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()
Exemplo n.º 19
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()
Exemplo n.º 20
0
    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 _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()
    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)
    def _utilities_attachment_to_base64_function(self, event, *args, **kwargs):
        """Function: Reads a file attachment in the incident, and produces a base64-encoded string with the file attachment content. This content can then be used in combination with other workflow functions to create an artifact, a new file attachment, or to analyze the contents using various tools."""
        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:
            incident_id = kwargs.get("incident_id")  # number
            artifact_id = kwargs.get("artifact_id")  # number
            task_id = kwargs.get("task_id")  # number
            attachment_id = kwargs.get("attachment_id")  # number

            log = logging.getLogger(__name__)
            log.info("incident_id: %s", incident_id)
            log.info("artifact_id: %s", artifact_id)
            log.info("task_id: %s", task_id)
            log.info("attachment_id: %s", attachment_id)

            # PUT YOUR FUNCTION IMPLEMENTATION CODE HERE
            #  yield StatusMessage("starting...")
            #  yield StatusMessage("done...")

            results = {"value": "xyz"}

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
    def _utilities_pdfid_function(self, event, *args, **kwargs):
        """Function: Produces summary information about the structure of a PDF file, using Didier Stevens' pdfid (https://blog.didierstevens.com/programs/pdf-tools/). Provide the PDF file content as a base64-encoded string, for example the output from the “Attachment to Base64” function.

This function is useful in initial triage of suspicious email attachments and other files. It allows you to identify PDF documents that contain (for example) JavaScript or that execute an action when opened. PDFiD also handles name obfuscation. The combination of PDF automatic action and JavaScript makes a document very suspicious."""
        try:

            # 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 'utilities_pdfid' running in workflow '{0}'".format(
                    wf_instance_id))

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

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

            ##############################################
            # PUT YOUR FUNCTION IMPLEMENTATION CODE HERE #
            ##############################################

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

            results = {"content": "xyz"}

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Exemplo n.º 25
0
    def _phish_ai_scan_url_function(self, event, *args, **kwargs):
        """Function: Scans URL against Phish.AI."""
        try:
            start_time = time.time()
            yield StatusMessage("starting...")
            api_key = self.options.get("phishai_api_key", None)

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

            log = logging.getLogger(__name__)
            if artifact_value is not None:
                log.info("artifact_value: %s", artifact_value)
            else:
                raise ValueError("artifact_value needs to be set to run this function.")

            ph = API(api_key=api_key)
            res = ph.scan_url(artifact_value)

            end_time = time.time()
            yield StatusMessage("done...")
            results = {
                "inputs": {
                    "artifact_value": artifact_value
                },
                "run_time": str(end_time - start_time),
                "content": res
            }

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            yield FunctionError(e)
    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()
Exemplo n.º 27
0
    def _fn_disable_hsts_function(self, event, *args, **kwargs):
        """Function: None"""
        try:

            # 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 'fn_disable_hsts' running in workflow '{0}'".format(
                    wf_instance_id))

            # Get the function parameters:

            log = logging.getLogger(__name__)
            os.system(
                'ssh [email protected] /snap/bin/kubectl apply -f /home/chao/digi/nginx-configmap-without-hsts.yaml'
            )

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

            results = {"content": "xyz"}

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
    def _utilities_extract_ssl_cert_from_url_function(self, event, *args,
                                                      **kwargs):
        """Function: This function takes in a HTTPS URL or DNS input, establishes a connection and then attempts to acquire the SSL certificate. If successful, the function then saves the certificate as an artifact of type ‘X509 Certificate File’. Works on most URLs including those with self-signed or expired certificates.

The output of this function is a string representation of the certificate saved in PEM format."""
        try:

            # 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 'utilities_extract_ssl_cert_from_url' running in workflow '{0}'"
                .format(wf_instance_id))

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

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

            ##############################################
            # PUT YOUR FUNCTION IMPLEMENTATION CODE HERE #
            ##############################################

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

            results = {"content": "xyz"}

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Exemplo n.º 29
0
    def _utilities_json2html_function(self, event, *args, **kwargs):
        """Function: convert a json string to html. Optionally, reference a portion of the json to render"""
        try:
            # Get the function parameters:
            json2html_data = kwargs.get("json2html_data")  # text
            json2html_keys = kwargs.get("json2html_keys")  # text

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

            json_node = json.loads(json2html_data)

            # look for path information to narrow the amount of json to render
            if json2html_keys:
                for key in json2html_keys.split('.'):
                    if key not in json_node.keys():
                        raise ValueError("{} key not found".format(key))
                    else:
                        json_node = json_node.get(key)

            result = json2html.convert(json=json_node)

            results = {"content": result}

            log.debug(results)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Exemplo n.º 30
0
    def create_meeting(self):
        """Creates a meeting based on options specified in app.config and function args"""
        meeting_xml = self.generate_create_meeting_xml()

        path = "/WBXService/XMLService"

        response = self.webex_request(path, "POST", meeting_xml)

        if response.text == "":
            raise FunctionError("Failed to create meeting, null response")

        status_regex = "<serv:result>(.*)<\/serv:result>"
        failure_reason_regex = "<serv:reason>(.*)<\/serv:reason>"

        status_regex_search = re.search(status_regex, response.text)
        failure_reason_regex_search = re.search(failure_reason_regex, response.text)

        results = {}

        if status_regex_search is not None:
            results["status"] = status_regex_search.group(1)

        if failure_reason_regex_search is not None:
            results["fail_reason"] = failure_reason_regex_search.group(1)
            return results

        success_details_regex = "<serv:host>(.*)<\/serv:host>\s*<serv:attendee>(.*)<\/serv:attendee>"

        success_details_regex_search = re.search(success_details_regex, response.text)

        if success_details_regex_search is not None:
            results["host_url"] = success_details_regex_search.group(1)
            results["attendee_url"] = success_details_regex_search.group(2)

        return results