| 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: acme_challenge_cert_helper |
| 10 |
author: "Felix Fontein (@felixfontein)" |
| 11 |
short_description: Prepare certificates required for ACME challenges such as C(tls-alpn-01) |
| 12 |
description: |
| 13 |
- Prepares certificates for ACME challenges such as C(tls-alpn-01). |
| 14 |
- The raw data is provided by the M(community.crypto.acme_certificate) module, and needs to be converted to a certificate |
| 15 |
to be used for challenge validation. This module provides a simple way to generate the required certificates. |
| 16 |
seealso: |
| 17 |
- name: Automatic Certificate Management Environment (ACME) |
| 18 |
description: The specification of the ACME protocol (RFC 8555). |
| 19 |
link: https://tools.ietf.org/html/rfc8555 |
| 20 |
- name: ACME TLS ALPN Challenge Extension |
| 21 |
description: The specification of the C(tls-alpn-01) challenge (RFC 8737). |
| 22 |
link: https://www.rfc-editor.org/rfc/rfc8737.html |
| 23 |
extends_documentation_fragment: |
| 24 |
- community.crypto._attributes |
| 25 |
- community.crypto._cryptography_dep.minimum |
| 26 |
attributes: |
| 27 |
check_mode: |
| 28 |
support: none |
| 29 |
details: |
| 30 |
- This action does not modify state. |
| 31 |
diff_mode: |
| 32 |
support: N/A |
| 33 |
details: |
| 34 |
- This action does not modify state. |
| 35 |
idempotent: |
| 36 |
support: none |
| 37 |
details: |
| 38 |
- The certificates returned are never the same, since the Not Before and Not After timestamps |
| 39 |
depend on the invocation's timestamp. |
| 40 |
options: |
| 41 |
challenge: |
| 42 |
description: |
| 43 |
- The challenge type. |
| 44 |
type: str |
| 45 |
required: true |
| 46 |
choices: |
| 47 |
- tls-alpn-01 |
| 48 |
challenge_data: |
| 49 |
description: |
| 50 |
- The RV(community.crypto.acme_certificate#module:challenge_data) entry provided by M(community.crypto.acme_certificate) |
| 51 |
for the challenge. |
| 52 |
type: dict |
| 53 |
required: true |
| 54 |
private_key_src: |
| 55 |
description: |
| 56 |
- Path to a file containing the private key file to use for this challenge certificate. |
| 57 |
- Mutually exclusive with O(private_key_content). |
| 58 |
type: path |
| 59 |
private_key_content: |
| 60 |
description: |
| 61 |
- Content of the private key to use for this challenge certificate. |
| 62 |
- Mutually exclusive with O(private_key_src). |
| 63 |
type: str |
| 64 |
private_key_passphrase: |
| 65 |
description: |
| 66 |
- Passphrase to use to decode the private key. |
| 67 |
type: str |
| 68 |
version_added: 1.6.0 |
| 69 |
""" |
| 70 |
|
| 71 |
EXAMPLES = r""" |
| 72 |
--- |
| 73 |
- name: Create challenges for a given CRT for sample.com |
| 74 |
community.crypto.acme_certificate: |
| 75 |
account_key_src: /etc/pki/cert/private/account.key |
| 76 |
challenge: tls-alpn-01 |
| 77 |
csr: /etc/pki/cert/csr/sample.com.csr |
| 78 |
dest: /etc/httpd/ssl/sample.com.crt |
| 79 |
modify_account: false |
| 80 |
register: sample_com_challenge |
| 81 |
|
| 82 |
- name: Create certificates for challenges |
| 83 |
community.crypto.acme_challenge_cert_helper: |
| 84 |
challenge: tls-alpn-01 |
| 85 |
challenge_data: "{{ item.value['tls-alpn-01'] }}" |
| 86 |
private_key_src: /etc/pki/cert/key/sample.com.key |
| 87 |
loop: "{{ sample_com_challenge.challenge_data | dictsort }}" |
| 88 |
register: sample_com_challenge_certs |
| 89 |
|
| 90 |
- name: Install challenge certificates |
| 91 |
# We need to set up HTTPS such that for the domain, |
| 92 |
# regular_certificate is delivered for regular connections, |
| 93 |
# except if ALPN selects the "acme-tls/1"; then, the |
| 94 |
# challenge_certificate must be delivered. |
| 95 |
# This can for example be achieved with very new versions |
| 96 |
# of NGINX; search for ssl_preread and |
| 97 |
# ssl_preread_alpn_protocols for information on how to |
| 98 |
# route by ALPN protocol. |
| 99 |
...: |
| 100 |
domain: "{{ item.domain }}" |
| 101 |
challenge_certificate: "{{ item.challenge_certificate }}" |
| 102 |
regular_certificate: "{{ item.regular_certificate }}" |
| 103 |
private_key: /etc/pki/cert/key/sample.com.key |
| 104 |
loop: "{{ sample_com_challenge_certs.results }}" |
| 105 |
|
| 106 |
- name: Create certificate for a given CSR for sample.com |
| 107 |
community.crypto.acme_certificate: |
| 108 |
account_key_src: /etc/pki/cert/private/account.key |
| 109 |
challenge: tls-alpn-01 |
| 110 |
csr: /etc/pki/cert/csr/sample.com.csr |
| 111 |
dest: /etc/httpd/ssl/sample.com.crt |
| 112 |
data: "{{ sample_com_challenge }}" |
| 113 |
modify_account: false |
| 114 |
""" |
| 115 |
|
| 116 |
RETURN = r""" |
| 117 |
domain: |
| 118 |
description: |
| 119 |
- The domain the challenge is for. The certificate should be provided if this is specified in the request's the C(Host) |
| 120 |
header. |
| 121 |
returned: always |
| 122 |
type: str |
| 123 |
identifier_type: |
| 124 |
description: |
| 125 |
- The identifier type for the actual resource identifier. |
| 126 |
returned: always |
| 127 |
type: str |
| 128 |
choices: |
| 129 |
- dns |
| 130 |
- ip |
| 131 |
identifier: |
| 132 |
description: |
| 133 |
- The identifier for the actual resource. Will be a domain name if RV(identifier_type=dns), or an IP address if RV(identifier_type=ip). |
| 134 |
returned: always |
| 135 |
type: str |
| 136 |
challenge_certificate: |
| 137 |
description: |
| 138 |
- The challenge certificate in PEM format. |
| 139 |
returned: always |
| 140 |
type: str |
| 141 |
regular_certificate: |
| 142 |
description: |
| 143 |
- A self-signed certificate for the challenge domain. |
| 144 |
- If no existing certificate exists, can be used to set-up https in the first place if that is needed for providing the |
| 145 |
challenge. |
| 146 |
returned: always |
| 147 |
type: str |
| 148 |
""" |
| 149 |
|
| 150 |
import base64 |
| 151 |
import datetime |
| 152 |
import ipaddress |
| 153 |
import typing as t |
| 154 |
|
| 155 |
from ansible.module_utils.basic import AnsibleModule |
| 156 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 157 |
|
| 158 |
from ansible_collections.community.crypto.plugins.module_utils._acme.errors import ( |
| 159 |
ModuleFailException, |
| 160 |
) |
| 161 |
from ansible_collections.community.crypto.plugins.module_utils._acme.io import read_file |
| 162 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import ( |
| 163 |
CRYPTOGRAPHY_TIMEZONE, |
| 164 |
set_not_valid_after, |
| 165 |
set_not_valid_before, |
| 166 |
) |
| 167 |
from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import ( |
| 168 |
COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION, |
| 169 |
assert_required_cryptography_version, |
| 170 |
) |
| 171 |
from ansible_collections.community.crypto.plugins.module_utils._time import ( |
| 172 |
get_now_datetime, |
| 173 |
) |
| 174 |
|
| 175 |
try: |
| 176 |
import cryptography |
| 177 |
import cryptography.hazmat.backends |
| 178 |
import cryptography.hazmat.primitives.asymmetric.dsa |
| 179 |
import cryptography.hazmat.primitives.asymmetric.ec |
| 180 |
import cryptography.hazmat.primitives.asymmetric.ed448 |
| 181 |
import cryptography.hazmat.primitives.asymmetric.ed25519 |
| 182 |
import cryptography.hazmat.primitives.asymmetric.padding |
| 183 |
import cryptography.hazmat.primitives.asymmetric.rsa |
| 184 |
import cryptography.hazmat.primitives.asymmetric.utils |
| 185 |
import cryptography.hazmat.primitives.hashes |
| 186 |
import cryptography.hazmat.primitives.serialization |
| 187 |
import cryptography.x509 |
| 188 |
import cryptography.x509.oid |
| 189 |
except ImportError: |
| 190 |
pass |
| 191 |
|
| 192 |
|
| 193 |
# Convert byte string to ASN1 encoded octet string |
| 194 |
def encode_octet_string(octet_string: bytes) -> bytes: |
| 195 |
if len(octet_string) >= 128: |
| 196 |
raise ModuleFailException( |
| 197 |
"Cannot handle octet strings with more than 128 bytes" |
| 198 |
) |
| 199 |
return bytes([0x4, len(octet_string)]) + octet_string |
| 200 |
|
| 201 |
|
| 202 |
def main() -> t.NoReturn: |
| 203 |
module = AnsibleModule( |
| 204 |
argument_spec={ |
| 205 |
"challenge": {"type": "str", "required": True, "choices": ["tls-alpn-01"]}, |
| 206 |
"challenge_data": {"type": "dict", "required": True}, |
| 207 |
"private_key_src": {"type": "path"}, |
| 208 |
"private_key_content": {"type": "str", "no_log": True}, |
| 209 |
"private_key_passphrase": {"type": "str", "no_log": True}, |
| 210 |
}, |
| 211 |
required_one_of=(["private_key_src", "private_key_content"],), |
| 212 |
mutually_exclusive=(["private_key_src", "private_key_content"],), |
| 213 |
) |
| 214 |
|
| 215 |
assert_required_cryptography_version( |
| 216 |
module, minimum_cryptography_version=COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION |
| 217 |
) |
| 218 |
|
| 219 |
try: |
| 220 |
# Get parameters |
| 221 |
challenge: t.Literal["tls-alpn-01"] = module.params["challenge"] |
| 222 |
challenge_data: dict[str, t.Any] = module.params["challenge_data"] |
| 223 |
|
| 224 |
# Get hold of private key |
| 225 |
private_key_content_str: str | None = module.params["private_key_content"] |
| 226 |
private_key_passphrase: str | None = module.params["private_key_passphrase"] |
| 227 |
if private_key_content_str is None: |
| 228 |
private_key_content = read_file(module.params["private_key_src"]) |
| 229 |
else: |
| 230 |
private_key_content = to_bytes(private_key_content_str) |
| 231 |
try: |
| 232 |
private_key = ( |
| 233 |
cryptography.hazmat.primitives.serialization.load_pem_private_key( |
| 234 |
private_key_content, |
| 235 |
password=( |
| 236 |
to_bytes(private_key_passphrase) |
| 237 |
if private_key_passphrase is not None |
| 238 |
else None |
| 239 |
), |
| 240 |
) |
| 241 |
) |
| 242 |
except Exception as e: |
| 243 |
raise ModuleFailException(f"Error while loading private key: {e}") from e |
| 244 |
if not isinstance( |
| 245 |
private_key, |
| 246 |
( |
| 247 |
cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey, |
| 248 |
cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey, |
| 249 |
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey, |
| 250 |
cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey, |
| 251 |
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey, |
| 252 |
), |
| 253 |
): |
| 254 |
raise ModuleFailException( |
| 255 |
f"Cannot use private key type {type(private_key)}" |
| 256 |
) |
| 257 |
|
| 258 |
# Some common attributes |
| 259 |
domain = to_text(challenge_data["resource"]) |
| 260 |
identifier_type, identifier = to_text( |
| 261 |
challenge_data.get("resource_original", "dns:" + challenge_data["resource"]) |
| 262 |
).split(":", 1) |
| 263 |
subject = issuer = cryptography.x509.Name([]) |
| 264 |
now = get_now_datetime(with_timezone=CRYPTOGRAPHY_TIMEZONE) |
| 265 |
not_valid_before = now |
| 266 |
not_valid_after = now + datetime.timedelta(days=10) |
| 267 |
san: cryptography.x509.GeneralName |
| 268 |
if identifier_type == "dns": |
| 269 |
san = cryptography.x509.DNSName(identifier) |
| 270 |
elif identifier_type == "ip": |
| 271 |
san = cryptography.x509.IPAddress(ipaddress.ip_address(identifier)) |
| 272 |
else: |
| 273 |
raise ModuleFailException( |
| 274 |
f'Unsupported identifier type "{identifier_type}"' |
| 275 |
) |
| 276 |
|
| 277 |
# Generate regular self-signed certificate |
| 278 |
cert_builder = ( |
| 279 |
cryptography.x509.CertificateBuilder() |
| 280 |
.subject_name(subject) |
| 281 |
.issuer_name(issuer) |
| 282 |
.public_key(private_key.public_key()) |
| 283 |
.serial_number(cryptography.x509.random_serial_number()) |
| 284 |
.add_extension( |
| 285 |
cryptography.x509.SubjectAlternativeName([san]), |
| 286 |
critical=False, |
| 287 |
) |
| 288 |
) |
| 289 |
cert_builder = set_not_valid_before(cert_builder, not_valid_before) |
| 290 |
cert_builder = set_not_valid_after(cert_builder, not_valid_after) |
| 291 |
regular_certificate = cert_builder.sign( |
| 292 |
private_key, |
| 293 |
cryptography.hazmat.primitives.hashes.SHA256(), |
| 294 |
) |
| 295 |
|
| 296 |
# Process challenge |
| 297 |
if challenge == "tls-alpn-01": |
| 298 |
value = base64.b64decode(challenge_data["resource_value"]) |
| 299 |
cert_builder = ( |
| 300 |
cryptography.x509.CertificateBuilder() |
| 301 |
.subject_name(subject) |
| 302 |
.issuer_name(issuer) |
| 303 |
.public_key(private_key.public_key()) |
| 304 |
.serial_number(cryptography.x509.random_serial_number()) |
| 305 |
.add_extension( |
| 306 |
cryptography.x509.SubjectAlternativeName([san]), |
| 307 |
critical=False, |
| 308 |
) |
| 309 |
.add_extension( |
| 310 |
cryptography.x509.UnrecognizedExtension( |
| 311 |
cryptography.x509.ObjectIdentifier("1.3.6.1.5.5.7.1.31"), |
| 312 |
encode_octet_string(value), |
| 313 |
), |
| 314 |
critical=True, |
| 315 |
) |
| 316 |
) |
| 317 |
cert_builder = set_not_valid_before(cert_builder, not_valid_before) |
| 318 |
cert_builder = set_not_valid_after(cert_builder, not_valid_after) |
| 319 |
challenge_certificate = cert_builder.sign( |
| 320 |
private_key, |
| 321 |
cryptography.hazmat.primitives.hashes.SHA256(), |
| 322 |
) |
| 323 |
else: |
| 324 |
raise AssertionError("Can never be reached") # pragma: no cover |
| 325 |
|
| 326 |
module.exit_json( |
| 327 |
changed=True, |
| 328 |
domain=domain, |
| 329 |
identifier_type=identifier_type, |
| 330 |
identifier=identifier, |
| 331 |
challenge_certificate=challenge_certificate.public_bytes( |
| 332 |
cryptography.hazmat.primitives.serialization.Encoding.PEM |
| 333 |
), |
| 334 |
regular_certificate=regular_certificate.public_bytes( |
| 335 |
cryptography.hazmat.primitives.serialization.Encoding.PEM |
| 336 |
), |
| 337 |
) |
| 338 |
except ModuleFailException as e: |
| 339 |
e.do_fail(module=module) |
| 340 |
|
| 341 |
|
| 342 |
if __name__ == "__main__": |
| 343 |
main() |