Debian Codegraph @

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