Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_cifs_profile.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_cifs_profile
23 short_description: Configure CIFS profile 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 cifs feature and profile 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 cifs_profile:
88 description:
89 - Configure CIFS profile.
90 default: null
91 type: dict
92 suboptions:
93 domain_controller:
94 description:
95 - Domain for which to decrypt CIFS traffic. Source credential-store.domain-controller.server-name.
96 type: str
97 file_filter:
98 description:
99 - File filter.
100 type: dict
101 suboptions:
102 entries:
103 description:
104 - File filter entries.
105 type: list
106 elements: dict
107 suboptions:
108 action:
109 description:
110 - Action taken for matched file.
111 type: str
112 choices:
113 - 'log'
114 - 'block'
115 comment:
116 description:
117 - Comment.
118 type: str
119 direction:
120 description:
121 - Match files transmitted in the session"s originating or reply direction.
122 type: str
123 choices:
124 - 'incoming'
125 - 'outgoing'
126 - 'any'
127 file_type:
128 description:
129 - Select file type.
130 type: list
131 elements: dict
132 suboptions:
133 name:
134 description:
135 - File type name. Source antivirus.filetype.name.
136 required: true
137 type: str
138 filter:
139 description:
140 - Add a file filter.
141 required: true
142 type: str
143 protocol:
144 description:
145 - Protocols to apply with.
146 type: list
147 elements: str
148 choices:
149 - 'cifs'
150 log:
151 description:
152 - Enable/disable file filter logging.
153 type: str
154 choices:
155 - 'enable'
156 - 'disable'
157 status:
158 description:
159 - Enable/disable file filter.
160 type: str
161 choices:
162 - 'enable'
163 - 'disable'
164 name:
165 description:
166 - Profile name.
167 required: true
168 type: str
169 server_credential_type:
170 description:
171 - CIFS server credential type.
172 type: str
173 choices:
174 - 'none'
175 - 'credential-replication'
176 - 'credential-keytab'
177 server_keytab:
178 description:
179 - Server keytab.
180 type: list
181 elements: dict
182 suboptions:
183 keytab:
184 description:
185 - Base64 encoded keytab file containing credential of the server.
186 type: str
187 password:
188 description:
189 - Password for keytab.
190 type: str
191 principal:
192 description:
193 - Service principal. For example, "host/[email protected]".
194 required: true
195 type: str
196 """
197
198 EXAMPLES = """
199 - name: Configure CIFS profile.
200 fortinet.fortios.fortios_cifs_profile:
201 vdom: "{{ vdom }}"
202 state: "present"
203 access_token: "<your_own_value>"
204 cifs_profile:
205 domain_controller: "<your_own_value> (source credential-store.domain-controller.server-name)"
206 file_filter:
207 entries:
208 -
209 action: "log"
210 comment: "Comment."
211 direction: "incoming"
212 file_type:
213 -
214 name: "default_name_10 (source antivirus.filetype.name)"
215 filter: "<your_own_value>"
216 protocol: "cifs"
217 log: "enable"
218 status: "enable"
219 name: "default_name_15"
220 server_credential_type: "none"
221 server_keytab:
222 -
223 keytab: "<your_own_value>"
224 password: "<your_own_value>"
225 principal: "<your_own_value>"
226 """
227
228 RETURN = """
229 build:
230 description: Build number of the fortigate image
231 returned: always
232 type: str
233 sample: '1547'
234 http_method:
235 description: Last method used to provision the content into FortiGate
236 returned: always
237 type: str
238 sample: 'PUT'
239 http_status:
240 description: Last result given by FortiGate on last operation applied
241 returned: always
242 type: str
243 sample: "200"
244 mkey:
245 description: Master key (id) used in the last call to FortiGate
246 returned: success
247 type: str
248 sample: "id"
249 name:
250 description: Name of the table used to fulfill the request
251 returned: always
252 type: str
253 sample: "urlfilter"
254 path:
255 description: Path of the table used to fulfill the request
256 returned: always
257 type: str
258 sample: "webfilter"
259 revision:
260 description: Internal revision number
261 returned: always
262 type: str
263 sample: "17.0.2.10658"
264 serial:
265 description: Serial number of the unit
266 returned: always
267 type: str
268 sample: "FGVMEVYYQT3AB5352"
269 status:
270 description: Indication of the operation's result
271 returned: always
272 type: str
273 sample: "success"
274 vdom:
275 description: Virtual domain used
276 returned: always
277 type: str
278 sample: "root"
279 version:
280 description: Version of the FortiGate
281 returned: always
282 type: str
283 sample: "v5.6.3"
284 """
285 from ansible.module_utils.basic import AnsibleModule
286 from ansible.module_utils.connection import Connection
287 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
288 FortiOSHandler,
289 )
290 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
291 check_legacy_fortiosapi,
292 )
293 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
294 schema_to_module_spec,
295 )
296 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
297 check_schema_versioning,
298 )
299 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
300 FAIL_SOCKET_MSG,
301 )
302 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
303 remove_invalid_fields,
304 )
305 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
306 is_same_comparison,
307 )
308 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
309 serialize,
310 )
311 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
312 find_current_values,
313 )
314 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
315 unify_data_format,
316 )
317
318
319 def filter_cifs_profile_data(json):
320 option_list = [
321 "domain_controller",
322 "file_filter",
323 "name",
324 "server_credential_type",
325 "server_keytab",
326 ]
327
328 json = remove_invalid_fields(json)
329 dictionary = {}
330
331 for attribute in option_list:
332 if attribute in json and json[attribute] is not None:
333 dictionary[attribute] = json[attribute]
334
335 return dictionary
336
337
338 def flatten_single_path(data, path, index):
339 if (
340 not data
341 or index == len(path)
342 or path[index] not in data
343 or (not data[path[index]] and not isinstance(data[path[index]], list))
344 ):
345 return
346
347 if index == len(path) - 1:
348 data[path[index]] = " ".join(str(elem) for elem in data[path[index]])
349 if len(data[path[index]]) == 0:
350 data[path[index]] = None
351 elif isinstance(data[path[index]], list):
352 for value in data[path[index]]:
353 flatten_single_path(value, path, index + 1)
354 else:
355 flatten_single_path(data[path[index]], path, index + 1)
356
357
358 def flatten_multilists_attributes(data):
359 multilist_attrs = [
360 ["file_filter", "entries", "protocol"],
361 ]
362
363 for attr in multilist_attrs:
364 flatten_single_path(data, attr, 0)
365
366 return data
367
368
369 def underscore_to_hyphen(data):
370 new_data = None
371 if isinstance(data, list):
372 new_data = []
373 for i, elem in enumerate(data):
374 new_data.append(underscore_to_hyphen(elem))
375 elif isinstance(data, dict):
376 new_data = {}
377 for k, v in data.items():
378 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
379 else:
380 return data
381 return new_data
382
383
384 def cifs_profile(data, fos, check_mode=False):
385
386 state = None
387 vdom = data["vdom"]
388 parameters = None
389 state = data.get("state", None)
390 cifs_profile_data = data["cifs_profile"]
391
392 filtered_data = filter_cifs_profile_data(cifs_profile_data)
393 filtered_data = flatten_multilists_attributes(filtered_data)
394 converted_data = underscore_to_hyphen(filtered_data)
395
396 # check_mode starts from here
397 if check_mode:
398 diff = {
399 "before": "",
400 "after": filtered_data,
401 }
402 mkeyname = fos.get_mkeyname(None, None)
403 mkey = fos.get_mkey("cifs", "profile", filtered_data, vdom=vdom)
404 current_data = fos.get(
405 "cifs", "profile", vdom=vdom, mkey=mkey, parameters=parameters
406 )
407 is_existed = (
408 current_data
409 and current_data.get("http_status") == 200
410 and (
411 mkeyname
412 and isinstance(current_data.get("results"), list)
413 and len(current_data["results"]) > 0
414 or not mkeyname
415 and current_data["results"] # global object response
416 )
417 )
418
419 # 2. if it exists and the state is 'present' then compare current settings with desired
420 if state == "present" or state is True or state is None:
421 # for non global modules, mkeyname must exist and it's a new module when mkey is None
422 if mkeyname is not None and mkey is None:
423 return False, True, filtered_data, diff
424
425 # if mkey exists then compare each other
426 # record exits and they're matched or not
427 copied_filtered_data = filtered_data.copy()
428 copied_filtered_data.pop(mkeyname, None)
429 unified_filtered_data = unify_data_format(copied_filtered_data)
430
431 current_data_results = current_data.get("results", {})
432 current_config = (
433 current_data_results[0]
434 if mkeyname
435 and isinstance(current_data_results, list)
436 and len(current_data_results) > 0
437 else current_data_results
438 )
439 if is_existed:
440 unified_current_values = find_current_values(
441 unified_filtered_data,
442 unify_data_format(current_config),
443 )
444
445 is_same = is_same_comparison(
446 serialize(unified_current_values), serialize(unified_filtered_data)
447 )
448
449 return (
450 False,
451 not is_same,
452 filtered_data,
453 {"before": unified_current_values, "after": unified_filtered_data},
454 )
455
456 # record does not exist
457 return False, True, filtered_data, diff
458
459 if state == "absent":
460 if mkey is None:
461 return (
462 False,
463 False,
464 filtered_data,
465 {"before": current_data["results"][0], "after": ""},
466 )
467
468 if is_existed:
469 return (
470 False,
471 True,
472 filtered_data,
473 {"before": current_data["results"][0], "after": ""},
474 )
475 return False, False, filtered_data, {}
476
477 return True, False, {"reason: ": "Must provide state parameter"}, {}
478 # pass post processed data to member operations
479 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
480 data_copy = data.copy()
481 data_copy["cifs_profile"] = filtered_data
482 fos.do_member_operation(
483 "cifs",
484 "profile",
485 data_copy,
486 )
487
488 if state == "present" or state is True:
489 return fos.set(
490 "cifs", "profile", data=converted_data, vdom=vdom, parameters=parameters
491 )
492
493 elif state == "absent":
494 return fos.delete(
495 "cifs",
496 "profile",
497 mkey=converted_data["name"],
498 vdom=vdom,
499 parameters=parameters,
500 )
501 else:
502 fos._module.fail_json(msg="state must be present or absent!")
503
504
505 def is_successful_status(resp):
506 return (
507 "status" in resp
508 and resp["status"] == "success"
509 or "http_status" in resp
510 and resp["http_status"] == 200
511 or "http_method" in resp
512 and resp["http_method"] == "DELETE"
513 and resp["http_status"] == 404
514 )
515
516
517 def fortios_cifs(data, fos, check_mode):
518
519 if data["cifs_profile"]:
520 resp = cifs_profile(data, fos, check_mode)
521 else:
522 fos._module.fail_json(msg="missing task body: %s" % ("cifs_profile"))
523 if isinstance(resp, tuple) and len(resp) == 4:
524 return resp
525 return (
526 not is_successful_status(resp),
527 is_successful_status(resp)
528 and (resp["revision_changed"] if "revision_changed" in resp else True),
529 resp,
530 {},
531 )
532
533
534 versioned_schema = {
535 "type": "list",
536 "elements": "dict",
537 "children": {
538 "name": {
539 "v_range": [["v6.2.0", "v6.2.7"], ["v6.4.1", "v6.4.1"]],
540 "type": "string",
541 "required": True,
542 },
543 "server_credential_type": {
544 "v_range": [["v6.2.0", "v6.2.7"], ["v6.4.1", "v6.4.1"]],
545 "type": "string",
546 "options": [
547 {"value": "none"},
548 {"value": "credential-replication"},
549 {"value": "credential-keytab"},
550 ],
551 },
552 "domain_controller": {
553 "v_range": [["v6.2.0", "v6.2.7"], ["v6.4.1", "v6.4.1"]],
554 "type": "string",
555 },
556 "server_keytab": {
557 "type": "list",
558 "elements": "dict",
559 "children": {
560 "principal": {
561 "v_range": [["v6.2.0", "v6.2.7"], ["v6.4.1", "v6.4.1"]],
562 "type": "string",
563 "required": True,
564 },
565 "keytab": {
566 "v_range": [["v6.2.0", "v6.2.7"], ["v6.4.1", "v6.4.1"]],
567 "type": "string",
568 },
569 "password": {"v_range": [["v6.2.3", "v6.2.3"]], "type": "string"},
570 },
571 "v_range": [["v6.2.0", "v6.2.7"], ["v6.4.1", "v6.4.1"]],
572 },
573 "file_filter": {
574 "v_range": [["v6.2.0", "v6.2.7"]],
575 "type": "dict",
576 "children": {
577 "status": {
578 "v_range": [["v6.2.0", "v6.2.7"]],
579 "type": "string",
580 "options": [{"value": "enable"}, {"value": "disable"}],
581 },
582 "log": {
583 "v_range": [["v6.2.0", "v6.2.7"]],
584 "type": "string",
585 "options": [{"value": "enable"}, {"value": "disable"}],
586 },
587 "entries": {
588 "type": "list",
589 "elements": "dict",
590 "children": {
591 "filter": {
592 "v_range": [["v6.2.0", "v6.2.7"]],
593 "type": "string",
594 "required": True,
595 },
596 "comment": {
597 "v_range": [["v6.2.0", "v6.2.7"]],
598 "type": "string",
599 },
600 "action": {
601 "v_range": [["v6.2.0", "v6.2.7"]],
602 "type": "string",
603 "options": [{"value": "log"}, {"value": "block"}],
604 },
605 "direction": {
606 "v_range": [["v6.2.0", "v6.2.7"]],
607 "type": "string",
608 "options": [
609 {"value": "incoming"},
610 {"value": "outgoing"},
611 {"value": "any"},
612 ],
613 },
614 "file_type": {
615 "type": "list",
616 "elements": "dict",
617 "children": {
618 "name": {
619 "v_range": [["v6.2.0", "v6.2.7"]],
620 "type": "string",
621 "required": True,
622 }
623 },
624 "v_range": [["v6.2.0", "v6.2.7"]],
625 },
626 "protocol": {
627 "v_range": [["v6.2.3", "v6.2.3"]],
628 "type": "list",
629 "options": [{"value": "cifs"}],
630 "multiple_values": True,
631 "elements": "str",
632 },
633 },
634 "v_range": [["v6.2.0", "v6.2.7"]],
635 },
636 },
637 },
638 },
639 "v_range": [["v6.2.0", "v6.2.7"], ["v6.4.1", "v6.4.1"]],
640 }
641
642
643 def main():
644 module_spec = schema_to_module_spec(versioned_schema)
645 mkeyname = "name"
646 fields = {
647 "access_token": {"required": False, "type": "str", "no_log": True},
648 "enable_log": {"required": False, "type": "bool", "default": False},
649 "vdom": {"required": False, "type": "str", "default": "root"},
650 "member_path": {"required": False, "type": "str"},
651 "member_state": {
652 "type": "str",
653 "required": False,
654 "choices": ["present", "absent"],
655 },
656 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
657 "cifs_profile": {
658 "required": False,
659 "type": "dict",
660 "default": None,
661 "options": {},
662 },
663 }
664 for attribute_name in module_spec["options"]:
665 fields["cifs_profile"]["options"][attribute_name] = module_spec["options"][
666 attribute_name
667 ]
668 if mkeyname and mkeyname == attribute_name:
669 fields["cifs_profile"]["options"][attribute_name]["required"] = True
670
671 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
672 check_legacy_fortiosapi(module)
673
674 is_error = False
675 has_changed = False
676 result = None
677 diff = None
678
679 versions_check_result = None
680 if module._socket_path:
681 connection = Connection(module._socket_path)
682 if "access_token" in module.params:
683 connection.set_custom_option("access_token", module.params["access_token"])
684
685 if "enable_log" in module.params:
686 connection.set_custom_option("enable_log", module.params["enable_log"])
687 else:
688 connection.set_custom_option("enable_log", False)
689 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
690 versions_check_result = check_schema_versioning(
691 fos, versioned_schema, "cifs_profile"
692 )
693
694 is_error, has_changed, result, diff = fortios_cifs(
695 module.params, fos, module.check_mode
696 )
697
698 else:
699 module.fail_json(**FAIL_SOCKET_MSG)
700
701 if versions_check_result and versions_check_result["matched"] is False:
702 module.warn(
703 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
704 )
705
706 if not is_error:
707 if versions_check_result and versions_check_result["matched"] is False:
708 module.exit_json(
709 changed=has_changed,
710 version_check_warning=versions_check_result,
711 meta=result,
712 diff=diff,
713 )
714 else:
715 module.exit_json(changed=has_changed, meta=result, diff=diff)
716 else:
717 if versions_check_result and versions_check_result["matched"] is False:
718 module.fail_json(
719 msg="Error in repo",
720 version_check_warning=versions_check_result,
721 meta=result,
722 )
723 else:
724 module.fail_json(msg="Error in repo", meta=result)
725
726
727 if __name__ == "__main__":
728 main()