Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_user_exchange.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_exchange
23 short_description: Configure MS Exchange server entries 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 exchange 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_exchange:
88 description:
89 - Configure MS Exchange server entries.
90 default: null
91 type: dict
92 suboptions:
93 auth_level:
94 description:
95 - Authentication security level used for the RPC protocol layer.
96 type: str
97 choices:
98 - 'connect'
99 - 'call'
100 - 'packet'
101 - 'integrity'
102 - 'privacy'
103 auth_type:
104 description:
105 - Authentication security type used for the RPC protocol layer.
106 type: str
107 choices:
108 - 'spnego'
109 - 'ntlm'
110 - 'kerberos'
111 auto_discover_kdc:
112 description:
113 - Enable/disable automatic discovery of KDC IP addresses.
114 type: str
115 choices:
116 - 'enable'
117 - 'disable'
118 connect_protocol:
119 description:
120 - Connection protocol used to connect to MS Exchange service.
121 type: str
122 choices:
123 - 'rpc-over-tcp'
124 - 'rpc-over-http'
125 - 'rpc-over-https'
126 domain_name:
127 description:
128 - MS Exchange server fully qualified domain name.
129 type: str
130 http_auth_type:
131 description:
132 - Authentication security type used for the HTTP transport.
133 type: str
134 choices:
135 - 'basic'
136 - 'ntlm'
137 ip:
138 description:
139 - Server IPv4 address.
140 type: str
141 kdc_ip:
142 description:
143 - KDC IPv4 addresses for Kerberos authentication.
144 type: list
145 elements: dict
146 suboptions:
147 ipv4:
148 description:
149 - KDC IPv4 addresses for Kerberos authentication.
150 required: true
151 type: str
152 name:
153 description:
154 - MS Exchange server entry name.
155 required: true
156 type: str
157 password:
158 description:
159 - Password for the specified username.
160 type: str
161 server_name:
162 description:
163 - MS Exchange server hostname.
164 type: str
165 ssl_min_proto_version:
166 description:
167 - Minimum SSL/TLS protocol version for HTTPS transport .
168 type: str
169 choices:
170 - 'default'
171 - 'SSLv3'
172 - 'TLSv1'
173 - 'TLSv1-1'
174 - 'TLSv1-2'
175 - 'TLSv1-3'
176 username:
177 description:
178 - User name used to sign in to the server. Must have proper permissions for service.
179 type: str
180 validate_server_certificate:
181 description:
182 - Enable/disable exchange server certificate validation.
183 type: str
184 choices:
185 - 'disable'
186 - 'enable'
187 """
188
189 EXAMPLES = """
190 - name: Configure MS Exchange server entries.
191 fortinet.fortios.fortios_user_exchange:
192 vdom: "{{ vdom }}"
193 state: "present"
194 access_token: "<your_own_value>"
195 user_exchange:
196 auth_level: "connect"
197 auth_type: "spnego"
198 auto_discover_kdc: "enable"
199 connect_protocol: "rpc-over-tcp"
200 domain_name: "<your_own_value>"
201 http_auth_type: "basic"
202 ip: "<your_own_value>"
203 kdc_ip:
204 -
205 ipv4: "<your_own_value>"
206 name: "default_name_12"
207 password: "<your_own_value>"
208 server_name: "<your_own_value>"
209 ssl_min_proto_version: "default"
210 username: "<your_own_value>"
211 validate_server_certificate: "disable"
212 """
213
214 RETURN = """
215 build:
216 description: Build number of the fortigate image
217 returned: always
218 type: str
219 sample: '1547'
220 http_method:
221 description: Last method used to provision the content into FortiGate
222 returned: always
223 type: str
224 sample: 'PUT'
225 http_status:
226 description: Last result given by FortiGate on last operation applied
227 returned: always
228 type: str
229 sample: "200"
230 mkey:
231 description: Master key (id) used in the last call to FortiGate
232 returned: success
233 type: str
234 sample: "id"
235 name:
236 description: Name of the table used to fulfill the request
237 returned: always
238 type: str
239 sample: "urlfilter"
240 path:
241 description: Path of the table used to fulfill the request
242 returned: always
243 type: str
244 sample: "webfilter"
245 revision:
246 description: Internal revision number
247 returned: always
248 type: str
249 sample: "17.0.2.10658"
250 serial:
251 description: Serial number of the unit
252 returned: always
253 type: str
254 sample: "FGVMEVYYQT3AB5352"
255 status:
256 description: Indication of the operation's result
257 returned: always
258 type: str
259 sample: "success"
260 vdom:
261 description: Virtual domain used
262 returned: always
263 type: str
264 sample: "root"
265 version:
266 description: Version of the FortiGate
267 returned: always
268 type: str
269 sample: "v5.6.3"
270 """
271 from ansible.module_utils.basic import AnsibleModule
272 from ansible.module_utils.connection import Connection
273 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
274 FortiOSHandler,
275 )
276 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
277 check_legacy_fortiosapi,
278 )
279 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
280 schema_to_module_spec,
281 )
282 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
283 check_schema_versioning,
284 )
285 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
286 FAIL_SOCKET_MSG,
287 )
288 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
289 remove_invalid_fields,
290 )
291 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
292 is_same_comparison,
293 )
294 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
295 serialize,
296 )
297 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
298 find_current_values,
299 )
300 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
301 unify_data_format,
302 )
303
304
305 def filter_user_exchange_data(json):
306 option_list = [
307 "auth_level",
308 "auth_type",
309 "auto_discover_kdc",
310 "connect_protocol",
311 "domain_name",
312 "http_auth_type",
313 "ip",
314 "kdc_ip",
315 "name",
316 "password",
317 "server_name",
318 "ssl_min_proto_version",
319 "username",
320 "validate_server_certificate",
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_exchange(data, fos, check_mode=False):
349
350 state = None
351 vdom = data["vdom"]
352 parameters = None
353 state = data.get("state", None)
354 user_exchange_data = data["user_exchange"]
355
356 filtered_data = filter_user_exchange_data(user_exchange_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", "exchange", filtered_data, vdom=vdom)
367 current_data = fos.get(
368 "user", "exchange", 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_exchange"] = filtered_data
445 fos.do_member_operation(
446 "user",
447 "exchange",
448 data_copy,
449 )
450
451 if state == "present" or state is True:
452 return fos.set(
453 "user", "exchange", data=converted_data, vdom=vdom, parameters=parameters
454 )
455
456 elif state == "absent":
457 return fos.delete(
458 "user",
459 "exchange",
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_exchange"]:
483 resp = user_exchange(data, fos, check_mode)
484 else:
485 fos._module.fail_json(msg="missing task body: %s" % ("user_exchange"))
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.2.0", ""]], "type": "string", "required": True},
502 "server_name": {"v_range": [["v6.2.0", ""]], "type": "string"},
503 "domain_name": {"v_range": [["v6.2.0", ""]], "type": "string"},
504 "username": {"v_range": [["v6.2.0", ""]], "type": "string"},
505 "password": {"v_range": [["v6.2.0", ""]], "type": "string"},
506 "ip": {"v_range": [["v6.2.0", ""]], "type": "string"},
507 "connect_protocol": {
508 "v_range": [["v6.2.0", ""]],
509 "type": "string",
510 "options": [
511 {"value": "rpc-over-tcp"},
512 {"value": "rpc-over-http"},
513 {"value": "rpc-over-https"},
514 ],
515 },
516 "validate_server_certificate": {
517 "v_range": [["v7.6.3", ""]],
518 "type": "string",
519 "options": [{"value": "disable"}, {"value": "enable"}],
520 },
521 "auth_type": {
522 "v_range": [["v6.2.0", ""]],
523 "type": "string",
524 "options": [{"value": "spnego"}, {"value": "ntlm"}, {"value": "kerberos"}],
525 },
526 "auth_level": {
527 "v_range": [["v6.2.0", ""]],
528 "type": "string",
529 "options": [
530 {"value": "connect"},
531 {"value": "call"},
532 {"value": "packet"},
533 {"value": "integrity"},
534 {"value": "privacy"},
535 ],
536 },
537 "http_auth_type": {
538 "v_range": [["v6.2.0", ""]],
539 "type": "string",
540 "options": [{"value": "basic"}, {"value": "ntlm"}],
541 },
542 "ssl_min_proto_version": {
543 "v_range": [["v6.2.0", ""]],
544 "type": "string",
545 "options": [
546 {"value": "default"},
547 {"value": "SSLv3"},
548 {"value": "TLSv1"},
549 {"value": "TLSv1-1"},
550 {"value": "TLSv1-2"},
551 {"value": "TLSv1-3", "v_range": [["v7.4.1", ""]]},
552 ],
553 },
554 "auto_discover_kdc": {
555 "v_range": [["v6.4.0", ""]],
556 "type": "string",
557 "options": [{"value": "enable"}, {"value": "disable"}],
558 },
559 "kdc_ip": {
560 "type": "list",
561 "elements": "dict",
562 "children": {
563 "ipv4": {
564 "v_range": [["v6.2.0", ""]],
565 "type": "string",
566 "required": True,
567 }
568 },
569 "v_range": [["v6.2.0", ""]],
570 },
571 },
572 "v_range": [["v6.2.0", ""]],
573 }
574
575
576 def main():
577 module_spec = schema_to_module_spec(versioned_schema)
578 mkeyname = "name"
579 fields = {
580 "access_token": {"required": False, "type": "str", "no_log": True},
581 "enable_log": {"required": False, "type": "bool", "default": False},
582 "vdom": {"required": False, "type": "str", "default": "root"},
583 "member_path": {"required": False, "type": "str"},
584 "member_state": {
585 "type": "str",
586 "required": False,
587 "choices": ["present", "absent"],
588 },
589 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
590 "user_exchange": {
591 "required": False,
592 "type": "dict",
593 "default": None,
594 "options": {},
595 },
596 }
597 for attribute_name in module_spec["options"]:
598 fields["user_exchange"]["options"][attribute_name] = module_spec["options"][
599 attribute_name
600 ]
601 if mkeyname and mkeyname == attribute_name:
602 fields["user_exchange"]["options"][attribute_name]["required"] = True
603
604 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
605 check_legacy_fortiosapi(module)
606
607 is_error = False
608 has_changed = False
609 result = None
610 diff = None
611
612 versions_check_result = None
613 if module._socket_path:
614 connection = Connection(module._socket_path)
615 if "access_token" in module.params:
616 connection.set_custom_option("access_token", module.params["access_token"])
617
618 if "enable_log" in module.params:
619 connection.set_custom_option("enable_log", module.params["enable_log"])
620 else:
621 connection.set_custom_option("enable_log", False)
622 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
623 versions_check_result = check_schema_versioning(
624 fos, versioned_schema, "user_exchange"
625 )
626
627 is_error, has_changed, result, diff = fortios_user(
628 module.params, fos, module.check_mode
629 )
630
631 else:
632 module.fail_json(**FAIL_SOCKET_MSG)
633
634 if versions_check_result and versions_check_result["matched"] is False:
635 module.warn(
636 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
637 )
638
639 if not is_error:
640 if versions_check_result and versions_check_result["matched"] is False:
641 module.exit_json(
642 changed=has_changed,
643 version_check_warning=versions_check_result,
644 meta=result,
645 diff=diff,
646 )
647 else:
648 module.exit_json(changed=has_changed, meta=result, diff=diff)
649 else:
650 if versions_check_result and versions_check_result["matched"] is False:
651 module.fail_json(
652 msg="Error in repo",
653 version_check_warning=versions_check_result,
654 meta=result,
655 )
656 else:
657 module.fail_json(msg="Error in repo", meta=result)
658
659
660 if __name__ == "__main__":
661 main()