Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_ips_settings.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_ips_settings
23 short_description: Configure IPS VDOM parameter 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 ips feature and settings 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 ips_settings:
80 description:
81 - Configure IPS VDOM parameter.
82 default: null
83 type: dict
84 suboptions:
85 ha_session_pickup:
86 description:
87 - IPS HA failover session pickup preference.
88 type: str
89 choices:
90 - 'connectivity'
91 - 'security'
92 ips_packet_quota:
93 description:
94 - Maximum amount of disk space in MB for logged packets when logging to disk. Range depends on disk size.
95 type: int
96 packet_log_history:
97 description:
98 - Number of packets to capture before and including the one in which the IPS signature is detected (1 - 255).
99 type: int
100 packet_log_memory:
101 description:
102 - Maximum memory can be used by packet log (64 - 8192 kB).
103 type: int
104 packet_log_post_attack:
105 description:
106 - Number of packets to log after the IPS signature is detected (0 - 255).
107 type: int
108 proxy_inline_ips:
109 description:
110 - Enable/disable proxy-mode policy inline IPS support.
111 type: str
112 choices:
113 - 'disable'
114 - 'enable'
115 """
116
117 EXAMPLES = """
118 - name: Configure IPS VDOM parameter.
119 fortinet.fortios.fortios_ips_settings:
120 vdom: "{{ vdom }}"
121 ips_settings:
122 ha_session_pickup: "connectivity"
123 ips_packet_quota: "0"
124 packet_log_history: "1"
125 packet_log_memory: "256"
126 packet_log_post_attack: "0"
127 proxy_inline_ips: "disable"
128 """
129
130 RETURN = """
131 build:
132 description: Build number of the fortigate image
133 returned: always
134 type: str
135 sample: '1547'
136 http_method:
137 description: Last method used to provision the content into FortiGate
138 returned: always
139 type: str
140 sample: 'PUT'
141 http_status:
142 description: Last result given by FortiGate on last operation applied
143 returned: always
144 type: str
145 sample: "200"
146 mkey:
147 description: Master key (id) used in the last call to FortiGate
148 returned: success
149 type: str
150 sample: "id"
151 name:
152 description: Name of the table used to fulfill the request
153 returned: always
154 type: str
155 sample: "urlfilter"
156 path:
157 description: Path of the table used to fulfill the request
158 returned: always
159 type: str
160 sample: "webfilter"
161 revision:
162 description: Internal revision number
163 returned: always
164 type: str
165 sample: "17.0.2.10658"
166 serial:
167 description: Serial number of the unit
168 returned: always
169 type: str
170 sample: "FGVMEVYYQT3AB5352"
171 status:
172 description: Indication of the operation's result
173 returned: always
174 type: str
175 sample: "success"
176 vdom:
177 description: Virtual domain used
178 returned: always
179 type: str
180 sample: "root"
181 version:
182 description: Version of the FortiGate
183 returned: always
184 type: str
185 sample: "v5.6.3"
186 """
187 from ansible.module_utils.basic import AnsibleModule
188 from ansible.module_utils.connection import Connection
189 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
190 FortiOSHandler,
191 )
192 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
193 check_legacy_fortiosapi,
194 )
195 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
196 schema_to_module_spec,
197 )
198 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
199 check_schema_versioning,
200 )
201 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
202 FAIL_SOCKET_MSG,
203 )
204 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
205 remove_invalid_fields,
206 )
207 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
208 is_same_comparison,
209 )
210 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
211 serialize,
212 )
213 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
214 find_current_values,
215 )
216 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
217 unify_data_format,
218 )
219
220
221 def filter_ips_settings_data(json):
222 option_list = [
223 "ha_session_pickup",
224 "ips_packet_quota",
225 "packet_log_history",
226 "packet_log_memory",
227 "packet_log_post_attack",
228 "proxy_inline_ips",
229 ]
230
231 json = remove_invalid_fields(json)
232 dictionary = {}
233
234 for attribute in option_list:
235 if attribute in json and json[attribute] is not None:
236 dictionary[attribute] = json[attribute]
237
238 return dictionary
239
240
241 def underscore_to_hyphen(data):
242 new_data = None
243 if isinstance(data, list):
244 new_data = []
245 for i, elem in enumerate(data):
246 new_data.append(underscore_to_hyphen(elem))
247 elif isinstance(data, dict):
248 new_data = {}
249 for k, v in data.items():
250 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
251 else:
252 return data
253 return new_data
254
255
256 def ips_settings(data, fos, check_mode=False):
257
258 state = None
259 vdom = data["vdom"]
260 parameters = None
261 state = data.get("state", None)
262 ips_settings_data = data["ips_settings"]
263
264 filtered_data = filter_ips_settings_data(ips_settings_data)
265 converted_data = underscore_to_hyphen(filtered_data)
266
267 # check_mode starts from here
268 if check_mode:
269 diff = {
270 "before": "",
271 "after": filtered_data,
272 }
273 mkeyname = fos.get_mkeyname(None, None)
274 mkey = fos.get_mkey("ips", "settings", filtered_data, vdom=vdom)
275 current_data = fos.get(
276 "ips", "settings", vdom=vdom, mkey=mkey, parameters=parameters
277 )
278 is_existed = (
279 current_data
280 and current_data.get("http_status") == 200
281 and (
282 mkeyname
283 and isinstance(current_data.get("results"), list)
284 and len(current_data["results"]) > 0
285 or not mkeyname
286 and current_data["results"] # global object response
287 )
288 )
289
290 # 2. if it exists and the state is 'present' then compare current settings with desired
291 if state == "present" or state is True or state is None:
292 # for non global modules, mkeyname must exist and it's a new module when mkey is None
293 if mkeyname is not None and mkey is None:
294 return False, True, filtered_data, diff
295
296 # if mkey exists then compare each other
297 # record exits and they're matched or not
298 copied_filtered_data = filtered_data.copy()
299 copied_filtered_data.pop(mkeyname, None)
300 unified_filtered_data = unify_data_format(copied_filtered_data)
301
302 current_data_results = current_data.get("results", {})
303 current_config = (
304 current_data_results[0]
305 if mkeyname
306 and isinstance(current_data_results, list)
307 and len(current_data_results) > 0
308 else current_data_results
309 )
310 if is_existed:
311 unified_current_values = find_current_values(
312 unified_filtered_data,
313 unify_data_format(current_config),
314 )
315
316 is_same = is_same_comparison(
317 serialize(unified_current_values), serialize(unified_filtered_data)
318 )
319
320 return (
321 False,
322 not is_same,
323 filtered_data,
324 {"before": unified_current_values, "after": unified_filtered_data},
325 )
326
327 # record does not exist
328 return False, True, filtered_data, diff
329
330 if state == "absent":
331 if mkey is None:
332 return (
333 False,
334 False,
335 filtered_data,
336 {"before": current_data["results"][0], "after": ""},
337 )
338
339 if is_existed:
340 return (
341 False,
342 True,
343 filtered_data,
344 {"before": current_data["results"][0], "after": ""},
345 )
346 return False, False, filtered_data, {}
347
348 return True, False, {"reason: ": "Must provide state parameter"}, {}
349 # pass post processed data to member operations
350 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
351 data_copy = data.copy()
352 data_copy["ips_settings"] = filtered_data
353 fos.do_member_operation(
354 "ips",
355 "settings",
356 data_copy,
357 )
358
359 return fos.set(
360 "ips", "settings", data=converted_data, vdom=vdom, parameters=parameters
361 )
362
363
364 def is_successful_status(resp):
365 return (
366 "status" in resp
367 and resp["status"] == "success"
368 or "http_status" in resp
369 and resp["http_status"] == 200
370 or "http_method" in resp
371 and resp["http_method"] == "DELETE"
372 and resp["http_status"] == 404
373 )
374
375
376 def fortios_ips(data, fos, check_mode):
377
378 if data["ips_settings"]:
379 resp = ips_settings(data, fos, check_mode)
380 else:
381 fos._module.fail_json(msg="missing task body: %s" % ("ips_settings"))
382 if isinstance(resp, tuple) and len(resp) == 4:
383 return resp
384 return (
385 not is_successful_status(resp),
386 is_successful_status(resp)
387 and (resp["revision_changed"] if "revision_changed" in resp else True),
388 resp,
389 {},
390 )
391
392
393 versioned_schema = {
394 "v_range": [["v6.0.0", ""]],
395 "type": "dict",
396 "children": {
397 "packet_log_history": {"v_range": [["v6.0.0", ""]], "type": "integer"},
398 "packet_log_post_attack": {"v_range": [["v6.0.0", ""]], "type": "integer"},
399 "packet_log_memory": {"v_range": [["v6.0.0", ""]], "type": "integer"},
400 "ips_packet_quota": {"v_range": [["v6.0.0", ""]], "type": "integer"},
401 "proxy_inline_ips": {
402 "v_range": [["v7.4.2", ""]],
403 "type": "string",
404 "options": [{"value": "disable"}, {"value": "enable"}],
405 },
406 "ha_session_pickup": {
407 "v_range": [["v7.6.0", ""]],
408 "type": "string",
409 "options": [{"value": "connectivity"}, {"value": "security"}],
410 },
411 },
412 }
413
414
415 def main():
416 module_spec = schema_to_module_spec(versioned_schema)
417 mkeyname = None
418 fields = {
419 "access_token": {"required": False, "type": "str", "no_log": True},
420 "enable_log": {"required": False, "type": "bool", "default": False},
421 "vdom": {"required": False, "type": "str", "default": "root"},
422 "member_path": {"required": False, "type": "str"},
423 "member_state": {
424 "type": "str",
425 "required": False,
426 "choices": ["present", "absent"],
427 },
428 "ips_settings": {
429 "required": False,
430 "type": "dict",
431 "default": None,
432 "options": {},
433 },
434 }
435 for attribute_name in module_spec["options"]:
436 fields["ips_settings"]["options"][attribute_name] = module_spec["options"][
437 attribute_name
438 ]
439 if mkeyname and mkeyname == attribute_name:
440 fields["ips_settings"]["options"][attribute_name]["required"] = True
441
442 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
443 check_legacy_fortiosapi(module)
444
445 is_error = False
446 has_changed = False
447 result = None
448 diff = None
449
450 versions_check_result = None
451 if module._socket_path:
452 connection = Connection(module._socket_path)
453 if "access_token" in module.params:
454 connection.set_custom_option("access_token", module.params["access_token"])
455
456 if "enable_log" in module.params:
457 connection.set_custom_option("enable_log", module.params["enable_log"])
458 else:
459 connection.set_custom_option("enable_log", False)
460 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
461 versions_check_result = check_schema_versioning(
462 fos, versioned_schema, "ips_settings"
463 )
464
465 is_error, has_changed, result, diff = fortios_ips(
466 module.params, fos, module.check_mode
467 )
468
469 else:
470 module.fail_json(**FAIL_SOCKET_MSG)
471
472 if versions_check_result and versions_check_result["matched"] is False:
473 module.warn(
474 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
475 )
476
477 if not is_error:
478 if versions_check_result and versions_check_result["matched"] is False:
479 module.exit_json(
480 changed=has_changed,
481 version_check_warning=versions_check_result,
482 meta=result,
483 diff=diff,
484 )
485 else:
486 module.exit_json(changed=has_changed, meta=result, diff=diff)
487 else:
488 if versions_check_result and versions_check_result["matched"] is False:
489 module.fail_json(
490 msg="Error in repo",
491 version_check_warning=versions_check_result,
492 meta=result,
493 )
494 else:
495 module.fail_json(msg="Error in repo", meta=result)
496
497
498 if __name__ == "__main__":
499 main()