def get_query_progress(self, auth, url): """ Checks on the progress of a query ID. :param auth: Authentication header created in create_auth_header() :param url: URL created in create_endpoint_url() :return: xml """ headers = {'Content-Type': 'text/xml', 'Authorization': auth} handle = open_url(url=url, headers=headers, method="GET", validate_certs=self.ssl_context) out_xml = None try: out_xml = handle.read() if 'error code="255"' in out_xml: raise FSMBaseException( msg="Query Error, invalid query_id used to query progress." ) except BaseException as err: raise FSMBaseException(msg="get_query_progress() failed. Error: " + str(err)) return out_xml
def submit_report_request(self, auth, url, report_xml): """ Submits the report request to the API. :param auth: Authentication header created in create_auth_header() :param url: URL created in create_endpoint_url() :param report_xml: string format of the report XML to be submitted. :return: xml """ headers = {'Content-Type': 'text/xml', 'Authorization': auth} handle = open_url(url=url, data=report_xml, headers=headers, validate_certs=self.ssl_context) out_xml = None try: out_xml = handle.read() try: self.last_http_return_code = handle.getcode() self.last_http_return_headers = handle.info() self.last_http_return_url = url except BaseException as err: raise FSMBaseException( msg= "submit_report_request() failed to get last HTTP codes. Error: " + str(err)) except BaseException as err: raise FSMBaseException( msg="submit_report_request() failed. Error: " + str(err)) return out_xml
def submit_simple_request(self, auth, url): """ Submits a simple GET request without an XML payload. :param auth: Authentication header created in create_auth_header() :param url: URL created in create_endpoint_url() :return: xml """ handle = open_url(url, headers={"Authorization": auth}, method="GET", validate_certs=self.ssl_context) out_xml = None try: out_xml = handle.read() try: self.last_http_return_code = handle.getcode() self.last_http_return_headers = handle.info() self.last_http_return_url = url except BaseException as err: raise FSMBaseException( msg= "submit_simple_request() failed to get http codes. Error: " + str(err)) except BaseException as err: raise FSMBaseException(msg="submit_simple_request() failed" + str(err)) return out_xml
def handle_simple_request(self): """ Handles the "simple" get request without an XML payload, from end-to-end, including result formatting. :return: dict """ formatted_output_dict = None auth = self.create_auth_header() url = self.create_endpoint_url() output_xml = self.submit_simple_request(auth, url) try: if "<password>" in output_xml: output_xml = re.sub(r'(<password>.*?<\/password>)', '', output_xml) output_xml = re.sub(r'(<suPassword>.*?<\/suPassword>)', '', output_xml) except BaseException as err: pass if output_xml: try: output_json = self._tools.xml2dict(output_xml) formatted_output_dict = self.format_results(output_json, output_xml) except BaseException as err: try: output_json = {"fsm_response": str(output_xml)} output_xml = "<fsm_response>" + str(output_xml + "</fsm_response>") formatted_output_dict = self.format_results(output_json, output_xml) except BaseException as err: raise FSMBaseException(msg="handle_simple_request() couldn't deal with the response. " "Error:" + str(err)) elif not output_xml: output_json = {"status": "OK"} output_xml = "<status>OK</status>" formatted_output_dict = self.format_results(output_json, output_xml) return formatted_output_dict
def submit_simple_payload_request(self, auth, url, payload): """ Submits a simple GET request with an XML payload. :param auth: Authentication header created in create_auth_header() :param url: URL created in create_endpoint_url() :param payload: XML payload in string form :return: xml """ handle = open_url(url, data=payload, method="PUT", validate_certs=self.ssl_context, headers={ "Authorization": auth, "Content-Type": "text/xml", "Content-Length": len(payload), }) out_xml = None try: out_xml = handle.read() try: self.last_http_return_code = handle.getcode() self.last_http_return_headers = handle.info() self.last_http_return_url = url except BaseException as err: raise FSMBaseException( msg="submit_simple_payload_request() couldn't " "get the HTTP codes. Error: " + str(err)) except BaseException as err: error_msg = str(err) if "HTTP Status 500" in error_msg: raise FSMBaseException( msg="submit_simple_payload_request(): " "500 Internal Server Error. In our experience, " "this means the object exists or doesn't. " "If that doesn't work, double check your inputs. " "Perhaps it already exists? " "You should change the mode, most likely. " "HTTP Error: " + str(error_msg)) raise FSMBaseException( msg="submit_simple_payload_request() HTTP Error: " + str(error_msg)) return out_xml
def retrieve_finished_query(self): """ Gets results from a finished report. Formats results for return. :return: dict """ query_id = self.report_query_id self._module.paramgram["uri"] = FSMEndpoints.GET_REPORT_RESULTS + str(query_id) + "/0/1000" url = self.create_endpoint_url() out_xml = [] first_results = self.get_query_results(self.next_http_auth, url) out_xml.append(first_results.decode("utf-8")) try: p = re.compile('totalCount="\d+"') mlist = p.findall(out_xml[0]) mm = mlist[0].replace('"', '') row_count = mm.split("=")[-1] row_count = int(row_count) except BaseException as err: raise FSMBaseException(msg="retrieve_finished_query() couldn't count the rows. " "This suggest a major change in API return format. Error: " + str(err)) if row_count > 1000: pages = int(row_count) / 1000 if pages > 0: for i in range(pages): self._module.paramgram["uri"] = FSMEndpoints.GET_REPORT_RESULTS + str(query_id) \ + "/" + str((i + 1) * 1000) + '/1000' url = self.create_endpoint_url() out_xml_append = self.get_query_results(self.next_http_auth, url) if out_xml_append != '': out_xml.append(out_xml_append.decode("utf-8")) # FORMAT THE RETURN DICTIONARY if row_count > 0: combined_xml_string = self._tools.merge_xml_from_list_to_string(out_xml) raw_output_json = self._tools.xml2dict(combined_xml_string) output_json = self._tools.dump_xml(out_xml) output_csv = self._tools.report_result_to_csv(output_json) formatted_output_dict = self.format_results(output_json, combined_xml_string) formatted_output_dict["csv_results"] = output_csv formatted_output_dict["json_results_raw"] = raw_output_json formatted_output_dict["xml_results_raw"] = combined_xml_string formatted_output_dict["row_count"] = row_count formatted_output_dict["report_rc"] = formatted_output_dict["json_results_raw"]["queryResult"]["@errorCode"] formatted_output_dict["query_id"] = query_id formatted_output_dict["xml_query"] = self.report_xml_source elif row_count == 0: combined_xml_string = out_xml[0] output_json = self._tools.xml2dict(combined_xml_string) formatted_output_dict = self.format_results(output_json, combined_xml_string) formatted_output_dict["csv_results"] = None formatted_output_dict["row_count"] = "0" formatted_output_dict["query_id"] = query_id formatted_output_dict["xml_query"] = self.report_xml_source return formatted_output_dict
def get_query_results(self, auth, url): """ Gets the results of a specific query ID. :param auth: Authentication header created in create_auth_header() :param url: URL created in create_endpoint_url() :return: xml """ headers = {'Content-Type': 'text/xml', 'Authorization': auth} req = urllib2.Request(url, None, headers) out_xml = None try: handle = urllib2.urlopen(req, context=self.ssl_context) out_xml = handle.read() if 'error code="255"' in out_xml: raise FSMBaseException(msg="Query Error.") except BaseException as err: raise FSMBaseException(msg="get_query_results() failed. Error: " + str(err)) return out_xml
def submit_simple_payload_request(self, auth, url, payload): """ Submits a simple GET request with an XML payload. :param auth: Authentication header created in create_auth_header() :param url: URL created in create_endpoint_url() :param payload: XML payload in string form :return: xml """ req = urllib2.Request(url, payload, {"Authorization": auth, "Content-Type": "text/xml", "Content-Length": len(payload), }) req.get_method = lambda: 'PUT' out_xml = None try: opener = urllib2.build_opener(urllib2.HTTPSHandler(debuglevel=False, context=self.ssl_context)) urllib2.install_opener(opener) handle = urllib2.urlopen(req) out_xml = handle.read() try: self.last_http_return_code = handle.getcode() self.last_http_return_headers = handle.info() self.last_http_return_url = url except BaseException as err: raise FSMBaseException(msg="submit_simple_payload_request() couldn't " "get the HTTP codes. Error: " + str(err)) except urllib2.HTTPError as err: error_msg = err.read() if "HTTP Status 500" in error_msg: raise FSMBaseException(msg="submit_simple_payload_request(): " "500 Internal Server Error. In our experience, " "this means the object exists or doesn't. " "If that doesn't work, double check your inputs. " "Perhaps it already exists? " "You should change the mode, most likely. " "HTTP Error: " + str(error_msg)) raise FSMBaseException(msg="submit_simple_payload_request() HTTP Error: " + str(error_msg)) return out_xml
def csv_results_to_file_path(self, csv_results): """ Writes results to a CSV file :param csv_results: csv to write to file """ try: f = open(self.export_csv_to_file_path, "w") f.write(csv_results) f.close() except BaseException as err: raise FSMBaseException(msg="CSV Failed to write to file: " + str(self.export_csv_to_file_path) + "| Error: " + str(err))
def json_results_to_file_path(self, json_results): """ Writes results to a JSON file. Formats the JSON. :param json_results: json to write to file """ try: f = open(self.export_json_to_file_path, "w") f.write(json.dumps(json_results, indent=4, sort_keys=True)) f.close() except BaseException as err: raise FSMBaseException(msg="JSON Failed to write to file: " + str(self.export_json_to_file_path) + "| Error: " + str(err))
def post_report_get_query_id(self): """ Submits report XML for query, and returns the query ID. No return. Writes query_id to self. """ self.next_http_auth = self.create_auth_header() url = self.create_endpoint_url() report_xml = self._tools.prepare_report_xml_query(self._module.paramgram["input_xml"]) query_id = self.submit_report_request(self.next_http_auth, url, report_xml) self.report_query_id = query_id if 'error code="255"' in query_id: raise FSMBaseException(msg="Query Error, debug XML file being sent, it caused an error.")
def xml_results_to_file_path(self, xml_results): """ Writes results to a XML file. Pretty-Prints the XML. :param xml_results: xml to write to file """ try: xml_out = xml.dom.minidom.parseString(xml_results) xml_pretty = xml_out.toprettyxml() f = open(self.export_xml_to_file_path, "w") f.write(xml_pretty) f.close() except BaseException as err: raise FSMBaseException(msg="XML Failed to write to file: " + str(self.export_xml_to_file_path) + "| Error: " + str(err))
def get_file_contents(self, file_path): """ Gets the contents of a file. Commonly used with modules that allow custom XML files. :param file_path: path of file to collect contents :return: string of file contents """ source = None try: f = open(file_path, "r") source = f.read() f.close() self.report_xml_source = source except BaseException as err: FSMBaseException(msg="Failed to get file contents at path: " + str(self.export_json_to_file_path) + "| Error: " + str(err)) return source
def handle_syslog_request(self): """ Handles a syslog request from end-to-end, and reports on the results. :return: dict """ output_dict = {"status": "FAILED", "message": "None"} try: log = SendSyslog(host=self._module.paramgram["syslog_host"], port=self._module.paramgram["network_port"], protocol=self._module.paramgram["network_protocol"], level=self._module.paramgram["syslog_level"], facility=self._module.paramgram["syslog_facility"], ssl_context=self.create_ssl_context(), ) output_dict = log.send(header=self._module.paramgram["syslog_header"], message=self._module.paramgram["syslog_message"]) except BaseException as err: raise FSMBaseException(msg="handle_syslog_request() couldn't send the syslog. Error: " + str(err)) return output_dict
def create_ssl_context(self): """ Creates the SSL context for handling certificates. :return: ssl context object """ ignore_ssl_setting = None ctx = None try: ignore_ssl_setting = self._module.paramgram["ignore_ssl_errors"] except BaseException as err: FSMBaseException( msg="create_ssl_context() failed to ignore ssl setting" + str(err)) if ignore_ssl_setting == "enable": ctx = False else: ctx = True return ctx
def create_ssl_context(self): """ Creates the SSL context for handling certificates. :return: ssl context object """ ignore_ssl_setting = None ctx = None try: ignore_ssl_setting = self._module.paramgram["ignore_ssl_errors"] except BaseException as err: FSMBaseException(msg="create_ssl_context() failed to ignore ssl setting" + str(err)) if ignore_ssl_setting == "enable": ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE else: ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_REQUIRED return ctx
def govern_response(self, module, results, msg=None, good_codes=None, stop_on_fail=None, stop_on_success=None, skipped=None, changed=None, unreachable=None, failed=None, success=None, changed_if_success=None, ansible_facts=None): """ This function will attempt to apply default values to canned responses from FortiSIEM we know of. This saves time, and turns the response in the module into a "one-liner", while still giving us... the flexibility to directly use return_response in modules if we have too. This function saves repeated code. :param module: The Ansible Module CLASS object, used to run fail/exit json :type module: object :param msg: An overridable custom message from the module that called this. :type msg: string :param results: A dictionary object containing an API call results :type results: dict :param good_codes: A list of exit codes considered successful from FortiSIEM :type good_codes: list :param stop_on_fail: If true, stops playbook run when return code is NOT IN good codes (default: true) :type stop_on_fail: boolean :param stop_on_success: If true, stops playbook run when return code is IN good codes (default: false) :type stop_on_success: boolean :param changed: If True, tells Ansible that object was changed (default: false) :type skipped: boolean :param skipped: If True, tells Ansible that object was skipped (default: false) :type skipped: boolean :param unreachable: If True, tells Ansible that object was unreachable (default: false) :type unreachable: boolean :param failed: If True, tells Ansible that execution was a failure. Overrides good_codes. (default: false) :type unreachable: boolean :param success: If True, tells Ansible that execution was a success. Overrides good_codes. (default: false) :type unreachable: boolean :param changed_if_success: If True, defaults to changed if successful if you specify or not" :type changed_if_success: boolean :param ansible_facts: A prepared dictionary of ansible facts from the execution. :type ansible_facts: dict """ if module is None and results is None: raise FSMBaseException( "govern_response() was called without a module and/or results tuple! Fix!" ) # Get the Return code from results try: rc = results["rc"] except BaseException: raise FSMBaseException( "govern_response() was called without the return code at results[rc]" ) # init a few items rc_data = None # Get the default values for the said return code. try: rc_codes = FSM_RC.get('fsm_return_codes') rc_data = rc_codes.get(rc) except BaseException: pass if not rc_data: rc_data = {} # ONLY add to overrides if not none -- This is very important that the keys aren't added at this stage # if they are empty. And there aren't that many, so let's just do a few if then statements. if good_codes is not None: rc_data["good_codes"] = good_codes if stop_on_fail is not None: rc_data["stop_on_fail"] = stop_on_fail if stop_on_success is not None: rc_data["stop_on_success"] = stop_on_success if skipped is not None: rc_data["skipped"] = skipped if changed is not None: rc_data["changed"] = changed if unreachable is not None: rc_data["unreachable"] = unreachable if failed is not None: rc_data["failed"] = failed if success is not None: rc_data["success"] = success if changed_if_success is not None: rc_data["changed_if_success"] = changed_if_success if msg is not None: rc_data["msg"] = msg if ansible_facts is None: rc_data["ansible_facts"] = {} else: rc_data["ansible_facts"] = ansible_facts # PROCESS OUTPUTS TO FILES if self.export_json_to_file_path: try: if results["json_results"]: self.json_results_to_file_path(results["json_results"]) except BaseException as err: raise FSMBaseException( msg="Writing JSON results to file failed. Error: " + str(err)) if self.export_xml_to_file_path: try: if results["xml_results"]: self.xml_results_to_file_path(results["xml_results"]) except BaseException as err: raise FSMBaseException( msg="Writing XML results to file failed. Error: " + str(err)) if self.export_csv_to_file_path: try: if results["csv_results"]: self.csv_results_to_file_path(results["csv_results"]) except BaseException as err: raise FSMBaseException( msg="Writing CSV results to file failed. Error: " + str(err)) return self.return_response( module=module, results=results, msg=rc_data.get("msg", "NULL"), good_codes=rc_data.get("good_codes", (200, )), stop_on_fail=rc_data.get("stop_on_fail", True), stop_on_success=rc_data.get("stop_on_success", False), skipped=rc_data.get("skipped", False), changed=rc_data.get("changed", False), changed_if_success=rc_data.get("changed_if_success", False), unreachable=rc_data.get("unreachable", False), failed=rc_data.get("failed", False), success=rc_data.get("success", False), ansible_facts=rc_data.get("ansible_facts", dict()), export_json_to_screen=self.export_json_to_screen)
def return_response(module, results, msg="NULL", good_codes=(200, ), stop_on_fail=True, stop_on_success=False, skipped=False, changed=False, unreachable=False, failed=False, success=False, changed_if_success=True, ansible_facts=(), export_json_to_screen=None): """ This function controls the logout and error reporting after an method or function runs. The exit_json for ansible comes from logic within this function. If this function returns just the msg, it means to continue execution on the playbook. It is called from the ansible module, or from the self.govern_response function. :param module: The Ansible Module CLASS object, used to run fail/exit json :type module: object :param msg: An overridable custom message from the module that called this. :type msg: string :param results: A dictionary object containing an API call results :type results: dict :param good_codes: A list of exit codes considered successful from FortiSIEM :type good_codes: list :param stop_on_fail: If true, stops playbook run when return code is NOT IN good codes (default: true) :type stop_on_fail: boolean :param stop_on_success: If true, stops playbook run when return code is IN good codes (default: false) :type stop_on_success: boolean :param changed: If True, tells Ansible that object was changed (default: false) :type skipped: boolean :param skipped: If True, tells Ansible that object was skipped (default: false) :type skipped: boolean :param unreachable: If True, tells Ansible that object was unreachable (default: false) :type unreachable: boolean :param failed: If True, tells Ansible that execution was a failure. Overrides good_codes. (default: false) :type unreachable: boolean :param success: If True, tells Ansible that execution was a success. Overrides good_codes. (default: false) :type unreachable: boolean :param changed_if_success: If True, defaults to changed if successful if you specify or not" :type changed_if_success: boolean :param ansible_facts: A prepared dictionary of ansible facts from the execution. :type ansible_facts: dict :param export_json_to_screen: If enabled/true, we will export the json results to screen. :type export_json_to_screen: bool :return: A string object that contains an error message :rtype: str """ return_results = None # VALIDATION ERROR if (len(results) == 0) or (failed and success) or (changed and unreachable): module.exit_json( msg= "Handle_response was called with no results, or conflicting failed/success or " "changed/unreachable parameters. Fix the exit code on module. " "Generic Failure", failed=True) # IDENTIFY SUCCESS/FAIL IF NOT DEFINED if not failed and not success: if len(results) > 0: if results["rc"] not in good_codes: failed = True elif results["rc"] in good_codes: success = True if len(results) > 0: # IF NO MESSAGE WAS SUPPLIED, GET IT FROM THE RESULTS, IF THAT DOESN'T WORK, THEN WRITE AN ERROR MESSAGE if msg == "NULL": try: msg = results["http_metadata"]['status']['message'] except BaseException: msg = "No status message returned at results[http_metadata][status][message], " \ "and none supplied to msg parameter for handle_response." raise FSMBaseException(msg) # PROCESS PRINT TO SCREEN OPTION if export_json_to_screen == "enable": return_results = results["json_results"] elif export_json_to_screen == "disable": return_results = "Results printing to screen is disabled " \ "from export_json_to_screen = disable in playbook. We also remove from " \ "Ansible_facts so if you need that data pipeline, re-enable export json to screen" del ansible_facts["response"] if failed: # BECAUSE SKIPPED/FAILED WILL OFTEN OCCUR ON CODES THAT DON'T GET INCLUDED, THEY ARE CONSIDERED FAILURES # HOWEVER, THEY ARE MUTUALLY EXCLUSIVE, SO IF IT IS MARKED SKIPPED OR UNREACHABLE BY THE MODULE LOGIC # THEN REMOVE THE FAILED FLAG SO IT DOESN'T OVERRIDE THE DESIRED STATUS OF SKIPPED OR UNREACHABLE. if failed and skipped: failed = False if failed and unreachable: failed = False if stop_on_fail: module.exit_json(msg=msg, failed=failed, changed=changed, unreachable=unreachable, skipped=skipped, ansible_module_results=return_results, ansible_facts=ansible_facts, invocation={ "module_args": ansible_facts["ansible_params"] }) elif success: if changed_if_success: changed = True success = False if stop_on_success: module.exit_json(msg=msg, success=success, changed=changed, unreachable=unreachable, skipped=skipped, results=return_results, ansible_module_results=ansible_facts, invocation={ "module_args": ansible_facts["ansible_params"] }) return msg
def main(): argument_spec = dict( host=dict(required=True, type="str"), username=dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])), password=dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True), ignore_ssl_errors=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_screen=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_file_path=dict(required=False, type="str"), export_xml_to_file_path=dict(required=False, type="str"), export_csv_to_file_path=dict(required=False, type="str"), mode=dict(required=False, type="str", choices=["short_all", "ip_range", "detailed_single", "update"], default="short_all"), ip_range=dict(required=False, type="str"), ip=dict(required=False, type="str"), update_xml_file=dict(required=False, type="str") ) required_if = [ ['mode', 'ip_range', ['ip_range']], ['mode', 'detailed_single', ['ip']], ['mode', 'update', ['update_xml_file']], ] module = AnsibleModule(argument_spec, supports_check_mode=False, required_if=required_if) paramgram = { "host": module.params["host"], "username": module.params["username"], "password": module.params["password"], "export_json_to_screen": module.params["export_json_to_screen"], "export_json_to_file_path": module.params["export_json_to_file_path"], "export_xml_to_file_path": module.params["export_xml_to_file_path"], "export_csv_to_file_path": module.params["export_csv_to_file_path"], "ignore_ssl_errors": module.params["ignore_ssl_errors"], "ip_range": module.params["ip_range"], "ip": module.params["ip"], "update_xml_file": module.params["update_xml_file"], "mode": module.params["mode"], "uri": None } # DETERMINE THE MODE AND ADD THE CORRECT DATA TO THE PARAMGRAM if paramgram["mode"] in ["short_all", "ip_range", "detailed_single"]: paramgram["uri"] = FSMEndpoints.GET_MONITORED_DEVICES elif paramgram["mode"] == "update": paramgram["uri"] = FSMEndpoints.UPDATE_DEVICE_MONITORING if paramgram["uri"] is None: raise FSMBaseException("Base URI couldn't be constructed. Check options.") module.paramgram = paramgram # TRY TO INIT THE CONNECTION SOCKET PATH AND FortiManagerHandler OBJECT AND TOOLS fsm = None results = DEFAULT_EXIT_MSG try: fsm = FortiSIEMHandler(module) except BaseException as err: raise FSMBaseException("Couldn't load FortiSIEM Handler from mod_utils. Error: " + str(err)) # RUN IF MODE = SHORT ALL if paramgram["mode"] == "short_all": try: results = fsm.handle_simple_request() except BaseException as err: raise FSMBaseException(err) # ADD A SUMMARY TO THE RESULTS try: results = fsm._tools.get_monitors_summary_for_short_all(results) except BaseException as err: raise FSMBaseException(err) # RUN IF MODE = IP RANGE if paramgram["mode"] == "ip_range": try: results = fsm.handle_simple_request() except BaseException as err: raise FSMBaseException(err) # FOR EACH IP ADDRESS IN RANGE, RUN THE METHOD get_monitors_info_for_specific_ip try: ipr = str(paramgram["ip_range"]).split("-") ipr_list = FSMCommon.get_ip_list_from_range(ipr[0], ipr[1]) except BaseException as err: raise FSMBaseException(err) try: results_append_list = [] for ip in ipr_list: append = fsm._tools.get_monitors_info_for_specific_ip(results, str(ip)) if len(append) > 0: results_append_list.append(append) results["json_results"]["summary"] = results_append_list # REMOVE THE FULL QUERY TO CLEAN UP THE RESULTS del results["json_results"]["monitoredDevices"] except BaseException as err: raise FSMBaseException(err) # RUN IF MODE = SINGLE IP ADDRESS if paramgram["mode"] == "detailed_single": try: results = fsm.handle_simple_request() except BaseException as err: raise FSMBaseException(err) results_append_list = [] append = fsm._tools.get_monitors_info_for_specific_ip(results, paramgram["ip"]) if len(append) > 0: results_append_list.append(append) results["json_results"]["summary"] = results_append_list # REMOVE THE FULL QUERY TO CLEAN UP THE RESULTS del results["json_results"]["monitoredDevices"] if isinstance(results["json_results"]["summary"], dict): # CONVERT SUMMARY DICT INTO XML results["xml_results"] = fsm._tools.dict2xml(results["json_results"]["summary"]) elif isinstance(results["json_results"]["summary"], list): temp_xml_dict = {"results": results["xml_results"]} results["xml_results"] = fsm._tools.dict2xml(temp_xml_dict) # RUN IF MODE = UPDATE if paramgram["mode"] == "update": try: paramgram["input_xml"] = fsm.get_file_contents(paramgram["update_xml_file"]) paramgram["input_xml"] = re.sub(r'\n', '', paramgram["input_xml"]) except BaseException as err: raise FSMBaseException(msg="Couldn't find or load update_xml_file path. Double check. Error: " + str(err)) # REFRESH PARAMGRAM module.paramgram = paramgram try: results = fsm.handle_simple_payload_request(str(paramgram["input_xml"])) except BaseException as err: raise FSMBaseException(err) # CONVERT SUMMARY DICT INTO XML results["xml_results"] = fsm._tools.dict2xml(results["json_results"]) # EXIT USING GOVERN_RESPONSE() fsm.govern_response(module=module, results=results, changed=False, good_codes=[200, 204], ansible_facts=fsm.construct_ansible_facts(results["json_results"], module.params, paramgram)) # elif paramgram["mode"] == "update": return module.exit_json(msg=results)
def main(): argument_spec = dict( host=dict(required=True, type="str"), username=dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])), password=dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True), ignore_ssl_errors=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_screen=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_file_path=dict(required=False, type="str"), export_xml_to_file_path=dict(required=False, type="str"), export_csv_to_file_path=dict(required=False, type="str"), mode=dict(required=False, type="str", choices=["short_all", "ip_range", "detailed_single"], default="short_all"), ip_range=dict(required=False, type="str"), ip=dict(required=False, type="str")) required_if = [ ['mode', 'ip_range', ['ip_range']], ['mode', 'detailed_single', ['ip']], ] module = AnsibleModule(argument_spec, supports_check_mode=False, required_if=required_if) paramgram = { "host": module.params["host"], "username": module.params["username"], "password": module.params["password"], "export_json_to_screen": module.params["export_json_to_screen"], "export_json_to_file_path": module.params["export_json_to_file_path"], "export_xml_to_file_path": module.params["export_xml_to_file_path"], "export_csv_to_file_path": module.params["export_csv_to_file_path"], "ignore_ssl_errors": module.params["ignore_ssl_errors"], "mode": module.params["mode"], "uri": None } # DETERMINE THE MODE AND ADD THE CORRECT DATA TO THE PARAMGRAM if paramgram["mode"] == "short_all": paramgram["uri"] = FSMEndpoints.GET_CMDB_SHORT elif paramgram["mode"] == "ip_range": paramgram[ "uri"] = FSMEndpoints.GET_CMDB_IPRANGE + module.params["ip_range"] elif paramgram["mode"] == "detailed_single": paramgram[ "uri"] = FSMEndpoints.GET_CMDB_DETAILED_SINGLE + module.params[ "ip"] + "&loadDepend=true" if paramgram["uri"] is None: raise FSMBaseException( "Base URI couldn't be constructed. Check options.") module.paramgram = paramgram # TRY TO INIT THE CONNECTION SOCKET PATH AND FortiManagerHandler OBJECT AND TOOLS fsm = None results = DEFAULT_EXIT_MSG try: fsm = FortiSIEMHandler(module) except BaseException as err: raise FSMBaseException( "Couldn't load FortiSIEM Handler from mod_utils. Error: " + str(err)) # EXECUTE THE MODULE OPERATION try: results = fsm.handle_simple_request() except BaseException as err: raise FSMBaseException(err) # EXIT USING GOVERN_RESPONSE() fsm.govern_response(module=module, results=results, changed=False, ansible_facts=fsm.construct_ansible_facts( results["json_results"], module.params, paramgram)) return module.exit_json(msg=results)
def main(): argument_spec = dict( host=dict(required=True, type="str"), username=dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])), password=dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True), ignore_ssl_errors=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_screen=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_file_path=dict(required=False, type="str"), export_xml_to_file_path=dict(required=False, type="str"), export_csv_to_file_path=dict(required=False, type="str"), input_xml_file=dict(required=False, type="str"), mode=dict(required=False, type="str", default="add", choices=["add", "delete"]), name=dict(required=False, type="str"), description=dict(required=False, type="str"), devices=dict(required=False, type="str"), groups=dict(required=False, type="str"), fire_incidents=dict(required=False, type="bool"), time_zone_id=dict(required=False, type="str"), start_hour=dict(required=False, type="str"), start_min=dict(required=False, type="str"), duration=dict(required=False, type="str"), time_zone=dict(required=False, type="str"), start_date=dict(required=False, type="str"), end_date=dict(required=False, type="str"), end_date_open=dict(required=False, type="bool"), ) module = AnsibleModule(argument_spec, supports_check_mode=False) paramgram = { "host": module.params["host"], "username": module.params["username"], "password": module.params["password"], "export_json_to_screen": module.params["export_json_to_screen"], "export_json_to_file_path": module.params["export_json_to_file_path"], "export_xml_to_file_path": module.params["export_xml_to_file_path"], "export_csv_to_file_path": module.params["export_csv_to_file_path"], "ignore_ssl_errors": module.params["ignore_ssl_errors"], "input_xml_file": module.params["input_xml_file"], "mode": module.params["mode"], "name": module.params["name"], "description": module.params["description"], "devices": module.params["devices"], "groups": module.params["groups"], "fire_incidents": module.params["fire_incidents"], "time_zone_id": module.params["time_zone_id"], "start_hour": module.params["start_hour"], "start_min": module.params["start_min"], "duration": module.params["duration"], "time_zone": module.params["time_zone"], "start_date": module.params["start_date"], "end_date": module.params["end_date"], "end_date_open": module.params["end_date_open"], "uri": None, "input_xml": None, } if not paramgram["end_date_open"]: paramgram["end_date_open"] = False module.paramgram = paramgram # TRY TO INIT THE CONNECTION SOCKET PATH AND FortiManagerHandler OBJECT AND TOOLS fsm = None results = DEFAULT_EXIT_MSG try: fsm = FortiSIEMHandler(module) except BaseException as err: raise FSMBaseException( "Couldn't load FortiSIEM Handler from mod_utils. Error: " + str(err)) # EXECUTE THE MODULE OPERATION if paramgram["mode"] == "add": paramgram["uri"] = FSMEndpoints.SET_MAINTENANCE try: if paramgram["input_xml_file"]: paramgram["input_xml"] = fsm.get_file_contents( paramgram["input_xml_file"]) else: paramgram["input_xml"] = fsm._xml.create_maint_payload() results = fsm.handle_simple_payload_request(paramgram["input_xml"]) except BaseException as err: raise FSMBaseException(err) elif paramgram["mode"] == "delete": paramgram["uri"] = FSMEndpoints.DEL_MAINTENANCE try: if paramgram["input_xml_file"]: paramgram["input_xml"] = fsm.get_file_contents( paramgram["input_xml_file"]) else: paramgram["input_xml"] = fsm._xml.create_maint_payload() results = fsm.handle_simple_payload_request(paramgram["input_xml"]) except BaseException as err: raise FSMBaseException(err) # EXIT USING GOVERN_RESPONSE() fsm.govern_response(module=module, results=results, changed=False, good_codes=[ 200, 204, ], ansible_facts=fsm.construct_ansible_facts( results["json_results"], module.params, paramgram)) return module.exit_json(msg=results)
def main(): argument_spec = dict( host=dict(required=True, type="str"), username=dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])), password=dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True), ignore_ssl_errors=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_screen=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_file_path=dict(required=False, type="str"), export_xml_to_file_path=dict(required=False, type="str"), export_csv_to_file_path=dict(required=False, type="str"), mode=dict(required=False, type="str", choices=["get", "update", "add"], default="get"), org_name=dict(required=False, type="str"), org_display_name=dict(required=False, type="str"), org_description=dict(required=False, type="str"), org_admin_username=dict(required=False, type="str"), org_admin_password=dict(required=False, type="str", no_log=True), org_admin_email=dict(required=False, type="str"), org_eps=dict(required=False, type="str"), org_max_devices=dict(required=False, type="int", default=0), org_include_ip_range=dict(required=False, type="str"), org_exclude_ip_range=dict(required=False, type="str"), org_collectors=dict(required=False, type="list"), org_collector_name=dict(required=False, type="str"), org_collector_eps=dict(required=False, type="str"), ) required_if = [ [ 'mode', 'add', [ 'org_admin_username', 'org_admin_password', 'org_admin_email', 'org_name', 'org_display_name', 'org_description' ] ], ['mode', 'update', ['org_name']], ] module = AnsibleModule(argument_spec, supports_check_mode=False, required_if=required_if) paramgram = { "host": module.params["host"], "username": module.params["username"], "password": module.params["password"], "export_json_to_screen": module.params["export_json_to_screen"], "export_json_to_file_path": module.params["export_json_to_file_path"], "export_xml_to_file_path": module.params["export_xml_to_file_path"], "export_csv_to_file_path": module.params["export_csv_to_file_path"], "ignore_ssl_errors": module.params["ignore_ssl_errors"], "mode": module.params["mode"], "uri": None, "input_xml": None, "org_name": module.params["org_name"], "org_display_name": module.params["org_display_name"], "org_description": module.params["org_description"], "org_admin_username": module.params["org_admin_username"], "org_admin_password": module.params["org_admin_password"], "org_admin_email": module.params["org_admin_email"], "org_eps": module.params["org_eps"], "org_max_devices": module.params["org_max_devices"], "org_include_ip_range": module.params["org_include_ip_range"], "org_exclude_ip_range": module.params["org_exclude_ip_range"], "org_collectors": module.params["org_collectors"], "org_collector_name": module.params["org_collector_name"], "org_collector_eps": module.params["org_collector_eps"], } # DETERMINE THE MODE AND ADD THE CORRECT DATA TO THE PARAMGRAM if paramgram["mode"] == "get": paramgram["uri"] = FSMEndpoints.GET_ORGS elif paramgram["mode"] == "update": paramgram["uri"] = FSMEndpoints.UPDATE_ORGS elif paramgram["mode"] == "add": paramgram["uri"] = FSMEndpoints.ADD_ORGS if paramgram["uri"] is None: raise FSMBaseException( "Base URI couldn't be constructed. Check options.") module.paramgram = paramgram # TRY TO INIT THE CONNECTION SOCKET PATH AND FortiManagerHandler OBJECT AND TOOLS fsm = None results = DEFAULT_EXIT_MSG try: fsm = FortiSIEMHandler(module) except BaseException as err: raise FSMBaseException( "Couldn't load FortiSIEM Handler from mod_utils. Error: " + str(err)) # EXECUTE THE MODULE OPERATION if paramgram["mode"] in ['get']: try: results = fsm.handle_simple_request() except BaseException as err: raise FSMBaseException(err) elif paramgram["mode"] in ['update', 'add']: try: # CREATE PAYLOAD paramgram["input_xml"] = fsm._xml.create_org_payload() results = fsm.handle_simple_payload_request( payload=paramgram["input_xml"]) except BaseException as err: raise FSMBaseException(err) # EXIT USING GOVERN_RESPONSE() fsm.govern_response(module=module, results=results, changed=False, good_codes=[200, 204], ansible_facts=fsm.construct_ansible_facts( results["json_results"], module.params, paramgram)) return module.exit_json(msg=results)
def main(): argument_spec = dict( host=dict(required=True, type="str"), username=dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])), password=dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True), ignore_ssl_errors=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_screen=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_file_path=dict(required=False, type="str"), export_xml_to_file_path=dict(required=False, type="str"), export_csv_to_file_path=dict(required=False, type="str"), ip_to_verify=dict(required=False, type="str"), ip_list_to_verify=dict(required=False, type="list"), ip_list_file_path=dict(required=False, type="str"), append_results_to_file=dict(required=False, type="str")) mutually_exclusive = [ 'ip_to_verify', 'ip_list_to_verify', 'ip_list_file_path' ] module = AnsibleModule( argument_spec, supports_check_mode=False, mutually_exclusive=mutually_exclusive, ) paramgram = { "host": module.params["host"], "username": module.params["username"], "password": module.params["password"], "export_json_to_screen": module.params["export_json_to_screen"], "export_json_to_file_path": module.params["export_json_to_file_path"], "export_xml_to_file_path": module.params["export_xml_to_file_path"], "export_csv_to_file_path": module.params["export_csv_to_file_path"], "ignore_ssl_errors": module.params["ignore_ssl_errors"], "ip_to_verify": module.params["ip_to_verify"], "ip_list_to_verify": module.params["ip_list_to_verify"], "ip_list_file_path": module.params["ip_list_file_path"], "append_results_to_file": module.params["append_results_to_file"], "uri": FSMEndpoints.PUT_SUBMIT_REPORT, "input_xml": None, "queryId": None } module.paramgram = paramgram # TRY TO INIT THE CONNECTION SOCKET PATH AND FortiManagerHandler OBJECT AND TOOLS fsm = None results = DEFAULT_EXIT_MSG results_list = list() try: fsm = FortiSIEMHandler(module) except BaseException as err: raise FSMBaseException( "Couldn't load FortiSIEM Handler from mod_utils. Error: " + str(err)) if paramgram["ip_to_verify"]: results = fsm_verify_single_device(fsm, paramgram) if paramgram["ip_list_file_path"] or paramgram["ip_list_to_verify"]: if paramgram["ip_list_to_verify"]: if isinstance(paramgram["ip_list_to_verify"], list): for ip in paramgram["ip_list_to_verify"]: if ip != "" and ip is not None: paramgram["ip_to_verify"] = str(ip) results_add = fsm_verify_single_device(fsm, paramgram) results_list.append(results_add) if paramgram["ip_list_file_path"]: results_list = list() ip_list = fsm.get_file_contents(paramgram["ip_list_file_path"]) parsed_ip_list = ip_list.split("\n") for ip in parsed_ip_list: if ip != "" and ip is not None: paramgram["ip_to_verify"] = str(ip) results_add = fsm_verify_single_device(fsm, paramgram) results_list.append(results_add) results = { "rc": 200, "json_results": { "all_results": results_list }, "xml_results": { "all_results": results_list }, } # WRITE TO THE FILE IF SPECIFIED try: if paramgram["append_results_to_file"]: try: if results["json_results"]["all_results"]: for result in results["json_results"]["all_results"]: fsm._tools.append_file_with_device_results( result, paramgram["append_results_to_file"]) except BaseException: try: fsm._tools.append_file_with_device_results( results, paramgram["append_results_to_file"]) except BaseException as err: raise FSMBaseException( msg= "An issue happened writing the results to a file. Error: " + str(err)) except BaseException as err: raise FSMBaseException( msg="An issue happened writing the results to a file. Error: " + str(err)) # EXIT USING GOVERN_RESPONSE() fsm.govern_response(module=module, results=results, changed=False, ansible_facts=fsm.construct_ansible_facts( results["json_results"], module.params, paramgram)) return module.exit_json(msg=results)
def main(): argument_spec = dict( syslog_host=dict(required=True, type="str"), ignore_ssl_errors=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), network_protocol=dict(required=False, type="str", default="udp", choices=["udp", "tcp", "tcp-tls1.2"]), network_port=dict(required=False, type="int", default=0), syslog_message=dict(required=False, type="str"), syslog_header=dict(required=False, type="str", default=None), syslog_facility=dict(required=False, type="str", default="USER", choices=['KERN', 'USER', 'MAIL', 'DAEMON', 'AUTH', 'SYSLOG', 'LPR', 'NEWS', 'UUCP', 'CRON', 'AUTHPRIV', 'FTP', 'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3', 'LOCAL4', 'LOCAL5', 'LOCAL6', 'LOCAL7']), syslog_level=dict(required=False, type="str", default="INFO", choices=['EMERG', 'ALERT', 'CRIT', 'ERR', 'WARNING', 'NOTICE', 'INFO', 'DEBUG']), ) module = AnsibleModule(argument_spec, supports_check_mode=False) paramgram = { "syslog_host": module.params["syslog_host"], "ignore_ssl_errors": module.params["ignore_ssl_errors"], "network_protocol": module.params["network_protocol"], "network_port": module.params["network_port"], "syslog_message": module.params["syslog_message"], "syslog_header": module.params["syslog_header"], "syslog_facility": module.params["syslog_facility"], "syslog_level": module.params["syslog_level"], } # SET THE APPROPRIATE PORT IF NOT SUPPLIED if paramgram["network_port"] == 0: if paramgram["network_protocol"] == "udp": paramgram["network_port"] = 514 if paramgram["network_protocol"] == "tcp": paramgram["network_port"] = 1470 if paramgram["network_protocol"] == "tcp-tls1.2": paramgram["network_port"] = 6514 # GET THE PROPER VALUES FROM FACILITY AND LEVELS try: facility_search = "SyslogFacility." + str(paramgram["syslog_facility"].upper()) paramgram["syslog_facility"] = eval(facility_search) except BaseException as err: raise FSMBaseException(msg="An error occured converted Syslog Facility to an integer. Error: " + str(err)) try: level_search = "SyslogLevel." + str(paramgram["syslog_level"].upper()) paramgram["syslog_level"] = eval(level_search) except BaseException as err: raise FSMBaseException(msg="An error occured converted Syslog Facility to an integer. Error: " + str(err)) module.paramgram = paramgram # TRY TO INIT THE CONNECTION SOCKET PATH AND FortiManagerHandler OBJECT AND TOOLS fsm = None try: fsm = FortiSIEMHandler(module) except BaseException as err: raise FSMBaseException("Couldn't load FortiSIEM Handler from mod_utils. Error: " + str(err)) if not paramgram["syslog_header"]: paramgram["syslog_header"] = str(fsm._tools.get_current_datetime() + " ansible_module:fsm_send_syslog") module.paramgram = paramgram # EXECUTE THE MODULE OPERATION results = DEFAULT_EXIT_MSG try: results = fsm.handle_syslog_request() except BaseException as err: raise FSMBaseException(err) return module.exit_json(msg=str(results["message"]), results=str(results["status"]))
def main(): argument_spec = dict( host=dict(required=True, type="str"), username=dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])), password=dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True), ignore_ssl_errors=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_screen=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_file_path=dict(required=False, type="str"), export_xml_to_file_path=dict(required=False, type="str"), export_csv_to_file_path=dict(required=False, type="str"), mode=dict(required=False, type="str", choices=["add", "update", "get"], default="get"), ip_range=dict(required=False, type="str"), access_id=dict(required=False, type="str"), input_xml_file=dict(required=False, type="str"), access_protocol=dict(required=False, type="str", choices=['ftp', 'ftp_over_ssl', 'imap', 'imap_over_ssl', 'jdbc', 'jmx', 'kafka_api', 'pop3', 'pop3_over_ssl', 'smtp', 'smtp_over_ssl', 'smtp_over_tls', 'ssh', 'telnet', 'vm_sdk']), friendly_name=dict(required=False, type="str"), description=dict(required=False, type="str"), pull_interval=dict(required=False, type="str", default="5"), cred_username=dict(required=False, type="str"), cred_password=dict(required=False, type="str", no_log=True), super_password=dict(required=False, type="str", no_log=True), port=dict(required=False, type="str"), ) module = AnsibleModule(argument_spec, supports_check_mode=False, ) paramgram = { "host": module.params["host"], "username": module.params["username"], "password": module.params["password"], "export_json_to_screen": module.params["export_json_to_screen"], "export_json_to_file_path": module.params["export_json_to_file_path"], "export_xml_to_file_path": module.params["export_xml_to_file_path"], "export_csv_to_file_path": module.params["export_csv_to_file_path"], "ignore_ssl_errors": module.params["ignore_ssl_errors"], "mode": module.params["mode"], "uri": None, "input_xml": None, "ip_range": module.params["ip_range"], "access_id": module.params["access_id"], "password_type": "Manual", "input_xml_file": module.params["input_xml_file"], "access_protocol": module.params["access_protocol"], "friendly_name": module.params["friendly_name"], "description": module.params["description"], "pull_interval": module.params["pull_interval"], "cred_username": module.params["cred_username"], "cred_password": module.params["cred_password"], "super_password": module.params["super_password"], "port": module.params["port"], } # DETERMINE THE MODE AND ADD THE CORRECT DATA TO THE PARAMGRAM if paramgram["mode"] in ["add", "update"]: paramgram["uri"] = FSMEndpoints.SET_CREDS elif paramgram["mode"] == "get": paramgram["uri"] = FSMEndpoints.GET_CREDS if paramgram["uri"] is None: raise FSMBaseException("Base URI couldn't be constructed. Check options.") if not paramgram["port"]: if paramgram["access_protocol"] == "ftp": paramgram["port"] = "21" if paramgram["access_protocol"] == "ftp_over_ssl": paramgram["port"] = "990" if paramgram["access_protocol"] == "imap": paramgram["port"] = "143" if paramgram["access_protocol"] == "imap_over_ssl": paramgram["port"] = "993" if paramgram["access_protocol"] == "jdbc": paramgram["port"] = "1433" if paramgram["access_protocol"] == "jmx": paramgram["port"] = "0" if paramgram["access_protocol"] == "pop3": paramgram["port"] = "110" if paramgram["access_protocol"] == "pop3_over_ssl": paramgram["port"] = "995" if paramgram["access_protocol"] == "smtp": paramgram["port"] = "25" if paramgram["access_protocol"] == "smtp_over_ssl": paramgram["port"] = "465" if paramgram["access_protocol"] == "smtp_over_tls": paramgram["port"] = "465" if paramgram["access_protocol"] == "ssh": paramgram["port"] = "22" if paramgram["access_protocol"] == "telnet": paramgram["port"] = "23" if paramgram["access_protocol"] == "vm_sdk": paramgram["port"] = None module.paramgram = paramgram # TRY TO INIT THE CONNECTION SOCKET PATH AND FortiManagerHandler OBJECT AND TOOLS fsm = None results = DEFAULT_EXIT_MSG try: fsm = FortiSIEMHandler(module) except BaseException as err: raise FSMBaseException("Couldn't load FortiSIEM Handler from mod_utils. Error: " + str(err)) # EXECUTE THE MODULE OPERATION if paramgram["mode"] in ["add", "update"]: if paramgram["input_xml_file"]: paramgram["input_xml"] = fsm.get_file_contents(paramgram["input_xml_file"]) try: results = fsm.handle_simple_payload_request(paramgram["input_xml"]) except BaseException as err: raise FSMBaseException(err) else: paramgram["input_xml"] = fsm._xml.create_credential_payload() try: results = fsm.handle_simple_payload_request(paramgram["input_xml"]) except BaseException as err: raise FSMBaseException(err) elif paramgram["mode"] == "get": try: results = fsm.handle_simple_request() except BaseException as err: raise FSMBaseException(err) # EXIT USING GOVERN_RESPONSE() fsm.govern_response(module=module, results=results, changed=False, ansible_facts=fsm.construct_ansible_facts(results["json_results"], module.params, paramgram)) return module.exit_json(msg=results)
def main(): argument_spec = dict( host=dict(required=True, type="str"), username=dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])), password=dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True), ignore_ssl_errors=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_screen=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_file_path=dict(required=False, type="str"), export_xml_to_file_path=dict(required=False, type="str"), export_csv_to_file_path=dict(required=False, type="str"), report_name=dict(required=False, type="str"), report_string=dict(required=False, type="str"), report_file_path=dict(required=False, type="str"), report_relative_mins=dict(required=False, type="int"), report_absolute_begin_date=dict(required=False, type="str"), report_absolute_begin_time=dict(required=False, type="str"), report_absolute_end_date=dict(required=False, type="str"), report_absolute_end_time=dict(required=False, type="str"), ) mututally_exclusive = [ ['report_name', 'report_string', 'report_file_pat'], ['report_relative_mins', 'report_absolute_begin_date'], ['report_relative_mins', 'report_absolute_begin_time'], ['report_relative_mins', 'report_absolute_end_date'], ['report_relative_mins', 'report_absolute_end_time'], ] module = AnsibleModule(argument_spec, supports_check_mode=False, mutually_exclusive=mututally_exclusive) paramgram = { "host": module.params["host"], "username": module.params["username"], "password": module.params["password"], "export_json_to_screen": module.params["export_json_to_screen"], "export_json_to_file_path": module.params["export_json_to_file_path"], "export_xml_to_file_path": module.params["export_xml_to_file_path"], "export_csv_to_file_path": module.params["export_csv_to_file_path"], "ignore_ssl_errors": module.params["ignore_ssl_errors"], "report_name": module.params["report_name"], "report_string": module.params["report_string"], "report_file_path": module.params["report_file_path"], "report_relative_mins": module.params["report_relative_mins"], "report_absolute_begin_date": module.params["report_absolute_begin_date"], "report_absolute_begin_time": module.params["report_absolute_begin_time"], "report_absolute_end_date": module.params["report_absolute_end_date"], "report_absolute_end_time": module.params["report_absolute_end_time"], "uri": FSMEndpoints.PUT_SUBMIT_REPORT, "input_xml": None, "queryId": None } module.paramgram = paramgram # TRY TO INIT THE CONNECTION SOCKET PATH AND FortiManagerHandler OBJECT AND TOOLS fsm = None results = DEFAULT_EXIT_MSG try: fsm = FortiSIEMHandler(module) except BaseException as err: raise FSMBaseException( "Couldn't load FortiSIEM Handler from mod_utils. Error: " + str(err)) if paramgram["report_string"]: paramgram["input_xml"] = paramgram["report_string"] if paramgram["report_file_path"]: paramgram["input_xml"] = fsm.get_file_contents( paramgram["report_file_path"]) # IF REPORT TIME PARAMETERS HAVE BEEN SET, THEN PROCESS THOSE, AND EDIT THE REPORT XML if paramgram["report_relative_mins"]: new_xml = fsm.replace_fsm_report_timestamp_relative() paramgram["input_xml"] = new_xml elif paramgram["report_absolute_begin_date"] and paramgram["report_absolute_begin_time"] \ and paramgram["report_absolute_end_date"] and paramgram["report_absolute_end_time"]: new_xml = fsm.replace_fsm_report_timestamp_absolute() paramgram["input_xml"] = new_xml # CHECK IF INPUT XML IS ACTUALLY VALID XML try: fsm._tools.validate_xml(paramgram["input_xml"]) except BaseException as err: raise FSMBaseException("XML Report Provided was unable to be parsed. " "Please double check source XML. Error: " + str(err)) # EXECUTE MODULE OPERATION try: results = fsm.handle_report_submission() except BaseException as err: raise FSMBaseException(err) # EXIT USING GOVERN_RESPONSE() fsm.govern_response(module=module, results=results, changed=False, ansible_facts=fsm.construct_ansible_facts( results["json_results"], module.params, paramgram)) return module.exit_json(msg=results)
def main(): argument_spec = dict( host=dict(required=True, type="str"), username=dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])), password=dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True), ignore_ssl_errors=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_screen=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_file_path=dict(required=False, type="str"), export_xml_to_file_path=dict(required=False, type="str"), export_csv_to_file_path=dict(required=False, type="str"), mode=dict(required=False, type="str", choices=["get", "set", "update", "delete", "add"], default="get"), uri=dict(required=True, type="str"), payload_file=dict(required=False, type="str", default=None) ) module = AnsibleModule(argument_spec, supports_check_mode=False, ) paramgram = { "host": module.params["host"], "username": module.params["username"], "password": module.params["password"], "export_json_to_screen": module.params["export_json_to_screen"], "export_json_to_file_path": module.params["export_json_to_file_path"], "export_xml_to_file_path": module.params["export_xml_to_file_path"], "export_csv_to_file_path": module.params["export_csv_to_file_path"], "ignore_ssl_errors": module.params["ignore_ssl_errors"], "mode": module.params["mode"], "uri": module.params["uri"], "payload_file": module.params["payload_file"], "input_xml": None } module.paramgram = paramgram # TRY TO INIT THE CONNECTION SOCKET PATH AND FortiManagerHandler OBJECT AND TOOLS fsm = None results = DEFAULT_EXIT_MSG try: fsm = FortiSIEMHandler(module) except BaseException as err: raise FSMBaseException("Couldn't load FortiSIEM Handler from mod_utils. Error: " + str(err)) if paramgram["payload_file"]: paramgram["input_xml"] = fsm.get_file_contents(paramgram["payload_file"]) try: results = fsm.handle_simple_payload_request(paramgram["input_xml"]) except BaseException as err: raise FSMBaseException(err) else: try: results = fsm.handle_simple_request() except BaseException as err: raise FSMBaseException(err) # EXIT USING GOVERN_RESPONSE() fsm.govern_response(module=module, results=results, changed=False, ansible_facts=fsm.construct_ansible_facts(results["json_results"], module.params, paramgram)) return module.exit_json(msg=results)
def main(): argument_spec = dict( host=dict(required=True, type="str"), username=dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])), password=dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True), ignore_ssl_errors=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_screen=dict(required=False, type="str", choices=["enable", "disable"], default="enable"), export_json_to_file_path=dict(required=False, type="str"), export_xml_to_file_path=dict(required=False, type="str"), export_csv_to_file_path=dict(required=False, type="str"), wait_to_finish=dict(required=False, type="bool", default="false"), type=dict(required=True, type="str", choices=["RangeScan", "SmartScan", "L2Scan", "status"]), root_ip=dict(required=False, type="str"), include_range=dict(required=False, type="str"), exclude_range=dict(required=False, type="str"), no_ping=dict(required=False, type="bool", default="false"), only_ping=dict(required=False, type="bool", default="false"), task_id=dict(required=False, type="int"), delta=dict(required=False, type="bool", default="false"), vm_off=dict(required=False, type="bool", default="false"), vm_templates=dict(required=False, type="bool", default="false"), discover_routes=dict(required=False, type="bool", default="true"), winexe_based=dict(required=False, type="bool", default="false"), unmanaged=dict(required=False, type="bool", default="false"), monitor_win_events=dict(required=False, type="bool", default="true"), monitor_win_patches=dict(required=False, type="bool", default="true"), monitor_installed_sw=dict(required=False, type="bool", default="true"), name_resolution_dns_first=dict(required=False, type="bool", default="true"), ) required_if = [ ['type', 'SmartScan', ['root_ip']], ['type', 'RangeScan', ['include_range']], ['type', 'L2Scan', ['include_range']], ['type', 'status', ['task_id']], ] module = AnsibleModule(argument_spec, supports_check_mode=False, required_if=required_if) paramgram = { "host": module.params["host"], "username": module.params["username"], "password": module.params["password"], "export_json_to_screen": module.params["export_json_to_screen"], "export_json_to_file_path": module.params["export_json_to_file_path"], "export_xml_to_file_path": module.params["export_xml_to_file_path"], "export_csv_to_file_path": module.params["export_csv_to_file_path"], "ignore_ssl_errors": module.params["ignore_ssl_errors"], "type": module.params["type"], "wait_to_finish": module.params["wait_to_finish"], "root_ip": module.params["root_ip"], "include_range": module.params["include_range"], "exclude_range": module.params["exclude_range"], "no_ping": module.params["no_ping"], "only_ping": module.params["only_ping"], "task_id": module.params["task_id"], "delta": module.params["delta"], "vm_off": module.params["vm_off"], "vm_templates": module.params["vm_templates"], "discover_routes": module.params["discover_routes"], "winexe_based": module.params["winexe_based"], "unmanaged": module.params["unmanaged"], "monitor_win_events": module.params["monitor_win_events"], "monitor_win_patches": module.params["monitor_win_patches"], "monitor_installed_sw": module.params["monitor_installed_sw"], "name_resolution_dns_first": module.params["name_resolution_dns_first"], "uri": FSMEndpoints.SET_DISCOVERY, "input_xml": None } module.paramgram = paramgram # TRY TO INIT THE CONNECTION SOCKET PATH AND FortiManagerHandler OBJECT AND TOOLS fsm = None results = DEFAULT_EXIT_MSG try: fsm = FortiSIEMHandler(module) except BaseException as err: raise FSMBaseException( "Couldn't load FortiSIEM Handler from mod_utils. Error: " + str(err)) # EXECUTE THE MODULE OPERATION # SEND THE DISCOVERY XML PAYLOAD if paramgram["type"] != "status": paramgram["input_xml"] = fsm._xml.create_discover_payload() try: results = fsm.handle_simple_payload_request(paramgram["input_xml"]) except BaseException as err: raise FSMBaseException(err) # REFACTOR THE GENERIC RESPONSE BECAUSE IT WASN'T STRUCTURED BY FORTISIEM IN AN XML RESPONSE # RECORD THE TASK ID try: paramgram["task_id"] = results["json_results"]["fsm_response"] del results["json_results"]["fsm_response"] results["json_results"]["task_id"] = paramgram["task_id"] results["xml_results"] = "<task_id>" + str( paramgram["task_id"]) + "</task_id>" except BaseException as err: raise FSMBaseException( msg="Couldn't extract discovery task ID from response! Error: " + str(err)) # START THE STATUS CHECKING PORTION if paramgram["type"] == "status" or paramgram["wait_to_finish"]: if not paramgram["task_id"]: raise FSMBaseException( msg="fsm_discovery was called to status " "or wait_to_finish but the task ID was empty") if paramgram["task_id"]: paramgram["uri"] = FSMEndpoints.GET_DISCOVERY + str( paramgram["task_id"]) module.paramgram = paramgram try: results = fsm.handle_simple_request() except BaseException as err: raise FSMBaseException( msg="Failed to get status of task ID: " + str(paramgram["task_id"]) + " - Error: " + str(err)) # PROCESS WAIT TO FINISH! if paramgram["wait_to_finish"]: try: task_status_result = results["json_results"][ "fsm_response"].split(":") # SLEEP FOR 5 SECOND INTERVALS AND KEEP CHECKING UNTIL PROGRESS IS 100% while task_status_result[1] != "Done": time.sleep(5) try: results = fsm.handle_simple_request() except BaseException as err: raise FSMBaseException( msg="Failed to get status of task ID: " + str(paramgram["task_id"]) + " - Error: " + str(err)) try: if results["json_results"]["taskResults"]: task_status_result = [ str(paramgram["task_id"]), "Done" ] except BaseException: try: task_status_result = results["json_results"][ "fsm_response"].split(":") except BaseException as err: raise FSMBaseException(err) except BaseException: try: if results["json_results"]["taskResults"]: pass except BaseException as err: raise FSMBaseException( msg="Something happened while looping " "for the status. Error: " + str(err)) pass # EXIT USING GOVERN_RESPONSE() fsm.govern_response(module=module, results=results, changed=False, ansible_facts=fsm.construct_ansible_facts( results["json_results"], module.params, paramgram)) return module.exit_json(msg=results)