Ejemplo n.º 1
0
    def get_locked_adom_list(self):
        """
        Gets the list of locked adoms
        """
        try:
            locked_list = list()
            locked_by_user_list = list()
            for adom in self._adom_list:
                adom_lock_info = self.get_lock_info(adom=adom)
                try:
                    if adom_lock_info[1]["status"]["message"] == "OK":
                        continue
                except IndexError as err:
                    pass
                try:
                    if adom_lock_info[1][0]["lock_user"]:
                        locked_list.append(to_text(adom))
                    if adom_lock_info[1][0][
                            "lock_user"] == self._logged_in_user:
                        locked_by_user_list.append({
                            "adom":
                            to_text(adom),
                            "user":
                            to_text(adom_lock_info[1][0]["lock_user"])
                        })
                except Exception as err:
                    raise FMGBaseException(err)
            self._locked_adom_list = locked_list
            self._locked_adoms_by_user = locked_by_user_list

        except Exception as err:
            raise FMGBaseException(msg=(
                "An error occurred while trying to get the locked adom list. Error: "
                + to_text(err)))
Ejemplo n.º 2
0
 def check_mode(self):
     """
     Checks FortiManager for the use of Workspace mode
     """
     url = "/cli/global/system/global"
     code, resp_obj = self.send_request(
         FMGRMethods.GET,
         self._tools.format_request(
             FMGRMethods.GET, url, fields=["workspace-mode",
                                           "adom-status"]))
     try:
         if resp_obj["workspace-mode"] == "workflow":
             self.uses_workspace = True
         elif resp_obj["workspace-mode"] == "disabled":
             self.uses_workspace = False
     except KeyError:
         raise FMGBaseException(
             msg="Couldn't determine workspace-mode in the plugin")
     try:
         if resp_obj["adom-status"] in [1, "enable"]:
             self.uses_adoms = True
         else:
             self.uses_adoms = False
     except KeyError:
         raise FMGBaseException(
             msg="Couldn't determine adom-status in the plugin")
Ejemplo n.º 3
0
    def send_request(self, method, params):
        """
        Responsible for actual sending of data to the connection httpapi base plugin. Does some formatting too.
        :param params: A formatted dictionary that was returned by self.common_datagram_params()
        before being called here.
        :param method: The preferred API Request method (GET, ADD, POST, etc....)
        :type method: basestring

        :return: Dictionary of status, if it logged in or not.
        """
        try:
            if self.sid is None and params[0]["url"] != "sys/login/user":
                try:
                    self.connection._connect()
                except Exception as err:
                    raise FMGBaseException(
                        msg=
                        "An problem happened with the httpapi plugin self-init connection process. "
                        "Error: " + to_text(err))
        except IndexError:
            raise FMGBaseException(
                "An attempt was made at communicating with a FMG with "
                "no valid session and an incorrectly formatted request.")
        except Exception as err:
            raise FMGBaseException(
                "An attempt was made at communicating with a FMG with "
                "no valid session and an unexpected error was discovered. \n Error: "
                + to_text(err))

        self._update_request_id()
        json_request = {
            "method": method,
            "params": params,
            "session": self.sid,
            "id": self.req_id,
            "verbose": 1
        }
        data = json.dumps(json_request,
                          ensure_ascii=False).replace('\\\\', '\\')
        try:
            # Sending URL and Data in Unicode, per Ansible Specifications for Connection Plugins
            response, response_data = self.connection.send(
                path=to_text(self._url),
                data=to_text(data),
                headers=BASE_HEADERS)
            # Get Unicode Response - Must convert from StringIO to unicode first so we can do a replace function below
            result = json.loads(to_text(response_data.getvalue()))
            self._update_self_from_response(result, self._url, data)
            return self._handle_response(result)
        except Exception as err:
            raise FMGBaseException(err)
Ejemplo n.º 4
0
    def login(self, username, password):
        """
        This function will log the plugin into FortiManager, and return the results.
        :param username: Username of FortiManager Admin
        :param password: Password of FortiManager Admin

        :return: Dictionary of status, if it logged in or not.
        """
        self.send_request(
            FMGRMethods.EXEC,
            self._tools.format_request(
                FMGRMethods.EXEC,
                "sys/login/user",
                passwd=password,
                user=username,
            ))

        if "FortiManager object connected to FortiManager" in self.__str__():
            # If Login worked, then inspect the FortiManager for Workspace Mode, and it's system information.
            self.inspect_fmgr()
            return
        else:
            raise FMGBaseException(
                msg=
                "Unknown error while logging in...connection was lost during login operation...."
                " Exiting")
def main():
    argument_spec = dict(
        adom=dict(type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"],
                  type="str",
                  default="add"),
        startip=dict(required=False, type="str"),
        name=dict(required=False, type="str"),
        endip=dict(required=False, type="str"),
        comments=dict(required=False, type="str"),
        dynamic_mapping=dict(required=False, type="list"),
        dynamic_mapping_comments=dict(required=False, type="str"),
        dynamic_mapping_endip=dict(required=False, type="str"),
        dynamic_mapping_startip=dict(required=False, type="str"),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )
    # MODULE PARAMGRAM
    paramgram = {
        "mode": module.params["mode"],
        "adom": module.params["adom"],
        "startip": module.params["startip"],
        "name": module.params["name"],
        "endip": module.params["endip"],
        "comments": module.params["comments"],
        "dynamic_mapping": {
            "comments": module.params["dynamic_mapping_comments"],
            "endip": module.params["dynamic_mapping_endip"],
            "startip": module.params["dynamic_mapping_startip"],
        }
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    list_overrides = ['dynamic_mapping']
    paramgram = fmgr.tools.paramgram_child_list_override(
        list_overrides=list_overrides, paramgram=paramgram, module=module)

    results = DEFAULT_RESULT_OBJ

    try:
        results = fmgr_fwobj_ippool6_modify(fmgr, paramgram)
        fmgr.govern_response(module=module,
                             results=results,
                             ansible_facts=fmgr.construct_ansible_facts(
                                 results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 6
0
def main():
    argument_spec = dict(
        adom=dict(required=False, type="str", default="root"),
        device_unique_name=dict(required=True, type="str"),
        fortimeter_utm_level=dict(required=True, type="str"),
        foslic_type=dict(required=False, type="int", default=2)
    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, )
    paramgram = {
        "adom": module.params["adom"],
        "device_unique_name": module.params["device_unique_name"],
        "fortimeter_utm_level": module.params["fortimeter_utm_level"],
        "foslic_type": module.params["foslic_type"]
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    results = DEFAULT_RESULT_OBJ
    try:
        results = fmgr_set_fortimeter_lic(fmgr, paramgram)
        fmgr.govern_response(module=module, results=results,
                             ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 7
0
    def return_connected_fmgr(self):
        """
        Returns the data stored under self._connected_fmgr

        :return: dict
        """
        try:
            if self._connected_fmgr:
                return self._connected_fmgr
        except BaseException:
            raise FMGBaseException("Couldn't Retrieve Connected FMGR Stats")
Ejemplo n.º 8
0
def main():
    argument_spec = dict(
        adom=dict(required=False, type="str", default="root"),
        device_unique_name=dict(required=True, type="str"),
        device_hostname=dict(required=False, type="str"),
        interface=dict(required=False, type="str"),
        interface_ip=dict(required=False, type="str"),
        interface_allow_access=dict(required=False, type="str"),
        install_config=dict(required=False, type="str", default="disable"),
    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, )
    paramgram = {
        "device_unique_name": module.params["device_unique_name"],
        "device_hostname": module.params["device_hostname"],
        "interface": module.params["interface"],
        "interface_ip": module.params["interface_ip"],
        "interface_allow_access": module.params["interface_allow_access"],
        "install_config": module.params["install_config"],
        "adom": module.params["adom"]
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    # BEGIN MODULE-SPECIFIC LOGIC -- THINGS NEED TO HAPPEN DEPENDING ON THE ENDPOINT AND OPERATION
    results = DEFAULT_RESULT_OBJ
    try:
        if paramgram["device_hostname"] is not None:
            results = update_device_hostname(fmgr, paramgram)
            fmgr.govern_response(module=module, results=results,
                                 ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))

        if paramgram["interface_ip"] is not None or paramgram["interface_allow_access"] is not None:
            results = update_device_interface(fmgr, paramgram)
            fmgr.govern_response(module=module, results=results,
                                 ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))

        if paramgram["install_config"] == "enable":
            results = exec_config(fmgr, paramgram)
            fmgr.govern_response(module=module, results=results,
                                 ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 9
0
    def process_request(self, url, datagram, method):
        """
        Formats and Runs the API Request via Connection Plugin. Streamlined for use FROM Modules.

        :param url: Connection URL to access
        :type url: string
        :param datagram: The prepared payload for the API Request in dictionary format
        :type datagram: dict
        :param method: The preferred API Request method (GET, ADD, POST, etc....)
        :type method: basestring

        :return: Dictionary containing results of the API Request via Connection Plugin
        :rtype: dict
        """
        try:
            adom = self._module.paramgram["adom"]
            if self.uses_workspace and adom not in self._locked_adom_list and method != FMGRMethods.GET:
                self.lock_adom(adom=adom)
        except BaseException as err:
            raise FMGBaseException(err)

        data = self._tools.format_request(method, url, **datagram)
        response = self._conn.send_request(method, data)

        try:
            adom = self._module.paramgram["adom"]
            if self.uses_workspace and adom in self._locked_adom_list \
                    and response[0] == 0 and method != FMGRMethods.GET:
                self.commit_changes(adom=adom)
        except BaseException as err:
            raise FMGBaseException(err)

        # if HAS_FMGR_DEBUG:
        #     try:
        #         debug_dump(response, datagram, self._module.paramgram, url, method)
        #     except BaseException:
        #         pass

        return response
Ejemplo n.º 10
0
 def workspace_check(self):
     """
    Checks FortiManager for the use of Workspace mode
    """
     url = "/cli/global/system/global"
     data = {"fields": ["workspace-mode", "adom-status"]}
     resp_obj = self.process_request(url, data, FMGRMethods.GET)
     try:
         if resp_obj[1]["workspace-mode"] in ["workflow", "normal"]:
             self.uses_workspace = True
         elif resp_obj[1]["workspace-mode"] == "disabled":
             self.uses_workspace = False
     except KeyError:
         raise FMGBaseException(
             msg="Couldn't determine workspace-mode in the plugin")
     try:
         if resp_obj[1]["adom-status"] in [1, "enable"]:
             self.uses_adoms = True
         else:
             self.uses_adoms = False
     except KeyError:
         raise FMGBaseException(
             msg="Couldn't determine adom-status in the plugin")
Ejemplo n.º 11
0
    def inspect_fmgr(self):
        # CHECK FOR WORKSPACE MODE TO SEE IF WE HAVE TO ENABLE ADOM LOCKS

        self.check_mode()
        # CHECK FOR SYSTEM STATUS -- SHOULD RETURN 0
        status = self.get_system_status()
        if status[0] == -11:
            # THE CONNECTION GOT LOST SOMEHOW, REMOVE THE SID AND REPORT BAD LOGIN
            self.logout()
            raise FMGBaseException(
                msg=
                "Error -11 -- the Session ID was likely malformed somehow. Contact authors."
                " Exiting")
        elif status[0] == 0:
            try:
                self._connected_fmgr = status[1]
                self._host = self._connected_fmgr["Hostname"]
            except BaseException:
                pass
        return
Ejemplo n.º 12
0
    def process_request(self, url, datagram, method):
        """
        Formats and Runs the API Request via Connection Plugin. Streamlined for use FROM Modules.

        :param url: Connection URL to access
        :type url: string
        :param datagram: The prepared payload for the API Request in dictionary format
        :type datagram: dict
        :param method: The preferred API Request method (GET, ADD, POST, etc....)
        :type method: basestring

        :return: Dictionary containing results of the API Request via Connection Plugin
        :rtype: dict
        """

        try:
            adom = self._module.paramgram["adom"]
            if self.uses_workspace and adom not in self._locked_adom_list and method != FMGRMethods.GET:
                self.lock_adom(adom=adom)

        except BaseException as err:
            raise FMGBaseException(err)

        data = self._tools.format_request(method, url, **datagram)
        response = self._conn.send_request(method, data)

        # 7.29.19 - LW FIX FOR FMGR_SCRIPT EXEC IN WORKSPACE MODE -- BECAUSE THE MODULE ISN'T WAITING FOR THE TASK
        # TO FINISH, WE NEED TO ADD THESE LINES TO CHECK FOR A TASK ID IN THE RESPONSE. IF WE GET ONE, AND
        # THE FORTIMANAGER HAS WORKSPACE MODE ENABLED, EVERY TWO SECONDS WE'LL QUERY FOR THE STATUS OF THAT TASK
        # AND IT WILL NOT MOVE FORWARD UNTIL THE TASK HAS REACHED 100%

        if self.uses_workspace:
            task_id = None
            try:
                # LOOK FOR A TASK ID, IF THERE IS, WAIT FOR IT TO FINISH BEFORE GOING MOVING ON
                task_id = response[1]["task"]
            except BaseException:
                pass

            if task_id:
                retry_interval = 5
                retry_count = 150
                try:
                    if isinstance(self._module.paramgram["retry_interval"],
                                  int):
                        retry_interval = int(
                            self._module.paramgram["retry_interval"])
                except KeyError:
                    pass
                try:
                    if isinstance(self._module.paramgram["retry_count"], int):
                        retry_count = int(
                            self._module.paramgram["retry_count"])
                except KeyError:
                    pass
                task_status = 0
                query_count = 0
                while task_status != 100:
                    if query_count > retry_count:
                        self.unlock_adom(adom=adom)
                        raise FMGBaseException(
                            msg=
                            "The Task in workspace mode exceeded the timeout/retry count. "
                            "Please adjust the retry_count and retry_interval variables "
                            "in the playbook/module.")
                    time.sleep(retry_interval)
                    task_query_data = self._tools.format_request(
                        FMGRMethods.GET,
                        '/task/task/{task_id}'.format(task_id=task_id),
                        {"adom": self._module.paramgram["adom"]})
                    task_query_response = self._conn.send_request(
                        FMGRMethods.GET, task_query_data)
                    try:
                        task_status = task_query_response[1]["percent"]
                    except BaseException as err:
                        self.unlock_adom(adom=adom)
                        raise FMGBaseException(
                            msg=
                            "A task was executed in workspace mode, but the task_id wasn't"
                            "returned. Something has gone wrong. We've unlocked the ADOM,"
                            "and no changes should have been made. Error: " +
                            str(err))
                    query_count += 1

            try:
                adom = self._module.paramgram["adom"]
                if self.uses_workspace and adom in self._locked_adom_list \
                        and response[0] == 0 and method != FMGRMethods.GET:
                    self.commit_changes(adom=adom)
            except BaseException as err:
                raise FMGBaseException(err)

        # if HAS_FMGR_DEBUG:
        #     try:
        #         debug_dump(response, datagram, self._module.paramgram, url, method)
        #     except BaseException:
        #         pass

        return response
Ejemplo n.º 13
0
def main():
    argument_spec = dict(
        adom=dict(type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"],
                  type="str",
                  default="add"),
        transparent=dict(required=False,
                         type="str",
                         choices=["disable", "enable"]),
        name=dict(required=False, type="str"),
        comments=dict(required=False, type="str"),
        auth_group=dict(required=False, type="str"),
        cifs=dict(required=False, type="dict"),
        cifs_byte_caching=dict(required=False,
                               type="str",
                               choices=["disable", "enable"]),
        cifs_log_traffic=dict(required=False,
                              type="str",
                              choices=["disable", "enable"]),
        cifs_port=dict(required=False, type="str"),
        cifs_prefer_chunking=dict(required=False,
                                  type="str",
                                  choices=["dynamic", "fix"]),
        cifs_secure_tunnel=dict(required=False,
                                type="str",
                                choices=["disable", "enable"]),
        cifs_status=dict(required=False,
                         type="str",
                         choices=["disable", "enable"]),
        cifs_tunnel_sharing=dict(
            required=False,
            type="str",
            choices=["private", "shared", "express-shared"]),
        ftp=dict(required=False, type="dict"),
        ftp_byte_caching=dict(required=False,
                              type="str",
                              choices=["disable", "enable"]),
        ftp_log_traffic=dict(required=False,
                             type="str",
                             choices=["disable", "enable"]),
        ftp_port=dict(required=False, type="str"),
        ftp_prefer_chunking=dict(required=False,
                                 type="str",
                                 choices=["dynamic", "fix"]),
        ftp_secure_tunnel=dict(required=False,
                               type="str",
                               choices=["disable", "enable"]),
        ftp_status=dict(required=False,
                        type="str",
                        choices=["disable", "enable"]),
        ftp_tunnel_sharing=dict(
            required=False,
            type="str",
            choices=["private", "shared", "express-shared"]),
        http=dict(required=False, type="dict"),
        http_byte_caching=dict(required=False,
                               type="str",
                               choices=["disable", "enable"]),
        http_log_traffic=dict(required=False,
                              type="str",
                              choices=["disable", "enable"]),
        http_port=dict(required=False, type="str"),
        http_prefer_chunking=dict(required=False,
                                  type="str",
                                  choices=["dynamic", "fix"]),
        http_secure_tunnel=dict(required=False,
                                type="str",
                                choices=["disable", "enable"]),
        http_ssl=dict(required=False,
                      type="str",
                      choices=["disable", "enable"]),
        http_ssl_port=dict(required=False, type="str"),
        http_status=dict(required=False,
                         type="str",
                         choices=["disable", "enable"]),
        http_tunnel_non_http=dict(required=False,
                                  type="str",
                                  choices=["disable", "enable"]),
        http_tunnel_sharing=dict(
            required=False,
            type="str",
            choices=["private", "shared", "express-shared"]),
        http_unknown_http_version=dict(
            required=False,
            type="str",
            choices=["best-effort", "reject", "tunnel"]),
        mapi=dict(required=False, type="dict"),
        mapi_byte_caching=dict(required=False,
                               type="str",
                               choices=["disable", "enable"]),
        mapi_log_traffic=dict(required=False,
                              type="str",
                              choices=["disable", "enable"]),
        mapi_port=dict(required=False, type="str"),
        mapi_secure_tunnel=dict(required=False,
                                type="str",
                                choices=["disable", "enable"]),
        mapi_status=dict(required=False,
                         type="str",
                         choices=["disable", "enable"]),
        mapi_tunnel_sharing=dict(
            required=False,
            type="str",
            choices=["private", "shared", "express-shared"]),
        tcp=dict(required=False, type="dict"),
        tcp_byte_caching=dict(required=False,
                              type="str",
                              choices=["disable", "enable"]),
        tcp_byte_caching_opt=dict(required=False,
                                  type="str",
                                  choices=["mem-only", "mem-disk"]),
        tcp_log_traffic=dict(required=False,
                             type="str",
                             choices=["disable", "enable"]),
        tcp_port=dict(required=False, type="str"),
        tcp_secure_tunnel=dict(required=False,
                               type="str",
                               choices=["disable", "enable"]),
        tcp_ssl=dict(required=False, type="str", choices=["disable",
                                                          "enable"]),
        tcp_ssl_port=dict(required=False, type="str"),
        tcp_status=dict(required=False,
                        type="str",
                        choices=["disable", "enable"]),
        tcp_tunnel_sharing=dict(
            required=False,
            type="str",
            choices=["private", "shared", "express-shared"]),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )
    # MODULE PARAMGRAM
    paramgram = {
        "mode": module.params["mode"],
        "adom": module.params["adom"],
        "transparent": module.params["transparent"],
        "name": module.params["name"],
        "comments": module.params["comments"],
        "auth-group": module.params["auth_group"],
        "cifs": {
            "byte-caching": module.params["cifs_byte_caching"],
            "log-traffic": module.params["cifs_log_traffic"],
            "port": module.params["cifs_port"],
            "prefer-chunking": module.params["cifs_prefer_chunking"],
            "secure-tunnel": module.params["cifs_secure_tunnel"],
            "status": module.params["cifs_status"],
            "tunnel-sharing": module.params["cifs_tunnel_sharing"],
        },
        "ftp": {
            "byte-caching": module.params["ftp_byte_caching"],
            "log-traffic": module.params["ftp_log_traffic"],
            "port": module.params["ftp_port"],
            "prefer-chunking": module.params["ftp_prefer_chunking"],
            "secure-tunnel": module.params["ftp_secure_tunnel"],
            "status": module.params["ftp_status"],
            "tunnel-sharing": module.params["ftp_tunnel_sharing"],
        },
        "http": {
            "byte-caching": module.params["http_byte_caching"],
            "log-traffic": module.params["http_log_traffic"],
            "port": module.params["http_port"],
            "prefer-chunking": module.params["http_prefer_chunking"],
            "secure-tunnel": module.params["http_secure_tunnel"],
            "ssl": module.params["http_ssl"],
            "ssl-port": module.params["http_ssl_port"],
            "status": module.params["http_status"],
            "tunnel-non-http": module.params["http_tunnel_non_http"],
            "tunnel-sharing": module.params["http_tunnel_sharing"],
            "unknown-http-version": module.params["http_unknown_http_version"],
        },
        "mapi": {
            "byte-caching": module.params["mapi_byte_caching"],
            "log-traffic": module.params["mapi_log_traffic"],
            "port": module.params["mapi_port"],
            "secure-tunnel": module.params["mapi_secure_tunnel"],
            "status": module.params["mapi_status"],
            "tunnel-sharing": module.params["mapi_tunnel_sharing"],
        },
        "tcp": {
            "byte-caching": module.params["tcp_byte_caching"],
            "byte-caching-opt": module.params["tcp_byte_caching_opt"],
            "log-traffic": module.params["tcp_log_traffic"],
            "port": module.params["tcp_port"],
            "secure-tunnel": module.params["tcp_secure_tunnel"],
            "ssl": module.params["tcp_ssl"],
            "ssl-port": module.params["tcp_ssl_port"],
            "status": module.params["tcp_status"],
            "tunnel-sharing": module.params["tcp_tunnel_sharing"],
        }
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    list_overrides = ['cifs', 'ftp', 'http', 'mapi', 'tcp']
    paramgram = fmgr.tools.paramgram_child_list_override(
        list_overrides=list_overrides, paramgram=paramgram, module=module)

    results = DEFAULT_RESULT_OBJ

    try:
        results = fmgr_wanopt_profile_modify(fmgr, paramgram)
        fmgr.govern_response(module=module,
                             results=results,
                             ansible_facts=fmgr.construct_ansible_facts(
                                 results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
def main():
    argument_spec = dict(
        adom=dict(type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"],
                  type="str",
                  default="add"),
        unknown_application_log=dict(required=False,
                                     type="str",
                                     choices=["disable", "enable"]),
        unknown_application_action=dict(required=False,
                                        type="str",
                                        choices=["pass", "block"]),
        replacemsg_group=dict(required=False, type="str"),
        p2p_black_list=dict(required=False,
                            type="str",
                            choices=["skype", "edonkey", "bittorrent"]),
        other_application_log=dict(required=False,
                                   type="str",
                                   choices=["disable", "enable"]),
        other_application_action=dict(required=False,
                                      type="str",
                                      choices=["pass", "block"]),
        options=dict(required=False,
                     type="str",
                     choices=[
                         "allow-dns", "allow-icmp", "allow-http", "allow-ssl",
                         "allow-quic"
                     ]),
        name=dict(required=False, type="str"),
        extended_log=dict(required=False,
                          type="str",
                          choices=["disable", "enable"]),
        deep_app_inspection=dict(required=False,
                                 type="str",
                                 choices=["disable", "enable"]),
        comment=dict(required=False, type="str"),
        app_replacemsg=dict(required=False,
                            type="str",
                            choices=["disable", "enable"]),
        entries=dict(required=False, type="list"),
        entries_action=dict(required=False,
                            type="str",
                            choices=["pass", "block", "reset"]),
        entries_application=dict(required=False, type="str"),
        entries_behavior=dict(required=False, type="str"),
        entries_category=dict(required=False, type="str"),
        entries_log=dict(required=False,
                         type="str",
                         choices=["disable", "enable"]),
        entries_log_packet=dict(required=False,
                                type="str",
                                choices=["disable", "enable"]),
        entries_per_ip_shaper=dict(required=False, type="str"),
        entries_popularity=dict(required=False,
                                type="str",
                                choices=["1", "2", "3", "4", "5"]),
        entries_protocols=dict(required=False, type="str"),
        entries_quarantine=dict(required=False,
                                type="str",
                                choices=["none", "attacker"]),
        entries_quarantine_expiry=dict(required=False, type="str"),
        entries_quarantine_log=dict(required=False,
                                    type="str",
                                    choices=["disable", "enable"]),
        entries_rate_count=dict(required=False, type="int"),
        entries_rate_duration=dict(required=False, type="int"),
        entries_rate_mode=dict(required=False,
                               type="str",
                               choices=["periodical", "continuous"]),
        entries_rate_track=dict(required=False,
                                type="str",
                                choices=[
                                    "none", "src-ip", "dest-ip",
                                    "dhcp-client-mac", "dns-domain"
                                ]),
        entries_risk=dict(required=False, type="str"),
        entries_session_ttl=dict(required=False, type="int"),
        entries_shaper=dict(required=False, type="str"),
        entries_shaper_reverse=dict(required=False, type="str"),
        entries_sub_category=dict(required=False, type="str"),
        entries_technology=dict(required=False, type="str"),
        entries_vendor=dict(required=False, type="str"),
        entries_parameters_value=dict(required=False, type="str"),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )
    # MODULE PARAMGRAM
    paramgram = {
        "mode": module.params["mode"],
        "adom": module.params["adom"],
        "unknown-application-log": module.params["unknown_application_log"],
        "unknown-application-action":
        module.params["unknown_application_action"],
        "replacemsg-group": module.params["replacemsg_group"],
        "p2p-black-list": module.params["p2p_black_list"],
        "other-application-log": module.params["other_application_log"],
        "other-application-action": module.params["other_application_action"],
        "options": module.params["options"],
        "name": module.params["name"],
        "extended-log": module.params["extended_log"],
        "deep-app-inspection": module.params["deep_app_inspection"],
        "comment": module.params["comment"],
        "app-replacemsg": module.params["app_replacemsg"],
        "entries": {
            "action": module.params["entries_action"],
            "application": module.params["entries_application"],
            "behavior": module.params["entries_behavior"],
            "category": module.params["entries_category"],
            "log": module.params["entries_log"],
            "log-packet": module.params["entries_log_packet"],
            "per-ip-shaper": module.params["entries_per_ip_shaper"],
            "popularity": module.params["entries_popularity"],
            "protocols": module.params["entries_protocols"],
            "quarantine": module.params["entries_quarantine"],
            "quarantine-expiry": module.params["entries_quarantine_expiry"],
            "quarantine-log": module.params["entries_quarantine_log"],
            "rate-count": module.params["entries_rate_count"],
            "rate-duration": module.params["entries_rate_duration"],
            "rate-mode": module.params["entries_rate_mode"],
            "rate-track": module.params["entries_rate_track"],
            "risk": module.params["entries_risk"],
            "session-ttl": module.params["entries_session_ttl"],
            "shaper": module.params["entries_shaper"],
            "shaper-reverse": module.params["entries_shaper_reverse"],
            "sub-category": module.params["entries_sub_category"],
            "technology": module.params["entries_technology"],
            "vendor": module.params["entries_vendor"],
            "parameters": {
                "value": module.params["entries_parameters_value"],
            }
        }
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    list_overrides = ['entries']
    paramgram = fmgr.tools.paramgram_child_list_override(
        list_overrides=list_overrides, paramgram=paramgram, module=module)

    results = DEFAULT_RESULT_OBJ
    try:
        results = fmgr_application_list_modify(fmgr, paramgram)
        fmgr.govern_response(module=module,
                             results=results,
                             ansible_facts=fmgr.construct_ansible_facts(
                                 results, module.params, paramgram))
    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
def main():
    argument_spec = dict(
        adom=dict(required=False, type="str", default="root"),
        mode=dict(choices=["add", "set", "delete"], type="str", default="add"),
        name=dict(required=False, type="str"),
        object_type=dict(required=True,
                         type="str",
                         choices=['pkg', 'folder', 'install']),
        package_folder=dict(required=False, type="str"),
        central_nat=dict(required=False,
                         type="str",
                         default="disable",
                         choices=['enable', 'disable']),
        fwpolicy_implicit_log=dict(required=False,
                                   type="str",
                                   default="disable",
                                   choices=['enable', 'disable']),
        fwpolicy6_implicit_log=dict(required=False,
                                    type="str",
                                    default="disable",
                                    choices=['enable', 'disable']),
        inspection_mode=dict(required=False,
                             type="str",
                             default="flow",
                             choices=['flow', 'proxy']),
        ngfw_mode=dict(required=False,
                       type="str",
                       default="profile-based",
                       choices=['profile-based', 'policy-based']),
        ssl_ssh_profile=dict(required=False, type="str"),
        scope_members=dict(required=False, type="str"),
        scope_members_vdom=dict(required=False, type="str", default="root"),
        parent_folder=dict(required=False, type="str"),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )
    # MODULE DATAGRAM
    paramgram = {
        "adom": module.params["adom"],
        "name": module.params["name"],
        "mode": module.params["mode"],
        "object_type": module.params["object_type"],
        "package-folder": module.params["package_folder"],
        "central-nat": module.params["central_nat"],
        "fwpolicy-implicit-log": module.params["fwpolicy_implicit_log"],
        "fwpolicy6-implicit-log": module.params["fwpolicy6_implicit_log"],
        "inspection-mode": module.params["inspection_mode"],
        "ngfw-mode": module.params["ngfw_mode"],
        "ssl-ssh-profile": module.params["ssl_ssh_profile"],
        "scope_members": module.params["scope_members"],
        "scope_members_vdom": module.params["scope_members_vdom"],
        "parent_folder": module.params["parent_folder"],
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    # BEGIN MODULE-SPECIFIC LOGIC -- THINGS NEED TO HAPPEN DEPENDING ON THE ENDPOINT AND OPERATION
    results = DEFAULT_RESULT_OBJ

    try:
        if paramgram["object_type"] == "pkg":
            results = fmgr_fwpol_package(fmgr, paramgram)
            fmgr.govern_response(module=module,
                                 results=results,
                                 ansible_facts=fmgr.construct_ansible_facts(
                                     results, module.params, paramgram))
    except Exception as err:
        raise FMGBaseException(err)

    try:
        # IF THE object_type IS FOLDER LETS RUN THAT METHOD
        if paramgram["object_type"] == "folder":
            results = fmgr_fwpol_package_folder(fmgr, paramgram)
            fmgr.govern_response(module=module,
                                 results=results,
                                 ansible_facts=fmgr.construct_ansible_facts(
                                     results, module.params, paramgram))
    except Exception as err:
        raise FMGBaseException(err)

    try:
        # IF THE object_type IS INSTALL AND NEEDED PARAMETERS ARE DEFINED INSTALL THE PACKAGE
        if paramgram["scope_members"] is not None and paramgram["name"] is not None and\
                paramgram["object_type"] == "install":
            results = fmgr_fwpol_package_install(fmgr, paramgram)
            fmgr.govern_response(module=module,
                                 results=results,
                                 ansible_facts=fmgr.construct_ansible_facts(
                                     results, module.params, paramgram))
    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 16
0
def main():
    argument_spec = dict(
        adom=dict(required=False, type="str", default="root"),
        mode=dict(required=False, type="str", choices=['add', 'set', 'delete'], default="add"),
        app_category=dict(required=False, type="str"),
        app_service_type=dict(required=False, type="str"),
        application=dict(required=False, type="str"),
        category=dict(required=False, type="str"),
        check_reset_range=dict(required=False, type="str"),
        color=dict(required=False, type="int", default=22),
        comment=dict(required=False, type="str"),
        custom_type=dict(required=False, type="str", choices=['tcp_udp_sctp', 'icmp', 'icmp6', 'ip', 'http', 'ftp',
                                                              'connect', 'socks_tcp', 'socks_udp', 'all'],
                         default="all"),
        explicit_proxy=dict(required=False, type="str", choices=['enable', 'disable'], default="disable"),
        fqdn=dict(required=False, type="str", default=""),
        group_name=dict(required=False, type="str"),
        group_member=dict(required=False, type="str"),
        icmp_code=dict(required=False, type="int"),
        icmp_type=dict(required=False, type="int"),
        iprange=dict(required=False, type="str", default="0.0.0.0"),
        name=dict(required=False, type="str"),
        protocol=dict(required=False, type="str"),
        protocol_number=dict(required=False, type="int"),
        sctp_portrange=dict(required=False, type="str"),
        session_ttl=dict(required=False, type="int", default=0),
        object_type=dict(required=False, type="str", choices=['custom', 'group', 'category']),
        tcp_halfclose_timer=dict(required=False, type="int", default=0),
        tcp_halfopen_timer=dict(required=False, type="int", default=0),
        tcp_portrange=dict(required=False, type="str"),
        tcp_timewait_timer=dict(required=False, type="int", default=0),
        udp_idle_timer=dict(required=False, type="int", default=0),
        udp_portrange=dict(required=False, type="str"),
        visibility=dict(required=False, type="str", default="enable", choices=["enable", "disable"]),

    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, )
    # MODULE DATAGRAM
    paramgram = {
        "adom": module.params["adom"],
        "app-category": module.params["app_category"],
        "app-service-type": module.params["app_service_type"],
        "application": module.params["application"],
        "category": module.params["category"],
        "check-reset-range": module.params["check_reset_range"],
        "color": module.params["color"],
        "comment": module.params["comment"],
        "custom_type": module.params["custom_type"],
        "explicit-proxy": module.params["explicit_proxy"],
        "fqdn": module.params["fqdn"],
        "group-name": module.params["group_name"],
        "group-member": module.params["group_member"],
        "icmp_code": module.params["icmp_code"],
        "icmp_type": module.params["icmp_type"],
        "iprange": module.params["iprange"],
        "name": module.params["name"],
        "mode": module.params["mode"],
        "protocol": module.params["protocol"],
        "protocol-number": module.params["protocol_number"],
        "sctp-portrange": module.params["sctp_portrange"],
        "object_type": module.params["object_type"],
        "session-ttl": module.params["session_ttl"],
        "tcp-halfclose-timer": module.params["tcp_halfclose_timer"],
        "tcp-halfopen-timer": module.params["tcp_halfopen_timer"],
        "tcp-portrange": module.params["tcp_portrange"],
        "tcp-timewait-timer": module.params["tcp_timewait_timer"],
        "udp-idle-timer": module.params["udp_idle_timer"],
        "udp-portrange": module.params["udp_portrange"],
        "visibility": module.params["visibility"],
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    results = DEFAULT_RESULT_OBJ

    try:
        # CHECK FOR CATEGORIES TO ADD
        # THIS IS ONLY WHEN OBJECT_TYPE ISN'T SPECIFICALLY ADDING A CATEGORY!
        # WE NEED TO ADD THE CATEGORY BEFORE ADDING THE OBJECT
        # IF ANY category ARE DEFINED AND MODE IS ADD OR SET LETS ADD THOSE
        # THIS IS A "BLIND ADD" AND THE EXIT CODE FOR OBJECT ALREADY EXISTS IS TREATED AS A PASS
        if paramgram["category"] is not None and paramgram["mode"] in ['add', 'set'] \
                and paramgram["object_type"] != "category":
            category_add = fmgr_fwobj_service_category(fmgr, paramgram)
            fmgr.govern_response(module=module, results=category_add,
                                 ansible_facts=fmgr.construct_ansible_facts(category_add, module.params, paramgram))
    except Exception as err:
        raise FMGBaseException(err)

    try:
        # IF OBJECT_TYPE IS CATEGORY...
        if paramgram["object_type"] == 'category':
            results = fmgr_fwobj_service_category(fmgr, paramgram)
            fmgr.govern_response(module=module, results=results, good_codes=[0, -2, -3],
                                 ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))
    except Exception as err:
        raise FMGBaseException(err)

    try:
        # IF OBJECT_TYPE IS CUSTOM...
        if paramgram["object_type"] == 'custom':
            results = fmgr_fwobj_service_custom(fmgr, paramgram)
            fmgr.govern_response(module=module, results=results, good_codes=[0, -2, -3],
                                 ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))
    except Exception as err:
        raise FMGBaseException(err)

    try:
        # IF OBJECT_TYPE IS GROUP...
        if paramgram["object_type"] == 'group':
            results = fmgr_fwobj_service_group(fmgr, paramgram)
            fmgr.govern_response(module=module, results=results, good_codes=[0, -2, -3],
                                 ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))
    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 17
0
    def return_response(self,
                        module,
                        results,
                        msg="NULL",
                        good_codes=(0, ),
                        stop_on_fail=True,
                        stop_on_success=False,
                        skipped=False,
                        changed=False,
                        unreachable=False,
                        failed=False,
                        success=False,
                        changed_if_success=True,
                        ansible_facts=()):
        """
        This function controls the logout and error reporting after an method or function runs. The exit_json for
        ansible comes from logic within this function. If this function returns just the msg, it means to continue
        execution on the playbook. It is called from the ansible module, or from the self.govern_response function.

        :param module: The Ansible Module CLASS object, used to run fail/exit json
        :type module: object
        :param msg: An overridable custom message from the module that called this.
        :type msg: string
        :param results: A dictionary object containing an API call results
        :type results: dict
        :param good_codes: A list of exit codes considered successful from FortiManager
        :type good_codes: list
        :param stop_on_fail: If true, stops playbook run when return code is NOT IN good codes (default: true)
        :type stop_on_fail: boolean
        :param stop_on_success: If true, stops playbook run when return code is IN good codes (default: false)
        :type stop_on_success: boolean
        :param changed: If True, tells Ansible that object was changed (default: false)
        :type skipped: boolean
        :param skipped: If True, tells Ansible that object was skipped (default: false)
        :type skipped: boolean
        :param unreachable: If True, tells Ansible that object was unreachable (default: false)
        :type unreachable: boolean
        :param failed: If True, tells Ansible that execution was a failure. Overrides good_codes. (default: false)
        :type unreachable: boolean
        :param success: If True, tells Ansible that execution was a success. Overrides good_codes. (default: false)
        :type unreachable: boolean
        :param changed_if_success: If True, defaults to changed if successful if you specify or not"
        :type changed_if_success: boolean
        :param ansible_facts: A prepared dictionary of ansible facts from the execution.
        :type ansible_facts: dict

        :return: A string object that contains an error message
        :rtype: str
        """

        # VALIDATION ERROR
        if (len(results) == 0) or (failed and success) or (changed
                                                           and unreachable):
            module.exit_json(
                msg=
                "Handle_response was called with no results, or conflicting failed/success or "
                "changed/unreachable parameters. Fix the exit code on module. "
                "Generic Failure",
                failed=True)

        # IDENTIFY SUCCESS/FAIL IF NOT DEFINED
        if not failed and not success:
            if len(results) > 0:
                if results[0] not in good_codes:
                    failed = True
                elif results[0] in good_codes:
                    success = True

        if len(results) > 0:
            # IF NO MESSAGE WAS SUPPLIED, GET IT FROM THE RESULTS, IF THAT DOESN'T WORK, THEN WRITE AN ERROR MESSAGE
            if msg == "NULL":
                try:
                    msg = results[1]['status']['message']
                except BaseException:
                    msg = "No status message returned at results[1][status][message], " \
                          "and none supplied to msg parameter for handle_response."

            if failed:
                # BECAUSE SKIPPED/FAILED WILL OFTEN OCCUR ON CODES THAT DON'T GET INCLUDED, THEY ARE CONSIDERED FAILURES
                # HOWEVER, THEY ARE MUTUALLY EXCLUSIVE, SO IF IT IS MARKED SKIPPED OR UNREACHABLE BY THE MODULE LOGIC
                # THEN REMOVE THE FAILED FLAG SO IT DOESN'T OVERRIDE THE DESIRED STATUS OF SKIPPED OR UNREACHABLE.
                if failed and skipped:
                    failed = False
                if failed and unreachable:
                    failed = False
                if stop_on_fail:
                    if self._uses_workspace:
                        try:
                            self.run_unlock()
                        except BaseException as err:
                            raise FMGBaseException(
                                msg=("Couldn't unlock ADOM! Error: " +
                                     str(err)))
                    module.exit_json(msg=msg,
                                     failed=failed,
                                     changed=changed,
                                     unreachable=unreachable,
                                     skipped=skipped,
                                     results=results[1],
                                     ansible_facts=ansible_facts,
                                     rc=results[0],
                                     invocation={
                                         "module_args":
                                         ansible_facts["ansible_params"]
                                     })
            elif success:
                if changed_if_success:
                    changed = True
                    success = False
                if stop_on_success:
                    if self._uses_workspace:
                        try:
                            self.run_unlock()
                        except BaseException as err:
                            raise FMGBaseException(
                                msg=("Couldn't unlock ADOM! Error: " +
                                     str(err)))
                    module.exit_json(msg=msg,
                                     success=success,
                                     changed=changed,
                                     unreachable=unreachable,
                                     skipped=skipped,
                                     results=results[1],
                                     ansible_facts=ansible_facts,
                                     rc=results[0],
                                     invocation={
                                         "module_args":
                                         ansible_facts["ansible_params"]
                                     })
        return msg
Ejemplo n.º 18
0
def main():
    argument_spec = dict(
        adom=dict(required=False, type="str", default="root"),
        vdom=dict(required=False, type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"],
                  type="str",
                  default="add"),
        grp_desc=dict(required=False, type="str"),
        grp_name=dict(required=True, type="str"),
        grp_members=dict(required=False, type="str"),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )
    paramgram = {
        "mode": module.params["mode"],
        "grp_name": module.params["grp_name"],
        "grp_desc": module.params["grp_desc"],
        "grp_members": module.params["grp_members"],
        "adom": module.params["adom"],
        "vdom": module.params["vdom"]
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    # BEGIN MODULE-SPECIFIC LOGIC -- THINGS NEED TO HAPPEN DEPENDING ON THE ENDPOINT AND OPERATION
    results = DEFAULT_RESULT_OBJ
    try:
        # PROCESS THE GROUP ADDS FIRST
        if paramgram["grp_name"] is not None and paramgram["mode"] in [
                "add", "set", "update"
        ]:
            # add device group
            results = add_device_group(fmgr, paramgram)
            fmgr.govern_response(module=module,
                                 results=results,
                                 ansible_facts=fmgr.construct_ansible_facts(
                                     results, module.params, paramgram))

        # PROCESS THE GROUP MEMBER ADDS
        if paramgram["grp_members"] is not None and paramgram["mode"] in [
                "add", "set", "update"
        ]:
            # assign devices to device group
            results = add_group_member(fmgr, paramgram)
            fmgr.govern_response(module=module,
                                 results=results,
                                 ansible_facts=fmgr.construct_ansible_facts(
                                     results, module.params, paramgram))

        # PROCESS THE GROUP MEMBER DELETES
        if paramgram["grp_members"] is not None and paramgram[
                "mode"] == "delete":
            # remove devices grom a group
            results = delete_group_member(fmgr, paramgram)
            fmgr.govern_response(module=module,
                                 results=results,
                                 ansible_facts=fmgr.construct_ansible_facts(
                                     results, module.params, paramgram))

        # PROCESS THE GROUP DELETES, ONLY IF GRP_MEMBERS IS NOT NULL TOO
        if paramgram["grp_name"] is not None and paramgram[
                "mode"] == "delete" and paramgram["grp_members"] is None:
            # delete device group
            results = delete_device_group(fmgr, paramgram)
            fmgr.govern_response(module=module,
                                 results=results,
                                 ansible_facts=fmgr.construct_ansible_facts(
                                     results, module.params, paramgram))
    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 19
0
def main():
    argument_spec = dict(
        adom=dict(type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"],
                  type="str", default="add"),

        replacemsg_group=dict(required=False, type="str"),
        name=dict(required=False, type="str"),
        extended_log=dict(required=False, type="str",
                          choices=["disable", "enable"]),
        comment=dict(required=False, type="str"),
        block_malicious_url=dict(required=False, type="str", choices=[
                                 "disable", "enable"]),
        entries=dict(required=False, type="list"),
        entries_action=dict(required=False, type="str", choices=[
                            "pass", "block", "reset", "default"]),
        entries_application=dict(required=False, type="str"),
        entries_location=dict(required=False, type="str"),
        entries_log=dict(required=False, type="str",
                         choices=["disable", "enable"]),
        entries_log_attack_context=dict(
            required=False, type="str", choices=["disable", "enable"]),
        entries_log_packet=dict(required=False, type="str", choices=[
                                "disable", "enable"]),
        entries_os=dict(required=False, type="str"),
        entries_protocol=dict(required=False, type="str"),
        entries_quarantine=dict(required=False, type="str", choices=[
                                "none", "attacker"]),
        entries_quarantine_expiry=dict(required=False, type="str"),
        entries_quarantine_log=dict(
            required=False, type="str", choices=["disable", "enable"]),
        entries_rate_count=dict(required=False, type="int"),
        entries_rate_duration=dict(required=False, type="int"),
        entries_rate_mode=dict(required=False, type="str", choices=[
                               "periodical", "continuous"]),
        entries_rate_track=dict(required=False, type="str",
                                choices=["none", "src-ip", "dest-ip", "dhcp-client-mac", "dns-domain"]),
        entries_rule=dict(required=False, type="str"),
        entries_severity=dict(required=False, type="str"),
        entries_status=dict(required=False, type="str", choices=[
                            "disable", "enable", "default"]),

        entries_exempt_ip_dst_ip=dict(required=False, type="str"),
        entries_exempt_ip_src_ip=dict(required=False, type="str"),
        filter=dict(required=False, type="list"),
        filter_action=dict(required=False, type="str", choices=[
                           "pass", "block", "default", "reset"]),
        filter_application=dict(required=False, type="str"),
        filter_location=dict(required=False, type="str"),
        filter_log=dict(required=False, type="str",
                        choices=["disable", "enable"]),
        filter_log_packet=dict(required=False, type="str",
                               choices=["disable", "enable"]),
        filter_name=dict(required=False, type="str"),
        filter_os=dict(required=False, type="str"),
        filter_protocol=dict(required=False, type="str"),
        filter_quarantine=dict(required=False, type="str",
                               choices=["none", "attacker"]),
        filter_quarantine_expiry=dict(required=False, type="int"),
        filter_quarantine_log=dict(required=False, type="str", choices=[
                                   "disable", "enable"]),
        filter_severity=dict(required=False, type="str"),
        filter_status=dict(required=False, type="str", choices=[
                           "disable", "enable", "default"]),
        override=dict(required=False, type="list"),
        override_action=dict(required=False, type="str",
                             choices=["pass", "block", "reset"]),
        override_log=dict(required=False, type="str",
                          choices=["disable", "enable"]),
        override_log_packet=dict(required=False, type="str", choices=[
                                 "disable", "enable"]),
        override_quarantine=dict(required=False, type="str", choices=[
                                 "none", "attacker"]),
        override_quarantine_expiry=dict(required=False, type="int"),
        override_quarantine_log=dict(
            required=False, type="str", choices=["disable", "enable"]),
        override_rule_id=dict(required=False, type="str"),
        override_status=dict(required=False, type="str",
                             choices=["disable", "enable"]),

        override_exempt_ip_dst_ip=dict(required=False, type="str"),
        override_exempt_ip_src_ip=dict(required=False, type="str"),

    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, )
    # MODULE PARAMGRAM
    paramgram = {
        "mode": module.params["mode"],
        "adom": module.params["adom"],
        "replacemsg-group": module.params["replacemsg_group"],
        "name": module.params["name"],
        "extended-log": module.params["extended_log"],
        "comment": module.params["comment"],
        "block-malicious-url": module.params["block_malicious_url"],
        "entries": {
            "action": module.params["entries_action"],
            "application": module.params["entries_application"],
            "location": module.params["entries_location"],
            "log": module.params["entries_log"],
            "log-attack-context": module.params["entries_log_attack_context"],
            "log-packet": module.params["entries_log_packet"],
            "os": module.params["entries_os"],
            "protocol": module.params["entries_protocol"],
            "quarantine": module.params["entries_quarantine"],
            "quarantine-expiry": module.params["entries_quarantine_expiry"],
            "quarantine-log": module.params["entries_quarantine_log"],
            "rate-count": module.params["entries_rate_count"],
            "rate-duration": module.params["entries_rate_duration"],
            "rate-mode": module.params["entries_rate_mode"],
            "rate-track": module.params["entries_rate_track"],
            "rule": module.params["entries_rule"],
            "severity": module.params["entries_severity"],
            "status": module.params["entries_status"],
            "exempt-ip": {
                "dst-ip": module.params["entries_exempt_ip_dst_ip"],
                "src-ip": module.params["entries_exempt_ip_src_ip"],
            },
        },
        "filter": {
            "action": module.params["filter_action"],
            "application": module.params["filter_application"],
            "location": module.params["filter_location"],
            "log": module.params["filter_log"],
            "log-packet": module.params["filter_log_packet"],
            "name": module.params["filter_name"],
            "os": module.params["filter_os"],
            "protocol": module.params["filter_protocol"],
            "quarantine": module.params["filter_quarantine"],
            "quarantine-expiry": module.params["filter_quarantine_expiry"],
            "quarantine-log": module.params["filter_quarantine_log"],
            "severity": module.params["filter_severity"],
            "status": module.params["filter_status"],
        },
        "override": {
            "action": module.params["override_action"],
            "log": module.params["override_log"],
            "log-packet": module.params["override_log_packet"],
            "quarantine": module.params["override_quarantine"],
            "quarantine-expiry": module.params["override_quarantine_expiry"],
            "quarantine-log": module.params["override_quarantine_log"],
            "rule-id": module.params["override_rule_id"],
            "status": module.params["override_status"],
            "exempt-ip": {
                "dst-ip": module.params["override_exempt_ip_dst_ip"],
                "src-ip": module.params["override_exempt_ip_src_ip"],
            }
        }
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    list_overrides = ['entries', 'filter', 'override']

    paramgram = fmgr.tools.paramgram_child_list_override(list_overrides=list_overrides,
                                                         paramgram=paramgram, module=module)

    results = DEFAULT_RESULT_OBJ
    try:
        results = fmgr_ips_sensor_modify(fmgr, paramgram)
        fmgr.govern_response(module=module, results=results,
                             ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 20
0
    def govern_response(self, module, results, msg=None, good_codes=None,
                        stop_on_fail=None, stop_on_success=None, skipped=None,
                        changed=None, unreachable=None, failed=None, success=None, changed_if_success=None,
                        ansible_facts=None):
        """
        This function will attempt to apply default values to canned responses from FortiManager we know of.
        This saves time, and turns the response in the module into a "one-liner", while still giving us...
        the flexibility to directly use return_response in modules if we have too. This function saves repeated code.

        :param module: The Ansible Module CLASS object, used to run fail/exit json
        :type module: object
        :param msg: An overridable custom message from the module that called this.
        :type msg: string
        :param results: A dictionary object containing an API call results
        :type results: dict
        :param good_codes: A list of exit codes considered successful from FortiManager
        :type good_codes: list
        :param stop_on_fail: If true, stops playbook run when return code is NOT IN good codes (default: true)
        :type stop_on_fail: boolean
        :param stop_on_success: If true, stops playbook run when return code is IN good codes (default: false)
        :type stop_on_success: boolean
        :param changed: If True, tells Ansible that object was changed (default: false)
        :type skipped: boolean
        :param skipped: If True, tells Ansible that object was skipped (default: false)
        :type skipped: boolean
        :param unreachable: If True, tells Ansible that object was unreachable (default: false)
        :type unreachable: boolean
        :param failed: If True, tells Ansible that execution was a failure. Overrides good_codes. (default: false)
        :type unreachable: boolean
        :param success: If True, tells Ansible that execution was a success. Overrides good_codes. (default: false)
        :type unreachable: boolean
        :param changed_if_success: If True, defaults to changed if successful if you specify or not"
        :type changed_if_success: boolean
        :param ansible_facts: A prepared dictionary of ansible facts from the execution.
        :type ansible_facts: dict
        """
        if module is None and results is None:
            raise FMGBaseException("govern_response() was called without a module and/or results tuple! Fix!")
        # Get the Return code from results
        try:
            rc = results[0]
        except BaseException:
            raise FMGBaseException("govern_response() was called without the return code at results[0]")

        # init a few items
        rc_data = None

        # Get the default values for the said return code.
        try:
            rc_codes = FMGR_RC.get('fmgr_return_codes')
            rc_data = rc_codes.get(rc)
        except BaseException:
            pass

        if not rc_data:
            rc_data = {}
        # ONLY add to overrides if not none -- This is very important that the keys aren't added at this stage
        # if they are empty. And there aren't that many, so let's just do a few if then statements.
        if good_codes is not None:
            rc_data["good_codes"] = good_codes
        if stop_on_fail is not None:
            rc_data["stop_on_fail"] = stop_on_fail
        if stop_on_success is not None:
            rc_data["stop_on_success"] = stop_on_success
        if skipped is not None:
            rc_data["skipped"] = skipped
        if changed is not None:
            rc_data["changed"] = changed
        if unreachable is not None:
            rc_data["unreachable"] = unreachable
        if failed is not None:
            rc_data["failed"] = failed
        if success is not None:
            rc_data["success"] = success
        if changed_if_success is not None:
            rc_data["changed_if_success"] = changed_if_success
        if results is not None:
            rc_data["results"] = results
        if msg is not None:
            rc_data["msg"] = msg
        if ansible_facts is None:
            rc_data["ansible_facts"] = {}
        else:
            rc_data["ansible_facts"] = ansible_facts

        return self.return_response(module=module,
                                    results=results,
                                    msg=rc_data.get("msg", "NULL"),
                                    good_codes=rc_data.get("good_codes", (0,)),
                                    stop_on_fail=rc_data.get("stop_on_fail", True),
                                    stop_on_success=rc_data.get("stop_on_success", False),
                                    skipped=rc_data.get("skipped", False),
                                    changed=rc_data.get("changed", False),
                                    changed_if_success=rc_data.get("changed_if_success", False),
                                    unreachable=rc_data.get("unreachable", False),
                                    failed=rc_data.get("failed", False),
                                    success=rc_data.get("success", False),
                                    ansible_facts=rc_data.get("ansible_facts", dict()))
def main():
    argument_spec = dict(
        adom=dict(type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"], type="str", default="add"),

        type=dict(required=False, type="str", choices=["overload",
                                                       "one-to-one",
                                                       "fixed-port-range",
                                                       "port-block-allocation"]),
        startip=dict(required=False, type="str"),
        source_startip=dict(required=False, type="str"),
        source_endip=dict(required=False, type="str"),
        permit_any_host=dict(required=False, type="str", choices=["disable", "enable"]),
        pba_timeout=dict(required=False, type="int"),
        num_blocks_per_user=dict(required=False, type="int"),
        name=dict(required=False, type="str"),
        endip=dict(required=False, type="str"),
        comments=dict(required=False, type="str"),
        block_size=dict(required=False, type="int"),
        associated_interface=dict(required=False, type="str"),
        arp_reply=dict(required=False, type="str", choices=["disable", "enable"]),
        arp_intf=dict(required=False, type="str"),
        dynamic_mapping=dict(required=False, type="list"),
        dynamic_mapping_arp_intf=dict(required=False, type="str"),
        dynamic_mapping_arp_reply=dict(required=False, type="str", choices=["disable", "enable"]),
        dynamic_mapping_associated_interface=dict(required=False, type="str"),
        dynamic_mapping_block_size=dict(required=False, type="int"),
        dynamic_mapping_comments=dict(required=False, type="str"),
        dynamic_mapping_endip=dict(required=False, type="str"),
        dynamic_mapping_num_blocks_per_user=dict(required=False, type="int"),
        dynamic_mapping_pba_timeout=dict(required=False, type="int"),
        dynamic_mapping_permit_any_host=dict(required=False, type="str", choices=["disable", "enable"]),
        dynamic_mapping_source_endip=dict(required=False, type="str"),
        dynamic_mapping_source_startip=dict(required=False, type="str"),
        dynamic_mapping_startip=dict(required=False, type="str"),
        dynamic_mapping_type=dict(required=False, type="str", choices=["overload",
                                                                       "one-to-one",
                                                                       "fixed-port-range",
                                                                       "port-block-allocation"]),

    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, )
    # MODULE PARAMGRAM
    paramgram = {
        "mode": module.params["mode"],
        "adom": module.params["adom"],
        "type": module.params["type"],
        "startip": module.params["startip"],
        "source-startip": module.params["source_startip"],
        "source-endip": module.params["source_endip"],
        "permit-any-host": module.params["permit_any_host"],
        "pba-timeout": module.params["pba_timeout"],
        "num-blocks-per-user": module.params["num_blocks_per_user"],
        "name": module.params["name"],
        "endip": module.params["endip"],
        "comments": module.params["comments"],
        "block-size": module.params["block_size"],
        "associated-interface": module.params["associated_interface"],
        "arp-reply": module.params["arp_reply"],
        "arp-intf": module.params["arp_intf"],
        "dynamic_mapping": {
            "arp-intf": module.params["dynamic_mapping_arp_intf"],
            "arp-reply": module.params["dynamic_mapping_arp_reply"],
            "associated-interface": module.params["dynamic_mapping_associated_interface"],
            "block-size": module.params["dynamic_mapping_block_size"],
            "comments": module.params["dynamic_mapping_comments"],
            "endip": module.params["dynamic_mapping_endip"],
            "num-blocks-per-user": module.params["dynamic_mapping_num_blocks_per_user"],
            "pba-timeout": module.params["dynamic_mapping_pba_timeout"],
            "permit-any-host": module.params["dynamic_mapping_permit_any_host"],
            "source-endip": module.params["dynamic_mapping_source_endip"],
            "source-startip": module.params["dynamic_mapping_source_startip"],
            "startip": module.params["dynamic_mapping_startip"],
            "type": module.params["dynamic_mapping_type"],
        }
    }

    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    list_overrides = ['dynamic_mapping']
    paramgram = fmgr.tools.paramgram_child_list_override(list_overrides=list_overrides,
                                                         paramgram=paramgram, module=module)
    # UPDATE THE CHANGED PARAMGRAM
    module.paramgram = paramgram

    results = DEFAULT_RESULT_OBJ
    try:
        results = fmgr_fwobj_ippool_modify(fmgr, paramgram)
        fmgr.govern_response(module=module, results=results,
                             ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 22
0
def main():
    argument_spec = dict(
        adom=dict(type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"],
                  type="str",
                  default="add"),
        youtube_channel_status=dict(
            required=False,
            type="str",
            choices=["disable", "blacklist", "whitelist"]),
        wisp_servers=dict(required=False, type="str"),
        wisp_algorithm=dict(
            required=False,
            type="str",
            choices=["auto-learning", "primary-secondary", "round-robin"]),
        wisp=dict(required=False, type="str", choices=["disable", "enable"]),
        web_url_log=dict(required=False,
                         type="str",
                         choices=["disable", "enable"]),
        web_invalid_domain_log=dict(required=False,
                                    type="str",
                                    choices=["disable", "enable"]),
        web_ftgd_quota_usage=dict(required=False,
                                  type="str",
                                  choices=["disable", "enable"]),
        web_ftgd_err_log=dict(required=False,
                              type="str",
                              choices=["disable", "enable"]),
        web_filter_vbs_log=dict(required=False,
                                type="str",
                                choices=["disable", "enable"]),
        web_filter_unknown_log=dict(required=False,
                                    type="str",
                                    choices=["disable", "enable"]),
        web_filter_referer_log=dict(required=False,
                                    type="str",
                                    choices=["disable", "enable"]),
        web_filter_jscript_log=dict(required=False,
                                    type="str",
                                    choices=["disable", "enable"]),
        web_filter_js_log=dict(required=False,
                               type="str",
                               choices=["disable", "enable"]),
        web_filter_cookie_removal_log=dict(required=False,
                                           type="str",
                                           choices=["disable", "enable"]),
        web_filter_cookie_log=dict(required=False,
                                   type="str",
                                   choices=["disable", "enable"]),
        web_filter_command_block_log=dict(required=False,
                                          type="str",
                                          choices=["disable", "enable"]),
        web_filter_applet_log=dict(required=False,
                                   type="str",
                                   choices=["disable", "enable"]),
        web_filter_activex_log=dict(required=False,
                                    type="str",
                                    choices=["disable", "enable"]),
        web_extended_all_action_log=dict(required=False,
                                         type="str",
                                         choices=["disable", "enable"]),
        web_content_log=dict(required=False,
                             type="str",
                             choices=["disable", "enable"]),
        replacemsg_group=dict(required=False, type="str"),
        post_action=dict(required=False,
                         type="str",
                         choices=["normal", "block"]),
        ovrd_perm=dict(required=False,
                       type="list",
                       choices=[
                           "bannedword-override", "urlfilter-override",
                           "fortiguard-wf-override",
                           "contenttype-check-override"
                       ]),
        options=dict(required=False,
                     type="list",
                     choices=[
                         "block-invalid-url", "jscript", "js", "vbs",
                         "unknown", "wf-referer", "intrinsic", "wf-cookie",
                         "per-user-bwl", "activexfilter", "cookiefilter",
                         "javafilter"
                     ]),
        name=dict(required=False, type="str"),
        log_all_url=dict(required=False,
                         type="str",
                         choices=["disable", "enable"]),
        inspection_mode=dict(required=False,
                             type="str",
                             choices=["proxy", "flow-based"]),
        https_replacemsg=dict(required=False,
                              type="str",
                              choices=["disable", "enable"]),
        extended_log=dict(required=False,
                          type="str",
                          choices=["disable", "enable"]),
        comment=dict(required=False, type="str"),
        ftgd_wf=dict(required=False, type="list"),
        ftgd_wf_exempt_quota=dict(required=False, type="str"),
        ftgd_wf_max_quota_timeout=dict(required=False, type="int"),
        ftgd_wf_options=dict(required=False,
                             type="str",
                             choices=[
                                 "error-allow", "rate-server-ip",
                                 "connect-request-bypass", "ftgd-disable"
                             ]),
        ftgd_wf_ovrd=dict(required=False, type="str"),
        ftgd_wf_rate_crl_urls=dict(required=False,
                                   type="str",
                                   choices=["disable", "enable"]),
        ftgd_wf_rate_css_urls=dict(required=False,
                                   type="str",
                                   choices=["disable", "enable"]),
        ftgd_wf_rate_image_urls=dict(required=False,
                                     type="str",
                                     choices=["disable", "enable"]),
        ftgd_wf_rate_javascript_urls=dict(required=False,
                                          type="str",
                                          choices=["disable", "enable"]),
        ftgd_wf_filters_action=dict(
            required=False,
            type="str",
            choices=["block", "monitor", "warning", "authenticate"]),
        ftgd_wf_filters_auth_usr_grp=dict(required=False, type="str"),
        ftgd_wf_filters_category=dict(required=False, type="str"),
        ftgd_wf_filters_log=dict(required=False,
                                 type="str",
                                 choices=["disable", "enable"]),
        ftgd_wf_filters_override_replacemsg=dict(required=False, type="str"),
        ftgd_wf_filters_warn_duration=dict(required=False, type="str"),
        ftgd_wf_filters_warning_duration_type=dict(
            required=False, type="str", choices=["session", "timeout"]),
        ftgd_wf_filters_warning_prompt=dict(
            required=False, type="str", choices=["per-domain",
                                                 "per-category"]),
        ftgd_wf_quota_category=dict(required=False, type="str"),
        ftgd_wf_quota_duration=dict(required=False, type="str"),
        ftgd_wf_quota_override_replacemsg=dict(required=False, type="str"),
        ftgd_wf_quota_type=dict(required=False,
                                type="str",
                                choices=["time", "traffic"]),
        ftgd_wf_quota_unit=dict(required=False,
                                type="str",
                                choices=["B", "KB", "MB", "GB"]),
        ftgd_wf_quota_value=dict(required=False, type="int"),
        override=dict(required=False, type="list"),
        override_ovrd_cookie=dict(required=False,
                                  type="str",
                                  choices=["deny", "allow"]),
        override_ovrd_dur=dict(required=False, type="str"),
        override_ovrd_dur_mode=dict(required=False,
                                    type="str",
                                    choices=["constant", "ask"]),
        override_ovrd_scope=dict(
            required=False,
            type="str",
            choices=["user", "user-group", "ip", "ask", "browser"]),
        override_ovrd_user_group=dict(required=False, type="str"),
        override_profile=dict(required=False, type="str"),
        override_profile_attribute=dict(
            required=False,
            type="list",
            choices=[
                "User-Name", "NAS-IP-Address", "Framed-IP-Address",
                "Framed-IP-Netmask", "Filter-Id", "Login-IP-Host",
                "Reply-Message", "Callback-Number", "Callback-Id",
                "Framed-Route", "Framed-IPX-Network", "Class",
                "Called-Station-Id", "Calling-Station-Id", "NAS-Identifier",
                "Proxy-State", "Login-LAT-Service", "Login-LAT-Node",
                "Login-LAT-Group", "Framed-AppleTalk-Zone", "Acct-Session-Id",
                "Acct-Multi-Session-Id"
            ]),
        override_profile_type=dict(required=False,
                                   type="str",
                                   choices=["list", "radius"]),
        url_extraction=dict(required=False, type="list"),
        url_extraction_redirect_header=dict(required=False, type="str"),
        url_extraction_redirect_no_content=dict(required=False,
                                                type="str",
                                                choices=["disable", "enable"]),
        url_extraction_redirect_url=dict(required=False, type="str"),
        url_extraction_server_fqdn=dict(required=False, type="str"),
        url_extraction_status=dict(required=False,
                                   type="str",
                                   choices=["disable", "enable"]),
        web=dict(required=False, type="list"),
        web_blacklist=dict(required=False,
                           type="str",
                           choices=["disable", "enable"]),
        web_bword_table=dict(required=False, type="str"),
        web_bword_threshold=dict(required=False, type="int"),
        web_content_header_list=dict(required=False, type="str"),
        web_keyword_match=dict(required=False, type="str"),
        web_log_search=dict(required=False,
                            type="str",
                            choices=["disable", "enable"]),
        web_safe_search=dict(required=False,
                             type="str",
                             choices=["url", "header"]),
        web_urlfilter_table=dict(required=False, type="str"),
        web_whitelist=dict(required=False,
                           type="list",
                           choices=[
                               "exempt-av", "exempt-webcontent",
                               "exempt-activex-java-cookie", "exempt-dlp",
                               "exempt-rangeblock", "extended-log-others"
                           ]),
        web_youtube_restrict=dict(required=False,
                                  type="str",
                                  choices=["strict", "none", "moderate"]),
        youtube_channel_filter=dict(required=False, type="list"),
        youtube_channel_filter_channel_id=dict(required=False, type="str"),
        youtube_channel_filter_comment=dict(required=False, type="str"),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )
    # MODULE PARAMGRAM
    paramgram = {
        "mode":
        module.params["mode"],
        "adom":
        module.params["adom"],
        "youtube-channel-status":
        module.params["youtube_channel_status"],
        "wisp-servers":
        module.params["wisp_servers"],
        "wisp-algorithm":
        module.params["wisp_algorithm"],
        "wisp":
        module.params["wisp"],
        "web-url-log":
        module.params["web_url_log"],
        "web-invalid-domain-log":
        module.params["web_invalid_domain_log"],
        "web-ftgd-quota-usage":
        module.params["web_ftgd_quota_usage"],
        "web-ftgd-err-log":
        module.params["web_ftgd_err_log"],
        "web-filter-vbs-log":
        module.params["web_filter_vbs_log"],
        "web-filter-unknown-log":
        module.params["web_filter_unknown_log"],
        "web-filter-referer-log":
        module.params["web_filter_referer_log"],
        "web-filter-jscript-log":
        module.params["web_filter_jscript_log"],
        "web-filter-js-log":
        module.params["web_filter_js_log"],
        "web-filter-cookie-removal-log":
        module.params["web_filter_cookie_removal_log"],
        "web-filter-cookie-log":
        module.params["web_filter_cookie_log"],
        "web-filter-command-block-log":
        module.params["web_filter_command_block_log"],
        "web-filter-applet-log":
        module.params["web_filter_applet_log"],
        "web-filter-activex-log":
        module.params["web_filter_activex_log"],
        "web-extended-all-action-log":
        module.params["web_extended_all_action_log"],
        "web-content-log":
        module.params["web_content_log"],
        "replacemsg-group":
        module.params["replacemsg_group"],
        "post-action":
        module.params["post_action"],
        "ovrd-perm":
        module.params["ovrd_perm"],
        "options":
        module.params["options"],
        "name":
        module.params["name"],
        "log-all-url":
        module.params["log_all_url"],
        "inspection-mode":
        module.params["inspection_mode"],
        "https-replacemsg":
        module.params["https_replacemsg"],
        "extended-log":
        module.params["extended_log"],
        "comment":
        module.params["comment"],
        "ftgd-wf": {
            "exempt-quota": module.params["ftgd_wf_exempt_quota"],
            "max-quota-timeout": module.params["ftgd_wf_max_quota_timeout"],
            "options": module.params["ftgd_wf_options"],
            "ovrd": module.params["ftgd_wf_ovrd"],
            "rate-crl-urls": module.params["ftgd_wf_rate_crl_urls"],
            "rate-css-urls": module.params["ftgd_wf_rate_css_urls"],
            "rate-image-urls": module.params["ftgd_wf_rate_image_urls"],
            "rate-javascript-urls":
            module.params["ftgd_wf_rate_javascript_urls"],
            "filters": {
                "action":
                module.params["ftgd_wf_filters_action"],
                "auth-usr-grp":
                module.params["ftgd_wf_filters_auth_usr_grp"],
                "category":
                module.params["ftgd_wf_filters_category"],
                "log":
                module.params["ftgd_wf_filters_log"],
                "override-replacemsg":
                module.params["ftgd_wf_filters_override_replacemsg"],
                "warn-duration":
                module.params["ftgd_wf_filters_warn_duration"],
                "warning-duration-type":
                module.params["ftgd_wf_filters_warning_duration_type"],
                "warning-prompt":
                module.params["ftgd_wf_filters_warning_prompt"],
            },
            "quota": {
                "category":
                module.params["ftgd_wf_quota_category"],
                "duration":
                module.params["ftgd_wf_quota_duration"],
                "override-replacemsg":
                module.params["ftgd_wf_quota_override_replacemsg"],
                "type":
                module.params["ftgd_wf_quota_type"],
                "unit":
                module.params["ftgd_wf_quota_unit"],
                "value":
                module.params["ftgd_wf_quota_value"],
            },
        },
        "override": {
            "ovrd-cookie": module.params["override_ovrd_cookie"],
            "ovrd-dur": module.params["override_ovrd_dur"],
            "ovrd-dur-mode": module.params["override_ovrd_dur_mode"],
            "ovrd-scope": module.params["override_ovrd_scope"],
            "ovrd-user-group": module.params["override_ovrd_user_group"],
            "profile": module.params["override_profile"],
            "profile-attribute": module.params["override_profile_attribute"],
            "profile-type": module.params["override_profile_type"],
        },
        "url-extraction": {
            "redirect-header":
            module.params["url_extraction_redirect_header"],
            "redirect-no-content":
            module.params["url_extraction_redirect_no_content"],
            "redirect-url":
            module.params["url_extraction_redirect_url"],
            "server-fqdn":
            module.params["url_extraction_server_fqdn"],
            "status":
            module.params["url_extraction_status"],
        },
        "web": {
            "blacklist": module.params["web_blacklist"],
            "bword-table": module.params["web_bword_table"],
            "bword-threshold": module.params["web_bword_threshold"],
            "content-header-list": module.params["web_content_header_list"],
            "keyword-match": module.params["web_keyword_match"],
            "log-search": module.params["web_log_search"],
            "safe-search": module.params["web_safe_search"],
            "urlfilter-table": module.params["web_urlfilter_table"],
            "whitelist": module.params["web_whitelist"],
            "youtube-restrict": module.params["web_youtube_restrict"],
        },
        "youtube-channel-filter": {
            "channel-id": module.params["youtube_channel_filter_channel_id"],
            "comment": module.params["youtube_channel_filter_comment"],
        }
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    list_overrides = [
        'ftgd-wf', 'override', 'url-extraction', 'web',
        'youtube-channel-filter'
    ]
    paramgram = fmgr.tools.paramgram_child_list_override(
        list_overrides=list_overrides, paramgram=paramgram, module=module)

    results = DEFAULT_RESULT_OBJ

    try:

        results = fmgr_webfilter_profile_modify(fmgr, paramgram)
        fmgr.govern_response(module=module,
                             results=results,
                             ansible_facts=fmgr.construct_ansible_facts(
                                 results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
def main():
    argument_spec = dict(
        adom=dict(type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"], type="str", default="add"),

        name=dict(required=False, type="str"),
        comment=dict(required=False, type="str"),
        sccp=dict(required=False, type="dict"),
        sccp_block_mcast=dict(required=False, type="str", choices=["disable", "enable"]),
        sccp_log_call_summary=dict(required=False, type="str", choices=["disable", "enable"]),
        sccp_log_violations=dict(required=False, type="str", choices=["disable", "enable"]),
        sccp_max_calls=dict(required=False, type="int"),
        sccp_status=dict(required=False, type="str", choices=["disable", "enable"]),
        sccp_verify_header=dict(required=False, type="str", choices=["disable", "enable"]),
        sip=dict(required=False, type="dict"),
        sip_ack_rate=dict(required=False, type="int"),
        sip_block_ack=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_bye=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_cancel=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_geo_red_options=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_info=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_invite=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_long_lines=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_message=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_notify=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_options=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_prack=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_publish=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_refer=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_register=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_subscribe=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_unknown=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_block_update=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_bye_rate=dict(required=False, type="int"),
        sip_call_keepalive=dict(required=False, type="int"),
        sip_cancel_rate=dict(required=False, type="int"),
        sip_contact_fixup=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_hnt_restrict_source_ip=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_hosted_nat_traversal=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_info_rate=dict(required=False, type="int"),
        sip_invite_rate=dict(required=False, type="int"),
        sip_ips_rtp=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_log_call_summary=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_log_violations=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_malformed_header_allow=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_call_id=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_contact=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_content_length=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_content_type=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_cseq=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_expires=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_from=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_max_forwards=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_p_asserted_identity=dict(required=False, type="str", choices=["pass",
                                                                                           "discard",
                                                                                           "respond"]),
        sip_malformed_header_rack=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_record_route=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_route=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_rseq=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_a=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_b=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_c=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_i=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_k=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_m=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_o=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_r=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_s=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_t=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_v=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_sdp_z=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_to=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_header_via=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_malformed_request_line=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_max_body_length=dict(required=False, type="int"),
        sip_max_dialogs=dict(required=False, type="int"),
        sip_max_idle_dialogs=dict(required=False, type="int"),
        sip_max_line_length=dict(required=False, type="int"),
        sip_message_rate=dict(required=False, type="int"),
        sip_nat_trace=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_no_sdp_fixup=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_notify_rate=dict(required=False, type="int"),
        sip_open_contact_pinhole=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_open_record_route_pinhole=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_open_register_pinhole=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_open_via_pinhole=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_options_rate=dict(required=False, type="int"),
        sip_prack_rate=dict(required=False, type="int"),
        sip_preserve_override=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_provisional_invite_expiry_time=dict(required=False, type="int"),
        sip_publish_rate=dict(required=False, type="int"),
        sip_refer_rate=dict(required=False, type="int"),
        sip_register_contact_trace=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_register_rate=dict(required=False, type="int"),
        sip_rfc2543_branch=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_rtp=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_ssl_algorithm=dict(required=False, type="str", choices=["high", "medium", "low"]),
        sip_ssl_auth_client=dict(required=False, type="str"),
        sip_ssl_auth_server=dict(required=False, type="str"),
        sip_ssl_client_certificate=dict(required=False, type="str"),
        sip_ssl_client_renegotiation=dict(required=False, type="str", choices=["allow", "deny", "secure"]),
        sip_ssl_max_version=dict(required=False, type="str", choices=["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2"]),
        sip_ssl_min_version=dict(required=False, type="str", choices=["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2"]),
        sip_ssl_mode=dict(required=False, type="str", choices=["off", "full"]),
        sip_ssl_pfs=dict(required=False, type="str", choices=["require", "deny", "allow"]),
        sip_ssl_send_empty_frags=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_ssl_server_certificate=dict(required=False, type="str"),
        sip_status=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_strict_register=dict(required=False, type="str", choices=["disable", "enable"]),
        sip_subscribe_rate=dict(required=False, type="int"),
        sip_unknown_header=dict(required=False, type="str", choices=["pass", "discard", "respond"]),
        sip_update_rate=dict(required=False, type="int"),

    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, )
    # MODULE PARAMGRAM
    paramgram = {
        "mode": module.params["mode"],
        "adom": module.params["adom"],
        "name": module.params["name"],
        "comment": module.params["comment"],
        "sccp": {
            "block-mcast": module.params["sccp_block_mcast"],
            "log-call-summary": module.params["sccp_log_call_summary"],
            "log-violations": module.params["sccp_log_violations"],
            "max-calls": module.params["sccp_max_calls"],
            "status": module.params["sccp_status"],
            "verify-header": module.params["sccp_verify_header"],
        },
        "sip": {
            "ack-rate": module.params["sip_ack_rate"],
            "block-ack": module.params["sip_block_ack"],
            "block-bye": module.params["sip_block_bye"],
            "block-cancel": module.params["sip_block_cancel"],
            "block-geo-red-options": module.params["sip_block_geo_red_options"],
            "block-info": module.params["sip_block_info"],
            "block-invite": module.params["sip_block_invite"],
            "block-long-lines": module.params["sip_block_long_lines"],
            "block-message": module.params["sip_block_message"],
            "block-notify": module.params["sip_block_notify"],
            "block-options": module.params["sip_block_options"],
            "block-prack": module.params["sip_block_prack"],
            "block-publish": module.params["sip_block_publish"],
            "block-refer": module.params["sip_block_refer"],
            "block-register": module.params["sip_block_register"],
            "block-subscribe": module.params["sip_block_subscribe"],
            "block-unknown": module.params["sip_block_unknown"],
            "block-update": module.params["sip_block_update"],
            "bye-rate": module.params["sip_bye_rate"],
            "call-keepalive": module.params["sip_call_keepalive"],
            "cancel-rate": module.params["sip_cancel_rate"],
            "contact-fixup": module.params["sip_contact_fixup"],
            "hnt-restrict-source-ip": module.params["sip_hnt_restrict_source_ip"],
            "hosted-nat-traversal": module.params["sip_hosted_nat_traversal"],
            "info-rate": module.params["sip_info_rate"],
            "invite-rate": module.params["sip_invite_rate"],
            "ips-rtp": module.params["sip_ips_rtp"],
            "log-call-summary": module.params["sip_log_call_summary"],
            "log-violations": module.params["sip_log_violations"],
            "malformed-header-allow": module.params["sip_malformed_header_allow"],
            "malformed-header-call-id": module.params["sip_malformed_header_call_id"],
            "malformed-header-contact": module.params["sip_malformed_header_contact"],
            "malformed-header-content-length": module.params["sip_malformed_header_content_length"],
            "malformed-header-content-type": module.params["sip_malformed_header_content_type"],
            "malformed-header-cseq": module.params["sip_malformed_header_cseq"],
            "malformed-header-expires": module.params["sip_malformed_header_expires"],
            "malformed-header-from": module.params["sip_malformed_header_from"],
            "malformed-header-max-forwards": module.params["sip_malformed_header_max_forwards"],
            "malformed-header-p-asserted-identity": module.params["sip_malformed_header_p_asserted_identity"],
            "malformed-header-rack": module.params["sip_malformed_header_rack"],
            "malformed-header-record-route": module.params["sip_malformed_header_record_route"],
            "malformed-header-route": module.params["sip_malformed_header_route"],
            "malformed-header-rseq": module.params["sip_malformed_header_rseq"],
            "malformed-header-sdp-a": module.params["sip_malformed_header_sdp_a"],
            "malformed-header-sdp-b": module.params["sip_malformed_header_sdp_b"],
            "malformed-header-sdp-c": module.params["sip_malformed_header_sdp_c"],
            "malformed-header-sdp-i": module.params["sip_malformed_header_sdp_i"],
            "malformed-header-sdp-k": module.params["sip_malformed_header_sdp_k"],
            "malformed-header-sdp-m": module.params["sip_malformed_header_sdp_m"],
            "malformed-header-sdp-o": module.params["sip_malformed_header_sdp_o"],
            "malformed-header-sdp-r": module.params["sip_malformed_header_sdp_r"],
            "malformed-header-sdp-s": module.params["sip_malformed_header_sdp_s"],
            "malformed-header-sdp-t": module.params["sip_malformed_header_sdp_t"],
            "malformed-header-sdp-v": module.params["sip_malformed_header_sdp_v"],
            "malformed-header-sdp-z": module.params["sip_malformed_header_sdp_z"],
            "malformed-header-to": module.params["sip_malformed_header_to"],
            "malformed-header-via": module.params["sip_malformed_header_via"],
            "malformed-request-line": module.params["sip_malformed_request_line"],
            "max-body-length": module.params["sip_max_body_length"],
            "max-dialogs": module.params["sip_max_dialogs"],
            "max-idle-dialogs": module.params["sip_max_idle_dialogs"],
            "max-line-length": module.params["sip_max_line_length"],
            "message-rate": module.params["sip_message_rate"],
            "nat-trace": module.params["sip_nat_trace"],
            "no-sdp-fixup": module.params["sip_no_sdp_fixup"],
            "notify-rate": module.params["sip_notify_rate"],
            "open-contact-pinhole": module.params["sip_open_contact_pinhole"],
            "open-record-route-pinhole": module.params["sip_open_record_route_pinhole"],
            "open-register-pinhole": module.params["sip_open_register_pinhole"],
            "open-via-pinhole": module.params["sip_open_via_pinhole"],
            "options-rate": module.params["sip_options_rate"],
            "prack-rate": module.params["sip_prack_rate"],
            "preserve-override": module.params["sip_preserve_override"],
            "provisional-invite-expiry-time": module.params["sip_provisional_invite_expiry_time"],
            "publish-rate": module.params["sip_publish_rate"],
            "refer-rate": module.params["sip_refer_rate"],
            "register-contact-trace": module.params["sip_register_contact_trace"],
            "register-rate": module.params["sip_register_rate"],
            "rfc2543-branch": module.params["sip_rfc2543_branch"],
            "rtp": module.params["sip_rtp"],
            "ssl-algorithm": module.params["sip_ssl_algorithm"],
            "ssl-auth-client": module.params["sip_ssl_auth_client"],
            "ssl-auth-server": module.params["sip_ssl_auth_server"],
            "ssl-client-certificate": module.params["sip_ssl_client_certificate"],
            "ssl-client-renegotiation": module.params["sip_ssl_client_renegotiation"],
            "ssl-max-version": module.params["sip_ssl_max_version"],
            "ssl-min-version": module.params["sip_ssl_min_version"],
            "ssl-mode": module.params["sip_ssl_mode"],
            "ssl-pfs": module.params["sip_ssl_pfs"],
            "ssl-send-empty-frags": module.params["sip_ssl_send_empty_frags"],
            "ssl-server-certificate": module.params["sip_ssl_server_certificate"],
            "status": module.params["sip_status"],
            "strict-register": module.params["sip_strict_register"],
            "subscribe-rate": module.params["sip_subscribe_rate"],
            "unknown-header": module.params["sip_unknown_header"],
            "update-rate": module.params["sip_update_rate"],
        }
    }

    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    list_overrides = ['sccp', 'sip']
    paramgram = fmgr.tools.paramgram_child_list_override(list_overrides=list_overrides,
                                                         paramgram=paramgram, module=module)
    module.paramgram = paramgram

    results = DEFAULT_RESULT_OBJ
    try:

        results = fmgr_voip_profile_modify(fmgr, paramgram)
        fmgr.govern_response(module=module, results=results,
                             ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 24
0
def main():
    argument_spec = dict(
        adom=dict(type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"], type="str", default="add"),

        youtube_restrict=dict(required=False, type="str", choices=["strict", "moderate"]),
        sdns_ftgd_err_log=dict(required=False, type="str", choices=["disable", "enable"]),
        sdns_domain_log=dict(required=False, type="str", choices=["disable", "enable"]),
        safe_search=dict(required=False, type="str", choices=["disable", "enable"]),
        redirect_portal=dict(required=False, type="str"),
        name=dict(required=False, type="str"),
        log_all_domain=dict(required=False, type="str", choices=["disable", "enable"]),
        external_ip_blocklist=dict(required=False, type="str"),
        comment=dict(required=False, type="str"),
        block_botnet=dict(required=False, type="str", choices=["disable", "enable"]),
        block_action=dict(required=False, type="str", choices=["block", "redirect"]),

        domain_filter_domain_filter_table=dict(required=False, type="str"),

        ftgd_dns_options=dict(required=False, type="str", choices=["error-allow", "ftgd-disable"]),

        ftgd_dns_filters_action=dict(required=False, type="str", choices=["monitor", "block"]),
        ftgd_dns_filters_category=dict(required=False, type="str"),
        ftgd_dns_filters_log=dict(required=False, type="str", choices=["disable", "enable"]),

    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, )
    # MODULE PARAMGRAM
    paramgram = {
        "mode": module.params["mode"],
        "adom": module.params["adom"],
        "youtube-restrict": module.params["youtube_restrict"],
        "sdns-ftgd-err-log": module.params["sdns_ftgd_err_log"],
        "sdns-domain-log": module.params["sdns_domain_log"],
        "safe-search": module.params["safe_search"],
        "redirect-portal": module.params["redirect_portal"],
        "name": module.params["name"],
        "log-all-domain": module.params["log_all_domain"],
        "external-ip-blocklist": module.params["external_ip_blocklist"],
        "comment": module.params["comment"],
        "block-botnet": module.params["block_botnet"],
        "block-action": module.params["block_action"],
        "domain-filter": {
            "domain-filter-table": module.params["domain_filter_domain_filter_table"],
        },
        "ftgd-dns": {
            "options": module.params["ftgd_dns_options"],
            "filters": {
                "action": module.params["ftgd_dns_filters_action"],
                "category": module.params["ftgd_dns_filters_category"],
                "log": module.params["ftgd_dns_filters_log"],
            }
        }
    }

    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    results = DEFAULT_RESULT_OBJ

    try:
        results = fmgr_dnsfilter_profile_modify(fmgr, paramgram)
        fmgr.govern_response(module=module, results=results,
                             ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 25
0
def main():
    argument_spec = dict(
        adom=dict(type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"], type="str", default="add"),

        webfilter_profile=dict(required=False, type="str"),
        waf_profile=dict(required=False, type="str"),
        voip_profile=dict(required=False, type="str"),
        ssl_ssh_profile=dict(required=False, type="str"),
        ssh_filter_profile=dict(required=False, type="str"),
        spamfilter_profile=dict(required=False, type="str"),
        profile_protocol_options=dict(required=False, type="str"),
        name=dict(required=False, type="str"),
        mms_profile=dict(required=False, type="str"),
        ips_sensor=dict(required=False, type="str"),
        icap_profile=dict(required=False, type="str"),
        dnsfilter_profile=dict(required=False, type="str"),
        dlp_sensor=dict(required=False, type="str"),
        av_profile=dict(required=False, type="str"),
        application_list=dict(required=False, type="str"),

    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, )
    # MODULE PARAMGRAM
    paramgram = {
        "mode": module.params["mode"],
        "adom": module.params["adom"],
        "webfilter-profile": module.params["webfilter_profile"],
        "waf-profile": module.params["waf_profile"],
        "voip-profile": module.params["voip_profile"],
        "ssl-ssh-profile": module.params["ssl_ssh_profile"],
        "ssh-filter-profile": module.params["ssh_filter_profile"],
        "spamfilter-profile": module.params["spamfilter_profile"],
        "profile-protocol-options": module.params["profile_protocol_options"],
        "name": module.params["name"],
        "mms-profile": module.params["mms_profile"],
        "ips-sensor": module.params["ips_sensor"],
        "icap-profile": module.params["icap_profile"],
        "dnsfilter-profile": module.params["dnsfilter_profile"],
        "dlp-sensor": module.params["dlp_sensor"],
        "av-profile": module.params["av_profile"],
        "application-list": module.params["application_list"],

    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    results = DEFAULT_RESULT_OBJ

    try:
        results = fmgr_firewall_profile_group_modify(fmgr, paramgram)
        fmgr.govern_response(module=module, results=results,
                             ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 26
0
def main():
    argument_spec = dict(
        adom=dict(type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"],
                  type="str",
                  default="add"),
        spam_rbl_table=dict(required=False, type="str"),
        spam_mheader_table=dict(required=False, type="str"),
        spam_log_fortiguard_response=dict(required=False,
                                          type="str",
                                          choices=["disable", "enable"]),
        spam_log=dict(required=False,
                      type="str",
                      choices=["disable", "enable"]),
        spam_iptrust_table=dict(required=False, type="str"),
        spam_filtering=dict(required=False,
                            type="str",
                            choices=["disable", "enable"]),
        spam_bword_threshold=dict(required=False, type="int"),
        spam_bword_table=dict(required=False, type="str"),
        spam_bwl_table=dict(required=False, type="str"),
        replacemsg_group=dict(required=False, type="str"),
        options=dict(required=False,
                     type="list",
                     choices=[
                         "bannedword", "spamfsip", "spamfssubmit",
                         "spamfschksum", "spamfsurl", "spamhelodns",
                         "spamraddrdns", "spamrbl", "spamhdrcheck",
                         "spamfsphish", "spambwl"
                     ]),
        name=dict(required=False, type="str"),
        flow_based=dict(required=False,
                        type="str",
                        choices=["disable", "enable"]),
        external=dict(required=False,
                      type="str",
                      choices=["disable", "enable"]),
        comment=dict(required=False, type="str"),
        gmail=dict(required=False, type="dict"),
        gmail_log=dict(required=False,
                       type="str",
                       choices=["disable", "enable"]),
        imap=dict(required=False, type="dict"),
        imap_action=dict(required=False, type="str", choices=["pass", "tag"]),
        imap_log=dict(required=False,
                      type="str",
                      choices=["disable", "enable"]),
        imap_tag_msg=dict(required=False, type="str"),
        imap_tag_type=dict(required=False,
                           type="str",
                           choices=["subject", "header", "spaminfo"]),
        mapi=dict(required=False, type="dict"),
        mapi_action=dict(required=False,
                         type="str",
                         choices=["pass", "discard"]),
        mapi_log=dict(required=False,
                      type="str",
                      choices=["disable", "enable"]),
        msn_hotmail=dict(required=False, type="dict"),
        msn_hotmail_log=dict(required=False,
                             type="str",
                             choices=["disable", "enable"]),
        pop3=dict(required=False, type="dict"),
        pop3_action=dict(required=False, type="str", choices=["pass", "tag"]),
        pop3_log=dict(required=False,
                      type="str",
                      choices=["disable", "enable"]),
        pop3_tag_msg=dict(required=False, type="str"),
        pop3_tag_type=dict(required=False,
                           type="str",
                           choices=["subject", "header", "spaminfo"]),
        smtp=dict(required=False, type="dict"),
        smtp_action=dict(required=False,
                         type="str",
                         choices=["pass", "tag", "discard"]),
        smtp_hdrip=dict(required=False,
                        type="str",
                        choices=["disable", "enable"]),
        smtp_local_override=dict(required=False,
                                 type="str",
                                 choices=["disable", "enable"]),
        smtp_log=dict(required=False,
                      type="str",
                      choices=["disable", "enable"]),
        smtp_tag_msg=dict(required=False, type="str"),
        smtp_tag_type=dict(required=False,
                           type="str",
                           choices=["subject", "header", "spaminfo"]),
        yahoo_mail=dict(required=False, type="dict"),
        yahoo_mail_log=dict(required=False,
                            type="str",
                            choices=["disable", "enable"]),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )
    # MODULE PARAMGRAM
    paramgram = {
        "mode":
        module.params["mode"],
        "adom":
        module.params["adom"],
        "spam-rbl-table":
        module.params["spam_rbl_table"],
        "spam-mheader-table":
        module.params["spam_mheader_table"],
        "spam-log-fortiguard-response":
        module.params["spam_log_fortiguard_response"],
        "spam-log":
        module.params["spam_log"],
        "spam-iptrust-table":
        module.params["spam_iptrust_table"],
        "spam-filtering":
        module.params["spam_filtering"],
        "spam-bword-threshold":
        module.params["spam_bword_threshold"],
        "spam-bword-table":
        module.params["spam_bword_table"],
        "spam-bwl-table":
        module.params["spam_bwl_table"],
        "replacemsg-group":
        module.params["replacemsg_group"],
        "options":
        module.params["options"],
        "name":
        module.params["name"],
        "flow-based":
        module.params["flow_based"],
        "external":
        module.params["external"],
        "comment":
        module.params["comment"],
        "gmail": {
            "log": module.params["gmail_log"],
        },
        "imap": {
            "action": module.params["imap_action"],
            "log": module.params["imap_log"],
            "tag-msg": module.params["imap_tag_msg"],
            "tag-type": module.params["imap_tag_type"],
        },
        "mapi": {
            "action": module.params["mapi_action"],
            "log": module.params["mapi_log"],
        },
        "msn-hotmail": {
            "log": module.params["msn_hotmail_log"],
        },
        "pop3": {
            "action": module.params["pop3_action"],
            "log": module.params["pop3_log"],
            "tag-msg": module.params["pop3_tag_msg"],
            "tag-type": module.params["pop3_tag_type"],
        },
        "smtp": {
            "action": module.params["smtp_action"],
            "hdrip": module.params["smtp_hdrip"],
            "local-override": module.params["smtp_local_override"],
            "log": module.params["smtp_log"],
            "tag-msg": module.params["smtp_tag_msg"],
            "tag-type": module.params["smtp_tag_type"],
        },
        "yahoo-mail": {
            "log": module.params["yahoo_mail_log"],
        }
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    list_overrides = [
        'gmail', 'imap', 'mapi', 'msn-hotmail', 'pop3', 'smtp', 'yahoo-mail'
    ]
    paramgram = fmgr.tools.paramgram_child_list_override(
        list_overrides=list_overrides, paramgram=paramgram, module=module)

    results = DEFAULT_RESULT_OBJ
    try:

        results = fmgr_spamfilter_profile_modify(fmgr, paramgram)
        fmgr.govern_response(module=module,
                             results=results,
                             ansible_facts=fmgr.construct_ansible_facts(
                                 results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
def main():
    argument_spec = dict(
        adom=dict(required=False, type="str", default="root"),
        mode=dict(choices=["add", "set", "delete"], type="str", default="add"),
        allow_routing=dict(required=False,
                           type="str",
                           choices=['enable', 'disable'],
                           default="disable"),
        associated_interface=dict(required=False, type="str"),
        cache_ttl=dict(required=False, type="str"),
        color=dict(required=False, type="str", default=22),
        comment=dict(required=False, type="str"),
        country=dict(required=False, type="str"),
        fqdn=dict(required=False, type="str"),
        name=dict(required=False, type="str"),
        start_ip=dict(required=False, type="str"),
        end_ip=dict(required=False, type="str"),
        ipv4=dict(required=False,
                  type="str",
                  choices=[
                      'ipmask', 'iprange', 'fqdn', 'wildcard', 'geography',
                      'wildcard-fqdn', 'group'
                  ]),
        visibility=dict(required=False,
                        type="str",
                        choices=['enable', 'disable'],
                        default="enable"),
        wildcard=dict(required=False, type="str"),
        wildcard_fqdn=dict(required=False, type="str"),
        ipv6=dict(required=False,
                  type="str",
                  choices=['ip', 'iprange', 'group']),
        group_members=dict(required=False, type="str"),
        group_name=dict(required=False, type="str"),
        ipv4addr=dict(required=False, type="str"),
        ipv6addr=dict(required=False, type="str"),
        multicast=dict(required=False,
                       type="str",
                       choices=['multicastrange', 'broadcastmask', 'ip6']),
        obj_id=dict(required=False, type="str"),
    )

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False,
                           mutually_exclusive=[['ipv4', 'ipv6'],
                                               ['ipv4', 'multicast'],
                                               ['ipv6', 'multicast']])
    paramgram = {
        "adom": module.params["adom"],
        "allow-routing": module.params["allow_routing"],
        "associated-interface": module.params["associated_interface"],
        "cache-ttl": module.params["cache_ttl"],
        "color": module.params["color"],
        "comment": module.params["comment"],
        "country": module.params["country"],
        "end-ip": module.params["end_ip"],
        "fqdn": module.params["fqdn"],
        "name": module.params["name"],
        "start-ip": module.params["start_ip"],
        "visibility": module.params["visibility"],
        "wildcard": module.params["wildcard"],
        "wildcard-fqdn": module.params["wildcard_fqdn"],
        "ipv6": module.params["ipv6"],
        "ipv4": module.params["ipv4"],
        "group_members": module.params["group_members"],
        "group_name": module.params["group_name"],
        "ipv4addr": module.params["ipv4addr"],
        "ipv6addr": module.params["ipv6addr"],
        "multicast": module.params["multicast"],
        "mode": module.params["mode"],
        "obj-id": module.params["obj_id"],
    }

    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr._tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    results = DEFAULT_RESULT_OBJ
    try:
        if paramgram["ipv4"]:
            results = fmgr_fwobj_ipv4(fmgr, paramgram)

        elif paramgram["ipv6"]:
            results = fmgr_fwobj_ipv6(fmgr, paramgram)

        elif paramgram["multicast"]:
            results = fmgr_fwobj_multicast(fmgr, paramgram)

        fmgr.govern_response(module=module,
                             results=results,
                             ansible_facts=fmgr.construct_ansible_facts(
                                 results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    if results is not None:
        return module.exit_json(**results[1])
    else:
        return module.exit_json(
            msg="Couldn't find a proper ipv4 or ipv6 or multicast parameter "
            "to run in the logic tree. Exiting...")
Ejemplo n.º 28
0
def main():
    argument_spec = dict(
        adom=dict(required=False, type="str", default="root"),
        object=dict(required=True,
                    type="str",
                    choices=["device", "cluster_nodes", "task", "custom"]),
        custom_endpoint=dict(required=False, type="str"),
        custom_dict=dict(required=False, type="dict"),
        device_ip=dict(required=False, type="str"),
        device_unique_name=dict(required=False, type="str"),
        device_serial=dict(required=False, type="str"),
        nodes=dict(required=False, type="list"),
        task_id=dict(required=False, type="str"))

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )
    paramgram = {
        "adom": module.params["adom"],
        "object": module.params["object"],
        "device_ip": module.params["device_ip"],
        "device_unique_name": module.params["device_unique_name"],
        "device_serial": module.params["device_serial"],
        "nodes": module.params["nodes"],
        "task_id": module.params["task_id"],
        "custom_endpoint": module.params["custom_endpoint"],
        "custom_dict": module.params["custom_dict"]
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    results = DEFAULT_RESULT_OBJ

    try:
        # IF OBJECT IS DEVICE
        if paramgram["object"] == "device" and any(v is not None for v in [
                paramgram["device_unique_name"], paramgram["device_serial"],
                paramgram["device_ip"]
        ]):
            results = fmgr_get_device(fmgr, paramgram)
            if results[0] not in [0]:
                module.fail_json(msg="Device query failed!")
            elif len(results[1]) == 0:
                module.exit_json(msg="Device NOT FOUND!")
            else:
                module.exit_json(msg="Device Found", **results[1][0])
    except Exception as err:
        raise FMGBaseException(err)

    try:
        # IF OBJECT IS CLUSTER_NODES
        if paramgram["object"] == "cluster_nodes" and paramgram[
                "nodes"] is not None:
            results = fmgr_get_cluster_nodes(fmgr, paramgram)
            if results["cluster_status"] == "MISSING":
                module.exit_json(msg="No cluster device found!", **results)
            elif results["query_status"] == "good":
                module.exit_json(msg="Cluster Found - Showing Nodes",
                                 **results)
            elif results is None:
                module.fail_json(
                    msg="Query FAILED -- Check module or playbook syntax")
    except Exception as err:
        raise FMGBaseException(err)

    try:
        # IF OBJECT IS TASK
        if paramgram["object"] == "task":
            results = fmgr_get_task_status(fmgr, paramgram)
            if results[0] != 0:
                module.fail_json(**results[1])
            if results[0] == 0:
                module.exit_json(**results[1])
    except Exception as err:
        raise FMGBaseException(err)

    try:
        # IF OBJECT IS CUSTOM
        if paramgram["object"] == "custom":
            results = fmgr_get_custom(fmgr, paramgram)
            if results[0] != 0:
                module.fail_json(
                    msg=
                    "QUERY FAILED -- Please check syntax check JSON guide if needed."
                )
            if results[0] == 0:
                results_len = len(results[1])
                if results_len > 0:
                    results_combine = dict()
                    if isinstance(results[1], dict):
                        results_combine["results"] = results[1]
                    if isinstance(results[1], list):
                        results_combine["results"] = results[1][0:results_len]
                    module.exit_json(msg="Custom Query Success",
                                     **results_combine)
                else:
                    module.exit_json(msg="NO RESULTS")
    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
def main():
    argument_spec = dict(
        adom=dict(type="str", default="root"),
        mode=dict(choices=["add", "set", "delete", "update"],
                  type="str",
                  default="add"),
        strip_encoding=dict(required=False,
                            type="str",
                            choices=["disable", "enable"]),
        name=dict(required=False, type="str"),
        log_header_change=dict(required=False,
                               type="str",
                               choices=["disable", "enable"]),
        header_x_forwarded_for=dict(required=False,
                                    type="str",
                                    choices=["pass", "add", "remove"]),
        header_x_authenticated_user=dict(required=False,
                                         type="str",
                                         choices=["pass", "add", "remove"]),
        header_x_authenticated_groups=dict(required=False,
                                           type="str",
                                           choices=["pass", "add", "remove"]),
        header_via_response=dict(required=False,
                                 type="str",
                                 choices=["pass", "add", "remove"]),
        header_via_request=dict(required=False,
                                type="str",
                                choices=["pass", "add", "remove"]),
        header_front_end_https=dict(required=False,
                                    type="str",
                                    choices=["pass", "add", "remove"]),
        header_client_ip=dict(required=False,
                              type="str",
                              choices=["pass", "add", "remove"]),
        headers=dict(required=False, type="list"),
        headers_action=dict(required=False,
                            type="str",
                            choices=[
                                "add-to-request", "add-to-response",
                                "remove-from-request", "remove-from-response"
                            ]),
        headers_content=dict(required=False, type="str"),
        headers_name=dict(required=False, type="str"),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )
    # MODULE PARAMGRAM
    paramgram = {
        "mode":
        module.params["mode"],
        "adom":
        module.params["adom"],
        "strip-encoding":
        module.params["strip_encoding"],
        "name":
        module.params["name"],
        "log-header-change":
        module.params["log_header_change"],
        "header-x-forwarded-for":
        module.params["header_x_forwarded_for"],
        "header-x-authenticated-user":
        module.params["header_x_authenticated_user"],
        "header-x-authenticated-groups":
        module.params["header_x_authenticated_groups"],
        "header-via-response":
        module.params["header_via_response"],
        "header-via-request":
        module.params["header_via_request"],
        "header-front-end-https":
        module.params["header_front_end_https"],
        "header-client-ip":
        module.params["header_client_ip"],
        "headers": {
            "action": module.params["headers_action"],
            "content": module.params["headers_content"],
            "name": module.params["headers_name"],
        }
    }

    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    list_overrides = ['headers']
    paramgram = fmgr.tools.paramgram_child_list_override(
        list_overrides=list_overrides, paramgram=paramgram, module=module)
    module.paramgram = paramgram

    results = DEFAULT_RESULT_OBJ
    try:
        results = fmgr_web_proxy_profile_modify(fmgr, paramgram)
        fmgr.govern_response(module=module,
                             results=results,
                             ansible_facts=fmgr.construct_ansible_facts(
                                 results, module.params, paramgram))

    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])
Ejemplo n.º 30
0
def main():
    argument_spec = dict(
        adom=dict(required=False, type="str", default="root"),
        vdom=dict(required=False, type="str", default="root"),
        mode=dict(choices=["add", "execute", "set", "delete"],
                  type="str",
                  default="add"),
        script_name=dict(required=True, type="str"),
        script_type=dict(required=False, type="str"),
        script_target=dict(required=False, type="str"),
        script_description=dict(required=False, type="str"),
        script_content=dict(required=False, type="str"),
        script_scope=dict(required=False, type="str"),
        script_package=dict(required=False, type="str"),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )
    paramgram = {
        "script_name": module.params["script_name"],
        "script_type": module.params["script_type"],
        "script_target": module.params["script_target"],
        "script_description": module.params["script_description"],
        "script_content": module.params["script_content"],
        "script_scope": module.params["script_scope"],
        "script_package": module.params["script_package"],
        "adom": module.params["adom"],
        "vdom": module.params["vdom"],
        "mode": module.params["mode"],
    }
    module.paramgram = paramgram
    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        fmgr = FortiManagerHandler(connection, module)
        fmgr.tools = FMGRCommon()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    results = DEFAULT_RESULT_OBJ

    try:
        if paramgram["mode"] in ['add', 'set']:
            results = set_script(fmgr, paramgram)
            fmgr.govern_response(module=module,
                                 results=results,
                                 msg="Operation Finished",
                                 ansible_facts=fmgr.construct_ansible_facts(
                                     results, module.params, module.params))
    except Exception as err:
        raise FMGBaseException(err)

    try:
        if paramgram["mode"] == "execute":
            results = execute_script(fmgr, paramgram)
            fmgr.govern_response(module=module,
                                 results=results,
                                 msg="Operation Finished",
                                 ansible_facts=fmgr.construct_ansible_facts(
                                     results, module.params, module.params))
    except Exception as err:
        raise FMGBaseException(err)

    try:
        if paramgram["mode"] == "delete":
            results = delete_script(fmgr, paramgram)
            fmgr.govern_response(module=module,
                                 results=results,
                                 msg="Operation Finished",
                                 ansible_facts=fmgr.construct_ansible_facts(
                                     results, module.params, module.params))
    except Exception as err:
        raise FMGBaseException(err)

    return module.exit_json(**results[1])