def _handle_test_connectivity(self, param): # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) # NOTE: test connectivity does _NOT_ take any parameters # i.e. the param dictionary passed to this handler will be empty. # Also typically it does not add any data into an action_result either. # The status and progress messages are more important. self.save_progress('Connecting to endpoint') # make rest call to the status endpoint ret_val, response = self._make_rest_call('categories/status', action_result) if phantom.is_fail(ret_val): # The call failed. Return status and error returned. self.save_progress('Test connectivity failed: {}'.format(response)) return action_result.get_status() self.save_progress('Test connectivity passed') return action_result.set_status(phantom.APP_SUCCESS)
def _handle_test_connectivity(self, param): action_result = self.add_action_result(ActionResult(dict(param))) self.save_progress("Connecting to {}{} endpoint".format( self._base_url, HEALTH_ENDPOINT)) # make rest call ret_val, response = self._make_rest_call(HEALTH_ENDPOINT, action_result, params=None, headers=None) # Return success if 'healthy' in str(response): self.save_progress("Test Connectivity Passed") return action_result.set_status(phantom.APP_SUCCESS) if phantom.is_fail(ret_val): self.save_progress("Test Connectivity Failed") return action_result.get_status() self.save_progress("Test Connectivity Failed") return action_result.set_status(phantom.APP_ERROR)
def _get_updated_reports(self, param, action_result): try: config = self.get_config() program = self._handle_unicode_for_input_str( config['program_name']) state = self._handle_unicode_for_input_str( param.get('state_filter')) assignment = self._handle_unicode_for_input_str( param.get('assignment_filter')) add_comments = param.get('full_comments', False) # Integer Validation for 'range' parameter minutes = param.get('range') ret_val, minutes = self._validate_integer(action_result, minutes, RANGE_KEY) if phantom.is_fail(ret_val): return action_result.get_status() self.debug_print( "There might be timezone variance. Please check for the timezone variance." ) date = (datetime.datetime.now() - datetime.timedelta( minutes=minutes)).strftime('%Y-%m-%dT%H:%M:%S.%fZ') reports = self._get_filtered_reports(program, state, assignment, add_comments, date) if not reports: self.__print('No reports found') return action_result.set_status(phantom.APP_ERROR, 'Failed to get reports') action_result.add_data({'reports': reports, 'count': len(reports)}) self._add_report_artifacts(reports) self.__print('Successfully collected reports') return action_result.set_status(phantom.APP_SUCCESS, 'Successfully collected reports') except Exception as e: err = self._get_error_message_from_exception(e) self.__print('Failed to get reports') action_result.add_exception_details(err) return action_result.set_status(phantom.APP_ERROR, 'Failed to get reports')
def _get_phantom_base_url(self, action_result): """ Get base url of phantom. :param action_result: object of ActionResult class :return: status phantom.APP_ERROR/phantom.APP_SUCCESS(along with appropriate message), base url of phantom """ url = '{0}{1}{2}'.format(BaseConnector._get_phantom_base_url(), 'rest', PHANTOM_SYSTEM_INFO_ENDPOINT) ret_val, resp_json = self._make_rest_call(action_result=action_result, endpoint=url, verify=False) if phantom.is_fail(ret_val): return ret_val, None phantom_base_url = resp_json.get('base_url') if not phantom_base_url: return action_result.set_status( phantom.APP_ERROR, WEBEX_ERR_PHANTOM_BASE_URL_NOT_FOUND), None return phantom.APP_SUCCESS, phantom_base_url.rstrip('/')
def _handle_lookup_url(self, param): self.save_progress("In action handler for: {0}".format( self.get_action_identifier())) action_result = self.add_action_result(ActionResult(dict(param))) url = param['url'] data = {} data['url'] = url ret_val, response = self._make_rest_call('/url', action_result, params=None, headers=None, method="post", data=data) if phantom.is_fail(ret_val): self.save_progress("Failed to contact URLhaus") return action_result.get_status() action_result.add_data(response) try: summary = action_result.update_summary({}) if response['query_status'] == "no_results": summary['message'] = "No results found for: {0}".format(url) elif response['query_status'] == "ok": summary['date_added'] = response['date_added'] payload_count = len(response['payloads']) summary['payload_count'] = payload_count summary[ 'message'] = "URL {0} observed dropping {1} payloads".format( url, payload_count) summary['query_status'] = response['query_status'] except Exception as e: error_msg = self._get_error_message_from_exception(e) return action_result.set_status(phantom.APP_ERROR, error_msg) return action_result.set_status(phantom.APP_SUCCESS)
def _handle_get_user(self, param): self.save_progress("In action handler for: {0}".format( self.get_action_identifier())) action_result = self.add_action_result(ActionResult(dict(param))) user_id = param['user_id'] ret_val, response = self._make_rest_call('/users/{}'.format(user_id), action_result, params=None, headers=None) if phantom.is_fail(ret_val): return action_result.get_status() action_result.add_data(response) return action_result.set_status( phantom.APP_SUCCESS, 'User information for id {} successfully retrieved'.format( user_id))
def _disable_session_scrolling(self, action_result, scroll_id, flag=False): """ This function is used to disable session scrolling for indicators and search APIs. :param action_result: object of ActionResult class :param scroll_id: session scroll id to be disabled. :param flag: If flag value is True, this paginator finalize work for indicators APIs; else it's works for all search APIs :return: status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ if not scroll_id: self.debug_print("Scroll session is not available") return phantom.APP_SUCCESS endpoint = str() data = { "scroll_id": scroll_id } if flag: # This block is used for indicators simple APIs endpoint = FLASHPOINT_SIMPLIFIED_INDICATORS_SCROLL_ENDPOINT else: # This block is used for all search APIs endpoint = FLASHPOINT_ALL_SEARCH_SCROLL_ENDPOINT self.debug_print("Make a rest call to disable scroll session") # Make rest call ret_val, _ = self._make_rest_call(endpoint, action_result, method='delete', data=json.dumps(data)) if phantom.is_fail(ret_val): # If session already disabled if FLASHPOINT_ALREADY_DISABLE_SESSION_SCROLL_ERROR_MESSAGE in action_result.get_message(): self.debug_print("Session is already disabled") return phantom.APP_SUCCESS return action_result.get_status() self.debug_print("Successfully disabled the scroll session") return phantom.APP_SUCCESS
def _test_connectivity(self): 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('', self, params, method='post', stream=True) if (phantom.is_fail(ret_val)): self.append_to_message('Test connectivity failed') return self.get_status() return self.set_status_save_progress(ret_val, "Test Connectivity Passed")
def _handle_test_connectivity(self, param): # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) self.save_progress("Connecting to endpoint") params = {'duration': '2_hours'} endpoint = FIREEYEAX_ALERTS_ENDPOINT # make rest call ret_val, _ = self._make_rest_call(endpoint, action_result, params=params) if phantom.is_fail(ret_val): self.save_progress("Test Connectivity Failed") return action_result.get_status() # Return success self.save_progress("Test Connectivity Passed") return action_result.set_status(phantom.APP_SUCCESS)
def _handle_add_note(self, param): self.save_progress(f"Run action {self.get_action_identifier()}") # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) content = param.get("content", "") category = "Splunk Phantom" incident_id = param.get("incident_id") if not incident_id: self.debug_print(f"required incident_id param not present in action: {self.get_action_identifier()}") return action_result.set_status(phantom.APP_ERROR, "incident id not specified") body = { "content": content, "category": category, } radar_val, data = self._make_rest_call(f"/incidents/{incident_id}/notes", action_result, method="post", data=json.dumps(body)) if phantom.is_fail(radar_val): return action_result.get_status() # construct note output with fields we want to render note = dict() try: note["id"] = data["headers"]["Location"].split("/")[4] # return error for missing id from response headers except Exception: self.debug_print("could not parse id from response headers: ", data["headers"]) return action_result.set_status(phantom.APP_ERROR, "Response payload is missing necessary fields: 'id'") note["incident_id"] = incident_id note["content"] = content self.save_progress("Add data to action result") action_result.add_data(note) return action_result.set_status(phantom.APP_SUCCESS, "Successfully added note")
def _handle_get_notes(self, param): self.save_progress(f"Run action {self.get_action_identifier()}") # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) incident_id = param.get("incident_id") if not incident_id: self.debug_print(f"required incident_id param not present in action: {self.get_action_identifier()}") return action_result.set_status(phantom.APP_ERROR, "incident id not specified") radar_val, data = self._make_rest_call(f"/incidents/{incident_id}/notes", action_result, method="get") if phantom.is_fail(radar_val): return action_result.get_status() # construct note output with fields we want to render notes = [] for note_data in data: try: if note_data["category"] == "Splunk Phantom": notes.append({ "incident_id": incident_id, "id": note_data["id"], "content": note_data["content"], "category": note_data["category"], "created_at": self._format_display_time(self._localize_time(note_data["created_at"])), "created_by": note_data["created_by"], "updated_at": self._format_display_time(self._localize_time(note_data["updated_at"])), "updated_by": note_data["updated_by"], }) # return errors for missing fields that should always be present except KeyError as ex: return self._payload_err(ex, action_result, data) self.save_progress("Add data to action result") action_result.add_data(notes) return action_result.set_status(phantom.APP_SUCCESS, "Successfully fetched notes")
def _handle_whois_history(self, param): # Adding action handler message self.save_progress("In action handler for: {0}".format(self.get_action_identifier())) # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) # Pass domain to the search domain = param['domain'] # Issue request to history whois endpoint = '/history/{}/whois?page=1'.format(domain) # Make connection to the SecurityTrails endpoint ret_val, response = self._make_rest_call(endpoint, action_result) # Connect to Phantom Endpoint self.save_progress("Downloading Page 1 of output") if (phantom.is_fail(ret_val)): # the call to the 3rd party device or service failed, action result should contain all the error details # so just return from here message = "Failed Response to whois history." return action_result.set_status(phantom.APP_ERROR, status_message=message) # Create new python dictionary to store output data_output = response # Add the response into the data section action_result.add_data(data_output) # Add a dictionary that is made up of the most important values from data into the summary summary = action_result.update_summary({}) summary['domain'] = domain # Return success, no need to set the message, only the status # BaseConnector will create a textual message based off of the summary dictionary return action_result.set_status(phantom.APP_SUCCESS)
def _update_fw_rule(self, action_result, zone_id, payload): fw_rule_id = payload['id'] paused = payload['paused'] self.save_progress("Updating Firewall Rule {}".format(fw_rule_id)) ret_val, response = self._make_rest_call( CLOUDFLARE_FWRULE_ENDPOINT.format(zone_id=zone_id), action_result, method='put', data=json.dumps([payload]), headers=self._headers) if phantom.is_fail(ret_val): return RetVal( action_result.set_status(phantom.APP_ERROR, action_result.get_message()), None) msg = "Successfully {} firewall rule {}".format( "enabled" if not paused else "disabled", fw_rule_id) return RetVal(action_result.set_status(phantom.APP_SUCCESS, msg), response)
def _handle_test_connectivity(self, param): # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) self.save_progress("Connecting to the SentinelOne server") # make rest call header = self.HEADER header["Authorization"] = "APIToken %s" % self.token ret_val, response = self._make_rest_call('/web/api/v1.6/threats/summary', action_result, headers=header) self.save_progress("response: {0}".format(response)) if (phantom.is_fail(ret_val)): # the call to the 3rd party device or service failed, action result should contain all the error details # so just return from here self.save_progress("Test Connectivity Failed. Error: {0}".format(action_result.get_message())) return action_result.get_status() # Return success self.save_progress("Login to SentinelOne server is successful") return action_result.set_status(phantom.APP_SUCCESS)
def _make_rest_call(self, endpoint, result, params={}, headers={}, json=None, method="get", stream=False): url = "{0}{1}".format(self._rest_url, endpoint) if self._headers is not None: (headers.update(self._headers)) request_func = getattr(requests, method) if not request_func: return result.set_status( phantom.APP_ERROR, "Invalid method call: {0} for requests module".format( method)), None try: r = request_func(url, headers=headers, params=params, json=json, stream=stream) except Exception as e: return result.set_status(phantom.APP_ERROR, "REST Api to server failed", e), None ret_val, resp_data = self._parse_response(result, r) # Any http or parsing error is handled by the _parse_response function if phantom.is_fail(ret_val): return (result.get_status(), resp_data) return (phantom.APP_SUCCESS, resp_data)
def _hunt_domain(self, param): action_result = self.add_action_result(ActionResult(dict(param))) summary_data = action_result.update_summary({}) # Getting mandatory input params domain = param[PHISHME_JSON_DOMAIN] # Convert URL to domain if phantom.is_url(domain): domain = phantom.get_host_from_url(domain) # Getting optional parameter max_threat_cnt = int(param.get(PHISHME_JSON_MAX_THREAT_COUNT, PHISHME_DEFAULT_MAX_THREAT_COUNT)) data = {'domain': domain} return_value, json_resp = self._threat_search(data, max_threat_cnt, action_result) # Something went wrong with the request if phantom.is_fail(return_value): self.debug_print(action_result.get_message()) return action_result.get_status() # Resource not found is treated as app success # Empty threats is also treated as app success if not json_resp or not json_resp["data"]["threats"]: return action_result.set_status(phantom.APP_SUCCESS, PHISHME_REST_RESP_RESOURCE_NOT_FOUND_MSG) # Get the required data to dump in action result data_to_add = self._parse_response(json_resp, ioc_type='Domain Name', param_value=domain) action_result.add_data(data_to_add) total_threats = len(json_resp["data"]["threats"]) summary_data['total_threats'] = total_threats return action_result.set_status(phantom.APP_SUCCESS)
def _handle_remove_member(self, param): self.save_progress("In action handler for: {0}".format(self.get_action_identifier())) action_result = self.add_action_result(ActionResult(dict(param))) uri = '/api/directory/remove-group-member' headers = self._get_request_headers(uri=uri, action_result=action_result) data = { "data": [ { "id": param.get("id") } ] } data_object = {} member = param.get("member") if phantom.is_domain(member): data_object['domain'] = member elif phantom.is_email(member): data_object['emailAddress'] = member if data_object: data['data'][0].update(data_object) ret_val, response = self._make_rest_call_helper(uri, action_result, headers=headers, method="post", data=data) if phantom.is_fail(ret_val): return ret_val action_result.add_data(response['data'][0]) summary = action_result.update_summary({}) summary['status'] = "Successfully removed member from group" return action_result.set_status(phantom.APP_SUCCESS)
def _handle_delete_ip(self, param): self.save_progress("In action handler for: {0}".format(self.get_action_identifier())) # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) ip_set_id = param.get('ip_set_id') ip_set_name = param.get('ip_set_name') ip_address = param.get('ip_address') if not ip_set_id and not ip_set_name: return action_result.set_status(phantom.APP_ERROR, AWSWAF_INSUFFICIENT_PARAM) ip_set = self.paginator(AWSWAF_DEFAULT_LIMIT, action_result) ip_set_id = self._verify_ip_set(action_result, ip_set, ip_set_id, ip_set_name) if not ip_set_id: return action_result.set_status(phantom.APP_ERROR, AWSWAF_INVALID_INPUT) type = self._validate_ip(ip_address) if type is None: return action_result.set_status(phantom.APP_ERROR, AWSWAF_IMPROPER_FORMAT) if not type: return action_result.set_status(phantom.APP_ERROR, AWSWAF_INVALID_IP) ret_val = self._ip_update(action_result, type, ip_address, ip_set_id) summary = action_result.update_summary({}) summary['ip_status'] = 'IP deleted successfully' if phantom.is_fail(ret_val): summary['ip_status'] = 'IP could not be deleted' return action_result.get_status()
def _handle_list_providers(self, param): self.save_progress("In action handler for: {0}".format(self.get_action_identifier())) # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) query = param.get('query', '') type_param = param.get('type', '') ret_val, limit = self._validate_integer(action_result, param.get('limit')) if phantom.is_fail(ret_val): return action_result.get_status() params = dict() params = { 'limit': 200, 'q': query, 'type_param': type_param } providers_list = self._get_paginated_results('/idps', limit, action_result, params=params, headers=None) if providers_list is None: return action_result.set_status(phantom.APP_ERROR, OKTA_PAGINATION_MSG_ERR.format(action_name=self.get_action_identifier())) # Add the response into the data section for item in providers_list: action_result.add_data(item) # Add a dictionary that is made up of the most important values from data into the summary summary = action_result.update_summary({}) summary['num_idps'] = len(providers_list) # Return success, no need to set the message, only the status # BaseConnector will create a textual message based off of the summary dictionary return action_result.set_status(phantom.APP_SUCCESS)
def _handle_describe_instance(self, param): self.save_progress( "In action handler for: {0}".format(self.get_action_identifier()) ) action_result = self.add_action_result(ActionResult(dict(param))) if not self._create_discovery_client(action_result): self.save_progress("Could not create API client") return action_result.get_status() zone = param["zone"] resourceid = param["id"] try: request = self._client.instances().get( project=self._project, zone=zone, instance=resourceid ) except Exception as e: err = self._get_error_message_from_exception(e) return action_result.set_status(phantom.APP_ERROR, err) ret_val, response = self._send_request(request, action_result) if phantom.is_fail(ret_val): return ret_val action_result.add_data(response) summary = action_result.update_summary({}) try: summary["id"] = response.get("id") summary["name"] = response.get("name") summary["machineType"] = response.get("machineType") except Exception as e: err = self._get_error_message_from_exception(e) return action_result.set_status(phantom.APP_ERROR, err) return action_result.set_status(phantom.APP_SUCCESS, "Success")
def _handle_list_tickets(self, param): # Implement the handler here # use self.save_progress(...) to send progress messages back to the platform self.save_progress("In action handler for: {0}".format( self.get_action_identifier())) # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) authToken = "Bearer " + self._api_key headers = {'Authorization': authToken} params = {'range': 'all'} ret_val, response = self._make_rest_call('api/case', action_result, params=params, headers=headers) if (phantom.is_fail(ret_val)): # the call to the 3rd party device or service failed, action result should contain all the error details # so just return from here return action_result.get_status() # Now post process the data, uncomment code as you deem fit # Add the response into the data section # action_result.add_data(response) for ticket in response: action_result.add_data(ticket) summary = action_result.set_summary({}) summary['num_tickets'] = len(response) # Add a dictionary that is made up of the most important values from data into the summary # Return success, no need to set the message, only the status # BaseConnector will create a textual message based off of the summary dictionary return action_result.set_status(phantom.APP_SUCCESS)
def _handle_scan_endpoint(self, param): self.save_progress("In action handler for: {0}".format( self.get_action_identifier())) action_result = self.add_action_result(ActionResult(dict(param))) ip_hostname = param['ip_hostname'] try: ret_val = self._get_agent_id(ip_hostname, action_result) except Exception: return action_result.set_status( phantom.APP_ERROR, "Did not get proper response from the server") self.save_progress('Agent query: {}'.format(ret_val)) if ret_val == '0': return action_result.set_status(phantom.APP_ERROR, "Endpoint not found") elif ret_val == '99': return action_result.set_status(phantom.APP_ERROR, "More than one endpoint found") else: summary = action_result.update_summary({}) summary['ip_hostname'] = ip_hostname summary['agent_id'] = ret_val header = self.HEADER header["Authorization"] = "APIToken %s" % self.token body = {"data": {}, "filter": {"ids": ret_val}} ret_val, response = self._make_rest_call( '/web/api/v2.1/agents/actions/initiate-scan', action_result, headers=header, data=json.dumps(body), method='post') self.save_progress("Ret_val: {0}".format(ret_val)) if phantom.is_fail(ret_val): self.save_progress( "Failed to scan endpoint. Error: {0}".format( action_result.get_message())) return action_result.get_status() return action_result.set_status(phantom.APP_SUCCESS)
def _handle_backup_corelight(self, param): self.save_progress("In action handler for: {0}".format(self.get_action_identifier())) action_result = self.add_action_result(ActionResult(dict(param))) bundlePassword = param['bundle_password'] uri = '/api/provision/bundle?bundle-password='******'&no-sensitive=0&type=backup' ret_val, response = self._make_rest_call(uri, action_result, params=None, headers=None) try: fileName = param['backup_name'] file_path = "{0}/{1}".format(self._local_dir, fileName) output = json.dumps(response) with open(file_path, 'wb') as f: f.write(output) except Exception as e: return action_result.set_status(phantom.APP_ERROR, "Unable to write to a temporary file in the folder {0}".format(self._local_dir), e) vault_ret_dict = Vault.add_attachment(file_path, self.get_container_id(), file_name=fileName) curr_data = {} if (vault_ret_dict['succeeded']): curr_data[phantom.APP_JSON_VAULT_ID] = vault_ret_dict[phantom.APP_JSON_HASH] curr_data[phantom.APP_JSON_NAME] = fileName action_result.add_data(curr_data) wanted_keys = [phantom.APP_JSON_VAULT_ID, phantom.APP_JSON_NAME] summary = {x: curr_data[x] for x in wanted_keys} action_result.update_summary(summary) action_result.set_status(phantom.APP_SUCCESS) else: action_result.set_status(phantom.APP_ERROR, phantom.APP_ERR_FILE_ADD_TO_VAULT) action_result.append_to_message(vault_ret_dict['message']) if (phantom.is_fail(ret_val)): return action_result.get_status() action_result.add_data(response) return action_result.set_status(phantom.APP_SUCCESS)
def _handle_reset_password(self, param): self.save_progress("In action handler for: {0}".format( self.get_action_identifier())) # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) user_id = self._handle_py_ver_compat_for_input_str(param['user_id']) receive_type = param['receive_type'] if receive_type not in RECEIVE_TYPE_VALUE_LIST: return action_result.set_status( phantom.APP_ERROR, VALUE_LIST_VALIDATION_MSG.format(RECEIVE_TYPE_VALUE_LIST, 'receive_type')) params = dict() params['sendEmail'] = True if receive_type == 'UI': params['sendEmail'] = False # make rest call ret_val, response = self._make_rest_call( '/users/{}/lifecycle/reset_password'.format(user_id), action_result, params=params, method='post') if phantom.is_fail(ret_val): return action_result.get_status() # Add the response into the data section action_result.add_data(response) # Return success, no need to set the message, only the status # BaseConnector will create a textual message based off of the summary dictionary return action_result.set_status(phantom.APP_SUCCESS, OKTA_RESET_PASSWORD_SUCC)
def _format_list_applocker_script(self, action_result, location, ldap, xml=True, module=True): suffix = "-XML" if xml else "" if location.lower() not in ('local', 'domain', 'effective'): return action_result.set_status( phantom.APP_ERROR, 'Error: "location" must be one of "local", "domain", or "effective"' ), None if location.lower() == "domain": if not ldap: return action_result.set_status( phantom.APP_ERROR, 'Error: "ldap" must be included with "domain"'), None else: args = {"LDAP": ldap} if module: prefix = consts.APPLOCKER_BASE_SCRIPT + 'Get-AppLockerPolicy -Domain' else: prefix = 'Get-AppLockerPolicy -Domain' ret_val, ps_script = self._create_ps_script(action_result, args, cmd_prefix=prefix, cmd_suffix=suffix) if phantom.is_fail(ret_val): return ret_val, None else: if module: ps_script = consts.APPLOCKER_BASE_SCRIPT + 'Get-AppLockerPolicy -{0} {1}'.format( location, suffix) else: ps_script = 'Get-AppLockerPolicy -{0} {1}'.format( location, suffix) return phantom.APP_SUCCESS, ps_script
def _handle_delete_ip(self, param): self.save_progress( AWSWAF_INFO_ACTION.format(self.get_action_identifier())) # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) ip_set_id = param.get('ip_set_id') ip_set_name = param.get('ip_set_name') ip_address = param.get('ip_address') ip_address_list = [ x.strip() for x in ip_address.split(',') if x.strip() ] _ = self.validate_params(action_result, ip_set_id, ip_set_name, ip_address_list) ip_set = self.paginator(AWSWAF_DEFAULT_LIMIT, action_result) ip_set_id, ip_set_name = self._verify_ip_set(action_result, ip_set, ip_set_id, ip_set_name) if not ip_set_id: return action_result.set_status(phantom.APP_ERROR, AWSWAF_INVALID_INPUT) ret_val = self._ip_update(action_result, ip_address_list, ip_set_id, ip_set_name) summary = action_result.update_summary({}) if phantom.is_fail(ret_val): summary['ip_status'] = AWSWAF_DELETE_IP_FAILED summary['ip_status'] = AWSWAF_DELETE_IP_SUCCESS return action_result.get_status()
def _handle_get_file(self, param): action_result = self.add_action_result(ActionResult(dict(param))) if not self._init_session(action_result, param): return action_result.get_status() file_path = param['file_path'] file_path = self._sanitize_string(file_path) script_str = consts.GET_FILE.format(file_path) additional_data = { 'container_id': self.get_container_id(), 'file_name': ntpath.split(file_path)[-1] } ret_val = self._run_ps(action_result, script_str, pc.decodeb64_add_to_vault, additional_data) if phantom.is_fail(ret_val): return ret_val return action_result.set_status( phantom.APP_SUCCESS, "Successfully retrieved file and added it to the Vault")
def _get_system_volume(self, action_result): ps_script = '"list volume" | diskpart' ret_val = self._run_ps(action_result, ps_script) if phantom.is_fail(ret_val): return RetVal(ret_val) volume = -1 std_out = action_result.get_data()[0]['std_out'] try: for line in std_out.splitlines(): if line.strip().lower().endswith('system'): volume = int(line.split()[1]) except: return RetVal( action_result.set_status(phantom.APP_ERROR, "Error parsing diskpart output")) if volume == -1: return RetVal( action_result.set_status( phantom.APP_ERROR, "Could not find the System partition")) return phantom.APP_SUCCESS, volume
def _make_me_available(self, action_result, make_me_available_url): """ This function is used to call the makeMeAvailable endpoint, which is required to perform other actions. :param action_result: Object of ActionResult class :param make_me_available_url: URL for makeMeAvailable :return: status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ request_headers = { 'Authorization': 'Bearer {0}'.format(self._access_token), 'Content-Type': SKYPE4B_HEADERS_APP_JSON } request_status, _ = self._make_rest_call(make_me_available_url, method='post', data=json.dumps({}), headers=request_headers, action_result=action_result) if phantom.is_fail(request_status): return action_result.get_status() return phantom.APP_SUCCESS
def _get_phantom_base_url_skype(self, action_result): """ Get base URL of phantom. :param action_result: object of ActionResult class :return: status phantom.APP_ERROR/phantom.APP_SUCCESS(along with appropriate message), base URL of phantom """ url = '{0}{1}'.format( SKYPE4B_PHANTOM_BASE_URL.format( phantom_base_url=self._get_phantom_base_url()), SKYPE4B_PHANTOM_SYS_INFO_URL) ret_val, resp_json = self._make_rest_call(action_result=action_result, endpoint=url, verify=False) if phantom.is_fail(ret_val): return action_result.get_status(), None phantom_base_url = resp_json.get('base_url') if not phantom_base_url: return action_result.set_status( phantom.APP_ERROR, SKYPE4B_BASE_URL_NOT_FOUND_MSG), None return phantom.APP_SUCCESS, phantom_base_url