Debian Codegraph @

ansible_collections/community/general/plugins/modules/ipa_user.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_user
10 author: Thomas Krahn (@Nosmoht)
11 short_description: Manage FreeIPA users
12 description:
13 - Add, modify and delete user within IPA server.
14 attributes:
15 check_mode:
16 support: full
17 diff_mode:
18 support: none
19 options:
20 displayname:
21 description: Display name.
22 type: str
23 update_password:
24 description:
25 - Set password for a user.
26 type: str
27 default: 'always'
28 choices: [always, on_create]
29 givenname:
30 description:
31 - First name.
32 - If user does not exist and O(state=present), the usage of O(givenname) is required.
33 type: str
34 krbpasswordexpiration:
35 description:
36 - Date at which the user password expires.
37 - In the format YYYYMMddHHmmss.
38 - For example V(20180121182022) expires on 21 January 2018 at 18:20:22.
39 type: str
40 loginshell:
41 description: Login shell.
42 type: str
43 mail:
44 description:
45 - List of mail addresses assigned to the user.
46 - If an empty list is passed all assigned email addresses are deleted.
47 - If None is passed email addresses are not checked nor changed.
48 type: list
49 elements: str
50 password:
51 description:
52 - Password for a user.
53 - It is not set for an existing user unless O(update_password=always), which is the default.
54 type: str
55 sn:
56 description:
57 - Surname.
58 - If user does not exist and O(state=present), the usage of O(sn) is required.
59 type: str
60 sshpubkey:
61 description:
62 - List of public SSH key.
63 - If an empty list is passed all assigned public keys are deleted.
64 - If None is passed SSH public keys are not checked nor changed.
65 type: list
66 elements: str
67 state:
68 description: State to ensure.
69 default: "present"
70 choices: ["absent", "disabled", "enabled", "present"]
71 type: str
72 telephonenumber:
73 description:
74 - List of telephone numbers assigned to the user.
75 - If an empty list is passed all assigned telephone numbers are deleted.
76 - If None is passed telephone numbers are not checked nor changed.
77 type: list
78 elements: str
79 title:
80 description: Title.
81 type: str
82 uid:
83 description: Uid of the user.
84 required: true
85 aliases: ["name"]
86 type: str
87 uidnumber:
88 description:
89 - Account Settings UID/Posix User ID number.
90 type: str
91 gidnumber:
92 description:
93 - Posix Group ID.
94 type: str
95 homedirectory:
96 description:
97 - Default home directory of the user.
98 type: str
99 version_added: '0.2.0'
100 userauthtype:
101 description:
102 - The authentication type to use for the user.
103 - To remove all authentication types from the user, use an empty list V([]).
104 - The choice V(idp) and V(passkey) has been added in community.general 8.1.0.
105 choices: ["password", "radius", "otp", "pkinit", "hardened", "idp", "passkey"]
106 type: list
107 elements: str
108 version_added: '1.2.0'
109 extends_documentation_fragment:
110 - community.general._ipa.documentation
111 - community.general._ipa.connection_notes
112 - community.general._attributes
113
114 requirements:
115 - base64
116 - hashlib
117 """
118
119 EXAMPLES = r"""
120 - name: Ensure pinky is present and always reset password
121 community.general.ipa_user:
122 name: pinky
123 state: present
124 krbpasswordexpiration: 20200119235959
125 givenname: Pinky
126 sn: Acme
127 mail:
128 - [email protected]
129 telephonenumber:
130 - '+555123456'
131 sshpubkey:
132 - ssh-rsa ....
133 - ssh-dsa ....
134 uidnumber: '1001'
135 gidnumber: '100'
136 homedirectory: /home/pinky
137 ipa_host: ipa.example.com
138 ipa_user: admin
139 ipa_pass: topsecret
140
141 - name: Ensure brain is absent
142 community.general.ipa_user:
143 name: brain
144 state: absent
145 ipa_host: ipa.example.com
146 ipa_user: admin
147 ipa_pass: topsecret
148
149 - name: Ensure pinky is present but don't reset password if already exists
150 community.general.ipa_user:
151 name: pinky
152 state: present
153 givenname: Pinky
154 sn: Acme
155 password: zounds
156 ipa_host: ipa.example.com
157 ipa_user: admin
158 ipa_pass: topsecret
159 update_password: on_create
160
161 - name: Ensure pinky is present and using one time password and RADIUS authentication
162 community.general.ipa_user:
163 name: pinky
164 state: present
165 userauthtype:
166 - otp
167 - radius
168 ipa_host: ipa.example.com
169 ipa_user: admin
170 ipa_pass: topsecret
171 """
172
173 RETURN = r"""
174 user:
175 description: User as returned by IPA API.
176 returned: always
177 type: dict
178 """
179
180 import base64
181 import hashlib
182 import traceback
183
184 from ansible.module_utils.basic import AnsibleModule
185
186 from ansible_collections.community.general.plugins.module_utils._ipa import IPAClient, ipa_argument_spec
187
188
189 class UserIPAClient(IPAClient):
190 def __init__(self, module, host, port, protocol):
191 super().__init__(module, host, port, protocol)
192
193 def user_find(self, name):
194 return self._post_json(method="user_find", name=None, item={"all": True, "uid": name})
195
196 def user_add(self, name, item):
197 return self._post_json(method="user_add", name=name, item=item)
198
199 def user_mod(self, name, item):
200 return self._post_json(method="user_mod", name=name, item=item)
201
202 def user_del(self, name):
203 return self._post_json(method="user_del", name=name)
204
205 def user_disable(self, name):
206 return self._post_json(method="user_disable", name=name)
207
208 def user_enable(self, name):
209 return self._post_json(method="user_enable", name=name)
210
211
212 def get_user_dict(
213 displayname=None,
214 givenname=None,
215 krbpasswordexpiration=None,
216 loginshell=None,
217 mail=None,
218 nsaccountlock=False,
219 sn=None,
220 sshpubkey=None,
221 telephonenumber=None,
222 title=None,
223 userpassword=None,
224 gidnumber=None,
225 uidnumber=None,
226 homedirectory=None,
227 userauthtype=None,
228 ):
229 user = {}
230 if displayname is not None:
231 user["displayname"] = displayname
232 if krbpasswordexpiration is not None:
233 user["krbpasswordexpiration"] = f"{krbpasswordexpiration}Z"
234 if givenname is not None:
235 user["givenname"] = givenname
236 if loginshell is not None:
237 user["loginshell"] = loginshell
238 if mail is not None:
239 user["mail"] = mail
240 user["nsaccountlock"] = nsaccountlock
241 if sn is not None:
242 user["sn"] = sn
243 if sshpubkey is not None:
244 user["ipasshpubkey"] = sshpubkey
245 if telephonenumber is not None:
246 user["telephonenumber"] = telephonenumber
247 if title is not None:
248 user["title"] = title
249 if userpassword is not None:
250 user["userpassword"] = userpassword
251 if gidnumber is not None:
252 user["gidnumber"] = gidnumber
253 if uidnumber is not None:
254 user["uidnumber"] = uidnumber
255 if homedirectory is not None:
256 user["homedirectory"] = homedirectory
257 if userauthtype is not None:
258 user["ipauserauthtype"] = userauthtype
259
260 return user
261
262
263 def get_user_diff(client, ipa_user, module_user):
264 """
265 Return the keys of each dict whereas values are different. Unfortunately the IPA
266 API returns everything as a list even if only a single value is possible.
267 Therefore some more complexity is needed.
268 The method will check if the value type of module_user.attr is not a list and
269 create a list with that element if the same attribute in ipa_user is list. In this way I hope that the method
270 must not be changed if the returned API dict is changed.
271 :param ipa_user:
272 :param module_user:
273 :return:
274 """
275 # sshpubkeyfp is the list of ssh key fingerprints. IPA doesn't return the keys itself but instead the fingerprints.
276 # These are used for comparison.
277 sshpubkey = None
278 if "ipasshpubkey" in module_user:
279 hash_algo = "md5"
280 if "sshpubkeyfp" in ipa_user and ipa_user["sshpubkeyfp"][0][:7].upper() == "SHA256:":
281 hash_algo = "sha256"
282 module_user["sshpubkeyfp"] = [
283 get_ssh_key_fingerprint(pubkey, hash_algo) for pubkey in module_user["ipasshpubkey"]
284 ]
285 # Remove the ipasshpubkey element as it is not returned from IPA but save its value to be used later on
286 sshpubkey = module_user["ipasshpubkey"]
287 del module_user["ipasshpubkey"]
288
289 result = client.get_diff(ipa_data=ipa_user, module_data=module_user)
290
291 # If there are public keys, remove the fingerprints and add them back to the dict
292 if sshpubkey is not None:
293 del module_user["sshpubkeyfp"]
294 module_user["ipasshpubkey"] = sshpubkey
295 return result
296
297
298 def get_ssh_key_fingerprint(ssh_key, hash_algo="sha256"):
299 """
300 Return the public key fingerprint of a given public SSH key
301 in format "[fp] [comment] (ssh-rsa)" where fp is of the format:
302 FB:0C:AC:0A:07:94:5B:CE:75:6E:63:32:13:AD:AD:D7
303 for md5 or
304 SHA256:[base64]
305 for sha256
306 Comments are assumed to be all characters past the second
307 whitespace character in the sshpubkey string.
308 :param ssh_key:
309 :param hash_algo:
310 :return:
311 """
312 parts = ssh_key.strip().split(None, 2)
313 if len(parts) == 0:
314 return None
315 key_type = parts[0]
316 key = base64.b64decode(parts[1].encode("ascii"))
317
318 if hash_algo == "md5":
319 fp_plain = hashlib.md5(key).hexdigest()
320 key_fp = ":".join(a + b for a, b in zip(fp_plain[::2], fp_plain[1::2])).upper()
321 elif hash_algo == "sha256":
322 fp_plain = base64.b64encode(hashlib.sha256(key).digest()).decode("ascii").rstrip("=")
323 key_fp = f"SHA256:{fp_plain}"
324 if len(parts) < 3:
325 return f"{key_fp} ({key_type})"
326 else:
327 comment = parts[2]
328 return f"{key_fp} {comment} ({key_type})"
329
330
331 def ensure(module, client):
332 state = module.params["state"]
333 name = module.params["uid"]
334 nsaccountlock = state == "disabled"
335
336 module_user = get_user_dict(
337 displayname=module.params.get("displayname"),
338 krbpasswordexpiration=module.params.get("krbpasswordexpiration"),
339 givenname=module.params.get("givenname"),
340 loginshell=module.params["loginshell"],
341 mail=module.params["mail"],
342 sn=module.params["sn"],
343 sshpubkey=module.params["sshpubkey"],
344 nsaccountlock=nsaccountlock,
345 telephonenumber=module.params["telephonenumber"],
346 title=module.params["title"],
347 userpassword=module.params["password"],
348 gidnumber=module.params.get("gidnumber"),
349 uidnumber=module.params.get("uidnumber"),
350 homedirectory=module.params.get("homedirectory"),
351 userauthtype=module.params.get("userauthtype"),
352 )
353
354 update_password = module.params.get("update_password")
355 ipa_user = client.user_find(name=name)
356
357 changed = False
358 if state in ["present", "enabled", "disabled"]:
359 if not ipa_user:
360 changed = True
361 if not module.check_mode:
362 ipa_user = client.user_add(name=name, item=module_user)
363 else:
364 if update_password == "on_create":
365 module_user.pop("userpassword", None)
366 diff = get_user_diff(client, ipa_user, module_user)
367 if len(diff) > 0:
368 changed = True
369 if not module.check_mode:
370 ipa_user = client.user_mod(name=name, item=module_user)
371 else:
372 if ipa_user:
373 changed = True
374 if not module.check_mode:
375 client.user_del(name)
376
377 return changed, ipa_user
378
379
380 def main():
381 argument_spec = ipa_argument_spec()
382 argument_spec.update(
383 displayname=dict(type="str"),
384 givenname=dict(type="str"),
385 update_password=dict(type="str", default="always", choices=["always", "on_create"], no_log=False),
386 krbpasswordexpiration=dict(type="str", no_log=False),
387 loginshell=dict(type="str"),
388 mail=dict(type="list", elements="str"),
389 sn=dict(type="str"),
390 uid=dict(type="str", required=True, aliases=["name"]),
391 gidnumber=dict(type="str"),
392 uidnumber=dict(type="str"),
393 password=dict(type="str", no_log=True),
394 sshpubkey=dict(type="list", elements="str"),
395 state=dict(type="str", default="present", choices=["present", "absent", "enabled", "disabled"]),
396 telephonenumber=dict(type="list", elements="str"),
397 title=dict(type="str"),
398 homedirectory=dict(type="str"),
399 userauthtype=dict(
400 type="list", elements="str", choices=["password", "radius", "otp", "pkinit", "hardened", "idp", "passkey"]
401 ),
402 )
403
404 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
405
406 client = UserIPAClient(
407 module=module,
408 host=module.params["ipa_host"],
409 port=module.params["ipa_port"],
410 protocol=module.params["ipa_prot"],
411 )
412
413 # If sshpubkey is defined as None than module.params['sshpubkey'] is [None]. IPA itself returns None (not a list).
414 # Therefore a small check here to replace list(None) by None. Otherwise get_user_diff() would return sshpubkey
415 # as different which should be avoided.
416 if module.params["sshpubkey"] is not None:
417 if len(module.params["sshpubkey"]) == 1 and module.params["sshpubkey"][0] == "":
418 module.params["sshpubkey"] = None
419
420 try:
421 client.login(username=module.params["ipa_user"], password=module.params["ipa_pass"])
422 changed, user = ensure(module, client)
423 module.exit_json(changed=changed, user=user)
424 except Exception as e:
425 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
426
427
428 if __name__ == "__main__":
429 main()