Debian Codegraph @

ansible_collections/community/crypto/plugins/modules/acme_account.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_account
10 author: "Felix Fontein (@felixfontein)"
11 short_description: Create, modify or delete ACME accounts
12 description:
13 - Allows to create, modify or delete accounts with a CA supporting the L(ACME protocol,https://tools.ietf.org/html/rfc8555),
14 such as L(Let's Encrypt,https://letsencrypt.org/).
15 - This module only works with the ACME v2 protocol.
16 notes:
17 - The M(community.crypto.acme_certificate) module also allows to do basic account management. When using both modules, it
18 is recommended to disable account management for M(community.crypto.acme_certificate). For that, use the
19 O(community.crypto.acme_certificate#module:modify_account) option of M(community.crypto.acme_certificate).
20 seealso:
21 - name: Automatic Certificate Management Environment (ACME)
22 description: The specification of the ACME protocol (RFC 8555).
23 link: https://tools.ietf.org/html/rfc8555
24 - module: community.crypto.acme_account_info
25 description: Retrieves facts about an ACME account.
26 - module: community.crypto.openssl_privatekey
27 description: Can be used to create a private account key.
28 - module: community.crypto.openssl_privatekey_pipe
29 description: Can be used to create a private account key without writing it to disk.
30 - module: community.crypto.acme_inspect
31 description: Allows to debug problems.
32 extends_documentation_fragment:
33 - community.crypto._acme.basic
34 - community.crypto._acme.account
35 - community.crypto._attributes
36 - community.crypto._attributes.actiongroup_acme
37 attributes:
38 check_mode:
39 support: full
40 diff_mode:
41 support: full
42 idempotent:
43 support: partial
44 details:
45 - If O(state=changed_key) is used, the module is not idempotent.
46 options:
47 state:
48 description:
49 - The state of the account, to be identified by its account key.
50 - If the state is V(absent), the account will either not exist or be deactivated.
51 - If the state is V(changed_key), the account must exist. The account key will be changed; no other information will
52 be touched.
53 type: str
54 required: true
55 choices:
56 - present
57 - absent
58 - changed_key
59 allow_creation:
60 description:
61 - Whether account creation is allowed (when state is V(present)).
62 type: bool
63 default: true
64 contact:
65 description:
66 - A list of contact URLs.
67 - Email addresses must be prefixed with C(mailto:).
68 - See U(https://tools.ietf.org/html/rfc8555#section-7.3) for what is allowed.
69 - Must be specified when state is V(present). Will be ignored if state is V(absent) or V(changed_key).
70 type: list
71 elements: str
72 default: []
73 terms_agreed:
74 description:
75 - Boolean indicating whether you agree to the terms of service document.
76 - ACME servers can require this to be V(true).
77 type: bool
78 default: false
79 new_account_key_src:
80 description:
81 - Path to a file containing the ACME account RSA or Elliptic Curve key to change to.
82 - Same restrictions apply as to O(account_key_src).
83 - Mutually exclusive with O(new_account_key_content).
84 - Required if O(new_account_key_content) is not used and O(state) is V(changed_key).
85 type: path
86 new_account_key_content:
87 description:
88 - Content of the ACME account RSA or Elliptic Curve key to change to.
89 - Same restrictions apply as to O(account_key_content).
90 - Mutually exclusive with O(new_account_key_src).
91 - Required if O(new_account_key_src) is not used and O(state) is V(changed_key).
92 type: str
93 new_account_key_passphrase:
94 description:
95 - Passphrase to use to decode the new account key.
96 - B(Note:) this is not supported by the C(openssl) backend, only by the C(cryptography) backend.
97 type: str
98 version_added: 1.6.0
99 external_account_binding:
100 description:
101 - Allows to provide external account binding data during account creation.
102 - This is used by CAs like Sectigo, HARICA, or ZeroSSL to bind a new ACME account to an existing CA-specific account,
103 to be able to properly identify a customer.
104 - Only used when creating a new account. Can not be specified for ACME v1.
105 type: dict
106 suboptions:
107 kid:
108 description:
109 - The key identifier provided by the CA.
110 type: str
111 required: true
112 alg:
113 description:
114 - The MAC algorithm provided by the CA.
115 - If not specified by the CA, this is probably V(HS256).
116 type: str
117 required: true
118 choices: [HS256, HS384, HS512]
119 key:
120 description:
121 - Base64 URL encoded value of the MAC key provided by the CA.
122 - Padding (V(=) symbols at the end) can be omitted.
123 type: str
124 required: true
125 version_added: 1.1.0
126 """
127
128 EXAMPLES = r"""
129 ---
130 - name: Make sure account exists and has given contacts. We agree to TOS.
131 community.crypto.acme_account:
132 account_key_src: /etc/pki/cert/private/account.key
133 state: present
134 terms_agreed: true
135 contact:
136 - mailto:[email protected]
137 - mailto:[email protected]
138
139 - name: Make sure account has given email address. Do not create account if it does not exist
140 community.crypto.acme_account:
141 account_key_src: /etc/pki/cert/private/account.key
142 state: present
143 allow_creation: false
144 contact:
145 - mailto:[email protected]
146
147 - name: Change account's key to the one stored in the variable new_account_key
148 community.crypto.acme_account:
149 account_key_src: /etc/pki/cert/private/account.key
150 new_account_key_content: '{{ new_account_key }}'
151 state: changed_key
152
153 - name: Delete account (we have to use the new key)
154 community.crypto.acme_account:
155 account_key_content: '{{ new_account_key }}'
156 state: absent
157 """
158
159 RETURN = r"""
160 account_uri:
161 description: ACME account URI, or None if account does not exist.
162 returned: always
163 type: str
164 """
165
166 import base64
167 import typing as t
168
169 from ansible_collections.community.crypto.plugins.module_utils._acme.account import (
170 ACMEAccount,
171 )
172 from ansible_collections.community.crypto.plugins.module_utils._acme.acme import (
173 ACMEClient,
174 create_backend,
175 create_default_argspec,
176 )
177 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
178 KeyParsingError,
179 ModuleFailException,
180 )
181
182
183 def main() -> t.NoReturn:
184 argument_spec = create_default_argspec()
185 argument_spec.update_argspec(
186 terms_agreed={"type": "bool", "default": False},
187 state={
188 "type": "str",
189 "required": True,
190 "choices": ["absent", "present", "changed_key"],
191 },
192 allow_creation={"type": "bool", "default": True},
193 contact={"type": "list", "elements": "str", "default": []},
194 new_account_key_src={"type": "path"},
195 new_account_key_content={"type": "str", "no_log": True},
196 new_account_key_passphrase={"type": "str", "no_log": True},
197 external_account_binding={
198 "type": "dict",
199 "options": {
200 "kid": {"type": "str", "required": True},
201 "alg": {
202 "type": "str",
203 "required": True,
204 "choices": ["HS256", "HS384", "HS512"],
205 },
206 "key": {"type": "str", "required": True, "no_log": True},
207 },
208 },
209 )
210 argument_spec.update(
211 mutually_exclusive=[("new_account_key_src", "new_account_key_content")],
212 required_if=[
213 # Make sure that for state == changed_key, one of
214 # new_account_key_src and new_account_key_content are specified
215 (
216 "state",
217 "changed_key",
218 ["new_account_key_src", "new_account_key_content"],
219 True,
220 ),
221 ],
222 )
223 module = argument_spec.create_ansible_module(supports_check_mode=True)
224 backend = create_backend(module, needs_acme_v2=True)
225
226 if module.params["external_account_binding"]:
227 # Make sure padding is there
228 key: str = module.params["external_account_binding"]["key"]
229 if len(key) % 4 != 0:
230 key = key + ("=" * (4 - (len(key) % 4)))
231 # Make sure key is Base64 encoded
232 try:
233 base64.urlsafe_b64decode(key)
234 except Exception as e:
235 module.fail_json(
236 msg=f"Key for external_account_binding must be Base64 URL encoded ({e})"
237 )
238 module.params["external_account_binding"]["key"] = key
239
240 try:
241 client = ACMEClient(module=module, backend=backend)
242 account = ACMEAccount(client=client)
243 changed = False
244 state: t.Literal["present", "absent", "changed_key"] = module.params["state"]
245 diff_before: dict[str, t.Any] = {}
246 diff_after: dict[str, t.Any] = {}
247 if state == "absent":
248 created, account_data = account.setup_account(allow_creation=False)
249 if account_data:
250 diff_before = dict(account_data)
251 if client.account_key_data:
252 diff_before["public_account_key"] = client.account_key_data["jwk"]
253 if created:
254 raise AssertionError("Unwanted account creation") # pragma: no cover
255 if account_data is not None:
256 # Account is not yet deactivated
257 if not module.check_mode:
258 # Deactivate it
259 deactivate_payload = {"status": "deactivated"}
260 result, _info = client.send_signed_request(
261 t.cast(str, client.account_uri),
262 deactivate_payload,
263 error_msg="Failed to deactivate account",
264 expected_status_codes=[200],
265 )
266 changed = True
267 elif state == "present":
268 allow_creation = module.params.get("allow_creation")
269 contact = [str(v) for v in module.params.get("contact")]
270 terms_agreed = module.params.get("terms_agreed")
271 external_account_binding = module.params.get("external_account_binding")
272 created, account_data = account.setup_account(
273 contact=contact,
274 terms_agreed=terms_agreed,
275 allow_creation=allow_creation,
276 external_account_binding=external_account_binding,
277 )
278 if account_data is None:
279 raise ModuleFailException(
280 msg="Account does not exist or is deactivated."
281 )
282 if created:
283 diff_before = {}
284 else:
285 diff_before = dict(account_data)
286 if client.account_key_data:
287 diff_before["public_account_key"] = client.account_key_data["jwk"]
288 updated = False
289 if not created:
290 updated, account_data = account.update_account(
291 account_data=account_data, contact=contact
292 )
293 changed = created or updated
294 diff_after = dict(account_data)
295 if client.account_key_data:
296 diff_after["public_account_key"] = client.account_key_data["jwk"]
297 elif state == "changed_key":
298 # Parse new account key
299 try:
300 new_key_data = client.parse_key(
301 key_file=module.params.get("new_account_key_src"),
302 key_content=module.params.get("new_account_key_content"),
303 passphrase=module.params.get("new_account_key_passphrase"),
304 )
305 except KeyParsingError as e:
306 raise ModuleFailException(
307 f"Error while parsing new account key: {e.msg}"
308 ) from e
309 # Verify that the account exists and has not been deactivated
310 created, account_data = account.setup_account(allow_creation=False)
311 if created:
312 raise AssertionError("Unwanted account creation") # pragma: no cover
313 if account_data is None:
314 raise ModuleFailException(
315 msg="Account does not exist or is deactivated."
316 )
317 diff_before = dict(account_data)
318 if client.account_key_data:
319 diff_before["public_account_key"] = client.account_key_data["jwk"]
320 # Now we can start the account key rollover
321 if not module.check_mode:
322 # Compose inner signed message
323 # https://tools.ietf.org/html/rfc8555#section-7.3.5
324 url = client.directory["keyChange"]
325 protected = {
326 "alg": new_key_data["alg"],
327 "jwk": new_key_data["jwk"],
328 "url": url,
329 }
330 change_key_payload = {
331 "account": client.account_uri,
332 "newKey": new_key_data["jwk"], # specified in draft 12 and older
333 "oldKey": client.account_jwk, # specified in draft 13 and newer
334 }
335 data = client.sign_request(
336 protected=protected,
337 payload=change_key_payload,
338 key_data=new_key_data,
339 )
340 # Send request and verify result
341 result, _info = client.send_signed_request(
342 url,
343 data,
344 error_msg="Failed to rollover account key",
345 expected_status_codes=[200],
346 )
347 if module._diff: # pylint: disable=protected-access
348 client.account_key_data = new_key_data
349 if client.account_jws_header:
350 client.account_jws_header["alg"] = new_key_data["alg"]
351 diff_after = account.get_account_data() or {}
352 elif module._diff: # pylint: disable=protected-access
353 # Kind of fake diff_after
354 diff_after = dict(diff_before)
355 diff_after["public_account_key"] = new_key_data["jwk"]
356 changed = True
357 result = {
358 "changed": changed,
359 "account_uri": client.account_uri,
360 }
361 if module._diff: # pylint: disable=protected-access
362 result["diff"] = {
363 "before": diff_before,
364 "after": diff_after,
365 }
366 module.exit_json(**result)
367 except ModuleFailException as e:
368 e.do_fail(module=module)
369
370
371 if __name__ == "__main__":
372 main()