Debian Codegraph @

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