Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_user_local.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_local
23 short_description: Configure local users 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 local 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_local:
88 description:
89 - Configure local users.
90 default: null
91 type: dict
92 suboptions:
93 auth_concurrent_override:
94 description:
95 - Enable/disable overriding the policy-auth-concurrent under config system global.
96 type: str
97 choices:
98 - 'enable'
99 - 'disable'
100 auth_concurrent_value:
101 description:
102 - Maximum number of concurrent logins permitted from the same user.
103 type: int
104 authtimeout:
105 description:
106 - Time in minutes before the authentication timeout for a user is reached.
107 type: int
108 email_to:
109 description:
110 - Two-factor recipient"s email address.
111 type: str
112 fortitoken:
113 description:
114 - Two-factor recipient"s FortiToken serial number. Source user.fortitoken.serial-number.
115 type: str
116 id:
117 description:
118 - User ID.
119 type: int
120 ldap_server:
121 description:
122 - Name of LDAP server with which the user must authenticate. Source user.ldap.name.
123 type: str
124 name:
125 description:
126 - Local user name.
127 required: true
128 type: str
129 passwd:
130 description:
131 - User"s password.
132 type: str
133 passwd_policy:
134 description:
135 - Password policy to apply to this user, as defined in config user password-policy. Source user.password-policy.name.
136 type: str
137 passwd_time:
138 description:
139 - Time of the last password update.
140 type: str
141 ppk_identity:
142 description:
143 - IKEv2 Postquantum Preshared Key Identity.
144 type: str
145 ppk_secret:
146 description:
147 - IKEv2 Postquantum Preshared Key (ASCII string or hexadecimal encoded with a leading 0x).
148 type: str
149 qkd_profile:
150 description:
151 - Quantum Key Distribution (QKD) profile. Source vpn.qkd.name.
152 type: str
153 radius_server:
154 description:
155 - Name of RADIUS server with which the user must authenticate. Source user.radius.name.
156 type: str
157 saml_server:
158 description:
159 - Name of SAML server with which the user must authenticate. Source user.saml.name.
160 type: str
161 sms_custom_server:
162 description:
163 - Two-factor recipient"s SMS server. Source system.sms-server.name.
164 type: str
165 sms_phone:
166 description:
167 - Two-factor recipient"s mobile phone number.
168 type: str
169 sms_server:
170 description:
171 - Send SMS through FortiGuard or other external server.
172 type: str
173 choices:
174 - 'fortiguard'
175 - 'custom'
176 status:
177 description:
178 - Enable/disable allowing the local user to authenticate with the FortiGate unit.
179 type: str
180 choices:
181 - 'enable'
182 - 'disable'
183 tacacs_plus_server:
184 description:
185 - Name of TACACS+ server with which the user must authenticate. Source user.tacacs+.name.
186 type: str
187 two_factor:
188 description:
189 - Enable/disable two-factor authentication.
190 type: str
191 choices:
192 - 'disable'
193 - 'fortitoken'
194 - 'fortitoken-cloud'
195 - 'email'
196 - 'sms'
197 two_factor_authentication:
198 description:
199 - Authentication method by FortiToken Cloud.
200 type: str
201 choices:
202 - 'fortitoken'
203 - 'email'
204 - 'sms'
205 two_factor_notification:
206 description:
207 - Notification method for user activation by FortiToken Cloud.
208 type: str
209 choices:
210 - 'email'
211 - 'sms'
212 type:
213 description:
214 - Authentication method.
215 type: str
216 choices:
217 - 'password'
218 - 'radius'
219 - 'tacacs+'
220 - 'ldap'
221 - 'saml'
222 username_case_sensitivity:
223 description:
224 - Enable/disable case sensitivity when performing username matching (uppercase and lowercase letters are treated either as distinct or
225 equivalent).
226 type: str
227 choices:
228 - 'disable'
229 - 'enable'
230 username_sensitivity:
231 description:
232 - Enable/disable case and accent sensitivity when performing username matching (accents are stripped and case is ignored when disabled).
233 type: str
234 choices:
235 - 'disable'
236 - 'enable'
237 workstation:
238 description:
239 - Name of the remote user workstation, if you want to limit the user to authenticate only from a particular workstation.
240 type: str
241 """
242
243 EXAMPLES = """
244 - name: Configure local users.
245 fortinet.fortios.fortios_user_local:
246 vdom: "{{ vdom }}"
247 state: "present"
248 access_token: "<your_own_value>"
249 user_local:
250 auth_concurrent_override: "enable"
251 auth_concurrent_value: "0"
252 authtimeout: "0"
253 email_to: "<your_own_value>"
254 fortitoken: "<your_own_value> (source user.fortitoken.serial-number)"
255 id: "8"
256 ldap_server: "<your_own_value> (source user.ldap.name)"
257 name: "default_name_10"
258 passwd: "<your_own_value>"
259 passwd_policy: "<your_own_value> (source user.password-policy.name)"
260 passwd_time: "<your_own_value>"
261 ppk_identity: "<your_own_value>"
262 ppk_secret: "<your_own_value>"
263 qkd_profile: "<your_own_value> (source vpn.qkd.name)"
264 radius_server: "<your_own_value> (source user.radius.name)"
265 saml_server: "<your_own_value> (source user.saml.name)"
266 sms_custom_server: "<your_own_value> (source system.sms-server.name)"
267 sms_phone: "<your_own_value>"
268 sms_server: "fortiguard"
269 status: "enable"
270 tacacs_plus_server: "<your_own_value> (source user.tacacs+.name)"
271 two_factor: "disable"
272 two_factor_authentication: "fortitoken"
273 two_factor_notification: "email"
274 type: "password"
275 username_case_sensitivity: "disable"
276 username_sensitivity: "disable"
277 workstation: "<your_own_value>"
278 """
279
280 RETURN = """
281 build:
282 description: Build number of the fortigate image
283 returned: always
284 type: str
285 sample: '1547'
286 http_method:
287 description: Last method used to provision the content into FortiGate
288 returned: always
289 type: str
290 sample: 'PUT'
291 http_status:
292 description: Last result given by FortiGate on last operation applied
293 returned: always
294 type: str
295 sample: "200"
296 mkey:
297 description: Master key (id) used in the last call to FortiGate
298 returned: success
299 type: str
300 sample: "id"
301 name:
302 description: Name of the table used to fulfill the request
303 returned: always
304 type: str
305 sample: "urlfilter"
306 path:
307 description: Path of the table used to fulfill the request
308 returned: always
309 type: str
310 sample: "webfilter"
311 revision:
312 description: Internal revision number
313 returned: always
314 type: str
315 sample: "17.0.2.10658"
316 serial:
317 description: Serial number of the unit
318 returned: always
319 type: str
320 sample: "FGVMEVYYQT3AB5352"
321 status:
322 description: Indication of the operation's result
323 returned: always
324 type: str
325 sample: "success"
326 vdom:
327 description: Virtual domain used
328 returned: always
329 type: str
330 sample: "root"
331 version:
332 description: Version of the FortiGate
333 returned: always
334 type: str
335 sample: "v5.6.3"
336 """
337 from ansible.module_utils.basic import AnsibleModule
338 from ansible.module_utils.connection import Connection
339 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
340 FortiOSHandler,
341 )
342 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
343 check_legacy_fortiosapi,
344 )
345 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
346 schema_to_module_spec,
347 )
348 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
349 check_schema_versioning,
350 )
351 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
352 FAIL_SOCKET_MSG,
353 )
354 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
355 remove_invalid_fields,
356 )
357 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
358 is_same_comparison,
359 )
360 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
361 serialize,
362 )
363 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
364 find_current_values,
365 )
366 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
367 unify_data_format,
368 )
369
370
371 def filter_user_local_data(json):
372 option_list = [
373 "auth_concurrent_override",
374 "auth_concurrent_value",
375 "authtimeout",
376 "email_to",
377 "fortitoken",
378 "id",
379 "ldap_server",
380 "name",
381 "passwd",
382 "passwd_policy",
383 "passwd_time",
384 "ppk_identity",
385 "ppk_secret",
386 "qkd_profile",
387 "radius_server",
388 "saml_server",
389 "sms_custom_server",
390 "sms_phone",
391 "sms_server",
392 "status",
393 "tacacs_plus_server",
394 "two_factor",
395 "two_factor_authentication",
396 "two_factor_notification",
397 "type",
398 "username_case_sensitivity",
399 "username_sensitivity",
400 "workstation",
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 valid_attr_to_invalid_attr(data):
429 speciallist = {"tacacs+_server": "tacacs_plus_server"}
430
431 for k, v in speciallist.items():
432 if v == data:
433 return k
434
435 return data
436
437
438 def valid_attr_to_invalid_attrs(data):
439 if isinstance(data, list):
440 new_data = []
441 for elem in data:
442 elem = valid_attr_to_invalid_attrs(elem)
443 new_data.append(elem)
444 data = new_data
445 elif isinstance(data, dict):
446 new_data = {}
447 for k, v in data.items():
448 new_data[valid_attr_to_invalid_attr(k)] = valid_attr_to_invalid_attrs(v)
449 data = new_data
450
451 return valid_attr_to_invalid_attr(data)
452
453
454 def user_local(data, fos, check_mode=False):
455
456 state = None
457 vdom = data["vdom"]
458 parameters = None
459 state = data.get("state", None)
460 user_local_data = data["user_local"]
461
462 filtered_data = filter_user_local_data(user_local_data)
463 converted_data = underscore_to_hyphen(valid_attr_to_invalid_attrs(filtered_data))
464
465 # check_mode starts from here
466 if check_mode:
467 diff = {
468 "before": "",
469 "after": filtered_data,
470 }
471 mkeyname = fos.get_mkeyname(None, None)
472 mkey = fos.get_mkey("user", "local", filtered_data, vdom=vdom)
473 current_data = fos.get(
474 "user", "local", vdom=vdom, mkey=mkey, parameters=parameters
475 )
476 is_existed = (
477 current_data
478 and current_data.get("http_status") == 200
479 and (
480 mkeyname
481 and isinstance(current_data.get("results"), list)
482 and len(current_data["results"]) > 0
483 or not mkeyname
484 and current_data["results"] # global object response
485 )
486 )
487
488 # 2. if it exists and the state is 'present' then compare current settings with desired
489 if state == "present" or state is True or state is None:
490 # for non global modules, mkeyname must exist and it's a new module when mkey is None
491 if mkeyname is not None and mkey is None:
492 return False, True, filtered_data, diff
493
494 # if mkey exists then compare each other
495 # record exits and they're matched or not
496 copied_filtered_data = filtered_data.copy()
497 copied_filtered_data.pop(mkeyname, None)
498 unified_filtered_data = unify_data_format(copied_filtered_data)
499
500 current_data_results = current_data.get("results", {})
501 current_config = (
502 current_data_results[0]
503 if mkeyname
504 and isinstance(current_data_results, list)
505 and len(current_data_results) > 0
506 else current_data_results
507 )
508 if is_existed:
509 unified_current_values = find_current_values(
510 unified_filtered_data,
511 unify_data_format(current_config),
512 )
513
514 is_same = is_same_comparison(
515 serialize(unified_current_values), serialize(unified_filtered_data)
516 )
517
518 return (
519 False,
520 not is_same,
521 filtered_data,
522 {"before": unified_current_values, "after": unified_filtered_data},
523 )
524
525 # record does not exist
526 return False, True, filtered_data, diff
527
528 if state == "absent":
529 if mkey is None:
530 return (
531 False,
532 False,
533 filtered_data,
534 {"before": current_data["results"][0], "after": ""},
535 )
536
537 if is_existed:
538 return (
539 False,
540 True,
541 filtered_data,
542 {"before": current_data["results"][0], "after": ""},
543 )
544 return False, False, filtered_data, {}
545
546 return True, False, {"reason: ": "Must provide state parameter"}, {}
547 # pass post processed data to member operations
548 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
549 data_copy = data.copy()
550 data_copy["user_local"] = filtered_data
551 fos.do_member_operation(
552 "user",
553 "local",
554 data_copy,
555 )
556
557 if state == "present" or state is True:
558 return fos.set(
559 "user", "local", data=converted_data, vdom=vdom, parameters=parameters
560 )
561
562 elif state == "absent":
563 return fos.delete(
564 "user",
565 "local",
566 mkey=converted_data["name"],
567 vdom=vdom,
568 parameters=parameters,
569 )
570 else:
571 fos._module.fail_json(msg="state must be present or absent!")
572
573
574 def is_successful_status(resp):
575 return (
576 "status" in resp
577 and resp["status"] == "success"
578 or "http_status" in resp
579 and resp["http_status"] == 200
580 or "http_method" in resp
581 and resp["http_method"] == "DELETE"
582 and resp["http_status"] == 404
583 )
584
585
586 def fortios_user(data, fos, check_mode):
587
588 if data["user_local"]:
589 resp = user_local(data, fos, check_mode)
590 else:
591 fos._module.fail_json(msg="missing task body: %s" % ("user_local"))
592 if isinstance(resp, tuple) and len(resp) == 4:
593 return resp
594 return (
595 not is_successful_status(resp),
596 is_successful_status(resp)
597 and (resp["revision_changed"] if "revision_changed" in resp else True),
598 resp,
599 {},
600 )
601
602
603 versioned_schema = {
604 "type": "list",
605 "elements": "dict",
606 "children": {
607 "name": {"v_range": [["v6.0.0", ""]], "type": "string", "required": True},
608 "status": {
609 "v_range": [["v6.0.0", ""]],
610 "type": "string",
611 "options": [{"value": "enable"}, {"value": "disable"}],
612 },
613 "type": {
614 "v_range": [["v6.0.0", ""]],
615 "type": "string",
616 "options": [
617 {"value": "password"},
618 {"value": "radius"},
619 {"value": "tacacs+"},
620 {"value": "ldap"},
621 {"value": "saml", "v_range": [["v7.6.3", ""]]},
622 ],
623 },
624 "passwd": {"v_range": [["v6.0.0", ""]], "type": "string"},
625 "ldap_server": {"v_range": [["v6.0.0", ""]], "type": "string"},
626 "radius_server": {"v_range": [["v6.0.0", ""]], "type": "string"},
627 "saml_server": {"v_range": [["v7.6.3", ""]], "type": "string"},
628 "two_factor": {
629 "v_range": [["v6.0.0", ""]],
630 "type": "string",
631 "options": [
632 {"value": "disable"},
633 {"value": "fortitoken"},
634 {"value": "fortitoken-cloud", "v_range": [["v6.2.0", ""]]},
635 {"value": "email"},
636 {"value": "sms"},
637 ],
638 },
639 "two_factor_authentication": {
640 "v_range": [["v6.2.0", "v6.2.0"], ["v6.2.5", ""]],
641 "type": "string",
642 "options": [{"value": "fortitoken"}, {"value": "email"}, {"value": "sms"}],
643 },
644 "two_factor_notification": {
645 "v_range": [["v6.2.0", "v6.2.0"], ["v6.2.5", ""]],
646 "type": "string",
647 "options": [{"value": "email"}, {"value": "sms"}],
648 },
649 "fortitoken": {"v_range": [["v6.0.0", ""]], "type": "string"},
650 "email_to": {"v_range": [["v6.0.0", ""]], "type": "string"},
651 "sms_server": {
652 "v_range": [["v6.0.0", ""]],
653 "type": "string",
654 "options": [{"value": "fortiguard"}, {"value": "custom"}],
655 },
656 "sms_custom_server": {"v_range": [["v6.0.0", ""]], "type": "string"},
657 "sms_phone": {"v_range": [["v6.0.0", ""]], "type": "string"},
658 "passwd_policy": {"v_range": [["v6.0.0", ""]], "type": "string"},
659 "passwd_time": {"v_range": [["v6.0.0", ""]], "type": "string"},
660 "authtimeout": {"v_range": [["v6.0.0", ""]], "type": "integer"},
661 "workstation": {"v_range": [["v6.0.0", ""]], "type": "string"},
662 "auth_concurrent_override": {
663 "v_range": [["v6.0.0", ""]],
664 "type": "string",
665 "options": [{"value": "enable"}, {"value": "disable"}],
666 },
667 "auth_concurrent_value": {"v_range": [["v6.0.0", ""]], "type": "integer"},
668 "ppk_secret": {"v_range": [["v6.0.0", ""]], "type": "string"},
669 "ppk_identity": {"v_range": [["v6.0.0", ""]], "type": "string"},
670 "qkd_profile": {"v_range": [["v7.4.2", ""]], "type": "string"},
671 "username_sensitivity": {
672 "v_range": [["v7.0.1", ""]],
673 "type": "string",
674 "options": [{"value": "disable"}, {"value": "enable"}],
675 },
676 "id": {
677 "v_range": [["v6.0.0", "v7.0.5"], ["v7.2.0", "v7.2.0"]],
678 "type": "integer",
679 },
680 "username_case_sensitivity": {
681 "v_range": [
682 ["v6.0.0", "v6.0.0"],
683 ["v6.0.11", "v6.2.0"],
684 ["v6.2.5", "v7.0.0"],
685 ],
686 "type": "string",
687 "options": [{"value": "disable"}, {"value": "enable"}],
688 },
689 "tacacs_plus_server": {"v_range": [["v6.0.0", ""]], "type": "string"},
690 },
691 "v_range": [["v6.0.0", ""]],
692 }
693
694
695 def main():
696 module_spec = schema_to_module_spec(versioned_schema)
697 mkeyname = "name"
698 fields = {
699 "access_token": {"required": False, "type": "str", "no_log": True},
700 "enable_log": {"required": False, "type": "bool", "default": False},
701 "vdom": {"required": False, "type": "str", "default": "root"},
702 "member_path": {"required": False, "type": "str"},
703 "member_state": {
704 "type": "str",
705 "required": False,
706 "choices": ["present", "absent"],
707 },
708 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
709 "user_local": {
710 "required": False,
711 "type": "dict",
712 "default": None,
713 "options": {},
714 },
715 }
716 for attribute_name in module_spec["options"]:
717 fields["user_local"]["options"][attribute_name] = module_spec["options"][
718 attribute_name
719 ]
720 if mkeyname and mkeyname == attribute_name:
721 fields["user_local"]["options"][attribute_name]["required"] = True
722
723 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
724 check_legacy_fortiosapi(module)
725
726 is_error = False
727 has_changed = False
728 result = None
729 diff = None
730
731 versions_check_result = None
732 if module._socket_path:
733 connection = Connection(module._socket_path)
734 if "access_token" in module.params:
735 connection.set_custom_option("access_token", module.params["access_token"])
736
737 if "enable_log" in module.params:
738 connection.set_custom_option("enable_log", module.params["enable_log"])
739 else:
740 connection.set_custom_option("enable_log", False)
741 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
742 versions_check_result = check_schema_versioning(
743 fos, versioned_schema, "user_local"
744 )
745
746 is_error, has_changed, result, diff = fortios_user(
747 module.params, fos, module.check_mode
748 )
749
750 else:
751 module.fail_json(**FAIL_SOCKET_MSG)
752
753 if versions_check_result and versions_check_result["matched"] is False:
754 module.warn(
755 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
756 )
757
758 if not is_error:
759 if versions_check_result and versions_check_result["matched"] is False:
760 module.exit_json(
761 changed=has_changed,
762 version_check_warning=versions_check_result,
763 meta=result,
764 diff=diff,
765 )
766 else:
767 module.exit_json(changed=has_changed, meta=result, diff=diff)
768 else:
769 if versions_check_result and versions_check_result["matched"] is False:
770 module.fail_json(
771 msg="Error in repo",
772 version_check_warning=versions_check_result,
773 meta=result,
774 )
775 else:
776 module.fail_json(msg="Error in repo", meta=result)
777
778
779 if __name__ == "__main__":
780 main()