Ejemplo n.º 1
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()
Ejemplo n.º 2
0
    def unblock_ip(self, param):
        """
        Allow the IP address by deleting the rule which originally blocked the source IP address.

        URL https://10.255.111.100/mgmt/tm/security/firewall/policy/~Common~Phantom_Inbound/rules/sourceIP_8.8.8.8
        """

        config = self.get_config()
        self.debug_print("%s UNBLOCK_IP parameters:\n%s \nconfig:%s" % (F5_Connector.BANNER, param, config))

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

        URL = "/mgmt/tm/security/firewall/policy/~%s~%s/rules/%s" % (param["partition"], param["policy"], param["rule name"])
        self.debug_print("%s UNBLOCK_IP URL: %s" % (F5_Connector.BANNER, URL))

        F5 = iControl.BIG_IP(host=config.get("device"),
                             username=config.get("username"),
                             password=config.get("password"),
                             uri=URL,
                             method="DELETE")

        if F5.genericDELETE():
            action_result.set_status(phantom.APP_SUCCESS)
        else:
            action_result.set_status(phantom.APP_ERROR)

        action_result.add_data(F5.response)
        self.debug_print("%s UNBLOCK_IP code: %s \nresponse: %s" % (F5_Connector.BANNER, F5.status_code, F5.response))
        return
Ejemplo n.º 3
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()
    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()
Ejemplo n.º 5
0
    def unblock_ip(self, param):
        """
        Allow the IP address by deleting the rule which originally blocked the source IP address.

        URL https://10.255.111.100/mgmt/tm/security/firewall/policy/~Common~Phantom_Inbound/rules/sourceIP_8.8.8.8
        """

        config = self.get_config()
        self.debug_print("%s UNBLOCK_IP parameters:\n%s \nconfig:%s" %
                         (F5_Connector.BANNER, param, config))

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

        URL = "/mgmt/tm/security/firewall/policy/~%s~%s/rules/%s" % (
            param["partition"], param["policy"], param["rule name"])
        self.debug_print("%s UNBLOCK_IP URL: %s" % (F5_Connector.BANNER, URL))

        F5 = iControl.BIG_IP(host=config.get("device"),
                             username=config.get("username"),
                             password=config.get("password"),
                             uri=URL,
                             method="DELETE")

        if F5.genericDELETE():
            action_result.set_status(phantom.APP_SUCCESS)
        else:
            action_result.set_status(phantom.APP_ERROR)

        action_result.add_data(F5.response)
        self.debug_print("%s UNBLOCK_IP code: %s \nresponse: %s" %
                         (F5_Connector.BANNER, F5.status_code, F5.response))
        return
Ejemplo n.º 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()
Ejemplo n.º 7
0
    def _list_switches(self, url, param):
        action_result = ActionResult(param)
        self.add_action_result(action_result)

        try:
            self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, url)
            # switch_list = floodlight_rest.FloodlightRest(url=url).get('switches')
            self.save_progress("done.")
            if switch_list is None:
                return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_NO_DATA)
        except Exception as e:
            return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_SERVER_CONNECTION, e)

        # Rearrange into a table-friendly format here.
        # This should definitely change if we ever get a "tree" render type
        result = {"switches": [], "success": True}
        for switch in switch_list:
            addrmatch = re.match("/([^:]+):([0-9]+)", switch["inetAddress"])
            if not addrmatch:
                return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_PARSE, switch["inetAddress"])

            result["switches"].append(
                                {
                                 "ip": addrmatch.group(1),
                                 "port": addrmatch.group(2),
                                 "connectedSince": datetime.fromtimestamp(int(switch["connectedSince"]) / 1000).strftime('%Y-%m-%d %H:%M:%S'),
                                 "switchDPID": "dpid:{}".format(switch["switchDPID"])
                                })

        action_result.add_data(result)

        return action_result.set_status(phantom.APP_SUCCESS, OC2SDN_SUCC)
Ejemplo n.º 8
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()
Ejemplo n.º 9
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()
Ejemplo n.º 10
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()
Ejemplo n.º 11
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()
    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()
Ejemplo n.º 13
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()
Ejemplo n.º 14
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()
Ejemplo n.º 15
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))
 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()
Ejemplo n.º 17
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()
Ejemplo n.º 18
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()
Ejemplo n.º 19
0
    def modify_smartflow_policy(self, param, LADS, CRUD):
        " Modify the Smartflow Policy "

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

        source_ip = self.normalize_ip(
            param["source"])  # 8.8.8.8/32 or 192.0.2.0/24 or 4.4.4.4
        app_name = param["application"]  # WWT-API
        host_name = param["host"]  # default-host
        service_name = param["service"]  # default-service
        smartflow_name = param["smartflow"]  # default-smartflow
        try:
            rule_action = param[
                "action"]  # 'deny' or 'allow', not specified for unblock
        except KeyError:
            rule_action = None

        uri = "/api/v2/applications/%s/hosts/%s/services/%s/smartflows/%s/policies" % (
            app_name, host_name, service_name, smartflow_name)

        if LADS.genericGET(
                uri=uri):  # Successfully retrieved the Smartflow policy
            LADS.separate_access_policy(LADS.response)
            if LADS.modify_access_policy(CRUD, rule_action, source_ip):
                LADS.include_access_policy()
                uri += "/_import"
                if LADS.genericPOST(uri=uri,
                                    body=json.dumps(LADS.smartflow_policies)):
                    action_result.set_status(phantom.APP_SUCCESS)
                    LADS.separate_access_policy(
                        LADS.response)  # Isolate the access policy
                else:
                    action_result.set_status(phantom.APP_ERROR)
            else:
                action_result.set_status(
                    phantom.APP_ERROR)  # Failure in modifying access policy
        else:
            action_result.set_status(
                phantom.APP_ERROR)  # Failed to retrieve Smartflow policy

        action_result.add_data(
            LADS.access_policy
        )  # Put the current access policy in the result data
        self.debug_print(
            "%s modify_smartflow_policy code: %s \nresponse: %s" %
            (A10_LADS_Connector.BANNER, LADS.status_code, LADS.response))
        return
Ejemplo n.º 20
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()
Ejemplo n.º 21
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()
Ejemplo n.º 22
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()
Ejemplo n.º 23
0
    def _call_function_as_action(self, url, funct, param={}):
        action_result = ActionResult(param)
        self.add_action_result(action_result)

        try:
            self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, url)
            result = funct()
            self.save_progress("done.")
            if result is None:
                return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_NO_DATA)

            action_result.add_data(result)
            return action_result.set_status(phantom.APP_SUCCESS, OC2SDN_SUCC)

        except Exception as e:
            return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_SERVER_CONNECTION, e)
Ejemplo n.º 24
0
    def get_infrastructure_ip_ports(self, param):
        action_result = ActionResult(dict(param))
        self._connector.add_action_result(action_result)

        infrastructure_service = InfrastructureService(self._ds_api_key,
                                                       self._ds_api_secret_key)
        infrastructure_view = InfrastructureService.infrastructure_view()
        infrastructure_pages = infrastructure_service.find_all_pages(
            view=infrastructure_view)

        infrastructure_total = len(infrastructure_pages)
        if infrastructure_total > 0:
            summary = {
                'infrastructure_count': infrastructure_total,
                'infrastructure_found': True
            }
            action_result.update_summary(summary)

            for infrastructure_page in infrastructure_pages:
                for infrastructure in infrastructure_page:
                    data = {
                        'id': infrastructure.id,
                        'ipAddress': infrastructure.ip_address,
                        'portNumber': str(infrastructure.port_number),
                        'transport': infrastructure.transport,
                        'discoveredOpen': infrastructure.discovered_open,
                        'incident': {
                            'id': infrastructure.incident_id,
                            'scope': infrastructure.incident_scope,
                            'type': infrastructure.incident_type,
                            'subType': infrastructure.incident_sub_type,
                            'severity': infrastructure.incident_severity,
                            'title': infrastructure.incident_title,
                        }
                    }
                    action_result.add_data(data)
            action_result.set_status(phantom.APP_SUCCESS,
                                     DS_GET_INFRASTRUCTURE_SUCCESS)
        else:
            summary = {
                'infrastructure_count': 0,
                'infrastructure_found': False
            }
            action_result.update_summary(summary)
            action_result.set_status(phantom.APP_SUCCESS,
                                     DS_GET_INFRASTRUCTURE_NOT_FOUND)
        return action_result.get_status()
Ejemplo n.º 25
0
    def _list_devices(self, url, param):
        action_result = ActionResult(param)
        self.add_action_result(action_result)

        try:
            self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, url)
            # device_list = floodlight_rest.FloodlightRest(url=url).get('devices')
            self.save_progress("done.")
            if device_list is None:
                return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_NO_DATA)
        except Exception as e:
            return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_SERVER_CONNECTION, e)

        # Floodlight v1.2 and earlier returns a list.  Later versions return a root object containing a list.
        if isinstance(device_list, dict):
            device_list = device_list["devices"]

        # Rearrange into a table-friendly format here.
        # This should definitely change if we ever get a "tree" render type
        result = {"devices": [], "success": True}
        for device in device_list:
            for mac in device["mac"]:
                for vlan in device["vlan"]:
                    for ap in device["attachmentPoint"]:
                        for ip4 in device["ipv4"]:
                            result["devices"].append(
                                {"mac": mac,
                                 "vlan": vlan,
                                 "ip": ip4,
                                 "lastSeen": datetime.utcfromtimestamp(int(device["lastSeen"]) / 1000)
                                                                             .strftime('%Y-%m-%d %H:%M:%S UTC'),
                                 "attachmentPoint": {"port": ap["port"], "switchDPID": "dpid:{}".format(ap["switchDPID"])}
                                 })
                        for ip6 in device["ipv6"]:
                            result["devices"].append(
                                {"mac": mac,
                                 "vlan": vlan,
                                 "ip": ip6,
                                 "lastSeen": datetime.utcfromtimestamp(int(device["lastSeen"]) / 1000)
                                                                             .strftime('%Y-%m-%d %H:%M:%S UTC'),
                                 "attachmentPoint": {"port": ap["port"], "switchDPID": "dpid:{}".format(ap["switchDPID"])}
                                 })

        action_result.add_data(result)

        return action_result.set_status(phantom.APP_SUCCESS, OC2SDN_SUCC)
Ejemplo n.º 26
0
    def _block_flow(self, url, param):
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        try:
            self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, url)
            # result = floodlight_firewall.add_rule(url, "deny", param)
            self.save_progress("done.")
            msg = result.get("status", OC2SDN_ERR_NO_STATUS)
            if msg == u'Rule added':
                action_result.add_data({"activityid": result["activityid"]})
                return action_result.set_status(phantom.APP_SUCCESS, msg)

            return action_result.set_status(phantom.APP_ERROR, msg)

        except Exception as e:
            return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_SERVER_CONNECTION, e)
Ejemplo n.º 27
0
    def _block_flow(self, url, param):
        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        try:
            self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, url)
            # result = floodlight_firewall.add_rule(url, "deny", param)
            self.save_progress("done.")
            msg = result.get("status", OC2SDN_ERR_NO_STATUS)
            if msg == u'Rule added':
                action_result.add_data({"activityid": result["activityid"]})
                return action_result.set_status(phantom.APP_SUCCESS, msg)

            return action_result.set_status(phantom.APP_ERROR, msg)

        except Exception as e:
            return action_result.set_status(phantom.APP_ERROR,
                                            OC2SDN_ERR_SERVER_CONNECTION, e)
Ejemplo n.º 28
0
    def _call_function_as_action(self, url, funct, param={}):
        action_result = ActionResult(param)
        self.add_action_result(action_result)

        try:
            self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, url)
            result = funct()
            self.save_progress("done.")
            if result is None:
                return action_result.set_status(phantom.APP_ERROR,
                                                OC2SDN_ERR_NO_DATA)

            action_result.add_data(result)
            return action_result.set_status(phantom.APP_SUCCESS, OC2SDN_SUCC)

        except Exception as e:
            return action_result.set_status(phantom.APP_ERROR,
                                            OC2SDN_ERR_SERVER_CONNECTION, e)
    def run_job(self, param):
        """ Optionally set the dead interval, logon, determine if the user specified a job template name or the numeric id.
            Launch the job template. If the job was accepted (202 status_code), wait up to the dead interval for the job to
            complete and report back the job id. This numeric job id is specified on the Jobs tab in Ansible Tower.
        """

        self.debug_print("%s RUN_JOB parameters:\n%s" % (Tower_Connector.BANNER, param))
        action_result = ActionResult(dict(param))          # Add an action result to the App Run
        self.add_action_result(action_result)

        self.set_dead_interval(param)

        self.aaaLogin()
        if not self.token:                                 # token will be null if we failed to login
            action_result.set_status(phantom.APP_ERROR)
            self.set_status_save_progress(phantom.APP_ERROR, status_message="Failed to logon")
            return

        try:
            # Job template id used to identify the job template
            job_template_id = int(param["job template id"])
        except ValueError:
            # Job template name is used to identify the job template
            job_template_id = self.get_job_template_id(param["job template id"], self.query_api("/api/v1/job_templates/")["results"])

        # Launch the job specified
        status = self.launch_job(param, job_template_id)
        if status in Tower_Connector.GOOD_LAUNCH_STATES:
            results = self.wait_for_completion()
            if results:
                msg = "job id: %s status: %s name: %s elapsed time: %s sec ended: %s" % (self.job_id, results["status"], results["name"], results["elapsed"], results["finished"])
                action_result.add_data({"job_stats": {"id": self.job_id, "status": results["status"], "name": results["name"], "elapsed": results["elapsed"]}})
                if results["status"] in Tower_Connector.FAILED_JOB_STATES:
                    action_result.set_status(phantom.APP_ERROR)
                    self.set_status_save_progress(phantom.APP_ERROR, status_message=msg)
                else:
                    action_result.set_status(phantom.APP_SUCCESS)
                    self.set_status_save_progress(phantom.APP_SUCCESS, status_message=msg)
            else:
                # nothing to do here, results are None due to an error which has been reported
                pass
        else:
            self.set_status_save_progress(phantom.APP_ERROR, status_message="Job failed to launch: %s" % status)
        return
Ejemplo n.º 30
0
    def _delete_firewall_rule(self, url, param):
        action_result = ActionResult(param)
        self.add_action_result(action_result)

        try:
            self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, url)
            # result = floodlight_firewall.delete_rule(url, None, param)
            self.save_progress("done.")
            if result is None:
                return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_NO_DATA)

            action_result.add_data(result)
            if result.get("success") is not True:
                return action_result.set_status(phantom.APP_ERROR, result.get("status"))

            return action_result.set_status(phantom.APP_SUCCESS, OC2SDN_SUCC)

        except Exception as e:
            return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_SERVER_CONNECTION, e)
Ejemplo n.º 31
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()
Ejemplo n.º 32
0
    def listStaticBlackHoledIPs(self, param):
        """
        """
        action_result = ActionResult(
            dict(param))  # Add an action result to the App Run
        self.add_action_result(action_result)

        config = self.get_config()
        self.debug_print(config)

        try:
            self.username = config["username"]
            self.password = config["password"]
            self.device = config["trigger_host"]
            self.next_hop_IP = config['route_to_null']
        except KeyError:
            self.debug_print("Error: {0}".format(KeyError))

        self.debug_print("Device: {0}, User: {1}, Password: {2}".format(
            self.device, self.username, self.password))
        # Get the current list of static routes from the Target Host

        route_list = self._get_StaticBlackHoledIPs(self.username,
                                                   self.password, self.device,
                                                   self.next_hop_IP)

        self.debug_print(
            "listStaticBlackHoledIP's result RAW: {0}".format(route_list))

        # Even if the query was successfull the data might not be available
        if len(route_list) == 0:
            return action_result.set_status(
                phantom.APP_ERROR, 'CISCO_CSR_ERR_QUERY_RETURNED_NO_DATA')
        else:
            for dest in route_list:
                action_result.add_data({'blackholed-network': dest})
            summary = "Query returned %s routes" % len(route_list)
            action_result.update_summary({'message': summary})
            self.set_status_save_progress(phantom.APP_SUCCESS, summary)
            #action_result.set_status(phantom.APP_SUCCESS)

        return action_result.get_status()
Ejemplo n.º 33
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()
Ejemplo n.º 35
0
    def block_ip(self, param):
        """
        Block a source IP address,  a simple call to update a security policy in place.
        The firewall policy is called "Phantom_Inbound" which currently is tied to an inbound VIP in the "Common" partition.

        POST
        URL https://10.255.111.100/mgmt/tm/security/firewall/policy/~Common~Phantom_Inbound/rules
        body {"name":"DYNAMIC_BLOCK_NAME","action":"reject","place-after":"first","source":{"addresses":[{"name": "8.8.8.8/32"}"

        """
        config = self.get_config()
        self.debug_print("%s BLOCK_IP parameters:\n%s \nconfig:%s" %
                         (F5_Connector.BANNER, param, config))

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

        URL = "/mgmt/tm/security/firewall/policy/~%s~%s/rules" % (
            param["partition"], param["policy"])
        body = '{"name":"%s","action":"%s","place-after":"first","source":{"addresses":[{"name":"%s/32"}]}}' \
               % (param["rule name"], param["action"], param["source"])

        self.debug_print("%s BLOCK_IP URL: %s \nbody:%s" %
                         (F5_Connector.BANNER, URL, body))

        F5 = iControl.BIG_IP(host=config.get("device"),
                             username=config.get("username"),
                             password=config.get("password"),
                             uri=URL,
                             method="POST")

        if F5.genericPOST(body):
            action_result.set_status(phantom.APP_SUCCESS)
        else:
            action_result.set_status(phantom.APP_ERROR)

        action_result.add_data(F5.response)
        self.debug_print("%s BLOCK_IP code: %s \nresponse: %s" %
                         (F5_Connector.BANNER, F5.status_code, F5.response))
        return
Ejemplo n.º 36
0
    def _get_uptime(self, url, param):
        action_result = ActionResult(param)
        self.add_action_result(action_result)

        try:
            self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, url)
            # result = floodlight_rest.FloodlightRest(url=url).get("uptime")
            self.save_progress("done.")
            if result is None:
                return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_NO_DATA)
        except Exception as e:
            return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_SERVER_CONNECTION, e)

        # Add a human-readable timestamp
        uptime = datetime.utcfromtimestamp(0) + timedelta(microseconds=int(result["systemUptimeMsec"]) * 1000)
        result["hhmmss"] = uptime.strftime('%H:%M:%S.%f')[:-3]
        result["success"] = True

        action_result.add_data(result)

        return action_result.set_status(phantom.APP_SUCCESS, OC2SDN_SUCC)
    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()
Ejemplo n.º 38
0
    def _list_external_links(self, url, param):
        action_result = ActionResult(param)
        self.add_action_result(action_result)

        try:
            self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, url)
            # link_list = floodlight_rest.FloodlightRest(url=url).get('external_links')
            self.save_progress("done.")
            if link_list is None:
                return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_NO_DATA)
        except Exception as e:
            return action_result.set_status(phantom.APP_ERROR, OC2SDN_ERR_SERVER_CONNECTION, e)

        result = {"links": link_list, "success": True}
        # Add "dpid" namespaces to src-switch and dst-switch.
        for link in link_list:
            link["src-switch"] = "dpid:{}".format(link["src-switch"])
            link["dst-switch"] = "dpid:{}".format(link["dst-switch"])

        action_result.add_data(result)

        return action_result.set_status(phantom.APP_SUCCESS, OC2SDN_SUCC)
Ejemplo n.º 39
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()
Ejemplo n.º 40
0
    def modify_smartflow_policy(self, param, LADS, CRUD):
        " Modify the Smartflow Policy "

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

        source_ip = self.normalize_ip(param["source"])     # 8.8.8.8/32 or 192.0.2.0/24 or 4.4.4.4
        app_name = param["application"]                    # WWT-API
        host_name = param["host"]                          # default-host
        service_name = param["service"]                    # default-service
        smartflow_name = param["smartflow"]                # default-smartflow
        try:
            rule_action = param["action"]                  # 'deny' or 'allow', not specified for unblock
        except KeyError:
            rule_action = None

        uri = "/api/v2/applications/%s/hosts/%s/services/%s/smartflows/%s/policies" % (app_name, host_name, service_name, smartflow_name)

        if LADS.genericGET(uri=uri):                       # Successfully retrieved the Smartflow policy
            LADS.separate_access_policy(LADS.response)
            if LADS.modify_access_policy(CRUD, rule_action, source_ip):
                LADS.include_access_policy()
                uri += "/_import"
                if LADS.genericPOST(uri=uri, body=json.dumps(LADS.smartflow_policies)):
                    action_result.set_status(phantom.APP_SUCCESS)
                    LADS.separate_access_policy(LADS.response)    # Isolate the access policy
                else:
                    action_result.set_status(phantom.APP_ERROR)
            else:
                action_result.set_status(phantom.APP_ERROR)   # Failure in modifying access policy
        else:
            action_result.set_status(phantom.APP_ERROR)   # Failed to retrieve Smartflow policy

        action_result.add_data(LADS.access_policy)        # Put the current access policy in the result data
        self.debug_print("%s modify_smartflow_policy code: %s \nresponse: %s" % (A10_LADS_Connector.BANNER, LADS.status_code, LADS.response))
        return
Ejemplo n.º 41
0
    def block_ip(self, param):
        """
        Block a source IP address,  a simple call to update a security policy in place.
        The firewall policy is called "Phantom_Inbound" which currently is tied to an inbound VIP in the "Common" partition.

        POST
        URL https://10.255.111.100/mgmt/tm/security/firewall/policy/~Common~Phantom_Inbound/rules
        body {"name":"DYNAMIC_BLOCK_NAME","action":"reject","place-after":"first","source":{"addresses":[{"name": "8.8.8.8/32"}"

        """
        config = self.get_config()
        self.debug_print("%s BLOCK_IP parameters:\n%s \nconfig:%s" % (F5_Connector.BANNER, param, config))

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

        URL = "/mgmt/tm/security/firewall/policy/~%s~%s/rules" % (param["partition"], param["policy"])
        body = '{"name":"%s","action":"%s","place-after":"first","source":{"addresses":[{"name":"%s/32"}]}}' \
               % (param["rule name"], param["action"], param["source"])

        self.debug_print("%s BLOCK_IP URL: %s \nbody:%s" % (F5_Connector.BANNER, URL, body))

        F5 = iControl.BIG_IP(host=config.get("device"),
                             username=config.get("username"),
                             password=config.get("password"),
                             uri=URL,
                             method="POST")

        if F5.genericPOST(body):
            action_result.set_status(phantom.APP_SUCCESS)
        else:
            action_result.set_status(phantom.APP_ERROR)

        action_result.add_data(F5.response)
        self.debug_print("%s BLOCK_IP code: %s \nresponse: %s" % (F5_Connector.BANNER, F5.status_code, F5.response))
        return