Debian Codegraph @

ansible_collections/community/general/plugins/modules/java_keystore.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2021, quidame <[email protected]>
4 # Copyright (c) 2016, Guillaume Grossetie <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: java_keystore
12 short_description: Create a Java keystore in JKS format
13 description:
14 - Bundle a x509 certificate and its private key into a Java Keystore in JKS format.
15 attributes:
16 check_mode:
17 support: full
18 diff_mode:
19 support: none
20 options:
21 name:
22 description:
23 - Name of the certificate in the keystore.
24 - If the provided name does not exist in the keystore, the module re-creates the keystore. This behavior changed in
25 community.general 3.0.0, before that the module would fail when the name did not match.
26 type: str
27 required: true
28 certificate:
29 description:
30 - Content of the certificate used to create the keystore.
31 - If the fingerprint of the provided certificate does not match the fingerprint of the certificate bundled in the keystore,
32 the keystore is regenerated with the provided certificate.
33 - Exactly one of O(certificate) or O(certificate_path) is required.
34 type: str
35 certificate_path:
36 description:
37 - Location of the certificate used to create the keystore.
38 - If the fingerprint of the provided certificate does not match the fingerprint of the certificate bundled in the keystore,
39 the keystore is regenerated with the provided certificate.
40 - Exactly one of O(certificate) or O(certificate_path) is required.
41 type: path
42 version_added: '3.0.0'
43 private_key:
44 description:
45 - Content of the private key used to create the keystore.
46 - Exactly one of O(private_key) or O(private_key_path) is required.
47 type: str
48 private_key_path:
49 description:
50 - Location of the private key used to create the keystore.
51 - Exactly one of O(private_key) or O(private_key_path) is required.
52 type: path
53 version_added: '3.0.0'
54 private_key_passphrase:
55 description:
56 - Passphrase used to read the private key, if required.
57 type: str
58 version_added: '0.2.0'
59 password:
60 description:
61 - Password that should be used to secure the keystore.
62 - If the provided password fails to unlock the keystore, the module re-creates the keystore with the new passphrase.
63 This behavior changed in community.general 3.0.0, before that the module would fail when the password did not match.
64 type: str
65 required: true
66 dest:
67 description:
68 - Absolute path of the generated keystore.
69 type: path
70 required: true
71 force:
72 description:
73 - Keystore is created even if it already exists.
74 type: bool
75 default: false
76 owner:
77 description:
78 - Name of the user that should own jks file.
79 group:
80 description:
81 - Name of the group that should own jks file.
82 mode:
83 description:
84 - Mode the file should be.
85 ssl_backend:
86 description:
87 - Backend for loading private keys and certificates.
88 type: str
89 default: openssl
90 choices:
91 - openssl
92 - cryptography
93 version_added: 3.1.0
94 keystore_type:
95 description:
96 - Type of the Java keystore.
97 - When this option is omitted and the keystore does not already exist, the behavior follows C(keytool)'s default store
98 type which depends on Java version; V(pkcs12) since Java 9 and V(jks) prior (may also be V(pkcs12) if new default
99 has been backported to this version).
100 - When this option is omitted and the keystore already exists, the current type is left untouched, unless another option
101 leads to overwrite the keystore (in that case, this option behaves like for keystore creation).
102 - When O(keystore_type) is set, the keystore is created with this type if it does not already exist, or is overwritten
103 to match the given type in case of mismatch.
104 type: str
105 choices:
106 - jks
107 - pkcs12
108 version_added: 3.3.0
109 requirements:
110 - openssl in PATH (when O(ssl_backend=openssl))
111 - keytool in PATH
112 - cryptography >= 3.0 (when O(ssl_backend=cryptography))
113 author:
114 - Guillaume Grossetie (@Mogztter)
115 - quidame (@quidame)
116 extends_documentation_fragment:
117 - ansible.builtin.files
118 - community.general._attributes
119 seealso:
120 - module: community.crypto.openssl_pkcs12
121 - module: community.general.java_cert
122 notes:
123 - O(certificate) and O(private_key) require that their contents are available on the controller (either inline in a playbook,
124 or with the P(ansible.builtin.file#lookup) lookup), while O(certificate_path) and O(private_key_path) require that the
125 files are available on the target host.
126 - By design, any change of a value of options O(keystore_type), O(name) or O(password), as well as changes of key or certificate
127 materials causes the existing O(dest) to be overwritten.
128 """
129
130 EXAMPLES = r"""
131 - name: Create a keystore for the given certificate/private key pair (inline)
132 community.general.java_keystore:
133 name: example
134 certificate: |
135 -----BEGIN CERTIFICATE-----
136 h19dUZ2co2f...
137 -----END CERTIFICATE-----
138 private_key: |
139 -----BEGIN RSA PRIVATE KEY-----
140 DBVFTEVDVFJ...
141 -----END RSA PRIVATE KEY-----
142 password: changeit
143 dest: /etc/security/keystore.jks
144
145 - name: Create a keystore for the given certificate/private key pair (with files on controller)
146 community.general.java_keystore:
147 name: example
148 certificate: "{{ lookup('file', '/path/to/certificate.crt') }}"
149 private_key: "{{ lookup('file', '/path/to/private.key') }}"
150 password: changeit
151 dest: /etc/security/keystore.jks
152
153 - name: Create a keystore for the given certificate/private key pair (with files on target host)
154 community.general.java_keystore:
155 name: snakeoil
156 certificate_path: /etc/ssl/certs/ssl-cert-snakeoil.pem
157 private_key_path: /etc/ssl/private/ssl-cert-snakeoil.key
158 password: changeit
159 dest: /etc/security/keystore.jks
160 """
161
162 RETURN = r"""
163 err:
164 description: Output from stderr of keytool/openssl command after error of given command.
165 returned: failure
166 type: str
167 sample: "Keystore password is too short - must be at least 6 characters\n"
168
169 cmd:
170 description: Executed command to get action done.
171 returned: changed and failure
172 type: str
173 sample: "/usr/bin/openssl x509 -noout -in /tmp/user/1000/tmp8jd_lh23 -fingerprint -sha256"
174 """
175
176
177 import os
178 import re
179 import tempfile
180
181 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
182 from ansible.module_utils.common.text.converters import to_bytes
183
184 try:
185 from cryptography.exceptions import UnsupportedAlgorithm
186 from cryptography.hazmat.backends.openssl import backend
187 from cryptography.hazmat.primitives import hashes
188 from cryptography.hazmat.primitives.serialization import (
189 BestAvailableEncryption,
190 NoEncryption,
191 load_der_private_key,
192 load_pem_private_key,
193 )
194 from cryptography.hazmat.primitives.serialization.pkcs12 import serialize_key_and_certificates
195 from cryptography.x509 import (
196 load_der_x509_certificate,
197 load_pem_x509_certificate,
198 )
199
200 HAS_CRYPTOGRAPHY_PKCS12 = True
201 except ImportError:
202 HAS_CRYPTOGRAPHY_PKCS12 = False
203
204
205 class JavaKeystore:
206 def __init__(self, module):
207 self.module = module
208 self.result = dict()
209
210 self.keytool_bin = module.get_bin_path("keytool", True)
211
212 self.certificate = module.params["certificate"]
213 self.keypass = module.params["private_key_passphrase"]
214 self.keystore_path = module.params["dest"]
215 self.name = module.params["name"]
216 self.password = module.params["password"]
217 self.private_key = module.params["private_key"]
218 self.ssl_backend = module.params["ssl_backend"]
219 self.keystore_type = module.params["keystore_type"]
220
221 if self.ssl_backend == "openssl":
222 self.openssl_bin = module.get_bin_path("openssl", True)
223 else:
224 if not HAS_CRYPTOGRAPHY_PKCS12:
225 self.module.fail_json(msg=missing_required_lib("cryptography >= 3.0"))
226
227 if module.params["certificate_path"] is None:
228 self.certificate_path = create_file(self.certificate)
229 self.module.add_cleanup_file(self.certificate_path)
230 else:
231 self.certificate_path = module.params["certificate_path"]
232
233 if module.params["private_key_path"] is None:
234 self.private_key_path = create_file(self.private_key)
235 self.module.add_cleanup_file(self.private_key_path)
236 else:
237 self.private_key_path = module.params["private_key_path"]
238
239 def update_permissions(self):
240 file_args = self.module.load_file_common_arguments(self.module.params, path=self.keystore_path)
241 return self.module.set_fs_attributes_if_different(file_args, False)
242
243 def read_certificate_fingerprint(self, cert_format="PEM"):
244 if self.ssl_backend == "cryptography":
245 if cert_format == "PEM":
246 cert_loader = load_pem_x509_certificate
247 else:
248 cert_loader = load_der_x509_certificate
249
250 try:
251 with open(self.certificate_path, "rb") as cert_file:
252 cert = cert_loader(cert_file.read(), backend=backend)
253 except (OSError, ValueError) as e:
254 self.module.fail_json(msg=f"Unable to read the provided certificate: {e}")
255
256 fp = cert.fingerprint(hashes.SHA256()).hex().upper()
257 fingerprint = ":".join([fp[i : i + 2] for i in range(0, len(fp), 2)])
258 else:
259 current_certificate_fingerprint_cmd = [
260 self.openssl_bin,
261 "x509",
262 "-noout",
263 "-in",
264 self.certificate_path,
265 "-fingerprint",
266 "-sha256",
267 ]
268 (rc, current_certificate_fingerprint_out, current_certificate_fingerprint_err) = self.module.run_command(
269 current_certificate_fingerprint_cmd, environ_update=None, check_rc=False
270 )
271 if rc != 0:
272 return self.module.fail_json(
273 msg=current_certificate_fingerprint_out,
274 err=current_certificate_fingerprint_err,
275 cmd=current_certificate_fingerprint_cmd,
276 rc=rc,
277 )
278
279 current_certificate_match = re.search(r"=([\w:]+)", current_certificate_fingerprint_out)
280 if not current_certificate_match:
281 return self.module.fail_json(
282 msg=f"Unable to find the current certificate fingerprint in {current_certificate_fingerprint_out}",
283 cmd=current_certificate_fingerprint_cmd,
284 rc=rc,
285 )
286
287 fingerprint = current_certificate_match.group(1)
288 return fingerprint
289
290 def read_stored_certificate_fingerprint(self):
291 stored_certificate_fingerprint_cmd = [
292 self.keytool_bin,
293 "-list",
294 "-alias",
295 self.name,
296 "-keystore",
297 self.keystore_path,
298 "-v",
299 ]
300 (rc, stored_certificate_fingerprint_out, stored_certificate_fingerprint_err) = self.module.run_command(
301 stored_certificate_fingerprint_cmd, data=self.password, check_rc=False
302 )
303 if rc != 0:
304 if (
305 f"keytool error: java.lang.Exception: Alias <{self.name}> does not exist"
306 in stored_certificate_fingerprint_out
307 ):
308 return "alias mismatch"
309 if re.match(
310 r"keytool error: java\.io\.IOException: [Kk]eystore( was tampered with, or)? password was incorrect",
311 stored_certificate_fingerprint_out,
312 ):
313 return "password mismatch"
314 return self.module.fail_json(
315 msg=stored_certificate_fingerprint_out,
316 err=stored_certificate_fingerprint_err,
317 cmd=stored_certificate_fingerprint_cmd,
318 rc=rc,
319 )
320
321 if self.keystore_type not in (None, self.current_type()):
322 return "keystore type mismatch"
323
324 stored_certificate_match = re.search(r"SHA256: ([\w:]+)", stored_certificate_fingerprint_out)
325 if not stored_certificate_match:
326 return self.module.fail_json(
327 msg=f"Unable to find the stored certificate fingerprint in {stored_certificate_fingerprint_out}",
328 cmd=stored_certificate_fingerprint_cmd,
329 rc=rc,
330 )
331
332 return stored_certificate_match.group(1)
333
334 def current_type(self):
335 magic_bytes = b"\xfe\xed\xfe\xed"
336 with open(self.keystore_path, "rb") as fd:
337 header = fd.read(4)
338 if header == magic_bytes:
339 return "jks"
340 return "pkcs12"
341
342 def cert_changed(self):
343 current_certificate_fingerprint = self.read_certificate_fingerprint()
344 stored_certificate_fingerprint = self.read_stored_certificate_fingerprint()
345 return current_certificate_fingerprint != stored_certificate_fingerprint
346
347 def cryptography_create_pkcs12_bundle(self, keystore_p12_path, key_format="PEM", cert_format="PEM"):
348 if key_format == "PEM":
349 key_loader = load_pem_private_key
350 else:
351 key_loader = load_der_private_key
352
353 if cert_format == "PEM":
354 cert_loader = load_pem_x509_certificate
355 else:
356 cert_loader = load_der_x509_certificate
357
358 try:
359 with open(self.private_key_path, "rb") as key_file:
360 private_key = key_loader(key_file.read(), password=to_bytes(self.keypass), backend=backend)
361 except TypeError:
362 # Re-attempt with no password to match existing behavior
363 try:
364 with open(self.private_key_path, "rb") as key_file:
365 private_key = key_loader(key_file.read(), password=None, backend=backend)
366 except (OSError, TypeError, ValueError, UnsupportedAlgorithm) as e:
367 self.module.fail_json(msg=f"The following error occurred while loading the provided private_key: {e}")
368 except (OSError, ValueError, UnsupportedAlgorithm) as e:
369 self.module.fail_json(msg=f"The following error occurred while loading the provided private_key: {e}")
370 try:
371 with open(self.certificate_path, "rb") as cert_file:
372 cert = cert_loader(cert_file.read(), backend=backend)
373 except (OSError, ValueError, UnsupportedAlgorithm) as e:
374 self.module.fail_json(msg=f"The following error occurred while loading the provided certificate: {e}")
375
376 if self.password:
377 encryption = BestAvailableEncryption(to_bytes(self.password))
378 else:
379 encryption = NoEncryption()
380
381 pkcs12_bundle = serialize_key_and_certificates(
382 name=to_bytes(self.name), key=private_key, cert=cert, cas=None, encryption_algorithm=encryption
383 )
384
385 with open(keystore_p12_path, "wb") as p12_file:
386 p12_file.write(pkcs12_bundle)
387
388 self.result.update(msg="PKCS#12 bundle created by cryptography backend")
389
390 def openssl_create_pkcs12_bundle(self, keystore_p12_path):
391 export_p12_cmd = [
392 self.openssl_bin,
393 "pkcs12",
394 "-export",
395 "-name",
396 self.name,
397 "-in",
398 self.certificate_path,
399 "-inkey",
400 self.private_key_path,
401 "-out",
402 keystore_p12_path,
403 "-passout",
404 "stdin",
405 ]
406
407 # when keypass is provided, add -passin
408 cmd_stdin = ""
409 if self.keypass:
410 export_p12_cmd.append("-passin")
411 export_p12_cmd.append("stdin")
412 cmd_stdin = f"{self.keypass}\n"
413 cmd_stdin += f"{self.password}\n{self.password}"
414
415 (rc, export_p12_out, export_p12_err) = self.module.run_command(
416 export_p12_cmd, data=cmd_stdin, environ_update=None, check_rc=False
417 )
418
419 self.result = dict(msg=export_p12_out, cmd=export_p12_cmd, rc=rc)
420 if rc != 0:
421 self.result["err"] = export_p12_err
422 self.module.fail_json(**self.result)
423
424 def create(self):
425 """Create the keystore, or replace it with a rollback in case of
426 keytool failure.
427 """
428 if self.module.check_mode:
429 self.result["changed"] = True
430 return self.result
431
432 keystore_p12_path = create_path()
433 self.module.add_cleanup_file(keystore_p12_path)
434
435 if self.ssl_backend == "cryptography":
436 self.cryptography_create_pkcs12_bundle(keystore_p12_path)
437 else:
438 self.openssl_create_pkcs12_bundle(keystore_p12_path)
439
440 if self.keystore_type == "pkcs12":
441 # Preserve properties of the destination file, if any.
442 self.module.atomic_move(os.path.abspath(keystore_p12_path), os.path.abspath(self.keystore_path))
443 self.update_permissions()
444 self.result["changed"] = True
445 return self.result
446
447 import_keystore_cmd = [
448 self.keytool_bin,
449 "-importkeystore",
450 "-destkeystore",
451 self.keystore_path,
452 "-srckeystore",
453 keystore_p12_path,
454 "-srcstoretype",
455 "pkcs12",
456 "-alias",
457 self.name,
458 "-noprompt",
459 ]
460
461 if self.keystore_type == "jks":
462 keytool_help = self.module.run_command([self.keytool_bin, "-importkeystore", "-help"])
463 if "-deststoretype" in keytool_help[1] + keytool_help[2]:
464 import_keystore_cmd.insert(4, "-deststoretype")
465 import_keystore_cmd.insert(5, self.keystore_type)
466
467 keystore_backup = None
468 if self.exists():
469 keystore_backup = f"{self.keystore_path}.tmpbak"
470 # Preserve properties of the source file
471 self.module.preserved_copy(self.keystore_path, keystore_backup)
472 os.remove(self.keystore_path)
473
474 (rc, import_keystore_out, import_keystore_err) = self.module.run_command(
475 import_keystore_cmd, data=f"{self.password}\n{self.password}\n{self.password}", check_rc=False
476 )
477
478 self.result = dict(msg=import_keystore_out, cmd=import_keystore_cmd, rc=rc)
479
480 # keytool may return 0 whereas the keystore has not been created.
481 if rc != 0 or not self.exists():
482 if keystore_backup is not None:
483 self.module.preserved_copy(keystore_backup, self.keystore_path)
484 os.remove(keystore_backup)
485 self.result["err"] = import_keystore_err
486 return self.module.fail_json(**self.result)
487
488 self.update_permissions()
489 if keystore_backup is not None:
490 os.remove(keystore_backup)
491 self.result["changed"] = True
492 return self.result
493
494 def exists(self):
495 return os.path.exists(self.keystore_path)
496
497
498 # Utility functions
499 def create_path():
500 dummy, tmpfile = tempfile.mkstemp()
501 os.remove(tmpfile)
502 return tmpfile
503
504
505 def create_file(content):
506 tmpfd, tmpfile = tempfile.mkstemp()
507 with os.fdopen(tmpfd, "w") as f:
508 f.write(content)
509 return tmpfile
510
511
512 def create_module() -> AnsibleModule:
513 choose_between = (["certificate", "certificate_path"], ["private_key", "private_key_path"])
514
515 module = AnsibleModule(
516 argument_spec=dict(
517 name=dict(type="str", required=True),
518 dest=dict(type="path", required=True),
519 certificate=dict(type="str", no_log=True),
520 certificate_path=dict(type="path"),
521 private_key=dict(type="str", no_log=True),
522 private_key_path=dict(type="path", no_log=False),
523 private_key_passphrase=dict(type="str", no_log=True),
524 password=dict(type="str", required=True, no_log=True),
525 ssl_backend=dict(type="str", default="openssl", choices=["openssl", "cryptography"]),
526 keystore_type=dict(type="str", choices=["jks", "pkcs12"]),
527 force=dict(type="bool", default=False),
528 ),
529 required_one_of=choose_between,
530 mutually_exclusive=choose_between,
531 supports_check_mode=True,
532 add_file_common_args=True,
533 )
534 module.run_command_environ_update = dict(LANGUAGE="C", LC_ALL="C")
535 return module
536
537
538 def main():
539 module = create_module()
540
541 result = dict()
542 jks = JavaKeystore(module)
543
544 if jks.exists():
545 if module.params["force"] or jks.cert_changed():
546 result = jks.create()
547 else:
548 result["changed"] = jks.update_permissions()
549 else:
550 result = jks.create()
551
552 module.exit_json(**result)
553
554
555 if __name__ == "__main__":
556 main()