forked from charleslbryant/PowerShellAccessControl
-
Notifications
You must be signed in to change notification settings - Fork 15
/
PowerShellAccessControlHelperFunctions.ps1
4095 lines (3474 loc) · 183 KB
/
PowerShellAccessControlHelperFunctions.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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function Get-CimInstanceFromPath {
<#
.SYNOPSIS
Converts a WMI path into a CimInstance object.
.DESCRIPTION
Get-CimInstanceFromPath takes an absolute WMI path and creates a WMI query that
Get-CimInstance takes as an argument. If everything works properly, a CimInstance
object will be returned.
.EXAMPLE
$Bios = Get-WmiObject Win32_BIOS; Get-CimInstanceFromPath -Path $Bios.__PATH
.EXAMPLE
Get-WmiObject Win32_BIOS | Get-CimInstanceFromPath
.NOTES
The function currently only works with absolute paths. It can easily be modified
to work with relative paths, too.
#>
<#
This function allows CIM objects to be represented as a string (like the WMI __PATH property). For example,
if you pass a CIM object that the module can get a security descriptor for (like a __SystemSecurity instance),
the SD's path property will include this string so that an instance of the CIM object can be obtained again.
WMI cmdlets have this functionality built-in:
$Computer = gwmi Win32_ComputerSystem
[wmi] $Computer.__PATH # Get WMI instance from path
This function was more usefule in v1.x of this module before GetNamedSecurityInfo() and GetSecurityInfo()
windows APIs were used.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true)]
[Alias('__PATH')]
# WMI path (Path must be absolute path, not relative path). See __PATH
# property on an object returned from Get-WmiObject
[string] $Path
)
process {
if ($Path -match "^\\\\(?<computername>[^\\]*)\\(?<namespace>[^:]*):(?<classname>[^=\.]*)(?<separator>\.|(=@))(?<keyvaluepairs>.*)?$") {
$Query = "SELECT * FROM {0}" -f $matches.classname
switch ($matches.separator) {
"." {
# Key/value pairs are in string, so add a WHERE clause
$Query += " WHERE {0}" -f [string]::Join(" AND ", $matches.keyvaluepairs -split ",")
}
}
$GcimParams = @{
ComputerName = $matches.computername
Namespace = $matches.namespace
Query = $Query
ErrorAction = "Stop"
}
}
else {
throw "Path not in expected format!"
}
Get-CimInstance @GcimParams
}
}
function Get-CimPathFromInstance {
<#
The opposite of the Get-CimInstanceFromPath. This is how a __PATH property can be computed for a CIM instance.
Like the other function, this was more useful in 1.x versions of the module. It is still used in the GetWmiObjectInfo
helper function and the Get-Win32SecurityDescriptor exposed function.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[ciminstance] $InputObject
)
process {
$Keys = $InputObject.CimClass.CimClassProperties |
Where-Object { $_.Qualifiers.Name -contains "Key" } |
Select-Object Name, CimType |
Sort-Object Name
$KeyValuePairs = $Keys | ForEach-Object {
$KeyName = $_.Name
switch -regex ($_.CimType) {
"Boolean|.Int\d+" {
# No quotes surrounding value:
$Value = $InputObject.$KeyName
}
"DateTime" {
# Conver to WMI datetime
$Value = '"{0}"' -f [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime($InputObject.$KeyName)
}
"Reference" {
throw "CimInstance contains a key with type 'Reference'. This isn't currenlty supported (but can be added later)"
}
default {
# Treat it like a string and cross your fingers:
$Value = '"{0}"' -f ($InputObject.$KeyName -replace "`"", "\`"")
}
}
"{0}={1}" -f $KeyName, $Value
}
if ($KeyValuePairs) {
$KeyValuePairsString = ".{0}" -f ($KeyValuePairs -join ",")
}
else {
# This is how WMI seems to handle paths with no keys
$KeyValuePairsString = "=@"
}
"\\{0}\{1}:{2}{3}" -f $InputObject.CimSystemProperties.ServerName,
($InputObject.CimSystemProperties.Namespace -replace "/","\"),
$InputObject.CimSystemProperties.ClassName,
$KeyValuePairsString
}
}
function Convert-AclToString {
<#
Converts an ACL into a string that has been formatted with Format-Table. The AccessToString and
AuditToString properties on the PSObject returned from Get-SecurityDescriptor use this function.
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
$Ace,
[int] $MaxAces = 20,
[PowerShellAccessControl.AppliesTo] $DefaultAppliesTo
)
begin {
$TableProperties = @(
@{ Label = "Type"
Expression = {
$CurrentAce = $_
if ($_.IsInherited) { $ExtraChar = ""}
else { $ExtraChar = "*" }
$ReturnString = switch ($_.AceType.ToString()) {
"AccessAllowed" { "Allow$ExtraChar" }
"AccessDenied" { "Deny$ExtraChar" }
"SystemAudit" {
$AuditSuccess = $AuditFailure = " "
if ($CurrentAce.AuditFlags -band [System.Security.AccessControl.AuditFlags]::Success) {
$AuditSuccess = "S"
}
if ($CurrentAce.AuditFlags -band [System.Security.AccessControl.AuditFlags]::Failure) {
$AuditFailure = "F"
}
"Audit$ExtraChar {0}{1}" -f $AuditSuccess, $AuditFailure
}
default { $_ }
}
$ReturnString -join " "
}
Width = 9
}
@{ Label = "IdentityReference"
Expression = {
$_.Principal -replace "($env:COMPUTERNAME|BUILTIN|NT AUTHORITY)\\", ""
}
Width = 20
}
@{ Label = "Rights"
Expression = {
$Display = $_.AccessMaskDisplay -replace "\s\(.*\)$"
if (($PSBoundParameters.ContainsKey("DefaultAppliesTo") -and ($_.AppliesTo.value__ -ne $DefaultAppliesTo.value__)) -or ($_.OnlyApplyToThisContainer)) {
#$Display += " (Special)"
$Display = "Special"
}
$Display
}
Width = 20
}
)
# If the following properties are the same, the ACEs will be grouped together
$PropertiesToGroupBy = @(
"AceType"
"SecurityIdentifier"
"StringPermissions" # Modified form of the AccessMaskDisplay property, which is a string representation of the AccessMask (not grouping on that b/c GenericRights would mean that the AccessMasks might not match, while the effecitve rights do)
"IsInherited"
"OnlyApplyToThisContainer"
"AuditFlags" # Doesn't affect grouping access rights; this is a CommonAce property
"ObjectAceType" # Since it will be null if this is an ACE that doesn't contain this property, shouldn't affect grouping of normal non-object ACEs
"InheritedObjectAceType" # Since it will be null if this is an ACE that doesn't contain this property, shouldn't affect grouping of normal non-object ACEs
)
$CollectedAces = @()
$ExtraMessage = $null
}
process {
$CollectedAces += $Ace
if ($CollectedAces.Count -ge $MaxAces) {
$ExtraMessage = "`n<...>"
break
}
}
end {
$Output = $CollectedAces | Format-Table -Property $TableProperties -HideTableHeaders -Wrap | Out-String | % { $_.Trim() }
$Output = "{0}{1}" -f $Output, $ExtraMessage
if (-not $Output) {
"<ACL INFORMATION NOT PRESENT>"
}
else {
$Output
}
}
}
function GetAppliesToMapping {
<#
ACE inheritance and propagation are handled by the InheritanceFlags and PropagationFlags properties
on an ACE. Based on the flags enabled, a GUI ACL editor will show you two separate pieces of information
about an ACE:
1. Whether or not it applies to itself, child containers, and/or child objects
2. Whether or not it applies only to direct children (one level deep) or all descendants (infinite
depth)
#1 is handled by both flags enumerations and #2 is only handled by PropagationFlags. This function
provides a way for determining #1 and #2 if you provide the flags enumerations, and it also provides
a way to get the proper flags enumerations for #1 if you provide string representations of where you
would like the ACE to apply.
#>
[CmdletBinding(DefaultParameterSetName='FromAppliesTo')]
param(
[Parameter(Mandatory=$true, ParameterSetName="FromAppliesTo", Position=0)]
[PowerShellAccessControl.AppliesTo] $AppliesTo,
[Parameter(Mandatory=$true, ParameterSetname="ToAppliesTo", ValueFromPipelineByPropertyName=$true)]
[System.Security.AccessControl.InheritanceFlags] $InheritanceFlags,
[Parameter(Mandatory=$true, ParameterSetname="ToAppliesTo", ValueFromPipelineByPropertyName=$true)]
[System.Security.AccessControl.PropagationFlags] $PropagationFlags,
[Parameter(ParameterSetname="ToAppliesTo")]
[switch] $CheckForNoPropagateInherit,
[Parameter(Mandatory=$true, ParameterSetName="ADFromAppliesTo")]
[PowerShellAccessControl.AppliesTo] $ADAppliesTo,
[Parameter(ParameterSetName="ADFromAppliesTo")]
[switch] $OnlyApplyToThisADContainer = $false
)
begin {
$Format = "{0},{1}"
$AppliesToMapping = @{ # Numeric values from [PowershellAccessControl.AppliesTo] flags enum
#ThisObjectOnly
1 = $Format -f [System.Security.AccessControl.InheritanceFlags]::None.value__, [System.Security.AccessControl.PropagationFlags]::None.value__
#ChildContainersOnly
2 = $Format -f [System.Security.AccessControl.InheritanceFlags]::ContainerInherit.value__, [System.Security.AccessControl.PropagationFlags]::InheritOnly.value__
#ThisObjectAndChildContainers
3 = $Format -f [System.Security.AccessControl.InheritanceFlags]::ContainerInherit.value__, [System.Security.AccessControl.PropagationFlags]::None.value__
#ChildObjectsOnly
4 = $Format -f [System.Security.AccessControl.InheritanceFlags]::ObjectInherit.value__, [System.Security.AccessControl.PropagationFlags]::InheritOnly.value__
#ThisObjectAndChildObjects
5 = $Format -f [System.Security.AccessControl.InheritanceFlags]::ObjectInherit.value__, [System.Security.AccessControl.PropagationFlags]::None.value__
#ChildContainersAndChildObjectsOnly
6 = $Format -f ([System.Security.AccessControl.InheritanceFlags] "ContainerInherit, ObjectInherit").value__, [System.Security.AccessControl.PropagationFlags]::InheritOnly.value__
#ThisObjectChildContainersAndChildObjects
7 = $Format -f ([System.Security.AccessControl.InheritanceFlags] "ContainerInherit, ObjectInherit").value__, [System.Security.AccessControl.PropagationFlags]::None.value__
}
}
process {
switch ($PSCmdlet.ParameterSetName) {
"FromAppliesTo" {
$MappingString = $AppliesToMapping[$AppliesTo.value__]
if ($MappingString -eq $null) {
Write-Error ("Unable to map AppliesTo value ({0} to inheritance and propagation flags!" -f $AppliesTo)
return
}
$Mappings = $MappingString -split ","
New-Object PSObject -Property @{
InheritanceFlags = [System.Security.AccessControl.InheritanceFlags] $Mappings[0]
PropagationFlags = [System.Security.AccessControl.PropagationFlags] $Mappings[1]
}
}
"ADFromAppliesTo" {
$Format = "{0}, {1}"
$ADAppliesToMapping = @{ # Numeric values from System.DirectoryServices.ActiveDirectorySecurityInheritance
# None is the same as [AppliesTo]::Object (doesn't matter if only applies here is set)
($Format -f [PowerShellAccessControl.AppliesTo]::Object.value__, $false) = [System.DirectoryServices.ActiveDirectorySecurityInheritance]::None
($Format -f [PowerShellAccessControl.AppliesTo]::Object.value__, $true) = [System.DirectoryServices.ActiveDirectorySecurityInheritance]::None
# All is the same as [AppliesTo]::Object, ChildContainers and applies to only this container false
($Format -f ([PowerShellAccessControl.AppliesTo] "Object, ChildContainers").value__, $false) = [System.DirectoryServices.ActiveDirectorySecurityInheritance]::All
# SelfAndChildren is the same as [AppliesTo]::Object, ChildContainers and applies to only this container is true
($Format -f ([PowerShellAccessControl.AppliesTo] "Object, ChildContainers").value__, $true) = [System.DirectoryServices.ActiveDirectorySecurityInheritance]::SelfAndChildren
# Descendats is the same as [AppliesTo]::ChildContainers and applies to only this container false
($Format -f [PowerShellAccessControl.AppliesTo]::ChildContainers.value__, $false) = [System.DirectoryServices.ActiveDirectorySecurityInheritance]::Descendents
# Children is the same as [AppliesTo]::ChildContainers and applies to only this container true
($Format -f [PowerShellAccessControl.AppliesTo]::ChildContainers.value__, $true) = [System.DirectoryServices.ActiveDirectorySecurityInheritance]::Children
}
# Get numeric form of AppliesTo (get rid of ChildObjects if it is present)
$AppliesToInt = $ADAppliesTo.value__ -band ([int32]::MaxValue -bxor [PowerShellAccessControl.AppliesTo]::ChildObjects)
$AdSecurityInheritance = $ADAppliesToMapping[($Format -f $AppliesToInt, $OnlyApplyToThisADContainer)]
if ($AdSecurityInheritance -eq $null) {
Write-Error ("Unable to convert AppliesTo ($ADAppliesTo) and OnlyApplyToThisContainer ($OnlyApplyToThisADContainer) to ActiveDirectorySecurityInheritance")
return
}
$AdSecurityInheritance
}
"ToAppliesTo" {
if ($CheckForNoPropagateInherit) {
$PropagationFlags = $PropagationFlags.value__
# NoPropagateInherit doesn't deal with AppliesTo, so make sure that flags isn't active
if ($PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::NoPropagateInherit) {
$true
}
else {
$false
}
}
else {
# NoPropagateInherit doesn't deal with AppliesTo, so make sure that flag isn't active
if ($PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::NoPropagateInherit) {
[System.Security.AccessControl.PropagationFlags] $PropagationFlags = $PropagationFlags -bxor [System.Security.AccessControl.PropagationFlags]::NoPropagateInherit
}
$MappingString = $Format -f $InheritanceFlags.value__, $PropagationFlags.value__
$FlagsValue = $AppliesToMapping.Keys | where { $AppliesToMapping.$_ -eq $MappingString }
[PowerShellAccessControl.AppliesTo] $FlagsValue
}
}
}
}
}
function ConvertToSpecificAce {
<#
This function will take a CommonAce or ObjectAce and convert it into a .NET ACE that can be used
with security descriptors for Files, Folders, Registry keys, and AD objects. At some point, this
will probably be merged with ConvertToCommonAce to have a single function that looks at any type
of ACE coming in, and converts it to the right type based on the $AclType.
This function allows Add-AccessControlEntry and Remove-AccessControlEntry to work with SDs from
the native Get-Acl cmdlet.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
$Rules,
[Parameter(Mandatory=$true)]
# The type of the ACL that this ACE will belong to.
[type] $AclType
)
begin {
# Figure out what the final type of the rule should be. This depends on
# the $AclType, and (if the ACL type is a CommonSecurityDescriptor), the
# ACE itself
if ($AclType.FullName -match "^(System\.Security\.AccessControl\.|System\.DirectoryServices\.)(\w+?)Security$") {
# If its a File/DirectorySecurity create a FileSystemAccessRule (or Audit); otherwise, match can be used
# as found (Registry or ActiveDirectory are all that I know of that will match this and work with New-Ace).
$AclRuleKind = "{0}{1}{{0}}Rule" -f $Matches[1], ($Matches[2] -replace "^File|^Directory", "FileSystem")
$AccessMaskParamName = $Matches[2] -replace "^Directory", "Folder"
# This will leave a string with a {0} where Access or Audit will go later
}
elseif ($AclType.FullName -eq "System.Security.AccessControl.CommonSecurityDescriptor") {
# This isn't suppported until a future release:
throw ("{0} ACLs aren't supported" -f $AclType.FullName)
# Final rule will need to either be a CommonAce or an ObjectAce (rules aren't different
# b/w Access and Audit rules)
# ObjectAce if .ObjectAceFlags exists and has flags other than 'None'
# This is a design decision that may change. For non-AD ACEs, this is easy: .ObjectAceFlags
# won't exist, so they will be converted to CommonAce objects (if they're not already). For
# AD ACEs, though, either type is fine. ActiveDirectorySecurity objects always have .ObjectAceFlags
# properties, even if the property is set to 'None'. This function would take one of those and
# only output an ObjectAce if an ObjectAceType or InheritedObjectAceType were set.
# Since more than one ACE can come through at once, this check is performed in the foreach()
# section in the process block.
}
else {
throw "Unknown ACL type ($($AclType.FullName))"
}
}
process {
foreach ($Rule in $Rules) {
# See note in begin block for an explanation of this check:
if ($AclType.Name -eq "CommonSecurityDescriptor") {
if ($Rule.ObjectAceFlags -and $Rule.ObjectAceFlags -ne "None") {
$AclRuleKind = "System.Security.AccessControl.ObjectAce"
}
else {
$AclRuleKind = "System.Security.AccessControl.CommonAce"
}
}
if ($Rule.AuditFlags -and $Rule.AuditFlags -ne [System.Security.AccessControl.AuditFlags]::None) {
# This must be an audit rule
$AuditOrAccess = "Audit"
}
else {
# This must be an access rule
$AuditOrAccess = "Access"
}
$CurrentRuleKind = $AclRuleKind -f $AuditOrAccess
# Check to see if it's already the right type of rule
if ($Rule.GetType().FullName -eq $CurrentRuleKind) {
Write-Debug ("{0}: Rule already $CurrentRuleKind; no need to convert" -f $MyInvocation.InvocationName)
$Rule
continue
}
Write-Debug ("{0}: Rule is currently {1}; needs to be converted to {2}" -f $MyInvocation.InvocationName, $Rule.GetType().FullName, $CurrentRuleKind)
# Make sure this is a known AceType (also, strip away 'Object' if it is at the end
# of the type)
if ($Rule.AceType -notmatch "^(\w+?)(Object)?$") {
throw "Unknown ACE type ($($Rule.AceType))"
}
$CurrentAceType = $Matches[1]
$NewAceParams = @{
AceType = $CurrentAceType
Principal = $Rule.SecurityIdentifier
$AccessMaskParamName = $Rule.AccessMask
AppliesTo = $Rule | GetAppliesToMapping
OnlyApplyToThisContainer = $Rule | GetAppliesToMapping -CheckForNoPropagateInherit
}
if ($Rule.ObjectAceType) {
$NewAceParams.ObjectAceType = $Rule.ObjectAceType
}
if ($Rule.InheritedObjectAceType) {
$NewAceParams.InheritedObjectAceType = $Rule.InheritedObjectAceType
}
if ($AuditOrAccess -eq "Audit") {
# Convert flags to string, split on comma, trim trailing or leading spaces, and
# create a boolean value to simulate [switch] statement for splatting:
$Rule.AuditFlags.ToString() -split "," | ForEach-Object {
$NewAceParams.$("Audit{0}" -f $_.Trim()) = $true
}
}
New-AccessControlEntry @NewAceParams -ErrorAction Stop
}
}
}
function ConvertToCommonAce {
<#
When dealing with the underlying CommonSecurityDescriptor object, ACEs need to be
CommonAce or ObjectAce types. This function takes lots of different types of ACEs
and converts them to ACEs that can be used by the CommonSecurityDescripor objects.
This allows the module to work with file system rules, registry rules, Win32_ACE rules,
etc.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[AllowNull()]
[object[]] $Rules, # Allow any object to come through since we can accept different ACE types
# By default, this will create an ACE that was not inherited, even if an inherited ACE is
# passed to it. This switch will keep that (might actually flip the behavior at some point)
#
# One more thing: this won't do anything for a file or registry ACE, only an ACE from a
# Win32SD or from an ACE in a RawAcl object
[switch] $KeepInheritedFlag
)
process {
foreach ($Rule in $Rules) {
if ($Rule -eq $null) { continue } # PSv2 iterates once if $Rules is null
# We work with System.Security.AccessControl.CommonAce objects, so make sure whatever came in
# is one of those, or can be converted to one:
Write-Debug "$($MyInvocation.MyCommand): Type of rule is '$($Rule.GetType().FullName)'"
switch ($Rule.GetType().FullName) {
{ $Rule.pstypenames -contains $__AdaptedAceTypeName } {
$IsRuleInherited = $Rule.IsInherited
# This is an ace created by the module; anything with this typename should be able to be
# piped directly to New-AccessControlEntry
# Note: Valid types should be CommonAce or ObjectAce
# Make the rule:
Write-Debug "$($MyInvocation.MyCommand): Rule is adapted type; running original back through New-AccessControlEntry"
$Rule = $Rule | New-AccessControlEntry
break
}
{ "System.Security.AccessControl.CommonAce", "System.Security.AccessControl.ObjectAce" -contains $_ } {
# Get a copy of the rule (we don't want to touch the original object)
Write-Debug "$($MyInvocation.MyCommand): No conversion necessary"
$Rule = $Rule.Copy()
$IsRuleInherited = [bool] ([int] $Rule.AceFlags -band [System.Security.AccessControl.AceFlags]::Inherited.value__)
break
}
{ $_ -eq "System.Security.AccessControl.FileSystemAccessRule" -or
$_ -eq "System.Security.AccessControl.RegistryAccessRule" -or
$_ -eq "System.DirectoryServices.ActiveDirectoryAccessRule" } {
# File system access rule or registry access rule
$IsRuleInherited = $Rule.IsInherited
if ($Rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow) {
$AceQualifier = [System.Security.AccessControl.AceQualifier]::AccessAllowed
}
else {
$AceQualifier = [System.Security.AccessControl.AceQualifier]::AccessDenied
}
$Params = @{
AceType = $AceQualifier
Principal = $Rule.IdentityReference
AppliesTo = $Rule | GetAppliesToMapping
OnlyApplyToThisContainer = $Rule | GetAppliesToMapping -CheckForNoPropagateInherit
GenericAce = $true
}
if ($_ -eq "System.Security.AccessControl.FileSystemAccessRule") {
$Params.FileRights = $Rule.FileSystemRights
}
elseif ($_ -eq "System.Security.AccessControl.RegistryAccessRule") {
$Params.RegistryRights = $Rule.RegistryRights
}
else {
# AD access rule
$Params.ActiveDirectoryRights = [int] $Rule.ActiveDirectoryRights
$Params.ObjectAceType = $Rule.ObjectType
$Params.InheritedObjectAceType = $Rule.InheritedObjectType
}
# Make the rule:
Write-Debug "$($MyInvocation.MyCommand): Calling New-AccessControlEntry to create CommonAce from access rule"
$Rule = New-AccessControlEntry @Params
break
}
{ $_ -eq "System.Security.AccessControl.FileSystemAuditRule" -or
$_ -eq "System.Security.AccessControl.RegistryAuditRule" -or
$_ -eq "System.DirectoryServices.ActiveDirectoryAuditRule" } {
# File system or registry audit
$IsRuleInherited = $Rule.IsInherited
$Params = @{
Principal = $Rule.IdentityReference
AppliesTo = $Rule | GetAppliesToMapping
OnlyApplyToThisContainer = $Rule | GetAppliesToMapping -CheckForNoPropagateInherit
GenericAce = $true
AceType = [System.Security.AccessControl.AceQualifier]::SystemAudit
AuditSuccess = [bool] ($Rule.AuditFlags -band [System.Security.AccessControl.AuditFlags]::Success)
AuditFailure = [bool] ($Rule.AuditFlags -band [System.Security.AccessControl.AuditFlags]::Failure)
}
if ($_ -eq "System.Security.AccessControl.FileSystemAuditRule") {
$Params.FileSystemRights = $Rule.FileSystemRights
}
elseif ($_ -eq "System.Security.AccessControl.RegistryAuditRule") {
$Params.RegistryRights = $Rule.RegistryRights
}
else {
# AD audit rule
$Params.ActiveDirectoryRights = [int] $Rule.ActiveDirectoryRights
$Params.ObjectAceType = $Rule.ObjectType
$Params.InheritedObjectAceType = $Rule.InheritedObjectType
}
# Make the rule:
Write-Debug "$($MyInvocation.MyCommand): Calling New-AccessControlEntry to create CommonAce from audit rule"
$Rule = New-AccessControlEntry @Params
break
}
{ ($_ -eq "System.Management.ManagementBaseObject" -and
($Rule.__CLASS -eq "Win32_ACE") -or ($Rule.__CLASS -eq "__ACE")) -or
($_ -eq "Microsoft.Management.Infrastructure.CimInstance" -and
($Rule.CimClass.CimClassName -eq "Win32_ACE") -or ($Rule.CimClass.CimClassName -eq "__ACE")) } {
$IsRuleInherited = [bool] ([int] $Rule.AceFlags -band [System.Security.AccessControl.AceFlags]::Inherited.value__)
# Long and scary looking condition, but it just means do the
# following if it's a WMI object of the Win32_ACE class
$Principal = ([System.Security.Principal.SecurityIdentifier] $Rule.Trustee.SIDString)
if ($Rule.AccessMask.GetType().FullName -eq "System.UInt32") {
# I've seen file access rights with UInts; convert them to signed ints:
$AccessMask = [System.BitConverter]::ToInt32([System.BitConverter]::GetBytes($Rule.AccessMask), 0)
}
else {
$AccessMask = $Rule.AccessMask
}
# Common params b/w access and audit ACEs:
$Params = @{
Principal = $Principal
AccessMask = $AccessMask
AceFlags = $Rule.AceFlags
AceType = [System.Security.AccessControl.AceType] $Rule.AceType
}
if ($Rule.AceType -eq [System.Security.AccessControl.AceQualifier]::SystemAudit) {
# Not an access entry, but an audit entry
$Params.AuditSuccess = [bool] ([int] $Rule.AceFlags -band [System.Security.AccessControl.AceFlags]::SuccessfulAccess.value__)
$Params.AuditFailure = [bool] ([int] $Rule.AceFlags -band [System.Security.AccessControl.AceFlags]::FailedAccess.value__)
}
# Make the rule:
Write-Debug "$($MyInvocation.MyCommand): Calling New-AccessControlEntry to create CommonAce from Win32_ACE"
$Rule = New-AccessControlEntry @Params
break
}
default {
Write-Error "Unknown access rule type!"
return
}
}
if (-not $KeepInheritedFlag) {
# There is a possibility that the ACE that came through
# this function was inherited. If this function is being used,
# it's usually to add or remove an ACE. In either of those
# scenarios, you don't want the resulting ACE to still be
# inherited, so remove that flag if it's present
if ([int] $Rule.AceFlags -band [System.Security.AccessControl.AceFlags]::Inherited.value__) {
$Rule.AceFlags = [int] $Rule.AceFlags -bxor [System.Security.AccessControl.AceFlags]::Inherited.value__
}
}
else {
if ($IsRuleInherited -and (-not ([int] $Rule.AceFlags -band [System.Security.AccessControl.AceFlags]::Inherited.value__))) {
# If the original rule was inherited, but the converted one isn't, fix it!
$Rule.AceFlags = [int] $Rule.AceFlags -bxor [System.Security.AccessControl.AceFlags]::Inherited.value__
}
}
# Output the rule:
$Rule
}
}
}
function GetSecurityInfo {
<#
Wraps the PInvoke signature for GetNamedSecurityInfo and GetSecurityInfo. Path validation is up
to the caller (but this function should return a meaningful error message if an error is encountered)
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ParameterSetName="Named")]
[string] $Path,
[Parameter(Mandatory=$true, Position=0, ParameterSetName="NotNamed")]
[IntPtr] $Handle,
[Parameter(Mandatory=$true)]
[System.Security.AccessControl.ResourceType] $ObjectType,
[PowerShellAccessControl.PInvoke.SecurityInformation] $SecurityInformation = "Owner, Group, Dacl"
)
# Initialize pointers for the different sections (the only pointer we'll use is the one
# to the entire SecurityDescriptor (it will work even if all sections weren't requested):
$pOwner = $pGroup = $pDacl = $pSacl = $pSecurityDescriptor = [System.IntPtr]::Zero
# Function and arguments are slightly different depending on param set:
if ($PSCmdlet.ParameterSetName -eq "Named") {
$FunctionName = "GetNamedSecurityInfo"
$FirstArgument = $Path
}
else {
$FunctionName = "GetSecurityInfo"
$FirstArgument = $Handle
}
Write-Debug "$($MyInvocation.MyCommand): Getting security descriptor for '$FirstArgument' ($ObjectType) with the following sections: $SecurityInformation"
if ($SecurityInformation -band [PowerShellAccessControl.PInvoke.SecurityInformation]::Sacl) {
# Make sure SeSecurityPrivilege is enabled, since this is required to view/modify
# the SACL
$AdjustPrivResults = SetTokenPrivilege -Privilege SeSecurityPrivilege
}
try {
# Put arguments in array b/c PSv2 seems to require it to do the Invoke() call below (I didn't look
# into it too much, but it was definitely erroring out when I had them in directly in the method
# call):
$Arguments = @(
$FirstArgument,
$ObjectType,
$SecurityInformation,
[ref] $pOwner,
[ref] $pGroup,
[ref] $pDacl,
[ref] $pSacl,
[ref] $pSecurityDescriptor
)
[PowerShellAccessControl.PInvoke.advapi32]::$FunctionName.Invoke($Arguments) |
CheckExitCode -ErrorAction Stop -Action "Getting security descriptor for '$FirstArgument'"
if ($pSecurityDescriptor -eq [System.IntPtr]::Zero) {
# I've seen this happen with ADMIN shares (\\.\c$); ReturnValue is 0,
# but no SD is returned.
#
# Invalid pointer, so no need to try to free the memory
Write-Error "No security descriptor available for '$FirstArgument'"
return
}
try {
# Get size of security descriptor:
$SDSize = [PowerShellAccessControl.PInvoke.advapi32]::GetSecurityDescriptorLength($pSecurityDescriptor)
Write-Debug "$($MyInvocation.MyCommand): SD size = $SDSize bytes"
# Put binary SD in byte array:
$ByteArray = New-Object byte[] $SDSize
[System.Runtime.InteropServices.Marshal]::Copy($pSecurityDescriptor, $ByteArray, 0, $SDSize)
# Output array:
$ByteArray
}
catch {
Write-Error $_
}
finally {
# Clear memory from SD:
Write-Debug "$($MyInvocation.MyCommand): Freeing SD memory"
[PowerShellAccessControl.PInvoke.kernel32]::LocalFree($pSecurityDescriptor) |
CheckExitCode -Action "Freeing memory for security descriptor ($FirstArgument)"
}
}
catch {
Write-Error $_
}
finally {
if ($AdjustPrivResults.PrivilegeChanged) {
# Privilege was changed earlier, so now it must be reverted:
$AdjustPrivResults = SetTokenPrivilege -Privilege SeSecurityPrivilege -Disable
if ($AdjustPrivResults.PrivilegeChanged -eq $false) {
Write-Error "Error reverting SeSecurityPrivilege back to disabled!"
}
}
}
}
function SetSecurityInfo {
<#
Wraps the PInvoke signature for SetNamedSecurityInfo and SetSecurityInfo. Path validation is up
to the caller (but this function should return a meaningful error message if an error is encountered)
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ParameterSetName="Named")]
[string] $Path,
[Parameter(Mandatory=$true, Position=0, ParameterSetName="NotNamed")]
[IntPtr] $Handle,
[Parameter(Mandatory=$true)]
[System.Security.AccessControl.ResourceType] $ObjectType,
[System.Security.Principal.IdentityReference] $Owner,
[System.Security.Principal.IdentityReference] $Group,
[System.Security.AccessControl.DiscretionaryAcl] $DiscretionaryAcl,
[System.Security.AccessControl.SystemAcl] $SystemAcl,
[PowerShellAccessControl.PInvoke.SecurityInformation] $SecurityInformation
)
if (-not $PSBoundParameters.ContainsKey("SecurityInformation")) {
# SecurityInformation enum wasn't provided, so function will
# build it up using the sections that were provided
$SecurityInformation = 0
}
# If SecurityInformation was specified, the following section may still modify it. Example would
# be if SecurityInformation contained 'Dacl, ProtectedDacl' and the Owner parameter was supplied,
# 'Owner' would be added to the SecurityInformation flag. The provided SecurityInformation will
# be bor'ed with the flags for any of the four SD sections that are provided.
# Get binary forms of sections:
foreach ($SectionName in "Owner", "Group", "DiscretionaryAcl", "SystemAcl") {
if ($PSBoundParameters.ContainsKey($SectionName)) {
$Section = $PSBoundParameters.$SectionName
$SectionLength = $Section.BinaryLength
if (-not $PSBoundParameters.ContainsKey("SecurityInformation")) {
# SecurityInformation wasn't provided to function, so it's the function's
# job to determine what needs to be set. It will do that by looking at the
# sections that were passed
# This will convert 'DiscretionaryAcl' to 'Dacl' and 'SystemAcl' to 'Sacl'
# so that the section names will match with the SecurityInfo enum (Owner and
# Group already match)
$FlagName = $SectionName -replace "(ystem|iscretionary)A", "a"
$SecurityInformation = $SecurityInformation -bor [PowerShellAccessControl.PInvoke.SecurityInformation]::$FlagName
}
if ($SectionLength -ne $null) {
$ByteArray = New-Object byte[] $SectionLength
$Section.GetBinaryForm($ByteArray, 0)
}
else {
# In this scenario, a null section was passed, but the function was called
# with this section enabled, so a null ACL will be applied
$ByteArray = $null
}
}
else {
# Section wasn't specified, so no ptr
$ByteArray = $null
}
Set-Variable -Scope Local -Name ${SectionName}ByteArray -Value $ByteArray -Confirm:$false -WhatIf:$false
}
# Function and arguments are slightly different depending on param set:
if ($PSCmdlet.ParameterSetName -eq "Named") {
$FunctionName = "SetNamedSecurityInfo"
$FirstArgument = $Path
}
else {
$FunctionName = "SetSecurityInfo"
$FirstArgument = $Handle
}
Write-Debug "$($MyInvocation.MyCommand): Setting security descriptor for '$FirstArgument' ($ObjectType) with the following sections: $SecurityInformation"
if ($SecurityInformation -band [PowerShellAccessControl.PInvoke.SecurityInformation]::Sacl) {
# Make sure SeSecurityPrivilege is enabled
$SecurityPrivResults = SetTokenPrivilege -Privilege SeSecurityPrivilege
}
if ($SecurityInformation -band [PowerShellAccessControl.PInvoke.SecurityInformation]::Owner) {
# Attempt to grant SeTakeOwnershipPrivilege and SeRestorePrivilege. If privilege isn't held,
# no error should be generated. That being said, these privs aren't always needed, so might
# end up putting logic here (or in Set-SecurityDescriptor) that checks to see if the current
# user has WRITE_OWNER and if the new owner is the current user (or a group that the current
# user has the Owner attribute set), then no privs are necessary. Also, if the current user
# doesn't have WRITE_OWNER, but they want the take ownership, then SeRestorePrivilege isn't
# required. Just some stuff to think about...
$TakeOwnershipPrivResults = SetTokenPrivilege -Privilege SeTakeOwnershipPrivilege
$RestorePrivilegeResults = SetTokenPrivilege -Privilege SeRestorePrivilege
}
try {
[PowerShellAccessControl.PInvoke.advapi32]::$FunctionName.Invoke(
$FirstArgument,
$ObjectType,
$SecurityInformation,
$OwnerByteArray,
$GroupByteArray,
$DiscretionaryAclByteArray,
$SystemAclByteArray
) | CheckExitCode -ErrorAction Stop -Action "Setting security descriptor for '$FirstArgument'"
}
catch {
Write-Error $_
}
finally {
foreach ($PrivilegeResult in ($SecurityPrivResults, $TakeOwnershipPrivResults, $RestorePrivilegeResults)) {
if ($PrivilegeResult.PrivilegeChanged) {
# If this is true, then the privilege was changed, so it needs to be
# reverted back. If it's false, then the privilege wasn't changed (either
# b/c the user doesn't hold the privilege, or b/c it was already enabled;
# it doesn't really matter why). So, disable it if it was successfully
# enabled earlier.
$NewResult = SetTokenPrivilege -Privilege $PrivilegeResult.PrivilegeName -Disable
if (-not $NewResult.PrivilegeChanged) {
# This is an error; privilege wasn't changed back to original setting
Write-Error ("Error reverting {0}" -f $PrivilegeResult.PrivilegeName)
}
}
}
}
}
function GetWmiObjectInfo {
<#
Takes as input a WMI or CimInstance object. Returns as output an object with the following
properties: ClassName, ComputerName, Path, Namespace.
All of those properties are readily available for either type of object, but they are located
in different properties depending on the type of the object. This function returns a common,
known format for the properties that GetPathInformation can use.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
$WmiObject
)
process {
$Properties = @{}
switch -Wildcard ($WmiObject.GetType().FullName) {
"Microsoft.Management.Infrastructure.CimInstance" {
$Properties.ClassName = $WmiObject.CimSystemProperties.ClassName
$Properties.ComputerName = $WmiObject.CimSystemProperties.ServerName
$Properties.Path = $WmiObject | Get-CimPathFromInstance
$Properties.Namespace = $WmiObject.CimSystemProperties.Namespace
}
"System.Management.Management*Object" {
$Properties.ClassName = $WmiObject.__CLASS
$Properties.ComputerName = $WmiObject.__SERVER
$Properties.Path = $WmiObject.__PATH
$Properties.Namespace = $WmiObject.__NAMESPACE
}
default {
throw "Unknown WMI object!"
}
}
New-Object PSObject -Property $Properties
}
}
function SetTokenPrivilege {
[CmdletBinding()]
param(
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int] $ProcessId = $pid,
[Parameter(Mandatory=$true)]
[ValidateSet( # Taken from Lee Holmes' privilege script:
"SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege", "SeChangeNotifyPrivilege",
"SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege", "SeCreatePermanentPrivilege",
"SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege", "SeDebugPrivilege", "SeEnableDelegationPrivilege",
"SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege", "SeIncreaseQuotaPrivilege",
"SeIncreaseWorkingSetPrivilege", "SeLoadDriverPrivilege", "SeLockMemoryPrivilege", "SeMachineAccountPrivilege",
"SeManageVolumePrivilege", "SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege",
"SeRestorePrivilege", "SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege",
"SeSystemEnvironmentPrivilege", "SeSystemProfilePrivilege", "SeSystemtimePrivilege", "SeTakeOwnershipPrivilege",
"SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege", "SeUndockPrivilege", "SeUnsolicitedInputPrivilege"
)]
[string] $Privilege,
[switch] $Disable
)
begin {
$Advapi32 = [PowerShellAccessControl.PInvoke.advapi32]
$Kernel32 = [PowerShellAccessControl.PInvoke.kernel32]
}
process {
if ($Disable) {
$Action = "disable"
}