Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_user_peer.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_peer
23 short_description: Configure peer 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 peer 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_peer:
88 description:
89 - Configure peer users.
90 default: null
91 type: dict
92 suboptions:
93 ca:
94 description:
95 - Name of the CA certificate. Source vpn.certificate.ca.name.
96 type: str
97 cn:
98 description:
99 - Peer certificate common name.
100 type: str
101 cn_type:
102 description:
103 - Peer certificate common name type.
104 type: str
105 choices:
106 - 'string'
107 - 'email'
108 - 'FQDN'
109 - 'ipv4'
110 - 'ipv6'
111 ldap_mode:
112 description:
113 - Mode for LDAP peer authentication.
114 type: str
115 choices:
116 - 'password'
117 - 'principal-name'
118 ldap_password:
119 description:
120 - Password for LDAP server bind.
121 type: str
122 ldap_server:
123 description:
124 - Name of an LDAP server defined under the user ldap command. Performs client access rights check. Source user.ldap.name.
125 type: str
126 ldap_username:
127 description:
128 - Username for LDAP server bind.
129 type: str
130 mandatory_ca_verify:
131 description:
132 - Determine what happens to the peer if the CA certificate is not installed. Disable to automatically consider the peer certificate as
133 valid.
134 type: str
135 choices:
136 - 'enable'
137 - 'disable'
138 mfa_mode:
139 description:
140 - MFA mode for remote peer authentication/authorization.
141 type: str
142 choices:
143 - 'none'
144 - 'password'
145 - 'subject-identity'
146 mfa_password:
147 description:
148 - Unified password for remote authentication. This field may be left empty when RADIUS authentication is used, in which case the FortiGate
149 will use the RADIUS username as a password.
150 type: str
151 mfa_server:
152 description:
153 - Name of a remote authenticator. Performs client access right check. Source user.radius.name user.ldap.name.
154 type: str
155 mfa_username:
156 description:
157 - Unified username for remote authentication.
158 type: str
159 name:
160 description:
161 - Peer name.
162 required: true
163 type: str
164 ocsp_override_server:
165 description:
166 - Online Certificate Status Protocol (OCSP) server for certificate retrieval. Source vpn.certificate.ocsp-server.name.
167 type: str
168 passwd:
169 description:
170 - Peer"s password used for two-factor authentication.
171 type: str
172 subject:
173 description:
174 - Peer certificate name constraints.
175 type: str
176 two_factor:
177 description:
178 - Enable/disable two-factor authentication, applying certificate and password-based authentication.
179 type: str
180 choices:
181 - 'enable'
182 - 'disable'
183 """
184
185 EXAMPLES = """
186 - name: Configure peer users.
187 fortinet.fortios.fortios_user_peer:
188 vdom: "{{ vdom }}"
189 state: "present"
190 access_token: "<your_own_value>"
191 user_peer:
192 ca: "<your_own_value> (source vpn.certificate.ca.name)"
193 cn: "<your_own_value>"
194 cn_type: "string"
195 ldap_mode: "password"
196 ldap_password: "<your_own_value>"
197 ldap_server: "<your_own_value> (source user.ldap.name)"
198 ldap_username: "<your_own_value>"
199 mandatory_ca_verify: "enable"
200 mfa_mode: "none"
201 mfa_password: "<your_own_value>"
202 mfa_server: "<your_own_value> (source user.radius.name user.ldap.name)"
203 mfa_username: "<your_own_value>"
204 name: "default_name_15"
205 ocsp_override_server: "<your_own_value> (source vpn.certificate.ocsp-server.name)"
206 passwd: "<your_own_value>"
207 subject: "<your_own_value>"
208 two_factor: "enable"
209 """
210
211 RETURN = """
212 build:
213 description: Build number of the fortigate image
214 returned: always
215 type: str
216 sample: '1547'
217 http_method:
218 description: Last method used to provision the content into FortiGate
219 returned: always
220 type: str
221 sample: 'PUT'
222 http_status:
223 description: Last result given by FortiGate on last operation applied
224 returned: always
225 type: str
226 sample: "200"
227 mkey:
228 description: Master key (id) used in the last call to FortiGate
229 returned: success
230 type: str
231 sample: "id"
232 name:
233 description: Name of the table used to fulfill the request
234 returned: always
235 type: str
236 sample: "urlfilter"
237 path:
238 description: Path of the table used to fulfill the request
239 returned: always
240 type: str
241 sample: "webfilter"
242 revision:
243 description: Internal revision number
244 returned: always
245 type: str
246 sample: "17.0.2.10658"
247 serial:
248 description: Serial number of the unit
249 returned: always
250 type: str
251 sample: "FGVMEVYYQT3AB5352"
252 status:
253 description: Indication of the operation's result
254 returned: always
255 type: str
256 sample: "success"
257 vdom:
258 description: Virtual domain used
259 returned: always
260 type: str
261 sample: "root"
262 version:
263 description: Version of the FortiGate
264 returned: always
265 type: str
266 sample: "v5.6.3"
267 """
268 from ansible.module_utils.basic import AnsibleModule
269 from ansible.module_utils.connection import Connection
270 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
271 FortiOSHandler,
272 )
273 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
274 check_legacy_fortiosapi,
275 )
276 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
277 schema_to_module_spec,
278 )
279 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
280 check_schema_versioning,
281 )
282 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
283 FAIL_SOCKET_MSG,
284 )
285 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
286 remove_invalid_fields,
287 )
288 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
289 is_same_comparison,
290 )
291 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
292 serialize,
293 )
294 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
295 find_current_values,
296 )
297 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
298 unify_data_format,
299 )
300
301
302 def filter_user_peer_data(json):
303 option_list = [
304 "ca",
305 "cn",
306 "cn_type",
307 "ldap_mode",
308 "ldap_password",
309 "ldap_server",
310 "ldap_username",
311 "mandatory_ca_verify",
312 "mfa_mode",
313 "mfa_password",
314 "mfa_server",
315 "mfa_username",
316 "name",
317 "ocsp_override_server",
318 "passwd",
319 "subject",
320 "two_factor",
321 ]
322
323 json = remove_invalid_fields(json)
324 dictionary = {}
325
326 for attribute in option_list:
327 if attribute in json and json[attribute] is not None:
328 dictionary[attribute] = json[attribute]
329
330 return dictionary
331
332
333 def underscore_to_hyphen(data):
334 new_data = None
335 if isinstance(data, list):
336 new_data = []
337 for i, elem in enumerate(data):
338 new_data.append(underscore_to_hyphen(elem))
339 elif isinstance(data, dict):
340 new_data = {}
341 for k, v in data.items():
342 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
343 else:
344 return data
345 return new_data
346
347
348 def user_peer(data, fos, check_mode=False):
349
350 state = None
351 vdom = data["vdom"]
352 parameters = None
353 state = data.get("state", None)
354 user_peer_data = data["user_peer"]
355
356 filtered_data = filter_user_peer_data(user_peer_data)
357 converted_data = underscore_to_hyphen(filtered_data)
358
359 # check_mode starts from here
360 if check_mode:
361 diff = {
362 "before": "",
363 "after": filtered_data,
364 }
365 mkeyname = fos.get_mkeyname(None, None)
366 mkey = fos.get_mkey("user", "peer", filtered_data, vdom=vdom)
367 current_data = fos.get(
368 "user", "peer", vdom=vdom, mkey=mkey, parameters=parameters
369 )
370 is_existed = (
371 current_data
372 and current_data.get("http_status") == 200
373 and (
374 mkeyname
375 and isinstance(current_data.get("results"), list)
376 and len(current_data["results"]) > 0
377 or not mkeyname
378 and current_data["results"] # global object response
379 )
380 )
381
382 # 2. if it exists and the state is 'present' then compare current settings with desired
383 if state == "present" or state is True or state is None:
384 # for non global modules, mkeyname must exist and it's a new module when mkey is None
385 if mkeyname is not None and mkey is None:
386 return False, True, filtered_data, diff
387
388 # if mkey exists then compare each other
389 # record exits and they're matched or not
390 copied_filtered_data = filtered_data.copy()
391 copied_filtered_data.pop(mkeyname, None)
392 unified_filtered_data = unify_data_format(copied_filtered_data)
393
394 current_data_results = current_data.get("results", {})
395 current_config = (
396 current_data_results[0]
397 if mkeyname
398 and isinstance(current_data_results, list)
399 and len(current_data_results) > 0
400 else current_data_results
401 )
402 if is_existed:
403 unified_current_values = find_current_values(
404 unified_filtered_data,
405 unify_data_format(current_config),
406 )
407
408 is_same = is_same_comparison(
409 serialize(unified_current_values), serialize(unified_filtered_data)
410 )
411
412 return (
413 False,
414 not is_same,
415 filtered_data,
416 {"before": unified_current_values, "after": unified_filtered_data},
417 )
418
419 # record does not exist
420 return False, True, filtered_data, diff
421
422 if state == "absent":
423 if mkey is None:
424 return (
425 False,
426 False,
427 filtered_data,
428 {"before": current_data["results"][0], "after": ""},
429 )
430
431 if is_existed:
432 return (
433 False,
434 True,
435 filtered_data,
436 {"before": current_data["results"][0], "after": ""},
437 )
438 return False, False, filtered_data, {}
439
440 return True, False, {"reason: ": "Must provide state parameter"}, {}
441 # pass post processed data to member operations
442 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
443 data_copy = data.copy()
444 data_copy["user_peer"] = filtered_data
445 fos.do_member_operation(
446 "user",
447 "peer",
448 data_copy,
449 )
450
451 if state == "present" or state is True:
452 return fos.set(
453 "user", "peer", data=converted_data, vdom=vdom, parameters=parameters
454 )
455
456 elif state == "absent":
457 return fos.delete(
458 "user",
459 "peer",
460 mkey=converted_data["name"],
461 vdom=vdom,
462 parameters=parameters,
463 )
464 else:
465 fos._module.fail_json(msg="state must be present or absent!")
466
467
468 def is_successful_status(resp):
469 return (
470 "status" in resp
471 and resp["status"] == "success"
472 or "http_status" in resp
473 and resp["http_status"] == 200
474 or "http_method" in resp
475 and resp["http_method"] == "DELETE"
476 and resp["http_status"] == 404
477 )
478
479
480 def fortios_user(data, fos, check_mode):
481
482 if data["user_peer"]:
483 resp = user_peer(data, fos, check_mode)
484 else:
485 fos._module.fail_json(msg="missing task body: %s" % ("user_peer"))
486 if isinstance(resp, tuple) and len(resp) == 4:
487 return resp
488 return (
489 not is_successful_status(resp),
490 is_successful_status(resp)
491 and (resp["revision_changed"] if "revision_changed" in resp else True),
492 resp,
493 {},
494 )
495
496
497 versioned_schema = {
498 "type": "list",
499 "elements": "dict",
500 "children": {
501 "name": {"v_range": [["v6.0.0", ""]], "type": "string", "required": True},
502 "mandatory_ca_verify": {
503 "v_range": [["v6.0.0", ""]],
504 "type": "string",
505 "options": [{"value": "enable"}, {"value": "disable"}],
506 },
507 "ca": {"v_range": [["v6.0.0", ""]], "type": "string"},
508 "subject": {"v_range": [["v6.0.0", ""]], "type": "string"},
509 "cn": {"v_range": [["v6.0.0", ""]], "type": "string"},
510 "cn_type": {
511 "v_range": [["v6.0.0", ""]],
512 "type": "string",
513 "options": [
514 {"value": "string"},
515 {"value": "email"},
516 {"value": "FQDN"},
517 {"value": "ipv4"},
518 {"value": "ipv6"},
519 ],
520 },
521 "mfa_mode": {
522 "v_range": [["v7.4.1", ""]],
523 "type": "string",
524 "options": [
525 {"value": "none"},
526 {"value": "password"},
527 {"value": "subject-identity"},
528 ],
529 },
530 "mfa_server": {"v_range": [["v7.4.1", ""]], "type": "string"},
531 "mfa_username": {"v_range": [["v7.4.1", ""]], "type": "string"},
532 "mfa_password": {"v_range": [["v7.4.1", ""]], "type": "string"},
533 "ocsp_override_server": {"v_range": [["v6.0.0", ""]], "type": "string"},
534 "two_factor": {
535 "v_range": [["v6.0.0", ""]],
536 "type": "string",
537 "options": [{"value": "enable"}, {"value": "disable"}],
538 },
539 "passwd": {"v_range": [["v6.0.0", ""]], "type": "string"},
540 "ldap_server": {"v_range": [["v6.0.0", "v7.4.0"]], "type": "string"},
541 "ldap_username": {"v_range": [["v6.0.0", "v7.4.0"]], "type": "string"},
542 "ldap_password": {"v_range": [["v6.0.0", "v7.4.0"]], "type": "string"},
543 "ldap_mode": {
544 "v_range": [["v6.0.0", "v7.4.0"]],
545 "type": "string",
546 "options": [{"value": "password"}, {"value": "principal-name"}],
547 },
548 },
549 "v_range": [["v6.0.0", ""]],
550 }
551
552
553 def main():
554 module_spec = schema_to_module_spec(versioned_schema)
555 mkeyname = "name"
556 fields = {
557 "access_token": {"required": False, "type": "str", "no_log": True},
558 "enable_log": {"required": False, "type": "bool", "default": False},
559 "vdom": {"required": False, "type": "str", "default": "root"},
560 "member_path": {"required": False, "type": "str"},
561 "member_state": {
562 "type": "str",
563 "required": False,
564 "choices": ["present", "absent"],
565 },
566 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
567 "user_peer": {
568 "required": False,
569 "type": "dict",
570 "default": None,
571 "options": {},
572 },
573 }
574 for attribute_name in module_spec["options"]:
575 fields["user_peer"]["options"][attribute_name] = module_spec["options"][
576 attribute_name
577 ]
578 if mkeyname and mkeyname == attribute_name:
579 fields["user_peer"]["options"][attribute_name]["required"] = True
580
581 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
582 check_legacy_fortiosapi(module)
583
584 is_error = False
585 has_changed = False
586 result = None
587 diff = None
588
589 versions_check_result = None
590 if module._socket_path:
591 connection = Connection(module._socket_path)
592 if "access_token" in module.params:
593 connection.set_custom_option("access_token", module.params["access_token"])
594
595 if "enable_log" in module.params:
596 connection.set_custom_option("enable_log", module.params["enable_log"])
597 else:
598 connection.set_custom_option("enable_log", False)
599 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
600 versions_check_result = check_schema_versioning(
601 fos, versioned_schema, "user_peer"
602 )
603
604 is_error, has_changed, result, diff = fortios_user(
605 module.params, fos, module.check_mode
606 )
607
608 else:
609 module.fail_json(**FAIL_SOCKET_MSG)
610
611 if versions_check_result and versions_check_result["matched"] is False:
612 module.warn(
613 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
614 )
615
616 if not is_error:
617 if versions_check_result and versions_check_result["matched"] is False:
618 module.exit_json(
619 changed=has_changed,
620 version_check_warning=versions_check_result,
621 meta=result,
622 diff=diff,
623 )
624 else:
625 module.exit_json(changed=has_changed, meta=result, diff=diff)
626 else:
627 if versions_check_result and versions_check_result["matched"] is False:
628 module.fail_json(
629 msg="Error in repo",
630 version_check_warning=versions_check_result,
631 meta=result,
632 )
633 else:
634 module.fail_json(msg="Error in repo", meta=result)
635
636
637 if __name__ == "__main__":
638 main()