| 1 |
#!/usr/bin/python |
| 2 |
# Copyright (c) 2018, 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: certificate_complete_chain |
| 10 |
author: "Felix Fontein (@felixfontein)" |
| 11 |
short_description: Complete certificate chain given a set of untrusted and root certificates |
| 12 |
description: |
| 13 |
- This module completes a given chain of certificates in PEM format by finding intermediate certificates from a given set |
| 14 |
of certificates, until it finds a root certificate in another given set of certificates. |
| 15 |
- This can for example be used to find the root certificate for a certificate chain returned by M(community.crypto.acme_certificate). |
| 16 |
- Note that this module does I(not) check for validity of the chains. It only checks that issuer and subject match, and |
| 17 |
that the signature is correct. It ignores validity dates and key usage completely. If you need to verify that a generated |
| 18 |
chain is valid, please use C(openssl verify ...). |
| 19 |
extends_documentation_fragment: |
| 20 |
- community.crypto._attributes |
| 21 |
- community.crypto._attributes.idempotent_not_modify_state |
| 22 |
- community.crypto._cryptography_dep.minimum |
| 23 |
attributes: |
| 24 |
check_mode: |
| 25 |
support: full |
| 26 |
details: |
| 27 |
- This action does not modify state. |
| 28 |
diff_mode: |
| 29 |
support: N/A |
| 30 |
details: |
| 31 |
- This action does not modify state. |
| 32 |
options: |
| 33 |
input_chain: |
| 34 |
description: |
| 35 |
- A concatenated set of certificates in PEM format forming a chain. |
| 36 |
- The module will try to complete this chain. |
| 37 |
type: str |
| 38 |
required: true |
| 39 |
root_certificates: |
| 40 |
description: |
| 41 |
- A list of filenames or directories. |
| 42 |
- A filename is assumed to point to a file containing one or more certificates in PEM format. All certificates in this |
| 43 |
file will be added to the set of root certificates. |
| 44 |
- If a directory name is given, all files in the directory and its subdirectories will be scanned and tried to be parsed |
| 45 |
as concatenated certificates in PEM format. |
| 46 |
- Symbolic links will be followed. |
| 47 |
type: list |
| 48 |
elements: path |
| 49 |
required: true |
| 50 |
intermediate_certificates: |
| 51 |
description: |
| 52 |
- A list of filenames or directories. |
| 53 |
- A filename is assumed to point to a file containing one or more certificates in PEM format. All certificates in this |
| 54 |
file will be added to the set of root certificates. |
| 55 |
- If a directory name is given, all files in the directory and its subdirectories will be scanned and tried to be parsed |
| 56 |
as concatenated certificates in PEM format. |
| 57 |
- Symbolic links will be followed. |
| 58 |
type: list |
| 59 |
elements: path |
| 60 |
default: [] |
| 61 |
""" |
| 62 |
|
| 63 |
|
| 64 |
EXAMPLES = r""" |
| 65 |
--- |
| 66 |
# Given a leaf certificate for www.ansible.com and one or more intermediate |
| 67 |
# certificates, finds the associated root certificate. |
| 68 |
- name: Find root certificate |
| 69 |
community.crypto.certificate_complete_chain: |
| 70 |
input_chain: "{{ lookup('ansible.builtin.file', '/etc/ssl/csr/www.ansible.com-fullchain.pem') }}" |
| 71 |
root_certificates: |
| 72 |
- /etc/ca-certificates/ |
| 73 |
register: www_ansible_com |
| 74 |
- name: Write root certificate to disk |
| 75 |
ansible.builtin.copy: |
| 76 |
dest: /etc/ssl/csr/www.ansible.com-root.pem |
| 77 |
content: "{{ www_ansible_com.root }}" |
| 78 |
|
| 79 |
# Given a leaf certificate for www.ansible.com, and a list of intermediate |
| 80 |
# certificates, finds the associated root certificate. |
| 81 |
- name: Find root certificate |
| 82 |
community.crypto.certificate_complete_chain: |
| 83 |
input_chain: "{{ lookup('ansible.builtin.file', '/etc/ssl/csr/www.ansible.com.pem') }}" |
| 84 |
intermediate_certificates: |
| 85 |
- /etc/ssl/csr/www.ansible.com-chain.pem |
| 86 |
root_certificates: |
| 87 |
- /etc/ca-certificates/ |
| 88 |
register: www_ansible_com |
| 89 |
- name: Write complete chain to disk |
| 90 |
ansible.builtin.copy: |
| 91 |
dest: /etc/ssl/csr/www.ansible.com-completechain.pem |
| 92 |
content: "{{ ''.join(www_ansible_com.complete_chain) }}" |
| 93 |
- name: Write root chain (intermediates and root) to disk |
| 94 |
ansible.builtin.copy: |
| 95 |
dest: /etc/ssl/csr/www.ansible.com-rootchain.pem |
| 96 |
content: "{{ ''.join(www_ansible_com.chain) }}" |
| 97 |
""" |
| 98 |
|
| 99 |
|
| 100 |
RETURN = r""" |
| 101 |
root: |
| 102 |
description: |
| 103 |
- The root certificate in PEM format. |
| 104 |
returned: success |
| 105 |
type: str |
| 106 |
chain: |
| 107 |
description: |
| 108 |
- The chain added to the given input chain. Includes the root certificate. |
| 109 |
- Returned as a list of PEM certificates. |
| 110 |
returned: success |
| 111 |
type: list |
| 112 |
elements: str |
| 113 |
complete_chain: |
| 114 |
description: |
| 115 |
- The completed chain, including leaf, all intermediates, and root. |
| 116 |
- Returned as a list of PEM certificates. |
| 117 |
returned: success |
| 118 |
type: list |
| 119 |
elements: str |
| 120 |
""" |
| 121 |
|
| 122 |
import os |
| 123 |
import typing as t |
| 124 |
|
| 125 |
from ansible.module_utils.basic import AnsibleModule |
| 126 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 127 |
|
| 128 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.pem import ( |
| 129 |
split_pem_list, |
| 130 |
) |
| 131 |
from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import ( |
| 132 |
COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION, |
| 133 |
assert_required_cryptography_version, |
| 134 |
) |
| 135 |
|
| 136 |
try: |
| 137 |
import cryptography |
| 138 |
import cryptography.exceptions |
| 139 |
import cryptography.hazmat.primitives.asymmetric.ec |
| 140 |
import cryptography.hazmat.primitives.asymmetric.padding |
| 141 |
import cryptography.hazmat.primitives.asymmetric.rsa |
| 142 |
import cryptography.hazmat.primitives.asymmetric.utils |
| 143 |
import cryptography.hazmat.primitives.hashes |
| 144 |
import cryptography.hazmat.primitives.serialization |
| 145 |
import cryptography.x509 |
| 146 |
import cryptography.x509.oid |
| 147 |
except ImportError: |
| 148 |
pass |
| 149 |
|
| 150 |
|
| 151 |
class Certificate: |
| 152 |
""" |
| 153 |
Stores PEM with parsed certificate. |
| 154 |
""" |
| 155 |
|
| 156 |
def __init__(self, pem: str, cert: cryptography.x509.Certificate) -> None: |
| 157 |
if not (pem.endswith("\n") or pem.endswith("\r")): |
| 158 |
pem = pem + "\n" |
| 159 |
self.pem = pem |
| 160 |
self.cert = cert |
| 161 |
|
| 162 |
|
| 163 |
def is_parent( |
| 164 |
module: AnsibleModule, |
| 165 |
cert: Certificate, |
| 166 |
potential_parent: Certificate, |
| 167 |
) -> bool: |
| 168 |
""" |
| 169 |
Tests whether the given certificate has been issued by the potential parent certificate. |
| 170 |
""" |
| 171 |
# Check issuer |
| 172 |
if cert.cert.issuer != potential_parent.cert.subject: |
| 173 |
return False |
| 174 |
# Check signature |
| 175 |
public_key = potential_parent.cert.public_key() |
| 176 |
try: |
| 177 |
if isinstance( |
| 178 |
public_key, cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey |
| 179 |
): |
| 180 |
if cert.cert.signature_hash_algorithm is None: |
| 181 |
raise AssertionError( # pragma: no cover |
| 182 |
"signature_hash_algorithm should be present for RSA certificates" |
| 183 |
) |
| 184 |
public_key.verify( |
| 185 |
cert.cert.signature, |
| 186 |
cert.cert.tbs_certificate_bytes, |
| 187 |
cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15(), |
| 188 |
cert.cert.signature_hash_algorithm, |
| 189 |
) |
| 190 |
elif isinstance( |
| 191 |
public_key, |
| 192 |
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey, |
| 193 |
): |
| 194 |
if cert.cert.signature_hash_algorithm is None: |
| 195 |
raise AssertionError( # pragma: no cover |
| 196 |
"signature_hash_algorithm should be present for EC certificates" |
| 197 |
) |
| 198 |
public_key.verify( |
| 199 |
cert.cert.signature, |
| 200 |
cert.cert.tbs_certificate_bytes, |
| 201 |
cryptography.hazmat.primitives.asymmetric.ec.ECDSA( |
| 202 |
cert.cert.signature_hash_algorithm |
| 203 |
), |
| 204 |
) |
| 205 |
elif isinstance( |
| 206 |
public_key, |
| 207 |
( |
| 208 |
cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey, |
| 209 |
cryptography.hazmat.primitives.asymmetric.ed448.Ed448PublicKey, |
| 210 |
), |
| 211 |
): |
| 212 |
public_key.verify(cert.cert.signature, cert.cert.tbs_certificate_bytes) |
| 213 |
else: |
| 214 |
# Unknown public key type |
| 215 |
module.warn(f'Unknown public key type "{public_key}"') |
| 216 |
return False |
| 217 |
return True |
| 218 |
except cryptography.exceptions.InvalidSignature: |
| 219 |
return False |
| 220 |
except cryptography.exceptions.UnsupportedAlgorithm: |
| 221 |
module.warn(f'Unsupported algorithm "{cert.cert.signature_hash_algorithm}"') |
| 222 |
return False |
| 223 |
except Exception as e: |
| 224 |
module.fail_json(msg=f"Unknown error on signature validation: {e}") |
| 225 |
|
| 226 |
|
| 227 |
def parse_pem_list( |
| 228 |
module: AnsibleModule, |
| 229 |
text: str, |
| 230 |
source: bytes | str | os.PathLike, |
| 231 |
fail_on_error: bool = True, |
| 232 |
) -> list[Certificate]: |
| 233 |
""" |
| 234 |
Parse concatenated PEM certificates. Return list of ``Certificate`` objects. |
| 235 |
""" |
| 236 |
result: list[Certificate] = [] |
| 237 |
for cert_pem in split_pem_list(text): |
| 238 |
# Try to load PEM certificate |
| 239 |
try: |
| 240 |
cert = cryptography.x509.load_pem_x509_certificate(to_bytes(cert_pem)) |
| 241 |
result.append(Certificate(cert_pem, cert)) |
| 242 |
except Exception as e: |
| 243 |
msg = f"Cannot parse certificate #{len(result) + 1} from {to_text(source)!r}: {e}" |
| 244 |
if fail_on_error: |
| 245 |
module.fail_json(msg=msg) |
| 246 |
else: |
| 247 |
module.warn(msg) |
| 248 |
return result |
| 249 |
|
| 250 |
|
| 251 |
def load_pem_list( |
| 252 |
module: AnsibleModule, path: bytes | str | os.PathLike, fail_on_error: bool = True |
| 253 |
) -> list[Certificate]: |
| 254 |
""" |
| 255 |
Load concatenated PEM certificates from file. Return list of ``Certificate`` objects. |
| 256 |
""" |
| 257 |
try: |
| 258 |
with open(path, "rb") as f: |
| 259 |
return parse_pem_list( |
| 260 |
module, |
| 261 |
f.read().decode("utf-8"), |
| 262 |
source=path, |
| 263 |
fail_on_error=fail_on_error, |
| 264 |
) |
| 265 |
except Exception as e: |
| 266 |
msg = f"Cannot read certificate file {to_text(path)!r}: {e}" |
| 267 |
if fail_on_error: |
| 268 |
module.fail_json(msg=msg) |
| 269 |
else: |
| 270 |
module.warn(msg) |
| 271 |
return [] |
| 272 |
|
| 273 |
|
| 274 |
class CertificateSet: |
| 275 |
""" |
| 276 |
Stores a set of certificates. Allows to search for parent (issuer of a certificate). |
| 277 |
""" |
| 278 |
|
| 279 |
def __init__(self, module: AnsibleModule) -> None: |
| 280 |
self.module = module |
| 281 |
self.certificates: set[Certificate] = set() |
| 282 |
self.certificates_by_issuer: dict[cryptography.x509.Name, list[Certificate]] = ( |
| 283 |
{} |
| 284 |
) |
| 285 |
self.certificate_by_cert: dict[cryptography.x509.Certificate, Certificate] = {} |
| 286 |
|
| 287 |
def _load_file(self, path: bytes | str | os.PathLike) -> None: |
| 288 |
certs = load_pem_list(self.module, path, fail_on_error=False) |
| 289 |
for cert in certs: |
| 290 |
self.certificates.add(cert) |
| 291 |
if cert.cert.subject not in self.certificates_by_issuer: |
| 292 |
self.certificates_by_issuer[cert.cert.subject] = [] |
| 293 |
self.certificates_by_issuer[cert.cert.subject].append(cert) |
| 294 |
self.certificate_by_cert[cert.cert] = cert |
| 295 |
|
| 296 |
def load(self, path: str | os.PathLike) -> None: |
| 297 |
""" |
| 298 |
Load lists of PEM certificates from a file or a directory. |
| 299 |
""" |
| 300 |
b_path = to_bytes(path, errors="surrogate_or_strict") |
| 301 |
if os.path.isdir(b_path): |
| 302 |
for directory, dummy, files in os.walk(b_path, followlinks=True): |
| 303 |
for file in files: |
| 304 |
self._load_file(os.path.join(directory, file)) |
| 305 |
else: |
| 306 |
self._load_file(b_path) |
| 307 |
|
| 308 |
def find_parent(self, cert: Certificate) -> Certificate | None: |
| 309 |
""" |
| 310 |
Search for the parent (issuer) of a certificate. Return ``None`` if none was found. |
| 311 |
""" |
| 312 |
potential_parents = self.certificates_by_issuer.get(cert.cert.issuer, []) |
| 313 |
for potential_parent in potential_parents: |
| 314 |
if is_parent(self.module, cert, potential_parent): |
| 315 |
return potential_parent |
| 316 |
return None |
| 317 |
|
| 318 |
|
| 319 |
def format_cert(cert: Certificate) -> str: |
| 320 |
""" |
| 321 |
Return human readable representation of certificate for error messages. |
| 322 |
""" |
| 323 |
return str(cert.cert) |
| 324 |
|
| 325 |
|
| 326 |
def check_cycle( |
| 327 |
module: AnsibleModule, |
| 328 |
occured_certificates: set[cryptography.x509.Certificate], |
| 329 |
next_certificate: Certificate, |
| 330 |
) -> None: |
| 331 |
""" |
| 332 |
Make sure that next_certificate is not in occured_certificates so far, and add it. |
| 333 |
""" |
| 334 |
next_cert = next_certificate.cert |
| 335 |
if next_cert in occured_certificates: |
| 336 |
module.fail_json(msg="Found cycle while building certificate chain") |
| 337 |
occured_certificates.add(next_cert) |
| 338 |
|
| 339 |
|
| 340 |
def main() -> t.NoReturn: |
| 341 |
module = AnsibleModule( |
| 342 |
argument_spec={ |
| 343 |
"input_chain": {"type": "str", "required": True}, |
| 344 |
"root_certificates": {"type": "list", "required": True, "elements": "path"}, |
| 345 |
"intermediate_certificates": { |
| 346 |
"type": "list", |
| 347 |
"default": [], |
| 348 |
"elements": "path", |
| 349 |
}, |
| 350 |
}, |
| 351 |
supports_check_mode=True, |
| 352 |
) |
| 353 |
|
| 354 |
assert_required_cryptography_version( |
| 355 |
module, minimum_cryptography_version=COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION |
| 356 |
) |
| 357 |
|
| 358 |
# Load chain |
| 359 |
chain = parse_pem_list(module, module.params["input_chain"], source="input chain") |
| 360 |
if len(chain) == 0: |
| 361 |
module.fail_json(msg="Input chain must contain at least one certificate") |
| 362 |
|
| 363 |
# Check chain |
| 364 |
for i, parent in enumerate(chain): |
| 365 |
if i > 0 and not is_parent(module, chain[i - 1], parent): |
| 366 |
module.fail_json( |
| 367 |
msg=( |
| 368 |
f"Cannot verify input chain: certificate #{i + 1}: {format_cert(parent)} is not issuer of certificate #{i}: {format_cert(chain[i - 1])}" |
| 369 |
) |
| 370 |
) |
| 371 |
|
| 372 |
# Load intermediate certificates |
| 373 |
intermediates = CertificateSet(module) |
| 374 |
for path in module.params["intermediate_certificates"]: |
| 375 |
intermediates.load(path) |
| 376 |
|
| 377 |
# Load root certificates |
| 378 |
roots = CertificateSet(module) |
| 379 |
for path in module.params["root_certificates"]: |
| 380 |
roots.load(path) |
| 381 |
|
| 382 |
# Try to complete chain |
| 383 |
current: Certificate | None = chain[-1] |
| 384 |
completed = [] |
| 385 |
occured_certificates = {cert.cert for cert in chain} |
| 386 |
if current and current.cert in roots.certificate_by_cert: |
| 387 |
# Do not try to complete the chain when it is already ending with a root certificate |
| 388 |
current = None |
| 389 |
while current: |
| 390 |
root = roots.find_parent(current) |
| 391 |
if root: |
| 392 |
check_cycle(module, occured_certificates, root) |
| 393 |
completed.append(root) |
| 394 |
break |
| 395 |
intermediate = intermediates.find_parent(current) |
| 396 |
if intermediate: |
| 397 |
check_cycle(module, occured_certificates, intermediate) |
| 398 |
completed.append(intermediate) |
| 399 |
current = intermediate |
| 400 |
else: |
| 401 |
module.fail_json( |
| 402 |
msg=f"Cannot complete chain. Stuck at certificate {format_cert(current)}" |
| 403 |
) |
| 404 |
|
| 405 |
# Return results |
| 406 |
complete_chain = chain + completed |
| 407 |
module.exit_json( |
| 408 |
changed=False, |
| 409 |
root=complete_chain[-1].pem, |
| 410 |
chain=[cert.pem for cert in completed], |
| 411 |
complete_chain=[cert.pem for cert in complete_chain], |
| 412 |
) |
| 413 |
|
| 414 |
|
| 415 |
if __name__ == "__main__": |
| 416 |
main() |