Example #1
0
    def _get_html_text(self, param):
        self.debug_print('_get_html_text() called.')

        # Add an action result to the App Run
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        # Get the data from the params to parse
        data = param[BS4_SOURCE_STRING]

        if not data:
            action_result.set_status(phantom.APP_ERROR, '', e)
            return action_result.get_status()

        try:
            parsed_html = BeautifulSoup(data, 'html.parser')
            plain_text = parsed_html.get_text()
            # .encode('ascii', 'ignore')

            # self.debug_print('soup text - {}'.format(plain_text))
            action_result.add_data(plain_text)
            action_result.set_status(phantom.APP_SUCCESS)
        except Exception as e:
            action_result.set_status(phantom.APP_ERROR, '', e)
            return action_result.get_status()

        return action_result.get_status()
Example #2
0
    def _handle_getIndicators(self, param):

        self.debug_print("param", param)

        # Add an action result to the App Run
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        try:
            # Attempt to log into server
            self.save_progress("Logging in...")
            msg, client = self.login()
            cybereason_data = client.getIndicators()
        except:
            action_result.set_status(phantom.APP_ERROR, "Error")
            return action_result.get_status()
        # The data is returned in a list format, so
        # this extracts the data from the list, and formats it into a
        # dictionary object where it can be added to the "action_result" object
        for i in cybereason_data:
            i = json.dumps(i, default=_json_fallback)
            i = json.loads(i)
            action_result.add_data(i)
        # set_status updates the current status and outputs to "message"
        action_result.set_status(phantom.APP_SUCCESS, "Successfully grabbed data.")
        return action_result.get_status()
Example #3
0
    def _get_html_urls(self, param):
        self.debug_print('_get_urls() called.')

        # Add an action result to the App Run
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        # Get the data from the params to parse
        data = param[BS4_SOURCE_STRING]
        urls = []

        if not data:
            action_result.set_status(phantom.APP_ERROR, '', e)
            return action_result.get_status()

        try:
            parsed_html = BeautifulSoup(data, "html.parser")
            for link in parsed_html.find_all('a'):
                urls.append(link.get('href'))

            action_result.add_data(urls)
            action_result.set_status(phantom.APP_SUCCESS)
        except Exception as e:
            action_result.set_status(phantom.APP_ERROR, '', e)
            return action_result.get_status()

        return action_result.get_status()
Example #4
0
    def _list_policies(self, param):

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

        # gets the full information for the Nessus policies
        ret_val, list_policies = self._make_rest_call('policies/',
                                                      action_result)

        if (phantom.is_fail(ret_val)):
            return action_result.get_status()

        policies = list_policies.get('policies', [])

        if (type(policies) != list):
            policies = [policies]

        policy_counter = 0

        for curr_item in policies:
            action_result.add_data(curr_item)
            if curr_item.get("id"):
                policy_counter = policy_counter + 1

        # creates an empty list to add the summary elements to
        summary = action_result.update_summary({})
        summary['policy_count'] = policy_counter
        action_result.set_status(phantom.APP_SUCCESS)

        return action_result.get_status()
Example #5
0
    def _find_strings(self, param):
        self.debug_print('_find_string() called.')

        # Add an action result to the App Run
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        # Get the data from the params to parse
        data = param[BS4_SOURCE_STRING]
        search_string = param[BS4_SEARCH_STRING]
        strings = []

        if not data:
            action_result.set_status(phantom.APP_ERROR, '', e)
            return action_result.get_status()

        try:
            parsed_html = BeautifulSoup(data, "html.parser")
            for link in parsed_html.find_all():
                self.debug_print('link -- {}'.format(link.find(search_string)))
                if link.find(search_string) != -1:
                    strings.append(link)
            self.debug_print('data raw - {}'.format(
                parsed_html.find_all(search_string)))
            self.debug_print('strings - {}'.format(strings))
            action_result.add_data(strings)
            action_result.set_status(phantom.APP_SUCCESS)
        except Exception as e:
            action_result.set_status(phantom.APP_ERROR, '', e)
            return action_result.get_status()

        return action_result.get_status()
Example #6
0
    def get_intel_incident_ioc_by_id(self, param):
        action_result = ActionResult(dict(param))
        self._connector.add_action_result(action_result)

        param_types = None if 'types' not in param else param.get(
            'types').split(',')

        try:
            intelligence_incident_service = IntelligenceIncidentService(
                self._ds_api_key, self._ds_api_secret_key)
            intelligence_incident_view = IntelligenceIncidentService.intelligence_incident_ioc_view(
                types=param_types)
        except Exception as e:
            error_message = self._handle_exception_object.get_error_message_from_exception(
                e)
            return action_result.set_status(
                phantom.APP_ERROR, "{0} {1}".format(SERVICE_ERR_MSG,
                                                    error_message))
        intel_incident_id = param['intel_incident_id']
        # validate 'intel_incident_id' action parameter
        ret_val, intel_incident_id = self._handle_exception_object.validate_integer(
            action_result, intel_incident_id, INTEL_INCIDENT_ID_KEY)
        if phantom.is_fail(ret_val):
            return action_result.get_status()

        try:
            intelligence_incident_ioc_pages = intelligence_incident_service.find_intel_incident_ioc_by_id(
                intel_incident_id=intel_incident_id,
                view=intelligence_incident_view)
            intelligence_incident_ioc_total = len(
                intelligence_incident_ioc_pages)
            self._connector.save_progress(
                "II IoC Total: {}".format(intelligence_incident_ioc_total))
        except StopIteration:
            error_message = 'No Incident review objects retrieved from the Digital Shadows API'
            return action_result.set_status(
                phantom.APP_ERROR, "Error Details: {0}".format(error_message))
        except Exception as e:
            error_message = self._handle_exception_object.get_error_message_from_exception(
                e)
            return action_result.set_status(
                phantom.APP_ERROR,
                "Error Connecting to server. {}".format(error_message))
        if intelligence_incident_ioc_total > 0:
            summary = {
                'intelligence_incident_ioc_count':
                intelligence_incident_ioc_total,
                'intelligence_incident_ioc_found': True
            }
            action_result.update_summary(summary)

            for intelligence_incident_ioc_page in intelligence_incident_ioc_pages:
                for intelligence_incident_ioc in intelligence_incident_ioc_page:
                    self._connector.save_progress("loop id: {}".format(
                        intelligence_incident_ioc.payload))
                    action_result.add_data(intelligence_incident_ioc.payload)

            action_result.set_status(phantom.APP_SUCCESS,
                                     DS_GET_INTELLIGENCE_INCIDENT_SUCCESS)
        return action_result.get_status()
Example #7
0
    def _find_string(self, param):
        self.debug_print('{}'.format(inspect.stack()[0][3]))
        # Add an action result to the App Run
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        try:
            searchString = param[PYTHONUTILITIES_SEARCH_STRING]
            sourceString = param[PYTHONUTILITIES_SOURCE_STRING]
            start = 0
            end = len(sourceString)
            if PYTHONUTILITIES_SOURCE_STRING_START in param:
                start = int(param[PYTHONUTILITIES_SOURCE_STRING_START])
            if PYTHONUTILITIES_SOURCE_STRING_END in param:
                end = int(param[PYTHONUTILITIES_SOURCE_STRING_END])
            results_dict = {}

            result_index = sourceString.find(searchString, start, end)
            results_dict.update({'search_string_index': result_index})
            action_result.add_data(results_dict)
            action_result.set_status(phantom.APP_SUCCESS)
        except Exception as e:
            action_result.set_status(phantom.APP_ERROR, '', e)
            return action_result.get_status()

        return action_result.get_status()
Example #8
0
    def _get_substring(self, param):
        self.debug_print('{}'.format(inspect.stack()[0][3]))

        # Add an action result to the App Run
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        try:
            # Find a better way to validate the inputs. Especially if they are left blank.
            sourceString = param[PYTHONUTILITIES_SOURCE_STRING]
            start = 0
            end = len(sourceString) - 1
            step = 1
            if PYTHONUTILITIES_SOURCE_STRING_START in param:
                start = int(param[PYTHONUTILITIES_SOURCE_STRING_START])
            if PYTHONUTILITIES_SOURCE_STRING_END in param:
                end = int(param[PYTHONUTILITIES_SOURCE_STRING_END])
            if PYTHONUTILITIES_SOURCE_STRING_STEP in param:
                step = int(param[PYTHONUTILITIES_SOURCE_STRING_STEP])

            self.debug_print('string {}, start {}, end {}'.format(
                sourceString, start, end))
            sub_dict = {'substring': sourceString[start:end:step]}

            self.debug_print('substring {}'.format(sub_dict))
            action_result.add_data(sub_dict)
            action_result.set_status(phantom.APP_SUCCESS)
        except Exception as e:
            action_result.set_status(phantom.APP_ERROR, '', e)
            return action_result.get_status()

        return action_result.get_status()
Example #9
0
    def post_incident_review(self, param):
        action_result = ActionResult(dict(param))
        self._connector.add_action_result(action_result)
        try:
            incident_service = IncidentService(self._ds_api_key,
                                               self._ds_api_secret_key)
        except Exception as e:
            error_message = self._handle_exception_object.get_error_message_from_exception(
                e)
            return action_result.set_status(
                phantom.APP_ERROR, "{0} {1}".format(SERVICE_ERR_MSG,
                                                    error_message))

        incident_id = param.get('incident_id')
        # validate 'incident_id' action parameter
        ret_val, incident_id = self._handle_exception_object.validate_integer(
            action_result, incident_id, INCIDENT_ID_KEY)
        if phantom.is_fail(ret_val):
            return action_result.get_status()
        post_data = {
            'note': param.get('review_note'),
            'status': param.get('review_status')
        }
        self._connector.save_progress("post_data: {}".format(post_data))
        try:
            response = incident_service.post_incident_review(
                post_data, incident_id=incident_id)
        except Exception as e:
            error_message = self._handle_exception_object.get_error_message_from_exception(
                e)
            return action_result.set_status(
                phantom.APP_ERROR,
                "Error Connecting to server. {0}".format(error_message))
        self._connector.save_progress("response: {}".format(response))

        try:
            summary = {
                'incident_reviews_status_code': response['status'],
                'incident_reviews_message': response['message']
            }
            action_result.update_summary(summary)
            action_result.add_data(response['content'][0])
            if response['message'] == "SUCCESS":
                action_result.set_status(
                    phantom.APP_SUCCESS,
                    "Digital Shadows Incident review posted successfully")
            else:
                action_result.set_status(
                    phantom.APP_SUCCESS,
                    "Error in incident review post request")
        except Exception as e:
            error_message = self._handle_exception_object.get_error_message_from_exception(
                e)
            return action_result.set_status(
                phantom.APP_ERROR,
                "Error occurred while fetching data from response. {}".format(
                    error_message))

        return action_result.get_status()
 def get_data_breach_record_by_id(self, param):
     action_result = ActionResult(dict(param))
     self._connector.add_action_result(action_result)
     try:
         breach_record_service = DataBreachRecordService(
             self._ds_api_key, self._ds_api_secret_key)
     except Exception as e:
         error_message = self._handle_exception_object.get_error_message_from_exception(
             e)
         return action_result.set_status(
             phantom.APP_ERROR, "{0} {1}".format(SERVICE_ERR_MSG,
                                                 error_message))
     breach_id = param['breach_id']
     # validate 'breach_id' action parameter
     ret_val, breach_id = self._handle_exception_object.validate_integer(
         action_result, breach_id, BREACH_ID_KEY)
     if phantom.is_fail(ret_val):
         return action_result.get_status()
     try:
         breach_record_pages = breach_record_service.find_all_pages(
             breach_id)
         breach_record_total = len(breach_record_pages)
     except StopIteration:
         error_message = 'No data breach record retrieved from the Digital Shadows API in page groups'
         return action_result.set_status(
             phantom.APP_ERROR, "Error Details: {0}".format(error_message))
     except Exception as e:
         error_message = self._handle_exception_object.get_error_message_from_exception(
             e)
         return action_result.set_status(
             phantom.APP_ERROR,
             "Error Connecting to server. {}".format(error_message))
     if breach_record_total > 0:
         summary = {
             'data_breach_record_count': breach_record_total,
             'data_breach_record_found': True
         }
         action_result.update_summary(summary)
         for breach_record_page in breach_record_pages:
             for breach_record in breach_record_page:
                 action_result.add_data(breach_record.payload)
         action_result.set_status(
             phantom.APP_SUCCESS,
             "Digital Shadows data breach records fetched")
     else:
         summary = {
             'data_breach_record_count': 0,
             'data_breach_record_found': False
         }
         action_result.update_summary(summary)
         action_result.set_status(
             phantom.APP_SUCCESS,
             "Data breach record not found in Digital Shadows")
     return action_result.get_status()
Example #11
0
    def _split_string(self, param):
        self.debug_print('{}'.format(inspect.stack()[0][3]))
        # Add an action result to the App Run
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        try:
            source_string = param[PYTHONUTILITIES_SOURCE_STRING]
            result = source_string.split(PYTHONUTILITIES_SPLIT_VALUE)
            action_result.add_data({'list': result})
            action_result.set_status(phantom.APP_SUCCESS)
        except Exception as e:
            action_result.set_status(phantom.APP_ERROR, '', e)
            return action_result.get_status()

        return action_result.get_status()
Example #12
0
    def _dictionary_to_list(self, param):
        self.debug_print('{}'.format(inspect.stack()[0][3]))
        # Add an action result to the App Run
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        try:
            dictionary = param[PYTHONUTILITIES_ITEM]
            result = dictionary.items()
            action_result.add_data({'result': result})
            action_result.set_status(phantom.APP_SUCCESS)
        except Exception as e:
            action_result.set_status(phantom.APP_ERROR, '', e)
            return action_result.get_status()

        return action_result.get_status()
Example #13
0
    def _item_length(self, param):
        self.debug_print('{}'.format(inspect.stack()[0][3]))
        # Add an action result to the App Run
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        try:
            user_item = param[PYTHONUTILITIES_ITEM]
            result = len(user_item)
            action_result.add_data({'length': result})
            action_result.set_status(phantom.APP_SUCCESS)
        except Exception as e:
            action_result.set_status(phantom.APP_ERROR, '', e)
            return action_result.get_status()

        return action_result.get_status()
    def get_data_breach(self, param):
        action_result = ActionResult(dict(param))
        self._connector.add_action_result(action_result)

        date_range = param['date_range']
        param_reposted_credentials = None if 'reposted_credentials' not in param else param[
            'reposted_credentials'].split(',')
        param_severities = None if 'severities' not in param else param.get(
            'severities').split(',')
        param_statuses = None if 'statuses' not in param else param.get(
            'statuses').split(',')
        param_user_name = None if 'user_name' not in param else param.get(
            'user_name').split(',')

        try:
            breach_service = DataBreachService(self._ds_api_key,
                                               self._ds_api_secret_key)
            breach_view = DataBreachService.data_breach_view(
                published=date_range,
                reposted_credentials=param_reposted_credentials,
                severities=param_severities,
                statuses=param_statuses,
                username=param_user_name)
        except Exception as e:
            error_message = self._handle_exception_object.get_error_message_from_exception(
                e)
            return action_result.set_status(
                phantom.APP_ERROR, "{0} {1}".format(SERVICE_ERR_MSG,
                                                    error_message))
        try:
            breach_pages = breach_service.find_all_pages(view=breach_view)
            breach_total = len(breach_pages)
        except StopIteration:
            error_message = 'No DataBreach objects retrieved from the Digital Shadows API in page groups'
            return action_result.set_status(
                phantom.APP_ERROR, "Error Details: {0}".format(error_message))
        except Exception as e:
            error_message = self._handle_exception_object.get_error_message_from_exception(
                e)
            return action_result.set_status(
                phantom.APP_ERROR,
                "Error Connecting to server. {}".format(error_message))
        if breach_total > 0:
            summary = {
                'data_breach_count': breach_total,
                'data_breach_found': True
            }
            action_result.update_summary(summary)

            for breach_page in breach_pages:
                for breach in breach_page:
                    action_result.add_data(breach.payload)
            action_result.set_status(phantom.APP_SUCCESS,
                                     DS_GET_BREACH_SUCCESS)
        else:
            summary = {'data_breach_count': 0, 'data_breach_found': False}
            action_result.update_summary(summary)
            action_result.set_status(phantom.APP_SUCCESS,
                                     DS_GET_BREACH_NOT_FOUND)
        return action_result.get_status()
    def lookup_username(self, param):
        action_result = ActionResult(dict(param))
        self._connector.add_action_result(action_result)

        username_to_lookup = param.get('username')

        username_service = DataBreachUsernameService(self._ds_api_key,
                                                     self._ds_api_secret_key)
        view = username_service.data_breach_username_view(
            username=username_to_lookup)

        found_username = next(
            (data_breach_username
             for data_breach_username in username_service.find_all(view=view)
             if data_breach_username.username == username_to_lookup), None)

        if found_username is not None:
            summary, data = self._lookup_success(username_to_lookup,
                                                 found_username)
            action_result.update_summary(summary)
            action_result.add_data(data)
            action_result.set_status(phantom.APP_SUCCESS,
                                     DS_LOOKUP_USERNAME_SUCCESS)
        else:
            summary, data = self._lookup_failure(username_to_lookup)
            action_result.update_summary(summary)
            action_result.add_data(data)
            action_result.set_status(phantom.APP_SUCCESS,
                                     DS_LOOKUP_USERNAME_NOT_FOUND)

        return action_result.get_status()
    def _test_connectivity(self, param):

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

        params = dict()
        params['url'] = "https://www.screenshotmachine.com"
        self.save_progress("Checking to see if Screenshotmachine.com is online...")

        params['key'] = self._api_key

        # 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).encode('utf-8')).hexdigest())

        params['cacheLimit'] = '0'
        ret_val, resp_data = self._make_rest_call('', action_result, params, method='post', stream=True)

        if phantom.is_fail(ret_val):
            action_result.append_to_message('Test connectivity failed')
            return action_result.get_status()

        self.save_progress("Test Connectivity Passed")
        return action_result.set_status(ret_val, "Test Connectivity Passed")
Example #17
0
    def _test_asset_connectivity(self, param):

        action_result = ActionResult()
        self.save_progress(PHISHME_CONNECTION_TEST_MSG)

        params = {'threatType': 'malware'}

        return_value, json_resp = self._make_rest_call(PHISHME_ENDPOINT, action_result, params=params)

        if phantom.is_fail(return_value):
            self.save_progress(action_result.get_message())
            self.set_status(phantom.APP_ERROR, PHISHME_CONNECTION_TEST_ERR_MSG)
            return action_result.get_status()

        self.set_status_save_progress(phantom.APP_SUCCESS, PHISHME_CONNECTION_TEST_SUCC_MSG)
        return action_result.get_status()
    def _test_connectivity(self, param):

        action_result = ActionResult()
        self.save_progress(DEEPSIGHT_TEST_ENDPOINT)

        return_val, json_resp = self._make_rest_call(
            DEEPSIGHT_ENDPOINT_USAGE_LIMIT, action_result)

        if (phantom.is_fail(return_val)):
            self.save_progress(action_result.get_message())
            self.set_status(phantom.APP_ERROR,
                            DEEPSIGHT_TEST_CONNECTIVITY_FAIL)
            return action_result.get_status()

        self.set_status_save_progress(phantom.APP_SUCCESS,
                                      DEEPSIGHT_TEST_CONNECTIVITY_PASS)

        return action_result.get_status()
Example #19
0
    def _handle_lookup_url(self, param):
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        # check for required input param
        url = param["url"]

        # build full REST endpoint with Auth signature
        # make GET request to CTIX OpenAPI
        try:
            endpoint = "/search/?Expires={}&AccessID={}&Signature={}&url={}".format(
                self._expires, self._access_id,
                self._generate_signature(self._access_id, self._secret_key,
                                         self._expires), url)
            status_code, response = self._make_request(
                "GET", "{}{}".format(self._baseurl, endpoint), self._verify,
                action_result)
        except Exception as e:
            err_msg = self._get_error_message_from_exception(e)
            self.save_progress(CYWARE_GET_REQ_FAILED.format(err_msg))
            return action_result.set_status(
                phantom.APP_ERROR, "URL Lookup failed. {}".format(err_msg))

        if phantom.is_fail(status_code):
            return action_result.get_status()

        # check response status_code
        if status_code == 200:
            try:
                if isinstance(response, list):
                    response = response[0]
                if not isinstance(response, dict):
                    return action_result.set_status(
                        phantom.APP_ERROR, CYWARE_RESP_FROM_SERVER_NOT_JSON)
                # commit action_result
                action_result.set_summary({"message": response['message']})
                action_result.add_data(response)
                self.save_progress(phantom.APP_SUCCESS,
                                   "URL Lookup Successful")
                return action_result.set_status(phantom.APP_SUCCESS,
                                                "URL Lookup Successful")
            except Exception as e:
                err_msg = self._get_error_message_from_exception(e)
                self.save_progress(
                    CYWARE_ADDING_RESP_DATA_TO_ACTION_RESULT_FAILED.format(
                        err_msg))
                return action_result.set_status(
                    phantom.APP_ERROR,
                    CYWARE_ADDING_RESP_DATA_TO_ACTION_RESULT_FAILED.format(
                        err_msg))
        else:
            self.save_progress(
                CYWARE_GET_REQ_FAILED_WITH_NON_200_STATUS.format(status_code))
            return action_result.set_status(
                phantom.APP_ERROR,
                CYWARE_GET_REQ_FAILED_WITH_NON_200_STATUS.format(status_code))
Example #20
0
    def _test_connectivity(self, param):

        action_result = ActionResult()
        self.save_progress(DNSDB_TEST_CONNECTIVITY_MSG)

        ret_val, json_resp = self._make_rest_call(
            (DNSDB_ENDPOINT_DOMAIN).format(domain=DNSDB_TEST_CONN_DOMAIN),
            action_result)

        # Forcefully set the status of the BaseConnector to failure, since
        # action_result is not added to the BaseConnector.
        if (phantom.is_fail(ret_val)):
            self.save_progress(action_result.get_message())
            self.set_status(phantom.APP_ERROR, DNSDB_TEST_CONN_FAIL)
            return action_result.get_status()

        self.set_status_save_progress(phantom.APP_SUCCESS,
                                      DNSDB_TEST_CONN_SUCC)
        return action_result.get_status()
Example #21
0
    def _handle_updateIndicators(self, param, choice):
        key = str(param['key'])
        reputation = str(param['reputation'])
        prevention = str(param['prevention'])
        comment = "null"

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

        try:
            # Attempt to log into server
            msg, client = self.login()
        except:
            action_result.set_status(phantom.APP_ERROR, "Unable to login.")

        # Formatting the data
        if choice:
            # REMOVING
            remove = 'true'
        else:
            # ADDING
            remove = 'false'
        prevention = prevention.lower()
        remove = remove.lower()

        # Setting up to add the the table widget, must in a list, and must contain dictionary
        tempObj = [{'key': key, 'reputation': reputation, 'prevention': prevention, 'comment': comment}]

        # Adding to object to action result so it can be read into the table
        for i in tempObj:
            i = json.dumps(i, default=_json_fallback)
            i = json.loads(i)
            action_result.add_data(i)
            
        try:
            # Updating the cybereason client
            client.updateIndicators(key, reputation, prevention, remove)
            action_result.set_status(phantom.APP_SUCCESS, "Successful")
        except:
            action_result.set_status(phantom.APP_ERROR, "Error with updateIndicator function")
            return action_result.get_status()
        return action_result.get_status()
Example #22
0
    def get_incident_review_by_id(self, param):
        action_result = ActionResult(dict(param))
        self._connector.add_action_result(action_result)

        incident_id = param['incident_id']
        # validate 'incident_id' action parameter
        ret_val, incident_id = self._handle_exception_object.validate_integer(
            action_result, incident_id, INCIDENT_ID_KEY)
        if phantom.is_fail(ret_val):
            return action_result.get_status()

        try:
            incident_service = IncidentService(self._ds_api_key,
                                               self._ds_api_secret_key)
        except Exception as e:
            error_message = self._handle_exception_object.get_error_message_from_exception(
                e)
            return action_result.set_status(
                phantom.APP_ERROR, "{0} {1}".format(SERVICE_ERR_MSG,
                                                    error_message))
        try:
            incident_reviews = incident_service.find_all_reviews(incident_id)
            incident_reviews_total = len(incident_reviews)
        except Exception as e:
            error_message = self._handle_exception_object.get_error_message_from_exception(
                e)
            return action_result.set_status(
                phantom.APP_ERROR,
                "Error Connecting to server. {0}".format(error_message))
        if incident_reviews_total > 0:
            summary = {
                'incident_reviews_count': incident_reviews_total,
                'incident_reviews_found': True
            }
            action_result.update_summary(summary)
            for incident_review in incident_reviews:
                action_result.add_data(incident_review)
            action_result.set_status(
                phantom.APP_SUCCESS,
                "Digital Shadows incident reviews fetched for the Incident ID: {}"
                .format(incident_id))
        return action_result.get_status()
 def get_data_breach_record_reviews(self, param):
     action_result = ActionResult(dict(param))
     self._connector.add_action_result(action_result)
     try:
         breach_record_service = DataBreachRecordService(
             self._ds_api_key, self._ds_api_secret_key)
     except Exception as e:
         error_message = self._handle_exception_object.get_error_message_from_exception(
             e)
         return action_result.set_status(
             phantom.APP_ERROR, "{0} {1}".format(SERVICE_ERR_MSG,
                                                 error_message))
     breach_record_id = param['breach_record_id']
     # validate 'breach_record_id' action parameter
     ret_val, breach_record_id = self._handle_exception_object.validate_integer(
         action_result, breach_record_id, BREACH_RECORD_ID_KEY)
     if phantom.is_fail(ret_val):
         return action_result.get_status()
     try:
         breach_record_reviews = breach_record_service.find_data_breach_record_reviews(
             breach_record_id)
         breach_record_reviews_total = len(breach_record_reviews)
     except Exception as e:
         error_message = self._handle_exception_object.get_error_message_from_exception(
             e)
         return action_result.set_status(
             phantom.APP_ERROR,
             "Error Connecting to server. {0}".format(error_message))
     if breach_record_reviews_total > 0:
         summary = {
             'breach_record_reviews_count': breach_record_reviews_total,
             'breach_record_reviews_found': True
         }
         action_result.update_summary(summary)
         for breach_record_review in breach_record_reviews:
             action_result.add_data(breach_record_review)
         action_result.set_status(
             phantom.APP_SUCCESS,
             "Digital Shadows breach record reviews fetched for the Breach Record ID: {}"
             .format(breach_record_id))
     return action_result.get_status()
Example #24
0
    def _test_asset_connectivity(self, param):
        """ This function tests the connectivity of an asset with given credentials.

        :param param: dictionary of input parameters
        :return: status phantom.APP_SUCCESS/phantom.APP_ERROR (along with appropriate message)
        """

        action_result = ActionResult()
        self.save_progress(consts.BMCREMEDY_TEST_CONNECTIVITY_MSG)
        self.save_progress("Configured URL: {}".format(self._base_url))

        response_status = self._generate_api_token(action_result)

        if phantom.is_fail(response_status):
            self.save_progress(action_result.get_message())
            self.set_status(phantom.APP_ERROR, consts.BMCREMEDY_TEST_CONNECTIVITY_FAIL)
            return action_result.get_status()

        self.set_status_save_progress(phantom.APP_SUCCESS, consts.BMCREMEDY_TEST_CONNECTIVITY_PASS)

        return action_result.get_status()
    def _handle_unblock_ip(self, param):

        config = self.get_config()
        self.debug_print("param", param)

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

        url = config[PFSENSE_URL]
        ip = param[PFSENSE_INCIDENT_IP]

        try:
            self.save_progress("Unblock IP {} on pfSense asset at {}".format(
                ip, url))
            self.pf.unblock_ip(ip)
        except Exception as e:
            action_result.set_status(phantom.APP_ERROR, PFSENSE_ERR_UNBLOCK, e)
            return action_result.get_status()

        action_result.set_status(phantom.APP_SUCCESS, PFSENSE_SUCC_UNBLOCK)
        return action_result.get_status()
    def _test_connectivity(self, param):

        action_result = ActionResult()

        self.save_progress(SYMANTEC_CONNECTION_TEST_MSG)

        response_status = self._generate_api_token(action_result)

        if phantom.is_fail(response_status):
            self.save_progress(
                SYMANTEC_CONNECTION_TEST_INVALID_URL_MSG.format(
                    url=self._base_url))
            self.save_progress(action_result.get_message())
            self.set_status(phantom.APP_ERROR,
                            SYMANTEC_CONNECTION_TEST_ERR_MSG)
            return action_result.get_status()

        self.set_status_save_progress(phantom.APP_SUCCESS,
                                      SYMANTEC_CONNECTION_TEST_SUCC_MSG)

        return action_result.get_status()
Example #27
0
    def _get_date(self, param):
        self.debug_print('{}'.format(inspect.stack()[0][3]))

        # Add an action result to the App Run
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        format_string = param.get('format_string', "%A, %d %B %Y %I:%M%p")

        # List of local time items
        local_dt = datetime.now()
        local_iso = local_dt.isocalendar()
        local_tt = local_dt.timetuple()
        local_time = {
            "local_year": local_tt[0],
            "local_month": local_tt[1],
            "local_day": local_tt[2],
            "local_hour": local_tt[3],
            "local_minute": local_tt[4],
            "local_second": local_tt[5],
            "local_weekday": local_tt[6],
            "local_day_number": local_tt[7],
            "local_tz": local_tt[8],
            "local_iso_week": local_iso[1],
            "local_iso_weekday": local_iso[2],
            "local_custom": local_dt.strftime(format_string)
        }

        # List of UTC time items
        utc_dt = datetime.utcnow()
        utc_iso = utc_dt.isocalendar()
        utc_tt = utc_dt.timetuple()
        utc_time = {
            "utc_year": utc_tt[0],
            "utc_month": utc_tt[1],
            "utc_day": utc_tt[2],
            "utc_hour": utc_tt[3],
            "utc_minute": utc_tt[4],
            "utc_second": utc_tt[5],
            "utc_weekday": utc_tt[6],
            "utc_day_number": utc_tt[7],
            "utc_tz": utc_tt[8],
            "utc_iso_week": utc_iso[1],
            "utc_iso_weekday": utc_iso[2],
            "utc_custom": utc_dt.strftime(format_string)
        }

        # Add time values to results
        action_result.add_data(local_time)
        action_result.add_data(utc_time)
        action_result.set_status(phantom.APP_SUCCESS)

        return action_result.get_status()
    def get_data_breach_by_id(self, param):
        action_result = ActionResult(dict(param))
        self._connector.add_action_result(action_result)
        try:
            breach_service = DataBreachService(self._ds_api_key,
                                               self._ds_api_secret_key)
        except Exception as e:
            error_message = self._handle_exception_object.get_error_message_from_exception(
                e)
            return action_result.set_status(
                phantom.APP_ERROR, "{0} {1}".format(SERVICE_ERR_MSG,
                                                    error_message))

        breach_id = param['breach_id']
        # validate 'breach_id' action parameter
        ret_val, breach_id = self._handle_exception_object.validate_integer(
            action_result, breach_id, BREACH_ID_KEY)
        if phantom.is_fail(ret_val):
            return action_result.get_status()
        try:
            breach = breach_service.find_data_breach_by_id(breach_id)
        except Exception as e:
            error_message = self._handle_exception_object.get_error_message_from_exception(
                e)
            return action_result.set_status(
                phantom.APP_ERROR,
                "Error Connecting to server. {0}".format(error_message))

        if 'id' in breach:
            summary = {'data_breach_count': 1, 'data_breach_found': True}
            action_result.update_summary(summary)
            action_result.add_data(breach)
            action_result.set_status(phantom.APP_SUCCESS,
                                     DS_GET_BREACH_SUCCESS)
        else:
            summary = {'data_breach_count': 0, 'data_breach_found': False}
            action_result.update_summary(summary)
            action_result.set_status(phantom.APP_SUCCESS,
                                     DS_GET_BREACH_NOT_FOUND)
        return action_result.get_status()
Example #29
0
    def _test_connectivity(self, param):
        """
        Called when the user depresses the test connectivity button on the Phantom UI.
        Use a basic query to determine if the device IP/hostname, username and password is correct
        """

        action_result = ActionResult()
        self.save_progress(FORTIGATE_TEST_CONNECTIVITY_MSG)
        self.save_progress("Configured URL: {}".format(self._device))

        ret_val = self._login(action_result)

        if phantom.is_fail(ret_val):
            # self.save_progress("Test Connectivity Failed")
            self.save_progress(action_result.get_message())
            # return action_result.get_status()

            # If SSL is enabled and URL configuration has IP address
            if self._verify_server_cert and (phantom.is_ip(self._device)
                                             or self._is_ipv6(self._device)):
                # The failure could be due to IP provided in URL instead of hostname
                self.save_progress(FORTIGATE_TEST_WARN_MSG)

            self.set_status(phantom.APP_ERROR, FORTIGATE_TEST_CONN_FAIL)
            return action_result.get_status()

        self.save_progress(FORTIGATE_TEST_ENDPOINT_MSG)

        # Querying endpoint to check connection to device
        status, _ = self._make_rest_call(FORTIGATE_BLOCKED_IPS, action_result)

        if phantom.is_fail(status):
            self.save_progress(action_result.get_message())
            self.set_status(phantom.APP_ERROR, FORTIGATE_TEST_CONN_FAIL)
            return action_result.get_status()

        self.set_status_save_progress(phantom.APP_SUCCESS,
                                      FORTIGATE_TEST_CONN_SUCC)
        return action_result.get_status()
Example #30
0
    def locate_device(self, param):
        """
        Locating client devices means walking a tree based on the API Key. The key is associated with one or more organizations,
        an organization can have one or more networks, each network can have multiple devices, and each device can have one or
        more client machines. Depending on the timespan specified, you may see differing results. Larger timespans may show the same
        client connected to multiple devices. Small timespans, may not return any results.
        """
        self.debug_print("%s LOCATE_DEVICE parameters:\n%s" %
                         (Meraki_Connector.BANNER, param))

        action_result = ActionResult(
            dict(param))  # Add an action result to the App Run
        self.add_action_result(action_result)

        try:
            param["search_string"]  # User left search_string empty
        except KeyError:
            param["search_string"] = "*"

        org_id_list = self.get_org_ids()
        for organization in org_id_list:
            networks_list = self.get_networks(organization["id"])
            for network in networks_list:
                device_list = self.get_devices(network["id"])
                for device in device_list:
                    client_list = self.get_clients(device["serial"],
                                                   param["timespan"])
                    for client in client_list:
                        response = self.build_output_record(
                            param["search_string"], organization, network,
                            device, client)
                        if response:
                            action_result.add_data(response)

        if action_result.get_data_size() > 0:
            action_result.set_status(phantom.APP_SUCCESS)
            self.set_status_save_progress(
                phantom.APP_SUCCESS,
                "Returned: %s clients" % action_result.get_data_size())
        else:
            action_result.set_status(phantom.APP_ERROR)
            self.set_status_save_progress(
                phantom.APP_ERROR,
                "Returned: %s clients" % action_result.get_data_size())

        self.debug_print(
            "%s Data size: %s" %
            (Meraki_Connector.BANNER, action_result.get_data_size()))
        return action_result.get_status()
    def locate_device(self, param):
        """
        Locating client devices means walking a tree based on the API Key. The key is associated with one or more organizations,
        an organization can have one or more networks, each network can have multiple devices, and each device can have one or
        more client machines. Depending on the timespan specified, you may see differing results. Larger timespans may show the same
        client connected to multiple devices. Small timespans, may not return any results.
        """
        self.debug_print("%s LOCATE_DEVICE parameters:\n%s" % (Meraki_Connector.BANNER, param))

        action_result = ActionResult(dict(param))          # Add an action result to the App Run
        self.add_action_result(action_result)

        try:
            param["search_string"]                         # User left search_string empty
        except KeyError:
            param["search_string"] = "*"

        org_id_list = self.get_org_ids()
        for organization in org_id_list:
            networks_list = self.get_networks(organization["id"])
            for network in networks_list:
                device_list = self.get_devices(network["id"])
                for device in device_list:
                    client_list = self.get_clients(device["serial"], param["timespan"])
                    for client in client_list:
                        response = self.build_output_record(param["search_string"], organization, network, device, client)
                        if response:
                            action_result.add_data(response)

        if action_result.get_data_size() > 0:
            action_result.set_status(phantom.APP_SUCCESS)
            self.set_status_save_progress(phantom.APP_SUCCESS, "Returned: %s clients" % action_result.get_data_size())
        else:
            action_result.set_status(phantom.APP_ERROR)
            self.set_status_save_progress(phantom.APP_ERROR, "Returned: %s clients" % action_result.get_data_size())

        self.debug_print("%s Data size: %s" % (Meraki_Connector.BANNER, action_result.get_data_size()))
        return action_result.get_status()