Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_authentication_scheme.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_scheme
23 short_description: Configure Authentication Schemes 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 scheme 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_scheme:
88 description:
89 - Configure Authentication Schemes.
90 default: null
91 type: dict
92 suboptions:
93 cert_http_header:
94 description:
95 - Enable/disable authentication with user certificate in Client-Cert HTTP header .
96 type: str
97 choices:
98 - 'enable'
99 - 'disable'
100 digest_algo:
101 description:
102 - Digest Authentication Algorithms.
103 type: list
104 elements: str
105 choices:
106 - 'md5'
107 - 'sha-256'
108 digest_rfc2069:
109 description:
110 - Enable/disable support for the deprecated RFC2069 Digest Client (no cnonce field).
111 type: str
112 choices:
113 - 'enable'
114 - 'disable'
115 domain_controller:
116 description:
117 - Domain controller setting. Source user.domain-controller.name.
118 type: str
119 ems_device_owner:
120 description:
121 - Enable/disable SSH public-key authentication with device owner .
122 type: str
123 choices:
124 - 'enable'
125 - 'disable'
126 external_idp:
127 description:
128 - External identity provider configuration. Source user.external-identity-provider.name.
129 type: str
130 fsso_agent_for_ntlm:
131 description:
132 - FSSO agent to use for NTLM authentication. Source user.fsso.name.
133 type: str
134 fsso_guest:
135 description:
136 - Enable/disable user fsso-guest authentication .
137 type: str
138 choices:
139 - 'enable'
140 - 'disable'
141 group_attr_type:
142 description:
143 - Group attribute type used to match SCIM groups .
144 type: str
145 choices:
146 - 'display-name'
147 - 'external-id'
148 kerberos_keytab:
149 description:
150 - Kerberos keytab setting. Source user.krb-keytab.name.
151 type: str
152 method:
153 description:
154 - Authentication methods .
155 type: list
156 elements: str
157 choices:
158 - 'ntlm'
159 - 'basic'
160 - 'digest'
161 - 'form'
162 - 'negotiate'
163 - 'fsso'
164 - 'rsso'
165 - 'ssh-publickey'
166 - 'cert'
167 - 'saml'
168 - 'entra-sso'
169 name:
170 description:
171 - Authentication scheme name.
172 required: true
173 type: str
174 negotiate_ntlm:
175 description:
176 - Enable/disable negotiate authentication for NTLM .
177 type: str
178 choices:
179 - 'enable'
180 - 'disable'
181 require_tfa:
182 description:
183 - Enable/disable two-factor authentication .
184 type: str
185 choices:
186 - 'enable'
187 - 'disable'
188 saml_server:
189 description:
190 - SAML configuration. Source user.saml.name.
191 type: str
192 saml_timeout:
193 description:
194 - SAML authentication timeout in seconds.
195 type: int
196 ssh_ca:
197 description:
198 - SSH CA name. Source firewall.ssh.local-ca.name.
199 type: str
200 user_cert:
201 description:
202 - Enable/disable authentication with user certificate .
203 type: str
204 choices:
205 - 'enable'
206 - 'disable'
207 user_database:
208 description:
209 - Authentication server to contain user information; "local-user-db" (default) or "123" (for LDAP).
210 type: list
211 elements: dict
212 suboptions:
213 name:
214 description:
215 - Authentication server name. Source system.datasource.name user.radius.name user.tacacs+.name user.ldap.name user.group.name user
216 .scim.name.
217 required: true
218 type: str
219 """
220
221 EXAMPLES = """
222 - name: Configure Authentication Schemes.
223 fortinet.fortios.fortios_authentication_scheme:
224 vdom: "{{ vdom }}"
225 state: "present"
226 access_token: "<your_own_value>"
227 authentication_scheme:
228 cert_http_header: "enable"
229 digest_algo: "md5"
230 digest_rfc2069: "enable"
231 domain_controller: "<your_own_value> (source user.domain-controller.name)"
232 ems_device_owner: "enable"
233 external_idp: "<your_own_value> (source user.external-identity-provider.name)"
234 fsso_agent_for_ntlm: "<your_own_value> (source user.fsso.name)"
235 fsso_guest: "enable"
236 group_attr_type: "display-name"
237 kerberos_keytab: "<your_own_value> (source user.krb-keytab.name)"
238 method: "ntlm"
239 name: "default_name_14"
240 negotiate_ntlm: "enable"
241 require_tfa: "enable"
242 saml_server: "<your_own_value> (source user.saml.name)"
243 saml_timeout: "120"
244 ssh_ca: "<your_own_value> (source firewall.ssh.local-ca.name)"
245 user_cert: "enable"
246 user_database:
247 -
248 name: "default_name_22 (source system.datasource.name user.radius.name user.tacacs+.name user.ldap.name user.group.name user.scim.name)"
249 """
250
251 RETURN = """
252 build:
253 description: Build number of the fortigate image
254 returned: always
255 type: str
256 sample: '1547'
257 http_method:
258 description: Last method used to provision the content into FortiGate
259 returned: always
260 type: str
261 sample: 'PUT'
262 http_status:
263 description: Last result given by FortiGate on last operation applied
264 returned: always
265 type: str
266 sample: "200"
267 mkey:
268 description: Master key (id) used in the last call to FortiGate
269 returned: success
270 type: str
271 sample: "id"
272 name:
273 description: Name of the table used to fulfill the request
274 returned: always
275 type: str
276 sample: "urlfilter"
277 path:
278 description: Path of the table used to fulfill the request
279 returned: always
280 type: str
281 sample: "webfilter"
282 revision:
283 description: Internal revision number
284 returned: always
285 type: str
286 sample: "17.0.2.10658"
287 serial:
288 description: Serial number of the unit
289 returned: always
290 type: str
291 sample: "FGVMEVYYQT3AB5352"
292 status:
293 description: Indication of the operation's result
294 returned: always
295 type: str
296 sample: "success"
297 vdom:
298 description: Virtual domain used
299 returned: always
300 type: str
301 sample: "root"
302 version:
303 description: Version of the FortiGate
304 returned: always
305 type: str
306 sample: "v5.6.3"
307 """
308 from ansible.module_utils.basic import AnsibleModule
309 from ansible.module_utils.connection import Connection
310 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
311 FortiOSHandler,
312 )
313 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
314 check_legacy_fortiosapi,
315 )
316 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
317 schema_to_module_spec,
318 )
319 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
320 check_schema_versioning,
321 )
322 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
323 FAIL_SOCKET_MSG,
324 )
325 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
326 remove_invalid_fields,
327 )
328 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
329 is_same_comparison,
330 )
331 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
332 serialize,
333 )
334 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
335 find_current_values,
336 )
337 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
338 unify_data_format,
339 )
340
341
342 def filter_authentication_scheme_data(json):
343 option_list = [
344 "cert_http_header",
345 "digest_algo",
346 "digest_rfc2069",
347 "domain_controller",
348 "ems_device_owner",
349 "external_idp",
350 "fsso_agent_for_ntlm",
351 "fsso_guest",
352 "group_attr_type",
353 "kerberos_keytab",
354 "method",
355 "name",
356 "negotiate_ntlm",
357 "require_tfa",
358 "saml_server",
359 "saml_timeout",
360 "ssh_ca",
361 "user_cert",
362 "user_database",
363 ]
364
365 json = remove_invalid_fields(json)
366 dictionary = {}
367
368 for attribute in option_list:
369 if attribute in json and json[attribute] is not None:
370 dictionary[attribute] = json[attribute]
371
372 return dictionary
373
374
375 def flatten_single_path(data, path, index):
376 if (
377 not data
378 or index == len(path)
379 or path[index] not in data
380 or (not data[path[index]] and not isinstance(data[path[index]], list))
381 ):
382 return
383
384 if index == len(path) - 1:
385 data[path[index]] = " ".join(str(elem) for elem in data[path[index]])
386 if len(data[path[index]]) == 0:
387 data[path[index]] = None
388 elif isinstance(data[path[index]], list):
389 for value in data[path[index]]:
390 flatten_single_path(value, path, index + 1)
391 else:
392 flatten_single_path(data[path[index]], path, index + 1)
393
394
395 def flatten_multilists_attributes(data):
396 multilist_attrs = [
397 ["method"],
398 ["digest_algo"],
399 ]
400
401 for attr in multilist_attrs:
402 flatten_single_path(data, attr, 0)
403
404 return data
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 authentication_scheme(data, fos, check_mode=False):
423
424 state = None
425 vdom = data["vdom"]
426 parameters = None
427 state = data.get("state", None)
428 authentication_scheme_data = data["authentication_scheme"]
429
430 filtered_data = filter_authentication_scheme_data(authentication_scheme_data)
431 filtered_data = flatten_multilists_attributes(filtered_data)
432 converted_data = underscore_to_hyphen(filtered_data)
433
434 # check_mode starts from here
435 if check_mode:
436 diff = {
437 "before": "",
438 "after": filtered_data,
439 }
440 mkeyname = fos.get_mkeyname(None, None)
441 mkey = fos.get_mkey("authentication", "scheme", filtered_data, vdom=vdom)
442 current_data = fos.get(
443 "authentication", "scheme", vdom=vdom, mkey=mkey, parameters=parameters
444 )
445 is_existed = (
446 current_data
447 and current_data.get("http_status") == 200
448 and (
449 mkeyname
450 and isinstance(current_data.get("results"), list)
451 and len(current_data["results"]) > 0
452 or not mkeyname
453 and current_data["results"] # global object response
454 )
455 )
456
457 # 2. if it exists and the state is 'present' then compare current settings with desired
458 if state == "present" or state is True or state is None:
459 # for non global modules, mkeyname must exist and it's a new module when mkey is None
460 if mkeyname is not None and mkey is None:
461 return False, True, filtered_data, diff
462
463 # if mkey exists then compare each other
464 # record exits and they're matched or not
465 copied_filtered_data = filtered_data.copy()
466 copied_filtered_data.pop(mkeyname, None)
467 unified_filtered_data = unify_data_format(copied_filtered_data)
468
469 current_data_results = current_data.get("results", {})
470 current_config = (
471 current_data_results[0]
472 if mkeyname
473 and isinstance(current_data_results, list)
474 and len(current_data_results) > 0
475 else current_data_results
476 )
477 if is_existed:
478 unified_current_values = find_current_values(
479 unified_filtered_data,
480 unify_data_format(current_config),
481 )
482
483 is_same = is_same_comparison(
484 serialize(unified_current_values), serialize(unified_filtered_data)
485 )
486
487 return (
488 False,
489 not is_same,
490 filtered_data,
491 {"before": unified_current_values, "after": unified_filtered_data},
492 )
493
494 # record does not exist
495 return False, True, filtered_data, diff
496
497 if state == "absent":
498 if mkey is None:
499 return (
500 False,
501 False,
502 filtered_data,
503 {"before": current_data["results"][0], "after": ""},
504 )
505
506 if is_existed:
507 return (
508 False,
509 True,
510 filtered_data,
511 {"before": current_data["results"][0], "after": ""},
512 )
513 return False, False, filtered_data, {}
514
515 return True, False, {"reason: ": "Must provide state parameter"}, {}
516 # pass post processed data to member operations
517 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
518 data_copy = data.copy()
519 data_copy["authentication_scheme"] = filtered_data
520 fos.do_member_operation(
521 "authentication",
522 "scheme",
523 data_copy,
524 )
525
526 if state == "present" or state is True:
527 return fos.set(
528 "authentication",
529 "scheme",
530 data=converted_data,
531 vdom=vdom,
532 parameters=parameters,
533 )
534
535 elif state == "absent":
536 return fos.delete(
537 "authentication",
538 "scheme",
539 mkey=converted_data["name"],
540 vdom=vdom,
541 parameters=parameters,
542 )
543 else:
544 fos._module.fail_json(msg="state must be present or absent!")
545
546
547 def is_successful_status(resp):
548 return (
549 "status" in resp
550 and resp["status"] == "success"
551 or "http_status" in resp
552 and resp["http_status"] == 200
553 or "http_method" in resp
554 and resp["http_method"] == "DELETE"
555 and resp["http_status"] == 404
556 )
557
558
559 def fortios_authentication(data, fos, check_mode):
560
561 if data["authentication_scheme"]:
562 resp = authentication_scheme(data, fos, check_mode)
563 else:
564 fos._module.fail_json(msg="missing task body: %s" % ("authentication_scheme"))
565 if isinstance(resp, tuple) and len(resp) == 4:
566 return resp
567 return (
568 not is_successful_status(resp),
569 is_successful_status(resp)
570 and (resp["revision_changed"] if "revision_changed" in resp else True),
571 resp,
572 {},
573 )
574
575
576 versioned_schema = {
577 "type": "list",
578 "elements": "dict",
579 "children": {
580 "name": {"v_range": [["v6.0.0", ""]], "type": "string", "required": True},
581 "method": {
582 "v_range": [["v6.0.0", ""]],
583 "type": "list",
584 "options": [
585 {"value": "ntlm"},
586 {"value": "basic"},
587 {"value": "digest"},
588 {"value": "form"},
589 {"value": "negotiate"},
590 {"value": "fsso"},
591 {"value": "rsso"},
592 {"value": "ssh-publickey"},
593 {"value": "cert", "v_range": [["v7.0.0", ""]]},
594 {"value": "saml", "v_range": [["v7.0.0", ""]]},
595 {"value": "entra-sso", "v_range": [["v7.6.1", ""]]},
596 ],
597 "multiple_values": True,
598 "elements": "str",
599 },
600 "negotiate_ntlm": {
601 "v_range": [["v6.0.0", ""]],
602 "type": "string",
603 "options": [{"value": "enable"}, {"value": "disable"}],
604 },
605 "kerberos_keytab": {"v_range": [["v6.0.0", ""]], "type": "string"},
606 "domain_controller": {"v_range": [["v6.0.0", ""]], "type": "string"},
607 "saml_server": {"v_range": [["v7.0.0", ""]], "type": "string"},
608 "saml_timeout": {"v_range": [["v7.0.0", ""]], "type": "integer"},
609 "fsso_agent_for_ntlm": {"v_range": [["v6.0.0", ""]], "type": "string"},
610 "require_tfa": {
611 "v_range": [["v6.0.0", ""]],
612 "type": "string",
613 "options": [{"value": "enable"}, {"value": "disable"}],
614 },
615 "fsso_guest": {
616 "v_range": [["v6.0.0", ""]],
617 "type": "string",
618 "options": [{"value": "enable"}, {"value": "disable"}],
619 },
620 "user_cert": {
621 "v_range": [["v7.0.1", ""]],
622 "type": "string",
623 "options": [{"value": "enable"}, {"value": "disable"}],
624 },
625 "cert_http_header": {
626 "v_range": [["v7.6.5", ""]],
627 "type": "string",
628 "options": [{"value": "enable"}, {"value": "disable"}],
629 },
630 "user_database": {
631 "type": "list",
632 "elements": "dict",
633 "children": {
634 "name": {
635 "v_range": [["v6.0.0", ""]],
636 "type": "string",
637 "required": True,
638 }
639 },
640 "v_range": [["v6.0.0", ""]],
641 },
642 "ssh_ca": {"v_range": [["v6.0.0", ""]], "type": "string"},
643 "external_idp": {"v_range": [["v7.6.1", ""]], "type": "string"},
644 "group_attr_type": {
645 "v_range": [["v7.6.3", ""]],
646 "type": "string",
647 "options": [{"value": "display-name"}, {"value": "external-id"}],
648 },
649 "digest_algo": {
650 "v_range": [["v7.6.3", ""]],
651 "type": "list",
652 "options": [{"value": "md5"}, {"value": "sha-256"}],
653 "multiple_values": True,
654 "elements": "str",
655 },
656 "digest_rfc2069": {
657 "v_range": [["v7.6.4", ""]],
658 "type": "string",
659 "options": [{"value": "enable"}, {"value": "disable"}],
660 },
661 "ems_device_owner": {
662 "v_range": [["v7.0.0", "v7.0.0"]],
663 "type": "string",
664 "options": [{"value": "enable"}, {"value": "disable"}],
665 },
666 },
667 "v_range": [["v6.0.0", ""]],
668 }
669
670
671 def main():
672 module_spec = schema_to_module_spec(versioned_schema)
673 mkeyname = "name"
674 fields = {
675 "access_token": {"required": False, "type": "str", "no_log": True},
676 "enable_log": {"required": False, "type": "bool", "default": False},
677 "vdom": {"required": False, "type": "str", "default": "root"},
678 "member_path": {"required": False, "type": "str"},
679 "member_state": {
680 "type": "str",
681 "required": False,
682 "choices": ["present", "absent"],
683 },
684 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
685 "authentication_scheme": {
686 "required": False,
687 "type": "dict",
688 "default": None,
689 "options": {},
690 },
691 }
692 for attribute_name in module_spec["options"]:
693 fields["authentication_scheme"]["options"][attribute_name] = module_spec[
694 "options"
695 ][attribute_name]
696 if mkeyname and mkeyname == attribute_name:
697 fields["authentication_scheme"]["options"][attribute_name][
698 "required"
699 ] = True
700
701 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
702 check_legacy_fortiosapi(module)
703
704 is_error = False
705 has_changed = False
706 result = None
707 diff = None
708
709 versions_check_result = None
710 if module._socket_path:
711 connection = Connection(module._socket_path)
712 if "access_token" in module.params:
713 connection.set_custom_option("access_token", module.params["access_token"])
714
715 if "enable_log" in module.params:
716 connection.set_custom_option("enable_log", module.params["enable_log"])
717 else:
718 connection.set_custom_option("enable_log", False)
719 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
720 versions_check_result = check_schema_versioning(
721 fos, versioned_schema, "authentication_scheme"
722 )
723
724 is_error, has_changed, result, diff = fortios_authentication(
725 module.params, fos, module.check_mode
726 )
727
728 else:
729 module.fail_json(**FAIL_SOCKET_MSG)
730
731 if versions_check_result and versions_check_result["matched"] is False:
732 module.warn(
733 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
734 )
735
736 if not is_error:
737 if versions_check_result and versions_check_result["matched"] is False:
738 module.exit_json(
739 changed=has_changed,
740 version_check_warning=versions_check_result,
741 meta=result,
742 diff=diff,
743 )
744 else:
745 module.exit_json(changed=has_changed, meta=result, diff=diff)
746 else:
747 if versions_check_result and versions_check_result["matched"] is False:
748 module.fail_json(
749 msg="Error in repo",
750 version_check_warning=versions_check_result,
751 meta=result,
752 )
753 else:
754 module.fail_json(msg="Error in repo", meta=result)
755
756
757 if __name__ == "__main__":
758 main()