From 6499cf56203bc9ae3a2c20a6f8a9a7e764528f73 Mon Sep 17 00:00:00 2001 From: Felix Fontein Date: Wed, 28 Dec 2022 21:32:41 +0100 Subject: [PATCH] Add x509_certificate_info filter. --- plugins/filter/x509_certificate_info.py | 346 ++++++++++++++++++ .../crypto/cryptography_support.py | 10 +- .../module_backends/certificate_info.py | 2 +- plugins/modules/x509_certificate_info.py | 4 + .../filter_x509_certificate_info/aliases | 7 + .../files/cert1.pem | 45 +++ .../meta/main.yml | 9 + .../tasks/impl.yml | 221 +++++++++++ .../tasks/main.yml | 151 ++++++++ 9 files changed, 789 insertions(+), 6 deletions(-) create mode 100644 plugins/filter/x509_certificate_info.py create mode 100644 tests/integration/targets/filter_x509_certificate_info/aliases create mode 100644 tests/integration/targets/filter_x509_certificate_info/files/cert1.pem create mode 100644 tests/integration/targets/filter_x509_certificate_info/meta/main.yml create mode 100644 tests/integration/targets/filter_x509_certificate_info/tasks/impl.yml create mode 100644 tests/integration/targets/filter_x509_certificate_info/tasks/main.yml diff --git a/plugins/filter/x509_certificate_info.py b/plugins/filter/x509_certificate_info.py new file mode 100644 index 000000000..c267a562d --- /dev/null +++ b/plugins/filter/x509_certificate_info.py @@ -0,0 +1,346 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2022, Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +DOCUMENTATION = ''' +name: x509_certificate_info +short_description: Retrieve information from X.509 certificates in PEM format +version_added: 2.10.0 +author: + - Felix Fontein (@felixfontein) +description: + - Provided a X.509 certificate in PEM format, retrieve information. + - This is a filter version of the M(community.crypto.x509_certificate_info) module. +options: + _input: + description: + - The content of the X.509 certificate in PEM format. + type: string + required: true +extends_documentation_fragment: + - community.crypto.name_encoding +seealso: + - module: community.crypto.x509_certificate_info +''' + +EXAMPLES = ''' +- name: Show the Subject Alt Names of the certificate + ansible.builtin.debug: + msg: >- + {{ + ( + lookup('ansible.builtin.file', '/path/to/cert.pem') + | community.crypto.x509_certificate_info + ).subject_alt_name | join(', ') + }} +''' + +RETURN = ''' +_value: + description: + - Information on the certificate. + type: dict + contains: + expired: + description: Whether the certificate is expired (in other words, C(notAfter) is in the past). + returned: success + type: bool + basic_constraints: + description: Entries in the C(basic_constraints) extension, or C(none) if extension is not present. + returned: success + type: list + elements: str + sample: ["CA:TRUE", "pathlen:1"] + basic_constraints_critical: + description: Whether the C(basic_constraints) extension is critical. + returned: success + type: bool + extended_key_usage: + description: Entries in the C(extended_key_usage) extension, or C(none) if extension is not present. + returned: success + type: list + elements: str + sample: [Biometric Info, DVCS, Time Stamping] + extended_key_usage_critical: + description: Whether the C(extended_key_usage) extension is critical. + returned: success + type: bool + extensions_by_oid: + description: Returns a dictionary for every extension OID. + returned: success + type: dict + contains: + critical: + description: Whether the extension is critical. + returned: success + type: bool + value: + description: + - The Base64 encoded value (in DER format) of the extension. + - B(Note) that depending on the C(cryptography) version used, it is + not possible to extract the ASN.1 content of the extension, but only + to provide the re-encoded content of the extension in case it was + parsed by C(cryptography). This should usually result in exactly the + same value, except if the original extension value was malformed. + returned: success + type: str + sample: "MAMCAQU=" + sample: {"1.3.6.1.5.5.7.1.24": { "critical": false, "value": "MAMCAQU="}} + key_usage: + description: Entries in the C(key_usage) extension, or C(none) if extension is not present. + returned: success + type: str + sample: [Key Agreement, Data Encipherment] + key_usage_critical: + description: Whether the C(key_usage) extension is critical. + returned: success + type: bool + subject_alt_name: + description: + - Entries in the C(subject_alt_name) extension, or C(none) if extension is not present. + - See I(name_encoding) for how IDNs are handled. + returned: success + type: list + elements: str + sample: ["DNS:www.ansible.com", "IP:1.2.3.4"] + subject_alt_name_critical: + description: Whether the C(subject_alt_name) extension is critical. + returned: success + type: bool + ocsp_must_staple: + description: C(true) if the OCSP Must Staple extension is present, C(none) otherwise. + returned: success + type: bool + ocsp_must_staple_critical: + description: Whether the C(ocsp_must_staple) extension is critical. + returned: success + type: bool + issuer: + description: + - The certificate's issuer. + - Note that for repeated values, only the last one will be returned. + returned: success + type: dict + sample: {"organizationName": "Ansible", "commonName": "ca.example.com"} + issuer_ordered: + description: The certificate's issuer as an ordered list of tuples. + returned: success + type: list + elements: list + sample: [["organizationName", "Ansible"], ["commonName": "ca.example.com"]] + subject: + description: + - The certificate's subject as a dictionary. + - Note that for repeated values, only the last one will be returned. + returned: success + type: dict + sample: {"commonName": "www.example.com", "emailAddress": "test@example.com"} + subject_ordered: + description: The certificate's subject as an ordered list of tuples. + returned: success + type: list + elements: list + sample: [["commonName", "www.example.com"], ["emailAddress": "test@example.com"]] + not_after: + description: C(notAfter) date as ASN.1 TIME. + returned: success + type: str + sample: '20190413202428Z' + not_before: + description: C(notBefore) date as ASN.1 TIME. + returned: success + type: str + sample: '20190331202428Z' + public_key: + description: Certificate's public key in PEM format. + returned: success + type: str + sample: "-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A..." + public_key_type: + description: + - The certificate's public key's type. + - One of C(RSA), C(DSA), C(ECC), C(Ed25519), C(X25519), C(Ed448), or C(X448). + - Will start with C(unknown) if the key type cannot be determined. + returned: success + type: str + sample: RSA + public_key_data: + description: + - Public key data. Depends on the public key's type. + returned: success + type: dict + contains: + size: + description: + - Bit size of modulus (RSA) or prime number (DSA). + type: int + returned: When C(public_key_type=RSA) or C(public_key_type=DSA) + modulus: + description: + - The RSA key's modulus. + type: int + returned: When C(public_key_type=RSA) + exponent: + description: + - The RSA key's public exponent. + type: int + returned: When C(public_key_type=RSA) + p: + description: + - The C(p) value for DSA. + - This is the prime modulus upon which arithmetic takes place. + type: int + returned: When C(public_key_type=DSA) + q: + description: + - The C(q) value for DSA. + - This is a prime that divides C(p - 1), and at the same time the order of the subgroup of the + multiplicative group of the prime field used. + type: int + returned: When C(public_key_type=DSA) + g: + description: + - The C(g) value for DSA. + - This is the element spanning the subgroup of the multiplicative group of the prime field used. + type: int + returned: When C(public_key_type=DSA) + curve: + description: + - The curve's name for ECC. + type: str + returned: When C(public_key_type=ECC) + exponent_size: + description: + - The maximum number of bits of a private key. This is basically the bit size of the subgroup used. + type: int + returned: When C(public_key_type=ECC) + x: + description: + - The C(x) coordinate for the public point on the elliptic curve. + type: int + returned: When C(public_key_type=ECC) + y: + description: + - For C(public_key_type=ECC), this is the C(y) coordinate for the public point on the elliptic curve. + - For C(public_key_type=DSA), this is the publicly known group element whose discrete logarithm w.r.t. C(g) is the private key. + type: int + returned: When C(public_key_type=DSA) or C(public_key_type=ECC) + public_key_fingerprints: + description: + - Fingerprints of certificate's public key. + - For every hash algorithm available, the fingerprint is computed. + returned: success + type: dict + sample: "{'sha256': 'd4:b3:aa:6d:c8:04:ce:4e:ba:f6:29:4d:92:a3:94:b0:c2:ff:bd:bf:33:63:11:43:34:0f:51:b0:95:09:2f:63', + 'sha512': 'f7:07:4a:f0:b0:f0:e6:8b:95:5f:f9:e6:61:0a:32:68:f1..." + fingerprints: + description: + - Fingerprints of the DER-encoded form of the whole certificate. + - For every hash algorithm available, the fingerprint is computed. + returned: success + type: dict + sample: "{'sha256': 'd4:b3:aa:6d:c8:04:ce:4e:ba:f6:29:4d:92:a3:94:b0:c2:ff:bd:bf:33:63:11:43:34:0f:51:b0:95:09:2f:63', + 'sha512': 'f7:07:4a:f0:b0:f0:e6:8b:95:5f:f9:e6:61:0a:32:68:f1..." + signature_algorithm: + description: The signature algorithm used to sign the certificate. + returned: success + type: str + sample: sha256WithRSAEncryption + serial_number: + description: The certificate's serial number. + returned: success + type: int + sample: 1234 + version: + description: The certificate version. + returned: success + type: int + sample: 3 + subject_key_identifier: + description: + - The certificate's subject key identifier. + - The identifier is returned in hexadecimal, with C(:) used to separate bytes. + - Is C(none) if the C(SubjectKeyIdentifier) extension is not present. + returned: success + type: str + sample: '00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33' + authority_key_identifier: + description: + - The certificate's authority key identifier. + - The identifier is returned in hexadecimal, with C(:) used to separate bytes. + - Is C(none) if the C(AuthorityKeyIdentifier) extension is not present. + returned: success + type: str + sample: '00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33' + authority_cert_issuer: + description: + - The certificate's authority cert issuer as a list of general names. + - Is C(none) if the C(AuthorityKeyIdentifier) extension is not present. + - See I(name_encoding) for how IDNs are handled. + returned: success + type: list + elements: str + sample: ["DNS:www.ansible.com", "IP:1.2.3.4"] + authority_cert_serial_number: + description: + - The certificate's authority cert serial number. + - Is C(none) if the C(AuthorityKeyIdentifier) extension is not present. + returned: success + type: int + sample: 12345 + ocsp_uri: + description: The OCSP responder URI, if included in the certificate. Will be + C(none) if no OCSP responder URI is included. + returned: success + type: str + issuer_uri: + description: The Issuer URI, if included in the certificate. Will be + C(none) if no issuer URI is included. + returned: success + type: str +''' + +from ansible.errors import AnsibleFilterError +from ansible.module_utils.six import string_types +from ansible.module_utils.common.text.converters import to_bytes, to_native + +from ansible_collections.community.crypto.plugins.module_utils.crypto.basic import ( + OpenSSLObjectError, +) + +from ansible_collections.community.crypto.plugins.module_utils.crypto.module_backends.certificate_info import ( + get_certificate_info, +) + +from ansible_collections.community.crypto.plugins.plugin_utils.filter_module import FilterModuleMock + + +def x509_certificate_info_filter(data, name_encoding='ignore'): + '''Extract information from X.509 PEM certificate.''' + if not isinstance(data, string_types): + raise AnsibleFilterError('The community.crypto.x509_certificate_info input must be a text type, not %s' % type(data)) + if not isinstance(name_encoding, string_types): + raise AnsibleFilterError('The name_encoding option must be of a text type, not %s' % type(data)) + name_encoding = to_native(name_encoding) + if name_encoding not in ('ignore', 'idna', 'unicode'): + raise AnsibleFilterError('The name_encoding option must be one of the values "ignore", "idna", or "unicode", not "%s"' % data) + + module = FilterModuleMock({'name_encoding': name_encoding}) + try: + return get_certificate_info(module, 'cryptography', content=to_bytes(data)) + except OpenSSLObjectError as exc: + raise AnsibleFilterError(to_native(exc)) + + +class FilterModule(object): + '''Ansible jinja2 filters''' + + def filters(self): + return { + 'x509_certificate_info': x509_certificate_info_filter, + } diff --git a/plugins/module_utils/crypto/cryptography_support.py b/plugins/module_utils/crypto/cryptography_support.py index 17a1910af..fde691997 100644 --- a/plugins/module_utils/crypto/cryptography_support.py +++ b/plugins/module_utils/crypto/cryptography_support.py @@ -14,7 +14,7 @@ import sys import traceback -from ansible.module_utils.common.text.converters import to_text, to_bytes +from ansible.module_utils.common.text.converters import to_text, to_bytes, to_native from ansible.module_utils.six.moves.urllib.parse import urlparse, urlunparse, ParseResult from ._asn1 import serialize_asn1_string_as_der @@ -138,7 +138,7 @@ def cryptography_get_extensions_from_cert(cert): der = backend._ffi.buffer(data.data, data.length)[:] entry = dict( critical=(crit == 1), - value=base64.b64encode(der), + value=to_native(base64.b64encode(der)), ) try: oid = obj2txt(backend._lib, backend._ffi, backend._lib.X509_EXTENSION_get_object(ext)) @@ -155,7 +155,7 @@ def cryptography_get_extensions_from_cert(cert): for ext in cert.extensions: result[ext.oid.dotted_string] = dict( critical=ext.critical, - value=base64.b64encode(ext.value.public_bytes()), + value=to_native(base64.b64encode(ext.value.public_bytes())), ) return result @@ -198,7 +198,7 @@ def cryptography_get_extensions_from_csr(csr): der = backend._ffi.buffer(data.data, data.length)[:] entry = dict( critical=(crit == 1), - value=base64.b64encode(der), + value=to_native(base64.b64encode(der)), ) try: oid = obj2txt(backend._lib, backend._ffi, backend._lib.X509_EXTENSION_get_object(ext)) @@ -215,7 +215,7 @@ def cryptography_get_extensions_from_csr(csr): for ext in csr.extensions: result[ext.oid.dotted_string] = dict( critical=ext.critical, - value=base64.b64encode(ext.value.public_bytes()), + value=to_native(base64.b64encode(ext.value.public_bytes())), ) return result diff --git a/plugins/module_utils/crypto/module_backends/certificate_info.py b/plugins/module_utils/crypto/module_backends/certificate_info.py index 8c13faaf2..a7beec6c1 100644 --- a/plugins/module_utils/crypto/module_backends/certificate_info.py +++ b/plugins/module_utils/crypto/module_backends/certificate_info.py @@ -171,7 +171,7 @@ def get_info(self, prefer_one_fingerprint=False): result['not_after'] = not_after.strftime(TIMESTAMP_FORMAT) result['expired'] = not_after < datetime.datetime.utcnow() - result['public_key'] = self._get_public_key_pem() + result['public_key'] = to_native(self._get_public_key_pem()) public_key_info = get_publickey_info( self.module, diff --git a/plugins/modules/x509_certificate_info.py b/plugins/modules/x509_certificate_info.py index 477124a2c..4c7a2bc4a 100644 --- a/plugins/modules/x509_certificate_info.py +++ b/plugins/modules/x509_certificate_info.py @@ -73,6 +73,10 @@ seealso: - module: community.crypto.x509_certificate - module: community.crypto.x509_certificate_pipe + - ref: community.crypto.x509_certificate_info filter + # - plugin: community.crypto.x509_certificate_info + # plugin_type: filter + description: A filter variant of this module. ''' EXAMPLES = r''' diff --git a/tests/integration/targets/filter_x509_certificate_info/aliases b/tests/integration/targets/filter_x509_certificate_info/aliases new file mode 100644 index 000000000..4602f1185 --- /dev/null +++ b/tests/integration/targets/filter_x509_certificate_info/aliases @@ -0,0 +1,7 @@ +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +azp/generic/2 +azp/posix/2 +destructive diff --git a/tests/integration/targets/filter_x509_certificate_info/files/cert1.pem b/tests/integration/targets/filter_x509_certificate_info/files/cert1.pem new file mode 100644 index 000000000..834eedc44 --- /dev/null +++ b/tests/integration/targets/filter_x509_certificate_info/files/cert1.pem @@ -0,0 +1,45 @@ +-----BEGIN CERTIFICATE----- +MIIH5jCCBs6gAwIBAgISA2gSCm/BtvCR2e2bIap5YbXaMA0GCSqGSIb3DQEBCwUA +MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD +ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0xODA3MjcxNzMxMjdaFw0x +ODEwMjUxNzMxMjdaM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oyg3TcMun5 +Gb2dEn1cttMnPW9u670/JdRjvjU/wTANBgkqhkiG9w0BAQsFAAOCAQEAGepCmckP +Tn9Sz268FEwkdD+6wWaPfeYlh+9nacFh90nQ35EYQMOK8a+X7ixHGbRz19On3Wt4 +1fcbPa9SefocTjAintMwwreCxpRTmwGACYojd7vRWEmA6q7+/HO2BfZahWzclOjw +mSDBycDEm8R0ZK52vYjzVno8x0mrsmSO0403S/6syYB/guH6P17kIBw+Tgx6/i/c +I1C6MoFkuaAKUUcZmgGGBgE+L/7cWtWjbkVXyA3ZQQy9G7rcBT+N/RrDfBh4iZDq +jAN5UIIYL8upBhjiMYVuoJrH2nklzEwr5SWKcccJX5eWkGLUwlcY9LGAA8+17l2I +l1Ou20Dm9TxnNw== +-----END CERTIFICATE----- diff --git a/tests/integration/targets/filter_x509_certificate_info/meta/main.yml b/tests/integration/targets/filter_x509_certificate_info/meta/main.yml new file mode 100644 index 000000000..7c2b42405 --- /dev/null +++ b/tests/integration/targets/filter_x509_certificate_info/meta/main.yml @@ -0,0 +1,9 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +dependencies: + - setup_openssl + - setup_remote_tmp_dir + - prepare_jinja2_compat diff --git a/tests/integration/targets/filter_x509_certificate_info/tasks/impl.yml b/tests/integration/targets/filter_x509_certificate_info/tasks/impl.yml new file mode 100644 index 000000000..963220ec1 --- /dev/null +++ b/tests/integration/targets/filter_x509_certificate_info/tasks/impl.yml @@ -0,0 +1,221 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +- name: Get certificate info + set_fact: + result: >- + {{ lookup('file', remote_tmp_dir ~ '/cert_1.pem') | community.crypto.x509_certificate_info }} + result_idna: >- + {{ lookup('file', remote_tmp_dir ~ '/cert_1.pem') | community.crypto.x509_certificate_info(name_encoding='idna') }} + result_unicode: >- + {{ lookup('file', remote_tmp_dir ~ '/cert_1.pem') | community.crypto.x509_certificate_info(name_encoding='unicode') }} + +- name: Check whether issuer and subject and extensions behave as expected + assert: + that: + - result.issuer.organizationalUnitName == 'ACME Department' + - "['organizationalUnitName', 'Crypto Department'] in result.issuer_ordered" + - "['organizationalUnitName', 'ACME Department'] in result.issuer_ordered" + - result.subject.organizationalUnitName == 'ACME Department' + - "['organizationalUnitName', 'Crypto Department'] in result.subject_ordered" + - "['organizationalUnitName', 'ACME Department'] in result.subject_ordered" + - result.public_key_type == 'RSA' + - result.public_key_data.size == (default_rsa_key_size_certifiates | int) + - "result.subject_alt_name == [ + 'DNS:www.ansible.com', + 'DNS:' ~ ('öç' if cryptography_version.stdout is version('2.1', '<') else 'xn--7ca3a') ~ '.com', + 'DNS:' ~ ('www.öç' if cryptography_version.stdout is version('2.1', '<') else 'xn--74h') ~ '.com', + 'IP:1.2.3.4', + 'IP:::1', + 'email:test@example.org', + 'URI:https://example.org/test/index.html' + ]" + - "result_idna.subject_alt_name == [ + 'DNS:www.ansible.com', + 'DNS:xn--7ca3a.com', + 'DNS:' ~ ('www.xn--7ca3a' if cryptography_version.stdout is version('2.1', '<') else 'xn--74h') ~ '.com', + 'IP:1.2.3.4', + 'IP:::1', + 'email:test@example.org', + 'URI:https://example.org/test/index.html' + ]" + - "result_unicode.subject_alt_name == [ + 'DNS:www.ansible.com', + 'DNS:öç.com', + 'DNS:' ~ ('www.öç' if cryptography_version.stdout is version('2.1', '<') else '☺') ~ '.com', + 'IP:1.2.3.4', + 'IP:::1', + 'email:test@example.org', + 'URI:https://example.org/test/index.html' + ]" + # TLS Feature + - result.extensions_by_oid['1.3.6.1.5.5.7.1.24'].critical == false + - result.extensions_by_oid['1.3.6.1.5.5.7.1.24'].value == 'MAMCAQU=' + # Key Usage + - result.extensions_by_oid['2.5.29.15'].critical == true + - result.extensions_by_oid['2.5.29.15'].value in ['AwMA/4A=', 'AwMH/4A='] + # Subject Alternative Names + - result.extensions_by_oid['2.5.29.17'].critical == false + - > + result.extensions_by_oid['2.5.29.17'].value == ( + 'MIGCgg93d3cuYW5zaWJsZS5jb22CDXhuLS03Y2EzYS5jb22CEXd3dy54bi0tN2NhM2EuY29thwQBAgMEhxAAAAAAAAAAAAAAAAAAAAABgRB0ZXN0QGV4YW1wbGUub3JnhiNodHRwczovL2V4YW1wbGUub3JnL3Rlc3QvaW5kZXguaHRtbA==' + if cryptography_version.stdout is version('2.1', '<') else + 'MHyCD3d3dy5hbnNpYmxlLmNvbYINeG4tLTdjYTNhLmNvbYILeG4tLTc0aC5jb22HBAECAwSHEAAAAAAAAAAAAAAAAAAAAAGBEHRlc3RAZXhhbXBsZS5vcmeGI2h0dHBzOi8vZXhhbXBsZS5vcmcvdGVzdC9pbmRleC5odG1s' + ) + # Basic Constraints + - result.extensions_by_oid['2.5.29.19'].critical == true + - result.extensions_by_oid['2.5.29.19'].value == 'MAYBAf8CARc=' + # Extended Key Usage + - result.extensions_by_oid['2.5.29.37'].critical == false + - result.extensions_by_oid['2.5.29.37'].value == 'MHQGCCsGAQUFBwMBBggrBgEFBQcDAQYIKwYBBQUHAwIGCCsGAQUFBwMDBggrBgEFBQcDBAYIKwYBBQUHAwgGCCsGAQUFBwMJBgRVHSUABggrBgEFBQcBAwYIKwYBBQUHAwoGCCsGAQUFBwMHBggrBgEFBQcBAg==' + +- name: Check SubjectKeyIdentifier and AuthorityKeyIdentifier + assert: + that: + - result.subject_key_identifier == "00:11:22:33" + - result.authority_key_identifier == "44:55:66:77" + - result.authority_cert_issuer == expected_authority_cert_issuer + - result.authority_cert_serial_number == 12345 + # Subject Key Identifier + - result.extensions_by_oid['2.5.29.14'].critical == false + # Authority Key Identifier + - result.extensions_by_oid['2.5.29.35'].critical == false + vars: + expected_authority_cert_issuer: + - "DNS:ca.example.org" + - "IP:1.2.3.4" + when: cryptography_version.stdout is version('1.3', '>=') + +- name: Get certificate info + set_fact: + result: >- + {{ lookup('file', remote_tmp_dir ~ '/cert_2.pem') | community.crypto.x509_certificate_info }} + +- name: Get certificate info + set_fact: + result: >- + {{ lookup('file', remote_tmp_dir ~ '/cert_3.pem') | community.crypto.x509_certificate_info }} + +- name: Check AuthorityKeyIdentifier + assert: + that: + - result.authority_key_identifier is none + - result.authority_cert_issuer == expected_authority_cert_issuer + - result.authority_cert_serial_number == 12345 + vars: + expected_authority_cert_issuer: + - "DNS:ca.example.org" + - "IP:1.2.3.4" + when: cryptography_version.stdout is version('1.3', '>=') + +- name: Get certificate info + set_fact: + result: >- + {{ lookup('file', remote_tmp_dir ~ '/cert_4.pem') | community.crypto.x509_certificate_info }} + +- name: Check AuthorityKeyIdentifier + assert: + that: + - result.authority_key_identifier == "44:55:66:77" + - result.authority_cert_issuer is none + - result.authority_cert_serial_number is none + when: cryptography_version.stdout is version('1.3', '>=') + +- name: Get certificate info for packaged cert 1 + set_fact: + result: >- + {{ lookup('file', role_path ~ '/files/cert1.pem') | community.crypto.x509_certificate_info }} +- name: Check extensions + assert: + that: + - "'ocsp_uri' in result" + - "result.ocsp_uri == 'http://ocsp.int-x3.letsencrypt.org'" + - "'issuer_uri' in result" + - "result.issuer_uri == 'http://cert.int-x3.letsencrypt.org/'" + - result.extensions_by_oid | length == 9 + # Precert Signed Certificate Timestamps + - result.extensions_by_oid['1.3.6.1.4.1.11129.2.4.2'].critical == false + - result.extensions_by_oid['1.3.6.1.4.1.11129.2.4.2'].value == 'BIHyAPAAdgDBFkrgp3LS1DktyArBB3DU8MSb3pkaSEDB+gdRZPYzYAAAAWTdAoU6AAAEAwBHMEUCIG5WpfKF536KKa9fnVlYbwcfrKh09Hi2MSRwU2kad49UAiEA4RUKjJOgw11IHFNdit+sy1RcCU3QCSOEQYrJ1/oPltAAdgApPFGWVMg5ZbqqUPxYB9S3b79Yeily3KTDDPTlRUf0eAAAAWTdAoc+AAAEAwBHMEUCIQCJjo75K4rVDSiWQe3XFLY6MiG3zcHQrKb0YhM17r1UKAIgGa8qMoN03DLp+Rm9nRJ9XLbTJz1vbuu9PyXUY741P8E=' + # Authority Information Access + - result.extensions_by_oid['1.3.6.1.5.5.7.1.1'].critical == false + - result.extensions_by_oid['1.3.6.1.5.5.7.1.1'].value == 'MGEwLgYIKwYBBQUHMAGGImh0dHA6Ly9vY3NwLmludC14My5sZXRzZW5jcnlwdC5vcmcwLwYIKwYBBQUHMAKGI2h0dHA6Ly9jZXJ0LmludC14My5sZXRzZW5jcnlwdC5vcmcv' + # Subject Key Identifier + - result.extensions_by_oid['2.5.29.14'].critical == false + - result.extensions_by_oid['2.5.29.14'].value == 'BBRtcOI/yg62Ehbu5vQzxMUUdBOYMw==' + # Key Usage (The certificate has 'AwIFoA==', while de-serializing and re-serializing yields 'AwIAoA=='!) + - result.extensions_by_oid['2.5.29.15'].critical == true + - result.extensions_by_oid['2.5.29.15'].value in ['AwIFoA==', 'AwIAoA=='] + # Subject Alternative Names + - result.extensions_by_oid['2.5.29.17'].critical == false + - result.extensions_by_oid['2.5.29.17'].value == 'MIIB5IIbY2VydC5pbnQteDEubGV0c2VuY3J5cHQub3JnghtjZXJ0LmludC14Mi5sZXRzZW5jcnlwdC5vcmeCG2NlcnQuaW50LXgzLmxldHNlbmNyeXB0Lm9yZ4IbY2VydC5pbnQteDQubGV0c2VuY3J5cHQub3JnghxjZXJ0LnJvb3QteDEubGV0c2VuY3J5cHQub3Jngh9jZXJ0LnN0YWdpbmcteDEubGV0c2VuY3J5cHQub3Jngh9jZXJ0LnN0Zy1pbnQteDEubGV0c2VuY3J5cHQub3JngiBjZXJ0LnN0Zy1yb290LXgxLmxldHNlbmNyeXB0Lm9yZ4ISY3AubGV0c2VuY3J5cHQub3JnghpjcC5yb290LXgxLmxldHNlbmNyeXB0Lm9yZ4ITY3BzLmxldHNlbmNyeXB0Lm9yZ4IbY3BzLnJvb3QteDEubGV0c2VuY3J5cHQub3Jnghtjcmwucm9vdC14MS5sZXRzZW5jcnlwdC5vcmeCD2xldHNlbmNyeXB0Lm9yZ4IWb3JpZ2luLmxldHNlbmNyeXB0Lm9yZ4IXb3JpZ2luMi5sZXRzZW5jcnlwdC5vcmeCFnN0YXR1cy5sZXRzZW5jcnlwdC5vcmeCE3d3dy5sZXRzZW5jcnlwdC5vcmc=' + # Basic Constraints + - result.extensions_by_oid['2.5.29.19'].critical == true + - result.extensions_by_oid['2.5.29.19'].value == 'MAA=' + # Certificate Policies + - result.extensions_by_oid['2.5.29.32'].critical == false + - result.extensions_by_oid['2.5.29.32'].value == 'MIHzMAgGBmeBDAECATCB5gYLKwYBBAGC3xMBAQEwgdYwJgYIKwYBBQUHAgEWGmh0dHA6Ly9jcHMubGV0c2VuY3J5cHQub3JnMIGrBggrBgEFBQcCAjCBngyBm1RoaXMgQ2VydGlmaWNhdGUgbWF5IG9ubHkgYmUgcmVsaWVkIHVwb24gYnkgUmVseWluZyBQYXJ0aWVzIGFuZCBvbmx5IGluIGFjY29yZGFuY2Ugd2l0aCB0aGUgQ2VydGlmaWNhdGUgUG9saWN5IGZvdW5kIGF0IGh0dHBzOi8vbGV0c2VuY3J5cHQub3JnL3JlcG9zaXRvcnkv' + # Authority Key Identifier + - result.extensions_by_oid['2.5.29.35'].critical == false + - result.extensions_by_oid['2.5.29.35'].value == 'MBaAFKhKamMEfd265tE5t6ZFZe/zqOyh' + # Extended Key Usage + - result.extensions_by_oid['2.5.29.37'].critical == false + - result.extensions_by_oid['2.5.29.37'].value == 'MBQGCCsGAQUFBwMBBggrBgEFBQcDAg==' +- name: Check fingerprints + assert: + that: + - (result.fingerprints.sha256 == '57:7c:f1:f5:dd:cc:6e:e9:f3:17:28:73:17:e4:25:c7:69:74:3e:f7:9a:df:58:20:7a:5a:e4:aa:de:bf:24:5b' if result.fingerprints.sha256 is defined else true) + - (result.fingerprints.sha1 == 'b7:79:64:f4:2b:e0:ae:45:74:d4:f3:08:f6:53:cb:39:26:fa:52:6b' if result.fingerprints.sha1 is defined else true) + +- name: Get invalid certificate info + set_fact: + result: >- + {{ [] | community.crypto.x509_certificate_info }} + ignore_errors: true + register: output + +- name: Check that task failed and error message is OK + assert: + that: + - output is failed + - output.msg is search("^The community.crypto.x509_certificate_info input must be a text type, not <(?:class|type) 'list'>$") + +- name: Get invalid certificate info + set_fact: + result: >- + {{ 'foo' | community.crypto.x509_certificate_info }} + ignore_errors: true + register: output + +- name: Check that task failed and error message is OK + assert: + that: + - output is failed + - output.msg is search("^Unable to load (?:certificate|PEM file)(?:\.|$)") + +- name: Get invalid certificate info + set_fact: + result: >- + {{ 'foo' | community.crypto.x509_certificate_info(name_encoding=[]) }} + ignore_errors: true + register: output + +- name: Check that task failed and error message is OK + assert: + that: + - output is failed + - output.msg is search("^The name_encoding option must be of a text type, not <(?:class|type) 'str'>$") + +- name: Get invalid name_encoding parameter + set_fact: + result: >- + {{ 'foo' | community.crypto.x509_certificate_info(name_encoding='foo') }} + ignore_errors: true + register: output + +- name: Check that task failed and error message is OK + assert: + that: + - output is failed + - output.msg is search("^The name_encoding option must be one of the values \"ignore\", \"idna\", or \"unicode\", not \"foo\"$") diff --git a/tests/integration/targets/filter_x509_certificate_info/tasks/main.yml b/tests/integration/targets/filter_x509_certificate_info/tasks/main.yml new file mode 100644 index 000000000..7a28644c6 --- /dev/null +++ b/tests/integration/targets/filter_x509_certificate_info/tasks/main.yml @@ -0,0 +1,151 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +#################################################################### +# WARNING: These are designed specifically for Ansible tests # +# and should not be used as examples of how to write Ansible roles # +#################################################################### + +- name: Make sure the Python idna library is installed + pip: + name: idna + state: present + +- name: Generate privatekey + openssl_privatekey: + path: '{{ remote_tmp_dir }}/privatekey.pem' + size: '{{ default_rsa_key_size_certifiates }}' + +- name: Generate privatekey with password + openssl_privatekey: + path: '{{ remote_tmp_dir }}/privatekeypw.pem' + passphrase: hunter2 + cipher: auto + select_crypto_backend: cryptography + size: '{{ default_rsa_key_size_certifiates }}' + +- name: Generate CSR 1 + openssl_csr: + path: '{{ remote_tmp_dir }}/csr_1.csr' + privatekey_path: '{{ remote_tmp_dir }}/privatekey.pem' + subject: + commonName: www.example.com + C: de + L: Somewhere + ST: Zurich + streetAddress: Welcome Street + O: Ansible + organizationalUnitName: + - Crypto Department + - ACME Department + serialNumber: "1234" + SN: Last Name + GN: First Name + title: Chief + pseudonym: test + UID: asdf + emailAddress: test@example.com + postalAddress: 1234 Somewhere + postalCode: "1234" + useCommonNameForSAN: no + key_usage: + - digitalSignature + - keyAgreement + - Non Repudiation + - Key Encipherment + - dataEncipherment + - Certificate Sign + - cRLSign + - Encipher Only + - decipherOnly + key_usage_critical: yes + extended_key_usage: + - serverAuth # the same as "TLS Web Server Authentication" + - TLS Web Server Authentication + - TLS Web Client Authentication + - Code Signing + - E-mail Protection + - timeStamping + - OCSPSigning + - Any Extended Key Usage + - qcStatements + - DVCS + - IPSec User + - biometricInfo + subject_alt_name: + - "DNS:www.ansible.com" + - "DNS:öç.com" + # cryptography < 2.1 cannot handle certain Unicode characters + - "DNS:{{ 'www.öç' if cryptography_version.stdout is version('2.1', '<') else '☺' }}.com" + - "IP:1.2.3.4" + - "IP:::1" + - "email:test@example.org" + - "URI:https://example.org/test/index.html" + basic_constraints: + - "CA:TRUE" + - "pathlen:23" + basic_constraints_critical: yes + ocsp_must_staple: yes + subject_key_identifier: '{{ "00:11:22:33" if cryptography_version.stdout is version("1.3", ">=") else omit }}' + authority_key_identifier: '{{ "44:55:66:77" if cryptography_version.stdout is version("1.3", ">=") else omit }}' + authority_cert_issuer: '{{ value_for_authority_cert_issuer if cryptography_version.stdout is version("1.3", ">=") else omit }}' + authority_cert_serial_number: '{{ 12345 if cryptography_version.stdout is version("1.3", ">=") else omit }}' + vars: + value_for_authority_cert_issuer: + - "DNS:ca.example.org" + - "IP:1.2.3.4" + +- name: Generate CSR 2 + openssl_csr: + path: '{{ remote_tmp_dir }}/csr_2.csr' + privatekey_path: '{{ remote_tmp_dir }}/privatekeypw.pem' + privatekey_passphrase: hunter2 + useCommonNameForSAN: no + basic_constraints: + - "CA:TRUE" + +- name: Generate CSR 3 + openssl_csr: + path: '{{ remote_tmp_dir }}/csr_3.csr' + privatekey_path: '{{ remote_tmp_dir }}/privatekey.pem' + useCommonNameForSAN: no + subject_alt_name: + - "DNS:*.ansible.com" + - "DNS:*.example.org" + - "IP:DEAD:BEEF::1" + basic_constraints: + - "CA:FALSE" + authority_cert_issuer: '{{ value_for_authority_cert_issuer if cryptography_version.stdout is version("1.3", ">=") else omit }}' + authority_cert_serial_number: '{{ 12345 if cryptography_version.stdout is version("1.3", ">=") else omit }}' + vars: + value_for_authority_cert_issuer: + - "DNS:ca.example.org" + - "IP:1.2.3.4" + +- name: Generate CSR 4 + openssl_csr: + path: '{{ remote_tmp_dir }}/csr_4.csr' + privatekey_path: '{{ remote_tmp_dir }}/privatekey.pem' + useCommonNameForSAN: no + authority_key_identifier: '{{ "44:55:66:77" if cryptography_version.stdout is version("1.3", ">=") else omit }}' + +- name: Generate selfsigned certificates + x509_certificate: + path: '{{ remote_tmp_dir }}/cert_{{ item }}.pem' + csr_path: '{{ remote_tmp_dir }}/csr_{{ item }}.csr' + privatekey_path: '{{ remote_tmp_dir }}/privatekey.pem' + provider: selfsigned + selfsigned_digest: sha256 + selfsigned_not_after: "+10d" + selfsigned_not_before: "-3d" + loop: + - 1 + - 2 + - 3 + - 4 + +- name: Running tests + include_tasks: impl.yml + when: cryptography_version.stdout is version('1.6', '>=')