Example #1
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 #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
Example #3
0
    def _test_connectivity(self, param):

        config = self.get_config()

        ip = config['ip']
        port = int(param.get('port', 137))
        timeout = int(param.get('timeout', 30))

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

        self.save_progress("Looking up IP : {0} to test connectivity".format(ip))
        nb = NetBIOS()
        hosts = nb.queryIPForName(ip, port, timeout)
        if hosts is None:
            self.save_progress("Request timed out")
            self.save_progress("Test Connectivity Failed")
            return action_result.set_status(phantom.APP_ERROR)

        if hosts:
            self.save_progress("Got {0} hosts".format(len(hosts)))
            self.save_progress("Test Connectivity Passed")
            return action_result.set_status(phantom.APP_SUCCESS)

        self.save_progress("Lookup did not return any results, but connectivity passed")

        return action_result.set_status(phantom.APP_SUCCESS)
Example #4
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
Example #5
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()
    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()
Example #7
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 #8
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 #9
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)
Example #10
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 #11
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 #12
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()
Example #13
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()
Example #14
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()
Example #15
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)
Example #16
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 #17
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()
    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 #19
0
    def _whois_object(self, param, json_key):

        self.debug_print("param", param)

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

        input_object = param[json_key]

        try:
            self._parsed_whois_domain(input_object, action_result)
        except Exception as e:
            self.debug_print(e)

        try:
            if not action_result.get_status() == phantom.APP_SUCCESS:
                self._regular_whois_domain(input_object, action_result)
        except Exception as e:
            message = 'Error while querying input_object'
            action_result.set_status(phantom.APP_ERROR, message, e)
            return action_result.get_status()

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

        data = action_result.get_data()

        if (not data):
            return action_result.get_status()

        response = data[0]

        if response and 'registrant' in response:
            # get the registrant
            summary = {'organization': response['registrant']}
            if 'parsed_whois' in response:
                contacts = response['parsed_whois'].get('contacts', {})
                if type(contacts) == list:
                    registrant = contacts[0]
                else:
                    registrant = contacts.get('registrant')
                summary['city'] = registrant.get('city')
                summary['country'] = registrant.get('country')
                action_result.update_summary(summary)

        return action_result.get_status()
Example #20
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()
Example #21
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)
Example #22
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)
    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()
Example #24
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)
Example #25
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)
Example #26
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()
Example #27
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)
Example #28
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 #30
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
    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()
Example #32
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)
Example #33
0
    def _handle_get_report(self, param):
        # type: (Dict[Text, Any]) -> bool

        submission_id = int(param["submission_id"])

        try:
            timeout = int(param["timeout"])
            if timeout < 0:
                timeout = DEFAULT_TIMEOUT
        except Exception:
            timeout = DEFAULT_TIMEOUT

        status, res = self._get_report(submission_id, timeout)
        if status == phantom.APP_ERROR:
            error_msg, exc = res
            self.set_status(phantom.APP_ERROR, error_msg, exc)
            return self.get_status()

        analyses = res["analyses"]
        reputation_lookup = res["reputation_lookup"]
        severity = res["severity"]
        submission_url = res["submission_url"]

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

        for analysis in analyses:
            action_result.add_data({"analysis": analysis})

        if reputation_lookup:
            action_result.add_data({"reputation_lookup": reputation_lookup[0]})

        action_result.update_summary({
            "severity": severity,
            "submission_id": submission_id,
            "url": submission_url
        })
        action_result.set_status(phantom.APP_SUCCESS)

        return action_result.get_status()
Example #34
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 #35
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 #36
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)
Example #37
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 #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)
    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()
Example #40
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
    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