Debian Codegraph @

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