Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, RSD Services S.A
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: java_cert
11
12 short_description: Uses keytool to import/remove certificate to/from java keystore (cacerts)
13 description:
14 - This is a wrapper module around keytool, which can be used to import certificates and optionally private keys to a given
15 java keystore, or remove them from it.
16 extends_documentation_fragment:
17 - community.general._attributes
18 - ansible.builtin.files
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: full
24 options:
25 cert_url:
26 description:
27 - Basic URL to fetch SSL certificate from.
28 - Exactly one of O(cert_url), O(cert_path), O(cert_content), or O(pkcs12_path) is required to load certificate.
29 type: str
30 cert_port:
31 description:
32 - Port to connect to URL.
33 - This is used to create server URL:PORT.
34 type: int
35 default: 443
36 cert_path:
37 description:
38 - Local path to load certificate from.
39 - Exactly one of O(cert_url), O(cert_path), O(cert_content), or O(pkcs12_path) is required to load certificate.
40 type: path
41 cert_content:
42 description:
43 - Content of the certificate used to create the keystore.
44 - Exactly one of O(cert_url), O(cert_path), O(cert_content), or O(pkcs12_path) is required to load certificate.
45 type: str
46 version_added: 8.6.0
47 cert_alias:
48 description:
49 - Imported certificate alias.
50 - The alias is used when checking for the presence of a certificate in the keystore.
51 type: str
52 trust_cacert:
53 description:
54 - Trust imported cert as CAcert.
55 type: bool
56 default: false
57 version_added: '0.2.0'
58 pkcs12_path:
59 description:
60 - Local path to load PKCS12 keystore from.
61 - Unlike O(cert_url), O(cert_path) and O(cert_content), the PKCS12 keystore embeds the private key matching the certificate,
62 and is used to import both the certificate and its private key into the java keystore.
63 - Exactly one of O(cert_url), O(cert_path), O(cert_content), or O(pkcs12_path) is required to load certificate.
64 type: path
65 pkcs12_password:
66 description:
67 - Password for importing from PKCS12 keystore.
68 type: str
69 pkcs12_alias:
70 description:
71 - Alias in the PKCS12 keystore.
72 type: str
73 keystore_path:
74 description:
75 - Path to keystore.
76 type: path
77 keystore_pass:
78 description:
79 - Keystore password.
80 type: str
81 required: true
82 keystore_create:
83 description:
84 - Create keystore if it does not exist.
85 type: bool
86 default: false
87 keystore_type:
88 description:
89 - Keystore type (JCEKS, JKS).
90 type: str
91 executable:
92 description:
93 - Path to keytool binary if not used we search in PATH for it.
94 type: str
95 default: keytool
96 state:
97 description:
98 - Defines action which can be either certificate import or removal.
99 - When O(state=present), the certificate is always inserted into the keystore, even if there already exists a cert alias
100 that is different.
101 type: str
102 choices: [absent, present]
103 default: present
104 mode:
105 version_added: 8.5.0
106 owner:
107 version_added: 8.5.0
108 group:
109 version_added: 8.5.0
110 seuser:
111 version_added: 8.5.0
112 serole:
113 version_added: 8.5.0
114 setype:
115 version_added: 8.5.0
116 selevel:
117 version_added: 8.5.0
118 unsafe_writes:
119 version_added: 8.5.0
120 attributes:
121 version_added: 8.5.0
122 requirements: [openssl, keytool]
123 author:
124 - Adam Hamsik (@haad)
125 """
126
127 EXAMPLES = r"""
128 - name: Import SSL certificate from google.com to a given cacerts keystore
129 community.general.java_cert:
130 cert_url: google.com
131 cert_port: 443
132 keystore_path: /usr/lib/jvm/jre7/lib/security/cacerts
133 keystore_pass: changeit
134 state: present
135
136 - name: Remove certificate with given alias from a keystore
137 community.general.java_cert:
138 cert_url: google.com
139 keystore_path: /usr/lib/jvm/jre7/lib/security/cacerts
140 keystore_pass: changeit
141 executable: /usr/lib/jvm/jre7/bin/keytool
142 state: absent
143
144 - name: Import trusted CA from SSL certificate
145 community.general.java_cert:
146 cert_path: /opt/certs/rootca.crt
147 keystore_path: /tmp/cacerts
148 keystore_pass: changeit
149 keystore_create: true
150 state: present
151 cert_alias: LE_RootCA
152 trust_cacert: true
153
154 - name: Import trusted CA from the SSL certificate stored in the cert_content variable
155 community.general.java_cert:
156 cert_content: |
157 -----BEGIN CERTIFICATE-----
158 ...
159 -----END CERTIFICATE-----
160 keystore_path: /tmp/cacerts
161 keystore_pass: changeit
162 keystore_create: true
163 state: present
164 cert_alias: LE_RootCA
165 trust_cacert: true
166
167 - name: Import SSL certificate from google.com to a keystore, create it if it doesn't exist
168 community.general.java_cert:
169 cert_url: google.com
170 keystore_path: /tmp/cacerts
171 keystore_pass: changeit
172 keystore_create: true
173 state: present
174
175 - name: Import a pkcs12 keystore with a specified alias, create it if it doesn't exist
176 community.general.java_cert:
177 pkcs12_path: "/tmp/importkeystore.p12"
178 cert_alias: default
179 keystore_path: /opt/wildfly/standalone/configuration/defaultkeystore.jks
180 keystore_pass: changeit
181 keystore_create: true
182 state: present
183
184 - name: Import SSL certificate to JCEKS keystore
185 community.general.java_cert:
186 pkcs12_path: "/tmp/importkeystore.p12"
187 pkcs12_alias: default
188 pkcs12_password: somepass
189 cert_alias: default
190 keystore_path: /opt/someapp/security/keystore.jceks
191 keystore_type: "JCEKS"
192 keystore_pass: changeit
193 keystore_create: true
194 state: present
195 """
196
197 RETURN = r"""
198 cmd:
199 description: Executed command to get action done.
200 returned: success
201 type: str
202 sample: "keytool -importcert -noprompt -keystore"
203 """
204
205 import os
206 import re
207 import tempfile
208 from urllib.parse import unquote, urlparse
209 from urllib.request import getproxies
210
211 # import module snippets
212 from ansible.module_utils.basic import AnsibleModule
213
214
215 def _get_keystore_type_keytool_parameters(keystore_type):
216 """Check that custom keystore is presented in parameters"""
217 if keystore_type:
218 return ["-storetype", keystore_type]
219 return []
220
221
222 def _check_cert_present(module, executable, keystore_path, keystore_pass, alias, keystore_type):
223 """Check if certificate with alias is present in keystore
224 located at keystore_path"""
225 test_cmd = [executable, "-list", "-keystore", keystore_path, "-alias", alias, "-rfc"]
226 test_cmd += _get_keystore_type_keytool_parameters(keystore_type)
227
228 (check_rc, stdout, dummy) = module.run_command(test_cmd, data=keystore_pass, check_rc=False)
229 if check_rc == 0:
230 return (True, stdout)
231 return (False, "")
232
233
234 def _get_certificate_from_url(module, executable, url, port, pem_certificate_output):
235 remote_cert_pem_chain = _download_cert_url(module, executable, url, port)
236 with open(pem_certificate_output, "w") as f:
237 f.write(remote_cert_pem_chain)
238
239
240 def _get_first_certificate_from_x509_file(module, pem_certificate_file, pem_certificate_output, openssl_bin):
241 """Read a X509 certificate chain file and output the first certificate in the list"""
242 extract_cmd = [openssl_bin, "x509", "-in", pem_certificate_file, "-out", pem_certificate_output]
243 (extract_rc, dummy, extract_stderr) = module.run_command(extract_cmd, check_rc=False)
244
245 if extract_rc != 0:
246 # trying der encoded file
247 extract_cmd += ["-inform", "der"]
248 (extract_rc, dummy, extract_stderr) = module.run_command(extract_cmd, check_rc=False)
249
250 if extract_rc != 0:
251 # this time it is a real failure
252 module.fail_json(
253 msg=f"Internal module failure, cannot extract certificate, error: {extract_stderr}",
254 rc=extract_rc,
255 cmd=extract_cmd,
256 )
257
258 return extract_rc
259
260
261 def _get_digest_from_x509_file(module, pem_certificate_file, openssl_bin):
262 """Read a X509 certificate file and output sha256 digest using openssl"""
263 # cleanup file before to compare
264 (dummy, tmp_certificate) = tempfile.mkstemp()
265 module.add_cleanup_file(tmp_certificate)
266 _get_first_certificate_from_x509_file(module, pem_certificate_file, tmp_certificate, openssl_bin)
267 dgst_cmd = [openssl_bin, "dgst", "-r", "-sha256", tmp_certificate]
268 (dgst_rc, dgst_stdout, dgst_stderr) = module.run_command(dgst_cmd, check_rc=False)
269
270 if dgst_rc != 0:
271 module.fail_json(
272 msg=f"Internal module failure, cannot compute digest for certificate, error: {dgst_stderr}",
273 rc=dgst_rc,
274 cmd=dgst_cmd,
275 )
276
277 return dgst_stdout.split(" ")[0]
278
279
280 def _export_public_cert_from_pkcs12(module, executable, pkcs_file, alias, password, dest):
281 """Runs keytools to extract the public cert from a PKCS12 archive and write it to a file."""
282 export_cmd = [executable, "-list", "-noprompt", "-keystore", pkcs_file, "-storetype", "pkcs12", "-rfc"]
283 # Append optional alias
284 if alias:
285 export_cmd.extend(["-alias", alias])
286 (export_rc, export_stdout, export_err) = module.run_command(export_cmd, data=password, check_rc=False)
287
288 if export_rc != 0:
289 module.fail_json(
290 msg=f"Internal module failure, cannot extract public certificate from PKCS12, message: {export_stdout}",
291 stderr=export_err,
292 rc=export_rc,
293 )
294
295 with open(dest, "w") as f:
296 f.write(export_stdout)
297
298
299 def get_proxy_settings(scheme="https"):
300 """Returns a tuple containing (proxy_host, proxy_port, proxy_user, proxy_pass).
301 (False, False, False, False) if no proxy is found."""
302 proxy_url = getproxies().get(scheme, "")
303 if not proxy_url:
304 return (False, False, False, False)
305 parsed_url = urlparse(proxy_url)
306 if parsed_url.scheme:
307 proxy_host = parsed_url.hostname
308 proxy_port = parsed_url.port
309 else:
310 (proxy_host, proxy_port) = parsed_url.path.split(":")
311 proxy_user = unquote(parsed_url.username) if parsed_url.username else False
312 proxy_pass = unquote(parsed_url.password) if parsed_url.password else False
313 return (proxy_host, proxy_port, proxy_user, proxy_pass)
314
315
316 def build_proxy_options():
317 """Returns list of valid proxy options for keytool"""
318 (proxy_host, proxy_port, proxy_user, proxy_pass) = get_proxy_settings()
319 no_proxy = os.getenv("no_proxy")
320
321 proxy_opts = []
322 if proxy_host:
323 proxy_opts.extend([f"-J-Dhttps.proxyHost={proxy_host}", f"-J-Dhttps.proxyPort={proxy_port}"])
324
325 if proxy_user and proxy_pass:
326 proxy_opts.extend(
327 [
328 f"-J-Dhttps.proxyUser={proxy_user}",
329 f"-J-Dhttps.proxyPassword={proxy_pass}",
330 # JDK 8u111+ disables Basic auth for HTTPS tunneling by default; clear that restriction.
331 "-J-Djdk.http.auth.tunneling.disabledSchemes=",
332 ]
333 )
334
335 if no_proxy is not None:
336 # For Java's nonProxyHosts property, items are separated by '|',
337 # and patterns have to start with "*".
338 non_proxy_hosts = no_proxy.replace(",", "|")
339 non_proxy_hosts = re.sub(r"(^|\|)\.", r"\1*.", non_proxy_hosts)
340
341 # The property name is http.nonProxyHosts, there is no
342 # separate setting for HTTPS.
343 proxy_opts.extend([f"-J-Dhttp.nonProxyHosts={non_proxy_hosts}"])
344 return proxy_opts
345
346
347 def _update_permissions(module, keystore_path):
348 """Updates keystore file attributes as necessary"""
349 file_args = module.load_file_common_arguments(module.params, path=keystore_path)
350 return module.set_fs_attributes_if_different(file_args, False)
351
352
353 def _download_cert_url(module, executable, url, port):
354 """Fetches the certificate from the remote URL using `keytool -printcert...`
355 The PEM formatted string is returned"""
356 proxy_opts = build_proxy_options()
357 fetch_cmd = [executable, "-printcert", "-rfc", "-sslserver"] + proxy_opts + [f"{url}:{port}"]
358
359 # Fetch SSL certificate from remote host.
360 (fetch_rc, fetch_out, fetch_err) = module.run_command(fetch_cmd, check_rc=False)
361
362 if fetch_rc != 0:
363 module.fail_json(
364 msg=f"Internal module failure, cannot download certificate, error: {fetch_err}", rc=fetch_rc, cmd=fetch_cmd
365 )
366
367 return fetch_out
368
369
370 def import_pkcs12_path(
371 module,
372 executable,
373 pkcs12_path,
374 pkcs12_pass,
375 pkcs12_alias,
376 keystore_path,
377 keystore_pass,
378 keystore_alias,
379 keystore_type,
380 ):
381 """Import pkcs12 from path into keystore located on
382 keystore_path as alias"""
383 optional_aliases = {"-destalias": keystore_alias, "-srcalias": pkcs12_alias}
384 import_cmd = [
385 executable,
386 "-importkeystore",
387 "-noprompt",
388 "-srcstoretype",
389 "pkcs12",
390 "-srckeystore",
391 pkcs12_path,
392 "-destkeystore",
393 keystore_path,
394 ]
395 # Append optional aliases
396 for flag, value in optional_aliases.items():
397 if value:
398 import_cmd.extend([flag, value])
399
400 import_cmd += _get_keystore_type_keytool_parameters(keystore_type)
401
402 secret_data = f"{keystore_pass}\n{pkcs12_pass}"
403 # Password of a new keystore must be entered twice, for confirmation
404 if not os.path.exists(keystore_path):
405 secret_data = f"{keystore_pass}\n{secret_data}"
406
407 # Use local certificate from local path and import it to a java keystore
408 (import_rc, import_out, import_err) = module.run_command(import_cmd, data=secret_data, check_rc=False)
409 diff = {"before": "\n", "after": f"{keystore_alias}\n"}
410
411 if import_rc != 0 or not os.path.exists(keystore_path):
412 module.fail_json(msg=import_out, rc=import_rc, cmd=import_cmd, error=import_err)
413
414 return dict(
415 changed=True, msg=import_out, rc=import_rc, cmd=import_cmd, stdout=import_out, error=import_err, diff=diff
416 )
417
418
419 def import_cert_path(module, executable, path, keystore_path, keystore_pass, alias, keystore_type, trust_cacert):
420 """Import certificate from path into keystore located on
421 keystore_path as alias"""
422 import_cmd = [executable, "-importcert", "-noprompt", "-keystore", keystore_path, "-file", path, "-alias", alias]
423 import_cmd += _get_keystore_type_keytool_parameters(keystore_type)
424
425 if trust_cacert:
426 import_cmd.extend(["-trustcacerts"])
427
428 # Use local certificate from local path and import it to a java keystore
429 (import_rc, import_out, import_err) = module.run_command(
430 import_cmd, data=f"{keystore_pass}\n{keystore_pass}", check_rc=False
431 )
432 diff = {"before": "\n", "after": f"{alias}\n"}
433
434 if import_rc != 0:
435 module.fail_json(msg=import_out, rc=import_rc, cmd=import_cmd, error=import_err)
436
437 return dict(
438 changed=True, msg=import_out, rc=import_rc, cmd=import_cmd, stdout=import_out, error=import_err, diff=diff
439 )
440
441
442 def delete_cert(module, executable, keystore_path, keystore_pass, alias, keystore_type):
443 """Delete certificate identified with alias from keystore on keystore_path"""
444 del_cmd = [executable, "-delete", "-noprompt", "-keystore", keystore_path, "-alias", alias]
445
446 del_cmd += _get_keystore_type_keytool_parameters(keystore_type)
447
448 # Delete SSL certificate from keystore
449 (del_rc, del_out, del_err) = module.run_command(del_cmd, data=keystore_pass, check_rc=True)
450 diff = {"before": f"{alias}\n", "after": None}
451
452 if del_rc != 0:
453 module.fail_json(msg=del_out, rc=del_rc, cmd=del_cmd, error=del_err)
454
455 return dict(changed=True, msg=del_out, rc=del_rc, cmd=del_cmd, stdout=del_out, error=del_err, diff=diff)
456
457
458 def test_keytool(module, executable):
459 """Test if keytool is actually executable or not"""
460 module.run_command([executable], check_rc=True)
461
462
463 def test_keystore(module, keystore_path):
464 """Check if we can access keystore as file or not"""
465 if keystore_path is None:
466 keystore_path = ""
467
468 if not os.path.exists(keystore_path) and not os.path.isfile(keystore_path):
469 # Keystore doesn't exist we want to create it
470 module.fail_json(changed=False, msg=f"Module require existing keystore at keystore_path '{keystore_path}'")
471
472
473 def main():
474 argument_spec = dict(
475 cert_url=dict(type="str"),
476 cert_path=dict(type="path"),
477 cert_content=dict(type="str"),
478 pkcs12_path=dict(type="path"),
479 pkcs12_password=dict(type="str", no_log=True),
480 pkcs12_alias=dict(type="str"),
481 cert_alias=dict(type="str"),
482 cert_port=dict(type="int", default=443),
483 keystore_path=dict(type="path"),
484 keystore_pass=dict(type="str", required=True, no_log=True),
485 trust_cacert=dict(type="bool", default=False),
486 keystore_create=dict(type="bool", default=False),
487 keystore_type=dict(type="str"),
488 executable=dict(type="str", default="keytool"),
489 state=dict(type="str", default="present", choices=["absent", "present"]),
490 )
491
492 module = AnsibleModule(
493 argument_spec=argument_spec,
494 required_if=[
495 ["state", "present", ("cert_path", "cert_url", "cert_content", "pkcs12_path"), True],
496 ["state", "absent", ("cert_url", "cert_alias"), True],
497 ],
498 required_together=[["keystore_path", "keystore_pass"]],
499 mutually_exclusive=[["cert_url", "cert_path", "cert_content", "pkcs12_path"]],
500 supports_check_mode=True,
501 add_file_common_args=True,
502 )
503 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
504
505 url = module.params.get("cert_url")
506 path = module.params.get("cert_path")
507 content = module.params.get("cert_content")
508 port = module.params.get("cert_port")
509
510 pkcs12_path = module.params.get("pkcs12_path")
511 pkcs12_pass = module.params.get("pkcs12_password", "")
512 pkcs12_alias = module.params.get("pkcs12_alias", "1")
513
514 cert_alias = module.params.get("cert_alias") or url
515 trust_cacert = module.params.get("trust_cacert")
516
517 keystore_path = module.params.get("keystore_path")
518 keystore_pass = module.params.get("keystore_pass")
519 keystore_create = module.params.get("keystore_create")
520 keystore_type = module.params.get("keystore_type")
521 executable = module.params.get("executable")
522 state = module.params.get("state")
523
524 # openssl dependency resolution
525 openssl_bin = module.get_bin_path("openssl", True)
526
527 if path and not cert_alias:
528 module.fail_json(changed=False, msg=f"Using local path import from {keystore_path} requires alias argument.")
529
530 test_keytool(module, executable)
531
532 if not keystore_create:
533 test_keystore(module, keystore_path)
534
535 alias_exists, alias_exists_output = _check_cert_present(
536 module, executable, keystore_path, keystore_pass, cert_alias, keystore_type
537 )
538
539 (dummy, new_certificate) = tempfile.mkstemp()
540 (dummy, old_certificate) = tempfile.mkstemp()
541 module.add_cleanup_file(new_certificate)
542 module.add_cleanup_file(old_certificate)
543
544 result = dict()
545
546 if state == "absent" and alias_exists:
547 if module.check_mode:
548 module.exit_json(changed=True)
549
550 # delete
551 result = delete_cert(module, executable, keystore_path, keystore_pass, cert_alias, keystore_type)
552
553 # dump certificate to enroll in the keystore on disk and compute digest
554 if state == "present":
555 # The alias exists in the keystore so we must now compare the SHA256 hash of the
556 # public certificate already in the keystore, and the certificate we are wanting to add
557 if alias_exists:
558 with open(old_certificate, "w") as f:
559 f.write(alias_exists_output)
560 keystore_cert_digest = _get_digest_from_x509_file(module, old_certificate, openssl_bin)
561
562 else:
563 keystore_cert_digest = ""
564
565 if pkcs12_path:
566 # Extracting certificate with openssl
567 _export_public_cert_from_pkcs12(module, executable, pkcs12_path, pkcs12_alias, pkcs12_pass, new_certificate)
568
569 elif path:
570 # Extracting the X509 digest is a bit easier. Keytool will print the PEM
571 # certificate to stdout so we don't need to do any transformations.
572 new_certificate = path
573
574 elif content:
575 with open(new_certificate, "w") as f:
576 f.write(content)
577
578 elif url:
579 # Getting the X509 digest from a URL is the same as from a path, we just have
580 # to download the cert first
581 _get_certificate_from_url(module, executable, url, port, new_certificate)
582
583 new_cert_digest = _get_digest_from_x509_file(module, new_certificate, openssl_bin)
584
585 if keystore_cert_digest != new_cert_digest:
586 if module.check_mode:
587 module.exit_json(changed=True)
588
589 if alias_exists:
590 # The certificate in the keystore does not match with the one we want to be present
591 # The existing certificate must first be deleted before we insert the correct one
592 delete_cert(module, executable, keystore_path, keystore_pass, cert_alias, keystore_type)
593
594 if pkcs12_path:
595 result = import_pkcs12_path(
596 module,
597 executable,
598 pkcs12_path,
599 pkcs12_pass,
600 pkcs12_alias,
601 keystore_path,
602 keystore_pass,
603 cert_alias,
604 keystore_type,
605 )
606 else:
607 result = import_cert_path(
608 module,
609 executable,
610 new_certificate,
611 keystore_path,
612 keystore_pass,
613 cert_alias,
614 keystore_type,
615 trust_cacert,
616 )
617
618 if os.path.exists(keystore_path):
619 changed_permissions = _update_permissions(module, keystore_path)
620 result["changed"] = result.get("changed", False) or changed_permissions
621
622 module.exit_json(**result)
623
624
625 if __name__ == "__main__":
626 main()