Debian Codegraph @

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