Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_crypto/cryptography_crl.py

raw
1 # Copyright (c) 2019, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import typing as t
11
12 from ansible_collections.community.crypto.plugins.module_utils._version import (
13 LooseVersion as _LooseVersion,
14 )
15
16 try:
17 import cryptography
18 from cryptography import x509
19 except ImportError:
20 # Error handled in the calling module.
21 pass
22
23 from ansible_collections.community.crypto.plugins.module_utils._crypto._obj2txt import (
24 obj2txt,
25 )
26 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
27 HAS_CRYPTOGRAPHY,
28 )
29 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
30 CRYPTOGRAPHY_TIMEZONE,
31 cryptography_decode_name,
32 )
33
34 if t.TYPE_CHECKING:
35 import datetime # pragma: no cover
36
37
38 # TODO: once cryptography has a _utc variant of InvalidityDate.invalidity_date, set this
39 # to True and adjust get_invalidity_date() accordingly.
40 # (https://github.com/pyca/cryptography/issues/10818)
41 CRYPTOGRAPHY_TIMEZONE_INVALIDITY_DATE = False # pylint: disable=invalid-name
42 if HAS_CRYPTOGRAPHY:
43 CRYPTOGRAPHY_TIMEZONE_INVALIDITY_DATE = _LooseVersion(
44 cryptography.__version__
45 ) >= _LooseVersion("43.0.0")
46
47 TIMESTAMP_FORMAT = "%Y%m%d%H%M%SZ"
48
49
50 if HAS_CRYPTOGRAPHY:
51 REVOCATION_REASON_MAP = {
52 "unspecified": x509.ReasonFlags.unspecified,
53 "key_compromise": x509.ReasonFlags.key_compromise,
54 "ca_compromise": x509.ReasonFlags.ca_compromise,
55 "affiliation_changed": x509.ReasonFlags.affiliation_changed,
56 "superseded": x509.ReasonFlags.superseded,
57 "cessation_of_operation": x509.ReasonFlags.cessation_of_operation,
58 "certificate_hold": x509.ReasonFlags.certificate_hold,
59 "privilege_withdrawn": x509.ReasonFlags.privilege_withdrawn,
60 "aa_compromise": x509.ReasonFlags.aa_compromise,
61 "remove_from_crl": x509.ReasonFlags.remove_from_crl,
62 }
63 REVOCATION_REASON_MAP_INVERSE = {}
64 for k, v in REVOCATION_REASON_MAP.items():
65 REVOCATION_REASON_MAP_INVERSE[v] = k
66
67 else:
68 REVOCATION_REASON_MAP = {}
69 REVOCATION_REASON_MAP_INVERSE = {}
70
71
72 def cryptography_decode_revoked_certificate(
73 cert: x509.RevokedCertificate,
74 ) -> dict[str, t.Any]:
75 result = {
76 "serial_number": cert.serial_number,
77 "revocation_date": get_revocation_date(cert),
78 "issuer": None,
79 "issuer_critical": False,
80 "reason": None,
81 "reason_critical": False,
82 "invalidity_date": None,
83 "invalidity_date_critical": False,
84 }
85 try:
86 ext_ci = cert.extensions.get_extension_for_class(x509.CertificateIssuer)
87 result["issuer"] = list(ext_ci.value)
88 result["issuer_critical"] = ext_ci.critical
89 except x509.ExtensionNotFound:
90 pass
91 try:
92 ext_cr = cert.extensions.get_extension_for_class(x509.CRLReason)
93 result["reason"] = ext_cr.value.reason
94 result["reason_critical"] = ext_cr.critical
95 except x509.ExtensionNotFound:
96 pass
97 try:
98 ext_id = cert.extensions.get_extension_for_class(x509.InvalidityDate)
99 result["invalidity_date"] = get_invalidity_date(ext_id.value)
100 result["invalidity_date_critical"] = ext_id.critical
101 except x509.ExtensionNotFound:
102 pass
103 return result
104
105
106 def cryptography_dump_revoked(
107 entry: dict[str, t.Any],
108 *,
109 idn_rewrite: t.Literal["ignore", "idna", "unicode"] = "ignore",
110 ) -> dict[str, t.Any]:
111 return {
112 "serial_number": entry["serial_number"],
113 "revocation_date": entry["revocation_date"].strftime(TIMESTAMP_FORMAT),
114 "issuer": (
115 [
116 cryptography_decode_name(issuer, idn_rewrite=idn_rewrite)
117 for issuer in entry["issuer"]
118 ]
119 if entry["issuer"] is not None
120 else None
121 ),
122 "issuer_critical": entry["issuer_critical"],
123 "reason": (
124 REVOCATION_REASON_MAP_INVERSE.get(entry["reason"])
125 if entry["reason"] is not None
126 else None
127 ),
128 "reason_critical": entry["reason_critical"],
129 "invalidity_date": (
130 entry["invalidity_date"].strftime(TIMESTAMP_FORMAT)
131 if entry["invalidity_date"] is not None
132 else None
133 ),
134 "invalidity_date_critical": entry["invalidity_date_critical"],
135 }
136
137
138 def cryptography_get_signature_algorithm_oid_from_crl(
139 crl: x509.CertificateRevocationList,
140 ) -> x509.oid.ObjectIdentifier:
141 try:
142 return crl.signature_algorithm_oid
143 except AttributeError:
144 # Older cryptography versions do not have signature_algorithm_oid yet
145 dotted = obj2txt(
146 crl._backend._lib, # type: ignore[attr-defined] # pylint: disable=protected-access
147 crl._backend._ffi, # type: ignore[attr-defined] # pylint: disable=protected-access
148 crl._x509_crl.sig_alg.algorithm, # type: ignore[attr-defined] # pylint: disable=protected-access
149 )
150 return x509.oid.ObjectIdentifier(dotted)
151
152
153 def get_next_update(obj: x509.CertificateRevocationList) -> datetime.datetime | None:
154 if CRYPTOGRAPHY_TIMEZONE:
155 return obj.next_update_utc
156 return obj.next_update
157
158
159 def get_last_update(obj: x509.CertificateRevocationList) -> datetime.datetime:
160 if CRYPTOGRAPHY_TIMEZONE:
161 return obj.last_update_utc
162 return obj.last_update
163
164
165 def get_revocation_date(obj: x509.RevokedCertificate) -> datetime.datetime:
166 if CRYPTOGRAPHY_TIMEZONE:
167 return obj.revocation_date_utc
168 return obj.revocation_date
169
170
171 def get_invalidity_date(obj: x509.InvalidityDate) -> datetime.datetime:
172 if CRYPTOGRAPHY_TIMEZONE_INVALIDITY_DATE:
173 return obj.invalidity_date_utc
174 return obj.invalidity_date
175
176
177 def set_next_update(
178 builder: x509.CertificateRevocationListBuilder, *, value: datetime.datetime
179 ) -> x509.CertificateRevocationListBuilder:
180 return builder.next_update(value)
181
182
183 def set_last_update(
184 builder: x509.CertificateRevocationListBuilder, *, value: datetime.datetime
185 ) -> x509.CertificateRevocationListBuilder:
186 return builder.last_update(value)
187
188
189 def set_revocation_date(
190 builder: x509.RevokedCertificateBuilder, *, value: datetime.datetime
191 ) -> x509.RevokedCertificateBuilder:
192 return builder.revocation_date(value)
193
194
195 __all__ = (
196 "REVOCATION_REASON_MAP",
197 "REVOCATION_REASON_MAP_INVERSE",
198 "cryptography_decode_revoked_certificate",
199 "cryptography_dump_revoked",
200 "cryptography_get_signature_algorithm_oid_from_crl",
201 "get_invalidity_date",
202 "get_last_update",
203 "get_next_update",
204 "get_revocation_date",
205 "set_last_update",
206 "set_next_update",
207 "set_revocation_date",
208 )