Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_firewall_policy46.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_firewall_policy46
23 short_description: Configure IPv4 to IPv6 policies 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 firewall feature and policy46 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 - We highly recommend using your own value as the policyid instead of 0, while '0' is a special placeholder that allows the backend to assign the latest
39 available number for the object, it does have limitations. Please find more details in Q&A.
40 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
41
42 - The module supports check_mode.
43
44 requirements:
45 - ansible>=2.16
46 options:
47 access_token:
48 description:
49 - Token-based authentication.
50 Generated from GUI of Fortigate.
51 type: str
52 required: false
53 enable_log:
54 description:
55 - Enable/Disable logging for task.
56 type: bool
57 required: false
58 default: false
59 vdom:
60 description:
61 - Virtual domain, among those defined previously. A vdom is a
62 virtual instance of the FortiGate that can be configured and
63 used as a different unit.
64 type: str
65 default: root
66 member_path:
67 type: str
68 description:
69 - Member attribute path to operate on.
70 - Delimited by a slash character if there are more than one attribute.
71 - Parameter marked with member_path is legitimate for doing member operation.
72 member_state:
73 type: str
74 description:
75 - Add or delete a member under specified attribute path.
76 - When member_state is specified, the state option is ignored.
77 choices:
78 - 'present'
79 - 'absent'
80
81 state:
82 description:
83 - Indicates whether to create or remove the object.
84 type: str
85 required: true
86 choices:
87 - 'present'
88 - 'absent'
89 firewall_policy46:
90 description:
91 - Configure IPv4 to IPv6 policies.
92 default: null
93 type: dict
94 suboptions:
95 action:
96 description:
97 - Accept or deny traffic matching the policy.
98 type: str
99 choices:
100 - 'accept'
101 - 'deny'
102 comments:
103 description:
104 - Comment.
105 type: str
106 dstaddr:
107 description:
108 - Destination address objects.
109 type: list
110 elements: dict
111 suboptions:
112 name:
113 description:
114 - Address name. Source firewall.vip46.name firewall.vipgrp46.name.
115 required: true
116 type: str
117 dstintf:
118 description:
119 - Destination interface name. Source system.interface.name system.zone.name.
120 type: str
121 fixedport:
122 description:
123 - Enable/disable fixed port for this policy.
124 type: str
125 choices:
126 - 'enable'
127 - 'disable'
128 ippool:
129 description:
130 - Enable/disable use of IP Pools for source NAT.
131 type: str
132 choices:
133 - 'enable'
134 - 'disable'
135 logtraffic:
136 description:
137 - Enable/disable traffic logging for this policy.
138 type: str
139 choices:
140 - 'enable'
141 - 'disable'
142 logtraffic_start:
143 description:
144 - Record logs when a session starts and ends.
145 type: str
146 choices:
147 - 'enable'
148 - 'disable'
149 name:
150 description:
151 - Policy name.
152 type: str
153 per_ip_shaper:
154 description:
155 - Per IP traffic shaper. Source firewall.shaper.per-ip-shaper.name.
156 type: str
157 permit_any_host:
158 description:
159 - Enable/disable allowing any host.
160 type: str
161 choices:
162 - 'enable'
163 - 'disable'
164 policyid:
165 description:
166 - Policy ID (0 - 4294967294). see <a href='#notes'>Notes</a>.
167 required: true
168 type: int
169 poolname:
170 description:
171 - IP Pool names.
172 type: list
173 elements: dict
174 suboptions:
175 name:
176 description:
177 - IP pool name. Source firewall.ippool6.name.
178 required: true
179 type: str
180 schedule:
181 description:
182 - Schedule name. Source firewall.schedule.onetime.name firewall.schedule.recurring.name firewall.schedule.group.name.
183 type: str
184 service:
185 description:
186 - Service name.
187 type: list
188 elements: dict
189 suboptions:
190 name:
191 description:
192 - Service name. Source firewall.service.custom.name firewall.service.group.name.
193 required: true
194 type: str
195 srcaddr:
196 description:
197 - Source address objects.
198 type: list
199 elements: dict
200 suboptions:
201 name:
202 description:
203 - Address name. Source firewall.address.name firewall.addrgrp.name.
204 required: true
205 type: str
206 srcintf:
207 description:
208 - Source interface name. Source system.zone.name system.interface.name.
209 type: str
210 status:
211 description:
212 - Enable/disable this policy.
213 type: str
214 choices:
215 - 'enable'
216 - 'disable'
217 tcp_mss_receiver:
218 description:
219 - TCP Maximum Segment Size value of receiver (0 - 65535)
220 type: int
221 tcp_mss_sender:
222 description:
223 - TCP Maximum Segment Size value of sender (0 - 65535).
224 type: int
225 traffic_shaper:
226 description:
227 - Traffic shaper. Source firewall.shaper.traffic-shaper.name.
228 type: str
229 traffic_shaper_reverse:
230 description:
231 - Reverse traffic shaper. Source firewall.shaper.traffic-shaper.name.
232 type: str
233 uuid:
234 description:
235 - Universally Unique Identifier (UUID; automatically assigned but can be manually reset).
236 type: str
237 """
238
239 EXAMPLES = """
240 - name: Configure IPv4 to IPv6 policies.
241 fortinet.fortios.fortios_firewall_policy46:
242 vdom: "{{ vdom }}"
243 state: "present"
244 access_token: "<your_own_value>"
245 firewall_policy46:
246 action: "accept"
247 comments: "<your_own_value>"
248 dstaddr:
249 -
250 name: "default_name_6 (source firewall.vip46.name firewall.vipgrp46.name)"
251 dstintf: "<your_own_value> (source system.interface.name system.zone.name)"
252 fixedport: "enable"
253 ippool: "enable"
254 logtraffic: "enable"
255 logtraffic_start: "enable"
256 name: "default_name_12"
257 per_ip_shaper: "<your_own_value> (source firewall.shaper.per-ip-shaper.name)"
258 permit_any_host: "enable"
259 policyid: "<you_own_value>"
260 poolname:
261 -
262 name: "default_name_17 (source firewall.ippool6.name)"
263 schedule: "<your_own_value> (source firewall.schedule.onetime.name firewall.schedule.recurring.name firewall.schedule.group.name)"
264 service:
265 -
266 name: "default_name_20 (source firewall.service.custom.name firewall.service.group.name)"
267 srcaddr:
268 -
269 name: "default_name_22 (source firewall.address.name firewall.addrgrp.name)"
270 srcintf: "<your_own_value> (source system.zone.name system.interface.name)"
271 status: "enable"
272 tcp_mss_receiver: "0"
273 tcp_mss_sender: "0"
274 traffic_shaper: "<your_own_value> (source firewall.shaper.traffic-shaper.name)"
275 traffic_shaper_reverse: "<your_own_value> (source firewall.shaper.traffic-shaper.name)"
276 uuid: "<your_own_value>"
277 """
278
279 RETURN = """
280 build:
281 description: Build number of the fortigate image
282 returned: always
283 type: str
284 sample: '1547'
285 http_method:
286 description: Last method used to provision the content into FortiGate
287 returned: always
288 type: str
289 sample: 'PUT'
290 http_status:
291 description: Last result given by FortiGate on last operation applied
292 returned: always
293 type: str
294 sample: "200"
295 mkey:
296 description: Master key (id) used in the last call to FortiGate
297 returned: success
298 type: str
299 sample: "id"
300 name:
301 description: Name of the table used to fulfill the request
302 returned: always
303 type: str
304 sample: "urlfilter"
305 path:
306 description: Path of the table used to fulfill the request
307 returned: always
308 type: str
309 sample: "webfilter"
310 revision:
311 description: Internal revision number
312 returned: always
313 type: str
314 sample: "17.0.2.10658"
315 serial:
316 description: Serial number of the unit
317 returned: always
318 type: str
319 sample: "FGVMEVYYQT3AB5352"
320 status:
321 description: Indication of the operation's result
322 returned: always
323 type: str
324 sample: "success"
325 vdom:
326 description: Virtual domain used
327 returned: always
328 type: str
329 sample: "root"
330 version:
331 description: Version of the FortiGate
332 returned: always
333 type: str
334 sample: "v5.6.3"
335 """
336 from ansible.module_utils.basic import AnsibleModule
337 from ansible.module_utils.connection import Connection
338 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
339 FortiOSHandler,
340 )
341 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
342 check_legacy_fortiosapi,
343 )
344 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
345 schema_to_module_spec,
346 )
347 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
348 check_schema_versioning,
349 )
350 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
351 FAIL_SOCKET_MSG,
352 )
353 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
354 remove_invalid_fields,
355 )
356 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
357 is_same_comparison,
358 )
359 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
360 serialize,
361 )
362 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
363 find_current_values,
364 )
365 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
366 unify_data_format,
367 )
368
369
370 def filter_firewall_policy46_data(json):
371 option_list = [
372 "action",
373 "comments",
374 "dstaddr",
375 "dstintf",
376 "fixedport",
377 "ippool",
378 "logtraffic",
379 "logtraffic_start",
380 "name",
381 "per_ip_shaper",
382 "permit_any_host",
383 "policyid",
384 "poolname",
385 "schedule",
386 "service",
387 "srcaddr",
388 "srcintf",
389 "status",
390 "tcp_mss_receiver",
391 "tcp_mss_sender",
392 "traffic_shaper",
393 "traffic_shaper_reverse",
394 "uuid",
395 ]
396
397 json = remove_invalid_fields(json)
398 dictionary = {}
399
400 for attribute in option_list:
401 if attribute in json and json[attribute] is not None:
402 dictionary[attribute] = json[attribute]
403
404 return dictionary
405
406
407 def underscore_to_hyphen(data):
408 new_data = None
409 if isinstance(data, list):
410 new_data = []
411 for i, elem in enumerate(data):
412 new_data.append(underscore_to_hyphen(elem))
413 elif isinstance(data, dict):
414 new_data = {}
415 for k, v in data.items():
416 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
417 else:
418 return data
419 return new_data
420
421
422 def firewall_policy46(data, fos, check_mode=False):
423
424 state = None
425 vdom = data["vdom"]
426 parameters = None
427 state = data.get("state", None)
428 firewall_policy46_data = data["firewall_policy46"]
429
430 filtered_data = filter_firewall_policy46_data(firewall_policy46_data)
431 converted_data = underscore_to_hyphen(filtered_data)
432
433 # check_mode starts from here
434 if check_mode:
435 diff = {
436 "before": "",
437 "after": filtered_data,
438 }
439 mkeyname = fos.get_mkeyname(None, None)
440 mkey = fos.get_mkey("firewall", "policy46", filtered_data, vdom=vdom)
441 current_data = fos.get(
442 "firewall", "policy46", vdom=vdom, mkey=mkey, parameters=parameters
443 )
444 is_existed = (
445 current_data
446 and current_data.get("http_status") == 200
447 and (
448 mkeyname
449 and isinstance(current_data.get("results"), list)
450 and len(current_data["results"]) > 0
451 or not mkeyname
452 and current_data["results"] # global object response
453 )
454 )
455
456 # 2. if it exists and the state is 'present' then compare current settings with desired
457 if state == "present" or state is True or state is None:
458 # for non global modules, mkeyname must exist and it's a new module when mkey is None
459 if mkeyname is not None and mkey is None:
460 return False, True, filtered_data, diff
461
462 # if mkey exists then compare each other
463 # record exits and they're matched or not
464 copied_filtered_data = filtered_data.copy()
465 copied_filtered_data.pop(mkeyname, None)
466 unified_filtered_data = unify_data_format(copied_filtered_data)
467
468 current_data_results = current_data.get("results", {})
469 current_config = (
470 current_data_results[0]
471 if mkeyname
472 and isinstance(current_data_results, list)
473 and len(current_data_results) > 0
474 else current_data_results
475 )
476 if is_existed:
477 unified_current_values = find_current_values(
478 unified_filtered_data,
479 unify_data_format(current_config),
480 )
481
482 is_same = is_same_comparison(
483 serialize(unified_current_values), serialize(unified_filtered_data)
484 )
485
486 return (
487 False,
488 not is_same,
489 filtered_data,
490 {"before": unified_current_values, "after": unified_filtered_data},
491 )
492
493 # record does not exist
494 return False, True, filtered_data, diff
495
496 if state == "absent":
497 if mkey is None:
498 return (
499 False,
500 False,
501 filtered_data,
502 {"before": current_data["results"][0], "after": ""},
503 )
504
505 if is_existed:
506 return (
507 False,
508 True,
509 filtered_data,
510 {"before": current_data["results"][0], "after": ""},
511 )
512 return False, False, filtered_data, {}
513
514 return True, False, {"reason: ": "Must provide state parameter"}, {}
515 # pass post processed data to member operations
516 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
517 data_copy = data.copy()
518 data_copy["firewall_policy46"] = filtered_data
519 fos.do_member_operation(
520 "firewall",
521 "policy46",
522 data_copy,
523 )
524
525 if state == "present" or state is True:
526 return fos.set(
527 "firewall",
528 "policy46",
529 data=converted_data,
530 vdom=vdom,
531 parameters=parameters,
532 )
533
534 elif state == "absent":
535 return fos.delete(
536 "firewall",
537 "policy46",
538 mkey=converted_data["policyid"],
539 vdom=vdom,
540 parameters=parameters,
541 )
542 else:
543 fos._module.fail_json(msg="state must be present or absent!")
544
545
546 def is_successful_status(resp):
547 return (
548 "status" in resp
549 and resp["status"] == "success"
550 or "http_status" in resp
551 and resp["http_status"] == 200
552 or "http_method" in resp
553 and resp["http_method"] == "DELETE"
554 and resp["http_status"] == 404
555 )
556
557
558 def fortios_firewall(data, fos, check_mode):
559
560 if data["firewall_policy46"]:
561 resp = firewall_policy46(data, fos, check_mode)
562 else:
563 fos._module.fail_json(msg="missing task body: %s" % ("firewall_policy46"))
564 if isinstance(resp, tuple) and len(resp) == 4:
565 return resp
566 return (
567 not is_successful_status(resp),
568 is_successful_status(resp)
569 and (resp["revision_changed"] if "revision_changed" in resp else True),
570 resp,
571 {},
572 )
573
574
575 versioned_schema = {
576 "type": "list",
577 "elements": "dict",
578 "children": {
579 "permit_any_host": {
580 "v_range": [["v6.0.0", "v7.0.0"]],
581 "type": "string",
582 "options": [{"value": "enable"}, {"value": "disable"}],
583 },
584 "policyid": {
585 "v_range": [["v6.0.0", "v7.0.0"]],
586 "type": "integer",
587 "required": True,
588 },
589 "name": {
590 "v_range": [["v6.4.0", "v6.4.0"], ["v6.4.4", "v7.0.0"]],
591 "type": "string",
592 },
593 "uuid": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "string"},
594 "srcintf": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "string"},
595 "dstintf": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "string"},
596 "srcaddr": {
597 "type": "list",
598 "elements": "dict",
599 "children": {
600 "name": {
601 "v_range": [["v6.0.0", "v7.0.0"]],
602 "type": "string",
603 "required": True,
604 }
605 },
606 "v_range": [["v6.0.0", "v7.0.0"]],
607 },
608 "dstaddr": {
609 "type": "list",
610 "elements": "dict",
611 "children": {
612 "name": {
613 "v_range": [["v6.0.0", "v7.0.0"]],
614 "type": "string",
615 "required": True,
616 }
617 },
618 "v_range": [["v6.0.0", "v7.0.0"]],
619 },
620 "action": {
621 "v_range": [["v6.0.0", "v7.0.0"]],
622 "type": "string",
623 "options": [{"value": "accept"}, {"value": "deny"}],
624 },
625 "status": {
626 "v_range": [["v6.0.0", "v7.0.0"]],
627 "type": "string",
628 "options": [{"value": "enable"}, {"value": "disable"}],
629 },
630 "schedule": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "string"},
631 "service": {
632 "type": "list",
633 "elements": "dict",
634 "children": {
635 "name": {
636 "v_range": [["v6.0.0", "v7.0.0"]],
637 "type": "string",
638 "required": True,
639 }
640 },
641 "v_range": [["v6.0.0", "v7.0.0"]],
642 },
643 "logtraffic": {
644 "v_range": [["v6.0.0", "v7.0.0"]],
645 "type": "string",
646 "options": [{"value": "enable"}, {"value": "disable"}],
647 },
648 "logtraffic_start": {
649 "v_range": [["v6.2.0", "v7.0.0"]],
650 "type": "string",
651 "options": [{"value": "enable"}, {"value": "disable"}],
652 },
653 "traffic_shaper": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "string"},
654 "traffic_shaper_reverse": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "string"},
655 "per_ip_shaper": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "string"},
656 "fixedport": {
657 "v_range": [["v6.0.0", "v7.0.0"]],
658 "type": "string",
659 "options": [{"value": "enable"}, {"value": "disable"}],
660 },
661 "tcp_mss_sender": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "integer"},
662 "tcp_mss_receiver": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "integer"},
663 "comments": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "string"},
664 "ippool": {
665 "v_range": [["v6.0.0", "v7.0.0"]],
666 "type": "string",
667 "options": [{"value": "enable"}, {"value": "disable"}],
668 },
669 "poolname": {
670 "type": "list",
671 "elements": "dict",
672 "children": {
673 "name": {
674 "v_range": [["v6.0.0", "v7.0.0"]],
675 "type": "string",
676 "required": True,
677 }
678 },
679 "v_range": [["v6.0.0", "v7.0.0"]],
680 },
681 },
682 "v_range": [["v6.0.0", "v7.0.0"]],
683 }
684
685
686 def main():
687 module_spec = schema_to_module_spec(versioned_schema)
688 mkeyname = "policyid"
689 fields = {
690 "access_token": {"required": False, "type": "str", "no_log": True},
691 "enable_log": {"required": False, "type": "bool", "default": False},
692 "vdom": {"required": False, "type": "str", "default": "root"},
693 "member_path": {"required": False, "type": "str"},
694 "member_state": {
695 "type": "str",
696 "required": False,
697 "choices": ["present", "absent"],
698 },
699 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
700 "firewall_policy46": {
701 "required": False,
702 "type": "dict",
703 "default": None,
704 "options": {},
705 },
706 }
707 for attribute_name in module_spec["options"]:
708 fields["firewall_policy46"]["options"][attribute_name] = module_spec["options"][
709 attribute_name
710 ]
711 if mkeyname and mkeyname == attribute_name:
712 fields["firewall_policy46"]["options"][attribute_name]["required"] = True
713
714 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
715 check_legacy_fortiosapi(module)
716
717 is_error = False
718 has_changed = False
719 result = None
720 diff = None
721
722 versions_check_result = None
723 if module._socket_path:
724 connection = Connection(module._socket_path)
725 if "access_token" in module.params:
726 connection.set_custom_option("access_token", module.params["access_token"])
727
728 if "enable_log" in module.params:
729 connection.set_custom_option("enable_log", module.params["enable_log"])
730 else:
731 connection.set_custom_option("enable_log", False)
732 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
733 versions_check_result = check_schema_versioning(
734 fos, versioned_schema, "firewall_policy46"
735 )
736
737 is_error, has_changed, result, diff = fortios_firewall(
738 module.params, fos, module.check_mode
739 )
740
741 else:
742 module.fail_json(**FAIL_SOCKET_MSG)
743
744 if versions_check_result and versions_check_result["matched"] is False:
745 module.warn(
746 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
747 )
748
749 if not is_error:
750 if versions_check_result and versions_check_result["matched"] is False:
751 module.exit_json(
752 changed=has_changed,
753 version_check_warning=versions_check_result,
754 meta=result,
755 diff=diff,
756 )
757 else:
758 module.exit_json(changed=has_changed, meta=result, diff=diff)
759 else:
760 if versions_check_result and versions_check_result["matched"] is False:
761 module.fail_json(
762 msg="Error in repo",
763 version_check_warning=versions_check_result,
764 meta=result,
765 )
766 else:
767 module.fail_json(msg="Error in repo", meta=result)
768
769
770 if __name__ == "__main__":
771 main()