Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_system_ips.py

raw symbols SCIP
1 #!/usr/bin/python
2 from __future__ import absolute_import, division, print_function
3
4 # Copyright: (c) 2022 Fortinet
5 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 __metaclass__ = type
13
14 ANSIBLE_METADATA = {
15 "status": ["preview"],
16 "supported_by": "community",
17 "metadata_version": "1.1",
18 }
19
20 DOCUMENTATION = """
21 ---
22 module: fortios_system_ips
23 short_description: Configure IPS system settings in Fortinet's FortiOS and FortiGate.
24 description:
25 - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
26 user to set and modify system feature and ips category.
27 Examples include all parameters and values need to be adjusted to datasources before usage.
28 Tested with FOS v6.0.0
29 version_added: "2.0.0"
30 author:
31 - Link Zheng (@chillancezen)
32 - Jie Xue (@JieX19)
33 - Hongbin Lu (@fgtdev-hblu)
34 - Frank Shen (@frankshen01)
35 - Miguel Angel Munoz (@mamunozgonzalez)
36 - Nicolas Thomas (@thomnico)
37 notes:
38 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
39
40 - The module supports check_mode.
41
42 requirements:
43 - ansible>=2.16
44 options:
45 access_token:
46 description:
47 - Token-based authentication.
48 Generated from GUI of Fortigate.
49 type: str
50 required: false
51 enable_log:
52 description:
53 - Enable/Disable logging for task.
54 type: bool
55 required: false
56 default: false
57 vdom:
58 description:
59 - Virtual domain, among those defined previously. A vdom is a
60 virtual instance of the FortiGate that can be configured and
61 used as a different unit.
62 type: str
63 default: root
64 member_path:
65 type: str
66 description:
67 - Member attribute path to operate on.
68 - Delimited by a slash character if there are more than one attribute.
69 - Parameter marked with member_path is legitimate for doing member operation.
70 member_state:
71 type: str
72 description:
73 - Add or delete a member under specified attribute path.
74 - When member_state is specified, the state option is ignored.
75 choices:
76 - 'present'
77 - 'absent'
78
79 system_ips:
80 description:
81 - Configure IPS system settings.
82 default: null
83 type: dict
84 suboptions:
85 override_signature_hold_by_id:
86 description:
87 - Enable/disable override of hold of triggering signatures that are specified by IDs regardless of hold.
88 type: str
89 choices:
90 - 'enable'
91 - 'disable'
92 signature_hold_time:
93 description:
94 - 'Time to hold and monitor IPS signatures. Format <#d##h> (day range: 0 - 21, hour range: 0 - 23, max hold time: 21d0h).'
95 type: str
96 """
97
98 EXAMPLES = """
99 - name: Configure IPS system settings.
100 fortinet.fortios.fortios_system_ips:
101 vdom: "{{ vdom }}"
102 system_ips:
103 override_signature_hold_by_id: "enable"
104 signature_hold_time: "<your_own_value>"
105 """
106
107 RETURN = """
108 build:
109 description: Build number of the fortigate image
110 returned: always
111 type: str
112 sample: '1547'
113 http_method:
114 description: Last method used to provision the content into FortiGate
115 returned: always
116 type: str
117 sample: 'PUT'
118 http_status:
119 description: Last result given by FortiGate on last operation applied
120 returned: always
121 type: str
122 sample: "200"
123 mkey:
124 description: Master key (id) used in the last call to FortiGate
125 returned: success
126 type: str
127 sample: "id"
128 name:
129 description: Name of the table used to fulfill the request
130 returned: always
131 type: str
132 sample: "urlfilter"
133 path:
134 description: Path of the table used to fulfill the request
135 returned: always
136 type: str
137 sample: "webfilter"
138 revision:
139 description: Internal revision number
140 returned: always
141 type: str
142 sample: "17.0.2.10658"
143 serial:
144 description: Serial number of the unit
145 returned: always
146 type: str
147 sample: "FGVMEVYYQT3AB5352"
148 status:
149 description: Indication of the operation's result
150 returned: always
151 type: str
152 sample: "success"
153 vdom:
154 description: Virtual domain used
155 returned: always
156 type: str
157 sample: "root"
158 version:
159 description: Version of the FortiGate
160 returned: always
161 type: str
162 sample: "v5.6.3"
163 """
164 from ansible.module_utils.basic import AnsibleModule
165 from ansible.module_utils.connection import Connection
166 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
167 FortiOSHandler,
168 )
169 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
170 check_legacy_fortiosapi,
171 )
172 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
173 schema_to_module_spec,
174 )
175 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
176 check_schema_versioning,
177 )
178 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
179 FAIL_SOCKET_MSG,
180 )
181 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
182 remove_invalid_fields,
183 )
184 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
185 is_same_comparison,
186 )
187 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
188 serialize,
189 )
190 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
191 find_current_values,
192 )
193 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
194 unify_data_format,
195 )
196
197
198 def filter_system_ips_data(json):
199 option_list = ["override_signature_hold_by_id", "signature_hold_time"]
200
201 json = remove_invalid_fields(json)
202 dictionary = {}
203
204 for attribute in option_list:
205 if attribute in json and json[attribute] is not None:
206 dictionary[attribute] = json[attribute]
207
208 return dictionary
209
210
211 def underscore_to_hyphen(data):
212 new_data = None
213 if isinstance(data, list):
214 new_data = []
215 for i, elem in enumerate(data):
216 new_data.append(underscore_to_hyphen(elem))
217 elif isinstance(data, dict):
218 new_data = {}
219 for k, v in data.items():
220 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
221 else:
222 return data
223 return new_data
224
225
226 def system_ips(data, fos, check_mode=False):
227
228 state = None
229 vdom = data["vdom"]
230 parameters = None
231 state = data.get("state", None)
232 system_ips_data = data["system_ips"]
233
234 filtered_data = filter_system_ips_data(system_ips_data)
235 converted_data = underscore_to_hyphen(filtered_data)
236
237 # check_mode starts from here
238 if check_mode:
239 diff = {
240 "before": "",
241 "after": filtered_data,
242 }
243 mkeyname = fos.get_mkeyname(None, None)
244 mkey = fos.get_mkey("system", "ips", filtered_data, vdom=vdom)
245 current_data = fos.get(
246 "system", "ips", vdom=vdom, mkey=mkey, parameters=parameters
247 )
248 is_existed = (
249 current_data
250 and current_data.get("http_status") == 200
251 and (
252 mkeyname
253 and isinstance(current_data.get("results"), list)
254 and len(current_data["results"]) > 0
255 or not mkeyname
256 and current_data["results"] # global object response
257 )
258 )
259
260 # 2. if it exists and the state is 'present' then compare current settings with desired
261 if state == "present" or state is True or state is None:
262 # for non global modules, mkeyname must exist and it's a new module when mkey is None
263 if mkeyname is not None and mkey is None:
264 return False, True, filtered_data, diff
265
266 # if mkey exists then compare each other
267 # record exits and they're matched or not
268 copied_filtered_data = filtered_data.copy()
269 copied_filtered_data.pop(mkeyname, None)
270 unified_filtered_data = unify_data_format(copied_filtered_data)
271
272 current_data_results = current_data.get("results", {})
273 current_config = (
274 current_data_results[0]
275 if mkeyname
276 and isinstance(current_data_results, list)
277 and len(current_data_results) > 0
278 else current_data_results
279 )
280 if is_existed:
281 unified_current_values = find_current_values(
282 unified_filtered_data,
283 unify_data_format(current_config),
284 )
285
286 is_same = is_same_comparison(
287 serialize(unified_current_values), serialize(unified_filtered_data)
288 )
289
290 return (
291 False,
292 not is_same,
293 filtered_data,
294 {"before": unified_current_values, "after": unified_filtered_data},
295 )
296
297 # record does not exist
298 return False, True, filtered_data, diff
299
300 if state == "absent":
301 if mkey is None:
302 return (
303 False,
304 False,
305 filtered_data,
306 {"before": current_data["results"][0], "after": ""},
307 )
308
309 if is_existed:
310 return (
311 False,
312 True,
313 filtered_data,
314 {"before": current_data["results"][0], "after": ""},
315 )
316 return False, False, filtered_data, {}
317
318 return True, False, {"reason: ": "Must provide state parameter"}, {}
319 # pass post processed data to member operations
320 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
321 data_copy = data.copy()
322 data_copy["system_ips"] = filtered_data
323 fos.do_member_operation(
324 "system",
325 "ips",
326 data_copy,
327 )
328
329 return fos.set(
330 "system", "ips", data=converted_data, vdom=vdom, parameters=parameters
331 )
332
333
334 def is_successful_status(resp):
335 return (
336 "status" in resp
337 and resp["status"] == "success"
338 or "http_status" in resp
339 and resp["http_status"] == 200
340 or "http_method" in resp
341 and resp["http_method"] == "DELETE"
342 and resp["http_status"] == 404
343 )
344
345
346 def fortios_system(data, fos, check_mode):
347
348 if data["system_ips"]:
349 resp = system_ips(data, fos, check_mode)
350 else:
351 fos._module.fail_json(msg="missing task body: %s" % ("system_ips"))
352 if isinstance(resp, tuple) and len(resp) == 4:
353 return resp
354 return (
355 not is_successful_status(resp),
356 is_successful_status(resp)
357 and (resp["revision_changed"] if "revision_changed" in resp else True),
358 resp,
359 {},
360 )
361
362
363 versioned_schema = {
364 "v_range": [["v6.4.0", "v6.4.0"], ["v6.4.4", ""]],
365 "type": "dict",
366 "children": {
367 "signature_hold_time": {
368 "v_range": [["v6.4.0", "v6.4.0"], ["v6.4.4", ""]],
369 "type": "string",
370 },
371 "override_signature_hold_by_id": {
372 "v_range": [["v6.4.0", "v6.4.0"], ["v6.4.4", ""]],
373 "type": "string",
374 "options": [{"value": "enable"}, {"value": "disable"}],
375 },
376 },
377 }
378
379
380 def main():
381 module_spec = schema_to_module_spec(versioned_schema)
382 mkeyname = None
383 fields = {
384 "access_token": {"required": False, "type": "str", "no_log": True},
385 "enable_log": {"required": False, "type": "bool", "default": False},
386 "vdom": {"required": False, "type": "str", "default": "root"},
387 "member_path": {"required": False, "type": "str"},
388 "member_state": {
389 "type": "str",
390 "required": False,
391 "choices": ["present", "absent"],
392 },
393 "system_ips": {
394 "required": False,
395 "type": "dict",
396 "default": None,
397 "options": {},
398 },
399 }
400 for attribute_name in module_spec["options"]:
401 fields["system_ips"]["options"][attribute_name] = module_spec["options"][
402 attribute_name
403 ]
404 if mkeyname and mkeyname == attribute_name:
405 fields["system_ips"]["options"][attribute_name]["required"] = True
406
407 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
408 check_legacy_fortiosapi(module)
409
410 is_error = False
411 has_changed = False
412 result = None
413 diff = None
414
415 versions_check_result = None
416 if module._socket_path:
417 connection = Connection(module._socket_path)
418 if "access_token" in module.params:
419 connection.set_custom_option("access_token", module.params["access_token"])
420
421 if "enable_log" in module.params:
422 connection.set_custom_option("enable_log", module.params["enable_log"])
423 else:
424 connection.set_custom_option("enable_log", False)
425 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
426 versions_check_result = check_schema_versioning(
427 fos, versioned_schema, "system_ips"
428 )
429
430 is_error, has_changed, result, diff = fortios_system(
431 module.params, fos, module.check_mode
432 )
433
434 else:
435 module.fail_json(**FAIL_SOCKET_MSG)
436
437 if versions_check_result and versions_check_result["matched"] is False:
438 module.warn(
439 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
440 )
441
442 if not is_error:
443 if versions_check_result and versions_check_result["matched"] is False:
444 module.exit_json(
445 changed=has_changed,
446 version_check_warning=versions_check_result,
447 meta=result,
448 diff=diff,
449 )
450 else:
451 module.exit_json(changed=has_changed, meta=result, diff=diff)
452 else:
453 if versions_check_result and versions_check_result["matched"] is False:
454 module.fail_json(
455 msg="Error in repo",
456 version_check_warning=versions_check_result,
457 meta=result,
458 )
459 else:
460 module.fail_json(msg="Error in repo", meta=result)
461
462
463 if __name__ == "__main__":
464 main()