FortiManager Plugin Module Conversion: fmgr_secprof_ssl_ssh (#52787)

* Auto Commit for: fmgr_secprof_ssl_ssh

* Auto Commit for: fmgr_secprof_ssl_ssh

* Auto Commit for: fmgr_secprof_ssl_ssh
This commit is contained in:
ftntcorecse 2019-02-27 01:31:03 -05:00 committed by Nilashish Chakraborty
parent 1aae196cfa
commit bf162e258b
3 changed files with 279 additions and 469 deletions

View file

@ -27,6 +27,8 @@ DOCUMENTATION = '''
---
module: fmgr_secprof_ssl_ssh
version_added: "2.8"
notes:
- Full Documentation at U(https://ftnt-ansible-docs.readthedocs.io/en/latest/).
author:
- Luke Weighall (@lweighall)
- Andrew Welsh (@Ghilli3)
@ -42,21 +44,6 @@ options:
required: false
default: root
host:
description:
- The FortiManager's address.
required: true
username:
description:
- The username associated with the account.
required: true
password:
description:
- The password associated with the username account.
required: true
mode:
description:
- Sets one of three modes for managing the object.
@ -684,17 +671,11 @@ options:
EXAMPLES = '''
- name: DELETE Profile
fmgr_secprof_ssl_ssh:
host: "{{inventory_hostname}}"
username: "{{ username }}"
password: "{{ password }}"
name: Ansible_SSL_SSH_Profile
mode: delete
- name: CREATE Profile
fmgr_secprof_ssl_ssh:
host: "{{inventory_hostname}}"
username: "{{ username }}"
password: "{{ password }}"
name: Ansible_SSL_SSH_Profile
comment: "Created by Ansible Module TEST"
mode: set
@ -715,29 +696,42 @@ api_result:
"""
from ansible.module_utils.basic import AnsibleModule, env_fallback
from ansible.module_utils.network.fortimanager.fortimanager import AnsibleFortiManager
from ansible.module_utils.connection import Connection
from ansible.module_utils.network.fortimanager.fortimanager import FortiManagerHandler
from ansible.module_utils.network.fortimanager.common import FMGBaseException
from ansible.module_utils.network.fortimanager.common import FMGRCommon
from ansible.module_utils.network.fortimanager.common import FMGRMethods
from ansible.module_utils.network.fortimanager.common import DEFAULT_RESULT_OBJ
from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG
from ansible.module_utils.network.fortimanager.common import prepare_dict
from ansible.module_utils.network.fortimanager.common import scrub_dict
###############
# START METHODS
###############
def fmgr_firewall_ssl_ssh_profile_addsetdelete(fmg, paramgram):
def fmgr_firewall_ssl_ssh_profile_modify(fmgr, paramgram):
"""
fmgr_firewall_ssl_ssh_profile -- Your Description here, bruh
:param fmgr: The fmgr object instance from fortimanager.py
:type fmgr: class object
:param paramgram: The formatted dictionary of options to process
:type paramgram: dict
:return: The response from the FortiManager
:rtype: dict
"""
mode = paramgram["mode"]
adom = paramgram["adom"]
response = (-100000, {"msg": "Illegal or malformed paramgram discovered. System Exception"})
response = DEFAULT_RESULT_OBJ
url = ""
datagram = {}
# EVAL THE MODE PARAMETER FOR SET OR ADD
if mode in ['set', 'add', 'update']:
url = '/pm/config/adom/{adom}/obj/firewall/ssl-ssh-profile'.format(adom=adom)
datagram = fmgr_del_none(fmgr_prepare_dict(paramgram))
datagram = scrub_dict(prepare_dict(paramgram))
# EVAL THE MODE PARAMETER FOR DELETE
elif mode == "delete":
@ -745,124 +739,11 @@ def fmgr_firewall_ssl_ssh_profile_addsetdelete(fmg, paramgram):
url = '/pm/config/adom/{adom}/obj/firewall/ssl-ssh-profile/{name}'.format(adom=adom, name=paramgram["name"])
datagram = {}
# IF MODE = SET -- USE THE 'SET' API CALL MODE
if mode == "set":
response = fmg.set(url, datagram)
# IF MODE = UPDATE -- USER THE 'UPDATE' API CALL MODE
elif mode == "update":
response = fmg.update(url, datagram)
# IF MODE = ADD -- USE THE 'ADD' API CALL MODE
elif mode == "add":
response = fmg.add(url, datagram)
# IF MODE = DELETE -- USE THE DELETE URL AND API CALL MODE
elif mode == "delete":
response = fmg.delete(url, datagram)
response = fmgr.process_request(url, datagram, paramgram["mode"])
return response
# ADDITIONAL COMMON FUNCTIONS
def fmgr_logout(fmg, module, msg="NULL", results=(), good_codes=(0,), logout_on_fail=True, logout_on_success=False):
"""
THIS METHOD CONTROLS THE LOGOUT AND ERROR REPORTING AFTER AN METHOD OR FUNCTION RUNS
"""
# VALIDATION ERROR (NO RESULTS, JUST AN EXIT)
if msg != "NULL" and len(results) == 0:
try:
fmg.logout()
except Exception:
pass
module.fail_json(msg=msg)
# SUBMISSION ERROR
if len(results) > 0:
if msg == "NULL":
try:
msg = results[1]['status']['message']
except Exception:
msg = "No status message returned from pyFMG. Possible that this was a GET with a tuple result."
if results[0] not in good_codes:
if logout_on_fail:
fmg.logout()
module.fail_json(msg=msg, **results[1])
else:
if logout_on_success:
fmg.logout()
module.exit_json(msg="API Called worked, but logout handler has been asked to logout on success",
**results[1])
return msg
# FUNCTION/METHOD FOR CONVERTING CIDR TO A NETMASK
# DID NOT USE IP ADDRESS MODULE TO KEEP INCLUDES TO A MINIMUM
def fmgr_cidr_to_netmask(cidr):
cidr = int(cidr)
mask = (0xffffffff >> (32 - cidr)) << (32 - cidr)
return(str((0xff000000 & mask) >> 24) + '.' +
str((0x00ff0000 & mask) >> 16) + '.' +
str((0x0000ff00 & mask) >> 8) + '.' +
str((0x000000ff & mask)))
# utility function: removing keys wih value of None, nothing in playbook for that key
def fmgr_del_none(obj):
if isinstance(obj, dict):
return type(obj)((fmgr_del_none(k), fmgr_del_none(v))
for k, v in obj.items() if k is not None and (v is not None and not fmgr_is_empty_dict(v)))
else:
return obj
# utility function: remove keys that are need for the logic but the FMG API won't accept them
def fmgr_prepare_dict(obj):
list_of_elems = ["mode", "adom", "host", "username", "password"]
if isinstance(obj, dict):
obj = dict((key, fmgr_prepare_dict(value)) for (key, value) in obj.items() if key not in list_of_elems)
return obj
def fmgr_is_empty_dict(obj):
return_val = False
if isinstance(obj, dict):
if len(obj) > 0:
for k, v in obj.items():
if isinstance(v, dict):
if len(v) == 0:
return_val = True
elif len(v) > 0:
for k1, v1 in v.items():
if v1 is None:
return_val = True
elif v1 is not None:
return_val = False
return return_val
elif v is None:
return_val = True
elif v is not None:
return_val = False
return return_val
elif len(obj) == 0:
return_val = True
return return_val
def fmgr_split_comma_strings_into_lists(obj):
if isinstance(obj, dict):
if len(obj) > 0:
for k, v in obj.items():
if isinstance(v, str):
new_list = list()
if "," in v:
new_items = v.split(",")
for item in new_items:
new_list.append(item.strip())
obj[k] = new_list
return obj
#############
# END METHODS
#############
@ -871,9 +752,6 @@ def fmgr_split_comma_strings_into_lists(obj):
def main():
argument_spec = dict(
adom=dict(type="str", default="root"),
host=dict(required=True, type="str"),
password=dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True, required=True),
username=dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"]), no_log=True, required=True),
mode=dict(choices=["add", "set", "delete", "update"], type="str", default="add"),
whitelist=dict(required=False, type="str", choices=["disable", "enable"]),
@ -958,8 +836,7 @@ def main():
)
module = AnsibleModule(argument_spec, supports_check_mode=False)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, )
# MODULE PARAMGRAM
paramgram = {
"mode": module.params["mode"],
@ -1051,44 +928,31 @@ def main():
}
}
list_overrides = ['ftps', 'https', 'imaps', 'pop3s', 'smtps', 'ssh', 'ssl', 'ssl-exempt', 'ssl-server']
for list_variable in list_overrides:
override_data = list()
try:
override_data = module.params[list_variable]
except Exception:
pass
try:
if override_data:
del paramgram[list_variable]
paramgram[list_variable] = override_data
except Exception:
pass
# CHECK IF THE HOST/USERNAME/PW EXISTS, AND IF IT DOES, LOGIN.
host = module.params["host"]
password = module.params["password"]
username = module.params["username"]
if host is None or username is None or password is None:
module.fail_json(msg="Host and username and password are required")
# CHECK IF LOGIN FAILED
fmg = AnsibleFortiManager(module, module.params["host"], module.params["username"], module.params["password"])
response = fmg.login()
if response[1]['status']['code'] != 0:
module.fail_json(msg="Connection to FortiManager Failed")
results = fmgr_firewall_ssl_ssh_profile_addsetdelete(fmg, paramgram)
if results[0] != 0:
fmgr_logout(fmg, module, results=results, good_codes=[0])
fmg.logout()
if results is not None:
return module.exit_json(**results[1])
module.paramgram = paramgram
fmgr = None
if module._socket_path:
connection = Connection(module._socket_path)
fmgr = FortiManagerHandler(connection, module)
fmgr.tools = FMGRCommon()
else:
return module.exit_json(msg="No results were returned from the API call.")
module.fail_json(**FAIL_SOCKET_MSG)
list_overrides = ['ftps', 'https', 'imaps', 'pop3s', 'smtps', 'ssh', 'ssl', 'ssl-exempt', 'ssl-server']
paramgram = fmgr.tools.paramgram_child_list_override(list_overrides=list_overrides,
paramgram=paramgram, module=module)
results = DEFAULT_RESULT_OBJ
try:
results = fmgr_firewall_ssl_ssh_profile_modify(fmgr, paramgram)
fmgr.govern_response(module=module, results=results,
ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))
except Exception as err:
raise FMGBaseException(err)
return module.exit_json(**results[1])
if __name__ == "__main__":

View file

@ -1,5 +1,5 @@
{
"fmgr_firewall_ssl_ssh_profile_addsetdelete": [
"fmgr_firewall_ssl_ssh_profile_modify": [
{
"paramgram_used": {
"comment": null,
@ -90,6 +90,7 @@
"untrusted-cert": null
}
},
"datagram_sent": {},
"raw_response": {
"status": {
"message": "OK",
@ -107,6 +108,17 @@
},
"url": "/pm/config/adom/root/obj/firewall/ssl-ssh-profile"
},
"datagram_sent": {
"comment": "Created by Ansible Module TEST",
"server-cert-mode": "replace",
"name": "Ansible_SSL_SSH_Profile",
"ssl-anomalies-log": "enable",
"mapi-over-https": "enable",
"whitelist": "enable",
"ssl-exemptions-log": "enable",
"rpc-over-https": "enable",
"use-ssl-server": "enable"
},
"paramgram_used": {
"comment": "Created by Ansible Module TEST",
"untrusted-caname": null,

View file

@ -19,7 +19,7 @@ __metaclass__ = type
import os
import json
from pyFMG.fortimgr import FortiManager
from ansible.module_utils.network.fortimanager.fortimanager import FortiManagerHandler
import pytest
try:
@ -27,15 +27,10 @@ try:
except ImportError:
pytest.skip("Could not load required modules for testing", allow_module_level=True)
fmg_instance = FortiManager("1.1.1.1", "admin", "")
def load_fixtures():
fixture_path = os.path.join(
os.path.dirname(__file__),
'fixtures') + "/{filename}.json".format(
filename=os.path.splitext(
os.path.basename(__file__))[0])
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') + "/{filename}.json".format(
filename=os.path.splitext(os.path.basename(__file__))[0])
try:
with open(fixture_path, "r") as fixture_file:
fixture_data = json.load(fixture_file)
@ -44,92 +39,31 @@ def load_fixtures():
return [fixture_data]
@pytest.fixture(autouse=True)
def module_mock(mocker):
connection_class_mock = mocker.patch('ansible.module_utils.basic.AnsibleModule')
return connection_class_mock
@pytest.fixture(autouse=True)
def connection_mock(mocker):
connection_class_mock = mocker.patch('ansible.modules.network.fortimanager.fmgr_secprof_ssl_ssh.Connection')
return connection_class_mock
@pytest.fixture(scope="function", params=load_fixtures())
def fixture_data(request):
func_name = request.function.__name__.replace("test_", "")
return request.param.get(func_name, None)
def test_fmgr_firewall_ssl_ssh_profile_addsetdelete(fixture_data, mocker):
mocker.patch("pyFMG.fortimgr.FortiManager._post_request", side_effect=fixture_data)
# Fixture sets used:###########################
fmg_instance = FortiManagerHandler(connection_mock, module_mock)
##################################################
# comment: None
# untrusted-caname: None
# mapi-over-https: None
# whitelist: None
# caname: None
# ftps: {'status': None, 'allow-invalid-server-cert': None, 'unsupported-ssl': None, 'client-cert-request': None,
# 'ports': None, 'untrusted-cert': None}
# ssl-exemptions-log: None
# https: {'status': None, 'allow-invalid-server-cert': None, 'unsupported-ssl': None, 'client-cert-request': None,
# 'ports': None, 'untrusted-cert': None}
# imaps: {'status': None, 'allow-invalid-server-cert': None, 'unsupported-ssl': None, 'client-cert-request': None,
# 'ports': None, 'untrusted-cert': None}
# server-cert-mode: None
# adom: root
# ssl-exempt: {'regex': None, 'wildcard-fqdn': None, 'fortiguard-category': None, 'address6': None,
# 'address': None, 'type': None}
# ssl: {'inspect-all': None, 'allow-invalid-server-cert': None, 'client-cert-request': None,
# 'untrusted-cert': None, 'unsupported-ssl': None}
# ssh: {'status': None, 'inspect-all': None, 'ssh-tun-policy-check': None, 'ssh-policy-check': None,
# 'ssh-algorithm': None, 'unsupported-version': None, 'ports': None}
# use-ssl-server: None
# server-cert: None
# name: Ansible_SSL_SSH_Profile
# ssl-anomalies-log: None
# ssl-server: {'pop3s-client-cert-request': None, 'imaps-client-cert-request': None,
# 'smtps-client-cert-request': None, 'ip': None, 'ssl-other-client-cert-request': None,
# 'https-client-cert-request': None, 'ftps-client-cert-request': None}
# smtps: {'status': None, 'allow-invalid-server-cert': None, 'unsupported-ssl': None, 'client-cert-request': None,
# 'ports': None, 'untrusted-cert': None}
# rpc-over-https: None
# mode: delete
# pop3s: {'status': None, 'allow-invalid-server-cert': None, 'unsupported-ssl': None, 'client-cert-request': None,
# 'ports': None, 'untrusted-cert': None}
##################################################
##################################################
# comment: Created by Ansible Module TEST
# untrusted-caname: None
# mapi-over-https: enable
# whitelist: enable
# caname: None
# ftps: {'status': None, 'allow-invalid-server-cert': None, 'unsupported-ssl': None, 'untrusted-cert': None,
# 'client-cert-request': None, 'ports': None}
# ssl-exemptions-log: enable
# https: {'status': None, 'allow-invalid-server-cert': None, 'unsupported-ssl': None, 'untrusted-cert': None,
# 'client-cert-request': None, 'ports': None}
# pop3s: {'status': None, 'allow-invalid-server-cert': None, 'unsupported-ssl': None, 'untrusted-cert': None,
# 'client-cert-request': None, 'ports': None}
# server-cert-mode: replace
# adom: root
# ssl-exempt: {'regex': None, 'wildcard-fqdn': None, 'fortiguard-category': None, 'address6': None,
# 'address': None, 'type': None}
# ssl: {'unsupported-ssl': None, 'inspect-all': None, 'allow-invalid-server-cert': None, 'untrusted-cert': None,
# 'client-cert-request': None}
# ssh: {'status': None, 'inspect-all': None, 'ssh-tun-policy-check': None, 'ssh-policy-check': None,
# 'ssh-algorithm': None, 'unsupported-version': None, 'ports': None}
# server-cert: None
# name: Ansible_SSL_SSH_Profile
# ssl-anomalies-log: enable
# ssl-server: {'pop3s-client-cert-request': None, 'imaps-client-cert-request': None,
# 'smtps-client-cert-request': None, 'ip': None, 'ssl-other-client-cert-request': None,
# 'https-client-cert-request': None, 'ftps-client-cert-request': None}
# smtps: {'status': None, 'allow-invalid-server-cert': None, 'unsupported-ssl': None, 'untrusted-cert': None,
# 'client-cert-request': None, 'ports': None}
# imaps: {'status': None, 'allow-invalid-server-cert': None, 'unsupported-ssl': None, 'untrusted-cert': None,
# 'client-cert-request': None, 'ports': None}
# rpc-over-https: enable
# mode: set
# use-ssl-server: enable
##################################################
# Test using fixture 1 #
output = fmgr_secprof_ssl_ssh.fmgr_firewall_ssl_ssh_profile_addsetdelete(
fmg_instance, fixture_data[0]['paramgram_used'])
def test_fmgr_firewall_ssl_ssh_profile_modify(fixture_data, mocker):
mocker.patch("ansible.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request",
side_effect=fixture_data)
output = fmgr_secprof_ssl_ssh.fmgr_firewall_ssl_ssh_profile_modify(fmg_instance, fixture_data[0]['paramgram_used'])
assert output['raw_response']['status']['code'] == 0
# Test using fixture 2 #
output = fmgr_secprof_ssl_ssh.fmgr_firewall_ssl_ssh_profile_addsetdelete(
fmg_instance, fixture_data[1]['paramgram_used'])
output = fmgr_secprof_ssl_ssh.fmgr_firewall_ssl_ssh_profile_modify(fmg_instance, fixture_data[1]['paramgram_used'])
assert output['raw_response']['status']['code'] == 0