Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_authentication_setting.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_setting
23 short_description: Configure authentication setting 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 setting 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 authentication_setting:
80 description:
81 - Configure authentication setting.
82 default: null
83 type: dict
84 suboptions:
85 active_auth_scheme:
86 description:
87 - Active authentication method (scheme name). Source authentication.scheme.name.
88 type: str
89 auth_https:
90 description:
91 - Enable/disable redirecting HTTP user authentication to HTTPS.
92 type: str
93 choices:
94 - 'enable'
95 - 'disable'
96 captive_portal:
97 description:
98 - Captive portal host name. Source firewall.address.name.
99 type: str
100 captive_portal_ip:
101 description:
102 - Captive portal IP address.
103 type: str
104 captive_portal_ip6:
105 description:
106 - Captive portal IPv6 address.
107 type: str
108 captive_portal_port:
109 description:
110 - Captive portal port number (1 - 65535).
111 type: int
112 captive_portal_ssl_port:
113 description:
114 - Captive portal SSL port number (1 - 65535).
115 type: int
116 captive_portal_type:
117 description:
118 - Captive portal type.
119 type: str
120 choices:
121 - 'fqdn'
122 - 'ip'
123 captive_portal6:
124 description:
125 - IPv6 captive portal host name. Source firewall.address6.name.
126 type: str
127 cert_auth:
128 description:
129 - Enable/disable redirecting certificate authentication to HTTPS portal.
130 type: str
131 choices:
132 - 'enable'
133 - 'disable'
134 cert_captive_portal:
135 description:
136 - Certificate captive portal host name. Source firewall.address.name.
137 type: str
138 cert_captive_portal_ip:
139 description:
140 - Certificate captive portal IP address.
141 type: str
142 cert_captive_portal_port:
143 description:
144 - Certificate captive portal port number (1 - 65535).
145 type: int
146 cookie_max_age:
147 description:
148 - Persistent web portal cookie maximum age in minutes (30 - 10080 (1 week)).
149 type: int
150 cookie_refresh_div:
151 description:
152 - Refresh rate divider of persistent web portal cookie . Refresh value = cookie-max-age/cookie-refresh-div.
153 type: int
154 dev_range:
155 description:
156 - Address range for the IP based device query.
157 type: list
158 elements: dict
159 suboptions:
160 name:
161 description:
162 - Address name. Source firewall.address.name firewall.addrgrp.name.
163 required: true
164 type: str
165 ip_auth_cookie:
166 description:
167 - Enable/disable persistent cookie on IP based web portal authentication .
168 type: str
169 choices:
170 - 'enable'
171 - 'disable'
172 persistent_cookie:
173 description:
174 - Enable/disable persistent cookie on web portal authentication .
175 type: str
176 choices:
177 - 'enable'
178 - 'disable'
179 sso_auth_scheme:
180 description:
181 - Single-Sign-On authentication method (scheme name). Source authentication.scheme.name.
182 type: str
183 update_time:
184 description:
185 - Time of the last update.
186 type: str
187 user_cert_ca:
188 description:
189 - CA certificate used for client certificate verification.
190 type: list
191 elements: dict
192 suboptions:
193 name:
194 description:
195 - CA certificate list. Source vpn.certificate.ca.name vpn.certificate.local.name.
196 required: true
197 type: str
198 """
199
200 EXAMPLES = """
201 - name: Configure authentication setting.
202 fortinet.fortios.fortios_authentication_setting:
203 vdom: "{{ vdom }}"
204 authentication_setting:
205 active_auth_scheme: "<your_own_value> (source authentication.scheme.name)"
206 auth_https: "enable"
207 captive_portal: "<your_own_value> (source firewall.address.name)"
208 captive_portal_ip: "<your_own_value>"
209 captive_portal_ip6: "<your_own_value>"
210 captive_portal_port: "7830"
211 captive_portal_ssl_port: "7831"
212 captive_portal_type: "fqdn"
213 captive_portal6: "<your_own_value> (source firewall.address6.name)"
214 cert_auth: "enable"
215 cert_captive_portal: "<your_own_value> (source firewall.address.name)"
216 cert_captive_portal_ip: "<your_own_value>"
217 cert_captive_portal_port: "7832"
218 cookie_max_age: "480"
219 cookie_refresh_div: "2"
220 dev_range:
221 -
222 name: "default_name_19 (source firewall.address.name firewall.addrgrp.name)"
223 ip_auth_cookie: "enable"
224 persistent_cookie: "enable"
225 sso_auth_scheme: "<your_own_value> (source authentication.scheme.name)"
226 update_time: "<your_own_value>"
227 user_cert_ca:
228 -
229 name: "default_name_25 (source vpn.certificate.ca.name vpn.certificate.local.name)"
230 """
231
232 RETURN = """
233 build:
234 description: Build number of the fortigate image
235 returned: always
236 type: str
237 sample: '1547'
238 http_method:
239 description: Last method used to provision the content into FortiGate
240 returned: always
241 type: str
242 sample: 'PUT'
243 http_status:
244 description: Last result given by FortiGate on last operation applied
245 returned: always
246 type: str
247 sample: "200"
248 mkey:
249 description: Master key (id) used in the last call to FortiGate
250 returned: success
251 type: str
252 sample: "id"
253 name:
254 description: Name of the table used to fulfill the request
255 returned: always
256 type: str
257 sample: "urlfilter"
258 path:
259 description: Path of the table used to fulfill the request
260 returned: always
261 type: str
262 sample: "webfilter"
263 revision:
264 description: Internal revision number
265 returned: always
266 type: str
267 sample: "17.0.2.10658"
268 serial:
269 description: Serial number of the unit
270 returned: always
271 type: str
272 sample: "FGVMEVYYQT3AB5352"
273 status:
274 description: Indication of the operation's result
275 returned: always
276 type: str
277 sample: "success"
278 vdom:
279 description: Virtual domain used
280 returned: always
281 type: str
282 sample: "root"
283 version:
284 description: Version of the FortiGate
285 returned: always
286 type: str
287 sample: "v5.6.3"
288 """
289 from ansible.module_utils.basic import AnsibleModule
290 from ansible.module_utils.connection import Connection
291 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
292 FortiOSHandler,
293 )
294 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
295 check_legacy_fortiosapi,
296 )
297 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
298 schema_to_module_spec,
299 )
300 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
301 check_schema_versioning,
302 )
303 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
304 FAIL_SOCKET_MSG,
305 )
306 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
307 remove_invalid_fields,
308 )
309 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
310 is_same_comparison,
311 )
312 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
313 serialize,
314 )
315 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
316 find_current_values,
317 )
318 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
319 unify_data_format,
320 )
321
322
323 def filter_authentication_setting_data(json):
324 option_list = [
325 "active_auth_scheme",
326 "auth_https",
327 "captive_portal",
328 "captive_portal_ip",
329 "captive_portal_ip6",
330 "captive_portal_port",
331 "captive_portal_ssl_port",
332 "captive_portal_type",
333 "captive_portal6",
334 "cert_auth",
335 "cert_captive_portal",
336 "cert_captive_portal_ip",
337 "cert_captive_portal_port",
338 "cookie_max_age",
339 "cookie_refresh_div",
340 "dev_range",
341 "ip_auth_cookie",
342 "persistent_cookie",
343 "sso_auth_scheme",
344 "update_time",
345 "user_cert_ca",
346 ]
347
348 json = remove_invalid_fields(json)
349 dictionary = {}
350
351 for attribute in option_list:
352 if attribute in json and json[attribute] is not None:
353 dictionary[attribute] = json[attribute]
354
355 return dictionary
356
357
358 def underscore_to_hyphen(data):
359 new_data = None
360 if isinstance(data, list):
361 new_data = []
362 for i, elem in enumerate(data):
363 new_data.append(underscore_to_hyphen(elem))
364 elif isinstance(data, dict):
365 new_data = {}
366 for k, v in data.items():
367 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
368 else:
369 return data
370 return new_data
371
372
373 def authentication_setting(data, fos, check_mode=False):
374
375 state = None
376 vdom = data["vdom"]
377 parameters = None
378 state = data.get("state", None)
379 authentication_setting_data = data["authentication_setting"]
380
381 filtered_data = filter_authentication_setting_data(authentication_setting_data)
382 converted_data = underscore_to_hyphen(filtered_data)
383
384 # check_mode starts from here
385 if check_mode:
386 diff = {
387 "before": "",
388 "after": filtered_data,
389 }
390 mkeyname = fos.get_mkeyname(None, None)
391 mkey = fos.get_mkey("authentication", "setting", filtered_data, vdom=vdom)
392 current_data = fos.get(
393 "authentication", "setting", vdom=vdom, mkey=mkey, parameters=parameters
394 )
395 is_existed = (
396 current_data
397 and current_data.get("http_status") == 200
398 and (
399 mkeyname
400 and isinstance(current_data.get("results"), list)
401 and len(current_data["results"]) > 0
402 or not mkeyname
403 and current_data["results"] # global object response
404 )
405 )
406
407 # 2. if it exists and the state is 'present' then compare current settings with desired
408 if state == "present" or state is True or state is None:
409 # for non global modules, mkeyname must exist and it's a new module when mkey is None
410 if mkeyname is not None and mkey is None:
411 return False, True, filtered_data, diff
412
413 # if mkey exists then compare each other
414 # record exits and they're matched or not
415 copied_filtered_data = filtered_data.copy()
416 copied_filtered_data.pop(mkeyname, None)
417 unified_filtered_data = unify_data_format(copied_filtered_data)
418
419 current_data_results = current_data.get("results", {})
420 current_config = (
421 current_data_results[0]
422 if mkeyname
423 and isinstance(current_data_results, list)
424 and len(current_data_results) > 0
425 else current_data_results
426 )
427 if is_existed:
428 unified_current_values = find_current_values(
429 unified_filtered_data,
430 unify_data_format(current_config),
431 )
432
433 is_same = is_same_comparison(
434 serialize(unified_current_values), serialize(unified_filtered_data)
435 )
436
437 return (
438 False,
439 not is_same,
440 filtered_data,
441 {"before": unified_current_values, "after": unified_filtered_data},
442 )
443
444 # record does not exist
445 return False, True, filtered_data, diff
446
447 if state == "absent":
448 if mkey is None:
449 return (
450 False,
451 False,
452 filtered_data,
453 {"before": current_data["results"][0], "after": ""},
454 )
455
456 if is_existed:
457 return (
458 False,
459 True,
460 filtered_data,
461 {"before": current_data["results"][0], "after": ""},
462 )
463 return False, False, filtered_data, {}
464
465 return True, False, {"reason: ": "Must provide state parameter"}, {}
466 # pass post processed data to member operations
467 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
468 data_copy = data.copy()
469 data_copy["authentication_setting"] = filtered_data
470 fos.do_member_operation(
471 "authentication",
472 "setting",
473 data_copy,
474 )
475
476 return fos.set(
477 "authentication",
478 "setting",
479 data=converted_data,
480 vdom=vdom,
481 parameters=parameters,
482 )
483
484
485 def is_successful_status(resp):
486 return (
487 "status" in resp
488 and resp["status"] == "success"
489 or "http_status" in resp
490 and resp["http_status"] == 200
491 or "http_method" in resp
492 and resp["http_method"] == "DELETE"
493 and resp["http_status"] == 404
494 )
495
496
497 def fortios_authentication(data, fos, check_mode):
498
499 if data["authentication_setting"]:
500 resp = authentication_setting(data, fos, check_mode)
501 else:
502 fos._module.fail_json(msg="missing task body: %s" % ("authentication_setting"))
503 if isinstance(resp, tuple) and len(resp) == 4:
504 return resp
505 return (
506 not is_successful_status(resp),
507 is_successful_status(resp)
508 and (resp["revision_changed"] if "revision_changed" in resp else True),
509 resp,
510 {},
511 )
512
513
514 versioned_schema = {
515 "v_range": [["v6.0.0", ""]],
516 "type": "dict",
517 "children": {
518 "active_auth_scheme": {"v_range": [["v6.0.0", ""]], "type": "string"},
519 "sso_auth_scheme": {"v_range": [["v6.0.0", ""]], "type": "string"},
520 "update_time": {"v_range": [["v7.2.0", ""]], "type": "string"},
521 "persistent_cookie": {
522 "v_range": [["v7.2.0", ""]],
523 "type": "string",
524 "options": [{"value": "enable"}, {"value": "disable"}],
525 },
526 "ip_auth_cookie": {
527 "v_range": [["v7.2.0", ""]],
528 "type": "string",
529 "options": [{"value": "enable"}, {"value": "disable"}],
530 },
531 "cookie_max_age": {"v_range": [["v7.2.0", ""]], "type": "integer"},
532 "cookie_refresh_div": {"v_range": [["v7.2.0", ""]], "type": "integer"},
533 "captive_portal_type": {
534 "v_range": [["v6.0.0", ""]],
535 "type": "string",
536 "options": [{"value": "fqdn"}, {"value": "ip"}],
537 },
538 "captive_portal_ip": {"v_range": [["v6.0.0", ""]], "type": "string"},
539 "captive_portal_ip6": {"v_range": [["v6.0.0", ""]], "type": "string"},
540 "captive_portal": {"v_range": [["v6.0.0", ""]], "type": "string"},
541 "captive_portal6": {"v_range": [["v6.0.0", ""]], "type": "string"},
542 "cert_auth": {
543 "v_range": [["v7.0.1", ""]],
544 "type": "string",
545 "options": [{"value": "enable"}, {"value": "disable"}],
546 },
547 "cert_captive_portal": {"v_range": [["v7.0.1", ""]], "type": "string"},
548 "cert_captive_portal_ip": {"v_range": [["v7.0.1", ""]], "type": "string"},
549 "cert_captive_portal_port": {"v_range": [["v7.0.1", ""]], "type": "integer"},
550 "captive_portal_port": {"v_range": [["v6.0.0", ""]], "type": "integer"},
551 "auth_https": {
552 "v_range": [["v6.2.0", ""]],
553 "type": "string",
554 "options": [{"value": "enable"}, {"value": "disable"}],
555 },
556 "captive_portal_ssl_port": {"v_range": [["v6.2.0", ""]], "type": "integer"},
557 "user_cert_ca": {
558 "type": "list",
559 "elements": "dict",
560 "children": {
561 "name": {
562 "v_range": [["v7.0.0", ""]],
563 "type": "string",
564 "required": True,
565 }
566 },
567 "v_range": [["v7.0.0", ""]],
568 },
569 "dev_range": {
570 "type": "list",
571 "elements": "dict",
572 "children": {
573 "name": {
574 "v_range": [["v7.0.0", ""]],
575 "type": "string",
576 "required": True,
577 }
578 },
579 "v_range": [["v7.0.0", ""]],
580 },
581 },
582 }
583
584
585 def main():
586 module_spec = schema_to_module_spec(versioned_schema)
587 mkeyname = None
588 fields = {
589 "access_token": {"required": False, "type": "str", "no_log": True},
590 "enable_log": {"required": False, "type": "bool", "default": False},
591 "vdom": {"required": False, "type": "str", "default": "root"},
592 "member_path": {"required": False, "type": "str"},
593 "member_state": {
594 "type": "str",
595 "required": False,
596 "choices": ["present", "absent"],
597 },
598 "authentication_setting": {
599 "required": False,
600 "type": "dict",
601 "default": None,
602 "options": {},
603 },
604 }
605 for attribute_name in module_spec["options"]:
606 fields["authentication_setting"]["options"][attribute_name] = module_spec[
607 "options"
608 ][attribute_name]
609 if mkeyname and mkeyname == attribute_name:
610 fields["authentication_setting"]["options"][attribute_name][
611 "required"
612 ] = True
613
614 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
615 check_legacy_fortiosapi(module)
616
617 is_error = False
618 has_changed = False
619 result = None
620 diff = None
621
622 versions_check_result = None
623 if module._socket_path:
624 connection = Connection(module._socket_path)
625 if "access_token" in module.params:
626 connection.set_custom_option("access_token", module.params["access_token"])
627
628 if "enable_log" in module.params:
629 connection.set_custom_option("enable_log", module.params["enable_log"])
630 else:
631 connection.set_custom_option("enable_log", False)
632 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
633 versions_check_result = check_schema_versioning(
634 fos, versioned_schema, "authentication_setting"
635 )
636
637 is_error, has_changed, result, diff = fortios_authentication(
638 module.params, fos, module.check_mode
639 )
640
641 else:
642 module.fail_json(**FAIL_SOCKET_MSG)
643
644 if versions_check_result and versions_check_result["matched"] is False:
645 module.warn(
646 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
647 )
648
649 if not is_error:
650 if versions_check_result and versions_check_result["matched"] is False:
651 module.exit_json(
652 changed=has_changed,
653 version_check_warning=versions_check_result,
654 meta=result,
655 diff=diff,
656 )
657 else:
658 module.exit_json(changed=has_changed, meta=result, diff=diff)
659 else:
660 if versions_check_result and versions_check_result["matched"] is False:
661 module.fail_json(
662 msg="Error in repo",
663 version_check_warning=versions_check_result,
664 meta=result,
665 )
666 else:
667 module.fail_json(msg="Error in repo", meta=result)
668
669
670 if __name__ == "__main__":
671 main()