Beispiel #1
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 _funct_zia_add_to_blocklist_function(self, event, *args, **kwargs):
        """Function: Add a URLs or IP addresses to the blocklist list.
            See link for URL guidelines:
              https://help.zscaler.com/zia/url-format-guidelines
        """
        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(["zia_blocklisturls", "zia_activate"],
                                        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 parameter '{1}' should be set '{2}'.")\
                    .format("zia_category_id", "zia_custom_only", "true")

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

            blocklisturls = fn_inputs.get("zia_blocklisturls")
            activate = fn_inputs.get("zia_activate")

            ziacli = ZiaClient(self.opts, self.fn_options)

            result = {
                "response": ziacli.blocklist_action(blocklisturls,
                                                    "ADD_TO_LIST")
            }

            result["activation"] = ziacli.activate(activate)

            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 _funct_zia_remove_from_url_category_function(self, event, *args,
                                                     **kwargs):
        """Function: Remove URLs or IP addresses from a URL Category. See following for URL guidelines https://help.zscaler.com/zia/url-format-guidelines"""
        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([
                "zia_configured_name", "zia_urls", "zia_category_id",
                "zia_activate"
            ], kwargs)

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

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

            category_id = fn_inputs.get("zia_category_id")
            configured_name = fn_inputs.get("zia_configured_name")
            urls = fn_inputs.get("zia_urls")
            activate = fn_inputs.get("zia_activate")

            ziacli = ZiaClient(self.opts, self.fn_options)

            result = {
                "response":
                ziacli.category_action(category_id, configured_name, urls,
                                       "REMOVE_FROM_LIST")
            }

            result["activation"] = ziacli.activate(activate)

            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 _funct_zia_add_url_category_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([
                "zia_configured_name", "zia_super_category", "zia_urls",
                "zia_custom_category", "zia_activate"
            ], kwargs)

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

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

            params = {
                "configured_name": fn_inputs.get("zia_configured_name"),
                "super_category": fn_inputs.get("zia_super_category"),
                "urls": fn_inputs.get("zia_urls"),
                "custom_category": fn_inputs.get("zia_custom_category"),
                "keywords": fn_inputs.get("zia_keywords"),
            }
            activate = fn_inputs.get("zia_activate")

            ziacli = ZiaClient(self.opts, self.fn_options)

            result = {"response": ziacli.add_url_category(**params)}

            result["activation"] = ziacli.activate(activate)

            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 _funct_zia_get_blocklist_function(self, event, *args, **kwargs):
        """Function: Get a list of block-listed URLs.
        """
        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)

            url_filter_patt = fn_inputs.get("zia_url_filter")
            if url_filter_patt and not is_regex(url_filter_patt):
                raise ValueError(
                    "The url query filter '{}' does not have a valid regular expression."
                    .format("zia_url_filter"))

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

            ziacli = ZiaClient(self.opts, self.fn_options)
            result = ziacli.get_blocklist_urls(url_filter=url_filter_patt)

            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 _funct_zia_get_sandbox_report_function(self, event, *args, **kwargs):
        """Function: Query an MD5  to see if it was run through the ZIA Sandbox.

           Get a full (i.e., complete) or summary detail report for a file that was analyzed.

        """
        try:
            LOG = logging.getLogger(__name__)
            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(
                ["zia_md5",
                 "zia_full_report"],
                kwargs)

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

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

            ziacli = ZiaClient(self.opts, self.fn_options)
            result = ziacli.get_sandbox_report(fn_inputs.get("zia_md5"), full=fn_inputs.get("zia_full_report"))

            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 selftest_function(opts):
    """
    Simple test to verify Zia connectivity.
    """
    fn_opts = opts.get("fn_zia", {})
    try:
        ziacli = ZiaClient(opts, fn_opts)
        result = ziacli.get_blocklist_urls()
        if isinstance(result, dict):
            return {
                "state": "success",
                "reason": "Successful connection to Zia endpoint"
            }
        else:
            return {
                "state": "failure",
                "reason": "Failed to connect to Zia endpoint"
            }

    except Exception as e:
        return {"state": "failure", "status_code": e}
    def _funct_zia_url_lookup_function(self, event, *args, **kwargs):
        """Function: Look up the categorization of a URL or set of URLs, e.g., ['abc.com', 'xyz.com'].  See following for URL guidelines https://help.zscaler.com/zia/url-format-guidelines"""
        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(
                ["zia_urls"],
                kwargs)

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

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

            urls = fn_inputs.get("zia_urls")

            ziacli = ZiaClient(self.opts, self.fn_options)
            result = ziacli.url_lookup(urls)

            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)