예제 #1
0
def selftest_function(opts):
    """
    Placeholder for selftest function. An example use would be to test package api connectivity.
    Suggested return values are be unimplemented, success, or failure.
    """

    # Call the getAddresses API with the hardcoded 'vsys' and 'vsys1' for the location since those are typically
    # function inputs. Returns success if the call is successful
    options = opts.get("fn_pa_panorama", {})
    try:
        panorama_util = PanoramaClient(options, "vsys", "vsys1")
        panorama_util.get_addresses()

        return {"status": "success"}

    except Exception as err:
        err_reason_msg = """Could not connect to Panorama.
        error: {}
        ---------
        Current Configs in app.config file:
        ---------
        api_key: {}
        panorama_host: {}
        cert: {}""".format(
            err,
            options.get("api_key"),
            options.get("panorama_host"),
            options.get("cert")
        )

        return {
            "status": "failure",
            "reason": err_reason_msg
        }
예제 #2
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 _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)
 def test_get_addresses_groups(self, mocked_requests_get):
     sim_content = {
         "@code": "19",
         "@status": "success",
         "result": {
             "@count":
             "1",
             "@total-count":
             "1",
             "entry": [{
                 "@location": "vsys",
                 "@name": "Blocked Group",
                 "@vsys": "vsys1",
                 "description": "None",
                 "static": {
                     "member": ["Test", "google.com", "8.8.8.8"]
                 }
             }]
         }
     }
     mocked_requests_get.return_value = self._generateResponse(
         json.dumps(sim_content), 200)
     pc = PanoramaClient(self.mocked_opts, self.mocked_location, None)
     result = pc.get_address_groups("Blocked_Group")
     assert result == sim_content
 def test_get_users_in_a_group(self, mocked_requests_get):
     sim_content = '<response status="success" code="19"><result total-count="1" count="1"><entry name="Blocked_Users" admin="admin" dirtyId="14" time="2019/06/27 07:51:28"/></result></response>'
     body_xpath = "/config/shared/local-user-database/user-group/entry[@name=\\'Blocked_Users\\']"
     mocked_requests_get.return_value = self._generateResponse(
         sim_content, 200)
     pc = PanoramaClient(self.mocked_opts, None, None)
     result = pc.get_users_in_a_group(body_xpath)
     assert result == sim_content
 def test_edit_users_in_a_group(self, mocked_requests_get):
     sim_content = '<response status="success" code="20"><msg>command succeeded</msg></response>'
     body_xpath = "/config/shared/local-user-database/user-group/entry[@name=\\'Blocked_Users\\']"
     xml = """<entry name="Blocked_Users">
                 <user>
                   <member>Blocked_User</member>
                 </user>
             </entry>"""
     mocked_requests_get.return_value = self._generateResponse(
         sim_content, 200)
     pc = PanoramaClient(self.mocked_opts, self.mocked_location, None)
     result = pc.edit_users_in_a_group(body_xpath, xml)
     assert result == sim_content
    def _panorama_edit_users_in_a_group_function(self, event, *args, **kwargs):
        """Function: Panorama get address groups returns the list of address groups """
        try:
            # Response code should equal 20 indicating the call went through successfully
            PASS_CONSTANT = "20"

            yield StatusMessage("Editing list of users in a group")
            rp = ResultPayload("fn_pa_panorama", **kwargs)

            validate_fields(
                ["panorama_user_group_xpath", "panorama_user_group_xml"],
                kwargs)

            # Get the function parameters:
            user_group_xpath = kwargs.get("panorama_user_group_xpath")  # text
            user_group_xml = self.get_textarea_param(
                kwargs.get("panorama_user_group_xml"))  # textarea
            location = self.get_select_param(
                kwargs.get("panorama_location"))  # select

            # Log inputs
            log.info(u"panorama_user_group_xpath: {}".format(user_group_xpath))
            log.info(u"panorama_user_group_xml: {}".format(user_group_xml))

            panorama_util = PanoramaClient(self.opts, location, None)
            xml_response = panorama_util.edit_users_in_a_group(
                user_group_xpath, user_group_xml)
            dict_response = xmltodict.parse(xml_response)

            try:
                if dict_response["response"].get("@code") == PASS_CONSTANT:
                    yield StatusMessage("User group was successfully edited.")
                else:
                    raise FunctionError(
                        "Editing the user group was unsuccessful with code {}, raising FunctionError."
                        .format(dict_response["response"]["@code"]))
            except KeyError as e:
                yield StatusMessage("Editing the user group was unsuccessful.")
                raise FunctionError(e)

            # add to dict_response to allow for more options in Resilient scripting and make some actions easier
            dict_response["xml_response"] = xml_response
            results = rp.done(True, dict_response)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            yield FunctionError(e)
 def test_create_address(self, mocked_requests_get):
     sim_content = {
         "@code": "20",
         "@status": "success",
         "msg": "command succeeded"
     }
     body = {
         "@code": "20",
         "@status": "success",
         "msg": "command succeeded"
     }
     mocked_requests_get.return_value = self._generateResponse(
         json.dumps(sim_content), 200)
     pc = PanoramaClient(self.mocked_opts, self.mocked_location, None)
     result = pc.add_address("2.2.2.2", json.dumps(body))
     assert result == sim_content
    def _panorama_get_users_in_a_group_function(self, event, *args, **kwargs):
        """Function: Panorama get address groups returns the list of address groups """
        try:
            yield StatusMessage("Getting list of users in a group")
            rp = ResultPayload("fn_pa_panorama", **kwargs)

            validate_fields(["panorama_user_group_xpath"], kwargs)

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

            # Log inputs
            log.info("panorama_user_group_xpath: {}".format(user_group_xpath))

            panorama_util = PanoramaClient(self.opts, location, None)
            xml_response = panorama_util.get_users_in_a_group(user_group_xpath)
            dict_response = xmltodict.parse(xml_response)

            user_list = []
            try:
                members = dict_response["response"]["result"]["entry"]["user"][
                    "member"]
                if isinstance(members, list):
                    # Multiple existing users
                    for m in members:
                        user_list.append(m)
                else:
                    # Single user in group
                    user_list.append(members.get("#text"))
            except KeyError:
                # No users returned
                yield StatusMessage("No users returned.")

            yield StatusMessage("{} users returned.".format(len(user_list)))

            # add to dict_response to allow for more options in Resilient scripting and make some actions easier
            dict_response["user_list"] = user_list
            dict_response["xml_response"] = xml_response
            results = rp.done(True, dict_response)

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            yield FunctionError(e)
 def test_edit_address_group(self, mocked_requests_get):
     sim_content = {
         "@code": "20",
         "@status": "success",
         "msg": "command succeeded"
     }
     body = {
         "entry": {
             "@name": "Blocked Group",
             "description": "None",
             "static": {
                 "member": ["google.com", "8.8.8.8"]
             }
         }
     }
     mocked_requests_get.return_value = self._generateResponse(
         json.dumps(sim_content), 200)
     pc = PanoramaClient(self.mocked_opts, self.mocked_location, None)
     result = pc.edit_address_groups("Blocked_Group", json.dumps(body))
     assert result == sim_content
 def test_get_addresses(self, mocked_requests_get):
     sim_content = {
         "@code": "19",
         "@status": "success",
         "result": {
             "@count":
             "4",
             "@total-count":
             "4",
             "entry": [{
                 "@location": "vsys",
                 "@name": "Test",
                 "@vsys": "vsys1",
                 "ip-netmask": "1.1.1.1"
             }, {
                 "@location": "vsys",
                 "@name": "9.9.9.9",
                 "@vsys": "vsys1",
                 "description": "9.9.9.9",
                 "ip-netmask": "9.9.9.9"
             }, {
                 "@location": "vsys",
                 "@name": "google.com",
                 "@vsys": "vsys1",
                 "description": "google.com",
                 "fqdn": "google.com"
             }, {
                 "@location": "vsys",
                 "@name": "8.8.8.8",
                 "@vsys": "vsys1",
                 "description": "8.8.8.8",
                 "ip-netmask": "8.8.8.8"
             }]
         }
     }
     mocked_requests_get.return_value = self._generateResponse(
         json.dumps(sim_content), 200)
     pc = PanoramaClient(self.mocked_opts, self.mocked_location, None)
     result = pc.get_addresses()
     assert result == sim_content