Exemplo 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 BaseException:
                    pass
                try:
                    if adom_lock_info[1][0]["lock_user"]:
                        locked_list.append(str(adom))
                    if adom_lock_info[1][0]["lock_user"] == self._logged_in_user:
                        locked_by_user_list.append({"adom": str(adom), "user": str(adom_lock_info[1][0]["lock_user"])})
                except BaseException as err:
                    raise FAZBaseException(err)
            self._locked_adom_list = locked_list
            self._locked_adoms_by_user = locked_by_user_list

        except BaseException as err:
            raise FAZBaseException(msg=("An error occurred while trying to get the locked adom list. Error: "
                                        + str(err)))
Exemplo n.º 2
0
 def check_mode(self):
     """
     Checks FortiAnalyzer for the use of Workspace mode
     """
     url = "/cli/global/system/global"
     code, resp_obj = self.send_request(FAZMethods.GET,
                                        self._tools.format_request(FAZMethods.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:
         self.uses_workspace = False
     except BaseException:
         raise FAZBaseException(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:
         self.uses_adoms = False
     except BaseException:
         raise FAZBaseException(msg="Couldn't determine adom-status in the plugin")
Exemplo n.º 3
0
    def return_connected_faz(self):
        """
        Returns the data stored under self._connected_faz

        :return: dict
        """
        try:
            if self._connected_faz:
                return self._connected_faz
        except BaseException:
            raise FAZBaseException("Couldn't Retrieve Connected FAZ Stats")
Exemplo n.º 4
0
    def send_request(self, method, params):
        """
        Responsible for actual sending of data to the connection httpapi base plugin. Does some formatting as well.
        :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":
                raise FAZBaseException("An attempt was made to login with the SID None and URL != login url.")
        except IndexError:
            raise FAZBaseException("An attempt was made at communicating with a FAZ with "
                                   "no valid session and an incorrectly formatted request.")
        except Exception:
            raise FAZBaseException("An attempt was made at communicating with a FAZ with "
                                   "no valid session and an unexpected error was discovered.")

        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 FAZBaseException(err)
Exemplo n.º 5
0
    def login(self, username, password):
        """
        This function will log the plugin into FortiAnalyzer, and return the results.
        :param username: Username of FortiAnalyzer Admin
        :param password: Password of FortiAnalyzer Admin

        :return: Dictionary of status, if it logged in or not.
        """

        self._logged_in_user = username
        self.send_request(FAZMethods.EXEC, self._tools.format_request(FAZMethods.EXEC, "sys/login/user",
                                                                      passwd=password, user=username,))

        if "FortiAnalyzer object connected to FortiAnalyzer" in self.__str__():
            # If Login worked, then inspect the FortiAnalyzer for Workspace Mode, and it's system information.
            self.inspect_faz()
            return
        else:
            raise FAZBaseException(msg="Unknown error while logging in...connection was lost during login operation...."
                                       " Exiting")
Exemplo n.º 6
0
 def inspect_faz(self):
     # CHECK FOR WORKSPACE MODE TO SEE IF WE HAVE TO ENABLE ADOM LOCKS
     status = self.get_system_status()
     if status[0] == -11:
         # THE CONNECTION GOT LOST SOMEHOW, REMOVE THE SID AND REPORT BAD LOGIN
         self.logout()
         raise FAZBaseException(msg="Error -11 -- the Session ID was likely malformed somehow. Contact authors."
                                    " Exiting")
     elif status[0] == 0:
         try:
             self.check_mode()
             if self._uses_adoms:
                 self.get_adom_list()
             if self._uses_workspace:
                 self.get_locked_adom_list()
             self._connected_faz = status[1]
             self._host = self._connected_faz["Hostname"]
         except BaseException:
             pass
     return
Exemplo n.º 7
0
def main():
    argument_spec = dict(
        adom=dict(required=False, type="str", default="root"),
        mode=dict(choices=["add", "delete", "promote"],
                  type="str",
                  default="add"),
        device_ip=dict(required=False, type="str"),
        device_username=dict(required=False, type="str"),
        device_password=dict(required=False, type="str", no_log=True),
        device_unique_name=dict(required=False, type="str"),
        device_serial=dict(required=False, type="str"),
        os_type=dict(required=False,
                     type="str",
                     choices=[
                         "unknown", "fos", "fsw", "foc", "fml", "faz", "fwb",
                         "fch", "fct", "log", "fmg", "fsa", "fdd", "fac"
                     ]),
        mgmt_mode=dict(required=False,
                       type="str",
                       choices=["unreg", "fmg", "faz", "fmgfaz"]),
        os_minor_vers=dict(required=False, type="str"),
        os_ver=dict(required=False,
                    type="str",
                    choices=[
                        "unknown", "0.0", "1.0", "2.0", "3.0", "4.0", "5.0",
                        "6.0"
                    ]),
        platform_str=dict(required=False, type="str"),
        faz_quota=dict(required=False, type="str"))

    required_if = [['mode', 'delete', ['device_unique_name']],
                   [
                       'mode', 'add',
                       [
                           'device_serial', 'device_username',
                           'device_password', 'device_unique_name',
                           'device_ip', 'mgmt_mode', 'platform_str'
                       ]
                   ]]

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
        required_if=required_if,
    )

    # START SESSION LOGIC
    paramgram = {
        "adom": module.params["adom"],
        "mode": module.params["mode"],
        "ip": module.params["device_ip"],
        "device_username": module.params["device_username"],
        "device_password": module.params["device_password"],
        "device_unique_name": module.params["device_unique_name"],
        "sn": module.params["device_serial"],
        "os_type": module.params["os_type"],
        "mgmt_mode": module.params["mgmt_mode"],
        "os_minor_vers": module.params["os_minor_vers"],
        "os_ver": module.params["os_ver"],
        "platform_str": module.params["platform_str"],
        "faz.quota": module.params["faz_quota"],
        "device_action": None
    }
    # INSERT THE PARAMGRAM INTO THE MODULE SO WHEN WE PASS IT TO MOD_UTILS.FortiManagerHandler IT HAS THAT INFO

    if paramgram["mode"] == "add":
        paramgram["device_action"] = "add_model"
    elif paramgram["mode"] == "promote":
        paramgram["device_action"] = "promote_unreg"
    module.paramgram = paramgram

    # TRY TO INIT THE CONNECTION SOCKET PATH AND FortiManagerHandler OBJECT AND TOOLS
    faz = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        faz = FortiAnalyzerHandler(connection, module)
        faz.tools = FAZCommon()
    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["mode"] == "add":
            results = faz_add_device(faz, paramgram)
    except BaseException as err:
        raise FAZBaseException(
            msg="An error occurred trying to add the device. Error: " +
            str(err))

    try:
        if paramgram["mode"] == "promote":
            if paramgram["ip"] is not None:
                results = faz_approve_unregistered_device_by_ip(faz, paramgram)
            elif paramgram["device_unique_name"] is not None:
                results = faz_approve_unregistered_device_by_name(
                    faz, paramgram)
    except BaseException as err:
        raise FAZBaseException(
            msg="An error occurred trying to promote the device. Error: " +
            str(err))

    try:
        if paramgram["mode"] == "delete":
            results = faz_delete_device(faz, paramgram)
    except BaseException as err:
        raise FAZBaseException(
            msg="An error occurred trying to delete the device. Error: " +
            str(err))

    # PROCESS RESULTS
    try:
        faz.govern_response(module=module,
                            results=results,
                            ansible_facts=faz.construct_ansible_facts(
                                results, module.params, paramgram))
    except BaseException as err:
        raise FAZBaseException(
            msg="An error occurred with govern_response(). Error: " + str(err))

    # This should only be hit if faz.govern_response is missed or failed somehow. In fact. It should never be hit.
    # But it's here JIC.
    return module.exit_json(**results[1])