Debian Codegraph @

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