Debian Codegraph @

ansible_collections/community/general/plugins/modules/ipa_otptoken.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2017, Ansible Project
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: ipa_otptoken
10 author: justchris1 (@justchris1)
11 short_description: Manage FreeIPA OTPs
12 version_added: 2.5.0
13 description:
14 - Add, modify, and delete One Time Passwords in IPA.
15 attributes:
16 check_mode:
17 support: full
18 diff_mode:
19 support: none
20 options:
21 uniqueid:
22 description: Unique ID of the token in IPA.
23 required: true
24 aliases: ["name"]
25 type: str
26 newuniqueid:
27 description: If specified, the unique ID specified is changed to this.
28 type: str
29 otptype:
30 description:
31 - Type of OTP.
32 - B(Note:) Cannot be modified after OTP is created.
33 type: str
34 choices: [totp, hotp]
35 secretkey:
36 description:
37 - Token secret (Base64).
38 - If OTP is created and this is not specified, a random secret is generated by IPA.
39 - B(Note:) Cannot be modified after OTP is created.
40 type: str
41 description:
42 description: Description of the token (informational only).
43 type: str
44 owner:
45 description: Assigned user of the token.
46 type: str
47 enabled:
48 description: Mark the token as enabled (default V(true)).
49 default: true
50 type: bool
51 notbefore:
52 description:
53 - First date/time the token can be used.
54 - In the format C(YYYYMMddHHmmss).
55 - For example, V(20180121182022) allows the token to be used starting on 21 January 2018 at 18:20:22.
56 type: str
57 notafter:
58 description:
59 - Last date/time the token can be used.
60 - In the format C(YYYYMMddHHmmss).
61 - For example, V(20200121182022) allows the token to be used until 21 January 2020 at 18:20:22.
62 type: str
63 vendor:
64 description: Token vendor name (informational only).
65 type: str
66 model:
67 description: Token model (informational only).
68 type: str
69 serial:
70 description: Token serial (informational only).
71 type: str
72 state:
73 description: State to ensure.
74 choices: ['present', 'absent']
75 default: 'present'
76 type: str
77 algorithm:
78 description:
79 - Token hash algorithm.
80 - B(Note:) Cannot be modified after OTP is created.
81 choices: ['sha1', 'sha256', 'sha384', 'sha512']
82 type: str
83 digits:
84 description:
85 - Number of digits each token code has.
86 - B(Note:) Cannot be modified after OTP is created.
87 choices: [6, 8]
88 type: int
89 offset:
90 description:
91 - TOTP token / IPA server time difference.
92 - B(Note:) Cannot be modified after OTP is created.
93 type: int
94 interval:
95 description:
96 - Length of TOTP token code validity in seconds.
97 - B(Note:) Cannot be modified after OTP is created.
98 type: int
99 counter:
100 description:
101 - Initial counter for the HOTP token.
102 - B(Note:) Cannot be modified after OTP is created.
103 type: int
104 extends_documentation_fragment:
105 - community.general._ipa.documentation
106 - community.general._ipa.connection_notes
107 - community.general._attributes
108 """
109
110 EXAMPLES = r"""
111 - name: Create a totp for pinky, allowing the IPA server to generate using defaults
112 community.general.ipa_otptoken:
113 uniqueid: Token123
114 otptype: totp
115 owner: pinky
116 ipa_host: ipa.example.com
117 ipa_user: admin
118 ipa_pass: topsecret
119
120 - name: Create a 8 digit hotp for pinky with sha256 with specified validity times
121 community.general.ipa_otptoken:
122 uniqueid: Token123
123 enabled: true
124 otptype: hotp
125 digits: 8
126 secretkey: UMKSIER00zT2T2tWMUlTRmNlekRCbFQvWFBVZUh2dElHWGR6T3VUR3IzK2xjaFk9
127 algorithm: sha256
128 notbefore: 20180121182123
129 notafter: 20220121182123
130 owner: pinky
131 ipa_host: ipa.example.com
132 ipa_user: admin
133 ipa_pass: topsecret
134
135 - name: Update Token123 to indicate a vendor, model, serial number (info only), and description
136 community.general.ipa_otptoken:
137 uniqueid: Token123
138 vendor: Acme
139 model: acme101
140 serial: SerialNumber1
141 description: Acme OTP device
142 ipa_host: ipa.example.com
143 ipa_user: admin
144 ipa_pass: topsecret
145
146 - name: Disable Token123
147 community.general.ipa_otptoken:
148 uniqueid: Token123
149 enabled: false
150 ipa_host: ipa.example.com
151 ipa_user: admin
152 ipa_pass: topsecret
153
154 - name: Rename Token123 to TokenABC and enable it
155 community.general.ipa_otptoken:
156 uniqueid: Token123
157 newuniqueid: TokenABC
158 enabled: true
159 ipa_host: ipa.example.com
160 ipa_user: admin
161 ipa_pass: topsecret
162 """
163
164 RETURN = r"""
165 otptoken:
166 description: OTP Token as returned by IPA API.
167 returned: always
168 type: dict
169 """
170
171 import base64
172 import traceback
173
174 from ansible.module_utils.basic import AnsibleModule, sanitize_keys
175
176 from ansible_collections.community.general.plugins.module_utils._ipa import IPAClient, ipa_argument_spec
177
178
179 class OTPTokenIPAClient(IPAClient):
180 def __init__(self, module, host, port, protocol):
181 super().__init__(module, host, port, protocol)
182
183 def otptoken_find(self, name):
184 return self._post_json(
185 method="otptoken_find",
186 name=None,
187 item={"all": True, "ipatokenuniqueid": name, "timelimit": "0", "sizelimit": "0"},
188 )
189
190 def otptoken_add(self, name, item):
191 return self._post_json(method="otptoken_add", name=name, item=item)
192
193 def otptoken_mod(self, name, item):
194 return self._post_json(method="otptoken_mod", name=name, item=item)
195
196 def otptoken_del(self, name):
197 return self._post_json(method="otptoken_del", name=name)
198
199
200 def base64_to_base32(base64_string):
201 """Converts base64 string to base32 string"""
202 b32_string = base64.b32encode(base64.b64decode(base64_string)).decode("ascii")
203 return b32_string
204
205
206 def base32_to_base64(base32_string):
207 """Converts base32 string to base64 string"""
208 b64_string = base64.b64encode(base64.b32decode(base32_string)).decode("ascii")
209 return b64_string
210
211
212 def get_otptoken_dict(
213 ansible_to_ipa,
214 uniqueid=None,
215 newuniqueid=None,
216 otptype=None,
217 secretkey=None,
218 description=None,
219 owner=None,
220 enabled=None,
221 notbefore=None,
222 notafter=None,
223 vendor=None,
224 model=None,
225 serial=None,
226 algorithm=None,
227 digits=None,
228 offset=None,
229 interval=None,
230 counter=None,
231 ):
232 """Create the dictionary of settings passed in"""
233
234 otptoken = {}
235 if uniqueid is not None:
236 otptoken[ansible_to_ipa["uniqueid"]] = uniqueid
237 if newuniqueid is not None:
238 otptoken[ansible_to_ipa["newuniqueid"]] = newuniqueid
239 if otptype is not None:
240 otptoken[ansible_to_ipa["otptype"]] = otptype.upper()
241 if secretkey is not None:
242 # For some unknown reason, while IPA returns the secret in base64,
243 # it wants the secret passed in as base32. This makes it more difficult
244 # for comparison (does 'current' equal to 'new'). Moreover, this may
245 # cause some subtle issue in a playbook as the output is encoded
246 # in a different way than if it was passed in as a parameter. For
247 # these reasons, have the module standardize on base64 input (as parameter)
248 # and output (from IPA).
249 otptoken[ansible_to_ipa["secretkey"]] = base64_to_base32(secretkey)
250 if description is not None:
251 otptoken[ansible_to_ipa["description"]] = description
252 if owner is not None:
253 otptoken[ansible_to_ipa["owner"]] = owner
254 if enabled is not None:
255 otptoken[ansible_to_ipa["enabled"]] = not enabled
256 if notbefore is not None:
257 otptoken[ansible_to_ipa["notbefore"]] = f"{notbefore}Z"
258 if notafter is not None:
259 otptoken[ansible_to_ipa["notafter"]] = f"{notafter}Z"
260 if vendor is not None:
261 otptoken[ansible_to_ipa["vendor"]] = vendor
262 if model is not None:
263 otptoken[ansible_to_ipa["model"]] = model
264 if serial is not None:
265 otptoken[ansible_to_ipa["serial"]] = serial
266 if algorithm is not None:
267 otptoken[ansible_to_ipa["algorithm"]] = algorithm
268 if digits is not None:
269 otptoken[ansible_to_ipa["digits"]] = str(digits)
270 if offset is not None:
271 otptoken[ansible_to_ipa["offset"]] = str(offset)
272 if interval is not None:
273 otptoken[ansible_to_ipa["interval"]] = str(interval)
274 if counter is not None:
275 otptoken[ansible_to_ipa["counter"]] = str(counter)
276
277 return otptoken
278
279
280 def transform_output(ipa_otptoken, ansible_to_ipa, ipa_to_ansible):
281 """Transform the output received by IPA to a format more friendly
282 before it is returned to the user. IPA returns even simple
283 strings as a list of strings. It also returns bools and
284 int as string. This function cleans that up before return.
285 """
286 updated_otptoken = ipa_otptoken
287
288 # Used to hold values that will be sanitized from output as no_log.
289 # For the case where secretkey is not specified at the module, but
290 # is passed back from IPA.
291 sanitize_strings = set()
292
293 # Rename the IPA parameters to the more friendly ansible module names for them
294 for ipa_parameter in ipa_to_ansible:
295 if ipa_parameter in ipa_otptoken:
296 updated_otptoken[ipa_to_ansible[ipa_parameter]] = ipa_otptoken[ipa_parameter]
297 updated_otptoken.pop(ipa_parameter)
298
299 # Change the type from IPA's list of string to the appropriate return value type
300 # based on field. By default, assume they should be strings.
301 for ansible_parameter in ansible_to_ipa:
302 if ansible_parameter in updated_otptoken:
303 if isinstance(updated_otptoken[ansible_parameter], list) and len(updated_otptoken[ansible_parameter]) == 1:
304 if ansible_parameter in ["digits", "offset", "interval", "counter"]:
305 updated_otptoken[ansible_parameter] = int(updated_otptoken[ansible_parameter][0])
306 elif ansible_parameter == "enabled":
307 updated_otptoken[ansible_parameter] = bool(updated_otptoken[ansible_parameter][0])
308 else:
309 updated_otptoken[ansible_parameter] = updated_otptoken[ansible_parameter][0]
310
311 if "secretkey" in updated_otptoken:
312 if isinstance(updated_otptoken["secretkey"], dict):
313 if "__base64__" in updated_otptoken["secretkey"]:
314 sanitize_strings.add(updated_otptoken["secretkey"]["__base64__"])
315 b64key = updated_otptoken["secretkey"]["__base64__"]
316 updated_otptoken.pop("secretkey")
317 updated_otptoken["secretkey"] = b64key
318 sanitize_strings.add(b64key)
319 elif "__base32__" in updated_otptoken["secretkey"]:
320 sanitize_strings.add(updated_otptoken["secretkey"]["__base32__"])
321 b32key = updated_otptoken["secretkey"]["__base32__"]
322 b64key = base32_to_base64(b32key)
323 updated_otptoken.pop("secretkey")
324 updated_otptoken["secretkey"] = b64key
325 sanitize_strings.add(b32key)
326 sanitize_strings.add(b64key)
327
328 return updated_otptoken, sanitize_strings
329
330
331 def validate_modifications(ansible_to_ipa, module, ipa_otptoken, module_otptoken, unmodifiable_after_creation):
332 """Checks to see if the requested modifications are valid. Some elements
333 cannot be modified after initial creation. However, we still want to
334 validate arguments that are specified, but are not different than what
335 is currently set on the server.
336 """
337
338 modifications_valid = True
339
340 for parameter in unmodifiable_after_creation:
341 if ansible_to_ipa[parameter] in module_otptoken and ansible_to_ipa[parameter] in ipa_otptoken:
342 mod_value = module_otptoken[ansible_to_ipa[parameter]]
343
344 # For someone unknown reason, the returns from IPA put almost all
345 # values in a list, even though passing them in a list (even of
346 # length 1) will be rejected. The module values for all elements
347 # other than type (totp or hotp) have this happen.
348 if parameter == "otptype":
349 ipa_value = ipa_otptoken[ansible_to_ipa[parameter]]
350 else:
351 if len(ipa_otptoken[ansible_to_ipa[parameter]]) != 1:
352 module.fail_json(
353 msg="Invariant fail: Return value from IPA is not a list of length 1. Please open a bug report for the module."
354 )
355 if parameter == "secretkey":
356 # We stored the secret key in base32 since we had assumed that would need to
357 # be the format if we were contacting IPA to create it. However, we are
358 # now comparing it against what is already set in the IPA server, so convert
359 # back to base64 for comparison.
360 mod_value = base32_to_base64(mod_value)
361
362 # For the secret key, it is even more specific in that the key is returned
363 # in a dict, in the list, as the __base64__ entry for the IPA response.
364 ipa_value = ipa_otptoken[ansible_to_ipa[parameter]][0]["__base64__"]
365 if "__base64__" in ipa_otptoken[ansible_to_ipa[parameter]][0]:
366 ipa_value = ipa_otptoken[ansible_to_ipa[parameter]][0]["__base64__"]
367 elif "__base32__" in ipa_otptoken[ansible_to_ipa[parameter]][0]:
368 b32key = ipa_otptoken[ansible_to_ipa[parameter]][0]["__base32__"]
369 b64key = base32_to_base64(b32key)
370 ipa_value = b64key
371 else:
372 ipa_value = None
373 else:
374 ipa_value = ipa_otptoken[ansible_to_ipa[parameter]][0]
375
376 if mod_value != ipa_value:
377 modifications_valid = False
378 fail_message = (
379 f"Parameter '{parameter}' cannot be changed once "
380 + f"the OTP is created and the requested value specified here ({mod_value}) "
381 + f"differs from what is set in the IPA server ({ipa_value})"
382 )
383 module.fail_json(msg=fail_message)
384
385 return modifications_valid
386
387
388 def ensure(module, client):
389 # dict to map from ansible parameter names to attribute names
390 # used by IPA (which are not so friendly).
391 ansible_to_ipa = {
392 "uniqueid": "ipatokenuniqueid",
393 "newuniqueid": "rename",
394 "otptype": "type",
395 "secretkey": "ipatokenotpkey",
396 "description": "description",
397 "owner": "ipatokenowner",
398 "enabled": "ipatokendisabled",
399 "notbefore": "ipatokennotbefore",
400 "notafter": "ipatokennotafter",
401 "vendor": "ipatokenvendor",
402 "model": "ipatokenmodel",
403 "serial": "ipatokenserial",
404 "algorithm": "ipatokenotpalgorithm",
405 "digits": "ipatokenotpdigits",
406 "offset": "ipatokentotpclockoffset",
407 "interval": "ipatokentotptimestep",
408 "counter": "ipatokenhotpcounter",
409 }
410
411 # Create inverse dictionary for mapping return values
412 ipa_to_ansible = {v: k for k, v in ansible_to_ipa.items()}
413
414 unmodifiable_after_creation = ["otptype", "secretkey", "algorithm", "digits", "offset", "interval", "counter"]
415 state = module.params["state"]
416 uniqueid = module.params["uniqueid"]
417
418 module_otptoken = get_otptoken_dict(
419 ansible_to_ipa=ansible_to_ipa,
420 uniqueid=module.params.get("uniqueid"),
421 newuniqueid=module.params.get("newuniqueid"),
422 otptype=module.params.get("otptype"),
423 secretkey=module.params.get("secretkey"),
424 description=module.params.get("description"),
425 owner=module.params.get("owner"),
426 enabled=module.params.get("enabled"),
427 notbefore=module.params.get("notbefore"),
428 notafter=module.params.get("notafter"),
429 vendor=module.params.get("vendor"),
430 model=module.params.get("model"),
431 serial=module.params.get("serial"),
432 algorithm=module.params.get("algorithm"),
433 digits=module.params.get("digits"),
434 offset=module.params.get("offset"),
435 interval=module.params.get("interval"),
436 counter=module.params.get("counter"),
437 )
438
439 ipa_otptoken = client.otptoken_find(name=uniqueid)
440
441 if ansible_to_ipa["newuniqueid"] in module_otptoken:
442 # Check to see if the new unique id is already taken in use
443 ipa_otptoken_new = client.otptoken_find(name=module_otptoken[ansible_to_ipa["newuniqueid"]])
444 if ipa_otptoken_new:
445 module.fail_json(
446 msg=(
447 f"Requested rename through newuniqueid to {module_otptoken[ansible_to_ipa['newuniqueid']]} "
448 "failed because the new unique id is already in use"
449 )
450 )
451
452 changed = False
453 if state == "present":
454 if not ipa_otptoken:
455 changed = True
456 if not module.check_mode:
457 # It would not make sense to have a rename after creation, so if the user
458 # specified a newuniqueid, just replace the uniqueid with the updated one
459 # before creation
460 if ansible_to_ipa["newuniqueid"] in module_otptoken:
461 module_otptoken[ansible_to_ipa["uniqueid"]] = module_otptoken[ansible_to_ipa["newuniqueid"]]
462 uniqueid = module_otptoken[ansible_to_ipa["newuniqueid"]]
463 module_otptoken.pop(ansible_to_ipa["newuniqueid"])
464
465 # IPA wants the unique id in the first position and not as a key/value pair.
466 # Get rid of it from the otptoken dict and just specify it in the name field
467 # for otptoken_add.
468 if ansible_to_ipa["uniqueid"] in module_otptoken:
469 module_otptoken.pop(ansible_to_ipa["uniqueid"])
470
471 module_otptoken["all"] = True
472 ipa_otptoken = client.otptoken_add(name=uniqueid, item=module_otptoken)
473 else:
474 if not validate_modifications(
475 ansible_to_ipa, module, ipa_otptoken, module_otptoken, unmodifiable_after_creation
476 ):
477 module.fail_json(msg="Modifications requested in module are not valid")
478
479 # IPA will reject 'modifications' that do not actually modify anything
480 # if any of the unmodifiable elements are specified. Explicitly
481 # get rid of them here. They were not different or else the
482 # we would have failed out in validate_modifications.
483 for x in unmodifiable_after_creation:
484 if ansible_to_ipa[x] in module_otptoken:
485 module_otptoken.pop(ansible_to_ipa[x])
486
487 diff = client.get_diff(ipa_data=ipa_otptoken, module_data=module_otptoken)
488 if len(diff) > 0:
489 changed = True
490 if not module.check_mode:
491 # IPA wants the unique id in the first position and not as a key/value pair.
492 # Get rid of it from the otptoken dict and just specify it in the name field
493 # for otptoken_mod.
494 if ansible_to_ipa["uniqueid"] in module_otptoken:
495 module_otptoken.pop(ansible_to_ipa["uniqueid"])
496
497 module_otptoken["all"] = True
498 ipa_otptoken = client.otptoken_mod(name=uniqueid, item=module_otptoken)
499 else:
500 if ipa_otptoken:
501 changed = True
502 if not module.check_mode:
503 client.otptoken_del(name=uniqueid)
504
505 # Transform the output to use ansible keywords (not the IPA keywords) and
506 # sanitize any key values in the output.
507 ipa_otptoken, sanitize_strings = transform_output(ipa_otptoken, ansible_to_ipa, ipa_to_ansible)
508 module.no_log_values = module.no_log_values.union(sanitize_strings)
509 sanitized_otptoken = sanitize_keys(obj=ipa_otptoken, no_log_strings=module.no_log_values)
510 return changed, sanitized_otptoken
511
512
513 def main():
514 argument_spec = ipa_argument_spec()
515 argument_spec.update(
516 uniqueid=dict(type="str", aliases=["name"], required=True),
517 newuniqueid=dict(type="str"),
518 otptype=dict(type="str", choices=["totp", "hotp"]),
519 secretkey=dict(type="str", no_log=True),
520 description=dict(type="str"),
521 owner=dict(type="str"),
522 enabled=dict(type="bool", default=True),
523 notbefore=dict(type="str"),
524 notafter=dict(type="str"),
525 vendor=dict(type="str"),
526 model=dict(type="str"),
527 serial=dict(type="str"),
528 state=dict(type="str", choices=["present", "absent"], default="present"),
529 algorithm=dict(type="str", choices=["sha1", "sha256", "sha384", "sha512"]),
530 digits=dict(type="int", choices=[6, 8]),
531 offset=dict(type="int"),
532 interval=dict(type="int"),
533 counter=dict(type="int"),
534 )
535
536 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
537
538 client = OTPTokenIPAClient(
539 module=module,
540 host=module.params["ipa_host"],
541 port=module.params["ipa_port"],
542 protocol=module.params["ipa_prot"],
543 )
544
545 try:
546 client.login(username=module.params["ipa_user"], password=module.params["ipa_pass"])
547 changed, otptoken = ensure(module, client)
548 except Exception as e:
549 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
550
551 module.exit_json(changed=changed, otptoken=otptoken)
552
553
554 if __name__ == "__main__":
555 main()