| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2012, Stephen Fromm <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: user |
| 11 |
version_added: "0.2" |
| 12 |
short_description: Manage user accounts |
| 13 |
description: |
| 14 |
- Manage user accounts and user attributes. |
| 15 |
- For Windows targets, use the M(ansible.windows.win_user) module instead. |
| 16 |
options: |
| 17 |
name: |
| 18 |
description: |
| 19 |
- Name of the user to create, remove or modify. |
| 20 |
type: str |
| 21 |
required: true |
| 22 |
aliases: [ user ] |
| 23 |
uid: |
| 24 |
description: |
| 25 |
- Optionally sets the I(UID) of the user. |
| 26 |
type: int |
| 27 |
comment: |
| 28 |
description: |
| 29 |
- Optionally sets the description (aka I(GECOS)) of user account. |
| 30 |
- On macOS, this defaults to the O(name) option. |
| 31 |
type: str |
| 32 |
hidden: |
| 33 |
description: |
| 34 |
- macOS only, optionally hide the user from the login window and system preferences. |
| 35 |
- The default will be V(true) if the O(system) option is used. |
| 36 |
type: bool |
| 37 |
version_added: "2.6" |
| 38 |
non_unique: |
| 39 |
description: |
| 40 |
- Optionally when used with the C(-u) option, this option allows to change the user ID to a non-unique value. |
| 41 |
- Not supported on distributions using BusyBox. |
| 42 |
type: bool |
| 43 |
default: no |
| 44 |
version_added: "1.1" |
| 45 |
seuser: |
| 46 |
description: |
| 47 |
- Optionally sets the C(seuser) type C(user_u) on SELinux enabled systems. |
| 48 |
- This parameter is silently ignored on systems where SELinux is not enabled. |
| 49 |
A warning will be emitted in this case. |
| 50 |
type: str |
| 51 |
version_added: "2.1" |
| 52 |
group: |
| 53 |
description: |
| 54 |
- Optionally sets the user's primary group (takes a group name). |
| 55 |
- On macOS, this defaults to V(staff). |
| 56 |
type: str |
| 57 |
groups: |
| 58 |
description: |
| 59 |
- A list of supplementary groups which the user is also a member of. |
| 60 |
- By default, the user is removed from all other groups. Configure O(append) to modify this. |
| 61 |
- When set to an empty string V(''), |
| 62 |
the user is removed from all groups except the primary group. |
| 63 |
- Before Ansible 2.3, the only input format allowed was a comma separated string. |
| 64 |
type: list |
| 65 |
elements: str |
| 66 |
append: |
| 67 |
description: |
| 68 |
- If V(true), add the user to the groups specified in O(groups). |
| 69 |
- If V(false), user will only be added to the groups specified in O(groups), |
| 70 |
removing them from all other groups. |
| 71 |
- From Ansible 2.21, this option is required when O(groups) is specified. |
| 72 |
type: bool |
| 73 |
default: no |
| 74 |
shell: |
| 75 |
description: |
| 76 |
- Optionally set the user's shell. |
| 77 |
- On macOS, before Ansible 2.5, the default shell for non-system users was V(/usr/bin/false). |
| 78 |
Since Ansible 2.5, the default shell for non-system users on macOS is V(/bin/bash). |
| 79 |
- On other operating systems, the default shell is determined by the underlying tool |
| 80 |
invoked by this module. See Notes for a per platform list of invoked tools. |
| 81 |
- From Ansible 2.18, the type is changed to I(path) from I(str). |
| 82 |
type: path |
| 83 |
home: |
| 84 |
description: |
| 85 |
- Optionally set the user's home directory. |
| 86 |
type: path |
| 87 |
skeleton: |
| 88 |
description: |
| 89 |
- Optionally set a home skeleton directory. |
| 90 |
- Requires O(create_home) option! |
| 91 |
type: str |
| 92 |
version_added: "2.0" |
| 93 |
password: |
| 94 |
description: |
| 95 |
- If provided, set the user's password to the provided encrypted hash (Linux) or plain text password (macOS). |
| 96 |
- B(Linux/Unix/POSIX:) Enter the hashed password as the value. |
| 97 |
- See L(FAQ entry,https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#how-do-i-generate-encrypted-passwords-for-the-user-module) |
| 98 |
for details on various ways to generate the hash of a password. |
| 99 |
- The module writes the value directly to C(/etc/shadow) without any validation. Because the module cannot verify the user input, |
| 100 |
providing an invalid value will likely result in authentication failure. |
| 101 |
However, this behaviour can be utilized intentionally to lock a user account. |
| 102 |
- To create an account with a locked/disabled password on Linux systems, set this to V('!') or V('*'). |
| 103 |
- To create an account with a locked/disabled password on OpenBSD, set this to V('*************'). |
| 104 |
- B(OS X/macOS:) Enter the cleartext password as the value. Be sure to take relevant security precautions. |
| 105 |
- On macOS, the password specified in the C(password) option will always be set, regardless of whether the user account already exists or not. |
| 106 |
- When the password is passed as an argument, the M(ansible.builtin.user) module will always return changed to C(true) for macOS systems. |
| 107 |
Since macOS no longer provides access to the hashed passwords directly. |
| 108 |
type: str |
| 109 |
state: |
| 110 |
description: |
| 111 |
- Whether the account should exist or not, taking action if the state is different from what is stated. |
| 112 |
- See this L(FAQ entry,https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#running-on-macos-as-a-target) |
| 113 |
for additional requirements when removing users on macOS systems. |
| 114 |
type: str |
| 115 |
choices: [ absent, present ] |
| 116 |
default: present |
| 117 |
create_home: |
| 118 |
description: |
| 119 |
- Unless set to V(false), a home directory will be made for the user |
| 120 |
when the account is created or if the home directory does not exist. |
| 121 |
- Changed from O(createhome) to O(create_home) in Ansible 2.5. |
| 122 |
type: bool |
| 123 |
default: yes |
| 124 |
aliases: [ createhome ] |
| 125 |
move_home: |
| 126 |
description: |
| 127 |
- "If set to V(true) when used with O(home), attempt to move the user's old home |
| 128 |
directory to the specified directory if it isn't there already and the old home exists." |
| 129 |
- If O(local) is set to V(true), this option will be ignored if the current home directory does not exist. |
| 130 |
type: bool |
| 131 |
default: no |
| 132 |
system: |
| 133 |
description: |
| 134 |
- When creating an account O(state=present), setting this to V(true) makes the user a system account. |
| 135 |
- This setting cannot be changed on existing users. |
| 136 |
type: bool |
| 137 |
default: no |
| 138 |
force: |
| 139 |
description: |
| 140 |
- This only affects O(state=absent), it forces removal of the user and associated directories on supported platforms. |
| 141 |
- The behavior is the same as C(userdel --force), check the man page for C(userdel) on your system for details and support. |
| 142 |
- When used with O(generate_ssh_key=yes) this forces an existing key to be overwritten. |
| 143 |
type: bool |
| 144 |
default: no |
| 145 |
remove: |
| 146 |
description: |
| 147 |
- This only affects O(state=absent), it attempts to remove directories associated with the user. |
| 148 |
- The behavior is the same as C(userdel --remove), check the man page for details and support. |
| 149 |
type: bool |
| 150 |
default: no |
| 151 |
login_class: |
| 152 |
description: |
| 153 |
- Optionally sets the user's login class, a feature of most BSD OSs. |
| 154 |
type: str |
| 155 |
generate_ssh_key: |
| 156 |
description: |
| 157 |
- Whether to generate a SSH key for the user in question. |
| 158 |
- This will B(not) overwrite an existing SSH key unless used with O(force=yes). |
| 159 |
- Requires C(ssh-keygen) from OpenSSH. |
| 160 |
type: bool |
| 161 |
default: no |
| 162 |
version_added: "0.9" |
| 163 |
ssh_key_bits: |
| 164 |
description: |
| 165 |
- Optionally specify number of bits in SSH key to create. |
| 166 |
- The default value depends on C(ssh-keygen). |
| 167 |
type: int |
| 168 |
version_added: "0.9" |
| 169 |
ssh_key_type: |
| 170 |
description: |
| 171 |
- Optionally specify the type of SSH key to generate. |
| 172 |
- Available SSH key types will depend on implementation |
| 173 |
present on target host. |
| 174 |
type: str |
| 175 |
default: rsa |
| 176 |
version_added: "0.9" |
| 177 |
ssh_key_file: |
| 178 |
description: |
| 179 |
- Optionally specify the SSH key filename. |
| 180 |
- If this is a relative filename then it will be relative to the user's home directory. |
| 181 |
- This parameter defaults to V(.ssh/id_rsa). |
| 182 |
type: path |
| 183 |
version_added: "0.9" |
| 184 |
ssh_key_comment: |
| 185 |
description: |
| 186 |
- Optionally define the comment for the SSH key. |
| 187 |
type: str |
| 188 |
default: ansible-generated on $HOSTNAME |
| 189 |
version_added: "0.9" |
| 190 |
ssh_key_passphrase: |
| 191 |
description: |
| 192 |
- Set a passphrase for the SSH key. |
| 193 |
- If no passphrase is provided, the SSH key will default to having no passphrase. |
| 194 |
type: str |
| 195 |
version_added: "0.9" |
| 196 |
update_password: |
| 197 |
description: |
| 198 |
- V(always) will update passwords if they differ. |
| 199 |
- V(on_create) will only set the password for newly created users. |
| 200 |
type: str |
| 201 |
choices: [ always, on_create ] |
| 202 |
default: always |
| 203 |
version_added: "1.3" |
| 204 |
expires: |
| 205 |
description: |
| 206 |
- An expiry time for the user in epoch, it will be ignored on platforms that do not support this. |
| 207 |
- Currently supported on GNU/Linux, FreeBSD, and DragonFlyBSD. |
| 208 |
- Since Ansible 2.6 you can remove the expiry time by specifying a negative value. |
| 209 |
Currently supported on GNU/Linux and FreeBSD. |
| 210 |
type: float |
| 211 |
version_added: "1.9" |
| 212 |
password_lock: |
| 213 |
description: |
| 214 |
- Lock the password (C(usermod -L), C(usermod -U), C(pw lock)). |
| 215 |
- Implementation differs by platform. This option does not always mean the user cannot login using other methods. |
| 216 |
- This option does not disable the user, only lock the password. |
| 217 |
- This must be set to V(false) in order to unlock a currently locked password. The absence of this parameter will not unlock a password. |
| 218 |
- Currently supported on Linux, FreeBSD, DragonFlyBSD, NetBSD, OpenBSD. |
| 219 |
type: bool |
| 220 |
version_added: "2.6" |
| 221 |
local: |
| 222 |
description: |
| 223 |
- Forces the use of "local" command alternatives on platforms that implement it. |
| 224 |
- This is useful in environments that use centralized authentication when you want to manipulate the local users |
| 225 |
(in other words, it uses C(luseradd) instead of C(useradd)). |
| 226 |
- This will check C(/etc/passwd) for an existing account before invoking commands. If the local account database |
| 227 |
exists somewhere other than C(/etc/passwd), this setting will not work properly. |
| 228 |
- This requires that the above commands as well as C(/etc/passwd) must exist on the target host, otherwise it will be a fatal error. |
| 229 |
- Not supported on distributions using BusyBox. |
| 230 |
type: bool |
| 231 |
default: no |
| 232 |
version_added: "2.4" |
| 233 |
profile: |
| 234 |
description: |
| 235 |
- Sets the profile of the user. |
| 236 |
- Can set multiple profiles using comma separation. |
| 237 |
- To delete all the profiles, use O(profile=''). |
| 238 |
- Currently supported on Illumos/Solaris. Does nothing when used with other platforms. |
| 239 |
type: str |
| 240 |
version_added: "2.8" |
| 241 |
authorization: |
| 242 |
description: |
| 243 |
- Sets the authorization of the user. |
| 244 |
- Can set multiple authorizations using comma separation. |
| 245 |
- To delete all authorizations, use O(authorization=''). |
| 246 |
- Currently supported on Illumos/Solaris. Does nothing when used with other platforms. |
| 247 |
type: str |
| 248 |
version_added: "2.8" |
| 249 |
role: |
| 250 |
description: |
| 251 |
- Sets the role of the user. |
| 252 |
- Can set multiple roles using comma separation. |
| 253 |
- To delete all roles, use O(role=''). |
| 254 |
- Currently supported on Illumos/Solaris. Does nothing when used with other platforms. |
| 255 |
type: str |
| 256 |
version_added: "2.8" |
| 257 |
password_expire_max: |
| 258 |
description: |
| 259 |
- Maximum number of days between password change. |
| 260 |
- Supported on Linux only. |
| 261 |
type: int |
| 262 |
version_added: "2.11" |
| 263 |
password_expire_min: |
| 264 |
description: |
| 265 |
- Minimum number of days between password change. |
| 266 |
- Supported on Linux only. |
| 267 |
type: int |
| 268 |
version_added: "2.11" |
| 269 |
password_expire_warn: |
| 270 |
description: |
| 271 |
- Number of days of warning before password expires. |
| 272 |
- Supported on Linux only. |
| 273 |
type: int |
| 274 |
version_added: "2.16" |
| 275 |
umask: |
| 276 |
description: |
| 277 |
- Sets the umask of the user. |
| 278 |
- Currently supported on Linux. Does nothing when used with other platforms. |
| 279 |
- Requires O(local) is omitted or V(false). |
| 280 |
type: str |
| 281 |
version_added: "2.12" |
| 282 |
password_expire_account_disable: |
| 283 |
description: |
| 284 |
- Number of days after a password expires until the account is disabled. |
| 285 |
- Currently supported on AIX, Linux, NetBSD, OpenBSD. |
| 286 |
type: int |
| 287 |
version_added: "2.18" |
| 288 |
uid_min: |
| 289 |
description: |
| 290 |
- Sets the UID_MIN value for user creation. |
| 291 |
- Overwrites /etc/login.defs default value. |
| 292 |
- Currently supported on Linux. Does nothing when used with other platforms. |
| 293 |
- Requires O(local) is omitted or V(False). |
| 294 |
type: int |
| 295 |
version_added: "2.18" |
| 296 |
uid_max: |
| 297 |
description: |
| 298 |
- Sets the UID_MAX value for user creation. |
| 299 |
- Overwrites /etc/login.defs default value. |
| 300 |
- Currently supported on Linux. Does nothing when used with other platforms. |
| 301 |
- Requires O(local) is omitted or V(False). |
| 302 |
type: int |
| 303 |
version_added: "2.18" |
| 304 |
|
| 305 |
extends_documentation_fragment: action_common_attributes |
| 306 |
attributes: |
| 307 |
check_mode: |
| 308 |
support: full |
| 309 |
diff_mode: |
| 310 |
support: none |
| 311 |
platform: |
| 312 |
platforms: posix |
| 313 |
notes: |
| 314 |
- There are specific requirements per platform on user management utilities. However |
| 315 |
they generally come pre-installed with the system and Ansible will require they |
| 316 |
are present at runtime. If they are not, a descriptive error message will be shown. |
| 317 |
- On SunOS platforms, the shadow file is backed up automatically since this module edits it directly. |
| 318 |
On other platforms, the shadow file is backed up by the underlying tools used by this module. |
| 319 |
- On macOS, this module uses C(dscl) to create, modify, and delete accounts. C(dseditgroup) is used to |
| 320 |
modify group membership. Accounts are hidden from the login window by modifying |
| 321 |
C(/Library/Preferences/com.apple.loginwindow.plist). |
| 322 |
- On FreeBSD, this module uses C(pw useradd) and C(chpass) to create, C(pw usermod) and C(chpass) to modify, |
| 323 |
C(pw userdel) remove, C(pw lock) to lock, and C(pw unlock) to unlock accounts. |
| 324 |
- On distributions using BusyBox, this module uses C(adduser), C(chpasswd), C(deluser), and C(delgroup). |
| 325 |
The C(/etc/passwd) file is modified directly by this module and is backed up before modification. |
| 326 |
- On distributions using BusyBox, O(move_home) is supported only if C(shadow) package is installed. |
| 327 |
- On all other platforms, this module uses C(useradd) to create, C(usermod) to modify, and |
| 328 |
C(userdel) to remove accounts. |
| 329 |
seealso: |
| 330 |
- module: ansible.posix.authorized_key |
| 331 |
- module: ansible.builtin.group |
| 332 |
- module: ansible.windows.win_user |
| 333 |
author: |
| 334 |
- Stephen Fromm (@sfromm) |
| 335 |
""" |
| 336 |
|
| 337 |
EXAMPLES = r""" |
| 338 |
- name: Add the user 'johnd' with a specific uid and a primary group of 'admin' |
| 339 |
ansible.builtin.user: |
| 340 |
name: johnd |
| 341 |
comment: John Doe |
| 342 |
uid: 1040 |
| 343 |
group: admin |
| 344 |
|
| 345 |
- name: Create a user 'johnd' with a home directory |
| 346 |
ansible.builtin.user: |
| 347 |
name: johnd |
| 348 |
create_home: yes |
| 349 |
|
| 350 |
- name: Add the user 'james' with a bash shell, appending the group 'admins' and 'developers' to the user's groups |
| 351 |
ansible.builtin.user: |
| 352 |
name: james |
| 353 |
shell: /bin/bash |
| 354 |
groups: admins,developers |
| 355 |
append: yes |
| 356 |
|
| 357 |
- name: Remove the user 'johnd' |
| 358 |
ansible.builtin.user: |
| 359 |
name: johnd |
| 360 |
state: absent |
| 361 |
remove: yes |
| 362 |
|
| 363 |
- name: Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa |
| 364 |
ansible.builtin.user: |
| 365 |
name: jsmith |
| 366 |
generate_ssh_key: yes |
| 367 |
ssh_key_bits: 2048 |
| 368 |
ssh_key_file: .ssh/id_rsa |
| 369 |
|
| 370 |
- name: Added a consultant whose account you want to expire |
| 371 |
ansible.builtin.user: |
| 372 |
name: james18 |
| 373 |
shell: /bin/zsh |
| 374 |
groups: developers |
| 375 |
expires: 1422403387 |
| 376 |
|
| 377 |
- name: Starting at Ansible 2.6, modify user, remove expiry time |
| 378 |
ansible.builtin.user: |
| 379 |
name: james18 |
| 380 |
expires: -1 |
| 381 |
|
| 382 |
- name: Set maximum expiration date for password |
| 383 |
ansible.builtin.user: |
| 384 |
name: ram19 |
| 385 |
password_expire_max: 10 |
| 386 |
|
| 387 |
- name: Set minimum expiration date for password |
| 388 |
ansible.builtin.user: |
| 389 |
name: pushkar15 |
| 390 |
password_expire_min: 5 |
| 391 |
|
| 392 |
- name: Set number of warning days for password expiration |
| 393 |
ansible.builtin.user: |
| 394 |
name: jane157 |
| 395 |
password_expire_warn: 30 |
| 396 |
|
| 397 |
- name: Set number of days after password expires until account is disabled |
| 398 |
ansible.builtin.user: |
| 399 |
name: jimholden2016 |
| 400 |
password_expire_account_disable: 15 |
| 401 |
""" |
| 402 |
|
| 403 |
RETURN = r""" |
| 404 |
append: |
| 405 |
description: Whether or not to append the user to groups. |
| 406 |
returned: When O(state) is V(present) and the user exists |
| 407 |
type: bool |
| 408 |
sample: True |
| 409 |
comment: |
| 410 |
description: Comment section from passwd file, usually the user name. |
| 411 |
returned: When user exists |
| 412 |
type: str |
| 413 |
sample: Agent Smith |
| 414 |
create_home: |
| 415 |
description: Whether or not to create the home directory. |
| 416 |
returned: When user does not exist and not check mode |
| 417 |
type: bool |
| 418 |
sample: True |
| 419 |
force: |
| 420 |
description: Whether or not a user account was forcibly deleted. |
| 421 |
returned: When O(state) is V(absent) and user exists |
| 422 |
type: bool |
| 423 |
sample: False |
| 424 |
group: |
| 425 |
description: Primary user group ID |
| 426 |
returned: When user exists |
| 427 |
type: int |
| 428 |
sample: 1001 |
| 429 |
groups: |
| 430 |
description: Comma-separated list of groups of which the user is a member. |
| 431 |
returned: When user exists and O(state) is V(present) |
| 432 |
type: str |
| 433 |
sample: 'chrony,apache' |
| 434 |
home: |
| 435 |
description: "Path to user's home directory." |
| 436 |
returned: When O(state) is V(present) |
| 437 |
type: str |
| 438 |
sample: '/home/asmith' |
| 439 |
move_home: |
| 440 |
description: Whether or not to move an existing home directory. |
| 441 |
returned: When O(state) is V(present) and user exists |
| 442 |
type: bool |
| 443 |
sample: False |
| 444 |
name: |
| 445 |
description: User account name. |
| 446 |
returned: always |
| 447 |
type: str |
| 448 |
sample: asmith |
| 449 |
password: |
| 450 |
description: Masked value of the password. |
| 451 |
returned: When O(state) is V(present) and O(password) is not empty |
| 452 |
type: str |
| 453 |
sample: 'NOT_LOGGING_PASSWORD' |
| 454 |
remove: |
| 455 |
description: Whether or not to remove the user account. |
| 456 |
returned: When O(state) is V(absent) and user exists |
| 457 |
type: bool |
| 458 |
sample: True |
| 459 |
shell: |
| 460 |
description: User login shell. |
| 461 |
returned: When O(state) is V(present) |
| 462 |
type: str |
| 463 |
sample: '/bin/bash' |
| 464 |
ssh_fingerprint: |
| 465 |
description: Fingerprint of generated SSH key. |
| 466 |
returned: When O(generate_ssh_key) is V(True) |
| 467 |
type: str |
| 468 |
sample: '2048 SHA256:aYNHYcyVm87Igh0IMEDMbvW0QDlRQfE0aJugp684ko8 ansible-generated on host (RSA)' |
| 469 |
ssh_key_file: |
| 470 |
description: Path to generated SSH private key file. |
| 471 |
returned: When O(generate_ssh_key) is V(True) |
| 472 |
type: str |
| 473 |
sample: /home/asmith/.ssh/id_rsa |
| 474 |
ssh_public_key: |
| 475 |
description: Generated SSH public key file. |
| 476 |
returned: When O(generate_ssh_key) is V(True) |
| 477 |
type: str |
| 478 |
sample: > |
| 479 |
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC95opt4SPEC06tOYsJQJIuN23BbLMGmYo8ysVZQc4h2DZE9ugbjWWGS1/pweUGjVstgzMkBEeBCByaEf/RJKNecKRPeGd2Bw9DCj/bn5Z6rGfNENKBmo |
| 480 |
618mUJBvdlEgea96QGjOwSB7/gmonduC7gsWDMNcOdSE3wJMTim4lddiBx4RgC9yXsJ6Tkz9BHD73MXPpT5ETnse+A3fw3IGVSjaueVnlUyUmOBf7fzmZbhlFVXf2Zi2rFTXqvbdGHKkzpw1U8eB8xFPP7y |
| 481 |
d5u1u0e6Acju/8aZ/l17IDFiLke5IzlqIMRTEbDwLNeO84YQKWTm9fODHzhYe0yvxqLiK07 ansible-generated on host' |
| 482 |
stderr: |
| 483 |
description: Standard error from running commands. |
| 484 |
returned: When stderr is returned by a command that is run |
| 485 |
type: str |
| 486 |
sample: Group wheels does not exist |
| 487 |
stdout: |
| 488 |
description: Standard output from running commands. |
| 489 |
returned: When standard output is returned by the command that is run |
| 490 |
type: str |
| 491 |
sample: |
| 492 |
system: |
| 493 |
description: Whether or not the account is a system account. |
| 494 |
returned: When O(system) is passed to the module and the account does not exist |
| 495 |
type: bool |
| 496 |
sample: True |
| 497 |
uid: |
| 498 |
description: User ID of the user account. |
| 499 |
returned: When O(uid) is passed to the module |
| 500 |
type: int |
| 501 |
sample: 1044 |
| 502 |
""" |
| 503 |
|
| 504 |
|
| 505 |
import ctypes.util |
| 506 |
from datetime import datetime |
| 507 |
import grp |
| 508 |
import calendar |
| 509 |
import os |
| 510 |
import re |
| 511 |
import pty |
| 512 |
import pwd |
| 513 |
import select |
| 514 |
import shutil |
| 515 |
import socket |
| 516 |
import subprocess |
| 517 |
import tempfile |
| 518 |
import time |
| 519 |
import math |
| 520 |
import typing as t |
| 521 |
|
| 522 |
from ansible.module_utils import distro |
| 523 |
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text |
| 524 |
from ansible.module_utils.basic import AnsibleModule |
| 525 |
from ansible.module_utils.common.locale import get_best_parsable_locale |
| 526 |
from ansible.module_utils.common.sys_info import get_platform_subclass |
| 527 |
|
| 528 |
|
| 529 |
# Placeholder home directories that should never be physically created on disk |
| 530 |
# These are conventions for system accounts that should not have real home directories |
| 531 |
PLACEHOLDER_HOME_DIRS = frozenset([ |
| 532 |
'/nonexistent', # FreeBSD convention for system accounts (www, nobody, etc.) |
| 533 |
'/dev/null', # Used on some Linux systems for system accounts |
| 534 |
'/var/empty', # OpenBSD convention for privilege-separated processes |
| 535 |
]) |
| 536 |
|
| 537 |
|
| 538 |
class StructSpwdType(ctypes.Structure): |
| 539 |
_fields_ = [ |
| 540 |
('sp_namp', ctypes.c_char_p), |
| 541 |
('sp_pwdp', ctypes.c_char_p), |
| 542 |
('sp_lstchg', ctypes.c_long), |
| 543 |
('sp_min', ctypes.c_long), |
| 544 |
('sp_max', ctypes.c_long), |
| 545 |
('sp_warn', ctypes.c_long), |
| 546 |
('sp_inact', ctypes.c_long), |
| 547 |
('sp_expire', ctypes.c_long), |
| 548 |
('sp_flag', ctypes.c_ulong), |
| 549 |
] |
| 550 |
|
| 551 |
|
| 552 |
try: |
| 553 |
_LIBC = ctypes.cdll.LoadLibrary( |
| 554 |
t.cast( |
| 555 |
str, |
| 556 |
ctypes.util.find_library('c') |
| 557 |
) |
| 558 |
) |
| 559 |
_LIBC.getspnam.argtypes = (ctypes.c_char_p,) |
| 560 |
_LIBC.getspnam.restype = ctypes.POINTER(StructSpwdType) |
| 561 |
HAVE_SPWD = True |
| 562 |
except AttributeError: |
| 563 |
HAVE_SPWD = False |
| 564 |
|
| 565 |
|
| 566 |
_HASH_RE = re.compile(r'[^a-zA-Z0-9./=]') |
| 567 |
LOCK_INDICATOR = '!' |
| 568 |
|
| 569 |
|
| 570 |
def getspnam(b_name): |
| 571 |
return _LIBC.getspnam(b_name).contents |
| 572 |
|
| 573 |
|
| 574 |
class User(object): |
| 575 |
""" |
| 576 |
This is a generic User manipulation class that is subclassed |
| 577 |
based on platform. |
| 578 |
|
| 579 |
A subclass may wish to override the following action methods:- |
| 580 |
- create_user() |
| 581 |
- remove_user() |
| 582 |
- modify_user() |
| 583 |
- ssh_key_gen() |
| 584 |
- ssh_key_fingerprint() |
| 585 |
- user_exists() |
| 586 |
|
| 587 |
All subclasses MUST define platform and distribution (which may be None). |
| 588 |
""" |
| 589 |
platform = 'Generic' |
| 590 |
distribution = None # type: str | None |
| 591 |
PASSWORDFILE = '/etc/passwd' |
| 592 |
SHADOWFILE = '/etc/shadow' # type: str | None |
| 593 |
SHADOWFILE_EXPIRE_INDEX = 7 |
| 594 |
LOGIN_DEFS = '/etc/login.defs' |
| 595 |
DATE_FORMAT = '%Y-%m-%d' |
| 596 |
|
| 597 |
def __new__(cls, *args, **kwargs): |
| 598 |
new_cls = get_platform_subclass(User) |
| 599 |
return super(cls, new_cls).__new__(new_cls) |
| 600 |
|
| 601 |
def __init__(self, module): |
| 602 |
self.module = module |
| 603 |
self.state = module.params['state'] |
| 604 |
self.name = module.params['name'] |
| 605 |
self.uid = module.params['uid'] |
| 606 |
self.hidden = module.params['hidden'] |
| 607 |
self.non_unique = module.params['non_unique'] |
| 608 |
self.seuser = module.params['seuser'] |
| 609 |
self.group = module.params['group'] |
| 610 |
self.comment = module.params['comment'] |
| 611 |
self.shell = module.params['shell'] |
| 612 |
self.password = module.params['password'] |
| 613 |
self.force = module.params['force'] |
| 614 |
self.remove = module.params['remove'] |
| 615 |
self.create_home = module.params['create_home'] |
| 616 |
self.move_home = module.params['move_home'] |
| 617 |
self.skeleton = module.params['skeleton'] |
| 618 |
self.system = module.params['system'] |
| 619 |
self.login_class = module.params['login_class'] |
| 620 |
self.append = module.params['append'] |
| 621 |
self.sshkeygen = module.params['generate_ssh_key'] |
| 622 |
self.ssh_bits = module.params['ssh_key_bits'] |
| 623 |
self.ssh_type = module.params['ssh_key_type'] |
| 624 |
self.ssh_comment = module.params['ssh_key_comment'] |
| 625 |
self.ssh_passphrase = module.params['ssh_key_passphrase'] |
| 626 |
self.update_password = module.params['update_password'] |
| 627 |
self.home = module.params['home'] |
| 628 |
self.expires = None |
| 629 |
self.password_lock = module.params['password_lock'] |
| 630 |
self.groups = None |
| 631 |
self.local = module.params['local'] |
| 632 |
self.profile = module.params['profile'] |
| 633 |
self.authorization = module.params['authorization'] |
| 634 |
self.role = module.params['role'] |
| 635 |
self.password_expire_max = module.params['password_expire_max'] |
| 636 |
self.password_expire_min = module.params['password_expire_min'] |
| 637 |
self.password_expire_warn = module.params['password_expire_warn'] |
| 638 |
self.umask = module.params['umask'] |
| 639 |
self.inactive = module.params['password_expire_account_disable'] |
| 640 |
self.uid_min = module.params['uid_min'] |
| 641 |
self.uid_max = module.params['uid_max'] |
| 642 |
|
| 643 |
if self.local: |
| 644 |
if self.umask is not None: |
| 645 |
module.fail_json(msg="'umask' can not be used with 'local'") |
| 646 |
if self.uid_min is not None: |
| 647 |
module.fail_json(msg="'uid_min' can not be used with 'local'") |
| 648 |
if self.uid_max is not None: |
| 649 |
module.fail_json(msg="'uid_max' can not be used with 'local'") |
| 650 |
|
| 651 |
if module.params['groups'] is not None: |
| 652 |
self.groups = ','.join(module.params['groups']) |
| 653 |
|
| 654 |
if module.params['expires'] is not None: |
| 655 |
try: |
| 656 |
self.expires = time.gmtime(module.params['expires']) |
| 657 |
except Exception as e: |
| 658 |
module.fail_json(msg="Invalid value for 'expires' %s: %s" % (self.expires, to_native(e))) |
| 659 |
|
| 660 |
if module.params['ssh_key_file'] is not None: |
| 661 |
self.ssh_file = module.params['ssh_key_file'] |
| 662 |
else: |
| 663 |
self.ssh_file = os.path.join('.ssh', 'id_%s' % self.ssh_type) |
| 664 |
|
| 665 |
def check_password_encrypted(self): |
| 666 |
# Darwin needs cleartext password, so skip validation |
| 667 |
if self.module.params['password'] and self.platform != 'Darwin': |
| 668 |
maybe_invalid = False |
| 669 |
|
| 670 |
# Allow setting certain passwords in order to disable the account |
| 671 |
if self.module.params['password'] in set(['*', '!', '*************']): |
| 672 |
maybe_invalid = False |
| 673 |
else: |
| 674 |
# : for delimiter, * for disable user, ! for lock user |
| 675 |
# these characters are invalid in the password |
| 676 |
if any(char in self.module.params['password'] for char in ':*!'): |
| 677 |
maybe_invalid = True |
| 678 |
if '$' not in self.module.params['password']: |
| 679 |
maybe_invalid = True |
| 680 |
else: |
| 681 |
fields = self.module.params['password'].split("$") |
| 682 |
if len(fields) >= 3: |
| 683 |
# contains character outside the crypto constraint |
| 684 |
if bool(_HASH_RE.search(fields[-1])): |
| 685 |
maybe_invalid = True |
| 686 |
# md5 |
| 687 |
if fields[1] == '1' and len(fields[-1]) != 22: |
| 688 |
maybe_invalid = True |
| 689 |
# sha256 |
| 690 |
if fields[1] == '5' and len(fields[-1]) != 43: |
| 691 |
maybe_invalid = True |
| 692 |
# sha512 |
| 693 |
if fields[1] == '6' and len(fields[-1]) != 86: |
| 694 |
maybe_invalid = True |
| 695 |
# yescrypt |
| 696 |
if fields[1] == 'y' and len(fields[-1]) != 43: |
| 697 |
maybe_invalid = True |
| 698 |
else: |
| 699 |
maybe_invalid = True |
| 700 |
if maybe_invalid: |
| 701 |
self.module.warn("The input password appears not to have been hashed. " |
| 702 |
"The 'password' argument must be encrypted for this module to work properly.") |
| 703 |
|
| 704 |
def execute_command(self, cmd, use_unsafe_shell=False, data=None, obey_checkmode=True): |
| 705 |
if self.module.check_mode and obey_checkmode: |
| 706 |
self.module.debug('In check mode, would have run: "%s"' % cmd) |
| 707 |
return (0, '', '') |
| 708 |
else: |
| 709 |
# cast all args to strings ansible-modules-core/issues/4397 |
| 710 |
cmd = [str(x) for x in cmd] |
| 711 |
return self.module.run_command(cmd, use_unsafe_shell=use_unsafe_shell, data=data) |
| 712 |
|
| 713 |
def backup_shadow(self): |
| 714 |
if not self.module.check_mode and self.SHADOWFILE: |
| 715 |
return self.module.backup_local(self.SHADOWFILE) |
| 716 |
|
| 717 |
def remove_user_userdel(self): |
| 718 |
if self.local: |
| 719 |
command_name = 'luserdel' |
| 720 |
else: |
| 721 |
command_name = 'userdel' |
| 722 |
|
| 723 |
cmd = [self.module.get_bin_path(command_name, True)] |
| 724 |
if self.force and not self.local: |
| 725 |
cmd.append('-f') |
| 726 |
if self.remove: |
| 727 |
cmd.append('-r') |
| 728 |
cmd.append(self.name) |
| 729 |
|
| 730 |
return self.execute_command(cmd) |
| 731 |
|
| 732 |
def create_user_useradd(self): |
| 733 |
|
| 734 |
if self.local: |
| 735 |
command_name = 'luseradd' |
| 736 |
lgroupmod_cmd = self.module.get_bin_path('lgroupmod', True) |
| 737 |
lchage_cmd = self.module.get_bin_path('lchage', True) |
| 738 |
else: |
| 739 |
command_name = 'useradd' |
| 740 |
|
| 741 |
cmd = [self.module.get_bin_path(command_name, True)] |
| 742 |
|
| 743 |
if self.uid is not None: |
| 744 |
cmd.append('-u') |
| 745 |
cmd.append(self.uid) |
| 746 |
|
| 747 |
if self.non_unique: |
| 748 |
cmd.append('-o') |
| 749 |
|
| 750 |
if self.seuser is not None and self.module.selinux_enabled(): |
| 751 |
cmd.append('-Z') |
| 752 |
cmd.append(self.seuser) |
| 753 |
if self.group is not None: |
| 754 |
if not self.group_exists(self.group): |
| 755 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 756 |
cmd.append('-g') |
| 757 |
cmd.append(self.group) |
| 758 |
elif self.group_exists(self.name): |
| 759 |
# use the -N option (no user group) if a group already |
| 760 |
# exists with the same name as the user to prevent |
| 761 |
# errors from useradd trying to create a group when |
| 762 |
# USERGROUPS_ENAB is set in /etc/login.defs. |
| 763 |
if self.local: |
| 764 |
# luseradd uses -n instead of -N |
| 765 |
cmd.append('-n') |
| 766 |
else: |
| 767 |
if os.path.exists('/etc/redhat-release'): |
| 768 |
dist = distro.version() |
| 769 |
major_release = int(dist.split('.')[0]) |
| 770 |
if major_release <= 5: |
| 771 |
cmd.append('-n') |
| 772 |
else: |
| 773 |
cmd.append('-N') |
| 774 |
elif os.path.exists('/etc/SuSE-release'): |
| 775 |
# -N did not exist in useradd before SLE 11 and did not |
| 776 |
# automatically create a group |
| 777 |
dist = distro.version() |
| 778 |
major_release = int(dist.split('.')[0]) |
| 779 |
if major_release >= 12: |
| 780 |
cmd.append('-N') |
| 781 |
else: |
| 782 |
cmd.append('-N') |
| 783 |
|
| 784 |
if self.groups is not None and len(self.groups): |
| 785 |
groups = self.get_groups_set() |
| 786 |
if not self.local: |
| 787 |
cmd.append('-G') |
| 788 |
cmd.append(','.join(groups)) |
| 789 |
|
| 790 |
if self.comment is not None: |
| 791 |
cmd.append('-c') |
| 792 |
cmd.append(self.comment) |
| 793 |
|
| 794 |
if self.home is not None: |
| 795 |
# If the specified path to the user home contains parent directories that |
| 796 |
# do not exist and create_home is True first create the parent directory |
| 797 |
# since useradd cannot create it. |
| 798 |
if self.create_home: |
| 799 |
parent = os.path.dirname(self.home) |
| 800 |
if not os.path.isdir(parent): |
| 801 |
self.create_homedir(self.home) |
| 802 |
cmd.append('-d') |
| 803 |
cmd.append(self.home) |
| 804 |
|
| 805 |
if self.shell is not None: |
| 806 |
cmd.append('-s') |
| 807 |
cmd.append(self.shell) |
| 808 |
|
| 809 |
if self.expires is not None and not self.local: |
| 810 |
cmd.append('-e') |
| 811 |
if self.expires < time.gmtime(0): |
| 812 |
cmd.append('') |
| 813 |
else: |
| 814 |
cmd.append(time.strftime(self.DATE_FORMAT, self.expires)) |
| 815 |
|
| 816 |
if self.inactive is not None: |
| 817 |
cmd.append('-f') |
| 818 |
cmd.append(int(self.inactive)) |
| 819 |
|
| 820 |
if self.password is not None: |
| 821 |
cmd.append('-p') |
| 822 |
if self.password_lock: |
| 823 |
cmd.append('!%s' % self.password) |
| 824 |
else: |
| 825 |
cmd.append(self.password) |
| 826 |
|
| 827 |
if self.create_home: |
| 828 |
if not self.local: |
| 829 |
cmd.append('-m') |
| 830 |
|
| 831 |
if self.skeleton is not None: |
| 832 |
cmd.append('-k') |
| 833 |
cmd.append(self.skeleton) |
| 834 |
|
| 835 |
if self.umask is not None: |
| 836 |
cmd.append('-K') |
| 837 |
cmd.append('UMASK=' + self.umask) |
| 838 |
else: |
| 839 |
cmd.append('-M') |
| 840 |
|
| 841 |
if self.system: |
| 842 |
cmd.append('-r') |
| 843 |
|
| 844 |
if self.uid_min is not None: |
| 845 |
cmd.append('-K') |
| 846 |
cmd.append('UID_MIN=' + str(self.uid_min)) |
| 847 |
|
| 848 |
if self.uid_max is not None: |
| 849 |
cmd.append('-K') |
| 850 |
cmd.append('UID_MAX=' + str(self.uid_max)) |
| 851 |
|
| 852 |
cmd.append(self.name) |
| 853 |
(rc, out, err) = self.execute_command(cmd) |
| 854 |
if not self.local or rc != 0: |
| 855 |
return (rc, out, err) |
| 856 |
|
| 857 |
if self.expires is not None: |
| 858 |
if self.expires < time.gmtime(0): |
| 859 |
lexpires = -1 |
| 860 |
else: |
| 861 |
# Convert seconds since Epoch to days since Epoch |
| 862 |
lexpires = int(math.floor(self.module.params['expires'])) // 86400 |
| 863 |
(rc, _out, _err) = self.execute_command([lchage_cmd, '-E', to_native(lexpires), self.name]) |
| 864 |
out += _out |
| 865 |
err += _err |
| 866 |
if rc != 0: |
| 867 |
return (rc, out, err) |
| 868 |
|
| 869 |
if self.groups is None or len(self.groups) == 0: |
| 870 |
return (rc, out, err) |
| 871 |
|
| 872 |
for add_group in groups: |
| 873 |
(rc, _out, _err) = self.execute_command([lgroupmod_cmd, '-M', self.name, add_group]) |
| 874 |
out += _out |
| 875 |
err += _err |
| 876 |
if rc != 0: |
| 877 |
return (rc, out, err) |
| 878 |
return (rc, out, err) |
| 879 |
|
| 880 |
def _check_usermod_append(self): |
| 881 |
# check if this version of usermod can append groups |
| 882 |
|
| 883 |
if self.local: |
| 884 |
command_name = 'lusermod' |
| 885 |
else: |
| 886 |
command_name = 'usermod' |
| 887 |
|
| 888 |
usermod_path = self.module.get_bin_path(command_name, True) |
| 889 |
|
| 890 |
# for some reason, usermod --help cannot be used by non root |
| 891 |
# on RH/Fedora, due to lack of execute bit for others |
| 892 |
if not os.access(usermod_path, os.X_OK): |
| 893 |
return False |
| 894 |
|
| 895 |
cmd = [usermod_path, '--help'] |
| 896 |
(rc, data1, data2) = self.execute_command(cmd, obey_checkmode=False) |
| 897 |
helpout = data1 + data2 |
| 898 |
|
| 899 |
# check if --append exists |
| 900 |
lines = to_native(helpout).split('\n') |
| 901 |
for line in lines: |
| 902 |
if line.strip().startswith('-a, --append'): |
| 903 |
return True |
| 904 |
|
| 905 |
return False |
| 906 |
|
| 907 |
def modify_user_usermod(self): |
| 908 |
|
| 909 |
if self.local: |
| 910 |
command_name = 'lusermod' |
| 911 |
lgroupmod_cmd = self.module.get_bin_path('lgroupmod', True) |
| 912 |
lgroupmod_add = set() |
| 913 |
lgroupmod_del = set() |
| 914 |
lchage_cmd = self.module.get_bin_path('lchage', True) |
| 915 |
lexpires = None |
| 916 |
else: |
| 917 |
command_name = 'usermod' |
| 918 |
|
| 919 |
cmd = [self.module.get_bin_path(command_name, True)] |
| 920 |
info = self.user_info() |
| 921 |
has_append = self._check_usermod_append() |
| 922 |
|
| 923 |
if self.uid is not None and info[2] != int(self.uid): |
| 924 |
cmd.append('-u') |
| 925 |
cmd.append(self.uid) |
| 926 |
|
| 927 |
if self.non_unique: |
| 928 |
cmd.append('-o') |
| 929 |
|
| 930 |
if self.group is not None: |
| 931 |
if not self.group_exists(self.group): |
| 932 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 933 |
ginfo = self.group_info(self.group) |
| 934 |
if info[3] != ginfo[2]: |
| 935 |
cmd.append('-g') |
| 936 |
cmd.append(ginfo[2]) |
| 937 |
|
| 938 |
if self.groups is not None: |
| 939 |
# get a list of all groups for the user, including the primary |
| 940 |
current_groups = self.user_group_membership(exclude_primary=False) |
| 941 |
groups_need_mod = False |
| 942 |
groups = [] |
| 943 |
|
| 944 |
if self.groups == '': |
| 945 |
if current_groups and not self.append: |
| 946 |
groups_need_mod = True |
| 947 |
else: |
| 948 |
groups = self.get_groups_set(remove_existing=False, names_only=True) |
| 949 |
group_diff = set(current_groups).symmetric_difference(groups) |
| 950 |
|
| 951 |
if group_diff: |
| 952 |
if self.append: |
| 953 |
for g in groups: |
| 954 |
if g in group_diff: |
| 955 |
if has_append: |
| 956 |
cmd.append('-a') |
| 957 |
groups_need_mod = True |
| 958 |
break |
| 959 |
else: |
| 960 |
groups_need_mod = True |
| 961 |
|
| 962 |
if groups_need_mod: |
| 963 |
if self.local: |
| 964 |
if self.append: |
| 965 |
lgroupmod_add = set(groups).difference(current_groups) |
| 966 |
lgroupmod_del = set() |
| 967 |
else: |
| 968 |
lgroupmod_add = set(groups).difference(current_groups) |
| 969 |
lgroupmod_del = set(current_groups).difference(groups) |
| 970 |
else: |
| 971 |
if self.append and not has_append: |
| 972 |
cmd.append('-A') |
| 973 |
cmd.append(','.join(group_diff)) |
| 974 |
else: |
| 975 |
cmd.append('-G') |
| 976 |
cmd.append(','.join(groups)) |
| 977 |
|
| 978 |
if self.comment is not None and info[4] != self.comment: |
| 979 |
cmd.append('-c') |
| 980 |
cmd.append(self.comment) |
| 981 |
|
| 982 |
existing_home = info[5] |
| 983 |
if self.home is not None and existing_home != self.home: |
| 984 |
cmd.append('-d') |
| 985 |
cmd.append(self.home) |
| 986 |
if self.move_home: |
| 987 |
if self.local and not os.path.exists(existing_home): |
| 988 |
self.module.warn("Ignoring move_home since home directory %s does not exist, but local is true" % existing_home) |
| 989 |
else: |
| 990 |
cmd.append('-m') |
| 991 |
|
| 992 |
if self.shell is not None and info[6] != self.shell: |
| 993 |
cmd.append('-s') |
| 994 |
cmd.append(self.shell) |
| 995 |
|
| 996 |
if self.expires is not None: |
| 997 |
|
| 998 |
current_expires = self.user_password()[1] or '0' |
| 999 |
current_expires = int(current_expires) |
| 1000 |
|
| 1001 |
if self.expires < time.gmtime(0): |
| 1002 |
if current_expires >= 0: |
| 1003 |
if self.local: |
| 1004 |
lexpires = -1 |
| 1005 |
else: |
| 1006 |
cmd.append('-e') |
| 1007 |
cmd.append('') |
| 1008 |
else: |
| 1009 |
# Convert days since Epoch to seconds since Epoch as struct_time |
| 1010 |
current_expire_date = time.gmtime(current_expires * 86400) |
| 1011 |
|
| 1012 |
# Current expires is negative or we compare year, month, and day only |
| 1013 |
if current_expires < 0 or current_expire_date[:3] != self.expires[:3]: |
| 1014 |
if self.local: |
| 1015 |
# Convert seconds since Epoch to days since Epoch |
| 1016 |
lexpires = int(math.floor(self.module.params['expires'])) // 86400 |
| 1017 |
else: |
| 1018 |
cmd.append('-e') |
| 1019 |
cmd.append(time.strftime(self.DATE_FORMAT, self.expires)) |
| 1020 |
|
| 1021 |
if self.inactive is not None: |
| 1022 |
cmd.append('-f') |
| 1023 |
cmd.append(self.inactive) |
| 1024 |
|
| 1025 |
# Lock if no password or unlocked, unlock only if locked |
| 1026 |
if self.password_lock and not info[1].startswith('!'): |
| 1027 |
cmd.append('-L') |
| 1028 |
elif self.password_lock is False and info[1].startswith('!'): |
| 1029 |
# usermod will refuse to unlock a user with no password, module shows 'changed' regardless |
| 1030 |
cmd.append('-U') |
| 1031 |
|
| 1032 |
if self.update_password == 'always' and self.password is not None and info[1].lstrip('!') != self.password.lstrip('!'): |
| 1033 |
# Remove options that are mutually exclusive with -p |
| 1034 |
cmd = [c for c in cmd if c not in ['-U', '-L']] |
| 1035 |
cmd.append('-p') |
| 1036 |
if self.password_lock: |
| 1037 |
# Lock the account and set the hash in a single command |
| 1038 |
cmd.append('!%s' % self.password) |
| 1039 |
else: |
| 1040 |
cmd.append(self.password) |
| 1041 |
|
| 1042 |
(rc, out, err) = (None, '', '') |
| 1043 |
|
| 1044 |
# skip if no usermod changes to be made |
| 1045 |
if len(cmd) > 1: |
| 1046 |
cmd.append(self.name) |
| 1047 |
(rc, out, err) = self.execute_command(cmd) |
| 1048 |
|
| 1049 |
if not self.local or not (rc is None or rc == 0): |
| 1050 |
return (rc, out, err) |
| 1051 |
|
| 1052 |
if lexpires is not None: |
| 1053 |
(rc, _out, _err) = self.execute_command([lchage_cmd, '-E', to_native(lexpires), self.name]) |
| 1054 |
out += _out |
| 1055 |
err += _err |
| 1056 |
if rc != 0: |
| 1057 |
return (rc, out, err) |
| 1058 |
|
| 1059 |
if len(lgroupmod_add) == 0 and len(lgroupmod_del) == 0: |
| 1060 |
return (rc, out, err) |
| 1061 |
|
| 1062 |
for add_group in lgroupmod_add: |
| 1063 |
(rc, _out, _err) = self.execute_command([lgroupmod_cmd, '-M', self.name, add_group]) |
| 1064 |
out += _out |
| 1065 |
err += _err |
| 1066 |
if rc != 0: |
| 1067 |
return (rc, out, err) |
| 1068 |
|
| 1069 |
for del_group in lgroupmod_del: |
| 1070 |
(rc, _out, _err) = self.execute_command([lgroupmod_cmd, '-m', self.name, del_group]) |
| 1071 |
out += _out |
| 1072 |
err += _err |
| 1073 |
if rc != 0: |
| 1074 |
return (rc, out, err) |
| 1075 |
return (rc, out, err) |
| 1076 |
|
| 1077 |
def group_exists(self, group): |
| 1078 |
try: |
| 1079 |
# Try group as a gid first |
| 1080 |
grp.getgrgid(int(group)) |
| 1081 |
return True |
| 1082 |
except (ValueError, KeyError): |
| 1083 |
try: |
| 1084 |
grp.getgrnam(group) |
| 1085 |
return True |
| 1086 |
except KeyError: |
| 1087 |
return False |
| 1088 |
|
| 1089 |
def group_info(self, group): |
| 1090 |
if not self.group_exists(group): |
| 1091 |
return False |
| 1092 |
try: |
| 1093 |
# Try group as a gid first |
| 1094 |
return list(grp.getgrgid(int(group))) |
| 1095 |
except (ValueError, KeyError): |
| 1096 |
return list(grp.getgrnam(group)) |
| 1097 |
|
| 1098 |
def get_groups_set(self, remove_existing=True, names_only=False): |
| 1099 |
if self.groups is None: |
| 1100 |
return None |
| 1101 |
info = self.user_info() |
| 1102 |
groups = set(x.strip() for x in self.groups.split(',') if x) |
| 1103 |
group_names = set() |
| 1104 |
for g in groups.copy(): |
| 1105 |
if not self.group_exists(g): |
| 1106 |
self.module.fail_json(msg="Group %s does not exist" % (g)) |
| 1107 |
group_info = self.group_info(g) |
| 1108 |
if info and remove_existing and group_info[2] == info[3]: |
| 1109 |
groups.remove(g) |
| 1110 |
elif names_only: |
| 1111 |
group_names.add(group_info[0]) |
| 1112 |
if names_only: |
| 1113 |
return group_names |
| 1114 |
return groups |
| 1115 |
|
| 1116 |
def user_group_membership(self, exclude_primary=True): |
| 1117 |
""" Return a list of groups the user belongs to """ |
| 1118 |
groups = [] |
| 1119 |
info = self.get_pwd_info() |
| 1120 |
for group in grp.getgrall(): |
| 1121 |
if self.name in group.gr_mem: |
| 1122 |
# Exclude the user's primary group by default |
| 1123 |
if not exclude_primary: |
| 1124 |
groups.append(group[0]) |
| 1125 |
else: |
| 1126 |
if info[3] != group.gr_gid: |
| 1127 |
groups.append(group[0]) |
| 1128 |
|
| 1129 |
return groups |
| 1130 |
|
| 1131 |
def user_exists(self): |
| 1132 |
# The pwd module does not distinguish between local and directory accounts. |
| 1133 |
# It's output cannot be used to determine whether or not an account exists locally. |
| 1134 |
# It returns True if the account exists locally or in the directory, so instead |
| 1135 |
# look in the local PASSWORD file for an existing account. |
| 1136 |
if self.local: |
| 1137 |
if not os.path.exists(self.PASSWORDFILE): |
| 1138 |
self.module.fail_json(msg="'local: true' specified but unable to find local account file {0} to parse.".format(self.PASSWORDFILE)) |
| 1139 |
|
| 1140 |
exists = False |
| 1141 |
name_test = '{0}:'.format(self.name) |
| 1142 |
with open(self.PASSWORDFILE, 'rb') as f: |
| 1143 |
reversed_lines = f.readlines()[::-1] |
| 1144 |
for line in reversed_lines: |
| 1145 |
if line.startswith(to_bytes(name_test)): |
| 1146 |
exists = True |
| 1147 |
break |
| 1148 |
|
| 1149 |
return exists |
| 1150 |
|
| 1151 |
else: |
| 1152 |
try: |
| 1153 |
if pwd.getpwnam(self.name): |
| 1154 |
return True |
| 1155 |
except KeyError: |
| 1156 |
return False |
| 1157 |
|
| 1158 |
def get_pwd_info(self): |
| 1159 |
if not self.user_exists(): |
| 1160 |
return False |
| 1161 |
return list(pwd.getpwnam(self.name)) |
| 1162 |
|
| 1163 |
def user_info(self): |
| 1164 |
if not self.user_exists(): |
| 1165 |
return False |
| 1166 |
info = self.get_pwd_info() |
| 1167 |
if len(info[1]) == 1 or len(info[1]) == 0: |
| 1168 |
info[1] = self.user_password()[0] |
| 1169 |
return info |
| 1170 |
|
| 1171 |
def set_password_expire(self): |
| 1172 |
min_needs_change = self.password_expire_min is not None |
| 1173 |
max_needs_change = self.password_expire_max is not None |
| 1174 |
warn_needs_change = self.password_expire_warn is not None |
| 1175 |
|
| 1176 |
if HAVE_SPWD: |
| 1177 |
try: |
| 1178 |
shadow_info = getspnam(to_bytes(self.name)) |
| 1179 |
except ValueError: |
| 1180 |
return None, '', '' |
| 1181 |
|
| 1182 |
min_needs_change &= self.password_expire_min != shadow_info.sp_min |
| 1183 |
max_needs_change &= self.password_expire_max != shadow_info.sp_max |
| 1184 |
warn_needs_change &= self.password_expire_warn != shadow_info.sp_warn |
| 1185 |
|
| 1186 |
if not (min_needs_change or max_needs_change or warn_needs_change): |
| 1187 |
return (None, '', '') # target state already reached |
| 1188 |
|
| 1189 |
command_name = 'chage' |
| 1190 |
cmd = [self.module.get_bin_path(command_name, True)] |
| 1191 |
if min_needs_change: |
| 1192 |
cmd.extend(["-m", self.password_expire_min]) |
| 1193 |
if max_needs_change: |
| 1194 |
cmd.extend(["-M", self.password_expire_max]) |
| 1195 |
if warn_needs_change: |
| 1196 |
cmd.extend(["-W", self.password_expire_warn]) |
| 1197 |
cmd.append(self.name) |
| 1198 |
|
| 1199 |
return self.execute_command(cmd) |
| 1200 |
|
| 1201 |
def user_password(self): |
| 1202 |
passwd = '' |
| 1203 |
expires = '' |
| 1204 |
if HAVE_SPWD: |
| 1205 |
try: |
| 1206 |
shadow_info = getspnam(to_bytes(self.name)) |
| 1207 |
passwd = to_native(shadow_info.sp_pwdp) |
| 1208 |
expires = shadow_info.sp_expire |
| 1209 |
return passwd, expires |
| 1210 |
except ValueError: |
| 1211 |
return passwd, expires |
| 1212 |
|
| 1213 |
if not self.user_exists(): |
| 1214 |
return passwd, expires |
| 1215 |
elif self.SHADOWFILE: |
| 1216 |
passwd, expires = self.parse_shadow_file() |
| 1217 |
|
| 1218 |
return passwd, expires |
| 1219 |
|
| 1220 |
def parse_shadow_file(self): |
| 1221 |
passwd = '' |
| 1222 |
expires = '' |
| 1223 |
if os.path.exists(self.SHADOWFILE) and os.access(self.SHADOWFILE, os.R_OK): |
| 1224 |
with open(self.SHADOWFILE, 'r') as f: |
| 1225 |
for line in f: |
| 1226 |
if line.startswith('%s:' % self.name): |
| 1227 |
passwd = line.split(':')[1] |
| 1228 |
expires = line.split(':')[self.SHADOWFILE_EXPIRE_INDEX] or -1 |
| 1229 |
return passwd, expires |
| 1230 |
|
| 1231 |
def get_ssh_key_path(self): |
| 1232 |
info = self.user_info() |
| 1233 |
if os.path.isabs(self.ssh_file): |
| 1234 |
ssh_key_file = self.ssh_file |
| 1235 |
else: |
| 1236 |
if not os.path.exists(info[5]) and not self.module.check_mode: |
| 1237 |
raise Exception('User %s home directory does not exist' % self.name) |
| 1238 |
ssh_key_file = os.path.join(info[5], self.ssh_file) |
| 1239 |
return ssh_key_file |
| 1240 |
|
| 1241 |
def ssh_key_gen(self): |
| 1242 |
info = self.user_info() |
| 1243 |
overwrite = None |
| 1244 |
try: |
| 1245 |
ssh_key_file = self.get_ssh_key_path() |
| 1246 |
pub_file = f'{ssh_key_file}.pub' |
| 1247 |
except Exception as e: |
| 1248 |
return (1, '', to_native(e)) |
| 1249 |
ssh_dir = os.path.dirname(ssh_key_file) |
| 1250 |
|
| 1251 |
# no need to check for broken symlnk as mkdir below will fail |
| 1252 |
if not os.path.exists(ssh_dir): |
| 1253 |
if self.module.check_mode: |
| 1254 |
return (0, '', '') |
| 1255 |
try: |
| 1256 |
os.mkdir(ssh_dir, int('0700', 8)) |
| 1257 |
os.chown(ssh_dir, info[2], info[3]) |
| 1258 |
except OSError as e: |
| 1259 |
return (1, '', f'Failed to create ssh directory {ssh_dir}: {e!r}') |
| 1260 |
|
| 1261 |
# use lexists instead of exists to account for broken symlinks |
| 1262 |
if os.path.lexists(ssh_key_file): |
| 1263 |
if self.force: |
| 1264 |
if not self.module.check_mode and os.path.islink(ssh_key_file): |
| 1265 |
os.unlink(ssh_key_file) |
| 1266 |
self.module.warn(f'Overwriting existing ssh key private file "{ssh_key_file}"') |
| 1267 |
overwrite = 'y' |
| 1268 |
else: |
| 1269 |
self.module.warn(f'Found existing ssh key private file "{ssh_key_file}", no force, so skipping ssh-keygen generation') |
| 1270 |
return (None, 'Key already exists, use "force: yes" to overwrite', '') |
| 1271 |
|
| 1272 |
if os.path.lexists(pub_file): |
| 1273 |
if self.force: |
| 1274 |
if not self.module.check_mode: |
| 1275 |
os.unlink(pub_file) |
| 1276 |
self.module.warn(f'Overwriting existing ssh key public file "{pub_file}"') |
| 1277 |
else: |
| 1278 |
self.module.warn(f'Found existing ssh key public file "{pub_file}", no force, so skipping ssh-keygen generation') |
| 1279 |
return (None, 'Public key already exists, use "force: yes" to overwrite', '') |
| 1280 |
|
| 1281 |
cmd = [self.module.get_bin_path('ssh-keygen', True)] |
| 1282 |
cmd.append('-t') |
| 1283 |
cmd.append(self.ssh_type) |
| 1284 |
if self.ssh_bits > 0: |
| 1285 |
cmd.append('-b') |
| 1286 |
cmd.append(self.ssh_bits) |
| 1287 |
cmd.append('-C') |
| 1288 |
cmd.append(self.ssh_comment) |
| 1289 |
cmd.append('-f') |
| 1290 |
cmd.append(ssh_key_file) |
| 1291 |
if self.ssh_passphrase is not None: |
| 1292 |
if self.module.check_mode: |
| 1293 |
self.module.debug('In check mode, would have run: "%s"' % cmd) |
| 1294 |
return (0, '', '') |
| 1295 |
|
| 1296 |
master_in_fd, slave_in_fd = pty.openpty() |
| 1297 |
master_out_fd, slave_out_fd = pty.openpty() |
| 1298 |
master_err_fd, slave_err_fd = pty.openpty() |
| 1299 |
env = os.environ.copy() |
| 1300 |
env['LC_ALL'] = get_best_parsable_locale(self.module) |
| 1301 |
try: |
| 1302 |
p = subprocess.Popen([to_bytes(c) for c in cmd], |
| 1303 |
stdin=slave_in_fd, |
| 1304 |
stdout=slave_out_fd, |
| 1305 |
stderr=slave_err_fd, |
| 1306 |
preexec_fn=os.setsid, |
| 1307 |
env=env) |
| 1308 |
out_buffer = b'' |
| 1309 |
err_buffer = b'' |
| 1310 |
first_prompt = b'Enter passphrase' |
| 1311 |
second_prompt = b'Enter same passphrase again' |
| 1312 |
prompt = first_prompt |
| 1313 |
start = datetime.now() |
| 1314 |
timeout = 900 |
| 1315 |
while p.poll() is None: |
| 1316 |
r_list = select.select([master_out_fd, master_err_fd], [], [], 1)[0] |
| 1317 |
now = datetime.now() |
| 1318 |
if (now - start).seconds > timeout: |
| 1319 |
return (1, '', f'Timeout after {timeout} while reading passphrase for SSH key') |
| 1320 |
for fd in r_list: |
| 1321 |
if fd == master_out_fd: |
| 1322 |
chunk = os.read(master_out_fd, 10240) |
| 1323 |
out_buffer += chunk |
| 1324 |
if prompt in out_buffer: |
| 1325 |
os.write(master_in_fd, to_bytes(self.ssh_passphrase, errors='strict') + b'\r') |
| 1326 |
prompt = second_prompt |
| 1327 |
else: |
| 1328 |
chunk = os.read(master_err_fd, 10240) |
| 1329 |
err_buffer += chunk |
| 1330 |
if prompt in err_buffer: |
| 1331 |
os.write(master_in_fd, to_bytes(self.ssh_passphrase, errors='strict') + b'\r') |
| 1332 |
prompt = second_prompt |
| 1333 |
if b'Overwrite (y/n)?' in out_buffer or b'Overwrite (y/n)?' in err_buffer: |
| 1334 |
# The key was created between us checking for existence and now |
| 1335 |
return (None, 'Key already exists', '') |
| 1336 |
|
| 1337 |
rc = p.returncode |
| 1338 |
out = to_native(out_buffer) |
| 1339 |
err = to_native(err_buffer) |
| 1340 |
except OSError as e: |
| 1341 |
return (1, '', to_native(e)) |
| 1342 |
else: |
| 1343 |
cmd.append('-N') |
| 1344 |
cmd.append('') |
| 1345 |
|
| 1346 |
(rc, out, err) = self.execute_command(cmd, data=overwrite) |
| 1347 |
|
| 1348 |
if rc == 0 and not self.module.check_mode: |
| 1349 |
# If the keys were successfully created, we should be able |
| 1350 |
# to tweak ownership. |
| 1351 |
os.chown(ssh_key_file, info[2], info[3]) |
| 1352 |
os.chown(pub_file, info[2], info[3]) |
| 1353 |
return (rc, out, err) |
| 1354 |
|
| 1355 |
def ssh_key_fingerprint(self): |
| 1356 |
ssh_key_file = self.get_ssh_key_path() |
| 1357 |
if not os.path.exists(ssh_key_file): |
| 1358 |
return (1, 'SSH Key file %s does not exist' % ssh_key_file, '') |
| 1359 |
cmd = [self.module.get_bin_path('ssh-keygen', True)] |
| 1360 |
cmd.append('-l') |
| 1361 |
cmd.append('-f') |
| 1362 |
cmd.append(ssh_key_file) |
| 1363 |
|
| 1364 |
return self.execute_command(cmd, obey_checkmode=False) |
| 1365 |
|
| 1366 |
def get_ssh_public_key(self): |
| 1367 |
ssh_public_key_file = '%s.pub' % self.get_ssh_key_path() |
| 1368 |
try: |
| 1369 |
with open(ssh_public_key_file, 'r') as f: |
| 1370 |
ssh_public_key = f.read().strip() |
| 1371 |
except OSError: |
| 1372 |
return None |
| 1373 |
return ssh_public_key |
| 1374 |
|
| 1375 |
def create_user(self): |
| 1376 |
# by default we use the create_user_useradd method |
| 1377 |
return self.create_user_useradd() |
| 1378 |
|
| 1379 |
def remove_user(self): |
| 1380 |
# by default we use the remove_user_userdel method |
| 1381 |
return self.remove_user_userdel() |
| 1382 |
|
| 1383 |
def modify_user(self): |
| 1384 |
# by default we use the modify_user_usermod method |
| 1385 |
return self.modify_user_usermod() |
| 1386 |
|
| 1387 |
def create_homedir(self, path): |
| 1388 |
if not os.path.exists(path): |
| 1389 |
if self.skeleton is not None: |
| 1390 |
skeleton = self.skeleton |
| 1391 |
else: |
| 1392 |
skeleton = '/etc/skel' |
| 1393 |
|
| 1394 |
if os.path.exists(skeleton) and skeleton != os.devnull: |
| 1395 |
try: |
| 1396 |
shutil.copytree(skeleton, path, symlinks=True) |
| 1397 |
except OSError as e: |
| 1398 |
self.module.exit_json(failed=True, msg="%s" % to_native(e)) |
| 1399 |
else: |
| 1400 |
try: |
| 1401 |
os.makedirs(path) |
| 1402 |
except OSError as e: |
| 1403 |
self.module.exit_json(failed=True, msg="%s" % to_native(e)) |
| 1404 |
# get umask from /etc/login.defs and set correct home mode |
| 1405 |
if os.path.exists(self.LOGIN_DEFS): |
| 1406 |
# fallback if neither HOME_MODE nor UMASK are set; |
| 1407 |
# follow behaviour of useradd initializing UMASK = 022 |
| 1408 |
mode = 0o755 |
| 1409 |
with open(self.LOGIN_DEFS, 'r') as fh: |
| 1410 |
for line in fh: |
| 1411 |
# HOME_MODE has higher precedence as UMASK |
| 1412 |
match = re.match(r'^HOME_MODE\s+(\d+)$', line) |
| 1413 |
if match: |
| 1414 |
mode = int(match.group(1), 8) |
| 1415 |
break # higher precedence |
| 1416 |
match = re.match(r'^UMASK\s+(\d+)$', line) |
| 1417 |
if match: |
| 1418 |
umask = int(match.group(1), 8) |
| 1419 |
mode = 0o777 & ~umask |
| 1420 |
try: |
| 1421 |
os.chmod(path, mode) |
| 1422 |
except OSError as e: |
| 1423 |
self.module.exit_json(failed=True, msg=to_native(e)) |
| 1424 |
|
| 1425 |
def chown_homedir(self, uid, gid, path): |
| 1426 |
try: |
| 1427 |
os.chown(path, uid, gid) |
| 1428 |
for root, dirs, files in os.walk(path): |
| 1429 |
for d in dirs: |
| 1430 |
os.chown(os.path.join(root, d), uid, gid) |
| 1431 |
for f in files: |
| 1432 |
full_path = os.path.join(root, f) |
| 1433 |
if not os.path.islink(full_path): |
| 1434 |
os.chown(full_path, uid, gid) |
| 1435 |
except OSError as e: |
| 1436 |
self.module.exit_json(failed=True, msg="%s" % to_native(e)) |
| 1437 |
|
| 1438 |
|
| 1439 |
# =========================================== |
| 1440 |
|
| 1441 |
class FreeBsdUser(User): |
| 1442 |
""" |
| 1443 |
This is a FreeBSD User manipulation class - it uses the pw command |
| 1444 |
to manipulate the user database, followed by the chpass command |
| 1445 |
to change the password. |
| 1446 |
|
| 1447 |
This overrides the following methods from the generic class:- |
| 1448 |
- create_user() |
| 1449 |
- remove_user() |
| 1450 |
- modify_user() |
| 1451 |
""" |
| 1452 |
|
| 1453 |
platform = 'FreeBSD' |
| 1454 |
distribution = None |
| 1455 |
SHADOWFILE = '/etc/master.passwd' |
| 1456 |
SHADOWFILE_EXPIRE_INDEX = 6 |
| 1457 |
DATE_FORMAT = '%d-%b-%Y' |
| 1458 |
|
| 1459 |
def _handle_lock(self): |
| 1460 |
info = self.user_info() |
| 1461 |
if self.password_lock and not info[1].startswith('*LOCKED*'): |
| 1462 |
cmd = [ |
| 1463 |
self.module.get_bin_path('pw', True), |
| 1464 |
'lock', |
| 1465 |
self.name |
| 1466 |
] |
| 1467 |
if self.uid is not None and info[2] != int(self.uid): |
| 1468 |
cmd.append('-u') |
| 1469 |
cmd.append(self.uid) |
| 1470 |
return self.execute_command(cmd) |
| 1471 |
elif self.password_lock is False and info[1].startswith('*LOCKED*'): |
| 1472 |
cmd = [ |
| 1473 |
self.module.get_bin_path('pw', True), |
| 1474 |
'unlock', |
| 1475 |
self.name |
| 1476 |
] |
| 1477 |
if self.uid is not None and info[2] != int(self.uid): |
| 1478 |
cmd.append('-u') |
| 1479 |
cmd.append(self.uid) |
| 1480 |
return self.execute_command(cmd) |
| 1481 |
|
| 1482 |
return (None, '', '') |
| 1483 |
|
| 1484 |
def remove_user(self): |
| 1485 |
cmd = [ |
| 1486 |
self.module.get_bin_path('pw', True), |
| 1487 |
'userdel', |
| 1488 |
'-n', |
| 1489 |
self.name |
| 1490 |
] |
| 1491 |
if self.remove: |
| 1492 |
cmd.append('-r') |
| 1493 |
|
| 1494 |
return self.execute_command(cmd) |
| 1495 |
|
| 1496 |
def create_user(self): |
| 1497 |
cmd = [ |
| 1498 |
self.module.get_bin_path('pw', True), |
| 1499 |
'useradd', |
| 1500 |
'-n', |
| 1501 |
self.name, |
| 1502 |
] |
| 1503 |
|
| 1504 |
if self.uid is not None: |
| 1505 |
cmd.append('-u') |
| 1506 |
cmd.append(self.uid) |
| 1507 |
|
| 1508 |
if self.non_unique: |
| 1509 |
cmd.append('-o') |
| 1510 |
|
| 1511 |
if self.comment is not None: |
| 1512 |
cmd.append('-c') |
| 1513 |
cmd.append(self.comment) |
| 1514 |
|
| 1515 |
if self.home is not None: |
| 1516 |
cmd.append('-d') |
| 1517 |
cmd.append(self.home) |
| 1518 |
|
| 1519 |
if self.group is not None: |
| 1520 |
if not self.group_exists(self.group): |
| 1521 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 1522 |
cmd.append('-g') |
| 1523 |
cmd.append(self.group) |
| 1524 |
|
| 1525 |
if self.groups is not None: |
| 1526 |
groups = self.get_groups_set() |
| 1527 |
cmd.append('-G') |
| 1528 |
cmd.append(','.join(groups)) |
| 1529 |
|
| 1530 |
if self.create_home: |
| 1531 |
cmd.append('-m') |
| 1532 |
|
| 1533 |
if self.skeleton is not None: |
| 1534 |
cmd.append('-k') |
| 1535 |
cmd.append(self.skeleton) |
| 1536 |
|
| 1537 |
if self.umask is not None: |
| 1538 |
cmd.append('-K') |
| 1539 |
cmd.append('UMASK=' + self.umask) |
| 1540 |
|
| 1541 |
if self.shell is not None: |
| 1542 |
cmd.append('-s') |
| 1543 |
cmd.append(self.shell) |
| 1544 |
|
| 1545 |
if self.login_class is not None: |
| 1546 |
cmd.append('-L') |
| 1547 |
cmd.append(self.login_class) |
| 1548 |
|
| 1549 |
if self.expires is not None: |
| 1550 |
cmd.append('-e') |
| 1551 |
if self.expires < time.gmtime(0): |
| 1552 |
cmd.append('0') |
| 1553 |
else: |
| 1554 |
cmd.append(str(calendar.timegm(self.expires))) |
| 1555 |
|
| 1556 |
if self.uid_min is not None: |
| 1557 |
cmd.append('-K') |
| 1558 |
cmd.append('UID_MIN=' + str(self.uid_min)) |
| 1559 |
|
| 1560 |
if self.uid_max is not None: |
| 1561 |
cmd.append('-K') |
| 1562 |
cmd.append('UID_MAX=' + str(self.uid_max)) |
| 1563 |
|
| 1564 |
# system cannot be handled currently - should we error if its requested? |
| 1565 |
# create the user |
| 1566 |
(rc, out, err) = self.execute_command(cmd) |
| 1567 |
|
| 1568 |
if rc is not None and rc != 0: |
| 1569 |
self.module.fail_json(name=self.name, msg=err, rc=rc) |
| 1570 |
|
| 1571 |
# we have to set the password in a second command |
| 1572 |
if self.password is not None: |
| 1573 |
cmd = [ |
| 1574 |
self.module.get_bin_path('chpass', True), |
| 1575 |
'-p', |
| 1576 |
self.password, |
| 1577 |
self.name |
| 1578 |
] |
| 1579 |
_rc, _out, _err = self.execute_command(cmd) |
| 1580 |
if rc is None: |
| 1581 |
rc = _rc |
| 1582 |
out += _out |
| 1583 |
err += _err |
| 1584 |
|
| 1585 |
# we have to lock/unlock the password in a distinct command |
| 1586 |
_rc, _out, _err = self._handle_lock() |
| 1587 |
if rc is None: |
| 1588 |
rc = _rc |
| 1589 |
out += _out |
| 1590 |
err += _err |
| 1591 |
|
| 1592 |
return (rc, out, err) |
| 1593 |
|
| 1594 |
def modify_user(self): |
| 1595 |
cmd = [ |
| 1596 |
self.module.get_bin_path('pw', True), |
| 1597 |
'usermod', |
| 1598 |
'-n', |
| 1599 |
self.name |
| 1600 |
] |
| 1601 |
cmd_len = len(cmd) |
| 1602 |
info = self.user_info() |
| 1603 |
|
| 1604 |
if self.uid is not None and info[2] != int(self.uid): |
| 1605 |
cmd.append('-u') |
| 1606 |
cmd.append(self.uid) |
| 1607 |
|
| 1608 |
if self.non_unique: |
| 1609 |
cmd.append('-o') |
| 1610 |
|
| 1611 |
if self.comment is not None and info[4] != self.comment: |
| 1612 |
cmd.append('-c') |
| 1613 |
cmd.append(self.comment) |
| 1614 |
|
| 1615 |
if self.home is not None: |
| 1616 |
# Skip home creation for placeholder directories (e.g., /nonexistent, /dev/null) |
| 1617 |
# These are conventions for system accounts and should not be created on disk |
| 1618 |
if (info[5] != self.home and self.move_home) or (info[5] not in PLACEHOLDER_HOME_DIRS and not os.path.exists(self.home) and self.create_home): |
| 1619 |
cmd.append('-m') |
| 1620 |
if info[5] != self.home: |
| 1621 |
cmd.append('-d') |
| 1622 |
cmd.append(self.home) |
| 1623 |
|
| 1624 |
if self.skeleton is not None: |
| 1625 |
cmd.append('-k') |
| 1626 |
cmd.append(self.skeleton) |
| 1627 |
|
| 1628 |
if self.umask is not None: |
| 1629 |
cmd.append('-K') |
| 1630 |
cmd.append('UMASK=' + self.umask) |
| 1631 |
|
| 1632 |
if self.group is not None: |
| 1633 |
if not self.group_exists(self.group): |
| 1634 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 1635 |
ginfo = self.group_info(self.group) |
| 1636 |
if info[3] != ginfo[2]: |
| 1637 |
cmd.append('-g') |
| 1638 |
cmd.append(self.group) |
| 1639 |
|
| 1640 |
if self.shell is not None and info[6] != self.shell: |
| 1641 |
cmd.append('-s') |
| 1642 |
cmd.append(self.shell) |
| 1643 |
|
| 1644 |
if self.login_class is not None: |
| 1645 |
# find current login class |
| 1646 |
user_login_class = None |
| 1647 |
if os.path.exists(self.SHADOWFILE) and os.access(self.SHADOWFILE, os.R_OK): |
| 1648 |
with open(self.SHADOWFILE, 'r') as f: |
| 1649 |
for line in f: |
| 1650 |
if line.startswith('%s:' % self.name): |
| 1651 |
user_login_class = line.split(':')[4] |
| 1652 |
|
| 1653 |
# act only if login_class change |
| 1654 |
if self.login_class != user_login_class: |
| 1655 |
cmd.append('-L') |
| 1656 |
cmd.append(self.login_class) |
| 1657 |
|
| 1658 |
if self.groups is not None: |
| 1659 |
current_groups = self.user_group_membership() |
| 1660 |
groups = self.get_groups_set(names_only=True) |
| 1661 |
|
| 1662 |
group_diff = set(current_groups).symmetric_difference(groups) |
| 1663 |
groups_need_mod = False |
| 1664 |
|
| 1665 |
if group_diff: |
| 1666 |
if self.append: |
| 1667 |
for g in groups: |
| 1668 |
if g in group_diff: |
| 1669 |
groups_need_mod = True |
| 1670 |
break |
| 1671 |
else: |
| 1672 |
groups_need_mod = True |
| 1673 |
|
| 1674 |
if groups_need_mod: |
| 1675 |
cmd.append('-G') |
| 1676 |
new_groups = groups |
| 1677 |
if self.append: |
| 1678 |
new_groups = groups | set(current_groups) |
| 1679 |
cmd.append(','.join(new_groups)) |
| 1680 |
|
| 1681 |
if self.expires is not None: |
| 1682 |
|
| 1683 |
current_expires = self.user_password()[1] or '0' |
| 1684 |
current_expires = int(current_expires) |
| 1685 |
|
| 1686 |
# If expiration is negative or zero and the current expiration is greater than zero, disable expiration. |
| 1687 |
# In OpenBSD, setting expiration to zero disables expiration. It does not expire the account. |
| 1688 |
if self.expires <= time.gmtime(0): |
| 1689 |
if current_expires > 0: |
| 1690 |
cmd.append('-e') |
| 1691 |
cmd.append('0') |
| 1692 |
else: |
| 1693 |
# Convert days since Epoch to seconds since Epoch as struct_time |
| 1694 |
current_expire_date = time.gmtime(current_expires) |
| 1695 |
|
| 1696 |
# Current expires is negative or we compare year, month, and day only |
| 1697 |
if current_expires <= 0 or current_expire_date[:3] != self.expires[:3]: |
| 1698 |
cmd.append('-e') |
| 1699 |
cmd.append(str(calendar.timegm(self.expires))) |
| 1700 |
|
| 1701 |
(rc, out, err) = (None, '', '') |
| 1702 |
|
| 1703 |
# modify the user if cmd will do anything |
| 1704 |
if cmd_len != len(cmd): |
| 1705 |
(rc, _out, _err) = self.execute_command(cmd) |
| 1706 |
out += _out |
| 1707 |
err += _err |
| 1708 |
|
| 1709 |
if rc is not None and rc != 0: |
| 1710 |
self.module.fail_json(name=self.name, msg=err, rc=rc) |
| 1711 |
|
| 1712 |
# we have to set the password in a second command |
| 1713 |
if self.update_password == 'always' and self.password is not None and info[1].lstrip('*LOCKED*') != self.password.lstrip('*LOCKED*'): |
| 1714 |
cmd = [ |
| 1715 |
self.module.get_bin_path('chpass', True), |
| 1716 |
'-p', |
| 1717 |
self.password, |
| 1718 |
self.name |
| 1719 |
] |
| 1720 |
_rc, _out, _err = self.execute_command(cmd) |
| 1721 |
if rc is None: |
| 1722 |
rc = _rc |
| 1723 |
out += _out |
| 1724 |
err += _err |
| 1725 |
|
| 1726 |
# we have to lock/unlock the password in a distinct command |
| 1727 |
_rc, _out, _err = self._handle_lock() |
| 1728 |
if rc is None: |
| 1729 |
rc = _rc |
| 1730 |
out += _out |
| 1731 |
err += _err |
| 1732 |
|
| 1733 |
return (rc, out, err) |
| 1734 |
|
| 1735 |
|
| 1736 |
class DragonFlyBsdUser(FreeBsdUser): |
| 1737 |
""" |
| 1738 |
This is a DragonFlyBSD User manipulation class - it inherits the |
| 1739 |
FreeBsdUser class behaviors, such as using the pw command to |
| 1740 |
manipulate the user database, followed by the chpass command |
| 1741 |
to change the password. |
| 1742 |
""" |
| 1743 |
|
| 1744 |
platform = 'DragonFly' |
| 1745 |
|
| 1746 |
|
| 1747 |
class OpenBSDUser(User): |
| 1748 |
""" |
| 1749 |
This is a OpenBSD User manipulation class. |
| 1750 |
Main differences are that OpenBSD:- |
| 1751 |
- has no concept of "system" account. |
| 1752 |
- has no force delete user |
| 1753 |
|
| 1754 |
This overrides the following methods from the generic class:- |
| 1755 |
- create_user() |
| 1756 |
- remove_user() |
| 1757 |
- modify_user() |
| 1758 |
""" |
| 1759 |
|
| 1760 |
platform = 'OpenBSD' |
| 1761 |
distribution = None |
| 1762 |
SHADOWFILE = '/etc/master.passwd' |
| 1763 |
|
| 1764 |
def create_user(self): |
| 1765 |
cmd = [self.module.get_bin_path('useradd', True)] |
| 1766 |
|
| 1767 |
if self.uid is not None: |
| 1768 |
cmd.append('-u') |
| 1769 |
cmd.append(self.uid) |
| 1770 |
|
| 1771 |
if self.non_unique: |
| 1772 |
cmd.append('-o') |
| 1773 |
|
| 1774 |
if self.group is not None: |
| 1775 |
if not self.group_exists(self.group): |
| 1776 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 1777 |
cmd.append('-g') |
| 1778 |
cmd.append(self.group) |
| 1779 |
|
| 1780 |
if self.groups is not None: |
| 1781 |
groups = self.get_groups_set() |
| 1782 |
cmd.append('-G') |
| 1783 |
cmd.append(','.join(groups)) |
| 1784 |
|
| 1785 |
if self.comment is not None: |
| 1786 |
cmd.append('-c') |
| 1787 |
cmd.append(self.comment) |
| 1788 |
|
| 1789 |
if self.home is not None: |
| 1790 |
cmd.append('-d') |
| 1791 |
cmd.append(self.home) |
| 1792 |
|
| 1793 |
if self.shell is not None: |
| 1794 |
cmd.append('-s') |
| 1795 |
cmd.append(self.shell) |
| 1796 |
|
| 1797 |
if self.login_class is not None: |
| 1798 |
cmd.append('-L') |
| 1799 |
cmd.append(self.login_class) |
| 1800 |
|
| 1801 |
if self.password is not None and self.password != '*': |
| 1802 |
cmd.append('-p') |
| 1803 |
cmd.append(self.password) |
| 1804 |
|
| 1805 |
if self.create_home: |
| 1806 |
cmd.append('-m') |
| 1807 |
|
| 1808 |
if self.skeleton is not None: |
| 1809 |
cmd.append('-k') |
| 1810 |
cmd.append(self.skeleton) |
| 1811 |
|
| 1812 |
if self.umask is not None: |
| 1813 |
cmd.append('-K') |
| 1814 |
cmd.append('UMASK=' + self.umask) |
| 1815 |
|
| 1816 |
if self.inactive is not None: |
| 1817 |
cmd.append('-f') |
| 1818 |
cmd.append(self.inactive) |
| 1819 |
if self.uid_min is not None: |
| 1820 |
cmd.append('-K') |
| 1821 |
cmd.append('UID_MIN=' + str(self.uid_min)) |
| 1822 |
|
| 1823 |
if self.uid_max is not None: |
| 1824 |
cmd.append('-K') |
| 1825 |
cmd.append('UID_MAX=' + str(self.uid_max)) |
| 1826 |
|
| 1827 |
cmd.append(self.name) |
| 1828 |
return self.execute_command(cmd) |
| 1829 |
|
| 1830 |
def remove_user_userdel(self): |
| 1831 |
cmd = [self.module.get_bin_path('userdel', True)] |
| 1832 |
if self.remove: |
| 1833 |
cmd.append('-r') |
| 1834 |
cmd.append(self.name) |
| 1835 |
return self.execute_command(cmd) |
| 1836 |
|
| 1837 |
def modify_user(self): |
| 1838 |
cmd = [self.module.get_bin_path('usermod', True)] |
| 1839 |
info = self.user_info() |
| 1840 |
|
| 1841 |
if self.uid is not None and info[2] != int(self.uid): |
| 1842 |
cmd.append('-u') |
| 1843 |
cmd.append(self.uid) |
| 1844 |
|
| 1845 |
if self.non_unique: |
| 1846 |
cmd.append('-o') |
| 1847 |
|
| 1848 |
if self.group is not None: |
| 1849 |
if not self.group_exists(self.group): |
| 1850 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 1851 |
ginfo = self.group_info(self.group) |
| 1852 |
if info[3] != ginfo[2]: |
| 1853 |
cmd.append('-g') |
| 1854 |
cmd.append(self.group) |
| 1855 |
|
| 1856 |
if self.groups is not None: |
| 1857 |
current_groups = self.user_group_membership() |
| 1858 |
groups_need_mod = False |
| 1859 |
groups_option = '-S' |
| 1860 |
groups = [] |
| 1861 |
|
| 1862 |
if self.groups == '': |
| 1863 |
if current_groups and not self.append: |
| 1864 |
groups_need_mod = True |
| 1865 |
else: |
| 1866 |
groups = self.get_groups_set(names_only=True) |
| 1867 |
group_diff = set(current_groups).symmetric_difference(groups) |
| 1868 |
|
| 1869 |
if group_diff: |
| 1870 |
if self.append: |
| 1871 |
for g in groups: |
| 1872 |
if g in group_diff: |
| 1873 |
groups_option = '-G' |
| 1874 |
groups_need_mod = True |
| 1875 |
break |
| 1876 |
else: |
| 1877 |
groups_need_mod = True |
| 1878 |
|
| 1879 |
if groups_need_mod: |
| 1880 |
cmd.append(groups_option) |
| 1881 |
cmd.append(','.join(groups)) |
| 1882 |
|
| 1883 |
if self.comment is not None and info[4] != self.comment: |
| 1884 |
cmd.append('-c') |
| 1885 |
cmd.append(self.comment) |
| 1886 |
|
| 1887 |
if self.home is not None and info[5] != self.home: |
| 1888 |
if self.move_home: |
| 1889 |
cmd.append('-m') |
| 1890 |
cmd.append('-d') |
| 1891 |
cmd.append(self.home) |
| 1892 |
|
| 1893 |
if self.shell is not None and info[6] != self.shell: |
| 1894 |
cmd.append('-s') |
| 1895 |
cmd.append(self.shell) |
| 1896 |
|
| 1897 |
if self.inactive is not None: |
| 1898 |
cmd.append('-f') |
| 1899 |
cmd.append(self.inactive) |
| 1900 |
|
| 1901 |
if self.login_class is not None: |
| 1902 |
# find current login class |
| 1903 |
user_login_class = None |
| 1904 |
userinfo_cmd = [self.module.get_bin_path('userinfo', True), self.name] |
| 1905 |
(rc, out, err) = self.execute_command(userinfo_cmd, obey_checkmode=False) |
| 1906 |
|
| 1907 |
for line in out.splitlines(): |
| 1908 |
tokens = line.split() |
| 1909 |
|
| 1910 |
if tokens[0] == 'class' and len(tokens) == 2: |
| 1911 |
user_login_class = tokens[1] |
| 1912 |
|
| 1913 |
# act only if login_class change |
| 1914 |
if self.login_class != user_login_class: |
| 1915 |
cmd.append('-L') |
| 1916 |
cmd.append(self.login_class) |
| 1917 |
|
| 1918 |
if self.password_lock and not info[1].startswith('*'): |
| 1919 |
cmd.append('-Z') |
| 1920 |
elif self.password_lock is False and info[1].startswith('*'): |
| 1921 |
cmd.append('-U') |
| 1922 |
|
| 1923 |
if self.update_password == 'always' and self.password is not None \ |
| 1924 |
and self.password != '*' and info[1] != self.password: |
| 1925 |
cmd.append('-p') |
| 1926 |
cmd.append(self.password) |
| 1927 |
|
| 1928 |
# skip if no changes to be made |
| 1929 |
if len(cmd) == 1: |
| 1930 |
return (None, '', '') |
| 1931 |
|
| 1932 |
cmd.append(self.name) |
| 1933 |
return self.execute_command(cmd) |
| 1934 |
|
| 1935 |
|
| 1936 |
class NetBSDUser(User): |
| 1937 |
""" |
| 1938 |
This is a NetBSD User manipulation class. |
| 1939 |
Main differences are that NetBSD:- |
| 1940 |
- has no concept of "system" account. |
| 1941 |
- has no force delete user |
| 1942 |
|
| 1943 |
|
| 1944 |
This overrides the following methods from the generic class:- |
| 1945 |
- create_user() |
| 1946 |
- remove_user() |
| 1947 |
- modify_user() |
| 1948 |
""" |
| 1949 |
|
| 1950 |
platform = 'NetBSD' |
| 1951 |
distribution = None |
| 1952 |
SHADOWFILE = '/etc/master.passwd' |
| 1953 |
|
| 1954 |
def create_user(self): |
| 1955 |
cmd = [self.module.get_bin_path('useradd', True)] |
| 1956 |
|
| 1957 |
if self.uid is not None: |
| 1958 |
cmd.append('-u') |
| 1959 |
cmd.append(self.uid) |
| 1960 |
|
| 1961 |
if self.non_unique: |
| 1962 |
cmd.append('-o') |
| 1963 |
|
| 1964 |
if self.group is not None: |
| 1965 |
if not self.group_exists(self.group): |
| 1966 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 1967 |
cmd.append('-g') |
| 1968 |
cmd.append(self.group) |
| 1969 |
|
| 1970 |
if self.groups is not None: |
| 1971 |
groups = self.get_groups_set() |
| 1972 |
if len(groups) > 16: |
| 1973 |
self.module.fail_json(msg="Too many groups (%d) NetBSD allows for 16 max." % len(groups)) |
| 1974 |
cmd.append('-G') |
| 1975 |
cmd.append(','.join(groups)) |
| 1976 |
|
| 1977 |
if self.comment is not None: |
| 1978 |
cmd.append('-c') |
| 1979 |
cmd.append(self.comment) |
| 1980 |
|
| 1981 |
if self.home is not None: |
| 1982 |
cmd.append('-d') |
| 1983 |
cmd.append(self.home) |
| 1984 |
|
| 1985 |
if self.shell is not None: |
| 1986 |
cmd.append('-s') |
| 1987 |
cmd.append(self.shell) |
| 1988 |
|
| 1989 |
if self.login_class is not None: |
| 1990 |
cmd.append('-L') |
| 1991 |
cmd.append(self.login_class) |
| 1992 |
|
| 1993 |
if self.password is not None: |
| 1994 |
cmd.append('-p') |
| 1995 |
cmd.append(self.password) |
| 1996 |
|
| 1997 |
if self.inactive is not None: |
| 1998 |
cmd.append('-f') |
| 1999 |
cmd.append(self.inactive) |
| 2000 |
|
| 2001 |
if self.create_home: |
| 2002 |
cmd.append('-m') |
| 2003 |
|
| 2004 |
if self.skeleton is not None: |
| 2005 |
cmd.append('-k') |
| 2006 |
cmd.append(self.skeleton) |
| 2007 |
|
| 2008 |
if self.umask is not None: |
| 2009 |
cmd.append('-K') |
| 2010 |
cmd.append('UMASK=' + self.umask) |
| 2011 |
|
| 2012 |
if self.uid_min is not None: |
| 2013 |
cmd.append('-K') |
| 2014 |
cmd.append('UID_MIN=' + str(self.uid_min)) |
| 2015 |
|
| 2016 |
if self.uid_max is not None: |
| 2017 |
cmd.append('-K') |
| 2018 |
cmd.append('UID_MAX=' + str(self.uid_max)) |
| 2019 |
|
| 2020 |
cmd.append(self.name) |
| 2021 |
return self.execute_command(cmd) |
| 2022 |
|
| 2023 |
def remove_user_userdel(self): |
| 2024 |
cmd = [self.module.get_bin_path('userdel', True)] |
| 2025 |
if self.remove: |
| 2026 |
cmd.append('-r') |
| 2027 |
cmd.append(self.name) |
| 2028 |
return self.execute_command(cmd) |
| 2029 |
|
| 2030 |
def modify_user(self): |
| 2031 |
cmd = [self.module.get_bin_path('usermod', True)] |
| 2032 |
info = self.user_info() |
| 2033 |
|
| 2034 |
if self.uid is not None and info[2] != int(self.uid): |
| 2035 |
cmd.append('-u') |
| 2036 |
cmd.append(self.uid) |
| 2037 |
|
| 2038 |
if self.non_unique: |
| 2039 |
cmd.append('-o') |
| 2040 |
|
| 2041 |
if self.group is not None: |
| 2042 |
if not self.group_exists(self.group): |
| 2043 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 2044 |
ginfo = self.group_info(self.group) |
| 2045 |
if info[3] != ginfo[2]: |
| 2046 |
cmd.append('-g') |
| 2047 |
cmd.append(self.group) |
| 2048 |
|
| 2049 |
if self.groups is not None: |
| 2050 |
current_groups = self.user_group_membership() |
| 2051 |
groups_need_mod = False |
| 2052 |
groups = [] |
| 2053 |
|
| 2054 |
if self.groups == '': |
| 2055 |
if current_groups and not self.append: |
| 2056 |
groups_need_mod = True |
| 2057 |
else: |
| 2058 |
groups = self.get_groups_set(names_only=True) |
| 2059 |
group_diff = set(current_groups).symmetric_difference(groups) |
| 2060 |
|
| 2061 |
if group_diff: |
| 2062 |
if self.append: |
| 2063 |
for g in groups: |
| 2064 |
if g in group_diff: |
| 2065 |
groups = set(current_groups).union(groups) |
| 2066 |
groups_need_mod = True |
| 2067 |
break |
| 2068 |
else: |
| 2069 |
groups_need_mod = True |
| 2070 |
|
| 2071 |
if groups_need_mod: |
| 2072 |
if len(groups) > 16: |
| 2073 |
self.module.fail_json(msg="Too many groups (%d) NetBSD allows for 16 max." % len(groups)) |
| 2074 |
cmd.append('-G') |
| 2075 |
cmd.append(','.join(groups)) |
| 2076 |
|
| 2077 |
if self.comment is not None and info[4] != self.comment: |
| 2078 |
cmd.append('-c') |
| 2079 |
cmd.append(self.comment) |
| 2080 |
|
| 2081 |
if self.home is not None and info[5] != self.home: |
| 2082 |
if self.move_home: |
| 2083 |
cmd.append('-m') |
| 2084 |
cmd.append('-d') |
| 2085 |
cmd.append(self.home) |
| 2086 |
|
| 2087 |
if self.shell is not None and info[6] != self.shell: |
| 2088 |
cmd.append('-s') |
| 2089 |
cmd.append(self.shell) |
| 2090 |
|
| 2091 |
if self.login_class is not None: |
| 2092 |
cmd.append('-L') |
| 2093 |
cmd.append(self.login_class) |
| 2094 |
|
| 2095 |
if self.inactive is not None: |
| 2096 |
cmd.append('-f') |
| 2097 |
cmd.append(self.inactive) |
| 2098 |
|
| 2099 |
if self.update_password == 'always' and self.password is not None and info[1] != self.password: |
| 2100 |
cmd.append('-p') |
| 2101 |
cmd.append(self.password) |
| 2102 |
|
| 2103 |
if self.password_lock and not info[1].startswith('*LOCKED*'): |
| 2104 |
cmd.append('-C yes') |
| 2105 |
elif self.password_lock is False and info[1].startswith('*LOCKED*'): |
| 2106 |
cmd.append('-C no') |
| 2107 |
|
| 2108 |
# skip if no changes to be made |
| 2109 |
if len(cmd) == 1: |
| 2110 |
return (None, '', '') |
| 2111 |
|
| 2112 |
cmd.append(self.name) |
| 2113 |
return self.execute_command(cmd) |
| 2114 |
|
| 2115 |
|
| 2116 |
class SunOS(User): |
| 2117 |
""" |
| 2118 |
This is a SunOS User manipulation class - The main difference between |
| 2119 |
this class and the generic user class is that Solaris-type distros |
| 2120 |
don't support the concept of a "system" account and we need to |
| 2121 |
edit the /etc/shadow file manually to set a password. (Ugh) |
| 2122 |
|
| 2123 |
This overrides the following methods from the generic class:- |
| 2124 |
- create_user() |
| 2125 |
- remove_user() |
| 2126 |
- modify_user() |
| 2127 |
- user_info() |
| 2128 |
""" |
| 2129 |
|
| 2130 |
platform = 'SunOS' |
| 2131 |
distribution = None |
| 2132 |
SHADOWFILE = '/etc/shadow' |
| 2133 |
USER_ATTR = '/etc/user_attr' |
| 2134 |
|
| 2135 |
def get_password_defaults(self): |
| 2136 |
# Read password aging defaults |
| 2137 |
try: |
| 2138 |
minweeks = '' |
| 2139 |
maxweeks = '' |
| 2140 |
warnweeks = '' |
| 2141 |
with open("/etc/default/passwd", 'r') as f: |
| 2142 |
for line in f: |
| 2143 |
line = line.strip() |
| 2144 |
if (line.startswith('#') or line == ''): |
| 2145 |
continue |
| 2146 |
m = re.match(r'^([^#]*)#(.*)$', line) |
| 2147 |
if m: # The line contains a hash / comment |
| 2148 |
line = m.group(1) |
| 2149 |
key, value = line.split('=') |
| 2150 |
if key == "MINWEEKS": |
| 2151 |
minweeks = value.rstrip('\n') |
| 2152 |
elif key == "MAXWEEKS": |
| 2153 |
maxweeks = value.rstrip('\n') |
| 2154 |
elif key == "WARNWEEKS": |
| 2155 |
warnweeks = value.rstrip('\n') |
| 2156 |
except Exception as err: |
| 2157 |
self.module.fail_json(msg="failed to read /etc/default/passwd: %s" % to_native(err)) |
| 2158 |
|
| 2159 |
return (minweeks, maxweeks, warnweeks) |
| 2160 |
|
| 2161 |
def remove_user(self): |
| 2162 |
cmd = [self.module.get_bin_path('userdel', True)] |
| 2163 |
if self.remove: |
| 2164 |
cmd.append('-r') |
| 2165 |
cmd.append(self.name) |
| 2166 |
|
| 2167 |
return self.execute_command(cmd) |
| 2168 |
|
| 2169 |
def create_user(self): |
| 2170 |
cmd = [self.module.get_bin_path('useradd', True)] |
| 2171 |
|
| 2172 |
if self.uid is not None: |
| 2173 |
cmd.append('-u') |
| 2174 |
cmd.append(self.uid) |
| 2175 |
|
| 2176 |
if self.non_unique: |
| 2177 |
cmd.append('-o') |
| 2178 |
|
| 2179 |
if self.group is not None: |
| 2180 |
if not self.group_exists(self.group): |
| 2181 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 2182 |
cmd.append('-g') |
| 2183 |
cmd.append(self.group) |
| 2184 |
|
| 2185 |
if self.groups is not None: |
| 2186 |
groups = self.get_groups_set() |
| 2187 |
cmd.append('-G') |
| 2188 |
cmd.append(','.join(groups)) |
| 2189 |
|
| 2190 |
if self.comment is not None: |
| 2191 |
cmd.append('-c') |
| 2192 |
cmd.append(self.comment) |
| 2193 |
|
| 2194 |
if self.home is not None: |
| 2195 |
cmd.append('-d') |
| 2196 |
cmd.append(self.home) |
| 2197 |
|
| 2198 |
if self.shell is not None: |
| 2199 |
cmd.append('-s') |
| 2200 |
cmd.append(self.shell) |
| 2201 |
|
| 2202 |
if self.create_home: |
| 2203 |
cmd.append('-m') |
| 2204 |
|
| 2205 |
if self.skeleton is not None: |
| 2206 |
cmd.append('-k') |
| 2207 |
cmd.append(self.skeleton) |
| 2208 |
|
| 2209 |
if self.umask is not None: |
| 2210 |
cmd.append('-K') |
| 2211 |
cmd.append('UMASK=' + self.umask) |
| 2212 |
|
| 2213 |
if self.profile is not None: |
| 2214 |
cmd.append('-P') |
| 2215 |
cmd.append(self.profile) |
| 2216 |
|
| 2217 |
if self.authorization is not None: |
| 2218 |
cmd.append('-A') |
| 2219 |
cmd.append(self.authorization) |
| 2220 |
|
| 2221 |
if self.role is not None: |
| 2222 |
cmd.append('-R') |
| 2223 |
cmd.append(self.role) |
| 2224 |
|
| 2225 |
if self.inactive is not None: |
| 2226 |
cmd.append('-f') |
| 2227 |
cmd.append(self.inactive) |
| 2228 |
if self.uid_min is not None: |
| 2229 |
cmd.append('-K') |
| 2230 |
cmd.append('UID_MIN=' + str(self.uid_min)) |
| 2231 |
|
| 2232 |
if self.uid_max is not None: |
| 2233 |
cmd.append('-K') |
| 2234 |
cmd.append('UID_MAX=' + str(self.uid_max)) |
| 2235 |
|
| 2236 |
cmd.append(self.name) |
| 2237 |
|
| 2238 |
(rc, out, err) = self.execute_command(cmd) |
| 2239 |
if rc is not None and rc != 0: |
| 2240 |
self.module.fail_json(name=self.name, msg=err, rc=rc) |
| 2241 |
|
| 2242 |
if not self.module.check_mode: |
| 2243 |
# we have to set the password by editing the /etc/shadow file |
| 2244 |
if self.password is not None: |
| 2245 |
self.backup_shadow() |
| 2246 |
minweeks, maxweeks, warnweeks = self.get_password_defaults() |
| 2247 |
try: |
| 2248 |
lines = [] |
| 2249 |
with open(self.SHADOWFILE, 'rb') as f: |
| 2250 |
for line in f: |
| 2251 |
line = to_native(line, errors='surrogate_or_strict') |
| 2252 |
fields = line.strip().split(':') |
| 2253 |
if not fields[0] == self.name: |
| 2254 |
lines.append(line) |
| 2255 |
continue |
| 2256 |
fields[1] = self.password |
| 2257 |
fields[2] = str(int(time.time() // 86400)) |
| 2258 |
if minweeks: |
| 2259 |
try: |
| 2260 |
fields[3] = str(int(minweeks) * 7) |
| 2261 |
except ValueError: |
| 2262 |
# mirror solaris, which allows for any value in this field, and ignores anything that is not an int. |
| 2263 |
pass |
| 2264 |
if maxweeks: |
| 2265 |
try: |
| 2266 |
fields[4] = str(int(maxweeks) * 7) |
| 2267 |
except ValueError: |
| 2268 |
# mirror solaris, which allows for any value in this field, and ignores anything that is not an int. |
| 2269 |
pass |
| 2270 |
if warnweeks: |
| 2271 |
try: |
| 2272 |
fields[5] = str(int(warnweeks) * 7) |
| 2273 |
except ValueError: |
| 2274 |
# mirror solaris, which allows for any value in this field, and ignores anything that is not an int. |
| 2275 |
pass |
| 2276 |
line = ':'.join(fields) |
| 2277 |
lines.append('%s\n' % line) |
| 2278 |
with open(self.SHADOWFILE, 'w+') as f: |
| 2279 |
f.writelines(lines) |
| 2280 |
except Exception as err: |
| 2281 |
self.module.fail_json(msg="failed to update users password: %s" % to_native(err)) |
| 2282 |
|
| 2283 |
return (rc, out, err) |
| 2284 |
|
| 2285 |
def modify_user_usermod(self): |
| 2286 |
cmd = [self.module.get_bin_path('usermod', True)] |
| 2287 |
cmd_len = len(cmd) |
| 2288 |
info = self.user_info() |
| 2289 |
|
| 2290 |
if self.uid is not None and info[2] != int(self.uid): |
| 2291 |
cmd.append('-u') |
| 2292 |
cmd.append(self.uid) |
| 2293 |
|
| 2294 |
if self.non_unique: |
| 2295 |
cmd.append('-o') |
| 2296 |
|
| 2297 |
if self.group is not None: |
| 2298 |
if not self.group_exists(self.group): |
| 2299 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 2300 |
ginfo = self.group_info(self.group) |
| 2301 |
if info[3] != ginfo[2]: |
| 2302 |
cmd.append('-g') |
| 2303 |
cmd.append(self.group) |
| 2304 |
|
| 2305 |
if self.groups is not None: |
| 2306 |
current_groups = self.user_group_membership() |
| 2307 |
groups = self.get_groups_set(names_only=True) |
| 2308 |
group_diff = set(current_groups).symmetric_difference(groups) |
| 2309 |
groups_need_mod = False |
| 2310 |
|
| 2311 |
if group_diff: |
| 2312 |
if self.append: |
| 2313 |
for g in groups: |
| 2314 |
if g in group_diff: |
| 2315 |
groups_need_mod = True |
| 2316 |
break |
| 2317 |
else: |
| 2318 |
groups_need_mod = True |
| 2319 |
|
| 2320 |
if groups_need_mod: |
| 2321 |
cmd.append('-G') |
| 2322 |
new_groups = groups |
| 2323 |
if self.append: |
| 2324 |
new_groups.update(current_groups) |
| 2325 |
cmd.append(','.join(new_groups)) |
| 2326 |
|
| 2327 |
if self.comment is not None and info[4] != self.comment: |
| 2328 |
cmd.append('-c') |
| 2329 |
cmd.append(self.comment) |
| 2330 |
|
| 2331 |
if self.home is not None and info[5] != self.home: |
| 2332 |
if self.move_home: |
| 2333 |
cmd.append('-m') |
| 2334 |
cmd.append('-d') |
| 2335 |
cmd.append(self.home) |
| 2336 |
|
| 2337 |
if self.shell is not None and info[6] != self.shell: |
| 2338 |
cmd.append('-s') |
| 2339 |
cmd.append(self.shell) |
| 2340 |
|
| 2341 |
if self.profile is not None and info[7] != self.profile: |
| 2342 |
cmd.append('-P') |
| 2343 |
cmd.append(self.profile) |
| 2344 |
|
| 2345 |
if self.authorization is not None and info[8] != self.authorization: |
| 2346 |
cmd.append('-A') |
| 2347 |
cmd.append(self.authorization) |
| 2348 |
|
| 2349 |
if self.role is not None and info[9] != self.role: |
| 2350 |
cmd.append('-R') |
| 2351 |
cmd.append(self.role) |
| 2352 |
|
| 2353 |
if self.inactive is not None: |
| 2354 |
cmd.append('-f') |
| 2355 |
cmd.append(self.inactive) |
| 2356 |
|
| 2357 |
# modify the user if cmd will do anything |
| 2358 |
if cmd_len != len(cmd): |
| 2359 |
cmd.append(self.name) |
| 2360 |
(rc, out, err) = self.execute_command(cmd) |
| 2361 |
if rc is not None and rc != 0: |
| 2362 |
self.module.fail_json(name=self.name, msg=err, rc=rc) |
| 2363 |
else: |
| 2364 |
(rc, out, err) = (None, '', '') |
| 2365 |
|
| 2366 |
# we have to set the password by editing the /etc/shadow file |
| 2367 |
if self.update_password == 'always' and self.password is not None and info[1] != self.password: |
| 2368 |
self.backup_shadow() |
| 2369 |
(rc, out, err) = (0, '', '') |
| 2370 |
if not self.module.check_mode: |
| 2371 |
minweeks, maxweeks, warnweeks = self.get_password_defaults() |
| 2372 |
try: |
| 2373 |
lines = [] |
| 2374 |
with open(self.SHADOWFILE, 'rb') as f: |
| 2375 |
for line in f: |
| 2376 |
line = to_native(line, errors='surrogate_or_strict') |
| 2377 |
fields = line.strip().split(':') |
| 2378 |
if not fields[0] == self.name: |
| 2379 |
lines.append(line) |
| 2380 |
continue |
| 2381 |
fields[1] = self.password |
| 2382 |
fields[2] = str(int(time.time() // 86400)) |
| 2383 |
if minweeks: |
| 2384 |
fields[3] = str(int(minweeks) * 7) |
| 2385 |
if maxweeks: |
| 2386 |
fields[4] = str(int(maxweeks) * 7) |
| 2387 |
if warnweeks: |
| 2388 |
fields[5] = str(int(warnweeks) * 7) |
| 2389 |
line = ':'.join(fields) |
| 2390 |
lines.append('%s\n' % line) |
| 2391 |
with open(self.SHADOWFILE, 'w+') as f: |
| 2392 |
f.writelines(lines) |
| 2393 |
rc = 0 |
| 2394 |
except Exception as err: |
| 2395 |
self.module.fail_json(msg="failed to update users password: %s" % to_native(err)) |
| 2396 |
|
| 2397 |
return (rc, out, err) |
| 2398 |
|
| 2399 |
def user_info(self): |
| 2400 |
info = super(SunOS, self).user_info() |
| 2401 |
if info: |
| 2402 |
info += self._user_attr_info() |
| 2403 |
return info |
| 2404 |
|
| 2405 |
def _user_attr_info(self): |
| 2406 |
info = [''] * 3 |
| 2407 |
with open(self.USER_ATTR, 'r') as file_handler: |
| 2408 |
for line in file_handler: |
| 2409 |
lines = line.strip().split('::::') |
| 2410 |
if lines[0] == self.name: |
| 2411 |
tmp = dict(x.split('=') for x in lines[1].split(';')) |
| 2412 |
info[0] = tmp.get('profiles', '') |
| 2413 |
info[1] = tmp.get('auths', '') |
| 2414 |
info[2] = tmp.get('roles', '') |
| 2415 |
return info |
| 2416 |
|
| 2417 |
|
| 2418 |
class DarwinUser(User): |
| 2419 |
""" |
| 2420 |
This is a Darwin macOS User manipulation class. |
| 2421 |
Main differences are that Darwin:- |
| 2422 |
- Handles accounts in a database managed by dscl(1) |
| 2423 |
- Has no useradd/groupadd |
| 2424 |
- Does not create home directories |
| 2425 |
- User password must be cleartext |
| 2426 |
- UID must be given |
| 2427 |
- System users must ben under 500 |
| 2428 |
|
| 2429 |
This overrides the following methods from the generic class:- |
| 2430 |
- user_exists() |
| 2431 |
- create_user() |
| 2432 |
- remove_user() |
| 2433 |
- modify_user() |
| 2434 |
""" |
| 2435 |
platform = 'Darwin' |
| 2436 |
distribution = None |
| 2437 |
SHADOWFILE = None |
| 2438 |
|
| 2439 |
dscl_directory = '.' |
| 2440 |
|
| 2441 |
fields = [ |
| 2442 |
('comment', 'RealName'), |
| 2443 |
('home', 'NFSHomeDirectory'), |
| 2444 |
('shell', 'UserShell'), |
| 2445 |
('uid', 'UniqueID'), |
| 2446 |
('group', 'PrimaryGroupID'), |
| 2447 |
('hidden', 'IsHidden'), |
| 2448 |
] |
| 2449 |
|
| 2450 |
def __init__(self, module): |
| 2451 |
|
| 2452 |
super(DarwinUser, self).__init__(module) |
| 2453 |
|
| 2454 |
# make the user hidden if option is set or defer to system option |
| 2455 |
if self.hidden is None: |
| 2456 |
if self.system: |
| 2457 |
self.hidden = 1 |
| 2458 |
elif self.hidden: |
| 2459 |
self.hidden = 1 |
| 2460 |
else: |
| 2461 |
self.hidden = 0 |
| 2462 |
|
| 2463 |
# add hidden to processing if set |
| 2464 |
if self.hidden is not None: |
| 2465 |
self.fields.append(('hidden', 'IsHidden')) |
| 2466 |
|
| 2467 |
def _get_dscl(self): |
| 2468 |
return [self.module.get_bin_path('dscl', True), self.dscl_directory] |
| 2469 |
|
| 2470 |
def _list_user_groups(self): |
| 2471 |
cmd = self._get_dscl() |
| 2472 |
cmd += ['-search', '/Groups', 'GroupMembership', self.name] |
| 2473 |
(rc, out, err) = self.execute_command(cmd, obey_checkmode=False) |
| 2474 |
groups = [] |
| 2475 |
for line in out.splitlines(): |
| 2476 |
if line.startswith(' ') or line.startswith(')'): |
| 2477 |
continue |
| 2478 |
groups.append(line.split()[0]) |
| 2479 |
return groups |
| 2480 |
|
| 2481 |
def _get_user_property(self, property): |
| 2482 |
"""Return user PROPERTY as given my dscl(1) read or None if not found.""" |
| 2483 |
cmd = self._get_dscl() |
| 2484 |
cmd += ['-read', '/Users/%s' % self.name, property] |
| 2485 |
(rc, out, err) = self.execute_command(cmd, obey_checkmode=False) |
| 2486 |
if rc != 0: |
| 2487 |
return None |
| 2488 |
# from dscl(1) |
| 2489 |
# if property contains embedded spaces, the list will instead be |
| 2490 |
# displayed one entry per line, starting on the line after the key. |
| 2491 |
lines = out.splitlines() |
| 2492 |
# sys.stderr.write('*** |%s| %s -> %s\n' % (property, out, lines)) |
| 2493 |
if len(lines) == 1: |
| 2494 |
return lines[0].split(': ')[1] |
| 2495 |
if len(lines) > 2: |
| 2496 |
return '\n'.join([lines[1].strip()] + lines[2:]) |
| 2497 |
if len(lines) == 2: |
| 2498 |
return lines[1].strip() |
| 2499 |
return None |
| 2500 |
|
| 2501 |
def _get_next_uid(self, system=None): |
| 2502 |
""" |
| 2503 |
Return the next available uid. If system=True, then |
| 2504 |
uid should be below of 500, if possible. |
| 2505 |
""" |
| 2506 |
cmd = self._get_dscl() |
| 2507 |
cmd += ['-list', '/Users', 'UniqueID'] |
| 2508 |
(rc, out, err) = self.execute_command(cmd, obey_checkmode=False) |
| 2509 |
if rc != 0: |
| 2510 |
self.module.fail_json( |
| 2511 |
msg="Unable to get the next available uid", |
| 2512 |
rc=rc, |
| 2513 |
out=out, |
| 2514 |
err=err |
| 2515 |
) |
| 2516 |
|
| 2517 |
max_uid = 0 |
| 2518 |
max_system_uid = 0 |
| 2519 |
for line in out.splitlines(): |
| 2520 |
current_uid = int(line.split(' ')[-1]) |
| 2521 |
if max_uid < current_uid: |
| 2522 |
max_uid = current_uid |
| 2523 |
if max_system_uid < current_uid and current_uid < 500: |
| 2524 |
max_system_uid = current_uid |
| 2525 |
|
| 2526 |
if system and (0 < max_system_uid < 499): |
| 2527 |
return max_system_uid + 1 |
| 2528 |
return max_uid + 1 |
| 2529 |
|
| 2530 |
def _change_user_password(self): |
| 2531 |
"""Change password for SELF.NAME against SELF.PASSWORD. |
| 2532 |
|
| 2533 |
Please note that password must be cleartext. |
| 2534 |
""" |
| 2535 |
# some documentation on how is stored passwords on OSX: |
| 2536 |
# http://null-byte.wonderhowto.com/how-to/hack-mac-os-x-lion-passwords-0130036/ |
| 2537 |
# http://pastebin.com/RYqxi7Ca |
| 2538 |
# on OSX 10.8+ hash is SALTED-SHA512-PBKDF2 |
| 2539 |
# https://passlib.readthedocs.io/en/stable/lib/passlib.hash.pbkdf2_digest.html |
| 2540 |
# https://gist.github.com/nueh/8252572 |
| 2541 |
cmd = self._get_dscl() |
| 2542 |
if self.password: |
| 2543 |
cmd += ['-passwd', '/Users/%s' % self.name, self.password] |
| 2544 |
else: |
| 2545 |
cmd += ['-create', '/Users/%s' % self.name, 'Password', '*'] |
| 2546 |
(rc, out, err) = self.execute_command(cmd) |
| 2547 |
if rc != 0: |
| 2548 |
self.module.fail_json(msg='Error when changing password', err=err, out=out, rc=rc) |
| 2549 |
return (rc, out, err) |
| 2550 |
|
| 2551 |
def _make_group_numerical(self): |
| 2552 |
"""Convert SELF.GROUP to is stringed numerical value suitable for dscl.""" |
| 2553 |
if self.group is None: |
| 2554 |
self.group = 'nogroup' |
| 2555 |
try: |
| 2556 |
self.group = grp.getgrnam(self.group).gr_gid |
| 2557 |
except KeyError: |
| 2558 |
self.module.fail_json(msg='Group "%s" not found. Try to create it first using "group" module.' % self.group) |
| 2559 |
# We need to pass a string to dscl |
| 2560 |
self.group = str(self.group) |
| 2561 |
|
| 2562 |
def __modify_group(self, group, action): |
| 2563 |
"""Add or remove SELF.NAME to or from GROUP depending on ACTION. |
| 2564 |
ACTION can be 'add' or 'remove' otherwise 'remove' is assumed. """ |
| 2565 |
if action == 'add': |
| 2566 |
option = '-a' |
| 2567 |
else: |
| 2568 |
option = '-d' |
| 2569 |
cmd = ['dseditgroup', '-o', 'edit', option, self.name, '-t', 'user', group] |
| 2570 |
(rc, out, err) = self.execute_command(cmd) |
| 2571 |
if rc != 0: |
| 2572 |
self.module.fail_json(msg='Cannot %s user "%s" to group "%s".' |
| 2573 |
% (action, self.name, group), err=err, out=out, rc=rc) |
| 2574 |
return (rc, out, err) |
| 2575 |
|
| 2576 |
def _modify_group(self): |
| 2577 |
"""Add or remove SELF.NAME to or from GROUP depending on ACTION. |
| 2578 |
ACTION can be 'add' or 'remove' otherwise 'remove' is assumed. """ |
| 2579 |
|
| 2580 |
rc = 0 |
| 2581 |
out = '' |
| 2582 |
err = '' |
| 2583 |
changed = False |
| 2584 |
|
| 2585 |
current = set(self._list_user_groups()) |
| 2586 |
if self.groups is not None: |
| 2587 |
target = self.get_groups_set(names_only=True) |
| 2588 |
else: |
| 2589 |
target = set([]) |
| 2590 |
|
| 2591 |
if self.append is False: |
| 2592 |
for remove in current - target: |
| 2593 |
(_rc, _out, _err) = self.__modify_group(remove, 'delete') |
| 2594 |
rc += rc |
| 2595 |
out += _out |
| 2596 |
err += _err |
| 2597 |
changed = True |
| 2598 |
|
| 2599 |
for add in target - current: |
| 2600 |
(_rc, _out, _err) = self.__modify_group(add, 'add') |
| 2601 |
rc += _rc |
| 2602 |
out += _out |
| 2603 |
err += _err |
| 2604 |
changed = True |
| 2605 |
|
| 2606 |
return (rc, out, err, changed) |
| 2607 |
|
| 2608 |
def _update_system_user(self): |
| 2609 |
"""Hide or show user on login window according SELF.SYSTEM. |
| 2610 |
|
| 2611 |
Returns 0 if a change has been made, None otherwise.""" |
| 2612 |
|
| 2613 |
plist_file = '/Library/Preferences/com.apple.loginwindow.plist' |
| 2614 |
|
| 2615 |
# http://support.apple.com/kb/HT5017?viewlocale=en_US |
| 2616 |
cmd = ['defaults', 'read', plist_file, 'HiddenUsersList'] |
| 2617 |
(rc, out, err) = self.execute_command(cmd, obey_checkmode=False) |
| 2618 |
# returned value is |
| 2619 |
# ( |
| 2620 |
# "_userA", |
| 2621 |
# "_UserB", |
| 2622 |
# userc |
| 2623 |
# ) |
| 2624 |
hidden_users = [] |
| 2625 |
for x in out.splitlines()[1:-1]: |
| 2626 |
try: |
| 2627 |
x = x.split('"')[1] |
| 2628 |
except IndexError: |
| 2629 |
x = x.strip() |
| 2630 |
hidden_users.append(x) |
| 2631 |
|
| 2632 |
if self.system: |
| 2633 |
if self.name not in hidden_users: |
| 2634 |
cmd = ['defaults', 'write', plist_file, 'HiddenUsersList', '-array-add', self.name] |
| 2635 |
(rc, out, err) = self.execute_command(cmd) |
| 2636 |
if rc != 0: |
| 2637 |
self.module.fail_json(msg='Cannot user "%s" to hidden user list.' % self.name, err=err, out=out, rc=rc) |
| 2638 |
return 0 |
| 2639 |
else: |
| 2640 |
if self.name in hidden_users: |
| 2641 |
del (hidden_users[hidden_users.index(self.name)]) |
| 2642 |
|
| 2643 |
cmd = ['defaults', 'write', plist_file, 'HiddenUsersList', '-array'] + hidden_users |
| 2644 |
(rc, out, err) = self.execute_command(cmd) |
| 2645 |
if rc != 0: |
| 2646 |
self.module.fail_json(msg='Cannot remove user "%s" from hidden user list.' % self.name, err=err, out=out, rc=rc) |
| 2647 |
return 0 |
| 2648 |
|
| 2649 |
def user_exists(self): |
| 2650 |
"""Check is SELF.NAME is a known user on the system.""" |
| 2651 |
cmd = self._get_dscl() |
| 2652 |
cmd += ['-read', '/Users/%s' % self.name, 'UniqueID'] |
| 2653 |
(rc, out, err) = self.execute_command(cmd, obey_checkmode=False) |
| 2654 |
return rc == 0 |
| 2655 |
|
| 2656 |
def remove_user(self): |
| 2657 |
"""Delete SELF.NAME. If SELF.FORCE is true, remove its home directory.""" |
| 2658 |
info = self.user_info() |
| 2659 |
|
| 2660 |
cmd = self._get_dscl() |
| 2661 |
cmd += ['-delete', '/Users/%s' % self.name] |
| 2662 |
(rc, out, err) = self.execute_command(cmd) |
| 2663 |
|
| 2664 |
if rc != 0: |
| 2665 |
self.module.fail_json(msg='Cannot delete user "%s".' % self.name, err=err, out=out, rc=rc) |
| 2666 |
|
| 2667 |
if self.force: |
| 2668 |
if os.path.exists(info[5]): |
| 2669 |
shutil.rmtree(info[5]) |
| 2670 |
out += "Removed %s" % info[5] |
| 2671 |
|
| 2672 |
return (rc, out, err) |
| 2673 |
|
| 2674 |
def create_user(self, command_name='dscl'): |
| 2675 |
cmd = self._get_dscl() |
| 2676 |
cmd += ['-create', '/Users/%s' % self.name] |
| 2677 |
(rc, out, err) = self.execute_command(cmd) |
| 2678 |
if rc != 0: |
| 2679 |
self.module.fail_json(msg='Cannot create user "%s".' % self.name, err=err, out=out, rc=rc) |
| 2680 |
|
| 2681 |
# Make the Gecos (alias display name) default to username |
| 2682 |
if self.comment is None: |
| 2683 |
self.comment = self.name |
| 2684 |
|
| 2685 |
# Make user group default to 'staff' |
| 2686 |
if self.group is None: |
| 2687 |
self.group = 'staff' |
| 2688 |
|
| 2689 |
self._make_group_numerical() |
| 2690 |
if self.uid is None: |
| 2691 |
self.uid = str(self._get_next_uid(self.system)) |
| 2692 |
|
| 2693 |
# Homedir is not created by default |
| 2694 |
if self.create_home: |
| 2695 |
if self.home is None: |
| 2696 |
self.home = '/Users/%s' % self.name |
| 2697 |
if not self.module.check_mode: |
| 2698 |
if not os.path.exists(self.home): |
| 2699 |
os.makedirs(self.home) |
| 2700 |
self.chown_homedir(int(self.uid), int(self.group), self.home) |
| 2701 |
|
| 2702 |
# dscl sets shell to /usr/bin/false when UserShell is not specified |
| 2703 |
# so set the shell to /bin/bash when the user is not a system user |
| 2704 |
if not self.system and self.shell is None: |
| 2705 |
self.shell = '/bin/bash' |
| 2706 |
|
| 2707 |
for field in self.fields: |
| 2708 |
if field[0] in self.__dict__ and self.__dict__[field[0]]: |
| 2709 |
|
| 2710 |
cmd = self._get_dscl() |
| 2711 |
cmd += ['-create', '/Users/%s' % self.name, field[1], self.__dict__[field[0]]] |
| 2712 |
(rc, _out, _err) = self.execute_command(cmd) |
| 2713 |
if rc != 0: |
| 2714 |
self.module.fail_json(msg='Cannot add property "%s" to user "%s".' % (field[0], self.name), err=err, out=out, rc=rc) |
| 2715 |
|
| 2716 |
out += _out |
| 2717 |
err += _err |
| 2718 |
if rc != 0: |
| 2719 |
return (rc, _out, _err) |
| 2720 |
|
| 2721 |
(rc, _out, _err) = self._change_user_password() |
| 2722 |
out += _out |
| 2723 |
err += _err |
| 2724 |
|
| 2725 |
self._update_system_user() |
| 2726 |
# here we don't care about change status since it is a creation, |
| 2727 |
# thus changed is always true. |
| 2728 |
if self.groups: |
| 2729 |
(rc, _out, _err, changed) = self._modify_group() |
| 2730 |
out += _out |
| 2731 |
err += _err |
| 2732 |
return (rc, out, err) |
| 2733 |
|
| 2734 |
def modify_user(self): |
| 2735 |
changed = None |
| 2736 |
out = '' |
| 2737 |
err = '' |
| 2738 |
|
| 2739 |
if self.group: |
| 2740 |
self._make_group_numerical() |
| 2741 |
|
| 2742 |
for field in self.fields: |
| 2743 |
if field[0] in self.__dict__ and self.__dict__[field[0]]: |
| 2744 |
current = self._get_user_property(field[1]) |
| 2745 |
if current is None or current != to_text(self.__dict__[field[0]]): |
| 2746 |
cmd = self._get_dscl() |
| 2747 |
cmd += ['-create', '/Users/%s' % self.name, field[1], self.__dict__[field[0]]] |
| 2748 |
(rc, _out, _err) = self.execute_command(cmd) |
| 2749 |
if rc != 0: |
| 2750 |
self.module.fail_json( |
| 2751 |
msg='Cannot update property "%s" for user "%s".' |
| 2752 |
% (field[0], self.name), err=err, out=out, rc=rc) |
| 2753 |
changed = rc |
| 2754 |
out += _out |
| 2755 |
err += _err |
| 2756 |
if self.update_password == 'always' and self.password is not None: |
| 2757 |
(rc, _out, _err) = self._change_user_password() |
| 2758 |
out += _out |
| 2759 |
err += _err |
| 2760 |
changed = rc |
| 2761 |
|
| 2762 |
if self.groups: |
| 2763 |
(rc, _out, _err, _changed) = self._modify_group() |
| 2764 |
out += _out |
| 2765 |
err += _err |
| 2766 |
|
| 2767 |
if _changed is True: |
| 2768 |
changed = rc |
| 2769 |
|
| 2770 |
rc = self._update_system_user() |
| 2771 |
if rc == 0: |
| 2772 |
changed = rc |
| 2773 |
|
| 2774 |
return (changed, out, err) |
| 2775 |
|
| 2776 |
|
| 2777 |
class AIX(User): |
| 2778 |
""" |
| 2779 |
This is a AIX User manipulation class. |
| 2780 |
|
| 2781 |
This overrides the following methods from the generic class:- |
| 2782 |
- create_user() |
| 2783 |
- remove_user() |
| 2784 |
- modify_user() |
| 2785 |
- parse_shadow_file() |
| 2786 |
""" |
| 2787 |
|
| 2788 |
platform = 'AIX' |
| 2789 |
distribution = None |
| 2790 |
SHADOWFILE = '/etc/security/passwd' |
| 2791 |
|
| 2792 |
def remove_user(self): |
| 2793 |
cmd = [self.module.get_bin_path('userdel', True)] |
| 2794 |
if self.remove: |
| 2795 |
cmd.append('-r') |
| 2796 |
cmd.append(self.name) |
| 2797 |
|
| 2798 |
return self.execute_command(cmd) |
| 2799 |
|
| 2800 |
def create_user_useradd(self, command_name='useradd'): |
| 2801 |
cmd = [self.module.get_bin_path(command_name, True)] |
| 2802 |
|
| 2803 |
if self.uid is not None: |
| 2804 |
cmd.append('-u') |
| 2805 |
cmd.append(self.uid) |
| 2806 |
|
| 2807 |
if self.group is not None: |
| 2808 |
if not self.group_exists(self.group): |
| 2809 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 2810 |
cmd.append('-g') |
| 2811 |
cmd.append(self.group) |
| 2812 |
|
| 2813 |
if self.groups is not None and len(self.groups): |
| 2814 |
groups = self.get_groups_set() |
| 2815 |
cmd.append('-G') |
| 2816 |
cmd.append(','.join(groups)) |
| 2817 |
|
| 2818 |
if self.comment is not None: |
| 2819 |
cmd.append('-c') |
| 2820 |
cmd.append(self.comment) |
| 2821 |
|
| 2822 |
if self.home is not None: |
| 2823 |
cmd.append('-d') |
| 2824 |
cmd.append(self.home) |
| 2825 |
|
| 2826 |
if self.shell is not None: |
| 2827 |
cmd.append('-s') |
| 2828 |
cmd.append(self.shell) |
| 2829 |
|
| 2830 |
if self.create_home: |
| 2831 |
cmd.append('-m') |
| 2832 |
|
| 2833 |
if self.skeleton is not None: |
| 2834 |
cmd.append('-k') |
| 2835 |
cmd.append(self.skeleton) |
| 2836 |
|
| 2837 |
if self.umask is not None: |
| 2838 |
cmd.append('-K') |
| 2839 |
cmd.append('UMASK=' + self.umask) |
| 2840 |
|
| 2841 |
if self.inactive is not None: |
| 2842 |
cmd.append('-f') |
| 2843 |
cmd.append(self.inactive) |
| 2844 |
if self.uid_min is not None: |
| 2845 |
cmd.append('-K') |
| 2846 |
cmd.append('UID_MIN=' + str(self.uid_min)) |
| 2847 |
|
| 2848 |
if self.uid_max is not None: |
| 2849 |
cmd.append('-K') |
| 2850 |
cmd.append('UID_MAX=' + str(self.uid_max)) |
| 2851 |
|
| 2852 |
cmd.append(self.name) |
| 2853 |
(rc, out, err) = self.execute_command(cmd) |
| 2854 |
|
| 2855 |
# set password with chpasswd |
| 2856 |
if self.password is not None: |
| 2857 |
cmd = [] |
| 2858 |
cmd.append(self.module.get_bin_path('chpasswd', True)) |
| 2859 |
cmd.append('-e') |
| 2860 |
cmd.append('-c') |
| 2861 |
self.execute_command(cmd, data="%s:%s" % (self.name, self.password)) |
| 2862 |
|
| 2863 |
return (rc, out, err) |
| 2864 |
|
| 2865 |
def modify_user_usermod(self): |
| 2866 |
cmd = [self.module.get_bin_path('usermod', True)] |
| 2867 |
info = self.user_info() |
| 2868 |
|
| 2869 |
if self.uid is not None and info[2] != int(self.uid): |
| 2870 |
cmd.append('-u') |
| 2871 |
cmd.append(self.uid) |
| 2872 |
|
| 2873 |
if self.group is not None: |
| 2874 |
if not self.group_exists(self.group): |
| 2875 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 2876 |
ginfo = self.group_info(self.group) |
| 2877 |
if info[3] != ginfo[2]: |
| 2878 |
cmd.append('-g') |
| 2879 |
cmd.append(self.group) |
| 2880 |
|
| 2881 |
if self.groups is not None: |
| 2882 |
current_groups = self.user_group_membership() |
| 2883 |
groups_need_mod = False |
| 2884 |
groups = [] |
| 2885 |
|
| 2886 |
if self.groups == '': |
| 2887 |
if current_groups and not self.append: |
| 2888 |
groups_need_mod = True |
| 2889 |
else: |
| 2890 |
groups = self.get_groups_set(names_only=True) |
| 2891 |
group_diff = set(current_groups).symmetric_difference(groups) |
| 2892 |
|
| 2893 |
if group_diff: |
| 2894 |
if self.append: |
| 2895 |
for g in groups: |
| 2896 |
if g in group_diff: |
| 2897 |
groups_need_mod = True |
| 2898 |
break |
| 2899 |
else: |
| 2900 |
groups_need_mod = True |
| 2901 |
|
| 2902 |
if groups_need_mod: |
| 2903 |
cmd.append('-G') |
| 2904 |
cmd.append(','.join(groups)) |
| 2905 |
|
| 2906 |
if self.comment is not None and info[4] != self.comment: |
| 2907 |
cmd.append('-c') |
| 2908 |
cmd.append(self.comment) |
| 2909 |
|
| 2910 |
if self.home is not None and info[5] != self.home: |
| 2911 |
if self.move_home: |
| 2912 |
cmd.append('-m') |
| 2913 |
cmd.append('-d') |
| 2914 |
cmd.append(self.home) |
| 2915 |
|
| 2916 |
if self.shell is not None and info[6] != self.shell: |
| 2917 |
cmd.append('-s') |
| 2918 |
cmd.append(self.shell) |
| 2919 |
|
| 2920 |
if self.inactive is not None: |
| 2921 |
cmd.append('-f') |
| 2922 |
cmd.append(self.inactive) |
| 2923 |
|
| 2924 |
# skip if no changes to be made |
| 2925 |
if len(cmd) == 1: |
| 2926 |
(rc, out, err) = (None, '', '') |
| 2927 |
else: |
| 2928 |
cmd.append(self.name) |
| 2929 |
(rc, out, err) = self.execute_command(cmd) |
| 2930 |
|
| 2931 |
# set password with chpasswd |
| 2932 |
if self.update_password == 'always' and self.password is not None and info[1] != self.password: |
| 2933 |
cmd = [] |
| 2934 |
cmd.append(self.module.get_bin_path('chpasswd', True)) |
| 2935 |
cmd.append('-e') |
| 2936 |
cmd.append('-c') |
| 2937 |
(rc2, out2, err2) = self.execute_command(cmd, data="%s:%s" % (self.name, self.password)) |
| 2938 |
else: |
| 2939 |
(rc2, out2, err2) = (None, '', '') |
| 2940 |
|
| 2941 |
if rc is not None: |
| 2942 |
return (rc, out + out2, err + err2) |
| 2943 |
else: |
| 2944 |
return (rc2, out + out2, err + err2) |
| 2945 |
|
| 2946 |
def parse_shadow_file(self): |
| 2947 |
"""Example AIX shadowfile data: |
| 2948 |
nobody: |
| 2949 |
password = * |
| 2950 |
|
| 2951 |
operator1: |
| 2952 |
password = {ssha512}06$xxxxxxxxxxxx.... |
| 2953 |
lastupdate = 1549558094 |
| 2954 |
|
| 2955 |
test1: |
| 2956 |
password = * |
| 2957 |
lastupdate = 1553695126 |
| 2958 |
|
| 2959 |
""" |
| 2960 |
|
| 2961 |
b_name = to_bytes(self.name) |
| 2962 |
b_passwd = b'' |
| 2963 |
b_expires = b'' |
| 2964 |
if os.path.exists(self.SHADOWFILE) and os.access(self.SHADOWFILE, os.R_OK): |
| 2965 |
with open(self.SHADOWFILE, 'rb') as bf: |
| 2966 |
b_lines = bf.readlines() |
| 2967 |
|
| 2968 |
b_passwd_line = b'' |
| 2969 |
b_expires_line = b'' |
| 2970 |
try: |
| 2971 |
for index, b_line in enumerate(b_lines): |
| 2972 |
# Get password and lastupdate lines which come after the username |
| 2973 |
if b_line.startswith(b'%s:' % b_name): |
| 2974 |
b_passwd_line = b_lines[index + 1] |
| 2975 |
b_expires_line = b_lines[index + 2] |
| 2976 |
break |
| 2977 |
|
| 2978 |
# Sanity check the lines because sometimes both are not present |
| 2979 |
if b' = ' in b_passwd_line: |
| 2980 |
b_passwd = b_passwd_line.split(b' = ', 1)[-1].strip() |
| 2981 |
|
| 2982 |
if b' = ' in b_expires_line: |
| 2983 |
b_expires = b_expires_line.split(b' = ', 1)[-1].strip() |
| 2984 |
|
| 2985 |
except IndexError: |
| 2986 |
self.module.fail_json(msg='Failed to parse shadow file %s' % self.SHADOWFILE) |
| 2987 |
|
| 2988 |
passwd = to_native(b_passwd) |
| 2989 |
expires = to_native(b_expires) or -1 |
| 2990 |
return passwd, expires |
| 2991 |
|
| 2992 |
|
| 2993 |
class HPUX(User): |
| 2994 |
""" |
| 2995 |
This is a HP-UX User manipulation class. |
| 2996 |
|
| 2997 |
This overrides the following methods from the generic class:- |
| 2998 |
- create_user() |
| 2999 |
- remove_user() |
| 3000 |
- modify_user() |
| 3001 |
""" |
| 3002 |
|
| 3003 |
platform = 'HP-UX' |
| 3004 |
distribution = None |
| 3005 |
SHADOWFILE = '/etc/shadow' |
| 3006 |
|
| 3007 |
def create_user(self): |
| 3008 |
cmd = ['/usr/sam/lbin/useradd.sam'] |
| 3009 |
|
| 3010 |
if self.uid is not None: |
| 3011 |
cmd.append('-u') |
| 3012 |
cmd.append(self.uid) |
| 3013 |
|
| 3014 |
if self.non_unique: |
| 3015 |
cmd.append('-o') |
| 3016 |
|
| 3017 |
if self.group is not None: |
| 3018 |
if not self.group_exists(self.group): |
| 3019 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 3020 |
cmd.append('-g') |
| 3021 |
cmd.append(self.group) |
| 3022 |
|
| 3023 |
if self.groups is not None and len(self.groups): |
| 3024 |
groups = self.get_groups_set() |
| 3025 |
cmd.append('-G') |
| 3026 |
cmd.append(','.join(groups)) |
| 3027 |
|
| 3028 |
if self.comment is not None: |
| 3029 |
cmd.append('-c') |
| 3030 |
cmd.append(self.comment) |
| 3031 |
|
| 3032 |
if self.home is not None: |
| 3033 |
cmd.append('-d') |
| 3034 |
cmd.append(self.home) |
| 3035 |
|
| 3036 |
if self.shell is not None: |
| 3037 |
cmd.append('-s') |
| 3038 |
cmd.append(self.shell) |
| 3039 |
|
| 3040 |
if self.password is not None: |
| 3041 |
cmd.append('-p') |
| 3042 |
cmd.append(self.password) |
| 3043 |
|
| 3044 |
if self.create_home: |
| 3045 |
cmd.append('-m') |
| 3046 |
else: |
| 3047 |
cmd.append('-M') |
| 3048 |
|
| 3049 |
if self.system: |
| 3050 |
cmd.append('-r') |
| 3051 |
|
| 3052 |
cmd.append(self.name) |
| 3053 |
return self.execute_command(cmd) |
| 3054 |
|
| 3055 |
def remove_user(self): |
| 3056 |
cmd = ['/usr/sam/lbin/userdel.sam'] |
| 3057 |
if self.force: |
| 3058 |
cmd.append('-F') |
| 3059 |
if self.remove: |
| 3060 |
cmd.append('-r') |
| 3061 |
cmd.append(self.name) |
| 3062 |
return self.execute_command(cmd) |
| 3063 |
|
| 3064 |
def modify_user(self): |
| 3065 |
cmd = ['/usr/sam/lbin/usermod.sam'] |
| 3066 |
info = self.user_info() |
| 3067 |
|
| 3068 |
if self.uid is not None and info[2] != int(self.uid): |
| 3069 |
cmd.append('-u') |
| 3070 |
cmd.append(self.uid) |
| 3071 |
|
| 3072 |
if self.non_unique: |
| 3073 |
cmd.append('-o') |
| 3074 |
|
| 3075 |
if self.group is not None: |
| 3076 |
if not self.group_exists(self.group): |
| 3077 |
self.module.fail_json(msg="Group %s does not exist" % self.group) |
| 3078 |
ginfo = self.group_info(self.group) |
| 3079 |
if info[3] != ginfo[2]: |
| 3080 |
cmd.append('-g') |
| 3081 |
cmd.append(self.group) |
| 3082 |
|
| 3083 |
if self.groups is not None: |
| 3084 |
current_groups = self.user_group_membership() |
| 3085 |
groups_need_mod = False |
| 3086 |
groups = [] |
| 3087 |
|
| 3088 |
if self.groups == '': |
| 3089 |
if current_groups and not self.append: |
| 3090 |
groups_need_mod = True |
| 3091 |
else: |
| 3092 |
groups = self.get_groups_set(remove_existing=False, names_only=True) |
| 3093 |
group_diff = set(current_groups).symmetric_difference(groups) |
| 3094 |
|
| 3095 |
if group_diff: |
| 3096 |
if self.append: |
| 3097 |
for g in groups: |
| 3098 |
if g in group_diff: |
| 3099 |
groups_need_mod = True |
| 3100 |
break |
| 3101 |
else: |
| 3102 |
groups_need_mod = True |
| 3103 |
|
| 3104 |
if groups_need_mod: |
| 3105 |
cmd.append('-G') |
| 3106 |
new_groups = groups |
| 3107 |
if self.append: |
| 3108 |
new_groups = groups | set(current_groups) |
| 3109 |
cmd.append(','.join(new_groups)) |
| 3110 |
|
| 3111 |
if self.comment is not None and info[4] != self.comment: |
| 3112 |
cmd.append('-c') |
| 3113 |
cmd.append(self.comment) |
| 3114 |
|
| 3115 |
if self.home is not None and info[5] != self.home: |
| 3116 |
cmd.append('-d') |
| 3117 |
cmd.append(self.home) |
| 3118 |
if self.move_home: |
| 3119 |
cmd.append('-m') |
| 3120 |
|
| 3121 |
if self.shell is not None and info[6] != self.shell: |
| 3122 |
cmd.append('-s') |
| 3123 |
cmd.append(self.shell) |
| 3124 |
|
| 3125 |
if self.update_password == 'always' and self.password is not None and info[1] != self.password: |
| 3126 |
cmd.append('-F') |
| 3127 |
cmd.append('-p') |
| 3128 |
cmd.append(self.password) |
| 3129 |
|
| 3130 |
# skip if no changes to be made |
| 3131 |
if len(cmd) == 1: |
| 3132 |
return (None, '', '') |
| 3133 |
|
| 3134 |
cmd.append(self.name) |
| 3135 |
return self.execute_command(cmd) |
| 3136 |
|
| 3137 |
|
| 3138 |
class BusyBox(User): |
| 3139 |
""" |
| 3140 |
This is the BusyBox class for use on systems that have adduser, deluser, |
| 3141 |
and delgroup commands. It overrides the following methods: |
| 3142 |
- create_user() |
| 3143 |
- remove_user() |
| 3144 |
- modify_user() |
| 3145 |
""" |
| 3146 |
def _validate_shell(self): |
| 3147 |
if not self.shell: |
| 3148 |
return |
| 3149 |
|
| 3150 |
try: |
| 3151 |
with open("/etc/shells", "r") as f: |
| 3152 |
shells = [ |
| 3153 |
shell |
| 3154 |
for shell in (line.strip() for line in f) |
| 3155 |
if shell |
| 3156 |
and not shell.startswith("#") |
| 3157 |
] |
| 3158 |
except FileNotFoundError: |
| 3159 |
return |
| 3160 |
|
| 3161 |
if self.shell not in shells: |
| 3162 |
self.module.warn(f"'{self.shell}' is not listed as a valid shell on the remote host.") |
| 3163 |
|
| 3164 |
def _build_password_string(self, current_password=None): |
| 3165 |
""" |
| 3166 |
Build the appropriate password string based on the current password and |
| 3167 |
module parameters. |
| 3168 |
|
| 3169 |
This method will return '*' at a minimum to avoid creating an enabled |
| 3170 |
account with no password. |
| 3171 |
""" |
| 3172 |
lock = LOCK_INDICATOR if self.password_lock else '' |
| 3173 |
|
| 3174 |
# Order of precedence when choosing the password: |
| 3175 |
# 1. password from module parameters |
| 3176 |
# 2. current password |
| 3177 |
# 3. string to enable the account but without a password |
| 3178 |
password = '*' |
| 3179 |
if self.password is not None: |
| 3180 |
password = self.password |
| 3181 |
elif current_password: |
| 3182 |
password = current_password |
| 3183 |
if current_password == LOCK_INDICATOR: |
| 3184 |
# Special handling when the password is only a '!' to avoid |
| 3185 |
# unnecessary changes to the password to values like '!!' or '!*'. |
| 3186 |
lock = '' |
| 3187 |
elif current_password.startswith(LOCK_INDICATOR): |
| 3188 |
# Preserve the existing password but unlock the account even if |
| 3189 |
# no password hash was provided in the module parameters. |
| 3190 |
password = current_password.lstrip(LOCK_INDICATOR) |
| 3191 |
|
| 3192 |
return f'{lock}{password}' |
| 3193 |
|
| 3194 |
def create_user(self): |
| 3195 |
cmd = [self.module.get_bin_path('adduser', True)] |
| 3196 |
|
| 3197 |
self._validate_shell() |
| 3198 |
|
| 3199 |
cmd.append('-D') |
| 3200 |
|
| 3201 |
if self.uid is not None: |
| 3202 |
cmd.append('-u') |
| 3203 |
cmd.append(self.uid) |
| 3204 |
|
| 3205 |
if self.group is not None: |
| 3206 |
if not self.group_exists(self.group): |
| 3207 |
self.module.fail_json(msg=f'Group {self.group} does not exist') |
| 3208 |
|
| 3209 |
cmd.append('-G') |
| 3210 |
cmd.append(self.group) |
| 3211 |
|
| 3212 |
if self.comment is not None: |
| 3213 |
cmd.append('-g') |
| 3214 |
cmd.append(self.comment) |
| 3215 |
|
| 3216 |
if self.home is not None: |
| 3217 |
cmd.append('-h') |
| 3218 |
cmd.append(self.home) |
| 3219 |
|
| 3220 |
if self.shell is not None: |
| 3221 |
cmd.append('-s') |
| 3222 |
cmd.append(self.shell) |
| 3223 |
|
| 3224 |
if not self.create_home: |
| 3225 |
cmd.append('-H') |
| 3226 |
|
| 3227 |
if self.skeleton is not None: |
| 3228 |
cmd.append('-k') |
| 3229 |
cmd.append(self.skeleton) |
| 3230 |
|
| 3231 |
if self.umask is not None: |
| 3232 |
cmd.append('-K') |
| 3233 |
cmd.append('UMASK=' + self.umask) |
| 3234 |
|
| 3235 |
if self.system: |
| 3236 |
cmd.append('-S') |
| 3237 |
|
| 3238 |
if self.uid_min is not None: |
| 3239 |
cmd.append('-K') |
| 3240 |
cmd.append('UID_MIN=' + str(self.uid_min)) |
| 3241 |
|
| 3242 |
if self.uid_max is not None: |
| 3243 |
cmd.append('-K') |
| 3244 |
cmd.append('UID_MAX=' + str(self.uid_max)) |
| 3245 |
|
| 3246 |
cmd.append(self.name) |
| 3247 |
|
| 3248 |
rc, out, err = self.execute_command(cmd) |
| 3249 |
|
| 3250 |
if rc is not None and rc != 0: |
| 3251 |
self.module.fail_json(name=self.name, msg=err, rc=rc) |
| 3252 |
|
| 3253 |
cmd = [self.module.get_bin_path('chpasswd', True)] |
| 3254 |
cmd.append('--encrypted') |
| 3255 |
data = f'{self.name}:{self._build_password_string()}' |
| 3256 |
rc, out, err = self.execute_command(cmd, data=data) |
| 3257 |
|
| 3258 |
if rc is not None and rc != 0: |
| 3259 |
self.module.fail_json(name=self.name, msg=err, rc=rc) |
| 3260 |
|
| 3261 |
# Add to additional groups |
| 3262 |
if self.groups: |
| 3263 |
groups = self.get_groups_set() or set() |
| 3264 |
add_cmd_bin = self.module.get_bin_path('adduser', True) |
| 3265 |
for group in groups: |
| 3266 |
cmd = [add_cmd_bin, self.name, group] |
| 3267 |
rc, out, err = self.execute_command(cmd) |
| 3268 |
if rc is not None and rc != 0: |
| 3269 |
self.module.fail_json(name=self.name, msg=err, rc=rc) |
| 3270 |
|
| 3271 |
return rc, out, err |
| 3272 |
|
| 3273 |
def remove_user(self): |
| 3274 |
|
| 3275 |
cmd = [ |
| 3276 |
self.module.get_bin_path('deluser', True), |
| 3277 |
self.name |
| 3278 |
] |
| 3279 |
|
| 3280 |
if self.remove: |
| 3281 |
cmd.append('--remove-home') |
| 3282 |
|
| 3283 |
return self.execute_command(cmd) |
| 3284 |
|
| 3285 |
def modify_user(self): |
| 3286 |
current_groups = self.user_group_membership() |
| 3287 |
groups = [] |
| 3288 |
rc = None |
| 3289 |
out = '' |
| 3290 |
err = '' |
| 3291 |
user_info = self.user_info() |
| 3292 |
|
| 3293 |
if not user_info: |
| 3294 |
return rc, out, err |
| 3295 |
|
| 3296 |
gid = user_info[3] |
| 3297 |
if self.group is not None: |
| 3298 |
if not self.group_exists(self.group): |
| 3299 |
self.module.fail_json(msg=f'Group {self.group} does not exist') |
| 3300 |
|
| 3301 |
group_info = self.group_info(self.group) |
| 3302 |
if group_info: |
| 3303 |
gid = group_info[2] |
| 3304 |
|
| 3305 |
add_cmd_bin = self.module.get_bin_path('adduser', True) |
| 3306 |
remove_cmd_bin = self.module.get_bin_path('delgroup', True) |
| 3307 |
|
| 3308 |
self._validate_shell() |
| 3309 |
|
| 3310 |
# Manage group membership |
| 3311 |
if self.groups: |
| 3312 |
groups = self.get_groups_set() or set() |
| 3313 |
group_diff = set(current_groups).symmetric_difference(groups) |
| 3314 |
|
| 3315 |
if group_diff: |
| 3316 |
for g in groups: |
| 3317 |
if g in group_diff: |
| 3318 |
add_cmd = [add_cmd_bin, self.name, g] |
| 3319 |
rc, out, err = self.execute_command(add_cmd) |
| 3320 |
if rc is not None and rc != 0: |
| 3321 |
self.module.fail_json(name=self.name, msg=err, rc=rc) |
| 3322 |
|
| 3323 |
for g in group_diff: |
| 3324 |
if g not in groups and not self.append: |
| 3325 |
remove_cmd = [remove_cmd_bin, self.name, g] |
| 3326 |
rc, out, err = self.execute_command(remove_cmd) |
| 3327 |
if rc is not None and rc != 0: |
| 3328 |
self.module.fail_json(name=self.name, msg=err, rc=rc) |
| 3329 |
|
| 3330 |
# Manage password |
| 3331 |
current_password = to_native(user_info[1]) |
| 3332 |
new_password = self._build_password_string(current_password) |
| 3333 |
if self.update_password == 'always': |
| 3334 |
lock_status_mismatch = self.password_lock and not current_password.startswith('!') |
| 3335 |
password_changed = new_password != current_password |
| 3336 |
if lock_status_mismatch or password_changed: |
| 3337 |
cmd = [self.module.get_bin_path('chpasswd', True), '--encrypted'] |
| 3338 |
data = f'{self.name}:{new_password}' |
| 3339 |
rc, out, err = self.execute_command(cmd, data=data) |
| 3340 |
|
| 3341 |
if rc is not None and rc != 0: |
| 3342 |
self.module.fail_json(name=self.name, msg=err, rc=rc) |
| 3343 |
|
| 3344 |
# Move the home before rewriting /etc/passwd so usermod can still |
| 3345 |
# locate the current home directory contents. |
| 3346 |
if self.move_home and self.home is not None and user_info[5] != self.home: |
| 3347 |
usermod_bin = self.module.get_bin_path('usermod') |
| 3348 |
if usermod_bin is not None: |
| 3349 |
cmd = [usermod_bin, '-d', self.home, '-m', self.name] |
| 3350 |
rc, out, err = self.execute_command(cmd) |
| 3351 |
if rc is not None and rc != 0: |
| 3352 |
self.module.fail_json(name=self.name, msg=err, rc=rc) |
| 3353 |
|
| 3354 |
user_info = self.user_info() |
| 3355 |
else: |
| 3356 |
self.module.warn("usermod command not found, skipping home directory move") |
| 3357 |
|
| 3358 |
# Manage user settings |
| 3359 |
uid = user_info[2] |
| 3360 |
if self.uid is not None: |
| 3361 |
uid = self.uid |
| 3362 |
|
| 3363 |
passwd_entry = [ |
| 3364 |
self.name, |
| 3365 |
'x', |
| 3366 |
to_native(uid), |
| 3367 |
to_native(gid), |
| 3368 |
self.comment or user_info[4], |
| 3369 |
self.home or user_info[5], |
| 3370 |
self.shell or user_info[6], |
| 3371 |
] |
| 3372 |
|
| 3373 |
contents = [] |
| 3374 |
change = False |
| 3375 |
with open(self.PASSWORDFILE, 'r') as password_file: |
| 3376 |
for line in password_file: |
| 3377 |
if line.startswith('%s:' % self.name): |
| 3378 |
fields = line.strip().split(':') |
| 3379 |
if fields != passwd_entry: |
| 3380 |
change = True |
| 3381 |
line = ':'.join(passwd_entry) + '\n' |
| 3382 |
|
| 3383 |
contents.append(line) |
| 3384 |
|
| 3385 |
if change: |
| 3386 |
rc = 0 |
| 3387 |
if not self.module.check_mode: |
| 3388 |
tmpfd, tmpfile = tempfile.mkstemp(dir=self.module.tmpdir) |
| 3389 |
with os.fdopen(tmpfd, 'w') as f: |
| 3390 |
f.writelines(contents) |
| 3391 |
|
| 3392 |
self.module.backup_local(self.PASSWORDFILE) |
| 3393 |
self.module.atomic_move(tmpfile, self.PASSWORDFILE) |
| 3394 |
|
| 3395 |
return rc, out, err |
| 3396 |
|
| 3397 |
|
| 3398 |
class Alpine(BusyBox): |
| 3399 |
""" |
| 3400 |
This is the Alpine User manipulation class. It inherits the BusyBox class |
| 3401 |
behaviors such as using adduser and deluser commands. |
| 3402 |
""" |
| 3403 |
platform = 'Linux' |
| 3404 |
distribution = 'Alpine' |
| 3405 |
|
| 3406 |
|
| 3407 |
class Buildroot(BusyBox): |
| 3408 |
platform = 'Linux' |
| 3409 |
distribution = 'Buildroot' |
| 3410 |
|
| 3411 |
|
| 3412 |
def main(): |
| 3413 |
ssh_defaults = dict( |
| 3414 |
bits=0, |
| 3415 |
type='rsa', |
| 3416 |
passphrase=None, |
| 3417 |
comment='ansible-generated on %s' % socket.gethostname() |
| 3418 |
) |
| 3419 |
module = AnsibleModule( |
| 3420 |
argument_spec=dict( |
| 3421 |
state=dict(type='str', default='present', choices=['absent', 'present']), |
| 3422 |
name=dict(type='str', required=True, aliases=['user']), |
| 3423 |
uid=dict(type='int'), |
| 3424 |
non_unique=dict(type='bool', default=False), |
| 3425 |
group=dict(type='str'), |
| 3426 |
groups=dict(type='list', elements='str'), |
| 3427 |
comment=dict(type='str'), |
| 3428 |
home=dict(type='path'), |
| 3429 |
shell=dict(type='path'), |
| 3430 |
password=dict(type='str', no_log=True), |
| 3431 |
login_class=dict(type='str'), |
| 3432 |
password_expire_max=dict(type='int', no_log=False), |
| 3433 |
password_expire_min=dict(type='int', no_log=False), |
| 3434 |
password_expire_warn=dict(type='int', no_log=False), |
| 3435 |
# following options are specific to macOS |
| 3436 |
hidden=dict(type='bool'), |
| 3437 |
# following options are specific to selinux |
| 3438 |
seuser=dict(type='str'), |
| 3439 |
# following options are specific to userdel |
| 3440 |
force=dict(type='bool', default=False), |
| 3441 |
remove=dict(type='bool', default=False), |
| 3442 |
# following options are specific to useradd |
| 3443 |
create_home=dict(type='bool', default=True, aliases=['createhome']), |
| 3444 |
skeleton=dict(type='str'), |
| 3445 |
system=dict(type='bool', default=False), |
| 3446 |
# following options are specific to usermod |
| 3447 |
move_home=dict(type='bool', default=False), |
| 3448 |
append=dict(type='bool', default=False), |
| 3449 |
# following are specific to ssh key generation |
| 3450 |
generate_ssh_key=dict(type='bool'), |
| 3451 |
ssh_key_bits=dict(type='int', default=ssh_defaults['bits']), |
| 3452 |
ssh_key_type=dict(type='str', default=ssh_defaults['type']), |
| 3453 |
ssh_key_file=dict(type='path'), |
| 3454 |
ssh_key_comment=dict(type='str', default=ssh_defaults['comment']), |
| 3455 |
ssh_key_passphrase=dict(type='str', no_log=True), |
| 3456 |
update_password=dict(type='str', default='always', choices=['always', 'on_create'], no_log=False), |
| 3457 |
expires=dict(type='float'), |
| 3458 |
password_lock=dict(type='bool', no_log=False), |
| 3459 |
local=dict(type='bool'), |
| 3460 |
profile=dict(type='str'), |
| 3461 |
authorization=dict(type='str'), |
| 3462 |
role=dict(type='str'), |
| 3463 |
umask=dict(type='str'), |
| 3464 |
password_expire_account_disable=dict(type='int', no_log=False), |
| 3465 |
uid_min=dict(type='int'), |
| 3466 |
uid_max=dict(type='int'), |
| 3467 |
), |
| 3468 |
supports_check_mode=True, |
| 3469 |
required_if=[ |
| 3470 |
['append', True, ['groups']], |
| 3471 |
], |
| 3472 |
) |
| 3473 |
|
| 3474 |
user = User(module) |
| 3475 |
user.check_password_encrypted() |
| 3476 |
|
| 3477 |
if user.seuser is not None and not module.selinux_enabled(): |
| 3478 |
module.warn( |
| 3479 |
f"'seuser' is set to '{user.seuser}' but SELinux is not enabled on " |
| 3480 |
f"this system. The 'seuser' parameter will be ignored." |
| 3481 |
) |
| 3482 |
|
| 3483 |
module.debug('User instantiated - platform %s' % user.platform) |
| 3484 |
if user.distribution: |
| 3485 |
module.debug('User instantiated - distribution %s' % user.distribution) |
| 3486 |
|
| 3487 |
rc = None |
| 3488 |
out = '' |
| 3489 |
err = '' |
| 3490 |
result = {} |
| 3491 |
result['name'] = user.name |
| 3492 |
result['state'] = user.state |
| 3493 |
if user.state == 'absent': |
| 3494 |
if user.user_exists(): |
| 3495 |
if module.check_mode: |
| 3496 |
module.exit_json(changed=True) |
| 3497 |
(rc, out, err) = user.remove_user() |
| 3498 |
if rc != 0: |
| 3499 |
module.fail_json(name=user.name, msg=err, rc=rc) |
| 3500 |
result['force'] = user.force |
| 3501 |
result['remove'] = user.remove |
| 3502 |
elif user.state == 'present': |
| 3503 |
if not user.user_exists(): |
| 3504 |
if module.check_mode: |
| 3505 |
module.exit_json(changed=True) |
| 3506 |
|
| 3507 |
# Check to see if the provided home path contains parent directories |
| 3508 |
# that do not exist. |
| 3509 |
path_needs_parents = False |
| 3510 |
if user.home and user.create_home: |
| 3511 |
parent = os.path.dirname(user.home) |
| 3512 |
if not os.path.isdir(parent): |
| 3513 |
path_needs_parents = True |
| 3514 |
|
| 3515 |
(rc, out, err) = user.create_user() |
| 3516 |
|
| 3517 |
# If the home path had parent directories that needed to be created, |
| 3518 |
# make sure file permissions are correct in the created home directory. |
| 3519 |
if path_needs_parents: |
| 3520 |
info = user.user_info() |
| 3521 |
if info is not False: |
| 3522 |
user.chown_homedir(info[2], info[3], user.home) |
| 3523 |
|
| 3524 |
if module.check_mode: |
| 3525 |
result['system'] = user.name |
| 3526 |
else: |
| 3527 |
result['system'] = user.system |
| 3528 |
result['create_home'] = user.create_home |
| 3529 |
else: |
| 3530 |
# modify user (note: this function is check mode aware) |
| 3531 |
(rc, out, err) = user.modify_user() |
| 3532 |
result['append'] = user.append |
| 3533 |
result['move_home'] = user.move_home |
| 3534 |
if rc is not None and rc != 0: |
| 3535 |
module.fail_json(name=user.name, msg=err, rc=rc) |
| 3536 |
if user.password is not None: |
| 3537 |
result['password'] = 'NOT_LOGGING_PASSWORD' |
| 3538 |
|
| 3539 |
if rc is None: |
| 3540 |
result['changed'] = False |
| 3541 |
else: |
| 3542 |
result['changed'] = True |
| 3543 |
if out: |
| 3544 |
result['stdout'] = out |
| 3545 |
if err: |
| 3546 |
result['stderr'] = err |
| 3547 |
|
| 3548 |
if user.user_exists() and user.state == 'present': |
| 3549 |
info = user.user_info() |
| 3550 |
if info is False: |
| 3551 |
result['msg'] = "failed to look up user name: %s" % user.name |
| 3552 |
result['failed'] = True |
| 3553 |
result['uid'] = info[2] |
| 3554 |
result['group'] = info[3] |
| 3555 |
result['comment'] = info[4] |
| 3556 |
result['home'] = info[5] |
| 3557 |
result['shell'] = info[6] |
| 3558 |
result['groups'] = ','.join(user.user_group_membership()) |
| 3559 |
|
| 3560 |
# handle missing homedirs |
| 3561 |
info = user.user_info() |
| 3562 |
if user.home is None: |
| 3563 |
user.home = info[5] |
| 3564 |
if not os.path.exists(user.home) and user.home not in PLACEHOLDER_HOME_DIRS and user.create_home: |
| 3565 |
if not module.check_mode: |
| 3566 |
user.create_homedir(user.home) |
| 3567 |
user.chown_homedir(info[2], info[3], user.home) |
| 3568 |
result['changed'] = True |
| 3569 |
|
| 3570 |
# deal with ssh key |
| 3571 |
if user.sshkeygen: |
| 3572 |
# generate ssh key (note: this function is check mode aware) |
| 3573 |
(rc, out, err) = user.ssh_key_gen() |
| 3574 |
if rc is not None and rc != 0: |
| 3575 |
module.fail_json(name=user.name, msg=err, rc=rc) |
| 3576 |
if rc == 0: |
| 3577 |
result['changed'] = True |
| 3578 |
(rc, out, err) = user.ssh_key_fingerprint() |
| 3579 |
if rc == 0: |
| 3580 |
result['ssh_fingerprint'] = out.strip() |
| 3581 |
else: |
| 3582 |
result['ssh_fingerprint'] = err.strip() |
| 3583 |
result['ssh_key_file'] = user.get_ssh_key_path() |
| 3584 |
result['ssh_public_key'] = user.get_ssh_public_key() |
| 3585 |
|
| 3586 |
(rc, out, err) = user.set_password_expire() |
| 3587 |
if rc is None: |
| 3588 |
pass # target state reached, nothing to do |
| 3589 |
else: |
| 3590 |
if rc != 0: |
| 3591 |
module.fail_json(name=user.name, msg=err, rc=rc) |
| 3592 |
else: |
| 3593 |
result['changed'] = True |
| 3594 |
|
| 3595 |
module.exit_json(**result) |
| 3596 |
|
| 3597 |
|
| 3598 |
# import module snippets |
| 3599 |
if __name__ == '__main__': |
| 3600 |
main() |