-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGet-UserRightAssignment.ps1
480 lines (467 loc) · 23.9 KB
/
Get-UserRightAssignment.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
function Get-UserRightAssignment {
<#
.SYNOPSIS
Get Local User Account rights from the Local Security Policy
.DESCRIPTION
This script will gather the local security policy User Rights from the local, or a remote machine.
.PARAMETER ComputerName
Comma separated list of servers you want to run this script against. To run locally, run without this switch.
.PARAMETER FileOutputPath
Location to store the Output File. Set the Type (CSV or Text) with FileOutputType
.PARAMETER FileOutputType
Set the type of file you would like to output as. Combine with the OutputPath parameter.
.PARAMETER PassThru
Output as an object that you can manipulate / access.
.EXAMPLE
Usage:
Get Local User Account Rights and output to text in console:
PS C:\> .\Get-UserRights.ps1
Get Remote Server User Account Rights:
PS C:\> .\Get-UserRights.ps1 -ComputerName SQL.contoso.com
Get Local Machine and Multiple Server User Account Rights:
PS C:\> .\Get-UserRights.ps1 -ComputerName $env:COMPUTERNAME, SQL.contoso.com
Output to CSV in 'C:\Temp':
PS C:\> .\Get-UserRights.ps1 -FileOutputPath C:\Temp -FileOutputType CSV
Output to Text in 'C:\Temp':
PS C:\> .\Get-UserRights.ps1 -FileOutputPath C:\Temp -FileOutputType Text
Pass thru object:
PS C:\> .\Get-UserRights.ps1 -ComputerName SQL.contoso.com -PassThru | Where {$_.Principal -match "Administrator"}
.NOTES
This script is located in the following GitHub Repository: https://github.com/blakedrumm/SCOM-Scripts-and-SQL
Exact location: https://github.com/blakedrumm/SCOM-Scripts-and-SQL/blob/master/Powershell/General%20Functions/Get-UserRights.ps1
Blog post: https://blakedrumm.com/blog/set-and-check-user-rights-assignment/
Author: Blake Drumm ([email protected])
First Created on: June 10th, 2021
Last Modified on: August 15th, 2022
#>
[CmdletBinding()]
[OutputType([string])]
param
(
[Parameter(ValueFromPipeline = $true,
Position = 0,
HelpMessage = '(Server1, Server2) Comma separated list of servers you want to run this script against. To run locally, run without this switch. This argument accepts values from the pipeline.')]
[Alias('servers')]
[array]$ComputerName,
[Parameter(Position = 1,
HelpMessage = '(ex. C:\Temp) Location to store the Output File. Set the Type with FileOutputType')]
[string]$FileOutputPath,
[Parameter(Position = 2,
HelpMessage = '(CSV or Text) Set the type of file you would like to output as. Combine with the OutputPath parameter.')]
[ValidateSet('CSV', 'Text', '')]
[string]$FileOutputType,
[Parameter(Position = 3,
HelpMessage = 'Output as an object that you can manipulate / access.')]
[switch]$PassThru
)
BEGIN
{
#region Initialization
if (!$PassThru)
{
Write-Host @"
===================================================================
========================== Start of Script =======================
===================================================================
"@
}
$checkingpermission = "Checking for elevated permissions..."
$scriptout += $checkingpermission
if (!$PassThru)
{
Write-Host $checkingpermission
}
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$currentPath = $myinvocation.mycommand.definition
$nopermission = "Insufficient permissions to run this script. Attempting to open the PowerShell script ($currentPath) as administrator."
$scriptout += $nopermission
Write-Warning $nopermission
# We are not running "as Administrator" - so relaunch as administrator
# ($MyInvocation.Line -split '\.ps1[\s\''\"]\s*', 2)[-1]
Start-Process powershell.exe "-File", ('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
break
}
else
{
$permissiongranted = " Currently running as administrator - proceeding with script execution..."
if (!$PassThru)
{
Write-Host $permissiongranted
}
}
Function Time-Stamp
{
$TimeStamp = Get-Date -Format "MM/dd/yyyy hh:mm:ss tt"
return "$TimeStamp - "
}
if (!$PassThru)
{
Write-Output "$(Time-Stamp)Starting main script execution."
}
#endregion Initialization
}
PROCESS
{
#region MainFunctionSection
function Get-UserRights
{
param
(
[Parameter(ValueFromPipeline = $true,
Position = 0,
HelpMessage = '(Server1, Server2) Comma separated list of servers you want to run this script against. To run locally, run without this switch. This argument accepts values from the pipeline.')]
[Alias('servers')]
[array]$ComputerName,
[Parameter(Position = 1,
HelpMessage = '(ex. C:\Temp) Location to store the Output File. Set the Type with FileOutputType')]
[string]$FileOutputPath,
[Parameter(Mandatory = $false,
Position = 2,
HelpMessage = '(CSV or Text) Set the type of file you would like to output as. Combine with the OutputPath parameter.')]
[ValidateSet('CSV', 'Text', '')]
[string]$FileOutputType,
[Parameter(Position = 3,
HelpMessage = 'Output as an object that you can manipulate / access.')]
[switch]$PassThru
)
if (!$ComputerName)
{
$ComputerName = $env:COMPUTERNAME
}
[array]$localrights = $null
foreach ($ComputerName in $ComputerName)
{
if (!$PassThru)
{
Write-Output "$(Time-Stamp)Gathering current User Account Rights on: $ComputerName"
}
#region Non-LocalMachine
if ($ComputerName -notmatch $env:COMPUTERNAME)
{
$localrights += Invoke-Command -ScriptBlock {
param ([int]$VerbosePreference)
function Get-SecurityPolicy
{
#requires -version 2
# Fail script if we can't find SecEdit.exe
$SecEdit = Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::System)) "SecEdit.exe"
if (-not (Test-Path $SecEdit))
{
Write-Error "File not found - '$SecEdit'" -Category ObjectNotFound
return
}
Write-Verbose "Found Executable: $SecEdit"
# LookupPrivilegeDisplayName Win32 API doesn't resolve logon right display
# names, so use this hashtable
$UserLogonRights = @{
"SeBatchLogonRight" = "Log on as a batch job"
"SeDenyBatchLogonRight" = "Deny log on as a batch job"
"SeDenyInteractiveLogonRight" = "Deny log on locally"
"SeDenyNetworkLogonRight" = "Deny access to this computer from the network"
"SeDenyRemoteInteractiveLogonRight" = "Deny log on through Remote Desktop Services"
"SeDenyServiceLogonRight" = "Deny log on as a service"
"SeInteractiveLogonRight" = "Allow log on locally"
"SeNetworkLogonRight" = "Access this computer from the network"
"SeRemoteInteractiveLogonRight" = "Allow log on through Remote Desktop Services"
"SeServiceLogonRight" = "Log on as a service"
}
# Create type to invoke LookupPrivilegeDisplayName Win32 API
$Win32APISignature = @'
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LookupPrivilegeDisplayName(
string systemName,
string privilegeName,
System.Text.StringBuilder displayName,
ref uint cbDisplayName,
out uint languageId
);
'@
$AdvApi32 = Add-Type advapi32 $Win32APISignature -Namespace LookupPrivilegeDisplayName -PassThru
# Use LookupPrivilegeDisplayName Win32 API to get display name of privilege
# (except for user logon rights)
function Get-PrivilegeDisplayName
{
param (
[String]$name
)
$displayNameSB = New-Object System.Text.StringBuilder 1024
$languageId = 0
$ok = $AdvApi32::LookupPrivilegeDisplayName($null, $name, $displayNameSB, [Ref]$displayNameSB.Capacity, [Ref]$languageId)
if ($ok)
{
$displayNameSB.ToString()
}
else
{
# Doesn't lookup logon rights, so use hashtable for that
if ($UserLogonRights[$name])
{
$UserLogonRights[$name]
}
else
{
$name
}
}
}
# Outputs list of hashtables as a PSObject
function Out-Object
{
param (
[System.Collections.Hashtable[]]$hashData
)
$order = @()
$result = @{ }
$hashData | ForEach-Object {
$order += ($_.Keys -as [Array])[0]
$result += $_
}
$out = New-Object PSObject -Property $result | Select-Object $order
return $out
}
# Translates a SID in the form *S-1-5-... to its account name;
function Get-AccountName
{
param (
[String]$principal
)
try
{
$sid = New-Object System.Security.Principal.SecurityIdentifier($principal.Substring(1))
$sid.Translate([Security.Principal.NTAccount])
}
catch { $principal }
}
$TemplateFilename = Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName())
$LogFilename = Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName())
$StdOut = & $SecEdit /export /cfg $TemplateFilename /areas USER_RIGHTS /log $LogFilename
Write-Verbose "$StdOut"
if ($LASTEXITCODE -eq 0)
{
$dtable = $null
$dtable = New-Object System.Data.DataTable
$dtable.Columns.Add("Privilege", "System.String") | Out-Null
$dtable.Columns.Add("PrivilegeName", "System.String") | Out-Null
$dtable.Columns.Add("Principal", "System.String") | Out-Null
$dtable.Columns.Add("ComputerName", "System.String") | Out-Null
Select-String '^(Se\S+) = (\S+)' $TemplateFilename | Foreach-Object {
$Privilege = $_.Matches[0].Groups[1].Value
$Principals = $_.Matches[0].Groups[2].Value -split ','
foreach ($Principal in $Principals)
{
$nRow = $dtable.NewRow()
$nRow.Privilege = $Privilege
$nRow.PrivilegeName = Get-PrivilegeDisplayName $Privilege
$nRow.Principal = Get-AccountName $Principal
$nRow.ComputerName = $env:COMPUTERNAME
$dtable.Rows.Add($nRow)
}
return $dtable
}
}
else
{
$OFS = ""
Write-Error "$StdOut"
}
Remove-Item $TemplateFilename, $LogFilename -ErrorAction SilentlyContinue
}
return Get-SecurityPolicy
} -ArgumentList $VerbosePreference -computer $ComputerName -HideComputerName | Select-Object * -ExcludeProperty RunspaceID, PSShowComputerName, PSComputerName -Unique
} #endregion Non-LocalMachine
else #region LocalMachine
{
function Get-SecurityPolicy
{
#requires -version 2
# Fail script if we can't find SecEdit.exe
$SecEdit = Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::System)) "SecEdit.exe"
if (-not (Test-Path $SecEdit))
{
Write-Error "File not found - '$SecEdit'" -Category ObjectNotFound
return
}
Write-Verbose "Found Executable: $SecEdit"
# LookupPrivilegeDisplayName Win32 API doesn't resolve logon right display
# names, so use this hashtable
$UserLogonRights = @{
"SeBatchLogonRight" = "Log on as a batch job"
"SeDenyBatchLogonRight" = "Deny log on as a batch job"
"SeDenyInteractiveLogonRight" = "Deny log on locally"
"SeDenyNetworkLogonRight" = "Deny access to this computer from the network"
"SeDenyRemoteInteractiveLogonRight" = "Deny log on through Remote Desktop Services"
"SeDenyServiceLogonRight" = "Deny log on as a service"
"SeInteractiveLogonRight" = "Allow log on locally"
"SeNetworkLogonRight" = "Access this computer from the network"
"SeRemoteInteractiveLogonRight" = "Allow log on through Remote Desktop Services"
"SeServiceLogonRight" = "Log on as a service"
}
# Create type to invoke LookupPrivilegeDisplayName Win32 API
$Win32APISignature = @'
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LookupPrivilegeDisplayName(
string systemName,
string privilegeName,
System.Text.StringBuilder displayName,
ref uint cbDisplayName,
out uint languageId
);
'@
$AdvApi32 = Add-Type advapi32 $Win32APISignature -Namespace LookupPrivilegeDisplayName -PassThru
# Use LookupPrivilegeDisplayName Win32 API to get display name of privilege
# (except for user logon rights)
function Get-PrivilegeDisplayName
{
param (
[String]$name
)
$displayNameSB = New-Object System.Text.StringBuilder 1024
$languageId = 0
try {
$ok = $AdvApi32::LookupPrivilegeDisplayName($null, $name, $displayNameSB, [Ref]$displayNameSB.Capacity, [Ref]$languageId)
}
catch {
$ok = $null
}
if ($ok)
{
$displayNameSB.ToString()
}
else
{
# Doesn't lookup logon rights, so use hashtable for that
if ($UserLogonRights[$name])
{
$UserLogonRights[$name]
}
else
{
$name
}
}
}
# Outputs list of hashtables as a PSObject
function Out-Object
{
param (
[System.Collections.Hashtable[]]$hashData
)
$order = @()
$result = @{ }
$hashData | ForEach-Object {
$order += ($_.Keys -as [Array])[0]
$result += $_
}
$out = New-Object PSObject -Property $result | Select-Object $order
return $out
}
# Translates a SID in the form *S-1-5-... to its account name;
function Get-AccountName
{
param (
[String]$principal
)
try
{
$sid = New-Object System.Security.Principal.SecurityIdentifier($principal.Substring(1))
$sid.Translate([Security.Principal.NTAccount])
}
catch { $principal }
}
$TemplateFilename = Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName())
$LogFilename = Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName())
$StdOut = & $SecEdit /export /cfg $TemplateFilename /areas USER_RIGHTS /log $LogFilename
Write-Verbose "$StdOut"
if ($LASTEXITCODE -eq 0)
{
$dtable = $null
$dtable = New-Object System.Data.DataTable
$dtable.Columns.Add("Privilege", "System.String") | Out-Null
$dtable.Columns.Add("PrivilegeName", "System.String") | Out-Null
$dtable.Columns.Add("Principal", "System.String") | Out-Null
$dtable.Columns.Add("ComputerName", "System.String") | Out-Null
Select-String '^(Se\S+) = (\S+)' $TemplateFilename | Foreach-Object {
$Privilege = $_.Matches[0].Groups[1].Value
$Principals = $_.Matches[0].Groups[2].Value -split ','
foreach ($Principal in $Principals)
{
$nRow = $dtable.NewRow()
$nRow.Privilege = $Privilege
$nRow.PrivilegeName = Get-PrivilegeDisplayName $Privilege
$nRow.Principal = Get-AccountName $Principal
$nRow.ComputerName = $env:COMPUTERNAME
$dtable.Rows.Add($nRow)
}
return $dtable
}
}
else
{
$OFS = ""
Write-Error "$StdOut"
}
Remove-Item $TemplateFilename, $LogFilename -ErrorAction SilentlyContinue
}
$localrights += Get-SecurityPolicy
} #endregion LocalMachine
$output += $localrights
if (!$PassThru)
{
Write-Output "$(Time-Stamp)Gathering for $ComputerName completed."
}
}
if (!$PassThru)
{
Write-Output "$(Time-Stamp)Main script execution completed!"
}
$output = $output | Select-Object Privilege, PrivilegeName, Principal, ComputerName -Unique | Sort-Object Privilege, ComputerName
if ($PassThru)
{
return $output
}
elseif (!$FileOutputPath)
{
$output | Format-Table -AutoSize | Out-String -Width 2048
}
else
{
#region FileOutputType
if ($FileOutputType -eq 'Text')
{
Write-Output "$(Time-Stamp)Writing output to `'$FileOutputPath\UserLogonRights.txt`'."
$output | Format-Table -AutoSize | Out-String -Width 2048 | Out-File "$FileOutputPath\UserLogonRights.txt" -Force
}
elseif ($FileOutputType -eq 'CSV')
{
Write-Output "$(Time-Stamp)Writing output to `'$FileOutputPath\UserLogonRights.csv`'."
$output | Export-CSV $FileOutputPath\UserLogonRights.csv -NoTypeInformation
}
else
{
Write-Output "Unsupported File Output Type."
}
#endregion FileOutputType
}
}
#endregion MainFunctionSection
if ($FileOutputPath -or $FileOutputType -or $ComputerName -or $PassThru)
{
Get-UserRights -FileOutputPath:$FileOutputPath -FileOutputType:$FileOutputType -ComputerName:$ComputerName -PassThru:$PassThru
}
else
{
<# Edit line 467 to modify the default command run when this script is executed.
Example for output multiple servers to a text file:
Get-UserRights -ComputerName MS01-2019, IIS-2019 -FileOutputPath C:\Temp -FileOutputType Text
Example for gathering locally:
Get-UserRights
#>
Get-UserRights
}
}
END
{
Write-Verbose "$(Time-Stamp)Script Completed!"
}
}