Debian Codegraph @

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