Debian Codegraph @

ansible_collections/community/crypto/plugins/modules/x509_certificate_convert.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2024, Felix Fontein <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: x509_certificate_convert
10 short_description: Convert X.509 certificates
11 version_added: 2.19.0
12 description:
13 - This module allows to convert X.509 certificates between different formats.
14 author:
15 - Felix Fontein (@felixfontein)
16 extends_documentation_fragment:
17 - ansible.builtin.files
18 - community.crypto._attributes
19 - community.crypto._attributes.files
20 attributes:
21 check_mode:
22 support: full
23 diff_mode:
24 support: none
25 safe_file_operations:
26 support: full
27 idempotent:
28 support: full
29 options:
30 src_path:
31 description:
32 - Name of the file containing the X.509 certificate to convert.
33 - Exactly one of O(src_path) or O(src_content) must be specified.
34 type: path
35 src_content:
36 description:
37 - The content of the file containing the X.509 certificate to convert.
38 - This must be text. If you are not sure that the input file is PEM, you must Base64 encode the value and set O(src_content_base64=true).
39 You can use the P(ansible.builtin.b64encode#filter) filter plugin for this.
40 - Exactly one of O(src_path) or O(src_content) must be specified.
41 type: str
42 src_content_base64:
43 description:
44 - If set to V(true) when O(src_content) is provided, the module assumes that the value of O(src_content) is Base64 encoded.
45 type: bool
46 default: false
47 format:
48 description:
49 - Determines which format the destination X.509 certificate should be written in.
50 - Please note that not every key can be exported in any format, and that not every format supports encryption.
51 type: str
52 choices:
53 - pem
54 - der
55 required: true
56 strict:
57 description:
58 - If the input is a PEM file, ensure that it contains a single PEM object, that the header and footer match, and are
59 of type C(CERTIFICATE) or C(X509 CERTIFICATE).
60 - See also the O(verify_cert_parsable) option, which checks whether the certificate is parsable.
61 type: bool
62 default: false
63 dest_path:
64 description:
65 - Name of the file in which the generated TLS/SSL X.509 certificate will be written.
66 type: path
67 required: true
68 backup:
69 description:
70 - Create a backup file including a timestamp so you can get the original X.509 certificate back if you overwrote it
71 with a new one by accident.
72 type: bool
73 default: false
74 verify_cert_parsable:
75 description:
76 - If set to V(true), ensures that the certificate can be parsed.
77 - To ensure that a PEM file does not contain multiple certificates, use the O(strict) option.
78 type: bool
79 default: false
80 version_added: 2.23.0
81 seealso:
82 - plugin: ansible.builtin.b64encode
83 plugin_type: filter
84 - module: community.crypto.x509_certificate
85 - module: community.crypto.x509_certificate_pipe
86 - module: community.crypto.x509_certificate_info
87 """
88
89 EXAMPLES = r"""
90 ---
91 - name: Convert PEM X.509 certificate to DER format
92 community.crypto.x509_certificate_convert:
93 src_path: /etc/ssl/cert/ansible.com.pem
94 dest_path: /etc/ssl/cert/ansible.com.der
95 format: der
96 """
97
98 RETURN = r"""
99 backup_file:
100 description: Name of backup file created.
101 returned: changed and if O(backup) is V(true)
102 type: str
103 sample: /path/to/cert.pem.2019-03-09@11:22~
104 """
105
106 import base64
107 import os
108 import typing as t
109
110 from ansible.module_utils.basic import AnsibleModule
111 from ansible.module_utils.common.text.converters import to_bytes, to_text
112
113 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
114 OpenSSLObjectError,
115 )
116 from ansible_collections.community.crypto.plugins.module_utils._crypto.pem import (
117 PEM_END,
118 PEM_END_START,
119 PEM_START,
120 extract_pem,
121 identify_pem_format,
122 split_pem_list,
123 )
124 from ansible_collections.community.crypto.plugins.module_utils._crypto.support import (
125 OpenSSLObject,
126 )
127 from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import (
128 COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION,
129 assert_required_cryptography_version,
130 )
131 from ansible_collections.community.crypto.plugins.module_utils._io import (
132 load_file_if_exists,
133 write_file,
134 )
135
136 MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION
137
138 try:
139 from cryptography.x509 import load_der_x509_certificate
140 except ImportError:
141 pass
142
143
144 def parse_certificate(
145 certificate_content: bytes, strict: bool = False
146 ) -> tuple[bytes, t.Literal["pem", "der"], str | None]:
147 input_format: t.Literal["pem", "der"] = (
148 "pem" if identify_pem_format(certificate_content) else "der"
149 )
150 if input_format == "pem":
151 pems = split_pem_list(to_text(certificate_content))
152 if len(pems) > 1 and strict:
153 raise ValueError(
154 f"The input contains {len(pems)} PEM objects, expecting only one since strict=true"
155 )
156 pem_header_type, content = extract_pem(pems[0], strict=strict)
157 if strict and pem_header_type not in ("CERTIFICATE", "X509 CERTIFICATE"):
158 raise ValueError(
159 f"type is {pem_header_type!r}, expecting CERTIFICATE or X509 CERTIFICATE"
160 )
161 certificate_content = base64.b64decode(content)
162 else:
163 pem_header_type = None
164 return certificate_content, input_format, pem_header_type
165
166
167 class X509CertificateConvertModule(OpenSSLObject):
168 def __init__(self, module: AnsibleModule) -> None:
169 super().__init__(
170 path=module.params["dest_path"],
171 state="present",
172 force=False,
173 check_mode=module.check_mode,
174 )
175
176 self.src_path: str | None = module.params["src_path"]
177 self.src_content: str | None = module.params["src_content"]
178 self.src_content_base64: bool = module.params["src_content_base64"]
179 if self.src_content is not None:
180 self.input = to_bytes(self.src_content)
181 if self.src_content_base64:
182 try:
183 self.input = base64.b64decode(self.input)
184 except Exception as exc:
185 module.fail_json(msg=f"Cannot Base64 decode src_content: {exc}")
186 else:
187 if self.src_path is None:
188 module.fail_json(msg="One of src_path and src_content must be provided")
189 try:
190 with open(self.src_path, "rb") as f:
191 self.input = f.read()
192 except Exception as exc:
193 module.fail_json(
194 msg=f"Failure while reading file {self.src_path}: {exc}"
195 )
196
197 self.format: t.Literal["pem", "der"] = module.params["format"]
198 self.strict: bool = module.params["strict"]
199 self.wanted_pem_type = "CERTIFICATE"
200
201 try:
202 self.input, self.input_format, dummy = parse_certificate(
203 self.input, strict=self.strict
204 )
205 except Exception as exc:
206 module.fail_json(msg=f"Error while parsing PEM: {exc}")
207
208 if module.params["verify_cert_parsable"]:
209 self.verify_cert_parsable(module)
210
211 self.backup: bool = module.params["backup"]
212 self.backup_file: str | None = None
213
214 module.params["path"] = self.path
215
216 self.dest_content = load_file_if_exists(path=self.path, module=module)
217 self.dest_content_format = None
218 self.dest_content_pem_type = None
219 if self.dest_content is not None:
220 try:
221 (
222 self.dest_content,
223 self.dest_content_format,
224 self.dest_content_pem_type,
225 ) = parse_certificate(self.dest_content, strict=True)
226 except Exception:
227 pass
228
229 def verify_cert_parsable(self, module: AnsibleModule) -> None:
230 assert_required_cryptography_version(
231 module, minimum_cryptography_version=MINIMAL_CRYPTOGRAPHY_VERSION
232 )
233 try:
234 load_der_x509_certificate(self.input)
235 except Exception as exc:
236 module.fail_json(msg=f"Error while parsing certificate: {exc}")
237
238 def needs_conversion(self) -> bool:
239 if self.dest_content is None or self.dest_content_format is None:
240 return True
241 if self.dest_content_format != self.format:
242 return True
243 if self.input != self.dest_content:
244 return True
245 return bool(
246 self.format == "pem" and self.dest_content_pem_type != self.wanted_pem_type
247 )
248
249 def get_dest_certificate(self) -> bytes:
250 if self.format == "der":
251 return self.input
252 data = to_bytes(base64.b64encode(self.input))
253 lines = [to_bytes(f"{PEM_START}{self.wanted_pem_type}{PEM_END}")]
254 lines += [data[i : i + 64] for i in range(0, len(data), 64)]
255 lines.append(to_bytes(f"{PEM_END_START}{self.wanted_pem_type}{PEM_END}\n"))
256 return b"\n".join(lines)
257
258 def generate(self, module: AnsibleModule) -> None:
259 """Do conversion."""
260 if self.needs_conversion():
261 # Convert
262 cert_data = self.get_dest_certificate()
263 if not self.check_mode:
264 if self.backup:
265 self.backup_file = module.backup_local(self.path)
266 write_file(module=module, content=cert_data)
267 self.changed = True
268
269 file_args = module.load_file_common_arguments(module.params)
270 if module.check_file_absent_if_check_mode(file_args["path"]):
271 self.changed = True
272 else:
273 self.changed = module.set_fs_attributes_if_different(
274 file_args, self.changed
275 )
276
277 def dump(self) -> dict[str, t.Any]:
278 """Serialize the object into a dictionary."""
279 result: dict[str, t.Any] = {
280 "changed": self.changed,
281 }
282 if self.backup_file:
283 result["backup_file"] = self.backup_file
284
285 return result
286
287
288 def main() -> t.NoReturn:
289 argument_spec = {
290 "src_path": {"type": "path"},
291 "src_content": {"type": "str"},
292 "src_content_base64": {"type": "bool", "default": False},
293 "format": {"type": "str", "required": True, "choices": ["pem", "der"]},
294 "strict": {"type": "bool", "default": False},
295 "dest_path": {"type": "path", "required": True},
296 "backup": {"type": "bool", "default": False},
297 "verify_cert_parsable": {"type": "bool", "default": False},
298 }
299 module = AnsibleModule(
300 argument_spec,
301 supports_check_mode=True,
302 add_file_common_args=True,
303 required_one_of=[("src_path", "src_content")],
304 mutually_exclusive=[("src_path", "src_content")],
305 )
306
307 base_dir = os.path.dirname(module.params["dest_path"]) or "."
308 if not os.path.isdir(base_dir):
309 module.fail_json(
310 name=base_dir,
311 msg=f"The directory {base_dir} does not exist or the file is not a directory",
312 )
313
314 try:
315 cert = X509CertificateConvertModule(module)
316 cert.generate(module)
317 result = cert.dump()
318 module.exit_json(**result)
319 except OpenSSLObjectError as exc:
320 module.fail_json(msg=str(exc))
321
322
323 if __name__ == "__main__":
324 main()