Debian Codegraph @

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