Debian Codegraph @

ansible_collections/community/crypto/plugins/modules/acme_certificate_revoke.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2016 Michael Gruener <[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_certificate_revoke
10 author: "Felix Fontein (@felixfontein)"
11 short_description: Revoke certificates with the ACME protocol
12 description:
13 - Allows to revoke certificates issued by a CA supporting the L(ACME protocol,https://tools.ietf.org/html/rfc8555), such
14 as L(Let's Encrypt,https://letsencrypt.org/).
15 notes:
16 - Exactly one of O(account_key_src), O(account_key_content), O(private_key_src), or O(private_key_content) must be specified.
17 - Trying to revoke an already revoked certificate should result in an unchanged status, even if the revocation reason was
18 different than the one specified here. Also, depending on the server, it can happen that some other error is returned
19 if the certificate has already been revoked.
20 seealso:
21 - name: The Let's Encrypt documentation
22 description: Documentation for the Let's Encrypt Certification Authority. Provides useful information for example on rate
23 limits.
24 link: https://letsencrypt.org/docs/
25 - name: Automatic Certificate Management Environment (ACME)
26 description: The specification of the ACME protocol (RFC 8555).
27 link: https://tools.ietf.org/html/rfc8555
28 - module: community.crypto.acme_inspect
29 description: Allows to debug problems.
30 extends_documentation_fragment:
31 - community.crypto._acme.basic
32 - community.crypto._acme.account
33 - community.crypto._attributes
34 - community.crypto._attributes.actiongroup_acme
35 attributes:
36 check_mode:
37 support: none
38 diff_mode:
39 support: none
40 idempotent:
41 support: full
42 options:
43 certificate:
44 description:
45 - Path to the certificate to revoke.
46 type: path
47 required: true
48 account_key_src:
49 description:
50 - Path to a file containing the ACME account RSA or Elliptic Curve key.
51 - RSA keys can be created with C(openssl rsa ...). Elliptic curve keys can be created with C(openssl ecparam -genkey
52 ...). Any other tool creating private keys in PEM format can be used as well.
53 - Mutually exclusive with O(account_key_content).
54 - Required if O(account_key_content) is not used.
55 account_key_content:
56 description:
57 - Content of the ACME account RSA or Elliptic Curve key.
58 - Note that exactly one of O(account_key_src), O(account_key_content), O(private_key_src), or O(private_key_content)
59 must be specified.
60 - 'I(Warning): the content will be written into a temporary file, which will be deleted by Ansible when the module completes.
61 Since this is an important private key — it can be used to change the account key, or to revoke your certificates
62 without knowing their private keys —, this might not be acceptable.'
63 - In case C(cryptography) is used, the content is not written into a temporary file. It can still happen that it is
64 written to disk by Ansible in the process of moving the module with its argument to the node where it is executed.
65 private_key_src:
66 description:
67 - Path to the certificate's private key.
68 - Note that exactly one of O(account_key_src), O(account_key_content), O(private_key_src), or O(private_key_content)
69 must be specified.
70 type: path
71 private_key_content:
72 description:
73 - Content of the certificate's private key.
74 - Note that exactly one of O(account_key_src), O(account_key_content), O(private_key_src), or O(private_key_content)
75 must be specified.
76 - 'I(Warning): the content will be written into a temporary file, which will be deleted by Ansible when the module completes.
77 Since this is an important private key — it can be used to change the account key, or to revoke your certificates
78 without knowing their private keys —, this might not be acceptable.'
79 - In case C(cryptography) is used, the content is not written into a temporary file. It can still happen that it is
80 written to disk by Ansible in the process of moving the module with its argument to the node where it is executed.
81 type: str
82 private_key_passphrase:
83 description:
84 - Passphrase to use to decode the certificate's private key.
85 - B(Note:) this is not supported by the C(openssl) backend, only by the C(cryptography) backend.
86 type: str
87 version_added: 1.6.0
88 revoke_reason:
89 description:
90 - One of the revocation reasonCodes defined in L(Section 5.3.1 of RFC5280,https://tools.ietf.org/html/rfc5280#section-5.3.1).
91 - Possible values are V(0) (unspecified), V(1) (keyCompromise), V(2) (cACompromise), V(3) (affiliationChanged), V(4)
92 (superseded), V(5) (cessationOfOperation), V(6) (certificateHold), V(8) (removeFromCRL), V(9) (privilegeWithdrawn),
93 V(10) (aACompromise).
94 type: int
95 """
96
97 EXAMPLES = r"""
98 ---
99 - name: Revoke certificate with account key
100 community.crypto.acme_certificate_revoke:
101 account_key_src: /etc/pki/cert/private/account.key
102 certificate: /etc/httpd/ssl/sample.com.crt
103
104 - name: Revoke certificate with certificate's private key
105 community.crypto.acme_certificate_revoke:
106 private_key_src: /etc/httpd/ssl/sample.com.key
107 certificate: /etc/httpd/ssl/sample.com.crt
108 """
109
110 RETURN = """#"""
111
112 import typing as t
113
114 from ansible_collections.community.crypto.plugins.module_utils._acme.account import (
115 ACMEAccount,
116 )
117 from ansible_collections.community.crypto.plugins.module_utils._acme.acme import (
118 ACMEClient,
119 create_backend,
120 create_default_argspec,
121 )
122 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
123 ACMEProtocolException,
124 KeyParsingError,
125 ModuleFailException,
126 )
127 from ansible_collections.community.crypto.plugins.module_utils._acme.utils import (
128 nopad_b64,
129 pem_to_der,
130 )
131
132
133 def main() -> t.NoReturn:
134 argument_spec = create_default_argspec(require_account_key=False)
135 argument_spec.update_argspec(
136 private_key_src={"type": "path"},
137 private_key_content={"type": "str", "no_log": True},
138 private_key_passphrase={"type": "str", "no_log": True},
139 certificate={"type": "path", "required": True},
140 revoke_reason={"type": "int"},
141 )
142 argument_spec.update(
143 required_one_of=[
144 (
145 "account_key_src",
146 "account_key_content",
147 "private_key_src",
148 "private_key_content",
149 ),
150 ],
151 mutually_exclusive=[
152 (
153 "account_key_src",
154 "account_key_content",
155 "private_key_src",
156 "private_key_content",
157 ),
158 ],
159 )
160 module = argument_spec.create_ansible_module()
161 backend = create_backend(module, needs_acme_v2=False)
162
163 try:
164 client = ACMEClient(module=module, backend=backend)
165 account = ACMEAccount(client=client)
166 # Load certificate
167 certificate = pem_to_der(pem_filename=module.params.get("certificate"))
168 certificate_b64 = nopad_b64(certificate)
169 # Construct payload
170 payload = {"certificate": certificate_b64}
171 if module.params.get("revoke_reason") is not None:
172 payload["reason"] = module.params.get("revoke_reason")
173 endpoint = client.directory["revokeCert"]
174 # Get hold of private key (if available) and make sure it comes from disk
175 private_key = module.params.get("private_key_src")
176 private_key_content = module.params.get("private_key_content")
177 # Revoke certificate
178 if private_key or private_key_content:
179 passphrase = module.params["private_key_passphrase"]
180 # Step 1: load and parse private key
181 try:
182 private_key_data = client.parse_key(
183 key_file=private_key,
184 key_content=private_key_content,
185 passphrase=passphrase,
186 )
187 except KeyParsingError as e:
188 raise ModuleFailException(
189 f"Error while parsing private key: {e.msg}"
190 ) from e
191 # Step 2: sign revokation request with private key
192 jws_header = {
193 "alg": private_key_data["alg"],
194 "jwk": private_key_data["jwk"],
195 }
196 result, info = client.send_signed_request(
197 endpoint,
198 payload,
199 key_data=private_key_data,
200 jws_header=jws_header,
201 fail_on_error=False,
202 )
203 else:
204 # Step 1: get hold of account URI
205 created, account_data = account.setup_account(allow_creation=False)
206 if created:
207 raise AssertionError("Unwanted account creation") # pragma: no cover
208 if account_data is None:
209 raise ModuleFailException(
210 msg="Account does not exist or is deactivated."
211 )
212 # Step 2: sign revokation request with account key
213 result, info = client.send_signed_request(
214 endpoint, payload, fail_on_error=False
215 )
216 if info["status"] != 200:
217 already_revoked = False
218 # Standardized error from draft 14 on (https://tools.ietf.org/html/rfc8555#section-7.6)
219 if (
220 isinstance(result, dict)
221 and result.get("type") == "urn:ietf:params:acme:error:alreadyRevoked"
222 ):
223 already_revoked = True
224 else:
225 # Hack for Boulder errors
226 if (
227 isinstance(result, dict)
228 and result.get("type") == "urn:ietf:params:acme:error:malformed"
229 and result.get("detail") == "Certificate already revoked"
230 ):
231 # Fallback: boulder returns this in case the certificate was already revoked.
232 already_revoked = True
233 # If we know the certificate was already revoked, we do not fail,
234 # but successfully terminate while indicating no change
235 if already_revoked:
236 module.exit_json(changed=False)
237 raise ACMEProtocolException(
238 module=module,
239 msg="Failed to revoke certificate",
240 info=info,
241 content_json=result,
242 )
243 module.exit_json(changed=True)
244 except ModuleFailException as e:
245 e.do_fail(module=module)
246
247
248 if __name__ == "__main__":
249 main()