def destination_network(self, action, name=None, literal=None):
        """
        Add either an object or a literal to destinationNetworks.

        :param action: (str) Action to be done on this object
        :param name: (str) Object name
        :param literal: (str) Host, network or range
        :return: None
        """
        logging.debug("In destination_network() for PreFilterRules class.")
        if literal and name:
            raise ValueError(
                "Adding source literal and object at the same time not supported"
            )
            return

        if not hasattr(self, "destinationNetworks"):
            self.destinationNetworks = {"objects": [], "literals": []}

        if action == "add" and literal:
            literal_type = get_networkaddress_type(literal)
            self.destinationNetworks["literals"].append({
                "type": literal_type,
                "value": literal
            })
            return

        if name:
            new_object = self.find_object(name)

        if not new_object:
            return

        if action == "add":
            # Check if object is already in the list and if not, then add it
            if new_object not in self.destinationNetworks["objects"]:
                logging.info(
                    f'Adding "{name}" to destinationNetworks for prefilter rule'
                )
                self.destinationNetworks["objects"].append(new_object)

        elif action == "remove":
            index = self.destinationNetworks["objects"].index(new_object)
            logging.info(f'Removing "{new_object}" from destinationNetworks')
            self.destinationNetworks["objects"].pop(index)

        elif action == "clear":
            logging.info("Clearing all destination networks")
            del self.destinationNetworks
Beispiel #2
0
    def destination_network(self, action, name="", literal=None):
        """
        Add/modify name/literal to destinationNetworks field of AccessRules object.

        :param action: (str) the action to be done 'add', 'remove', 'clear'
        :param name: (str) name of the object in question
        :param literal: (dict) the literal in question {value:<>, type:<>}
        :return: None
        """
        # using dict() as default value is dangerous here, any thoughts/workarounds on this?

        logging.debug("In destination_network() for ACPRule class.")
        if literal and name != "":
            raise ValueError(
                "Only one of literals or name (object name) should be set while creating a source network"
            )

        if not hasattr(self, "destinationNetworks"):
            self.destinationNetworks = {"objects": [], "literals": {}}

        if action == "add":
            if literal:
                type_ = get_networkaddress_type(literal)
                self.destinationNetworks["literals"][literal] = type_
                logging.info(
                    f'Adding literal "{literal}" of type "{type_}" '
                    f"to destinationNetworks for this AccessRules."
                )
            else:
                ipaddresses_json = NetworkAddresses(fmc=self.fmc).get()
                networkgroup_json = NetworkGroups(fmc=self.fmc).get()
                if self.fmc.serverVersion >= "6.4":
                    fqdns_json = FQDNS(fmc=self.fmc).get()
                else:
                    fqdns_json = {"items": []}
                items = (
                    ipaddresses_json.get("items", [])
                    + networkgroup_json.get("items", [])
                    + fqdns_json.get("items", [])
                )
                new_net = None
                for item in items:
                    if item["name"] == name:
                        new_net = {
                            "name": item["name"],
                            "id": item["id"],
                            "type": item["type"],
                        }
                        break
                if new_net is None:
                    logging.warning(
                        f'Network "{name}" is not found in FMC.  Cannot add to destinationNetworks.'
                    )
                else:
                    if "destinationNetworks" in self.__dict__:
                        # thus either some objects are already present in destinationNetworks,
                        # or only literals are present in destinationNetworks
                        if "objects" in self.__dict__["destinationNetworks"]:
                            # some objects are already present
                            duplicate = False
                            for obj in self.destinationNetworks["objects"]:
                                if obj["name"] == new_net["name"]:
                                    duplicate = True
                                    break
                            if not duplicate:
                                self.destinationNetworks["objects"].append(new_net)
                                logging.info(
                                    f'Adding "{name}" to destinationNetworks for this AccessRules.'
                                )
                        else:
                            # this means no objects were present in destinationNetworks,
                            # and destinationNetworks contains literals only
                            self.destinationNetworks.update({"objects": [new_net]})
                            # So update the destinationNetworks dict which contained 'literals' key initially
                            # to have a 'objects' key as well
                            logging.info(
                                f'Adding "{name}" to destinationNetworks for this AccessRules.'
                            )
                    else:
                        # None of literals or objects are present in destinationNetworks,
                        # so initialize it with objects and update the provided object
                        self.destinationNetworks = {"objects": [new_net]}
                        logging.info(
                            f'Adding "{name}" to destinationNetworks for this AccessRules.'
                        )
        elif action == "remove":
            if "destinationNetworks" in self.__dict__:
                if name != "":
                    # an object's name has been provided to be removed
                    objects = []
                    for obj in self.destinationNetworks["objects"]:
                        if obj["name"] != name:
                            objects.append(obj)
                    if len(objects) == 0:
                        # it was the last object which was deleted now
                        del self.destinationNetworks
                        logging.info(
                            f'Removed "{name}" from destinationNetworks for this AccessRules'
                        )
                        logging.info(
                            "All Destination Networks removed from this AccessRules object."
                        )
                    else:
                        self.destinationNetworks["objects"] = objects
                        logging.info(
                            f'Removed "{name}" from destinationNetworks for this AccessRules.'
                        )
                else:
                    # a literal value has been provided to be removed
                    type_ = self.destinationNetworks["literals"].get(literal)
                    if type_:
                        self.destinationNetworks["literals"].pop(literal)
                        logging.info(
                            f'Removed literal "{literal}" of '
                            f'type "{type_}" from destinationNetworks for this AccessRules.'
                        )
                    else:
                        logging.info(
                            f'Unable to removed literal "{literal}" '
                            f"from destinationNetworks as it was not found"
                        )
            else:
                logging.info(
                    "destinationNetworks doesn't exist for this AccessRules.  Nothing to remove."
                )
        elif action == "clear":
            if "destinationNetworks" in self.__dict__:
                del self.destinationNetworks
                logging.info(
                    "All Destination Networks removed from this AccessRules object."
                )