| 1 |
# Copyright (c) 2016-2017, Yanis Guenane <[email protected]> |
| 2 |
# Copyright (c) 2017, Markus Teufelberger <[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 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 7 |
# Do not use this from other collections or standalone plugins/modules! |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import abc |
| 12 |
import typing as t |
| 13 |
|
| 14 |
from ansible_collections.community.crypto.plugins.module_utils._argspec import ( |
| 15 |
ArgumentSpec, |
| 16 |
) |
| 17 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import ( |
| 18 |
OpenSSLBadPassphraseError, |
| 19 |
OpenSSLObjectError, |
| 20 |
) |
| 21 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import ( |
| 22 |
cryptography_compare_public_keys, |
| 23 |
get_not_valid_after, |
| 24 |
get_not_valid_before, |
| 25 |
) |
| 26 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.certificate_info import ( |
| 27 |
get_certificate_info, |
| 28 |
) |
| 29 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.support import ( |
| 30 |
load_certificate, |
| 31 |
load_certificate_privatekey, |
| 32 |
load_certificate_request, |
| 33 |
) |
| 34 |
from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import ( |
| 35 |
COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION, |
| 36 |
assert_required_cryptography_version, |
| 37 |
) |
| 38 |
|
| 39 |
if t.TYPE_CHECKING: |
| 40 |
import datetime # pragma: no cover |
| 41 |
|
| 42 |
from ansible.module_utils.basic import AnsibleModule # pragma: no cover |
| 43 |
|
| 44 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import ( # pragma: no cover |
| 45 |
CertificatePrivateKeyTypes, |
| 46 |
) |
| 47 |
|
| 48 |
|
| 49 |
MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION |
| 50 |
|
| 51 |
try: |
| 52 |
import cryptography |
| 53 |
from cryptography import x509 |
| 54 |
except ImportError: |
| 55 |
pass |
| 56 |
|
| 57 |
|
| 58 |
class CertificateError(OpenSSLObjectError): |
| 59 |
pass |
| 60 |
|
| 61 |
|
| 62 |
class CertificateBackend(metaclass=abc.ABCMeta): |
| 63 |
def __init__(self, *, module: AnsibleModule) -> None: |
| 64 |
self.module = module |
| 65 |
|
| 66 |
self.force: bool = module.params["force"] |
| 67 |
self.ignore_timestamps: bool = module.params["ignore_timestamps"] |
| 68 |
self.privatekey_path: str | None = module.params["privatekey_path"] |
| 69 |
privatekey_content: str | None = module.params["privatekey_content"] |
| 70 |
if privatekey_content is not None: |
| 71 |
self.privatekey_content: bytes | None = privatekey_content.encode("utf-8") |
| 72 |
else: |
| 73 |
self.privatekey_content = None |
| 74 |
self.privatekey_passphrase: str | None = module.params["privatekey_passphrase"] |
| 75 |
self.csr_path: str | None = module.params["csr_path"] |
| 76 |
csr_content = module.params["csr_content"] |
| 77 |
if csr_content is not None: |
| 78 |
self.csr_content: bytes | None = csr_content.encode("utf-8") |
| 79 |
else: |
| 80 |
self.csr_content = None |
| 81 |
|
| 82 |
# The following are default values which make sure check() works as |
| 83 |
# before if providers do not explicitly change these properties. |
| 84 |
self.create_subject_key_identifier: str = "never_create" |
| 85 |
self.create_authority_key_identifier: bool = False |
| 86 |
|
| 87 |
self.privatekey: CertificatePrivateKeyTypes | None = None |
| 88 |
self.csr: x509.CertificateSigningRequest | None = None |
| 89 |
self.cert: x509.Certificate | None = None |
| 90 |
self.existing_certificate: x509.Certificate | None = None |
| 91 |
self.existing_certificate_bytes: bytes | None = None |
| 92 |
|
| 93 |
self.check_csr_subject: bool = True |
| 94 |
self.check_csr_extensions: bool = True |
| 95 |
|
| 96 |
self.diff_before = self._get_info(None) |
| 97 |
self.diff_after = self._get_info(None) |
| 98 |
|
| 99 |
def _get_info(self, data: bytes | None) -> dict[str, t.Any]: |
| 100 |
if data is None: |
| 101 |
return {} |
| 102 |
try: |
| 103 |
result = get_certificate_info( |
| 104 |
module=self.module, content=data, prefer_one_fingerprint=True |
| 105 |
) |
| 106 |
result["can_parse_certificate"] = True |
| 107 |
return result |
| 108 |
except Exception: |
| 109 |
return {"can_parse_certificate": False} |
| 110 |
|
| 111 |
@abc.abstractmethod |
| 112 |
def generate_certificate(self) -> None: |
| 113 |
"""(Re-)Generate certificate.""" |
| 114 |
|
| 115 |
@abc.abstractmethod |
| 116 |
def get_certificate_data(self) -> bytes: |
| 117 |
"""Return bytes for self.cert.""" |
| 118 |
|
| 119 |
def set_existing(self, certificate_bytes: bytes | None) -> None: |
| 120 |
"""Set existing certificate bytes. None indicates that the key does not exist.""" |
| 121 |
self.existing_certificate_bytes = certificate_bytes |
| 122 |
self.diff_after = self.diff_before = self._get_info( |
| 123 |
self.existing_certificate_bytes |
| 124 |
) |
| 125 |
|
| 126 |
def has_existing(self) -> bool: |
| 127 |
"""Query whether an existing certificate is/has been there.""" |
| 128 |
return self.existing_certificate_bytes is not None |
| 129 |
|
| 130 |
def _ensure_private_key_loaded(self) -> None: |
| 131 |
"""Load the provided private key into self.privatekey.""" |
| 132 |
if self.privatekey is not None: |
| 133 |
return |
| 134 |
if self.privatekey_path is None and self.privatekey_content is None: |
| 135 |
return |
| 136 |
try: |
| 137 |
self.privatekey = load_certificate_privatekey( |
| 138 |
path=self.privatekey_path, |
| 139 |
content=self.privatekey_content, |
| 140 |
passphrase=self.privatekey_passphrase, |
| 141 |
) |
| 142 |
except OpenSSLBadPassphraseError as exc: |
| 143 |
raise CertificateError(exc) from exc |
| 144 |
|
| 145 |
def _ensure_csr_loaded(self) -> None: |
| 146 |
"""Load the CSR into self.csr.""" |
| 147 |
if self.csr is not None: |
| 148 |
return |
| 149 |
if self.csr_path is None and self.csr_content is None: |
| 150 |
return |
| 151 |
self.csr = load_certificate_request( |
| 152 |
path=self.csr_path, |
| 153 |
content=self.csr_content, |
| 154 |
) |
| 155 |
|
| 156 |
def _ensure_existing_certificate_loaded(self) -> None: |
| 157 |
"""Load the existing certificate into self.existing_certificate.""" |
| 158 |
if self.existing_certificate is not None: |
| 159 |
return |
| 160 |
if self.existing_certificate_bytes is None: |
| 161 |
return |
| 162 |
self.existing_certificate = load_certificate( |
| 163 |
path=None, |
| 164 |
content=self.existing_certificate_bytes, |
| 165 |
) |
| 166 |
|
| 167 |
def _check_privatekey(self) -> bool: |
| 168 |
"""Check whether provided parameters match, assuming self.existing_certificate and self.privatekey have been populated.""" |
| 169 |
if self.existing_certificate is None: |
| 170 |
raise AssertionError( # pragma: no cover |
| 171 |
"Contract violation: existing_certificate has not been populated" |
| 172 |
) |
| 173 |
if self.privatekey is None: |
| 174 |
raise AssertionError( # pragma: no cover |
| 175 |
"Contract violation: privatekey has not been populated" |
| 176 |
) |
| 177 |
return cryptography_compare_public_keys( |
| 178 |
self.existing_certificate.public_key(), self.privatekey.public_key() |
| 179 |
) |
| 180 |
|
| 181 |
def _check_csr(self) -> bool: |
| 182 |
"""Check whether provided parameters match, assuming self.existing_certificate and self.csr have been populated.""" |
| 183 |
if self.existing_certificate is None: |
| 184 |
raise AssertionError( # pragma: no cover |
| 185 |
"Contract violation: existing_certificate has not been populated" |
| 186 |
) |
| 187 |
if self.csr is None: |
| 188 |
raise AssertionError( |
| 189 |
"Contract violation: csr has not been populated" |
| 190 |
) # pragma: no cover |
| 191 |
# Verify that CSR is signed by certificate's private key |
| 192 |
if not self.csr.is_signature_valid: |
| 193 |
return False |
| 194 |
if not cryptography_compare_public_keys( |
| 195 |
self.csr.public_key(), self.existing_certificate.public_key() |
| 196 |
): |
| 197 |
return False |
| 198 |
# Check subject |
| 199 |
if ( |
| 200 |
self.check_csr_subject |
| 201 |
and self.csr.subject != self.existing_certificate.subject |
| 202 |
): |
| 203 |
return False |
| 204 |
# Check extensions |
| 205 |
if not self.check_csr_extensions: |
| 206 |
return True |
| 207 |
cert_exts = list(self.existing_certificate.extensions) |
| 208 |
csr_exts = list(self.csr.extensions) |
| 209 |
if self.create_subject_key_identifier != "never_create": |
| 210 |
# Filter out SubjectKeyIdentifier extension before comparison |
| 211 |
cert_exts = list( |
| 212 |
filter( |
| 213 |
lambda x: not isinstance(x.value, x509.SubjectKeyIdentifier), |
| 214 |
cert_exts, |
| 215 |
) |
| 216 |
) |
| 217 |
csr_exts = list( |
| 218 |
filter( |
| 219 |
lambda x: not isinstance(x.value, x509.SubjectKeyIdentifier), |
| 220 |
csr_exts, |
| 221 |
) |
| 222 |
) |
| 223 |
if self.create_authority_key_identifier: |
| 224 |
# Filter out AuthorityKeyIdentifier extension before comparison |
| 225 |
cert_exts = list( |
| 226 |
filter( |
| 227 |
lambda x: not isinstance(x.value, x509.AuthorityKeyIdentifier), |
| 228 |
cert_exts, |
| 229 |
) |
| 230 |
) |
| 231 |
csr_exts = list( |
| 232 |
filter( |
| 233 |
lambda x: not isinstance(x.value, x509.AuthorityKeyIdentifier), |
| 234 |
csr_exts, |
| 235 |
) |
| 236 |
) |
| 237 |
if len(cert_exts) != len(csr_exts): |
| 238 |
return False |
| 239 |
for cert_ext in cert_exts: |
| 240 |
try: |
| 241 |
csr_ext = self.csr.extensions.get_extension_for_oid(cert_ext.oid) |
| 242 |
if cert_ext != csr_ext: |
| 243 |
return False |
| 244 |
except cryptography.x509.ExtensionNotFound: |
| 245 |
return False |
| 246 |
return True |
| 247 |
|
| 248 |
def _check_subject_key_identifier(self) -> bool: |
| 249 |
"""Check whether Subject Key Identifier matches, assuming self.existing_certificate and self.csr have been populated.""" |
| 250 |
if self.existing_certificate is None: |
| 251 |
raise AssertionError( # pragma: no cover |
| 252 |
"Contract violation: existing_certificate has not been populated" |
| 253 |
) |
| 254 |
if self.csr is None: |
| 255 |
raise AssertionError( |
| 256 |
"Contract violation: csr has not been populated" |
| 257 |
) # pragma: no cover |
| 258 |
# Get hold of certificate's SKI |
| 259 |
try: |
| 260 |
ext = self.existing_certificate.extensions.get_extension_for_class( |
| 261 |
x509.SubjectKeyIdentifier |
| 262 |
) |
| 263 |
except cryptography.x509.ExtensionNotFound: |
| 264 |
return False |
| 265 |
# Get hold of CSR's SKI for 'create_if_not_provided' |
| 266 |
csr_ext = None |
| 267 |
if self.create_subject_key_identifier == "create_if_not_provided": |
| 268 |
try: |
| 269 |
csr_ext = self.csr.extensions.get_extension_for_class( |
| 270 |
x509.SubjectKeyIdentifier |
| 271 |
) |
| 272 |
except cryptography.x509.ExtensionNotFound: |
| 273 |
pass |
| 274 |
if csr_ext is None: |
| 275 |
# If CSR had no SKI, or we chose to ignore it ('always_create'), compare with created SKI |
| 276 |
if ( |
| 277 |
ext.value.digest |
| 278 |
!= x509.SubjectKeyIdentifier.from_public_key( |
| 279 |
self.existing_certificate.public_key() |
| 280 |
).digest |
| 281 |
): |
| 282 |
return False |
| 283 |
else: |
| 284 |
# If CSR had SKI and we did not ignore it ('create_if_not_provided'), compare SKIs |
| 285 |
if ext.value.digest != csr_ext.value.digest: |
| 286 |
return False |
| 287 |
return True |
| 288 |
|
| 289 |
def needs_regeneration( |
| 290 |
self, |
| 291 |
*, |
| 292 |
not_before: datetime.datetime | None = None, |
| 293 |
not_after: datetime.datetime | None = None, |
| 294 |
) -> bool: |
| 295 |
"""Check whether a regeneration is necessary.""" |
| 296 |
if self.force or self.existing_certificate_bytes is None: |
| 297 |
return True |
| 298 |
|
| 299 |
try: |
| 300 |
self._ensure_existing_certificate_loaded() |
| 301 |
except Exception: |
| 302 |
return True |
| 303 |
assert self.existing_certificate is not None |
| 304 |
|
| 305 |
# Check whether private key matches |
| 306 |
self._ensure_private_key_loaded() |
| 307 |
if self.privatekey is not None and not self._check_privatekey(): |
| 308 |
return True |
| 309 |
|
| 310 |
# Check whether CSR matches |
| 311 |
self._ensure_csr_loaded() |
| 312 |
if self.csr is not None and not self._check_csr(): |
| 313 |
return True |
| 314 |
|
| 315 |
# Check SubjectKeyIdentifier |
| 316 |
if ( |
| 317 |
self.create_subject_key_identifier != "never_create" |
| 318 |
and not self._check_subject_key_identifier() |
| 319 |
): |
| 320 |
return True |
| 321 |
|
| 322 |
# Check not before |
| 323 |
if ( |
| 324 |
not_before is not None |
| 325 |
and not self.ignore_timestamps |
| 326 |
and get_not_valid_before(self.existing_certificate) != not_before |
| 327 |
): |
| 328 |
return True |
| 329 |
|
| 330 |
# Check not after |
| 331 |
return bool( |
| 332 |
not_after is not None |
| 333 |
and not self.ignore_timestamps |
| 334 |
and get_not_valid_after(self.existing_certificate) != not_after |
| 335 |
) |
| 336 |
|
| 337 |
def dump(self, *, include_certificate: bool) -> dict[str, t.Any]: |
| 338 |
"""Serialize the object into a dictionary.""" |
| 339 |
result: dict[str, t.Any] = { |
| 340 |
"privatekey": self.privatekey_path, |
| 341 |
"csr": self.csr_path, |
| 342 |
} |
| 343 |
# Get hold of certificate bytes |
| 344 |
certificate_bytes = self.existing_certificate_bytes |
| 345 |
if self.cert is not None: |
| 346 |
certificate_bytes = self.get_certificate_data() |
| 347 |
self.diff_after = self._get_info(certificate_bytes) |
| 348 |
if include_certificate: |
| 349 |
# Store result |
| 350 |
result["certificate"] = ( |
| 351 |
certificate_bytes.decode("utf-8") if certificate_bytes else None |
| 352 |
) |
| 353 |
|
| 354 |
result["diff"] = { |
| 355 |
"before": self.diff_before, |
| 356 |
"after": self.diff_after, |
| 357 |
} |
| 358 |
return result |
| 359 |
|
| 360 |
|
| 361 |
class CertificateProvider(metaclass=abc.ABCMeta): |
| 362 |
@abc.abstractmethod |
| 363 |
def validate_module_args(self, module: AnsibleModule) -> None: |
| 364 |
"""Check module arguments""" |
| 365 |
|
| 366 |
@abc.abstractmethod |
| 367 |
def create_backend(self, module: AnsibleModule) -> CertificateBackend: |
| 368 |
"""Create an implementation for a backend. |
| 369 |
|
| 370 |
Return value must be instance of CertificateBackend. |
| 371 |
""" |
| 372 |
|
| 373 |
|
| 374 |
def select_backend( |
| 375 |
*, module: AnsibleModule, provider: CertificateProvider |
| 376 |
) -> CertificateBackend: |
| 377 |
provider.validate_module_args(module) |
| 378 |
|
| 379 |
assert_required_cryptography_version( |
| 380 |
module, minimum_cryptography_version=MINIMAL_CRYPTOGRAPHY_VERSION |
| 381 |
) |
| 382 |
|
| 383 |
return provider.create_backend(module) |
| 384 |
|
| 385 |
|
| 386 |
def get_certificate_argument_spec() -> ArgumentSpec: |
| 387 |
return ArgumentSpec( |
| 388 |
argument_spec={ |
| 389 |
"provider": { |
| 390 |
"type": "str", |
| 391 |
"choices": [], |
| 392 |
}, # choices will be filled by add_XXX_provider_to_argument_spec() in certificate_xxx.py |
| 393 |
"force": { |
| 394 |
"type": "bool", |
| 395 |
"default": False, |
| 396 |
}, |
| 397 |
"csr_path": {"type": "path"}, |
| 398 |
"csr_content": {"type": "str"}, |
| 399 |
"ignore_timestamps": {"type": "bool", "default": True}, |
| 400 |
"select_crypto_backend": { |
| 401 |
"type": "str", |
| 402 |
"default": "auto", |
| 403 |
"choices": ["auto", "cryptography"], |
| 404 |
}, |
| 405 |
# General properties of a certificate |
| 406 |
"privatekey_path": {"type": "path"}, |
| 407 |
"privatekey_content": {"type": "str", "no_log": True}, |
| 408 |
"privatekey_passphrase": {"type": "str", "no_log": True}, |
| 409 |
}, |
| 410 |
mutually_exclusive=[ |
| 411 |
["csr_path", "csr_content"], |
| 412 |
["privatekey_path", "privatekey_content"], |
| 413 |
], |
| 414 |
) |
| 415 |
|
| 416 |
|
| 417 |
__all__ = ( |
| 418 |
"CertificateBackend", |
| 419 |
"CertificateError", |
| 420 |
"CertificateProvider", |
| 421 |
"get_certificate_argument_spec", |
| 422 |
) |