Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_dlp_settings.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_dlp_settings
23 short_description: Configure settings for DLP 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 dlp feature and settings 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 dlp_settings:
80 description:
81 - Configure settings for DLP.
82 default: null
83 type: dict
84 suboptions:
85 cache_mem_percent:
86 description:
87 - Maximum percentage of available memory allocated to caching DLP fingerprints (1 - 15).
88 type: int
89 chunk_size:
90 description:
91 - Maximum fingerprint chunk size. Caution, changing this setting will flush the entire database.
92 type: int
93 config_builder_timeout:
94 description:
95 - Maximum time allowed for building a single DLP profile .
96 type: int
97 db_mode:
98 description:
99 - Behavior when the maximum size is reached in the DLP fingerprint database.
100 type: str
101 choices:
102 - 'stop-adding'
103 - 'remove-modified-then-oldest'
104 - 'remove-oldest'
105 size:
106 description:
107 - Maximum total size of files within the DLP fingerprint database (MB).
108 type: int
109 storage_device:
110 description:
111 - Storage device name. Source system.storage.name.
112 type: str
113 """
114
115 EXAMPLES = """
116 - name: Configure settings for DLP.
117 fortinet.fortios.fortios_dlp_settings:
118 vdom: "{{ vdom }}"
119 dlp_settings:
120 cache_mem_percent: "2"
121 chunk_size: "2800"
122 config_builder_timeout: "60"
123 db_mode: "stop-adding"
124 size: "16"
125 storage_device: "<your_own_value> (source system.storage.name)"
126 """
127
128 RETURN = """
129 build:
130 description: Build number of the fortigate image
131 returned: always
132 type: str
133 sample: '1547'
134 http_method:
135 description: Last method used to provision the content into FortiGate
136 returned: always
137 type: str
138 sample: 'PUT'
139 http_status:
140 description: Last result given by FortiGate on last operation applied
141 returned: always
142 type: str
143 sample: "200"
144 mkey:
145 description: Master key (id) used in the last call to FortiGate
146 returned: success
147 type: str
148 sample: "id"
149 name:
150 description: Name of the table used to fulfill the request
151 returned: always
152 type: str
153 sample: "urlfilter"
154 path:
155 description: Path of the table used to fulfill the request
156 returned: always
157 type: str
158 sample: "webfilter"
159 revision:
160 description: Internal revision number
161 returned: always
162 type: str
163 sample: "17.0.2.10658"
164 serial:
165 description: Serial number of the unit
166 returned: always
167 type: str
168 sample: "FGVMEVYYQT3AB5352"
169 status:
170 description: Indication of the operation's result
171 returned: always
172 type: str
173 sample: "success"
174 vdom:
175 description: Virtual domain used
176 returned: always
177 type: str
178 sample: "root"
179 version:
180 description: Version of the FortiGate
181 returned: always
182 type: str
183 sample: "v5.6.3"
184 """
185 from ansible.module_utils.basic import AnsibleModule
186 from ansible.module_utils.connection import Connection
187 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
188 FortiOSHandler,
189 )
190 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
191 check_legacy_fortiosapi,
192 )
193 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
194 schema_to_module_spec,
195 )
196 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
197 check_schema_versioning,
198 )
199 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
200 FAIL_SOCKET_MSG,
201 )
202 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
203 remove_invalid_fields,
204 )
205 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
206 is_same_comparison,
207 )
208 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
209 serialize,
210 )
211 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
212 find_current_values,
213 )
214 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
215 unify_data_format,
216 )
217
218
219 def filter_dlp_settings_data(json):
220 option_list = [
221 "cache_mem_percent",
222 "chunk_size",
223 "config_builder_timeout",
224 "db_mode",
225 "size",
226 "storage_device",
227 ]
228
229 json = remove_invalid_fields(json)
230 dictionary = {}
231
232 for attribute in option_list:
233 if attribute in json and json[attribute] is not None:
234 dictionary[attribute] = json[attribute]
235
236 return dictionary
237
238
239 def underscore_to_hyphen(data):
240 new_data = None
241 if isinstance(data, list):
242 new_data = []
243 for i, elem in enumerate(data):
244 new_data.append(underscore_to_hyphen(elem))
245 elif isinstance(data, dict):
246 new_data = {}
247 for k, v in data.items():
248 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
249 else:
250 return data
251 return new_data
252
253
254 def dlp_settings(data, fos, check_mode=False):
255
256 state = None
257 vdom = data["vdom"]
258 parameters = None
259 state = data.get("state", None)
260 dlp_settings_data = data["dlp_settings"]
261
262 filtered_data = filter_dlp_settings_data(dlp_settings_data)
263 converted_data = underscore_to_hyphen(filtered_data)
264
265 # check_mode starts from here
266 if check_mode:
267 diff = {
268 "before": "",
269 "after": filtered_data,
270 }
271 mkeyname = fos.get_mkeyname(None, None)
272 mkey = fos.get_mkey("dlp", "settings", filtered_data, vdom=vdom)
273 current_data = fos.get(
274 "dlp", "settings", vdom=vdom, mkey=mkey, parameters=parameters
275 )
276 is_existed = (
277 current_data
278 and current_data.get("http_status") == 200
279 and (
280 mkeyname
281 and isinstance(current_data.get("results"), list)
282 and len(current_data["results"]) > 0
283 or not mkeyname
284 and current_data["results"] # global object response
285 )
286 )
287
288 # 2. if it exists and the state is 'present' then compare current settings with desired
289 if state == "present" or state is True or state is None:
290 # for non global modules, mkeyname must exist and it's a new module when mkey is None
291 if mkeyname is not None and mkey is None:
292 return False, True, filtered_data, diff
293
294 # if mkey exists then compare each other
295 # record exits and they're matched or not
296 copied_filtered_data = filtered_data.copy()
297 copied_filtered_data.pop(mkeyname, None)
298 unified_filtered_data = unify_data_format(copied_filtered_data)
299
300 current_data_results = current_data.get("results", {})
301 current_config = (
302 current_data_results[0]
303 if mkeyname
304 and isinstance(current_data_results, list)
305 and len(current_data_results) > 0
306 else current_data_results
307 )
308 if is_existed:
309 unified_current_values = find_current_values(
310 unified_filtered_data,
311 unify_data_format(current_config),
312 )
313
314 is_same = is_same_comparison(
315 serialize(unified_current_values), serialize(unified_filtered_data)
316 )
317
318 return (
319 False,
320 not is_same,
321 filtered_data,
322 {"before": unified_current_values, "after": unified_filtered_data},
323 )
324
325 # record does not exist
326 return False, True, filtered_data, diff
327
328 if state == "absent":
329 if mkey is None:
330 return (
331 False,
332 False,
333 filtered_data,
334 {"before": current_data["results"][0], "after": ""},
335 )
336
337 if is_existed:
338 return (
339 False,
340 True,
341 filtered_data,
342 {"before": current_data["results"][0], "after": ""},
343 )
344 return False, False, filtered_data, {}
345
346 return True, False, {"reason: ": "Must provide state parameter"}, {}
347 # pass post processed data to member operations
348 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
349 data_copy = data.copy()
350 data_copy["dlp_settings"] = filtered_data
351 fos.do_member_operation(
352 "dlp",
353 "settings",
354 data_copy,
355 )
356
357 return fos.set(
358 "dlp", "settings", data=converted_data, vdom=vdom, parameters=parameters
359 )
360
361
362 def is_successful_status(resp):
363 return (
364 "status" in resp
365 and resp["status"] == "success"
366 or "http_status" in resp
367 and resp["http_status"] == 200
368 or "http_method" in resp
369 and resp["http_method"] == "DELETE"
370 and resp["http_status"] == 404
371 )
372
373
374 def fortios_dlp(data, fos, check_mode):
375
376 if data["dlp_settings"]:
377 resp = dlp_settings(data, fos, check_mode)
378 else:
379 fos._module.fail_json(msg="missing task body: %s" % ("dlp_settings"))
380 if isinstance(resp, tuple) and len(resp) == 4:
381 return resp
382 return (
383 not is_successful_status(resp),
384 is_successful_status(resp)
385 and (resp["revision_changed"] if "revision_changed" in resp else True),
386 resp,
387 {},
388 )
389
390
391 versioned_schema = {
392 "v_range": [["v6.0.0", ""]],
393 "type": "dict",
394 "children": {
395 "storage_device": {"v_range": [["v6.0.0", ""]], "type": "string"},
396 "size": {"v_range": [["v6.0.0", ""]], "type": "integer"},
397 "db_mode": {
398 "v_range": [["v6.0.0", ""]],
399 "type": "string",
400 "options": [
401 {"value": "stop-adding"},
402 {"value": "remove-modified-then-oldest"},
403 {"value": "remove-oldest"},
404 ],
405 },
406 "cache_mem_percent": {"v_range": [["v6.0.0", ""]], "type": "integer"},
407 "chunk_size": {"v_range": [["v6.0.0", ""]], "type": "integer"},
408 "config_builder_timeout": {"v_range": [["v7.6.1", ""]], "type": "integer"},
409 },
410 }
411
412
413 def main():
414 module_spec = schema_to_module_spec(versioned_schema)
415 mkeyname = None
416 fields = {
417 "access_token": {"required": False, "type": "str", "no_log": True},
418 "enable_log": {"required": False, "type": "bool", "default": False},
419 "vdom": {"required": False, "type": "str", "default": "root"},
420 "member_path": {"required": False, "type": "str"},
421 "member_state": {
422 "type": "str",
423 "required": False,
424 "choices": ["present", "absent"],
425 },
426 "dlp_settings": {
427 "required": False,
428 "type": "dict",
429 "default": None,
430 "options": {},
431 },
432 }
433 for attribute_name in module_spec["options"]:
434 fields["dlp_settings"]["options"][attribute_name] = module_spec["options"][
435 attribute_name
436 ]
437 if mkeyname and mkeyname == attribute_name:
438 fields["dlp_settings"]["options"][attribute_name]["required"] = True
439
440 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
441 check_legacy_fortiosapi(module)
442
443 is_error = False
444 has_changed = False
445 result = None
446 diff = None
447
448 versions_check_result = None
449 if module._socket_path:
450 connection = Connection(module._socket_path)
451 if "access_token" in module.params:
452 connection.set_custom_option("access_token", module.params["access_token"])
453
454 if "enable_log" in module.params:
455 connection.set_custom_option("enable_log", module.params["enable_log"])
456 else:
457 connection.set_custom_option("enable_log", False)
458 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
459 versions_check_result = check_schema_versioning(
460 fos, versioned_schema, "dlp_settings"
461 )
462
463 is_error, has_changed, result, diff = fortios_dlp(
464 module.params, fos, module.check_mode
465 )
466
467 else:
468 module.fail_json(**FAIL_SOCKET_MSG)
469
470 if versions_check_result and versions_check_result["matched"] is False:
471 module.warn(
472 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
473 )
474
475 if not is_error:
476 if versions_check_result and versions_check_result["matched"] is False:
477 module.exit_json(
478 changed=has_changed,
479 version_check_warning=versions_check_result,
480 meta=result,
481 diff=diff,
482 )
483 else:
484 module.exit_json(changed=has_changed, meta=result, diff=diff)
485 else:
486 if versions_check_result and versions_check_result["matched"] is False:
487 module.fail_json(
488 msg="Error in repo",
489 version_check_warning=versions_check_result,
490 meta=result,
491 )
492 else:
493 module.fail_json(msg="Error in repo", meta=result)
494
495
496 if __name__ == "__main__":
497 main()