Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_authentication_rule.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_authentication_rule
23 short_description: Configure Authentication Rules 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 authentication feature and rule 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 state:
80 description:
81 - Indicates whether to create or remove the object.
82 type: str
83 required: true
84 choices:
85 - 'present'
86 - 'absent'
87 authentication_rule:
88 description:
89 - Configure Authentication Rules.
90 default: null
91 type: dict
92 suboptions:
93 active_auth_method:
94 description:
95 - Select an active authentication method. Source authentication.scheme.name.
96 type: str
97 cert_auth_cookie:
98 description:
99 - Enable/disable to use device certificate as authentication cookie .
100 type: str
101 choices:
102 - 'enable'
103 - 'disable'
104 comments:
105 description:
106 - Comment.
107 type: str
108 cors_depth:
109 description:
110 - Depth to allow CORS access .
111 type: int
112 cors_stateful:
113 description:
114 - Enable/disable allowance of CORS access .
115 type: str
116 choices:
117 - 'enable'
118 - 'disable'
119 dstaddr:
120 description:
121 - Select an IPv4 destination address from available options. Required for web proxy authentication.
122 type: list
123 elements: dict
124 suboptions:
125 name:
126 description:
127 - Address name. Source firewall.address.name firewall.addrgrp.name firewall.proxy-address.name firewall.proxy-addrgrp.name system
128 .external-resource.name.
129 required: true
130 type: str
131 dstaddr6:
132 description:
133 - Select an IPv6 destination address from available options. Required for web proxy authentication.
134 type: list
135 elements: dict
136 suboptions:
137 name:
138 description:
139 - Address name. Source firewall.address6.name firewall.addrgrp6.name.
140 required: true
141 type: str
142 ip_based:
143 description:
144 - Enable/disable IP-based authentication. When enabled, previously authenticated users from the same IP address will be exempted.
145 type: str
146 choices:
147 - 'enable'
148 - 'disable'
149 name:
150 description:
151 - Authentication rule name.
152 required: true
153 type: str
154 protocol:
155 description:
156 - Authentication is required for the selected protocol .
157 type: str
158 choices:
159 - 'http'
160 - 'ftp'
161 - 'socks'
162 - 'ssh'
163 - 'ztna-portal'
164 session_logout:
165 description:
166 - Enable/disable logout of a user from the current session.
167 type: str
168 choices:
169 - 'enable'
170 - 'disable'
171 srcaddr:
172 description:
173 - Authentication is required for the selected IPv4 source address.
174 type: list
175 elements: dict
176 suboptions:
177 name:
178 description:
179 - Address name. Source firewall.address.name firewall.addrgrp.name firewall.proxy-address.name firewall.proxy-addrgrp.name system
180 .external-resource.name.
181 required: true
182 type: str
183 srcaddr6:
184 description:
185 - Authentication is required for the selected IPv6 source address.
186 type: list
187 elements: dict
188 suboptions:
189 name:
190 description:
191 - Address name. Source firewall.address6.name firewall.addrgrp6.name.
192 required: true
193 type: str
194 srcintf:
195 description:
196 - Incoming (ingress) interface.
197 type: list
198 elements: dict
199 suboptions:
200 name:
201 description:
202 - Interface name. Source system.interface.name system.zone.name system.sdwan.zone.name.
203 required: true
204 type: str
205 sso_auth_method:
206 description:
207 - Select a single-sign on (SSO) authentication method. Source authentication.scheme.name.
208 type: str
209 status:
210 description:
211 - Enable/disable this authentication rule.
212 type: str
213 choices:
214 - 'enable'
215 - 'disable'
216 transaction_based:
217 description:
218 - Enable/disable transaction based authentication .
219 type: str
220 choices:
221 - 'enable'
222 - 'disable'
223 web_auth_cookie:
224 description:
225 - Enable/disable Web authentication cookies .
226 type: str
227 choices:
228 - 'enable'
229 - 'disable'
230 web_portal:
231 description:
232 - Enable/disable web portal for proxy transparent policy .
233 type: str
234 choices:
235 - 'enable'
236 - 'disable'
237 """
238
239 EXAMPLES = """
240 - name: Configure Authentication Rules.
241 fortinet.fortios.fortios_authentication_rule:
242 vdom: "{{ vdom }}"
243 state: "present"
244 access_token: "<your_own_value>"
245 authentication_rule:
246 active_auth_method: "<your_own_value> (source authentication.scheme.name)"
247 cert_auth_cookie: "enable"
248 comments: "<your_own_value>"
249 cors_depth: "3"
250 cors_stateful: "enable"
251 dstaddr:
252 -
253 name: "default_name_9 (source firewall.address.name firewall.addrgrp.name firewall.proxy-address.name firewall.proxy-addrgrp.name system
254 .external-resource.name)"
255 dstaddr6:
256 -
257 name: "default_name_11 (source firewall.address6.name firewall.addrgrp6.name)"
258 ip_based: "enable"
259 name: "default_name_13"
260 protocol: "http"
261 session_logout: "enable"
262 srcaddr:
263 -
264 name: "default_name_17 (source firewall.address.name firewall.addrgrp.name firewall.proxy-address.name firewall.proxy-addrgrp.name system
265 .external-resource.name)"
266 srcaddr6:
267 -
268 name: "default_name_19 (source firewall.address6.name firewall.addrgrp6.name)"
269 srcintf:
270 -
271 name: "default_name_21 (source system.interface.name system.zone.name system.sdwan.zone.name)"
272 sso_auth_method: "<your_own_value> (source authentication.scheme.name)"
273 status: "enable"
274 transaction_based: "enable"
275 web_auth_cookie: "enable"
276 web_portal: "enable"
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_authentication_rule_data(json):
371 option_list = [
372 "active_auth_method",
373 "cert_auth_cookie",
374 "comments",
375 "cors_depth",
376 "cors_stateful",
377 "dstaddr",
378 "dstaddr6",
379 "ip_based",
380 "name",
381 "protocol",
382 "session_logout",
383 "srcaddr",
384 "srcaddr6",
385 "srcintf",
386 "sso_auth_method",
387 "status",
388 "transaction_based",
389 "web_auth_cookie",
390 "web_portal",
391 ]
392
393 json = remove_invalid_fields(json)
394 dictionary = {}
395
396 for attribute in option_list:
397 if attribute in json and json[attribute] is not None:
398 dictionary[attribute] = json[attribute]
399
400 return dictionary
401
402
403 def underscore_to_hyphen(data):
404 new_data = None
405 if isinstance(data, list):
406 new_data = []
407 for i, elem in enumerate(data):
408 new_data.append(underscore_to_hyphen(elem))
409 elif isinstance(data, dict):
410 new_data = {}
411 for k, v in data.items():
412 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
413 else:
414 return data
415 return new_data
416
417
418 def authentication_rule(data, fos, check_mode=False):
419
420 state = None
421 vdom = data["vdom"]
422 parameters = None
423 state = data.get("state", None)
424 authentication_rule_data = data["authentication_rule"]
425
426 filtered_data = filter_authentication_rule_data(authentication_rule_data)
427 converted_data = underscore_to_hyphen(filtered_data)
428
429 # check_mode starts from here
430 if check_mode:
431 diff = {
432 "before": "",
433 "after": filtered_data,
434 }
435 mkeyname = fos.get_mkeyname(None, None)
436 mkey = fos.get_mkey("authentication", "rule", filtered_data, vdom=vdom)
437 current_data = fos.get(
438 "authentication", "rule", vdom=vdom, mkey=mkey, parameters=parameters
439 )
440 is_existed = (
441 current_data
442 and current_data.get("http_status") == 200
443 and (
444 mkeyname
445 and isinstance(current_data.get("results"), list)
446 and len(current_data["results"]) > 0
447 or not mkeyname
448 and current_data["results"] # global object response
449 )
450 )
451
452 # 2. if it exists and the state is 'present' then compare current settings with desired
453 if state == "present" or state is True or state is None:
454 # for non global modules, mkeyname must exist and it's a new module when mkey is None
455 if mkeyname is not None and mkey is None:
456 return False, True, filtered_data, diff
457
458 # if mkey exists then compare each other
459 # record exits and they're matched or not
460 copied_filtered_data = filtered_data.copy()
461 copied_filtered_data.pop(mkeyname, None)
462 unified_filtered_data = unify_data_format(copied_filtered_data)
463
464 current_data_results = current_data.get("results", {})
465 current_config = (
466 current_data_results[0]
467 if mkeyname
468 and isinstance(current_data_results, list)
469 and len(current_data_results) > 0
470 else current_data_results
471 )
472 if is_existed:
473 unified_current_values = find_current_values(
474 unified_filtered_data,
475 unify_data_format(current_config),
476 )
477
478 is_same = is_same_comparison(
479 serialize(unified_current_values), serialize(unified_filtered_data)
480 )
481
482 return (
483 False,
484 not is_same,
485 filtered_data,
486 {"before": unified_current_values, "after": unified_filtered_data},
487 )
488
489 # record does not exist
490 return False, True, filtered_data, diff
491
492 if state == "absent":
493 if mkey is None:
494 return (
495 False,
496 False,
497 filtered_data,
498 {"before": current_data["results"][0], "after": ""},
499 )
500
501 if is_existed:
502 return (
503 False,
504 True,
505 filtered_data,
506 {"before": current_data["results"][0], "after": ""},
507 )
508 return False, False, filtered_data, {}
509
510 return True, False, {"reason: ": "Must provide state parameter"}, {}
511 # pass post processed data to member operations
512 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
513 data_copy = data.copy()
514 data_copy["authentication_rule"] = filtered_data
515 fos.do_member_operation(
516 "authentication",
517 "rule",
518 data_copy,
519 )
520
521 if state == "present" or state is True:
522 return fos.set(
523 "authentication",
524 "rule",
525 data=converted_data,
526 vdom=vdom,
527 parameters=parameters,
528 )
529
530 elif state == "absent":
531 return fos.delete(
532 "authentication",
533 "rule",
534 mkey=converted_data["name"],
535 vdom=vdom,
536 parameters=parameters,
537 )
538 else:
539 fos._module.fail_json(msg="state must be present or absent!")
540
541
542 def is_successful_status(resp):
543 return (
544 "status" in resp
545 and resp["status"] == "success"
546 or "http_status" in resp
547 and resp["http_status"] == 200
548 or "http_method" in resp
549 and resp["http_method"] == "DELETE"
550 and resp["http_status"] == 404
551 )
552
553
554 def fortios_authentication(data, fos, check_mode):
555
556 if data["authentication_rule"]:
557 resp = authentication_rule(data, fos, check_mode)
558 else:
559 fos._module.fail_json(msg="missing task body: %s" % ("authentication_rule"))
560 if isinstance(resp, tuple) and len(resp) == 4:
561 return resp
562 return (
563 not is_successful_status(resp),
564 is_successful_status(resp)
565 and (resp["revision_changed"] if "revision_changed" in resp else True),
566 resp,
567 {},
568 )
569
570
571 versioned_schema = {
572 "type": "list",
573 "elements": "dict",
574 "children": {
575 "name": {"v_range": [["v6.0.0", ""]], "type": "string", "required": True},
576 "status": {
577 "v_range": [["v6.0.0", ""]],
578 "type": "string",
579 "options": [{"value": "enable"}, {"value": "disable"}],
580 },
581 "protocol": {
582 "v_range": [["v6.0.0", ""]],
583 "type": "string",
584 "options": [
585 {"value": "http"},
586 {"value": "ftp"},
587 {"value": "socks"},
588 {"value": "ssh"},
589 {"value": "ztna-portal", "v_range": [["v7.6.1", ""]]},
590 ],
591 },
592 "srcintf": {
593 "type": "list",
594 "elements": "dict",
595 "children": {
596 "name": {
597 "v_range": [["v7.0.0", ""]],
598 "type": "string",
599 "required": True,
600 }
601 },
602 "v_range": [["v7.0.0", ""]],
603 },
604 "srcaddr": {
605 "type": "list",
606 "elements": "dict",
607 "children": {
608 "name": {
609 "v_range": [["v6.0.0", ""]],
610 "type": "string",
611 "required": True,
612 }
613 },
614 "v_range": [["v6.0.0", ""]],
615 },
616 "dstaddr": {
617 "type": "list",
618 "elements": "dict",
619 "children": {
620 "name": {
621 "v_range": [["v7.0.0", ""]],
622 "type": "string",
623 "required": True,
624 }
625 },
626 "v_range": [["v7.0.0", ""]],
627 },
628 "srcaddr6": {
629 "type": "list",
630 "elements": "dict",
631 "children": {
632 "name": {
633 "v_range": [["v6.0.0", ""]],
634 "type": "string",
635 "required": True,
636 }
637 },
638 "v_range": [["v6.0.0", ""]],
639 },
640 "dstaddr6": {
641 "type": "list",
642 "elements": "dict",
643 "children": {
644 "name": {
645 "v_range": [["v7.0.0", ""]],
646 "type": "string",
647 "required": True,
648 }
649 },
650 "v_range": [["v7.0.0", ""]],
651 },
652 "ip_based": {
653 "v_range": [["v6.0.0", ""]],
654 "type": "string",
655 "options": [{"value": "enable"}, {"value": "disable"}],
656 },
657 "active_auth_method": {"v_range": [["v6.0.0", ""]], "type": "string"},
658 "sso_auth_method": {"v_range": [["v6.0.0", ""]], "type": "string"},
659 "web_auth_cookie": {
660 "v_range": [["v6.0.0", ""]],
661 "type": "string",
662 "options": [{"value": "enable"}, {"value": "disable"}],
663 },
664 "cors_stateful": {
665 "v_range": [["v7.4.1", ""]],
666 "type": "string",
667 "options": [{"value": "enable"}, {"value": "disable"}],
668 },
669 "cors_depth": {"v_range": [["v7.4.1", ""]], "type": "integer"},
670 "cert_auth_cookie": {
671 "v_range": [["v7.4.4", ""]],
672 "type": "string",
673 "options": [{"value": "enable"}, {"value": "disable"}],
674 },
675 "transaction_based": {
676 "v_range": [["v6.0.0", ""]],
677 "type": "string",
678 "options": [{"value": "enable"}, {"value": "disable"}],
679 },
680 "web_portal": {
681 "v_range": [["v6.2.0", ""]],
682 "type": "string",
683 "options": [{"value": "enable"}, {"value": "disable"}],
684 },
685 "comments": {"v_range": [["v6.0.0", ""]], "type": "string"},
686 "session_logout": {
687 "v_range": [["v7.6.5", ""]],
688 "type": "string",
689 "options": [{"value": "enable"}, {"value": "disable"}],
690 },
691 },
692 "v_range": [["v6.0.0", ""]],
693 }
694
695
696 def main():
697 module_spec = schema_to_module_spec(versioned_schema)
698 mkeyname = "name"
699 fields = {
700 "access_token": {"required": False, "type": "str", "no_log": True},
701 "enable_log": {"required": False, "type": "bool", "default": False},
702 "vdom": {"required": False, "type": "str", "default": "root"},
703 "member_path": {"required": False, "type": "str"},
704 "member_state": {
705 "type": "str",
706 "required": False,
707 "choices": ["present", "absent"],
708 },
709 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
710 "authentication_rule": {
711 "required": False,
712 "type": "dict",
713 "default": None,
714 "options": {},
715 },
716 }
717 for attribute_name in module_spec["options"]:
718 fields["authentication_rule"]["options"][attribute_name] = module_spec[
719 "options"
720 ][attribute_name]
721 if mkeyname and mkeyname == attribute_name:
722 fields["authentication_rule"]["options"][attribute_name]["required"] = True
723
724 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
725 check_legacy_fortiosapi(module)
726
727 is_error = False
728 has_changed = False
729 result = None
730 diff = None
731
732 versions_check_result = None
733 if module._socket_path:
734 connection = Connection(module._socket_path)
735 if "access_token" in module.params:
736 connection.set_custom_option("access_token", module.params["access_token"])
737
738 if "enable_log" in module.params:
739 connection.set_custom_option("enable_log", module.params["enable_log"])
740 else:
741 connection.set_custom_option("enable_log", False)
742 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
743 versions_check_result = check_schema_versioning(
744 fos, versioned_schema, "authentication_rule"
745 )
746
747 is_error, has_changed, result, diff = fortios_authentication(
748 module.params, fos, module.check_mode
749 )
750
751 else:
752 module.fail_json(**FAIL_SOCKET_MSG)
753
754 if versions_check_result and versions_check_result["matched"] is False:
755 module.warn(
756 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
757 )
758
759 if not is_error:
760 if versions_check_result and versions_check_result["matched"] is False:
761 module.exit_json(
762 changed=has_changed,
763 version_check_warning=versions_check_result,
764 meta=result,
765 diff=diff,
766 )
767 else:
768 module.exit_json(changed=has_changed, meta=result, diff=diff)
769 else:
770 if versions_check_result and versions_check_result["matched"] is False:
771 module.fail_json(
772 msg="Error in repo",
773 version_check_warning=versions_check_result,
774 meta=result,
775 )
776 else:
777 module.fail_json(msg="Error in repo", meta=result)
778
779
780 if __name__ == "__main__":
781 main()