Debian Codegraph @

ansible_collections/microsoft/ad/plugins/modules/user.ps1

raw
1 #!powershell
2
3 # Copyright: (c) 2023, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 #AnsibleRequires -CSharpUtil Ansible.AccessToken
7 #AnsibleRequires -CSharpUtil Ansible.Basic
8 #AnsibleRequires -PowerShell ..module_utils._ADObject
9
10 Function Test-Credential {
11 param(
12 [String]$Username,
13 [String]$Password,
14 [String]$Domain = $null
15 )
16 if (($Username.ToCharArray()) -contains [char]'@') {
17 # UserPrincipalName
18 $Domain = $null # force $Domain to be null, to prevent undefined behaviour, as a domain name is already included in the username
19 }
20 elseif (($Username.ToCharArray()) -contains [char]'\') {
21 # Pre Win2k Account Name
22 $Domain = ($Username -split '\\')[0]
23 $Username = ($Username -split '\\', 2)[-1]
24 } # If no domain provided, so maybe local user, or domain specified separately.
25
26 try {
27 ([Ansible.AccessToken.TokenUtil]::LogonUser($Username, $Domain, $Password, "Network", "Default")).Dispose()
28 return $true
29 }
30 catch [Ansible.AccessToken.Win32Exception] {
31 # following errors indicate the creds are correct but the user was
32 # unable to log on for other reasons, which we don't care about
33 $success_codes = @(
34 0x0000052F, # ERROR_ACCOUNT_RESTRICTION
35 0x00000530, # ERROR_INVALID_LOGON_HOURS
36 0x00000531, # ERROR_INVALID_WORKSTATION
37 0x00000569 # ERROR_LOGON_TYPE_GRANTED
38 )
39 $failed_codes = @(
40 0x0000052E, # ERROR_LOGON_FAILURE
41 0x00000532, # ERROR_PASSWORD_EXPIRED
42 0x00000701, # ERROR_ACCOUNT_EXPIRED
43 0x00000773, # ERROR_PASSWORD_MUST_CHANGE
44 0x00000533 # ERROR_ACCOUNT_DISABLED
45 )
46
47 if ($_.Exception.NativeErrorCode -in $failed_codes) {
48 return $false
49 }
50 elseif ($_.Exception.NativeErrorCode -in $success_codes) {
51 return $true
52 }
53 else {
54 # an unknown failure, reraise exception
55 throw $_
56 }
57 }
58 }
59
60 $setParams = @{
61 PropertyInfo = @(
62 [PSCustomObject]@{
63 Name = 'account_locked'
64 Option = @{
65 choices = @(, $false)
66 type = 'bool'
67 }
68 Attribute = 'LockedOut'
69 # We cannot lock a user and creating a user that is unlocked
70 # requires no action.
71 New = {}
72 Set = {
73 param($Module, $ADParams, $SetParams, $ADObject)
74
75 if ($ADObject.LockedOut) {
76 Unlock-ADAccount @ADParams -Identity $ADObject.ObjectGUID -WhatIf:$Module.CheckMode
77 $Module.Result.changed = $true
78 }
79
80 $Module.Diff.after.account_locked = $false
81 }
82 }
83
84 [PSCustomObject]@{
85 Name = 'city'
86 Option = @{ type = 'str' }
87 Attribute = 'City'
88 }
89
90 [PSCustomObject]@{
91 Name = 'company'
92 Option = @{ type = 'str' }
93 Attribute = 'company'
94 }
95
96 [PSCustomObject]@{
97 Name = 'country'
98 Option = @{ type = 'str' }
99 Attribute = 'Country'
100 }
101
102 [PSCustomObject]@{
103 Name = 'delegates'
104 Option = @{
105 aliases = 'principals_allowed_to_delegate'
106 type = 'add_remove_set'
107 }
108 Attribute = 'PrincipalsAllowedToDelegateToAccount'
109 DNLookup = $true
110 }
111
112 [PSCustomObject]@{
113 Name = 'email'
114 Option = @{ type = 'str' }
115 Attribute = 'EmailAddress'
116 }
117
118 [PSCustomObject]@{
119 Name = 'enabled'
120 Option = @{ type = 'bool' }
121 Attribute = 'Enabled'
122 }
123
124 [PSCustomObject]@{
125 Name = 'firstname'
126 Option = @{ type = 'str' }
127 Attribute = 'givenName'
128 }
129
130 [PSCustomObject]@{
131 Name = 'groups'
132 Option = @{
133 type = 'dict'
134 options = @{
135 add = @{ type = 'list'; elements = 'raw' }
136 remove = @{ type = 'list'; elements = 'raw' }
137 set = @{ type = 'list'; elements = 'raw' }
138 lookup_failure_action = @{
139 aliases = @('missing_behaviour')
140 choices = 'fail', 'ignore', 'warn'
141 default = 'fail'
142 type = 'str'
143 }
144 permissions_failure_action = @{
145 choices = 'fail', 'ignore', 'warn'
146 default = 'fail'
147 type = 'str'
148 }
149
150 }
151 }
152 }
153
154 [PSCustomObject]@{
155 Name = 'password'
156 Option = @{
157 no_log = $true
158 type = 'str'
159 }
160 New = {
161 param($Module, $ADParams, $NewParams)
162
163 $NewParams.AccountPassword = (ConvertTo-SecureString -AsPlainText -Force -String $module.Params.password)
164 $Module.Diff.after.password = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
165 }
166 Set = {
167 param($Module, $ADParams, $SetParams, $ADObject)
168
169 $Module.Diff.before.password = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
170
171 $changed = switch ($Module.Params.update_password) {
172 always { $true }
173 on_create { $false }
174 when_changed {
175 # Try and use the UPN but fallback to msDS-PrincipalName if none is defined
176 $username = $ADObject.UserPrincipalName
177 if (-not $username) {
178 $username = $ADObject['msDS-PrincipalName']
179 }
180
181 -not (Test-Credential -Username $username -Password $module.Params.password)
182 }
183 }
184
185 if (-not $changed) {
186 $Module.Diff.after.password = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
187 return
188 }
189
190 # -WhatIf was broken until Server 2016 and will set the
191 # password. Just avoid calling this in check mode.
192 if (-not $Module.CheckMode) {
193 $setParams = @{
194 Identity = $ADObject.ObjectGUID
195 Reset = $true
196 Confirm = $false
197 NewPassword = (ConvertTo-SecureString -AsPlainText -Force -String $module.Params.password)
198 }
199 Set-ADAccountPassword @setParams @ADParams
200 }
201
202 $Module.Diff.after.password = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER - changed'
203 $Module.Result.changed = $true
204 }
205 }
206
207 [PSCustomObject]@{
208 Name = 'password_expired'
209 Option = @{ type = 'bool' }
210 Attribute = 'PasswordExpired'
211 New = {
212 param($Module, $ADParams, $NewParams)
213
214 $NewParams.ChangePasswordAtLogon = $module.Params.password_expired
215 $Module.Diff.after.password_expired = $module.Params.password_expired
216 }
217 Set = {
218 param($Module, $ADParams, $SetParams, $ADObject)
219
220 if ($ADObject.PasswordExpired -ne $Module.Params.password_expired) {
221 $SetParams.ChangePasswordAtLogon = $Module.Params.password_expired
222 }
223
224 $Module.Diff.after.password_expired = $Module.Params.password_expired
225 }
226 }
227
228 [PSCustomObject]@{
229 Name = 'password_never_expires'
230 Option = @{ type = 'bool' }
231 Attribute = 'PasswordNeverExpires'
232 }
233
234 [PSCustomObject]@{
235 Name = 'postal_code'
236 Option = @{ type = 'str' }
237 Attribute = 'PostalCode'
238 }
239
240 [PSCustomObject]@{
241 Name = 'sam_account_name'
242 Option = @{ type = 'str' }
243 Attribute = 'sAMAccountName'
244 }
245
246 [PSCustomObject]@{
247 Name = 'spn'
248 Option = @{
249 aliases = 'spns'
250 type = 'dict'
251 options = @{
252 add = @{ type = 'list'; elements = 'str' }
253 remove = @{ type = 'list'; elements = 'str' }
254 set = @{ type = 'list'; elements = 'str' }
255 }
256 }
257 Attribute = 'ServicePrincipalNames'
258 New = {
259 param($Module, $ADParams, $NewParams)
260
261 $spns = @(
262 $Module.Params.spn.add
263 $Module.Params.spn.set
264 ) | Select-Object -Unique
265
266 $NewParams.ServicePrincipalNames = $spns
267 $Module.Diff.after.spn = $spns
268 }
269 Set = {
270 param($Module, $ADParams, $SetParams, $ADObject)
271
272 $desired = $Module.Params.spn
273 $compareParams = @{
274 Existing = $ADObject.ServicePrincipalNames
275 CaseInsensitive = $true
276 }
277 $res = Compare-AnsibleADIdempotentList @compareParams @desired
278 if ($res.Changed) {
279 $SetParams.ServicePrincipalNames = @{}
280 if ($res.ToAdd) {
281 $SetParams.ServicePrincipalNames.Add = $res.ToAdd
282 }
283 if ($res.ToRemove) {
284 $SetParams.ServicePrincipalNames.Remove = $res.ToRemove
285 }
286 }
287 $module.Diff.after.spn = @($res.Value | Sort-Object)
288 }
289 }
290
291 [PSCustomObject]@{
292 Name = 'state_province'
293 Option = @{ type = 'str' }
294 Attribute = 'State'
295 }
296
297 [PSCustomObject]@{
298 Name = 'street'
299 Option = @{ type = 'str' }
300 Attribute = 'StreetAddress'
301 }
302
303 [PSCustomObject]@{
304 Name = 'surname'
305 Option = @{
306 aliases = 'lastname'
307 type = 'str'
308 }
309 Attribute = 'Surname'
310 }
311
312 [PSCustomObject]@{
313 Name = 'update_password'
314 Option = @{
315 choices = 'always', 'on_create', 'when_changed'
316 default = 'always'
317 type = 'str'
318 }
319 }
320
321 [PSCustomObject]@{
322 Name = 'upn'
323 Option = @{ type = 'str' }
324 Attribute = 'userPrincipalName'
325 }
326
327 [PSCustomObject]@{
328 Name = 'user_cannot_change_password'
329 Option = @{ type = 'bool' }
330 Attribute = 'CannotChangePassword'
331 }
332 )
333 ModuleNoun = 'ADUser'
334 DefaultPath = {
335 param($Module, $ADParams)
336
337 $GUID_USERS_CONTAINER_W = 'A9D1CA15768811D1ADED00C04FD8D5CD'
338 $defaultNamingContext = (Get-ADRootDSE @ADParams -Properties defaultNamingContext).defaultNamingContext
339
340 Get-ADObject @ADParams -Identity $defaultNamingContext -Properties wellKnownObjects |
341 Select-Object -ExpandProperty wellKnownObjects |
342 Where-Object { $_.StartsWith("B:32:$($GUID_USERS_CONTAINER_W):") } |
343 ForEach-Object Substring 38
344 }
345 ExtraProperties = @(
346 # Used for password when checking if the password is valid
347 'msDS-PrincipalName'
348 )
349 PreAction = {
350 param ($Module, $ADParams, $ADObject)
351
352 if (
353 $Module.Params.state -eq 'present' -and
354 $null -eq $ADObject -and
355 $null -eq $Module.Params.enabled
356 ) {
357 $Module.Params.enabled = -not ([String]::IsNullOrWhiteSpace($Module.Params.password))
358 }
359 }
360 PostAction = {
361 param($Module, $ADParams, $ADObject)
362
363 if ($ADObject) {
364 $Module.Result.sid = $ADObject.SID.Value
365 }
366 elseif ($Module.Params.state -eq 'present') {
367 # Use dummy value for check mode when creating a new user
368 $Module.Result.sid = 'S-1-5-0000'
369 }
370
371 if ($null -eq $Module.Params.groups -or $Module.Params.groups.Count -eq 0 -or $Module.Params.state -eq 'absent') {
372 return
373 }
374
375 [string[]]$existingGroups = @(
376 # In check mode the ADObject won't be given
377 if ($ADObject) {
378 try {
379 # Get-ADPrincipalGroupMembership doesn't work well with
380 # cross domain membership. It also gets the primary group
381 # so this code reflects that using Get-ADUser instead.
382 $userMembership = Get-ADUser -Identity $ADObject.ObjectGUID @ADParams -Properties @(
383 'MemberOf',
384 'PrimaryGroup'
385 ) -ErrorAction Stop
386 $userMembership.memberOf
387 $userMembership.PrimaryGroup
388 }
389 catch {
390 $module.Warn("Failed to enumerate user groups but continuing on: $($_.Exception.Message)")
391 }
392 }
393 )
394
395 if ($Module.Diff.before) {
396 $Module.Diff.before.groups = @($existingGroups | Sort-Object)
397 }
398
399 $compareParams = @{
400 CaseInsensitive = $true
401 Existing = $existingGroups
402 }
403 $dnServerParams = @{}
404 foreach ($actionKvp in $Module.Params.groups.GetEnumerator()) {
405 if ($null -eq $actionKvp.Value -or $actionKvp.Key -in @('lookup_failure_action', 'missing_behaviour', 'permissions_failure_action')) {
406 continue
407 }
408
409 $convertParams = @{
410 Module = $Module
411 Context = "groups.$($actionKvp.Key)"
412 FailureAction = $Module.Params.groups.lookup_failure_action
413 }
414 $dns = foreach ($lookupId in $actionKvp.Value) {
415 $dn = $lookupId | ConvertTo-AnsibleADDistinguishedName @ADParams @convertParams
416 if (-not $dn) {
417 continue # Warning was written
418 }
419
420 # As membership is done on the group server, we need to store
421 # correct server and credentials that was used for the lookup.
422 if ($lookupId -is [System.Collections.IDictionary] -and $lookupId.server) {
423 $dnServerParams[$dn] = @{
424 Server = $lookupId.server
425 }
426
427 if ($Module.ServerCredentials.ContainsKey($lookupId.server)) {
428 $dnServerParams[$dn].Credential = $Module.ServerCredentials[$lookupId.server]
429 }
430 }
431 else {
432 $dnServerParams[$dn] = $ADParams
433 }
434
435 $dn
436 }
437
438 $compareParams[$actionKvp.Key] = @($dns)
439 }
440
441 $res = Compare-AnsibleADIdempotentList @compareParams
442 $Module.Diff.after.groups = $res.Value
443
444 if ($res.Changed) {
445 $commonParams = @{
446 Confirm = $false
447 WhatIf = $Module.CheckMode
448 }
449 foreach ($member in $res.ToAdd) {
450 $lookupParams = if ($dnServerParams.ContainsKey($member)) {
451 $dnServerParams[$member]
452 }
453 else {
454 $ADParams
455 }
456 if ($ADObject) {
457 try {
458 Set-ADObject -Identity $member -Add @{
459 member = $ADObject.DistinguishedName
460 } @lookupParams @commonParams
461 }
462 catch [Microsoft.ActiveDirectory.Management.ADException] {
463 if ($Module.Params.groups.permissions_failure_action -ne "fail") {
464 if ($Module.Params.groups.permissions_failure_action -eq "warn") {
465 $Module.Warn("Cannot add group '$member'. You do not have the required permissions, skipping: $($_.Exception.Message)")
466 }
467 }
468 else {
469 throw
470 }
471 }
472 }
473 $Module.Result.changed = $true
474 }
475 foreach ($member in $res.ToRemove) {
476 $lookupParams = if ($dnServerParams.ContainsKey($member)) {
477 $dnServerParams[$member]
478 }
479 else {
480 $ADParams
481 }
482 if ($ADObject) {
483 try {
484 Set-ADObject -Identity $member -Remove @{
485 member = $ADObject.DistinguishedName
486 } @lookupParams @commonParams
487 }
488 catch [Microsoft.ActiveDirectory.Management.ADException] {
489 if ($_.Exception.ErrorCode -eq 0x0000055E) {
490 # ERROR_MEMBERS_PRIMARY_GROUP - win_domain_user didn't
491 # fail in this scenario. To preserve compatibility just
492 # display a warning. The warning isn't added if set
493 # was an empty list.
494 if ($null -eq $Module.Params.groups -or $Module.Params.groups.set.Length -ne 0) {
495 $Module.Warn("Cannot remove group '$member' as it's the primary group of the user, skipping: $($_.Exception.Message)")
496 }
497 $Module.Diff.after.groups = @($Module.Diff.after.groups; $member)
498 }
499 elseif ($Module.Params.groups.permissions_failure_action -ne "fail") {
500 if ($Module.Params.groups.permissions_failure_action -eq "warn") {
501 $Module.Warn("Cannot remove group '$member'. You do not have the required permissions, skipping: $($_.Exception.Message)")
502 }
503 }
504 else {
505 throw
506 }
507 }
508 }
509 $Module.Result.changed = $true
510 }
511 }
512
513 # Ensure it's in alphabetical order to match before state as much as possible
514 $Module.Diff.after.groups = @($res.Value | Sort-Object)
515 }
516 }
517 Invoke-AnsibleADObject @setParams