Debian Codegraph @

test/support/windows-integration/plugins/modules/win_user.ps1

raw
1 #!powershell
2
3 # Copyright: (c) 2014, Paul Durivage <[email protected]>
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 #Requires -Module Ansible.ModuleUtils.Legacy
8
9 ########
10 $ADS_UF_PASSWD_CANT_CHANGE = 64
11 $ADS_UF_DONT_EXPIRE_PASSWD = 65536
12
13 $adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
14
15 function Get-User($user) {
16 $adsi.Children | Where-Object {$_.SchemaClassName -eq 'user' -and $_.Name -eq $user }
17 return
18 }
19
20 function Get-UserFlag($user, $flag) {
21 If ($user.UserFlags[0] -band $flag) {
22 $true
23 }
24 Else {
25 $false
26 }
27 }
28
29 function Set-UserFlag($user, $flag) {
30 $user.UserFlags = ($user.UserFlags[0] -BOR $flag)
31 }
32
33 function Clear-UserFlag($user, $flag) {
34 $user.UserFlags = ($user.UserFlags[0] -BXOR $flag)
35 }
36
37 function Get-Group($grp) {
38 $adsi.Children | Where-Object { $_.SchemaClassName -eq 'Group' -and $_.Name -eq $grp }
39 return
40 }
41
42 Function Test-LocalCredential {
43 param([String]$Username, [String]$Password)
44
45 try {
46 $handle = [Ansible.AccessToken.TokenUtil]::LogonUser($Username, $null, $Password, "Network", "Default")
47 $handle.Dispose()
48 $valid_credentials = $true
49 } catch [Ansible.AccessToken.Win32Exception] {
50 # following errors indicate the creds are correct but the user was
51 # unable to log on for other reasons, which we don't care about
52 $success_codes = @(
53 0x0000052F, # ERROR_ACCOUNT_RESTRICTION
54 0x00000530, # ERROR_INVALID_LOGON_HOURS
55 0x00000531, # ERROR_INVALID_WORKSTATION
56 0x00000569 # ERROR_LOGON_TYPE_GRANTED
57 )
58
59 if ($_.Exception.NativeErrorCode -eq 0x0000052E) {
60 # ERROR_LOGON_FAILURE - the user or pass was incorrect
61 $valid_credentials = $false
62 } elseif ($_.Exception.NativeErrorCode -in $success_codes) {
63 $valid_credentials = $true
64 } else {
65 # an unknown failure, reraise exception
66 throw $_
67 }
68 }
69 return $valid_credentials
70 }
71
72 ########
73
74 $params = Parse-Args $args;
75
76 $result = @{
77 changed = $false
78 };
79
80 $username = Get-AnsibleParam -obj $params -name "name" -type "str" -failifempty $true
81 $fullname = Get-AnsibleParam -obj $params -name "fullname" -type "str"
82 $description = Get-AnsibleParam -obj $params -name "description" -type "str"
83 $password = Get-AnsibleParam -obj $params -name "password" -type "str"
84 $state = Get-AnsibleParam -obj $params -name "state" -type "str" -default "present" -validateset "present","absent","query"
85 $update_password = Get-AnsibleParam -obj $params -name "update_password" -type "str" -default "always" -validateset "always","on_create"
86 $password_expired = Get-AnsibleParam -obj $params -name "password_expired" -type "bool"
87 $password_never_expires = Get-AnsibleParam -obj $params -name "password_never_expires" -type "bool"
88 $user_cannot_change_password = Get-AnsibleParam -obj $params -name "user_cannot_change_password" -type "bool"
89 $account_disabled = Get-AnsibleParam -obj $params -name "account_disabled" -type "bool"
90 $account_locked = Get-AnsibleParam -obj $params -name "account_locked" -type "bool"
91 $groups = Get-AnsibleParam -obj $params -name "groups"
92 $groups_action = Get-AnsibleParam -obj $params -name "groups_action" -type "str" -default "replace" -validateset "add","remove","replace"
93
94 If ($null -ne $account_locked -and $account_locked) {
95 Fail-Json $result "account_locked must be set to 'no' if provided"
96 }
97
98 If ($null -ne $groups) {
99 If ($groups -is [System.String]) {
100 [string[]]$groups = $groups.Split(",")
101 }
102 ElseIf ($groups -isnot [System.Collections.IList]) {
103 Fail-Json $result "groups must be a string or array"
104 }
105 $groups = $groups | ForEach-Object { ([string]$_).Trim() } | Where-Object { $_ }
106 If ($null -eq $groups) {
107 $groups = @()
108 }
109 }
110
111 $user_obj = Get-User $username
112
113 If ($state -eq 'present') {
114 # Add or update user
115 try {
116 If (-not $user_obj) {
117 $user_obj = $adsi.Create("User", $username)
118 If ($null -ne $password) {
119 $user_obj.SetPassword($password)
120 }
121 $user_obj.SetInfo()
122 $result.changed = $true
123 }
124 ElseIf (($null -ne $password) -and ($update_password -eq 'always')) {
125 # ValidateCredentials will fail if either of these are true- just force update...
126 If($user_obj.AccountDisabled -or $user_obj.PasswordExpired) {
127 $password_match = $false
128 }
129 Else {
130 try {
131 $password_match = Test-LocalCredential -Username $username -Password $password
132 } catch [System.ComponentModel.Win32Exception] {
133 Fail-Json -obj $result -message "Failed to validate the user's credentials: $($_.Exception.Message)"
134 }
135 }
136
137 If (-not $password_match) {
138 $user_obj.SetPassword($password)
139 $result.changed = $true
140 }
141 }
142 If (($null -ne $fullname) -and ($fullname -ne $user_obj.FullName[0])) {
143 $user_obj.FullName = $fullname
144 $result.changed = $true
145 }
146 If (($null -ne $description) -and ($description -ne $user_obj.Description[0])) {
147 $user_obj.Description = $description
148 $result.changed = $true
149 }
150 If (($null -ne $password_expired) -and ($password_expired -ne ($user_obj.PasswordExpired | ConvertTo-Bool))) {
151 $user_obj.PasswordExpired = If ($password_expired) { 1 } Else { 0 }
152 $result.changed = $true
153 }
154 If (($null -ne $password_never_expires) -and ($password_never_expires -ne (Get-UserFlag $user_obj $ADS_UF_DONT_EXPIRE_PASSWD))) {
155 If ($password_never_expires) {
156 Set-UserFlag $user_obj $ADS_UF_DONT_EXPIRE_PASSWD
157 }
158 Else {
159 Clear-UserFlag $user_obj $ADS_UF_DONT_EXPIRE_PASSWD
160 }
161 $result.changed = $true
162 }
163 If (($null -ne $user_cannot_change_password) -and ($user_cannot_change_password -ne (Get-UserFlag $user_obj $ADS_UF_PASSWD_CANT_CHANGE))) {
164 If ($user_cannot_change_password) {
165 Set-UserFlag $user_obj $ADS_UF_PASSWD_CANT_CHANGE
166 }
167 Else {
168 Clear-UserFlag $user_obj $ADS_UF_PASSWD_CANT_CHANGE
169 }
170 $result.changed = $true
171 }
172 If (($null -ne $account_disabled) -and ($account_disabled -ne $user_obj.AccountDisabled)) {
173 $user_obj.AccountDisabled = $account_disabled
174 $result.changed = $true
175 }
176 If (($null -ne $account_locked) -and ($account_locked -ne $user_obj.IsAccountLocked)) {
177 $user_obj.IsAccountLocked = $account_locked
178 $result.changed = $true
179 }
180 If ($result.changed) {
181 $user_obj.SetInfo()
182 }
183 If ($null -ne $groups) {
184 [string[]]$current_groups = $user_obj.Groups() | ForEach-Object { $_.GetType().InvokeMember("Name", "GetProperty", $null, $_, $null) }
185 If (($groups_action -eq "remove") -or ($groups_action -eq "replace")) {
186 ForEach ($grp in $current_groups) {
187 If ((($groups_action -eq "remove") -and ($groups -contains $grp)) -or (($groups_action -eq "replace") -and ($groups -notcontains $grp))) {
188 $group_obj = Get-Group $grp
189 If ($group_obj) {
190 $group_obj.Remove($user_obj.Path)
191 $result.changed = $true
192 }
193 Else {
194 Fail-Json $result "group '$grp' not found"
195 }
196 }
197 }
198 }
199 If (($groups_action -eq "add") -or ($groups_action -eq "replace")) {
200 ForEach ($grp in $groups) {
201 If ($current_groups -notcontains $grp) {
202 $group_obj = Get-Group $grp
203 If ($group_obj) {
204 $group_obj.Add($user_obj.Path)
205 $result.changed = $true
206 }
207 Else {
208 Fail-Json $result "group '$grp' not found"
209 }
210 }
211 }
212 }
213 }
214 }
215 catch {
216 Fail-Json $result $_.Exception.Message
217 }
218 }
219 ElseIf ($state -eq 'absent') {
220 # Remove user
221 try {
222 If ($user_obj) {
223 $username = $user_obj.Name.Value
224 $adsi.delete("User", $user_obj.Name.Value)
225 $result.changed = $true
226 $result.msg = "User '$username' deleted successfully"
227 $user_obj = $null
228 } else {
229 $result.msg = "User '$username' was not found"
230 }
231 }
232 catch {
233 Fail-Json $result $_.Exception.Message
234 }
235 }
236
237 try {
238 If ($user_obj -and $user_obj -is [System.DirectoryServices.DirectoryEntry]) {
239 $user_obj.RefreshCache()
240 $result.name = $user_obj.Name[0]
241 $result.fullname = $user_obj.FullName[0]
242 $result.path = $user_obj.Path
243 $result.description = $user_obj.Description[0]
244 $result.password_expired = ($user_obj.PasswordExpired | ConvertTo-Bool)
245 $result.password_never_expires = (Get-UserFlag $user_obj $ADS_UF_DONT_EXPIRE_PASSWD)
246 $result.user_cannot_change_password = (Get-UserFlag $user_obj $ADS_UF_PASSWD_CANT_CHANGE)
247 $result.account_disabled = $user_obj.AccountDisabled
248 $result.account_locked = $user_obj.IsAccountLocked
249 $result.sid = (New-Object System.Security.Principal.SecurityIdentifier($user_obj.ObjectSid.Value, 0)).Value
250 $user_groups = @()
251 ForEach ($grp in $user_obj.Groups()) {
252 $group_result = @{
253 name = $grp.GetType().InvokeMember("Name", "GetProperty", $null, $grp, $null)
254 path = $grp.GetType().InvokeMember("ADsPath", "GetProperty", $null, $grp, $null)
255 }
256 $user_groups += $group_result;
257 }
258 $result.groups = $user_groups
259 $result.state = "present"
260 }
261 Else {
262 $result.name = $username
263 if ($state -eq 'query') {
264 $result.msg = "User '$username' was not found"
265 }
266 $result.state = "absent"
267 }
268 }
269 catch {
270 Fail-Json $result $_.Exception.Message
271 }
272
273 Exit-Json $result