Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_dlp_filepattern.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_filepattern
23 short_description: Configure file patterns 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 filepattern 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 - We highly recommend using your own value as the id instead of 0, while '0' is a special placeholder that allows the backend to assign the latest
39 available number for the object, it does have limitations. Please find more details in Q&A.
40 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
41
42 - The module supports check_mode.
43
44 requirements:
45 - ansible>=2.16
46 options:
47 access_token:
48 description:
49 - Token-based authentication.
50 Generated from GUI of Fortigate.
51 type: str
52 required: false
53 enable_log:
54 description:
55 - Enable/Disable logging for task.
56 type: bool
57 required: false
58 default: false
59 vdom:
60 description:
61 - Virtual domain, among those defined previously. A vdom is a
62 virtual instance of the FortiGate that can be configured and
63 used as a different unit.
64 type: str
65 default: root
66 member_path:
67 type: str
68 description:
69 - Member attribute path to operate on.
70 - Delimited by a slash character if there are more than one attribute.
71 - Parameter marked with member_path is legitimate for doing member operation.
72 member_state:
73 type: str
74 description:
75 - Add or delete a member under specified attribute path.
76 - When member_state is specified, the state option is ignored.
77 choices:
78 - 'present'
79 - 'absent'
80
81 state:
82 description:
83 - Indicates whether to create or remove the object.
84 type: str
85 required: true
86 choices:
87 - 'present'
88 - 'absent'
89 dlp_filepattern:
90 description:
91 - Configure file patterns used by DLP blocking.
92 default: null
93 type: dict
94 suboptions:
95 comment:
96 description:
97 - Optional comments.
98 type: str
99 entries:
100 description:
101 - Configure file patterns used by DLP blocking.
102 type: list
103 elements: dict
104 suboptions:
105 file_type:
106 description:
107 - Select a file type.
108 type: str
109 choices:
110 - '7z'
111 - 'arj'
112 - 'cab'
113 - 'lzh'
114 - 'rar'
115 - 'tar'
116 - 'zip'
117 - 'bzip'
118 - 'gzip'
119 - 'bzip2'
120 - 'xz'
121 - 'bat'
122 - 'uue'
123 - 'mime'
124 - 'base64'
125 - 'binhex'
126 - 'elf'
127 - 'exe'
128 - 'dll'
129 - 'jnlp'
130 - 'hta'
131 - 'html'
132 - 'jad'
133 - 'class'
134 - 'cod'
135 - 'javascript'
136 - 'msoffice'
137 - 'msofficex'
138 - 'fsg'
139 - 'upx'
140 - 'petite'
141 - 'aspack'
142 - 'sis'
143 - 'hlp'
144 - 'activemime'
145 - 'jpeg'
146 - 'gif'
147 - 'tiff'
148 - 'png'
149 - 'bmp'
150 - 'unknown'
151 - 'mpeg'
152 - 'mov'
153 - 'mp3'
154 - 'wma'
155 - 'wav'
156 - 'pdf'
157 - 'avi'
158 - 'rm'
159 - 'torrent'
160 - 'hibun'
161 - 'msi'
162 - 'mach-o'
163 - 'dmg'
164 - '.net'
165 - 'xar'
166 - 'chm'
167 - 'iso'
168 - 'crx'
169 - 'flac'
170 - 'registry'
171 - 'hwp'
172 - 'rpm'
173 - 'genscript'
174 - 'python'
175 - 'c/cpp'
176 - 'pfile'
177 - 'lzip'
178 - 'wasm'
179 - 'sylk'
180 - 'shellscript'
181 - 'msc'
182 - 'ignored'
183 filter_type:
184 description:
185 - Filter by file name pattern or by file type.
186 type: str
187 choices:
188 - 'pattern'
189 - 'type'
190 pattern:
191 description:
192 - Add a file name pattern.
193 required: true
194 type: str
195 id:
196 description:
197 - ID. see <a href='#notes'>Notes</a>.
198 required: true
199 type: int
200 name:
201 description:
202 - Name of table containing the file pattern list.
203 type: str
204 """
205
206 EXAMPLES = """
207 - name: Configure file patterns used by DLP blocking.
208 fortinet.fortios.fortios_dlp_filepattern:
209 vdom: "{{ vdom }}"
210 state: "present"
211 access_token: "<your_own_value>"
212 dlp_filepattern:
213 comment: "Optional comments."
214 entries:
215 -
216 file_type: "7z"
217 filter_type: "pattern"
218 pattern: "<your_own_value>"
219 id: "8"
220 name: "default_name_9"
221 """
222
223 RETURN = """
224 build:
225 description: Build number of the fortigate image
226 returned: always
227 type: str
228 sample: '1547'
229 http_method:
230 description: Last method used to provision the content into FortiGate
231 returned: always
232 type: str
233 sample: 'PUT'
234 http_status:
235 description: Last result given by FortiGate on last operation applied
236 returned: always
237 type: str
238 sample: "200"
239 mkey:
240 description: Master key (id) used in the last call to FortiGate
241 returned: success
242 type: str
243 sample: "id"
244 name:
245 description: Name of the table used to fulfill the request
246 returned: always
247 type: str
248 sample: "urlfilter"
249 path:
250 description: Path of the table used to fulfill the request
251 returned: always
252 type: str
253 sample: "webfilter"
254 revision:
255 description: Internal revision number
256 returned: always
257 type: str
258 sample: "17.0.2.10658"
259 serial:
260 description: Serial number of the unit
261 returned: always
262 type: str
263 sample: "FGVMEVYYQT3AB5352"
264 status:
265 description: Indication of the operation's result
266 returned: always
267 type: str
268 sample: "success"
269 vdom:
270 description: Virtual domain used
271 returned: always
272 type: str
273 sample: "root"
274 version:
275 description: Version of the FortiGate
276 returned: always
277 type: str
278 sample: "v5.6.3"
279 """
280 from ansible.module_utils.basic import AnsibleModule
281 from ansible.module_utils.connection import Connection
282 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
283 FortiOSHandler,
284 )
285 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
286 check_legacy_fortiosapi,
287 )
288 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
289 schema_to_module_spec,
290 )
291 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
292 check_schema_versioning,
293 )
294 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
295 FAIL_SOCKET_MSG,
296 )
297 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
298 remove_invalid_fields,
299 )
300 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
301 is_same_comparison,
302 )
303 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
304 serialize,
305 )
306 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
307 find_current_values,
308 )
309 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
310 unify_data_format,
311 )
312
313
314 def filter_dlp_filepattern_data(json):
315 option_list = ["comment", "entries", "id", "name"]
316
317 json = remove_invalid_fields(json)
318 dictionary = {}
319
320 for attribute in option_list:
321 if attribute in json and json[attribute] is not None:
322 dictionary[attribute] = json[attribute]
323
324 return dictionary
325
326
327 def underscore_to_hyphen(data):
328 new_data = None
329 if isinstance(data, list):
330 new_data = []
331 for i, elem in enumerate(data):
332 new_data.append(underscore_to_hyphen(elem))
333 elif isinstance(data, dict):
334 new_data = {}
335 for k, v in data.items():
336 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
337 else:
338 return data
339 return new_data
340
341
342 def dlp_filepattern(data, fos, check_mode=False):
343
344 state = None
345 vdom = data["vdom"]
346 parameters = None
347 state = data.get("state", None)
348 dlp_filepattern_data = data["dlp_filepattern"]
349
350 filtered_data = filter_dlp_filepattern_data(dlp_filepattern_data)
351 converted_data = underscore_to_hyphen(filtered_data)
352
353 # check_mode starts from here
354 if check_mode:
355 diff = {
356 "before": "",
357 "after": filtered_data,
358 }
359 mkeyname = fos.get_mkeyname(None, None)
360 mkey = fos.get_mkey("dlp", "filepattern", filtered_data, vdom=vdom)
361 current_data = fos.get(
362 "dlp", "filepattern", vdom=vdom, mkey=mkey, parameters=parameters
363 )
364 is_existed = (
365 current_data
366 and current_data.get("http_status") == 200
367 and (
368 mkeyname
369 and isinstance(current_data.get("results"), list)
370 and len(current_data["results"]) > 0
371 or not mkeyname
372 and current_data["results"] # global object response
373 )
374 )
375
376 # 2. if it exists and the state is 'present' then compare current settings with desired
377 if state == "present" or state is True or state is None:
378 # for non global modules, mkeyname must exist and it's a new module when mkey is None
379 if mkeyname is not None and mkey is None:
380 return False, True, filtered_data, diff
381
382 # if mkey exists then compare each other
383 # record exits and they're matched or not
384 copied_filtered_data = filtered_data.copy()
385 copied_filtered_data.pop(mkeyname, None)
386 unified_filtered_data = unify_data_format(copied_filtered_data)
387
388 current_data_results = current_data.get("results", {})
389 current_config = (
390 current_data_results[0]
391 if mkeyname
392 and isinstance(current_data_results, list)
393 and len(current_data_results) > 0
394 else current_data_results
395 )
396 if is_existed:
397 unified_current_values = find_current_values(
398 unified_filtered_data,
399 unify_data_format(current_config),
400 )
401
402 is_same = is_same_comparison(
403 serialize(unified_current_values), serialize(unified_filtered_data)
404 )
405
406 return (
407 False,
408 not is_same,
409 filtered_data,
410 {"before": unified_current_values, "after": unified_filtered_data},
411 )
412
413 # record does not exist
414 return False, True, filtered_data, diff
415
416 if state == "absent":
417 if mkey is None:
418 return (
419 False,
420 False,
421 filtered_data,
422 {"before": current_data["results"][0], "after": ""},
423 )
424
425 if is_existed:
426 return (
427 False,
428 True,
429 filtered_data,
430 {"before": current_data["results"][0], "after": ""},
431 )
432 return False, False, filtered_data, {}
433
434 return True, False, {"reason: ": "Must provide state parameter"}, {}
435 # pass post processed data to member operations
436 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
437 data_copy = data.copy()
438 data_copy["dlp_filepattern"] = filtered_data
439 fos.do_member_operation(
440 "dlp",
441 "filepattern",
442 data_copy,
443 )
444
445 if state == "present" or state is True:
446 return fos.set(
447 "dlp", "filepattern", data=converted_data, vdom=vdom, parameters=parameters
448 )
449
450 elif state == "absent":
451 return fos.delete(
452 "dlp",
453 "filepattern",
454 mkey=converted_data["id"],
455 vdom=vdom,
456 parameters=parameters,
457 )
458 else:
459 fos._module.fail_json(msg="state must be present or absent!")
460
461
462 def is_successful_status(resp):
463 return (
464 "status" in resp
465 and resp["status"] == "success"
466 or "http_status" in resp
467 and resp["http_status"] == 200
468 or "http_method" in resp
469 and resp["http_method"] == "DELETE"
470 and resp["http_status"] == 404
471 )
472
473
474 def fortios_dlp(data, fos, check_mode):
475
476 if data["dlp_filepattern"]:
477 resp = dlp_filepattern(data, fos, check_mode)
478 else:
479 fos._module.fail_json(msg="missing task body: %s" % ("dlp_filepattern"))
480 if isinstance(resp, tuple) and len(resp) == 4:
481 return resp
482 return (
483 not is_successful_status(resp),
484 is_successful_status(resp)
485 and (resp["revision_changed"] if "revision_changed" in resp else True),
486 resp,
487 {},
488 )
489
490
491 versioned_schema = {
492 "type": "list",
493 "elements": "dict",
494 "children": {
495 "id": {"v_range": [["v6.0.0", ""]], "type": "integer", "required": True},
496 "name": {"v_range": [["v6.0.0", ""]], "type": "string"},
497 "comment": {"v_range": [["v6.0.0", ""]], "type": "string"},
498 "entries": {
499 "type": "list",
500 "elements": "dict",
501 "children": {
502 "filter_type": {
503 "v_range": [["v6.0.0", ""]],
504 "type": "string",
505 "options": [{"value": "pattern"}, {"value": "type"}],
506 },
507 "pattern": {
508 "v_range": [["v6.0.0", ""]],
509 "type": "string",
510 "required": True,
511 },
512 "file_type": {
513 "v_range": [["v6.0.0", ""]],
514 "type": "string",
515 "options": [
516 {"value": "7z"},
517 {"value": "arj"},
518 {"value": "cab"},
519 {"value": "lzh"},
520 {"value": "rar"},
521 {"value": "tar"},
522 {"value": "zip"},
523 {"value": "bzip"},
524 {"value": "gzip"},
525 {"value": "bzip2"},
526 {"value": "xz"},
527 {"value": "bat"},
528 {"value": "uue"},
529 {"value": "mime"},
530 {"value": "base64"},
531 {"value": "binhex"},
532 {"value": "elf"},
533 {"value": "exe"},
534 {"value": "dll", "v_range": [["v7.6.3", ""]]},
535 {"value": "jnlp", "v_range": [["v7.6.3", ""]]},
536 {"value": "hta"},
537 {"value": "html"},
538 {"value": "jad"},
539 {"value": "class"},
540 {"value": "cod"},
541 {"value": "javascript"},
542 {"value": "msoffice"},
543 {"value": "msofficex"},
544 {"value": "fsg"},
545 {"value": "upx"},
546 {"value": "petite"},
547 {"value": "aspack"},
548 {"value": "sis"},
549 {"value": "hlp"},
550 {"value": "activemime"},
551 {"value": "jpeg"},
552 {"value": "gif"},
553 {"value": "tiff"},
554 {"value": "png"},
555 {"value": "bmp"},
556 {"value": "unknown"},
557 {"value": "mpeg"},
558 {"value": "mov"},
559 {"value": "mp3"},
560 {"value": "wma"},
561 {"value": "wav"},
562 {"value": "pdf"},
563 {"value": "avi"},
564 {"value": "rm"},
565 {"value": "torrent"},
566 {"value": "hibun"},
567 {"value": "msi"},
568 {"value": "mach-o"},
569 {"value": "dmg"},
570 {"value": ".net"},
571 {"value": "xar"},
572 {"value": "chm"},
573 {"value": "iso"},
574 {"value": "crx"},
575 {"value": "flac", "v_range": [["v6.2.0", ""]]},
576 {"value": "registry", "v_range": [["v7.4.4", ""]]},
577 {"value": "hwp", "v_range": [["v7.4.4", ""]]},
578 {"value": "rpm", "v_range": [["v7.4.4", ""]]},
579 {"value": "genscript", "v_range": [["v7.6.4", ""]]},
580 {"value": "python", "v_range": [["v7.6.4", ""]]},
581 {"value": "c/cpp", "v_range": [["v7.4.4", ""]]},
582 {"value": "pfile", "v_range": [["v7.6.0", ""]]},
583 {"value": "lzip", "v_range": [["v7.6.0", ""]]},
584 {"value": "wasm", "v_range": [["v7.6.0", ""]]},
585 {"value": "sylk", "v_range": [["v7.6.0", ""]]},
586 {"value": "shellscript", "v_range": [["v7.6.1", ""]]},
587 {"value": "msc", "v_range": [["v6.0.0", "v6.4.1"]]},
588 {"value": "ignored", "v_range": [["v6.0.0", "v6.0.11"]]},
589 ],
590 },
591 },
592 "v_range": [["v6.0.0", ""]],
593 },
594 },
595 "v_range": [["v6.0.0", ""]],
596 }
597
598
599 def main():
600 module_spec = schema_to_module_spec(versioned_schema)
601 mkeyname = "id"
602 fields = {
603 "access_token": {"required": False, "type": "str", "no_log": True},
604 "enable_log": {"required": False, "type": "bool", "default": False},
605 "vdom": {"required": False, "type": "str", "default": "root"},
606 "member_path": {"required": False, "type": "str"},
607 "member_state": {
608 "type": "str",
609 "required": False,
610 "choices": ["present", "absent"],
611 },
612 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
613 "dlp_filepattern": {
614 "required": False,
615 "type": "dict",
616 "default": None,
617 "options": {},
618 },
619 }
620 for attribute_name in module_spec["options"]:
621 fields["dlp_filepattern"]["options"][attribute_name] = module_spec["options"][
622 attribute_name
623 ]
624 if mkeyname and mkeyname == attribute_name:
625 fields["dlp_filepattern"]["options"][attribute_name]["required"] = True
626
627 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
628 check_legacy_fortiosapi(module)
629
630 is_error = False
631 has_changed = False
632 result = None
633 diff = None
634
635 versions_check_result = None
636 if module._socket_path:
637 connection = Connection(module._socket_path)
638 if "access_token" in module.params:
639 connection.set_custom_option("access_token", module.params["access_token"])
640
641 if "enable_log" in module.params:
642 connection.set_custom_option("enable_log", module.params["enable_log"])
643 else:
644 connection.set_custom_option("enable_log", False)
645 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
646 versions_check_result = check_schema_versioning(
647 fos, versioned_schema, "dlp_filepattern"
648 )
649
650 is_error, has_changed, result, diff = fortios_dlp(
651 module.params, fos, module.check_mode
652 )
653
654 else:
655 module.fail_json(**FAIL_SOCKET_MSG)
656
657 if versions_check_result and versions_check_result["matched"] is False:
658 module.warn(
659 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
660 )
661
662 if not is_error:
663 if versions_check_result and versions_check_result["matched"] is False:
664 module.exit_json(
665 changed=has_changed,
666 version_check_warning=versions_check_result,
667 meta=result,
668 diff=diff,
669 )
670 else:
671 module.exit_json(changed=has_changed, meta=result, diff=diff)
672 else:
673 if versions_check_result and versions_check_result["matched"] is False:
674 module.fail_json(
675 msg="Error in repo",
676 version_check_warning=versions_check_result,
677 meta=result,
678 )
679 else:
680 module.fail_json(msg="Error in repo", meta=result)
681
682
683 if __name__ == "__main__":
684 main()