Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_certificate_crl.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_certificate_crl
23 short_description: Certificate Revocation List as a PEM file 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 certificate feature and crl 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 certificate_crl:
88 description:
89 - Certificate Revocation List as a PEM file.
90 default: null
91 type: dict
92 suboptions:
93 crl:
94 description:
95 - Certificate Revocation List as a PEM file.
96 type: str
97 http_url:
98 description:
99 - HTTP server URL for CRL auto-update.
100 type: str
101 last_updated:
102 description:
103 - Time at which CRL was last updated.
104 type: int
105 ldap_password:
106 description:
107 - LDAP server user password.
108 type: str
109 ldap_server:
110 description:
111 - LDAP server name for CRL auto-update.
112 type: str
113 ldap_username:
114 description:
115 - LDAP server user name.
116 type: str
117 name:
118 description:
119 - Name.
120 required: true
121 type: str
122 range:
123 description:
124 - Either global or VDOM IP address range for the certificate.
125 type: str
126 choices:
127 - 'global'
128 - 'vdom'
129 scep_cert:
130 description:
131 - Local certificate for SCEP communication for CRL auto-update. Source certificate.local.name.
132 type: str
133 scep_url:
134 description:
135 - SCEP server URL for CRL auto-update.
136 type: str
137 source:
138 description:
139 - Certificate source type.
140 type: str
141 choices:
142 - 'factory'
143 - 'user'
144 - 'bundle'
145 source_ip:
146 description:
147 - Source IP address for communications to a HTTP or SCEP CA server.
148 type: str
149 update_interval:
150 description:
151 - Time in seconds before the FortiGate checks for an updated CRL. Set to 0 to update only when it expires.
152 type: int
153 update_vdom:
154 description:
155 - VDOM for CRL update. Source system.vdom.name.
156 type: str
157 """
158
159 EXAMPLES = """
160 - name: Certificate Revocation List as a PEM file.
161 fortinet.fortios.fortios_certificate_crl:
162 vdom: "{{ vdom }}"
163 state: "present"
164 access_token: "<your_own_value>"
165 certificate_crl:
166 crl: "<your_own_value>"
167 http_url: "<your_own_value>"
168 last_updated: "2147483647"
169 ldap_password: "<your_own_value>"
170 ldap_server: "<your_own_value>"
171 ldap_username: "<your_own_value>"
172 name: "default_name_9"
173 range: "global"
174 scep_cert: "<your_own_value> (source certificate.local.name)"
175 scep_url: "<your_own_value>"
176 source: "factory"
177 source_ip: "84.230.14.43"
178 update_interval: "0"
179 update_vdom: "<your_own_value> (source system.vdom.name)"
180 """
181
182 RETURN = """
183 build:
184 description: Build number of the fortigate image
185 returned: always
186 type: str
187 sample: '1547'
188 http_method:
189 description: Last method used to provision the content into FortiGate
190 returned: always
191 type: str
192 sample: 'PUT'
193 http_status:
194 description: Last result given by FortiGate on last operation applied
195 returned: always
196 type: str
197 sample: "200"
198 mkey:
199 description: Master key (id) used in the last call to FortiGate
200 returned: success
201 type: str
202 sample: "id"
203 name:
204 description: Name of the table used to fulfill the request
205 returned: always
206 type: str
207 sample: "urlfilter"
208 path:
209 description: Path of the table used to fulfill the request
210 returned: always
211 type: str
212 sample: "webfilter"
213 revision:
214 description: Internal revision number
215 returned: always
216 type: str
217 sample: "17.0.2.10658"
218 serial:
219 description: Serial number of the unit
220 returned: always
221 type: str
222 sample: "FGVMEVYYQT3AB5352"
223 status:
224 description: Indication of the operation's result
225 returned: always
226 type: str
227 sample: "success"
228 vdom:
229 description: Virtual domain used
230 returned: always
231 type: str
232 sample: "root"
233 version:
234 description: Version of the FortiGate
235 returned: always
236 type: str
237 sample: "v5.6.3"
238 """
239 from ansible.module_utils.basic import AnsibleModule
240 from ansible.module_utils.connection import Connection
241 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
242 FortiOSHandler,
243 )
244 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
245 check_legacy_fortiosapi,
246 )
247 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
248 schema_to_module_spec,
249 )
250 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
251 check_schema_versioning,
252 )
253 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
254 FAIL_SOCKET_MSG,
255 )
256 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
257 remove_invalid_fields,
258 )
259 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
260 is_same_comparison,
261 )
262 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
263 serialize,
264 )
265 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
266 find_current_values,
267 )
268 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
269 unify_data_format,
270 )
271
272
273 def filter_certificate_crl_data(json):
274 option_list = [
275 "crl",
276 "http_url",
277 "last_updated",
278 "ldap_password",
279 "ldap_server",
280 "ldap_username",
281 "name",
282 "range",
283 "scep_cert",
284 "scep_url",
285 "source",
286 "source_ip",
287 "update_interval",
288 "update_vdom",
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 certificate_crl(data, fos, check_mode=False):
317
318 state = None
319 vdom = data["vdom"]
320 parameters = None
321 state = data.get("state", None)
322 certificate_crl_data = data["certificate_crl"]
323
324 filtered_data = filter_certificate_crl_data(certificate_crl_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("certificate", "crl", filtered_data, vdom=vdom)
335 current_data = fos.get(
336 "certificate", "crl", 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["certificate_crl"] = filtered_data
413 fos.do_member_operation(
414 "certificate",
415 "crl",
416 data_copy,
417 )
418
419 if state == "present" or state is True:
420 return fos.set(
421 "certificate", "crl", data=converted_data, vdom=vdom, parameters=parameters
422 )
423
424 elif state == "absent":
425 return fos.delete(
426 "certificate",
427 "crl",
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_certificate(data, fos, check_mode):
449
450 if data["certificate_crl"]:
451 resp = certificate_crl(data, fos, check_mode)
452 else:
453 fos._module.fail_json(msg="missing task body: %s" % ("certificate_crl"))
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": {"v_range": [["v6.0.0", ""]], "type": "string", "required": True},
470 "crl": {"v_range": [["v6.0.0", ""]], "type": "string"},
471 "range": {
472 "v_range": [["v6.0.0", ""]],
473 "type": "string",
474 "options": [{"value": "global"}, {"value": "vdom"}],
475 },
476 "source": {
477 "v_range": [["v6.0.0", ""]],
478 "type": "string",
479 "options": [{"value": "factory"}, {"value": "user"}, {"value": "bundle"}],
480 },
481 "update_vdom": {"v_range": [["v6.0.0", ""]], "type": "string"},
482 "ldap_server": {"v_range": [["v6.0.0", ""]], "type": "string"},
483 "ldap_username": {"v_range": [["v6.0.0", ""]], "type": "string"},
484 "ldap_password": {"v_range": [["v6.0.0", ""]], "type": "string"},
485 "http_url": {"v_range": [["v6.0.0", ""]], "type": "string"},
486 "scep_url": {"v_range": [["v6.0.0", ""]], "type": "string"},
487 "scep_cert": {"v_range": [["v6.0.0", ""]], "type": "string"},
488 "update_interval": {"v_range": [["v6.0.0", ""]], "type": "integer"},
489 "source_ip": {"v_range": [["v6.0.0", ""]], "type": "string"},
490 "last_updated": {
491 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
492 "type": "integer",
493 },
494 },
495 "v_range": [["v6.0.0", ""]],
496 }
497
498
499 def main():
500 module_spec = schema_to_module_spec(versioned_schema)
501 mkeyname = "name"
502 fields = {
503 "access_token": {"required": False, "type": "str", "no_log": True},
504 "enable_log": {"required": False, "type": "bool", "default": False},
505 "vdom": {"required": False, "type": "str", "default": "root"},
506 "member_path": {"required": False, "type": "str"},
507 "member_state": {
508 "type": "str",
509 "required": False,
510 "choices": ["present", "absent"],
511 },
512 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
513 "certificate_crl": {
514 "required": False,
515 "type": "dict",
516 "default": None,
517 "options": {},
518 },
519 }
520 for attribute_name in module_spec["options"]:
521 fields["certificate_crl"]["options"][attribute_name] = module_spec["options"][
522 attribute_name
523 ]
524 if mkeyname and mkeyname == attribute_name:
525 fields["certificate_crl"]["options"][attribute_name]["required"] = True
526
527 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
528 check_legacy_fortiosapi(module)
529
530 is_error = False
531 has_changed = False
532 result = None
533 diff = None
534
535 versions_check_result = None
536 if module._socket_path:
537 connection = Connection(module._socket_path)
538 if "access_token" in module.params:
539 connection.set_custom_option("access_token", module.params["access_token"])
540
541 if "enable_log" in module.params:
542 connection.set_custom_option("enable_log", module.params["enable_log"])
543 else:
544 connection.set_custom_option("enable_log", False)
545 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
546 versions_check_result = check_schema_versioning(
547 fos, versioned_schema, "certificate_crl"
548 )
549
550 is_error, has_changed, result, diff = fortios_certificate(
551 module.params, fos, module.check_mode
552 )
553
554 else:
555 module.fail_json(**FAIL_SOCKET_MSG)
556
557 if versions_check_result and versions_check_result["matched"] is False:
558 module.warn(
559 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
560 )
561
562 if not is_error:
563 if versions_check_result and versions_check_result["matched"] is False:
564 module.exit_json(
565 changed=has_changed,
566 version_check_warning=versions_check_result,
567 meta=result,
568 diff=diff,
569 )
570 else:
571 module.exit_json(changed=has_changed, meta=result, diff=diff)
572 else:
573 if versions_check_result and versions_check_result["matched"] is False:
574 module.fail_json(
575 msg="Error in repo",
576 version_check_warning=versions_check_result,
577 meta=result,
578 )
579 else:
580 module.fail_json(msg="Error in repo", meta=result)
581
582
583 if __name__ == "__main__":
584 main()