Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # Copyright (c) Ansible Project
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: get_certificate
10 author: "John Westcott IV (@john-westcott-iv)"
11 short_description: Get a certificate from a host:port
12 description:
13 - Makes a secure connection and returns information about the presented certificate.
14 - The module uses the cryptography Python library.
15 extends_documentation_fragment:
16 - community.crypto._attributes
17 - community.crypto._attributes.idempotent_not_modify_state
18 - community.crypto._cryptography_dep.minimum
19 attributes:
20 check_mode:
21 support: none
22 details:
23 - This action does not modify state.
24 diff_mode:
25 support: N/A
26 details:
27 - This action does not modify state.
28 options:
29 host:
30 description:
31 - The host to get the cert for (IP is fine).
32 type: str
33 required: true
34 ca_cert:
35 description:
36 - A PEM file containing one or more root certificates; if present, the cert will be validated against these root certs.
37 - Note that this only validates the certificate is signed by the chain; not that the cert is valid for the host presenting
38 it.
39 type: path
40 port:
41 description:
42 - The port to connect to.
43 type: int
44 required: true
45 server_name:
46 description:
47 - Server name used for SNI (L(Server Name Indication,https://en.wikipedia.org/wiki/Server_Name_Indication)) when hostname
48 is an IP or is different from server name.
49 type: str
50 version_added: 1.4.0
51 proxy_host:
52 description:
53 - Proxy host used when get a certificate.
54 type: str
55 proxy_port:
56 description:
57 - Proxy port used when get a certificate.
58 type: int
59 default: 8080
60 starttls:
61 description:
62 - Requests a secure connection for protocols which require clients to initiate encryption.
63 - Only available for V(mysql) currently.
64 type: str
65 choices:
66 - mysql
67 version_added: 1.9.0
68 timeout:
69 description:
70 - The timeout in seconds.
71 type: int
72 default: 10
73 select_crypto_backend:
74 description:
75 - Determines which crypto backend to use.
76 - The default choice is V(auto), which tries to use C(cryptography) if available.
77 - If set to V(cryptography), will try to use the L(cryptography,https://cryptography.io/) library.
78 - Note that with community.crypto 3.0.0, all values behave the same.
79 This option will be deprecated in a later version.
80 We recommend to not set it explicitly.
81 type: str
82 default: auto
83 choices: [auto, cryptography]
84 ciphers:
85 description:
86 - SSL/TLS Ciphers to use for the request.
87 - When a list is provided, all ciphers are joined in order with V(:).
88 - See the L(OpenSSL Cipher List Format,https://www.openssl.org/docs/manmaster/man1/openssl-ciphers.html#CIPHER-LIST-FORMAT)
89 for more details.
90 - The available ciphers is dependent on the Python and OpenSSL/LibreSSL versions.
91 type: list
92 elements: str
93 version_added: 2.11.0
94 asn1_base64:
95 description:
96 - Whether to encode the ASN.1 values in the RV(extensions) return value with Base64 or not.
97 - The documentation claimed for a long time that the values are Base64 encoded, but they never were. For compatibility
98 this option is set to V(false).
99 - The default value was changed from V(false) to V(true) incommunity.crypto 3.0.0.
100 type: bool
101 default: true
102 version_added: 2.12.0
103 tls_ctx_options:
104 description:
105 - TLS context options (TLS/SSL OP flags) to use for the request.
106 - See the L(List of SSL OP Flags,https://wiki.openssl.org/index.php/List_of_SSL_OP_Flags) for more details.
107 - The available TLS context options is dependent on the Python and OpenSSL/LibreSSL versions.
108 type: list
109 elements: raw
110 version_added: 2.21.0
111 get_certificate_chain:
112 description:
113 - If set to V(true), will obtain the certificate chain next to the certificate itself.
114 - The chain as returned by the server can be found in RV(unverified_chain), and the chain that passed validation in
115 RV(verified_chain).
116 - B(Note) that this needs B(Python 3.10 or newer). Also note that only Python 3.13 or newer officially supports this.
117 The module uses internal APIs of Python 3.10, 3.11, and 3.12 to achieve the same. It can be that future versions of
118 Python 3.10, 3.11, or 3.12 break this.
119 type: bool
120 default: false
121 version_added: 2.21.0
122
123 notes:
124 - When using ca_cert on OS X it has been reported that in some conditions the validate will always succeed.
125 requirements:
126 - "Python >= 3.10 when O(get_certificate_chain=true)"
127
128 seealso:
129 - plugin: community.crypto.to_serial
130 plugin_type: filter
131 """
132
133 RETURN = r"""
134 cert:
135 description: The certificate retrieved from the port.
136 returned: success
137 type: str
138 expired:
139 description: Boolean indicating if the cert is expired.
140 returned: success
141 type: bool
142 extensions:
143 description: Extensions applied to the cert.
144 returned: success
145 type: list
146 elements: dict
147 contains:
148 critical:
149 returned: success
150 type: bool
151 description: Whether the extension is critical.
152 asn1_data:
153 returned: success
154 type: str
155 description:
156 - The ASN.1 content of the extension.
157 - If O(asn1_base64=true) this will be Base64 encoded, otherwise the raw binary value will be returned.
158 - Please note that the raw binary value might not survive JSON serialization to the Ansible controller, and also might
159 cause failures when displaying it. See U(https://github.com/ansible/ansible/issues/80258) for more information.
160 - B(Note) that depending on the C(cryptography) version used, it is not possible to extract the ASN.1 content of the
161 extension, but only to provide the re-encoded content of the extension in case it was parsed by C(cryptography).
162 This should usually result in exactly the same value, except if the original extension value was malformed.
163 name:
164 returned: success
165 type: str
166 description: The extension's name.
167 issuer:
168 description: Information about the issuer of the cert.
169 returned: success
170 type: dict
171 not_after:
172 description: Expiration date of the cert.
173 returned: success
174 type: str
175 not_before:
176 description: Issue date of the cert.
177 returned: success
178 type: str
179 serial_number:
180 description:
181 - The serial number of the cert.
182 - This return value is an B(integer). If you need the serial numbers as a colon-separated hex string, such as C(11:22:33),
183 you need to convert it to that form with P(community.crypto.to_serial#filter).
184 returned: success
185 type: int
186 signature_algorithm:
187 description: The algorithm used to sign the cert.
188 returned: success
189 type: str
190 subject:
191 description: Information about the subject of the cert (C(OU), C(CN), and so on).
192 returned: success
193 type: dict
194 version:
195 description: The version number of the certificate.
196 returned: success
197 type: str
198 verified_chain:
199 description:
200 - The verified certificate chain retrieved from the port.
201 - The first entry is always RV(cert).
202 - The last certificate the root certificate the chain is traced to. If O(ca_cert) is provided this certificate is part
203 of that store; otherwise it is part of the store used by default by Python.
204 - Note that RV(unverified_chain) generally does not contain the root certificate, and might contain other certificates
205 that are not part of the validated chain.
206 returned: success and O(get_certificate_chain=true)
207 type: list
208 elements: str
209 version_added: 2.21.0
210 unverified_chain:
211 description:
212 - The certificate chain retrieved from the port.
213 - The first entry is always RV(cert).
214 returned: success and O(get_certificate_chain=true)
215 type: list
216 elements: str
217 version_added: 2.21.0
218 """
219
220 EXAMPLES = r"""
221 ---
222 - name: Get the cert from an RDP port
223 community.crypto.get_certificate:
224 host: "1.2.3.4"
225 port: 3389
226 delegate_to: localhost
227 run_once: true
228 register: cert
229
230 - name: Get a cert from an https port
231 community.crypto.get_certificate:
232 host: "www.google.com"
233 port: 443
234 delegate_to: localhost
235 run_once: true
236 register: cert
237
238 - name: How many days until cert expires
239 ansible.builtin.debug:
240 msg: "cert expires in: {{ expire_days }} days."
241 vars:
242 expire_days: >-
243 {{ (
244 (cert.not_after | ansible.builtin.to_datetime('%Y%m%d%H%M%SZ')) -
245 (ansible_date_time.iso8601 | ansible.builtin.to_datetime('%Y-%m-%dT%H:%M:%SZ'))
246 ).days }}
247
248 - name: Allow legacy insecure renegotiation to get a cert from a legacy device
249 community.crypto.get_certificate:
250 host: "legacy-device.domain.com"
251 port: 443
252 ciphers:
253 - HIGH
254 tls_ctx_options:
255 - OP_ALL
256 - OP_NO_SSLv3
257 - OP_CIPHER_SERVER_PREFERENCE
258 - OP_ENABLE_MIDDLEBOX_COMPAT
259 - OP_NO_COMPRESSION
260 - 4 # OP_LEGACY_SERVER_CONNECT
261 delegate_to: localhost
262 run_once: true
263 register: legacy_cert
264 """
265
266 import atexit
267 import base64
268 import ssl
269 import sys
270 import typing as t
271 from os.path import isfile
272 from socket import create_connection, setdefaulttimeout, socket
273 from ssl import (
274 CERT_NONE,
275 CERT_REQUIRED,
276 DER_cert_to_PEM_cert,
277 create_default_context,
278 )
279
280 from ansible.module_utils.basic import AnsibleModule
281 from ansible.module_utils.common.text.converters import to_bytes, to_text
282
283 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
284 CRYPTOGRAPHY_TIMEZONE,
285 cryptography_get_extensions_from_cert,
286 cryptography_oid_to_name,
287 get_not_valid_after,
288 get_not_valid_before,
289 )
290 from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import (
291 COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION,
292 assert_required_cryptography_version,
293 )
294 from ansible_collections.community.crypto.plugins.module_utils._time import (
295 get_now_datetime,
296 )
297
298 MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION
299
300 try:
301 import cryptography
302 import cryptography.exceptions
303 import cryptography.x509
304 except ImportError:
305 pass
306
307
308 def send_starttls_packet(sock: socket, server_type: t.Literal["mysql"]) -> None:
309 if server_type == "mysql":
310 ssl_request_packet = (
311 b"\x20\x00\x00\x01\x85\xae\x7f\x00"
312 + b"\x00\x00\x00\x01\x21\x00\x00\x00"
313 + b"\x00\x00\x00\x00\x00\x00\x00\x00"
314 + b"\x00\x00\x00\x00\x00\x00\x00\x00"
315 + b"\x00\x00\x00\x00"
316 )
317
318 sock.recv(
319 8192
320 ) # discard initial handshake from server for this naive implementation
321 sock.send(ssl_request_packet)
322
323
324 def main() -> t.NoReturn:
325 module = AnsibleModule(
326 argument_spec={
327 "ca_cert": {"type": "path"},
328 "host": {"type": "str", "required": True},
329 "port": {"type": "int", "required": True},
330 "proxy_host": {"type": "str"},
331 "proxy_port": {"type": "int", "default": 8080},
332 "server_name": {"type": "str"},
333 "timeout": {"type": "int", "default": 10},
334 "select_crypto_backend": {
335 "type": "str",
336 "default": "auto",
337 "choices": ["auto", "cryptography"],
338 },
339 "starttls": {"type": "str", "choices": ["mysql"]},
340 "ciphers": {"type": "list", "elements": "str"},
341 "asn1_base64": {"type": "bool", "default": True},
342 "tls_ctx_options": {"type": "list", "elements": "raw"},
343 "get_certificate_chain": {"type": "bool", "default": False},
344 },
345 )
346
347 ca_cert: str | None = module.params.get("ca_cert")
348 host: str = module.params.get("host")
349 port: int = module.params.get("port")
350 proxy_host: str | None = module.params.get("proxy_host")
351 proxy_port: int | None = module.params.get("proxy_port")
352 timeout: int = module.params.get("timeout")
353 server_name: str | None = module.params.get("server_name")
354 start_tls_server_type: t.Literal["mysql"] | None = module.params.get("starttls")
355 ciphers: list[str] | None = module.params.get("ciphers")
356 asn1_base64: bool = module.params["asn1_base64"]
357 tls_ctx_options: list[str | bytes | int] | None = module.params["tls_ctx_options"]
358 get_certificate_chain: bool = module.params["get_certificate_chain"]
359
360 if get_certificate_chain and sys.version_info < (3, 10):
361 module.fail_json(
362 msg="get_certificate_chain=true can only be used with Python 3.10 (Python 3.13+ officially supports this). "
363 f"The Python version used to run the get_certificate module is {sys.version}"
364 )
365
366 assert_required_cryptography_version(
367 module, minimum_cryptography_version=MINIMAL_CRYPTOGRAPHY_VERSION
368 )
369
370 result: dict[str, t.Any] = {
371 "changed": False,
372 }
373
374 if timeout:
375 setdefaulttimeout(timeout)
376
377 if ca_cert and not isfile(ca_cert):
378 module.fail_json(msg="ca_cert file does not exist")
379
380 verified_chain = None
381 unverified_chain = None
382
383 try:
384 if proxy_host:
385 connect = f"CONNECT {host}:{port} HTTP/1.0\r\n\r\n"
386 sock = socket()
387 atexit.register(sock.close)
388 sock.connect((proxy_host, proxy_port))
389 sock.send(connect.encode())
390 sock.recv(8192)
391 else:
392 sock = create_connection((host, port))
393 atexit.register(sock.close)
394
395 if ca_cert:
396 ctx = create_default_context(cafile=ca_cert)
397 ctx.check_hostname = False
398 ctx.verify_mode = CERT_REQUIRED
399 else:
400 ctx = create_default_context()
401 ctx.check_hostname = False
402 ctx.verify_mode = CERT_NONE
403
404 if start_tls_server_type is not None:
405 send_starttls_packet(sock, start_tls_server_type)
406
407 if ciphers is not None:
408 ciphers_joined = ":".join(ciphers)
409 ctx.set_ciphers(ciphers_joined)
410
411 if tls_ctx_options is not None:
412 # Clear default ctx options
413 ctx.options = 0 # type: ignore
414
415 # For each item in the tls_ctx_options list
416 for tls_ctx_option in tls_ctx_options:
417 # If the item is a string_type
418 if isinstance(tls_ctx_option, (str, bytes)):
419 # Convert tls_ctx_option to a native string
420 tls_ctx_option_str = to_text(tls_ctx_option)
421 # Get the tls_ctx_option_str attribute from ssl
422 tls_ctx_option_attr = getattr(ssl, tls_ctx_option_str, None)
423 # If tls_ctx_option_attr is an integer
424 if isinstance(tls_ctx_option_attr, int):
425 # Set tls_ctx_option_int to the attribute value
426 tls_ctx_option_int = tls_ctx_option_attr
427 # If tls_ctx_option_attr is not an integer
428 else:
429 module.fail_json(
430 msg=f"Failed to determine the numeric value for {tls_ctx_option_str}"
431 )
432 # If the item is an integer
433 elif isinstance(tls_ctx_option, int):
434 # Set tls_ctx_option_int to the item value
435 tls_ctx_option_int = tls_ctx_option
436 # If the item is not a string nor integer
437 else:
438 module.fail_json(
439 msg=f"tls_ctx_options must be a string or integer, got {tls_ctx_option!r}"
440 )
441 tls_ctx_option_int = ( # type: ignore[unreachable]
442 0 # make pylint happy; this code is actually unreachable
443 )
444
445 try:
446 # Add the int value of the item to ctx options
447 # (pylint does not yet notice that module.fail_json cannot return)
448 ctx.options |= tls_ctx_option_int # pylint: disable=possibly-used-before-assignment
449 except Exception:
450 module.fail_json(
451 msg=f"Failed to add {tls_ctx_option_str or tls_ctx_option_int} to CTX options"
452 )
453
454 tls_sock = ctx.wrap_socket(sock, server_hostname=server_name or host)
455 cert_der = tls_sock.getpeercert(True)
456 if cert_der is None:
457 raise Exception("Unexpected error: no peer certificate has been returned")
458 cert: str = DER_cert_to_PEM_cert(cert_der)
459
460 if get_certificate_chain:
461 if sys.version_info < (3, 13):
462 # The official way to access this has been added in https://github.com/python/cpython/pull/109113/files.
463 # We are basically doing the same for older Python versions. The internal API needed for this was added
464 # in https://github.com/python/cpython/commit/666991fc598bc312d72aff0078ecb553f0a968f1, which was first
465 # released in Python 3.10.0.
466 def _convert_chain(chain):
467 if not chain:
468 return []
469 return [
470 c.public_bytes(
471 ssl._ssl.ENCODING_DER # pylint: disable=protected-access
472 )
473 for c in chain
474 ]
475
476 ssl_obj = (
477 tls_sock._sslobj # pylint: disable=protected-access
478 ) # This is of type ssl._ssl._SSLSocket
479 verified_der_chain = _convert_chain(ssl_obj.get_verified_chain())
480 unverified_der_chain = _convert_chain(ssl_obj.get_unverified_chain())
481 else:
482 # This works with Python 3.13+
483
484 # Unfortunately due to a bug (https://github.com/python/cpython/issues/118658) some early pre-releases of
485 # Python 3.13 do not return lists of byte strings, but lists of _ssl.Certificate objects. This is going to
486 # be fixed by https://github.com/python/cpython/pull/118669. For now we convert the certificates ourselves
487 # if they are not byte strings to work around this.
488 def _convert_chain(chain: list[bytes]) -> list[bytes]:
489 return [
490 (
491 c
492 if isinstance(c, bytes)
493 else c.public_bytes(
494 ssl._ssl.ENCODING_DER # pylint: disable=protected-access
495 )
496 )
497 for c in chain
498 ]
499
500 verified_der_chain = _convert_chain(tls_sock.get_verified_chain())
501 unverified_der_chain = _convert_chain(tls_sock.get_unverified_chain())
502
503 verified_chain = [DER_cert_to_PEM_cert(c) for c in verified_der_chain]
504 unverified_chain = [DER_cert_to_PEM_cert(c) for c in unverified_der_chain]
505
506 except Exception as e:
507 if proxy_host:
508 module.fail_json(
509 msg=f"Failed to get cert via proxy {proxy_host}:{proxy_port} from {host}:{port}, error: {e}"
510 )
511 else:
512 module.fail_json(msg=f"Failed to get cert from {host}:{port}, error: {e}")
513
514 result["cert"] = cert
515
516 x509 = cryptography.x509.load_pem_x509_certificate(to_bytes(cert))
517 result["subject"] = {}
518 for attribute in x509.subject:
519 result["subject"][cryptography_oid_to_name(attribute.oid, short=True)] = (
520 attribute.value
521 )
522
523 result["expired"] = get_not_valid_after(x509) < get_now_datetime(
524 with_timezone=CRYPTOGRAPHY_TIMEZONE
525 )
526
527 result["extensions"] = []
528 for dotted_number, entry in cryptography_get_extensions_from_cert(x509).items():
529 oid = cryptography.x509.oid.ObjectIdentifier(dotted_number)
530 ext: dict[str, t.Any] = {
531 "critical": entry["critical"],
532 "asn1_data": entry["value"],
533 "name": cryptography_oid_to_name(oid, short=True),
534 }
535 if not asn1_base64:
536 ext["asn1_data"] = base64.b64decode(entry["value"]) # type: ignore
537 result["extensions"].append(ext)
538
539 result["issuer"] = {}
540 for attribute in x509.issuer:
541 result["issuer"][cryptography_oid_to_name(attribute.oid, short=True)] = (
542 attribute.value
543 )
544
545 result["not_after"] = get_not_valid_after(x509).strftime("%Y%m%d%H%M%SZ")
546 result["not_before"] = get_not_valid_before(x509).strftime("%Y%m%d%H%M%SZ")
547
548 result["serial_number"] = x509.serial_number
549 result["signature_algorithm"] = cryptography_oid_to_name(
550 x509.signature_algorithm_oid
551 )
552
553 # We need the -1 offset to get the same values as pyOpenSSL
554 if x509.version == cryptography.x509.Version.v1:
555 result["version"] = 1 - 1
556 elif x509.version == cryptography.x509.Version.v3:
557 result["version"] = 3 - 1
558 else:
559 result["version"] = "unknown" # type: ignore[unreachable]
560
561 if verified_chain is not None:
562 result["verified_chain"] = verified_chain
563 if unverified_chain is not None:
564 result["unverified_chain"] = unverified_chain
565
566 module.exit_json(**result)
567
568
569 if __name__ == "__main__":
570 main()