Exemple #1
0
def shorten_url():
    data = request.json
    long_url = data["url"]
    shortener = Shortener(long_url)
    short_url = shortener.shorten_url()
    api_response = APIResponse(200, short_url)
    return jsonify(api_response.serialize())
Exemple #2
0
    def login_as_root(self, domain=None, payload=None):
        """
        This method allows to login into the management server with root permissions.
        In order to use this method the application should be run directly on the management server
        and to have super-user privileges.

        :param domain: [optional] name/uid/IP address of the domain you want to log into in an MDS environment
        :param payload: [optional] dict of additional parameters for the login command
        :return: APIResponse object with the relevant details from the login command.
        """
        python_absolute_path = os.path.expandvars(
            "$MDS_FWDIR/Python/bin/python")
        api_get_port_absolute_path = os.path.expandvars(
            "$MDS_FWDIR/scripts/api_get_port.py")
        mgmt_cli_absolute_path = os.path.expandvars("$CPDIR/bin/mgmt_cli")

        # try to get the management server's port by running a script
        if not self.is_port_default():
            port = self.get_port()
        else:
            try:
                port = json.loads(
                    subprocess.check_output([
                        python_absolute_path, api_get_port_absolute_path, "-f",
                        "json"
                    ]))["external_port"]
            # if can't, default back to what the user wrote or the default (443)
            except (ValueError, subprocess.CalledProcessError):
                port = self.get_port()

        try:
            # This simple dict->cli format works only because the login command doesn't require
            # any complex parameters like objects and lists
            new_payload = []
            if payload:
                for key in payload.keys():
                    new_payload += [key, payload[key]]
            if domain:
                new_payload += ["domain", domain]
            login_response = json.loads(
                subprocess.check_output([
                    mgmt_cli_absolute_path, "login", "-r", "true", "-f",
                    "json", "--port",
                    str(port)
                ] + new_payload))
            self.sid = login_response["sid"]
            self.server = "127.0.0.1"
            self.domain = domain
            self.api_version = login_response["api-server-version"]
            return APIResponse(login_response, success=True)
        except ValueError as err:
            raise APIClientException(
                "Could not load JSON from login as root command, perhaps no root privileges?\n"
                + str(type(err)) + " - " + str(err))
        except (WindowsError, subprocess.CalledProcessError) as err:
            raise APIClientException("Could not login as root:\n" +
                                     str(type(err)) + " - " + str(err))
Exemple #3
0
    def api_call(self, command, payload={}, server=None, sid=None, wait_for_task=True):
        # convert the json payload to a string if needed
        if isinstance(payload, str):
            _data = payload
        else:
            _data = json.dumps(payload, sort_keys=False)

        # update class members if needed.
        if server is None:
            server = self.server
        if sid is None:
            sid = self.sid

        # set headers
        _headers = {
            "User-Agent": "python-api-wrapper",
            "Accept": "*/*",
            "Content-Type": "application/json",
            "Content-Length": len(_data)}

        # in all API calls (except for 'login') a header containing the
        # CheckPoint session-id is required.
        if sid is not None:
            _headers["X-chkp-sid"] = sid

        # create ssl context with no ssl verification, we do it by ourselves
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE

        # create https connection
        conn = HTTPSConnection(server, self.port, context=context)

        # set fingerprint
        conn.fingerprint = self.fingerprint

        # set debug level
        conn.set_debuglevel(self.http_debug_level)

        url = "/web_api/" + command

        try:
            # send the data to the Check Point server
            conn.request("POST", url, _data, _headers)
            # get the response from the Check Point server
            response = conn.getresponse()
            res = APIResponse(response)

        except ValueError as err:
            if (err.args[0] == "fingerprint value mismatch"):
                err_message = "Error: Fingerprint value mismatch:\n" + " Expecting : {}\n".format(err.args[1]) + " Got       : {}\n".format(err.args[2]) + "if you trust the new fingerprint, edit the 'fingerprints.txt' file."
                res = APIResponse("", err_message)
            else:
                res = APIResponse("", err)
        except Exception as inst:
            res = APIResponse("", inst)

        # when the command is 'login' we'd like to convert the password to
        # "****" so that it would not appear in the debug file.
        if command == "login":
            json_data = json.loads(_data)
            json_data["password"] = "******"
            _data = json.dumps(json_data)

        # store the request and the response (for debug purpose).
        _api_log = {}
        _api_log["request"] = {
            "url": url,
            "payload": json.loads(_data),
            "headers": _headers}
        _api_log["response"] = res.res_obj
        self.api_calls.append(_api_log)

        # FOR MY DEBUG save debug data with all api calls to disk
        # out_file = open(self.debug_file, 'w+')
        # out_file.write(json.dumps(self.api_calls, indent=4, sort_keys=True))

        # If we want to wait for the task to end, wait for it
        if wait_for_task is True and res.success and "task-id" in res.data:
            res = self.__wait_for_task(res.data["task-id"])

        return res
Exemple #4
0
    def api_call(self, command, payload=None, sid=None, wait_for_task=True):
        """
        performs a web-service API request to the management server

        :param command: the command is placed in the URL field
        :param payload: a JSON object (or a string representing a JSON object) with the command arguments
        :param sid: [optional]. The Check Point session-id. when omitted use self.sid.
        :param wait_for_task: determines the behavior when the API server responds with a "task-id".
                              by default, the function will periodically check the status of the task
                              and will not return until the task is completed.
                              when wait_for_task=False, it is up to the user to call the "show-task" API and check
                              the status of the command.
        :return: APIResponse object
        :side-effects: updates the class's uid and server variables
        """
        self.check_fingerprint()
        if payload is None:
            payload = {}
        # Convert the json payload to a string if needed
        if isinstance(payload, str):
            _data = payload
        elif isinstance(payload, dict):
            _data = json.dumps(payload, sort_keys=False)
        else:
            raise TypeError('Invalid payload type - must be dict/string')
        # update class members if needed.
        if sid is None:
            sid = self.sid

        # Set headers
        _headers = {
            "User-Agent": "python-api-wrapper",
            "Accept": "*/*",
            "Content-Type": "application/json",
            "Content-Length": len(_data)
        }

        # In all API calls (except for 'login') a header containing the Check Point session-id is required.
        if sid is not None:
            _headers["X-chkp-sid"] = sid

        # Create ssl context with no ssl verification, we do it by ourselves
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE

        # create https connection
        if self.proxy_host and self.proxy_port:
            conn = HTTPSConnection(self.proxy_host,
                                   self.proxy_port,
                                   context=context)
            conn.set_tunnel(self.server, self.get_port())
        else:
            conn = HTTPSConnection(self.server,
                                   self.get_port(),
                                   context=context)

        # Set fingerprint
        conn.fingerprint = self.fingerprint

        # Set debug level
        conn.set_debuglevel(self.http_debug_level)
        url = "/web_api/" + (("v" + str(self.api_version) +
                              "/") if self.api_version else "") + command

        response = None
        try:
            # Send the data to the server
            conn.request("POST", url, _data, _headers)
            # Get the reply from the server
            response = conn.getresponse()
            res = APIResponse.from_http_response(response)
        except ValueError as err:
            if err.args[0] == "Fingerprint value mismatch":
                err_message = "Error: Fingerprint value mismatch:\n" + " Expecting : {}\n".format(
                    err.args[1]
                ) + " Got: {}\n".format(
                    err.args[2]
                ) + "If you trust the new fingerprint, edit the 'fingerprints.txt' file."
                res = APIResponse("", False, err_message=err_message)
            else:
                res = APIResponse("", False, err_message=err)
        except Exception as err:
            res = APIResponse("", False, err_message=err)

        if response:
            res.status_code = response.status

        # When the command is 'login' we'd like to convert the password to "****" so that it
        # would not appear as plaintext in the debug file.
        if command == "login":
            json_data = json.loads(_data)
            json_data["password"] = "******"
            _data = json.dumps(json_data)

        # Store the request and the reply (for debug purpose).
        _api_log = {
            "request": {
                "url": url,
                "payload": json.loads(_data),
                "headers": _headers
            },
            "response": res.response()
        }
        self.api_calls.append(_api_log)

        # If we want to wait for the task to end, wait for it
        if wait_for_task is True and res.success and command != "show-task":
            if "task-id" in res.data:
                res = self.__wait_for_task(res.data["task-id"])
            elif "tasks" in res.data:
                res = self.__wait_for_tasks(res.data["tasks"])

        return res