Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_ips_global.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_global
23 short_description: Configure IPS global 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 global 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_global:
80 description:
81 - Configure IPS global parameter.
82 default: null
83 type: dict
84 suboptions:
85 anomaly_mode:
86 description:
87 - Global blocking mode for rate-based anomalies.
88 type: str
89 choices:
90 - 'periodical'
91 - 'continuous'
92 av_mem_limit:
93 description:
94 - Maximum percentage of system memory allowed for use on AV scanning (10 - 50). To disable set to zero. When disabled, there is no limit
95 on the AV memory usage.
96 type: int
97 cp_accel_mode:
98 description:
99 - IPS Pattern matching acceleration/offloading to CPx processors.
100 type: str
101 choices:
102 - 'none'
103 - 'basic'
104 - 'advanced'
105 database:
106 description:
107 - Regular or extended IPS database. Regular protects against the latest common and in-the-wild attacks. Extended includes protection from
108 legacy attacks.
109 type: str
110 choices:
111 - 'regular'
112 - 'extended'
113 deep_app_insp_db_limit:
114 description:
115 - Limit on number of entries in deep application inspection database (1 - 2147483647, use recommended setting = 0).
116 type: int
117 deep_app_insp_timeout:
118 description:
119 - Timeout for Deep application inspection (1 - 2147483647 sec., 0 = use recommended setting).
120 type: int
121 engine_count:
122 description:
123 - Number of IPS engines running. If set to the default value of 0, FortiOS sets the number to optimize performance depending on the number
124 of CPU cores.
125 type: int
126 exclude_signatures:
127 description:
128 - Excluded signatures.
129 type: str
130 choices:
131 - 'none'
132 - 'ot'
133 - 'industrial'
134 fail_open:
135 description:
136 - Enable to allow traffic if the IPS buffer is full. Default is disable and IPS traffic is blocked when the IPS buffer is full.
137 type: str
138 choices:
139 - 'enable'
140 - 'disable'
141 intelligent_mode:
142 description:
143 - Enable/disable IPS adaptive scanning (intelligent mode). Intelligent mode optimizes the scanning method for the type of traffic.
144 type: str
145 choices:
146 - 'enable'
147 - 'disable'
148 ips_reserve_cpu:
149 description:
150 - Enable/disable IPS daemon"s use of CPUs other than CPU 0.
151 type: str
152 choices:
153 - 'disable'
154 - 'enable'
155 machine_learning_detection:
156 description:
157 - Enable/disable machine learning detection.
158 type: str
159 choices:
160 - 'enable'
161 - 'disable'
162 ngfw_max_scan_range:
163 description:
164 - NGFW policy-mode app detection threshold.
165 type: int
166 np_accel_mode:
167 description:
168 - Acceleration mode for IPS processing by NPx processors.
169 type: str
170 choices:
171 - 'none'
172 - 'basic'
173 packet_log_queue_depth:
174 description:
175 - Packet/pcap log queue depth per IPS engine.
176 type: int
177 session_limit_mode:
178 description:
179 - Method of counting concurrent sessions used by session limit anomalies. Choose between greater accuracy (accurate) or improved
180 performance (heuristics).
181 type: str
182 choices:
183 - 'accurate'
184 - 'heuristic'
185 skype_client_public_ipaddr:
186 description:
187 - Public IP addresses of your network that receive Skype sessions. Helps identify Skype sessions. Separate IP addresses with commas.
188 type: str
189 socket_size:
190 description:
191 - IPS socket buffer size. Max and default value depend on available memory. Can be changed to tune performance.
192 type: int
193 sync_session_ttl:
194 description:
195 - Enable/disable use of kernel session TTL for IPS sessions.
196 type: str
197 choices:
198 - 'enable'
199 - 'disable'
200 tls_active_probe:
201 description:
202 - TLS active probe configuration.
203 type: dict
204 suboptions:
205 interface:
206 description:
207 - Specify outgoing interface to reach server. Source system.interface.name.
208 type: str
209 interface_select_method:
210 description:
211 - Specify how to select outgoing interface to reach server.
212 type: str
213 choices:
214 - 'auto'
215 - 'sdwan'
216 - 'specify'
217 source_ip:
218 description:
219 - Source IP address used for TLS active probe.
220 type: str
221 source_ip6:
222 description:
223 - Source IPv6 address used for TLS active probe.
224 type: str
225 vdom:
226 description:
227 - Virtual domain name for TLS active probe. Source system.vdom.name.
228 type: str
229 traffic_submit:
230 description:
231 - Enable/disable submitting attack data found by this FortiGate to FortiGuard.
232 type: str
233 choices:
234 - 'enable'
235 - 'disable'
236 """
237
238 EXAMPLES = """
239 - name: Configure IPS global parameter.
240 fortinet.fortios.fortios_ips_global:
241 vdom: "{{ vdom }}"
242 ips_global:
243 anomaly_mode: "periodical"
244 av_mem_limit: "0"
245 cp_accel_mode: "none"
246 database: "regular"
247 deep_app_insp_db_limit: "0"
248 deep_app_insp_timeout: "0"
249 engine_count: "0"
250 exclude_signatures: "none"
251 fail_open: "enable"
252 intelligent_mode: "enable"
253 ips_reserve_cpu: "disable"
254 machine_learning_detection: "enable"
255 ngfw_max_scan_range: "4096"
256 np_accel_mode: "none"
257 packet_log_queue_depth: "128"
258 session_limit_mode: "accurate"
259 skype_client_public_ipaddr: "<your_own_value>"
260 socket_size: "128"
261 sync_session_ttl: "enable"
262 tls_active_probe:
263 interface: "<your_own_value> (source system.interface.name)"
264 interface_select_method: "auto"
265 source_ip: "84.230.14.43"
266 source_ip6: "<your_own_value>"
267 vdom: "<your_own_value> (source system.vdom.name)"
268 traffic_submit: "enable"
269 """
270
271 RETURN = """
272 build:
273 description: Build number of the fortigate image
274 returned: always
275 type: str
276 sample: '1547'
277 http_method:
278 description: Last method used to provision the content into FortiGate
279 returned: always
280 type: str
281 sample: 'PUT'
282 http_status:
283 description: Last result given by FortiGate on last operation applied
284 returned: always
285 type: str
286 sample: "200"
287 mkey:
288 description: Master key (id) used in the last call to FortiGate
289 returned: success
290 type: str
291 sample: "id"
292 name:
293 description: Name of the table used to fulfill the request
294 returned: always
295 type: str
296 sample: "urlfilter"
297 path:
298 description: Path of the table used to fulfill the request
299 returned: always
300 type: str
301 sample: "webfilter"
302 revision:
303 description: Internal revision number
304 returned: always
305 type: str
306 sample: "17.0.2.10658"
307 serial:
308 description: Serial number of the unit
309 returned: always
310 type: str
311 sample: "FGVMEVYYQT3AB5352"
312 status:
313 description: Indication of the operation's result
314 returned: always
315 type: str
316 sample: "success"
317 vdom:
318 description: Virtual domain used
319 returned: always
320 type: str
321 sample: "root"
322 version:
323 description: Version of the FortiGate
324 returned: always
325 type: str
326 sample: "v5.6.3"
327 """
328 from ansible.module_utils.basic import AnsibleModule
329 from ansible.module_utils.connection import Connection
330 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
331 FortiOSHandler,
332 )
333 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
334 check_legacy_fortiosapi,
335 )
336 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
337 schema_to_module_spec,
338 )
339 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
340 check_schema_versioning,
341 )
342 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
343 FAIL_SOCKET_MSG,
344 )
345 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
346 remove_invalid_fields,
347 )
348 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
349 is_same_comparison,
350 )
351 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
352 serialize,
353 )
354 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
355 find_current_values,
356 )
357 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
358 unify_data_format,
359 )
360
361
362 def filter_ips_global_data(json):
363 option_list = [
364 "anomaly_mode",
365 "av_mem_limit",
366 "cp_accel_mode",
367 "database",
368 "deep_app_insp_db_limit",
369 "deep_app_insp_timeout",
370 "engine_count",
371 "exclude_signatures",
372 "fail_open",
373 "intelligent_mode",
374 "ips_reserve_cpu",
375 "machine_learning_detection",
376 "ngfw_max_scan_range",
377 "np_accel_mode",
378 "packet_log_queue_depth",
379 "session_limit_mode",
380 "skype_client_public_ipaddr",
381 "socket_size",
382 "sync_session_ttl",
383 "tls_active_probe",
384 "traffic_submit",
385 ]
386
387 json = remove_invalid_fields(json)
388 dictionary = {}
389
390 for attribute in option_list:
391 if attribute in json and json[attribute] is not None:
392 dictionary[attribute] = json[attribute]
393
394 return dictionary
395
396
397 def underscore_to_hyphen(data):
398 new_data = None
399 if isinstance(data, list):
400 new_data = []
401 for i, elem in enumerate(data):
402 new_data.append(underscore_to_hyphen(elem))
403 elif isinstance(data, dict):
404 new_data = {}
405 for k, v in data.items():
406 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
407 else:
408 return data
409 return new_data
410
411
412 def ips_global(data, fos, check_mode=False):
413
414 state = None
415 vdom = data["vdom"]
416 parameters = None
417 state = data.get("state", None)
418 ips_global_data = data["ips_global"]
419
420 filtered_data = filter_ips_global_data(ips_global_data)
421 converted_data = underscore_to_hyphen(filtered_data)
422
423 # check_mode starts from here
424 if check_mode:
425 diff = {
426 "before": "",
427 "after": filtered_data,
428 }
429 mkeyname = fos.get_mkeyname(None, None)
430 mkey = fos.get_mkey("ips", "global", filtered_data, vdom=vdom)
431 current_data = fos.get(
432 "ips", "global", vdom=vdom, mkey=mkey, parameters=parameters
433 )
434 is_existed = (
435 current_data
436 and current_data.get("http_status") == 200
437 and (
438 mkeyname
439 and isinstance(current_data.get("results"), list)
440 and len(current_data["results"]) > 0
441 or not mkeyname
442 and current_data["results"] # global object response
443 )
444 )
445
446 # 2. if it exists and the state is 'present' then compare current settings with desired
447 if state == "present" or state is True or state is None:
448 # for non global modules, mkeyname must exist and it's a new module when mkey is None
449 if mkeyname is not None and mkey is None:
450 return False, True, filtered_data, diff
451
452 # if mkey exists then compare each other
453 # record exits and they're matched or not
454 copied_filtered_data = filtered_data.copy()
455 copied_filtered_data.pop(mkeyname, None)
456 unified_filtered_data = unify_data_format(copied_filtered_data)
457
458 current_data_results = current_data.get("results", {})
459 current_config = (
460 current_data_results[0]
461 if mkeyname
462 and isinstance(current_data_results, list)
463 and len(current_data_results) > 0
464 else current_data_results
465 )
466 if is_existed:
467 unified_current_values = find_current_values(
468 unified_filtered_data,
469 unify_data_format(current_config),
470 )
471
472 is_same = is_same_comparison(
473 serialize(unified_current_values), serialize(unified_filtered_data)
474 )
475
476 return (
477 False,
478 not is_same,
479 filtered_data,
480 {"before": unified_current_values, "after": unified_filtered_data},
481 )
482
483 # record does not exist
484 return False, True, filtered_data, diff
485
486 if state == "absent":
487 if mkey is None:
488 return (
489 False,
490 False,
491 filtered_data,
492 {"before": current_data["results"][0], "after": ""},
493 )
494
495 if is_existed:
496 return (
497 False,
498 True,
499 filtered_data,
500 {"before": current_data["results"][0], "after": ""},
501 )
502 return False, False, filtered_data, {}
503
504 return True, False, {"reason: ": "Must provide state parameter"}, {}
505 # pass post processed data to member operations
506 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
507 data_copy = data.copy()
508 data_copy["ips_global"] = filtered_data
509 fos.do_member_operation(
510 "ips",
511 "global",
512 data_copy,
513 )
514
515 return fos.set(
516 "ips", "global", data=converted_data, vdom=vdom, parameters=parameters
517 )
518
519
520 def is_successful_status(resp):
521 return (
522 "status" in resp
523 and resp["status"] == "success"
524 or "http_status" in resp
525 and resp["http_status"] == 200
526 or "http_method" in resp
527 and resp["http_method"] == "DELETE"
528 and resp["http_status"] == 404
529 )
530
531
532 def fortios_ips(data, fos, check_mode):
533
534 if data["ips_global"]:
535 resp = ips_global(data, fos, check_mode)
536 else:
537 fos._module.fail_json(msg="missing task body: %s" % ("ips_global"))
538 if isinstance(resp, tuple) and len(resp) == 4:
539 return resp
540 return (
541 not is_successful_status(resp),
542 is_successful_status(resp)
543 and (resp["revision_changed"] if "revision_changed" in resp else True),
544 resp,
545 {},
546 )
547
548
549 versioned_schema = {
550 "v_range": [["v6.0.0", ""]],
551 "type": "dict",
552 "children": {
553 "fail_open": {
554 "v_range": [["v6.0.0", ""]],
555 "type": "string",
556 "options": [{"value": "enable"}, {"value": "disable"}],
557 },
558 "database": {
559 "v_range": [["v6.0.0", ""]],
560 "type": "string",
561 "options": [{"value": "regular"}, {"value": "extended"}],
562 },
563 "traffic_submit": {
564 "v_range": [["v6.0.0", ""]],
565 "type": "string",
566 "options": [{"value": "enable"}, {"value": "disable"}],
567 },
568 "anomaly_mode": {
569 "v_range": [["v6.0.0", ""]],
570 "type": "string",
571 "options": [{"value": "periodical"}, {"value": "continuous"}],
572 },
573 "session_limit_mode": {
574 "v_range": [["v6.0.0", ""]],
575 "type": "string",
576 "options": [{"value": "accurate"}, {"value": "heuristic"}],
577 },
578 "socket_size": {"v_range": [["v6.0.0", ""]], "type": "integer"},
579 "engine_count": {"v_range": [["v6.0.0", ""]], "type": "integer"},
580 "sync_session_ttl": {
581 "v_range": [["v6.0.0", ""]],
582 "type": "string",
583 "options": [{"value": "enable"}, {"value": "disable"}],
584 },
585 "np_accel_mode": {
586 "v_range": [["v6.0.0", ""]],
587 "type": "string",
588 "options": [{"value": "none"}, {"value": "basic"}],
589 },
590 "ips_reserve_cpu": {
591 "v_range": [["v6.0.0", "v7.4.1"], ["v7.4.3", ""]],
592 "type": "string",
593 "options": [{"value": "disable"}, {"value": "enable"}],
594 },
595 "cp_accel_mode": {
596 "v_range": [["v6.0.0", ""]],
597 "type": "string",
598 "options": [{"value": "none"}, {"value": "basic"}, {"value": "advanced"}],
599 },
600 "deep_app_insp_timeout": {"v_range": [["v6.0.0", ""]], "type": "integer"},
601 "deep_app_insp_db_limit": {"v_range": [["v6.0.0", ""]], "type": "integer"},
602 "exclude_signatures": {
603 "v_range": [["v6.0.0", ""]],
604 "type": "string",
605 "options": [
606 {"value": "none"},
607 {"value": "ot", "v_range": [["v7.4.1", ""]]},
608 {"value": "industrial", "v_range": [["v6.0.0", "v7.4.0"]]},
609 ],
610 },
611 "packet_log_queue_depth": {"v_range": [["v6.2.7", ""]], "type": "integer"},
612 "ngfw_max_scan_range": {"v_range": [["v6.4.4", ""]], "type": "integer"},
613 "av_mem_limit": {"v_range": [["v7.4.2", ""]], "type": "integer"},
614 "machine_learning_detection": {
615 "v_range": [["v7.6.3", ""]],
616 "type": "string",
617 "options": [{"value": "enable"}, {"value": "disable"}],
618 },
619 "tls_active_probe": {
620 "v_range": [["v6.2.7", "v6.2.7"], ["v6.4.4", ""]],
621 "type": "dict",
622 "children": {
623 "interface_select_method": {
624 "v_range": [["v6.2.7", "v6.2.7"], ["v6.4.4", ""]],
625 "type": "string",
626 "options": [
627 {"value": "auto"},
628 {"value": "sdwan"},
629 {"value": "specify"},
630 ],
631 },
632 "interface": {
633 "v_range": [["v6.2.7", "v6.2.7"], ["v6.4.4", ""]],
634 "type": "string",
635 },
636 "vdom": {
637 "v_range": [["v6.2.7", "v6.2.7"], ["v6.4.4", ""]],
638 "type": "string",
639 },
640 "source_ip": {
641 "v_range": [["v6.2.7", "v6.2.7"], ["v6.4.4", ""]],
642 "type": "string",
643 },
644 "source_ip6": {
645 "v_range": [["v6.2.7", "v6.2.7"], ["v6.4.4", ""]],
646 "type": "string",
647 },
648 },
649 },
650 "intelligent_mode": {
651 "v_range": [["v6.0.0", "v6.4.1"]],
652 "type": "string",
653 "options": [{"value": "enable"}, {"value": "disable"}],
654 },
655 "skype_client_public_ipaddr": {
656 "v_range": [["v6.0.0", "v6.2.7"]],
657 "type": "string",
658 },
659 },
660 }
661
662
663 def main():
664 module_spec = schema_to_module_spec(versioned_schema)
665 mkeyname = None
666 fields = {
667 "access_token": {"required": False, "type": "str", "no_log": True},
668 "enable_log": {"required": False, "type": "bool", "default": False},
669 "vdom": {"required": False, "type": "str", "default": "root"},
670 "member_path": {"required": False, "type": "str"},
671 "member_state": {
672 "type": "str",
673 "required": False,
674 "choices": ["present", "absent"],
675 },
676 "ips_global": {
677 "required": False,
678 "type": "dict",
679 "default": None,
680 "options": {},
681 },
682 }
683 for attribute_name in module_spec["options"]:
684 fields["ips_global"]["options"][attribute_name] = module_spec["options"][
685 attribute_name
686 ]
687 if mkeyname and mkeyname == attribute_name:
688 fields["ips_global"]["options"][attribute_name]["required"] = True
689
690 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
691 check_legacy_fortiosapi(module)
692
693 is_error = False
694 has_changed = False
695 result = None
696 diff = None
697
698 versions_check_result = None
699 if module._socket_path:
700 connection = Connection(module._socket_path)
701 if "access_token" in module.params:
702 connection.set_custom_option("access_token", module.params["access_token"])
703
704 if "enable_log" in module.params:
705 connection.set_custom_option("enable_log", module.params["enable_log"])
706 else:
707 connection.set_custom_option("enable_log", False)
708 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
709 versions_check_result = check_schema_versioning(
710 fos, versioned_schema, "ips_global"
711 )
712
713 is_error, has_changed, result, diff = fortios_ips(
714 module.params, fos, module.check_mode
715 )
716
717 else:
718 module.fail_json(**FAIL_SOCKET_MSG)
719
720 if versions_check_result and versions_check_result["matched"] is False:
721 module.warn(
722 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
723 )
724
725 if not is_error:
726 if versions_check_result and versions_check_result["matched"] is False:
727 module.exit_json(
728 changed=has_changed,
729 version_check_warning=versions_check_result,
730 meta=result,
731 diff=diff,
732 )
733 else:
734 module.exit_json(changed=has_changed, meta=result, diff=diff)
735 else:
736 if versions_check_result and versions_check_result["matched"] is False:
737 module.fail_json(
738 msg="Error in repo",
739 version_check_warning=versions_check_result,
740 meta=result,
741 )
742 else:
743 module.fail_json(msg="Error in repo", meta=result)
744
745
746 if __name__ == "__main__":
747 main()