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)
Пример #2
0
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)
Пример #3
0
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"),
        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(
        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)
Пример #6
0
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"),
        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=["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)
Пример #9
0
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)
Пример #10
0
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)