-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path202_Helpers_Service.ps1
679 lines (530 loc) · 28.1 KB
/
202_Helpers_Service.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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
function Get-ServiceControlManagerDacl {
<#
.SYNOPSIS
Helper - Get the DACL of the SCM (Service Control Manager)
Author: @itm4n
License: BSD 3-Clause
.DESCRIPTION
The SCM (Service Control Manager) has its own DACL which defines which users/groups can connect / create services / enumerate services / etc. This function requests Read access to the SCM and queries this DACL. The DACL is returned as a Security Descriptor, which is a binary blob. Therefore, it is converted to a list of ACE objects, which can then be easily used by the caller.
.EXAMPLE
PS C:\> Get-ServiceControlManagerDacl
AccessRights : Connect
BinaryLength : 20
AceQualifier : AccessAllowed
IsCallback : False
OpaqueLength : 0
AccessMask : 1
SecurityIdentifier : S-1-5-11
AceType : AccessAllowed
AceFlags : None
IsInherited : False
InheritanceFlags : None
PropagationFlags : None
AuditFlags : None
...
.NOTES
https://docs.microsoft.com/en-us/windows/win32/services/service-security-and-access-rights
#>
[CmdletBinding()] Param()
$SERVICES_ACTIVE_DATABASE = "ServicesActive"
$ServiceManagerHandle = $Advapi32::OpenSCManager($null, $SERVICES_ACTIVE_DATABASE, $ServiceControlManagerAccessRightsEnum::GenericRead)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($ServiceManagerHandle) {
$SizeNeeded = 0
$null = $Advapi32::QueryServiceObjectSecurity($ServiceManagerHandle, [Security.AccessControl.SecurityInfos]::DiscretionaryAcl, @(), 0, [Ref] $SizeNeeded)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
# 122 == The data area passed to a system call is too small
if (($LastError -eq 122) -and ($SizeNeeded -gt 0)) {
Write-Verbose "Size needed: $($SizeNeeded)"
$BinarySecurityDescriptor = New-Object Byte[]($SizeNeeded)
$Success = $Advapi32::QueryServiceObjectSecurity($ServiceManagerHandle, [Security.AccessControl.SecurityInfos]::DiscretionaryAcl, $BinarySecurityDescriptor, $BinarySecurityDescriptor.Count, [Ref] $SizeNeeded)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Success) {
$RawSecurityDescriptor = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $BinarySecurityDescriptor, 0
$Dacl = $RawSecurityDescriptor.DiscretionaryAcl
if ($null -eq $Dacl) {
$Result = New-Object -TypeName PSObject
$Result | Add-Member -MemberType "NoteProperty" -Name "AccessRights" -Value $ServiceControlManagerAccessRightsEnum::AllAccess
# $Result | Add-Member -MemberType "NoteProperty" -Name "AccessMask" -Value AccessRights.value__
$Result | Add-Member -MemberType "NoteProperty" -Name "SecurityIdentifier" -Value "S-1-1-0"
$Result | Add-Member -MemberType "NoteProperty" -Name "AceType" -Value "AccessAllowed"
$Result
}
else {
$Dacl | ForEach-Object {
Add-Member -InputObject $_ -MemberType NoteProperty -Name AccessRights -Value ($_.AccessMask -as $ServiceControlManagerAccessRightsEnum) -PassThru
}
}
}
}
else {
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
$null = $Advapi32::CloseServiceHandle($ServiceManagerHandle)
}
else {
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
}
function Get-ServiceFromRegistry {
<#
.SYNOPSIS
Extract the configuration of a service from the registry.
Author: @itm4n
License: BSD 3-Clause
.DESCRIPTION
Services' configuration is stored in teh registry under "HKLM\SYSTEM\CurrentControlSet\Services". For each service, a subkey is created and contains all the information we need. So we can just query this key to get a service's configuration.
.PARAMETER Name
Name of a service.
.EXAMPLE
PS C:\> Get-ServiceFromRegistry -Name Spooler
Name : Spooler
DisplayName : @C:\WINDOWS\system32\spoolsv.exe,-1
User : LocalSystem
ImagePath : C:\WINDOWS\System32\spoolsv.exe
StartMode : Automatic
Type : Win32OwnProcess, InteractiveProcess
RegistryKey : HKLM\SYSTEM\CurrentControlSet\Services
RegistryPath : HKLM\SYSTEM\CurrentControlSet\Services\Spooler
#>
[CmdletBinding()] Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]$Name
)
$RegKeyServices = "HKLM\SYSTEM\CurrentControlSet\Services"
$RegKey = Join-Path -Path $RegKeyServices -ChildPath $Name
$RegItem = Get-ItemProperty -Path "Registry::$($RegKey)" -ErrorAction SilentlyContinue
if ($null -eq $RegItem) { return }
$Result = New-Object -TypeName PSObject
$Result | Add-Member -MemberType "NoteProperty" -Name "Name" -Value $RegItem.PSChildName
$Result | Add-Member -MemberType "NoteProperty" -Name "DisplayName" -Value ([System.Environment]::ExpandEnvironmentVariables($RegItem.DisplayName))
$Result | Add-Member -MemberType "NoteProperty" -Name "User" -Value $RegItem.ObjectName
$Result | Add-Member -MemberType "NoteProperty" -Name "ImagePath" -Value $RegItem.ImagePath
$Result | Add-Member -MemberType "NoteProperty" -Name "StartMode" -Value ($RegItem.Start -as $ServiceStartTypeEnum)
$Result | Add-Member -MemberType "NoteProperty" -Name "Type" -Value ($RegItem.Type -as $ServiceTypeEnum)
$Result | Add-Member -MemberType "NoteProperty" -Name "RegistryKey" -Value $RegKeyServices
$Result | Add-Member -MemberType "NoteProperty" -Name "RegistryPath" -Value $RegKey
$Result
}
function Test-IsKnownService {
[OutputType([Boolean])]
[CmdletBinding()] Param(
[Parameter(Mandatory=$true)]
[Object]$Service
)
$SeparationCharacterSets = @('"', "'", ' ', "`"'", '" ', "' ", "`"' ")
foreach ($SeparationCharacterSet in $SeparationCharacterSets) {
$CandidatePaths = ($Service.ImagePath).Split($SeparationCharacterSet) | Where-Object { $_ -and (-not [String]::IsNullOrEmpty($_.trim())) }
foreach ($CandidatePath in $CandidatePaths) {
$TempPath = $([System.Environment]::ExpandEnvironmentVariables($CandidatePath))
$TempPathResolved = Resolve-Path -Path $TempPath -ErrorAction SilentlyContinue -ErrorVariable ErrorResolvePath
if ($ErrorResolvePath) { continue }
$File = Get-Item -Path $TempPathResolved -ErrorAction SilentlyContinue -ErrorVariable ErrorGetItem
if ($ErrorGetItem) { continue }
if ($File -and (Test-IsMicrosoftFile -File $File)) { return $true }
return $false
}
}
return $false
}
function Get-ServiceList {
<#
.SYNOPSIS
Helper - Enumerates services (based on the registry)
Author: @itm4n
License: BSD 3-Clause
.DESCRIPTION
This uses the registry to enumerate the services by looking for the subkeys of "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services". This allows any user to get information about all the services. So, even if non-privileged users can't access the details of a service through the Service Control Manager, they can do so simply by accessing the registry.
.PARAMETER FilterLevel
This parameter can be used to filter out the result returned by the function based on the
following criteria:
FilterLevel = 0 - No filtering
FilterLevel = 1 - Exclude 'Services with empty ImagePath'
FilterLevel = 2 - Exclude 'Services with empty ImagePath' + 'Drivers'
FilterLevel = 3 - Exclude 'Services with empty ImagePath' + 'Drivers' + 'Known services'
.EXAMPLE
PS C:\> Get-ServiceList -FilterLevel 3
Name : VMTools
DisplayName : VMware Tools
User : LocalSystem
ImagePath : "C:\Program Files\VMware\VMware Tools\vmtoolsd.exe"
StartMode : Automatic
Type : Win32OwnProcess
RegistryKey : HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VMTools
RegistryPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VMTools
.NOTES
A service "Type" can be one of the following:
KernelDriver = 1
FileSystemDriver = 2
Adapter = 4
RecognizerDriver = 8
Win32OwnProcess = 16
Win32ShareProcess = 32
InteractiveProcess = 256
#>
[CmdletBinding()] Param(
[Parameter(Mandatory=$true)]
[ValidateSet(0,1,2,3)]
[Int]
$FilterLevel
)
if ($CachedServiceList.Count -eq 0) {
# If the cached service list hasn't been initialized yet, enumerate all services and populate the
# cache.
$ServicesRegPath = "HKLM\SYSTEM\CurrentControlSet\Services"
$RegAllServices = Get-ChildItem -Path "Registry::$($ServicesRegPath)" -ErrorAction SilentlyContinue
$RegAllServices | ForEach-Object { [void]$CachedServiceList.Add((Get-ServiceFromRegistry -Name $_.PSChildName)) }
}
foreach ($ServiceItem in $CachedServiceList) {
# FilterLevel = 0 - Add the service to the list and go to the next one
if ($FilterLevel -eq 0) { $ServiceItem; continue }
if ($ServiceItem.ImagePath -and (-not [String]::IsNullOrEmpty($ServiceItem.ImagePath.trim()))) {
# FilterLevel = 1 - Add the service to the list of its ImagePath is not empty
if ($FilterLevel -le 1) { $ServiceItem; continue }
# Ignore services with no explicit type
if ($null -eq $ServiceItem.Type) {
Write-Warning "Service $($ServiceItem.Name) has no type"
continue
}
$TypeMask = $ServiceTypeEnum::Win32OwnProcess -bor $ServiceTypeEnum::Win32ShareProcess -bor $ServiceTypeEnum::InteractiveProcess
if (($ServiceItem.Type -band $TypeMask) -gt 0) {
# FilterLevel = 2 - Add the service to the list if it's not a driver
if ($FilterLevel -le 2) { $ServiceItem; continue }
if (-not (Test-IsKnownService -Service $ServiceItem)) {
# FilterLevel = 3 - Add the service if it's not a built-in Windows service
if ($FilterLevel -le 3) { $ServiceItem; continue }
}
}
}
}
}
function Add-ServiceDacl {
<#
.SYNOPSIS
Helper - Adds a Dacl field to a service object returned by Get-Service.
Author: Matthew Graeber
License: BSD 3-Clause
.DESCRIPTION
Takes one or more ServiceProcess.ServiceController objects on the pipeline and adds a Dacl field to each object. It does this by opening a handle with ReadControl for the service with using the GetServiceHandle Win32 API call and then uses QueryServiceObjectSecurity to retrieve a copy of the security descriptor for the service.
@itm4n: I had to make some small changes to the original code because i don't import the Win32 API functions the same way it was done in PowerUp.
.PARAMETER Name
An array of one or more service names to add a service Dacl for. Passable on the pipeline.
.EXAMPLE
PS C:\> Get-Service | Add-ServiceDacl
Add Dacls for every service the current user can read.
.EXAMPLE
PS C:\> Get-Service -Name VMTools | Add-ServiceDacl
Add the Dacl to the VMTools service object.
.OUTPUTS
ServiceProcess.ServiceController
.LINK
https://rohnspowershellblog.wordpress.com/2013/03/19/viewing-service-acls/
#>
[OutputType('ServiceProcess.ServiceController')]
param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('ServiceName')]
[ValidateNotNullOrEmpty()]
[String[]]$Name
)
BEGIN {
filter Local:Get-ServiceReadControlHandle {
[OutputType([IntPtr])]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[ValidateScript({ $_ -as 'ServiceProcess.ServiceController' })]
$Service
)
Add-Type -AssemblyName System.ServiceProcess # ServiceProcess is not loaded by default
$GetServiceHandle = [ServiceProcess.ServiceController].GetMethod('GetServiceHandle', [Reflection.BindingFlags] 'Instance, NonPublic')
$ReadControl = 0x00020000
$RawHandle = $GetServiceHandle.Invoke($Service, @($ReadControl))
$RawHandle
}
}
PROCESS {
foreach ($ServiceName in $Name) {
$IndividualService = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue -ErrorVariable GetServiceError
if (-not $GetServiceError) {
try {
$ServiceHandle = Get-ServiceReadControlHandle -Service $IndividualService
}
catch {
$ServiceHandle = $null
}
if ($ServiceHandle -and ($ServiceHandle -ne [IntPtr]::Zero)) {
$SizeNeeded = 0
$Result = $Advapi32::QueryServiceObjectSecurity($ServiceHandle, [Security.AccessControl.SecurityInfos]::DiscretionaryAcl, @(), 0, [Ref] $SizeNeeded)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
# 122 == The data area passed to a system call is too small
if ((-not $Result) -and ($LastError -eq 122) -and ($SizeNeeded -gt 0)) {
$BinarySecurityDescriptor = New-Object Byte[]($SizeNeeded)
$Result = $Advapi32::QueryServiceObjectSecurity($ServiceHandle, [Security.AccessControl.SecurityInfos]::DiscretionaryAcl, $BinarySecurityDescriptor, $BinarySecurityDescriptor.Count, [Ref] $SizeNeeded)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Result) {
$RawSecurityDescriptor = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $BinarySecurityDescriptor, 0
$RawDacl = $RawSecurityDescriptor.DiscretionaryAcl
# Check for NULL DACL first
if ($nul -eq $RawDacl) {
$Ace = New-Object -TypeName PSObject
$Ace | Add-Member -MemberType "NoteProperty" -Name "AccessRights" -Value $ServiceAccessRightsEnum::GenericAll
# $Ace | Add-Member -MemberType "NoteProperty" -Name "AccessMask" -Value AccessRights.value__
$Ace | Add-Member -MemberType "NoteProperty" -Name "SecurityIdentifier" -Value (Convert-SidStringToSid -Sid "S-1-1-0")
$Ace | Add-Member -MemberType "NoteProperty" -Name "AceType" -Value "AccessAllowed"
$Dacl = @($Ace)
}
else {
$Dacl = $RawDacl | ForEach-Object {
Add-Member -InputObject $_ -MemberType NoteProperty -Name AccessRights -Value ($_.AccessMask -as $ServiceAccessRightsEnum) -PassThru
}
}
Add-Member -InputObject $IndividualService -MemberType NoteProperty -Name Dacl -Value $Dacl -PassThru
}
}
$null = $Advapi32::CloseServiceHandle($ServiceHandle)
}
}
}
}
}
function Test-ServiceDaclPermission {
<#
.SYNOPSIS
Tests one or more passed services or service names against a given permission set, returning the service objects where the current user have the specified permissions.
Author: @harmj0y, Matthew Graeber
License: BSD 3-Clause
.DESCRIPTION
Takes a service Name or a ServiceProcess.ServiceController on the pipeline, and first adds a service Dacl to the service object with Add-ServiceDacl. All group SIDs for the current user are enumerated services where the user has some type of permission are filtered. The services are then filtered against a specified set of permissions, and services where the current user have the specified permissions are returned.
.PARAMETER Name
An array of one or more service names to test against the specified permission set.
.PARAMETER Permissions
A manual set of permission to test again. One of:'QueryConfig', 'ChangeConfig', 'QueryStatus', 'EnumerateDependents', 'Start', 'Stop', 'PauseContinue', 'Interrogate', UserDefinedControl', 'Delete', 'ReadControl', 'WriteDac', 'WriteOwner', 'Synchronize', 'AccessSystemSecurity', 'GenericAll', 'GenericExecute', 'GenericWrite', 'GenericRead', 'AllAccess'
.PARAMETER PermissionSet
A pre-defined permission set to test a specified service against. 'ChangeConfig', 'Restart', or 'AllAccess'.
.OUTPUTS
ServiceProcess.ServiceController
.EXAMPLE
PS C:\> Get-Service | Test-ServiceDaclPermission
Return all service objects where the current user can modify the service configuration.
.EXAMPLE
PS C:\> Get-Service | Test-ServiceDaclPermission -PermissionSet 'Restart'
Return all service objects that the current user can restart.
.EXAMPLE
PS C:\> Test-ServiceDaclPermission -Permissions 'Start' -Name 'VulnSVC'
Return the VulnSVC object if the current user has start permissions.
.LINK
https://rohnspowershellblog.wordpress.com/2013/03/19/viewing-service-acls/
#>
[OutputType('ServiceProcess.ServiceController')]
param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('ServiceName')]
[String[]]
[ValidateNotNullOrEmpty()]
$Name,
[String[]]
[ValidateSet('QueryConfig', 'ChangeConfig', 'QueryStatus', 'EnumerateDependents', 'Start', 'Stop', 'PauseContinue', 'Interrogate', 'UserDefinedControl', 'Delete', 'ReadControl', 'WriteDac', 'WriteOwner', 'Synchronize', 'AccessSystemSecurity', 'GenericAll', 'GenericExecute', 'GenericWrite', 'GenericRead', 'AllAccess')]
$Permissions,
[String]
[ValidateSet('ChangeConfig', 'Restart', 'AllAccess')]
$PermissionSet = 'ChangeConfig'
)
BEGIN {
$AccessMask = @{
'QueryConfig' = [UInt32]'0x00000001'
'ChangeConfig' = [UInt32]'0x00000002'
'QueryStatus' = [UInt32]'0x00000004'
'EnumerateDependents' = [UInt32]'0x00000008'
'Start' = [UInt32]'0x00000010'
'Stop' = [UInt32]'0x00000020'
'PauseContinue' = [UInt32]'0x00000040'
'Interrogate' = [UInt32]'0x00000080'
'UserDefinedControl' = [UInt32]'0x00000100'
'Delete' = [UInt32]'0x00010000'
'ReadControl' = [UInt32]'0x00020000'
'WriteDac' = [UInt32]'0x00040000'
'WriteOwner' = [UInt32]'0x00080000'
'Synchronize' = [UInt32]'0x00100000'
'AccessSystemSecurity' = [UInt32]'0x01000000'
'GenericAll' = [UInt32]'0x10000000'
'GenericExecute' = [UInt32]'0x20000000'
'GenericWrite' = [UInt32]'0x40000000'
'GenericRead' = [UInt32]'0x80000000'
'AllAccess' = [UInt32]'0x000F01FF'
}
$CheckAllPermissionsInSet = $false
if ($PSBoundParameters['Permissions']) {
$TargetPermissions = $Permissions
}
else {
if ($PermissionSet -eq 'ChangeConfig') {
$TargetPermissions = @('ChangeConfig', 'WriteDac', 'WriteOwner', 'GenericAll', ' GenericWrite', 'AllAccess')
}
elseif ($PermissionSet -eq 'Restart') {
$TargetPermissions = @('Start', 'Stop')
$CheckAllPermissionsInSet = $true # so we check all permissions && style
}
elseif ($PermissionSet -eq 'AllAccess') {
$TargetPermissions = @('GenericAll', 'AllAccess')
}
}
$CurrentUserSids = Get-CurrentUserSids
}
PROCESS {
foreach ($IndividualService in $Name) {
$TargetService = $IndividualService | Add-ServiceDacl
# We might not be able to access the Service at all so we must check whether Add-ServiceDacl
# returned something.
if ($TargetService -and $TargetService.Dacl) {
# Check all the Dacl objects of the current service
foreach ($Ace in $TargetService.Dacl) {
$MatchingDaclFound = $false
# An ACE object contains two properties we want to check: a SID and a list of AccessRights. First,
# we want to check if the current Dacl SID is in the list of SIDs of the current user
if ($CurrentUserSids -contains $Ace.SecurityIdentifier) {
if ($CheckAllPermissionsInSet) {
# If a Permission Set was specified, we want to make sure that we have all the necessary access
# rights
$AllMatched = $true
foreach ($TargetPermission in $TargetPermissions) {
# check permissions && style
if (($Ace.AccessRights -band $AccessMask[$TargetPermission]) -ne $AccessMask[$TargetPermission]) {
# Write-Verbose "Current user doesn't have '$TargetPermission' for $($TargetService.Name)"
$AllMatched = $false
break
}
}
if ($AllMatched) {
$TargetService | Add-Member -MemberType "NoteProperty" -Name "AccessRights" -Value $Ace.AccessRights
$TargetService | Add-Member -MemberType "NoteProperty" -Name "IdentityReference" -Value $(Convert-SidToName -Sid $Ace.SecurityIdentifier)
$TargetService
$MatchingDaclFound = $true
}
}
else {
foreach ($TargetPermission in $TargetPermissions) {
# check permissions || style
if (($Ace.AceType -eq 'AccessAllowed') -and ($Ace.AccessRights -band $AccessMask[$TargetPermission]) -eq $AccessMask[$TargetPermission]) {
$TargetService | Add-Member -MemberType "NoteProperty" -Name "AccessRights" -Value $Ace.AccessRights
$TargetService | Add-Member -MemberType "NoteProperty" -Name "IdentityReference" -Value $(Convert-SidToName -Sid $Ace.SecurityIdentifier)
$TargetService
$MatchingDaclFound = $true
break
}
}
}
}
if ($MatchingDaclFound) {
# As soon as we find a matching Dacl, we can stop searching
break
}
}
}
else {
Write-Verbose "Error enumerating the Dacl for service $IndividualService"
}
}
}
}
function Resolve-DriverImagePath {
[CmdletBinding()]
param (
[Object]$Service
)
if ($Service.ImagePath -match "^\\SystemRoot\\") {
$Service.ImagePath -replace "\\SystemRoot",$env:SystemRoot
}
elseif ($Service.ImagePath -match "^System32\\") {
Join-Path -Path $env:SystemRoot -ChildPath $Service.ImagePath
}
elseif ($Service.ImagePath -match "^\\\?\?\\") {
$Service.ImagePath -replace "\\\?\?\\",""
}
else {
$Service.ImagePath
}
}
function Get-DriverList {
[CmdletBinding()] param()
if ($CachedDriverList.Count -eq 0) {
# If the cached driver list hasn't been initialized yet, enumerate all drivers,
# resolve their paths and populate the cache.
Write-Verbose "Populating driver list cache..."
$Services = Get-ServiceList -FilterLevel 1 | Where-Object { @('KernelDriver','FileSystemDriver','RecognizerDriver') -contains $_.Type }
foreach ($Service in $Services) {
$ImagePath = Resolve-DriverImagePath -Service $Service
if (-not (Test-Path -Path $ImagePath)) { Write-Warning "Service: $($Service.Name) | Path not found: $($ImagePath)"; continue }
$Service | Add-Member -MemberType "NoteProperty" -Name "ImagePathResolved" -Value $ImagePath
[void]$CachedDriverList.Add($Service)
}
}
$CachedDriverList | ForEach-Object { $_ }
}
function Get-VulnerableDriverHashes {
[CmdletBinding()] param ()
$VulnerableDriverList = $VulnerableDrivers | ConvertFrom-Csv -Delimiter ";"
if ($null -eq $VulnerableDriverList) { Write-Warning "Failed to get list of vulnerable drivers."; return }
$VulnerableDriverList | ForEach-Object {
$Result = New-Object -TypeName PSObject
$Result | Add-Member -MemberType "NoteProperty" -Name "Url" -Value "https://www.loldrivers.io/drivers/$($_.Id)"
$Result | Add-Member -MemberType "NoteProperty" -Name "HashType" -Value $_.HashType
$Result | Add-Member -MemberType "NoteProperty" -Name "Hash" -Value ([string[]] ($_.Hash -split ","))
$Result
}
}
function Find-VulnerableDriver {
[CmdletBinding()] param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Object] $Service
)
BEGIN {
Write-Verbose "Initiliazing list of vulnerable driver hashes..."
$VulnerableDriverHashes = Get-VulnerableDriverHashes
}
PROCESS {
$ResultHash = ""
$ResultUrl = ""
$FileHashMd5 = ""
$FileHashSha1 = ""
$FileHashSha256 = ""
foreach ($VulnerableDriverHash in $VulnerableDriverHashes) {
switch ($VulnerableDriverHash.HashType) {
"Md5" {
if ([String]::IsNullOrEmpty($FileHashMd5)) { $FileHashMd5 = Get-FileHashHex -FilePath $Service.ImagePathResolved -Algorithm MD5 }
if ($VulnerableDriverHash.Hash -contains $FileHashMd5) {
$ResultHash = $FileHashMd5
$ResultUrl = $VulnerableDriverHash.Url
}
break
}
"Sha1" {
if ([String]::IsNullOrEmpty($FileHashSha1)) { $FileHashSha1 = Get-FileHashHex -FilePath $Service.ImagePathResolved -Algorithm SHA1 }
if ($VulnerableDriverHash.Hash -contains $FileHashSha1) {
$ResultHash = $FileHashSha1
$ResultUrl = $VulnerableDriverHash.Url
}
break
}
"Sha256" {
if ([String]::IsNullOrEmpty($FileHashSha256)) { $FileHashSha256 = Get-FileHashHex -FilePath $Service.ImagePathResolved -Algorithm SHA256 }
if ($VulnerableDriverHash.Hash -contains $FileHashSha256) {
$ResultHash = $FileHashSha256
$ResultUrl = $VulnerableDriverHash.Url
}
break
}
default {
Write-Warning "Empty or invalid hash type: '$($VulnerableDriverHash.HashType)' ($($VulnerableDriverHash.Url))"
}
}
if (-not [String]::IsNullOrEmpty($ResultHash)) {
$Service | Add-Member -MemberType "NoteProperty" -Name "FileHash" -Value $ResultHash
$Service | Add-Member -MemberType "NoteProperty" -Name "Url" -Value $ResultUrl
$Service
break
}
}
}
}