def _handle_get_content(self, param):
        # Implement the handler here
        # use self.save_progress(...) to send progress messages back to the platform
        self.save_progress("In action handler for: {0}".format(
            self.get_action_identifier()))

        # Add an action result object to self (BaseConnector) to represent the action for this param
        action_result = self.add_action_result(ActionResult(dict(param)))

        # Required values can be accessed directly
        s_url = param['url']
        followRefresh = param['followRefresh']

        query = {"url": "{}".format(s_url)}
        if followRefresh:
            query["gotoOptions"] = {"waitUntil": "networkidle2"}
        # make rest call
        ret_val, response = self._make_rest_call('/content',
                                                 action_result,
                                                 data=json.dumps(query))

        if phantom.is_fail(ret_val):
            return action_result.get_status()
        else:
            file_name = s_url + "_contents.txt"
            if hasattr(Vault, 'create_attachment'):
                vault_ret = Vault.create_attachment(response,
                                                    self.get_container_id(),
                                                    file_name=file_name)
            else:
                if hasattr(Vault, 'get_vault_tmp_dir'):
                    temp_dir = Vault.get_vault_tmp_dir()
                else:
                    temp_dir = '/opt/phantom/vault/tmp'
                temp_dir = temp_dir + ('/{}').format(
                    hashlib.md5(file_name).hexdigest())
                os.makedirs(temp_dir)
                file_path = os.path.join(temp_dir, 'tmpfile')
                with open(file_path, 'wb') as (f):
                    f.write(response)
                vault_ret = Vault.add_attachment(file_path,
                                                 self.get_container_id(),
                                                 file_name=file_name)
            if vault_ret.get('succeeded'):
                action_result.set_status(phantom.APP_SUCCESS,
                                         'Downloaded HTML Contents')
                summary = {
                    phantom.APP_JSON_VAULT_ID:
                    vault_ret[phantom.APP_JSON_HASH],
                    phantom.APP_JSON_NAME:
                    file_name,
                    'vault_file_path':
                    Vault.get_file_path(vault_ret[phantom.APP_JSON_HASH]),
                    phantom.APP_JSON_SIZE:
                    vault_ret.get(phantom.APP_JSON_SIZE)
                }
                action_result.update_summary(summary)
            return action_result.get_status()
    def _handle_get_content(self, param):
        self.save_progress("In action handler for: {0}".format(
            self.get_action_identifier()))

        action_result = self.add_action_result(ActionResult(dict(param)))

        s_url = self._handle_py_ver_compat_for_input_str(param['url'])
        followRefresh = param.get('followrefresh', True)
        query = {"url": s_url}
        if followRefresh:
            query["gotoOptions"] = {"waitUntil": "networkidle2"}
        # make rest call
        ret_val, response = self._make_rest_call('/content',
                                                 action_result,
                                                 data=json.dumps(query))

        if phantom.is_fail(ret_val):
            return action_result.get_status()
        try:
            file_name = "{}_contents.txt".format(s_url)
            if hasattr(Vault, 'create_attachment'):
                vault_ret = Vault.create_attachment(response,
                                                    self.get_container_id(),
                                                    file_name=file_name)
            else:
                if hasattr(Vault, 'get_vault_tmp_dir'):
                    temp_dir = Vault.get_vault_tmp_dir()
                else:
                    temp_dir = '/opt/phantom/vault/tmp'
                temp_dir = '{}/{}'.format(temp_dir,
                                          hashlib.md5(file_name).hexdigest())
                os.makedirs(temp_dir)
                file_path = os.path.join(temp_dir, 'tmpfile')
                with open(file_path, 'wb') as f:
                    f.write(response)
                vault_ret = Vault.add_attachment(file_path,
                                                 self.get_container_id(),
                                                 file_name=file_name)
            if vault_ret.get('succeeded'):
                action_result.set_status(phantom.APP_SUCCESS,
                                         'Downloaded HTML Contents')
                summary = {
                    phantom.APP_JSON_VAULT_ID:
                    vault_ret[phantom.APP_JSON_HASH],
                    phantom.APP_JSON_NAME:
                    file_name,
                    'vault_file_path':
                    Vault.get_file_path(vault_ret[phantom.APP_JSON_HASH]),
                    phantom.APP_JSON_SIZE:
                    vault_ret.get(phantom.APP_JSON_SIZE)
                }
                action_result.update_summary(summary)
        except Exception as e:
            err_msg = self._get_error_message_from_exception(e)
            return action_result.set_status(phantom.APP_ERROR, err_msg)
        return action_result.get_status()
Exemplo n.º 3
0
    def _get_vault_payload(self, param, action_result):
        vault_id = param['vault_id']
        try:
            if hasattr(Vault, 'get_file_path'):
                payload = open(Vault.get_file_path(vault_id), 'rb')
            else:
                payload = open(Vault.get_vault_file(vault_id), 'rb')
        except:
            return (action_result.set_status(phantom.APP_ERROR, ('File not found in vault ("{}")').format(vault_id)), None)

        return (phantom.APP_SUCCESS, payload)
Exemplo n.º 4
0
    def _get_vault_file_text(self, action_result, vault_id):
        # type: (ActionResult, str) -> str
        # Get the contents of a file in the vault
        file_path = Vault.get_file_path(vault_id)
        if not file_path:
            return action_result.set_status(phantom.APP_ERROR,
                                            "Cannot retrieve vault file"), None

        try:
            return (phantom.APP_SUCCESS, open(file_path, 'r').read())
        except Exception as e:
            return action_result.set_status(
                phantom.APP_ERROR,
                "Error reading vault file: {}".format(str(e))), None
    def _get_file_dict(self, param, action_result):
        vault_id = param['vault_id']

        try:
            if hasattr(Vault, 'get_file_path'):
                payload = open(Vault.get_file_path(vault_id), 'rb')
            else:
                payload = open(Vault.get_vault_file(vault_id), 'rb')
        except:
            return action_result.set_status(
                phantom.APP_ERROR,
                'File not found in vault ("{}")'.format(vault_id)), None

        files = {'file': (param['file_name'], payload)}

        return phantom.APP_SUCCESS, files
Exemplo n.º 6
0
    def _handle_send_file(self, param):
        action_result = self.add_action_result(ActionResult(dict(param)))
        if not self._init_session(action_result, param):
            return action_result.get_status()

        vault_id = param['vault_id']
        destination = param['destination']

        path = Vault.get_file_path(vault_id)
        if not path:
            return action_result.set_status(phantom.APP_ERROR,
                                            "Could not retrieve vault file")

        try:
            fp = open(path, 'rb')
            encoded_file = base64.b64encode(fp.read())
        except Exception as e:
            return action_result.set_status(phantom.APP_ERROR,
                                            "Unable to base64 encode file", e)

        destination = self._sanitize_string(destination)

        # Windows servers have a limit of 2074 characters per command, so we break it up into chunks
        sent_first = False  # Sent the first chunk
        chunks = textwrap.wrap(encoded_file, 1650)
        num_chunks = len(chunks)
        for i, chunk in enumerate(chunks):
            ps_script = consts.SEND_FILE_START.format(
                b64string_chunk=chunk,
                file_path=destination,
                action=">>" if sent_first else ">")
            # The final chunk
            if i == num_chunks - 1:
                ps_script += consts.SEND_FILE_END

            self.save_progress("Sending chunk {} of {}".format(
                i + 1, num_chunks))
            ret_val = self._run_ps(action_result,
                                   ps_script,
                                   parse_callback=pc.ensure_no_errors)
            if phantom.is_fail(ret_val):
                return action_result.append_to_message("Error sending file")

            sent_first = True

        return action_result.set_status(phantom.APP_SUCCESS,
                                        "Successfully sent file")
Exemplo n.º 7
0
    def _provide_attachment_details(self, attachment_list, action_result):
        """ Helper function that is used to get attachment from the vault, and provide attachment details which can be
        used to add attachment to an incident.

        :param attachment_list: list of vault IDs
        :param action_result: object of ActionResult class
        :return: status (success/failure) and (add_attachment_params_dict dictionary having attachment related
                            information and attachment_data dictionary containing attachment) / None
        """

        file_obj = []
        filename = []
        attachment_data = dict()
        add_attachment_params_dict = dict()

        attachment_list = attachment_list.split(',')

        # At most, three attachments should be provided
        if len(attachment_list) > 3:
            self.debug_print(consts.BMCREMEDY_ATTACHMENT_LIMIT_EXCEED)
            return action_result.set_status(phantom.APP_ERROR, consts.BMCREMEDY_ATTACHMENT_LIMIT_EXCEED), None, None

        # Searching for file with vault id in current container
        files_array = (Vault.get_file_info(container_id=self.get_container_id()))
        for vault_id in attachment_list:
            file_found = False
            vault_id = vault_id.strip()
            for file_data in files_array:
                if file_data[consts.BMCREMEDY_JSON_VAULT_ID] == vault_id:
                    # Getting filename to use
                    filename.append(file_data['name'].encode('utf-8'))
                    # Reading binary data of file
                    file_obj.append(open(Vault.get_file_path(vault_id), 'rb').read())
                    file_found = True
                    break
            if not file_found:
                self.debug_print(consts.BMCREMEDY_UNKNOWN_VAULT_ID)

                return action_result.set_status(phantom.APP_ERROR, consts.BMCREMEDY_UNKNOWN_VAULT_ID), None, None

        for index, value in enumerate(file_obj):
            add_attachment_params_dict['z2AF Work Log0{}'.format(index + 1)] = filename[index]
            attachment_data['attach-z2AF Work Log0{}'.format(index + 1)] = (filename[index], value)

        return phantom.APP_SUCCESS, add_attachment_params_dict, attachment_data
Exemplo n.º 8
0
    def _get_custom_parser_method(self, action_result, vault_id):
        if vault_id is None:
            return phantom.APP_SUCCESS, pc.basic

        file_path = Vault.get_file_path(vault_id)
        if not file_path:
            return action_result.set_status(
                phantom.APP_ERROR, "Could not retrieve vault file"), None

        try:
            custom_parser = imp.load_source('custom_parser', file_path)
        except Exception as e:
            return action_result.set_status(
                phantom.APP_ERROR,
                "Error creating custom parser: {}".format(str(e))), None

        try:
            return phantom.APP_SUCCESS, custom_parser.custom_parser  # noqa
        except Exception as e:
            return action_result.set_status(
                phantom.APP_ERROR,
                "Error saving custom parser: {}".format(str(e))), None
Exemplo n.º 9
0
    def _handle_show_comic(self, param):
        # Implement the handler here
        # use self.save_progress(...) to send progress messages back to the platform
        self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))

        # Add an action result object to self (BaseConnector) to represent the action for this param
        action_result = self.add_action_result(ActionResult(dict(param)))

        # Access action parameters passed in the 'param' dictionary

        # Required values can be accessed directly
        comic_id = param['comic_id']
        endpoint = '/{}/info.0.json'.format(comic_id)
        # Optional values should use the .get() function
        # optional_parameter = param.get('optional_parameter', 'default_value')

        # make rest call
        ret_val, response = self._make_rest_call(
            endpoint, action_result, params=None, headers=None
        )

        if phantom.is_fail(ret_val):
            # the call to the 3rd party device or service failed, action result should contain all the error details
            # for now the return is commented out, but after implementation, return from here
            return action_result.get_status()
            pass

        # Now post process the data,  uncomment code as you deem fit

        # Add the response into the data section
        action_result.add_data(response)

        # Add a dictionary that is made up of the most important values from data into the summary
        # summary = action_result.update_summary({})
        # summary['num_data'] = len(action_result['data'])
        # Retrieve Image
        try:
            img_url = response['img']
            # 'https://imgs.xkcd.com/comics/laser_scope.jpg'
            r_img = requests.get(img_url, stream=True)
            if r_img.status_code != 200:
                self.save_progress("[-] Error while fetching image: {}".format(r_img.status_code))
            r_img.raw.decode_content = True

            file_name = "{}.png".format(comic_id)
            ret_val, vault_ret_dict = self._store_file(action_result, file_name=file_name, file_content=r_img)
        except Exception as e:
            self.save_progress("[-] Exception while fetching image: {}".format(e))
            pass

        summary = action_result.update_summary({})
        summary['vault_info'] = vault_ret_dict

        # Add a dictionary that is made up of the most important values from data into the summary
        summary = action_result.update_summary({})
        summary['name'] = vault_ret_dict.pop('file_name', '')
        summary['vault_id'] = vault_ret_dict['vault_id']
        summary['vault_file_path'] = Vault.get_file_path(vault_ret_dict['vault_id'])
        # Return success, no need to set the message, only the status
        # BaseConnector will create a textual message based off of the summary dictionary
        return action_result.set_status(phantom.APP_SUCCESS)
Exemplo n.º 10
0
    def _handle_post_url(self, param):

        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        params = dict()
        params['url'] = param["url"]
        params['key'] = self._api_key

        # Check if we have a size
        sizes = {
            "tiny": "T",
            "small": "S",
            "normal": "N",
            "medium": "M",
            "large": "L",
            "full page": "F"
        }
        test = param.get("size")
        if not test:
            self.save_progress(
                "Size was blank, using the default \"full page\" size.")
            test = "full page"
        if not sizes.get(test.lower()):
            self.save_progress(
                "Given size not found, using the default \"full page\" size.")
            params['size'] = "F"
        else:
            params['size'] = sizes[test.lower()]

        # Check if we have a Secret Phrase
        if self._api_phrase is None:
            params['hash'] = ""
        else:
            params['hash'] = str(
                hashlib.md5(params['url'] + self._api_phrase).hexdigest())

        params['cacheLimit'] = '0'
        params['format'] = 'JPG'
        params['timeout'] = '200'

        ret_val, image = self._make_rest_call('',
                                              action_result,
                                              params,
                                              method='post',
                                              stream=True)
        if (phantom.is_fail(ret_val)):
            return action_result.get_status()

        permalink = None
        # only create a permalink if the hash is used
        if params['hash']:
            permalink = self._get_sspermalink('', params=params, method='post')

        file_name = param["url"] + "_screenshot.jpg"

        if hasattr(Vault, "create_attachment"):
            vault_ret = Vault.create_attachment(image,
                                                self.get_container_id(),
                                                file_name=file_name)
        else:
            if hasattr(Vault, 'get_vault_tmp_dir'):
                temp_dir = Vault.get_vault_tmp_dir()
            else:
                temp_dir = '/opt/phantom/vault/tmp'
            temp_dir = temp_dir + '/{}'.format(uuid.uuid4())
            os.makedirs(temp_dir)
            file_path = os.path.join(temp_dir, 'tempimage.jpg')

            with open(file_path, 'wb') as f:
                f.write(image)

            vault_ret = Vault.add_attachment(file_path,
                                             self.get_container_id(),
                                             file_name=file_name)

        if vault_ret.get('succeeded'):
            action_result.set_status(phantom.APP_SUCCESS,
                                     "Downloaded screenshot")
            summary = {
                phantom.APP_JSON_VAULT_ID:
                vault_ret[phantom.APP_JSON_HASH],
                phantom.APP_JSON_NAME:
                file_name,
                'vault_file_path':
                Vault.get_file_path(vault_ret[phantom.APP_JSON_HASH]),
                phantom.APP_JSON_SIZE:
                vault_ret.get(phantom.APP_JSON_SIZE)
            }
            if permalink:
                summary['permalink'] = permalink
            action_result.update_summary(summary)

        return action_result.get_status()
Exemplo n.º 11
0
    def _handle_detonate_file(self, param):
        # type: (Dict[Text, Any]) -> bool

        status, api = self._get_api()
        if api is None:
            return status

        vault_id = param["vault_id"]
        file_path = Vault.get_file_path(vault_id)
        file_info = Vault.get_file_info(vault_id=vault_id)

        self.save_progress("Submitting file %s" % vault_id)

        params = {"reanalyze": True}  # type: Dict[Text, Any]
        if param.get("comment", None) is not None:
            params["comment"] = param["comment"]
        if param.get("tags", None) is not None:
            params["tags"] = param["tags"]
        if param.get("type", "") != "":
            params["sample_type"] = param["type"]
        if param.get("config", "") != "":
            params["user_config"] = param["config"]
        if param.get("jobrules", "") != "":
            params["jobrule_entries"] = param["jobrules"]

        if param.get("file_name", "") != "":
            params["sample_filename_b64enc"] = (base64.b64encode(
                param["file_name"]))
        elif (file_info and len(file_info) == 1
              and file_info[0].get("name", "") != ""):
            params["sample_filename_b64enc"] = (base64.b64encode(
                file_info[0]["name"]))

        try:
            res = api.submit_file(file_path, params=params)
        except Exception as exc:
            self.set_status(phantom.APP_ERROR, VMRAY_ERR_SUBMIT_FILE, exc)
            return self.get_status()

        if res["errors"]:
            errors = [
                err.get("error_msg", "NO_ERROR_MSG_GIVEN")
                for err in res["errors"]
            ]
            self.set_status(phantom.APP_ERROR, ";".join(errors))
            return self.get_status()

        submission_id = res["submissions"][0]["submission_id"]
        submission_url = res["submissions"][0]["submission_webif_url"]
        submission_finished = True

        status, report = self._get_report(submission_id, DEFAULT_TIMEOUT)
        if status == phantom.APP_ERROR:
            error_msg, _exc = report
            if error_msg == VMRAY_ERR_SUBMISSION_NOT_FINISHED:
                submission_finished = False
            else:
                self.set_status(phantom.APP_ERROR, error_msg, _exc)
                return self.get_status()
            report = None

        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        if report is not None:
            for analysis in report["analyses"]:
                action_result.add_data({"analysis": analysis})
            if report["reputation_lookup"]:
                action_result.add_data(
                    {"reputation_lookup": report["reputation_lookup"][0]})
            action_result.update_summary({"severity": report["severity"]})

        action_result.update_summary({
            "submission_id": submission_id,
            "url": submission_url,
            "submission_finished": submission_finished
        })
        action_result.set_status(phantom.APP_SUCCESS)
        return action_result.get_status()
    def _handle_get_screenshot(self, param):
        self.save_progress("In action handler for: {0}".format(
            self.get_action_identifier()))

        action_result = self.add_action_result(ActionResult(dict(param)))

        s_url = self._handle_py_ver_compat_for_input_str(param['url'])
        ftype = self._handle_py_ver_compat_for_input_str(param['type'])
        quality = param['quality']
        # Validation of the quality parameter
        ret_val, quality = self._validate_integer(action_result, quality,
                                                  QUALITY_KEY)
        if phantom.is_fail(ret_val):
            return action_result.get_status()

        fullpage = param.get('fullpage', True)
        followRefresh = param.get('followrefresh', True)

        jpeg_query = {
            "url": s_url,
            "options": {
                "type": ftype,
                "quality": "{}".format(quality),
                "fullPage": "{}".format(fullpage)
            }
        }
        png_query = {
            "url": s_url,
            "options": {
                "type": ftype,
                "fullPage": "{}".format(fullpage)
            }
        }

        if ftype == "png":
            query = png_query
        elif ftype == "jpeg":
            query = jpeg_query
        else:
            return action_result.set_status(
                phantom.APP_ERROR,
                "Invalid input. The 'type' parameter value should be either png or jpeg"
            )

        if followRefresh:
            query["gotoOptions"] = {"waitUntil": "networkidle2"}
        # make rest call
        ret_val, response = self._make_rest_call('/screenshot',
                                                 action_result,
                                                 data=json.dumps(query))

        if phantom.is_fail(ret_val):
            return action_result.get_status()
        try:
            file_name = "{}_screenshot.{}".format(s_url, ftype)
            if hasattr(Vault, 'create_attachment'):
                vault_ret = Vault.create_attachment(response,
                                                    self.get_container_id(),
                                                    file_name=file_name)
            else:
                if hasattr(Vault, 'get_vault_tmp_dir'):
                    temp_dir = Vault.get_vault_tmp_dir()
                else:
                    temp_dir = '/opt/phantom/vault/tmp'
                temp_dir = '{}/{}'.format(temp_dir,
                                          hashlib.md5(file_name).hexdigest())
                os.makedirs(temp_dir)
                file_path = os.path.join(temp_dir, 'tmpfile')
                with open(file_path, 'wb') as f:
                    f.write(response)
                vault_ret = Vault.add_attachment(file_path,
                                                 self.get_container_id(),
                                                 file_name=file_name)
            if vault_ret.get('succeeded'):
                action_result.set_status(phantom.APP_SUCCESS,
                                         'Downloaded Screenshot')
                summary = {
                    phantom.APP_JSON_VAULT_ID:
                    vault_ret[phantom.APP_JSON_HASH],
                    phantom.APP_JSON_NAME:
                    file_name,
                    'vault_file_path':
                    Vault.get_file_path(vault_ret[phantom.APP_JSON_HASH]),
                    phantom.APP_JSON_SIZE:
                    vault_ret.get(phantom.APP_JSON_SIZE)
                }
                action_result.update_summary(summary)
        except Exception as e:
            err_msg = self._get_error_message_from_exception(e)
            return action_result.set_status(phantom.APP_ERROR, err_msg)
        return action_result.get_status()