Debian Codegraph @

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