forked from charleslbryant/PowerShellAccessControl
-
Notifications
You must be signed in to change notification settings - Fork 15
/
PowerShellAccessControl.psm1
4147 lines (3552 loc) · 208 KB
/
PowerShellAccessControl.psm1
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
<#
Version 3.0 BETA notes:
- The help is not finished for the module
- There are some examples of the new functionality, but there will be mroe
- More will be added/fixed before 3.0 is released
Version 3.1 (or later) features:
- Get-EffectiveAccess will allow additional groups, user claims, and device claims
- Get-EffectiveAccess will take CAP and share permissions into account
- DSC resources will allow CAP to be associated or cleared from an SD
- Set-MandatoryIntegrityLevel
- DSC resources will be able to set MILs
- New-AccessControlEntry will be able to create CallbackAce objects (-Condition parameter??)
#>
<#
New in 3.0:
- New-AdaptedAcl re-written. Now supports ObjectAces. Major changes, so other functions have been modified:
* Synthetic properties added to original CommonAce or ObjectAce. Check this in v2
* This required changes to formatting, so now FT and FL show a Principal field instead
of an IdentityReference. There is a Principal and SecurityIdentifier property for each
ACE (this is potentially a breaking change)
* Original AccessMask is left untouched, but there is now an AccessMaskDisplay property
(not always true; generic mappings now modify access mask)
* ACEs with the same properties (except access mask) are now merged (like the ACL Editor does)
* Generic rights mapping (see Get-Acl vs Get-SD for C:\WINDOWS, C:\WINDOWS\tracing, HKLM:\SOFTWARE)
- New-AccessControlEntry (and any of the *-AccessControlEntry functions that depend on it) can now support
remote accounts. Just put the account in the '[COMPUTER]\[USER]' format. It can also take SIDs now, too
(string or SecurityIdentifier object)
Removed -User and -Group aliases for New-Ace. Group alias was causing issues when SD was piped to Add/Remove-Ace (SDs have a
'Group' property, so it was being bound to principal if the user forgot to add the -Principal (or one of its aliases) as
a named parameter
- If a SID can't be translated locally, the SDObjectType and SDPath are checked to see if it is an AD object,
in which case the domain is pulled from the SDPath and that is used as the remote computer name to attempt
translation, or if the SDPath is in the \\computername\path format, in which case the computer name is pulled
and that is used to attempt translation. If translation still can't happen, the SID object's ToString method
is overloaded and that is assigned to the principal.
- Get-AccessControlEntry:
* Can handle Native .NET SDs (from Get-Acl) - This is b/c Get-SecurityDescriptor will convert a native .NET
SD into an "adapted SD"
* Can work with ObjectAceTypes in GUID or string format
* Because Get-Acl inputs are now converted to PAC objects, New-AdaptedAcl is used directly instead of using the 'Access' property. Also, 'Access' property
will start using Get-AccessControlEntry
- New-AccessControlEntry creates AD rules
- Set-SD can now handle native .NET SDs
- Long file name support (over 260 characters)
- Callback ACEs partially work. Condition isn't current displayed, but that will be easy enough to get (just convert ACE to SDDL and
grab the conditional string from that)
- Get-Ace -AuditSuccess and -AuditFailure can't be used at the same time. To see only audits, use -AceType SystemAudit
#>
<#
Dynamic parameters have been removed because of a bug in Get-Help displaying the syntax: https://connect.microsoft.com/PowerShell/feedback/details/397832/dynamicparam-not-returned-when-aliased
(Get/Add/Remove)-AccessControlEntry all shared the parameters of New-AccessControlEntry (which had some dynamic parameters of its own). This was
b/c in early versions of the module, the parameters were changing (and before 3.0, I knew that I wanted to add AD parameters). The param blocks
have reached a point to where they are pretty stable, so it's time to declare all of them as real params.
#>
#region Helper files/types
# Read helper functions:
. "$PSScriptRoot\PowerShellAccessControlHelperFunctions.ps1"
. "$PSScriptRoot\PowerShellAccessControlPInvokeSignatures.ps1"
. "$PSScriptRoot\PowerShellAccessControlAccessMaskEnumerations.ps1"
#endregion
#region Module-wide variables
# Store a list of access mask enumerations, which will be used for dynamic parameters (ignore ActiveDirectoryRights--it is special and has its own param set in New-AccessControlEntry):
$__AccessMaskEnumerations = [System.AppDomain]::CurrentDomain.GetAssemblies() | ? { $_.GlobalAssemblyCache -eq $false } | % { $_.GetTypes() } | ? { $_.FullName -match "^PowerShellAccessControl\..*(?<!ActiveDirectory)Rights$" }
# Some constants to help out with formatting (and to help functions know what types of objects
# they're dealing with since module doesn't create a true custom .NET object yet):
$__AdaptedSecurityDescriptorTypeName = "PowerShellAccessControl.Types.AdaptedSecurityDescriptor"
$__AdaptedAceTypeName = "PowerShellAccessControl.Types.AdaptedAce"
$__EffectiveAccessTypeName = "PowerShellAccessControl.Types.EffectiveAccess"
$__EffectiveAccessListAllTypeName = "PowerShellAccessControl.Types.EffectiveAccessListAllPermissions"
# GetSecurityItem and SetSecurityItem need System.Security.AccessControl.ResourceType objects to know what
# to work on. The following type is used when GetSecurityInfo and SetSecurityInfo won't be able to work
# with the security descriptor. This module will know how to handle these resources.
$__PowerShellAccessControlResourceTypeName = "ProviderDefined"
$__PartOfDomain = Get-WmiObject Win32_ComputerSystem -Property PartOfDomain | select -exp PartOfDomain
[version] $__OsVersion = Get-WmiObject Win32_OperatingSystem -Property Version | select -exp Version
# Change this to prevent -Apply switch from always causing a prompt (if -Force or -Confirm:$false aren't supplied)
$__ConfirmImpactForApplySdModification = [System.Management.Automation.ConfirmImpact]::High
# Used for Get-AccessControlEntry; number was pulled out of my head
$__MaxFilterConditionCount = 200
# These are used for AD objects. Hash tables are used for caching, and will be populated as the functionality is requested by
# the user
# The names for the hts and ValidateSet attributes are dependent on the Get-SdObjectAceType function. It is aware of the
# naming convention used, so if these are renamed, fix that (and the functions that populate the hash tables)
$__DsPropertyTable = @{}
$__DsPropertySetTable = @{}
$__DsValidatedWriteTable = @{}
$__DsClassObjectTable = @{}
$__DsExtendedRightTable = @{}
$__DsPropertyToPropertySetTable = @{}
$__GroupedPropertyCache = @{}
# These are used with the Get ObjectAce functions (the attributes are cached so they're only populated once per session,
# and only after they're needed for the first time)
$__PropertyValidateSet = $null # New-Object System.Management.Automation.ValidateSetAttribute "Property"
$__PropertySetValidateSet = $null # New-Object System.Management.Automation.ValidateSetAttribute "PropertySet"
$__ValidatedWriteValidateSet = $null # New-Object System.Management.Automation.ValidateSetAttribute "ValidatedWrite"
$__ExtendedRightValidateSet = $null # New-Object System.Management.Automation.ValidateSetAttribute "ExtendedRight"
$__ClassObjectValidateSet = $null # New-Object System.Management.Automation.ValidateSetAttribute "Class"
#endregion
#region Settings
# Thinking of making these configurable through a function; need to figure out where to save per-user settings...
$__ObjectsToMergeAces = @(
"FileObject"
"RegistryKey"
"RegistryWow6432Key"
)
$__GetInheritanceSource = $true
$__DontTranslateGenericRights = $false
#endregion
#.ExternalHelp PowerShellAccessControl.Help.xml
function New-AccessControlEntry {
<#
DESIGN NOTES:
The GenericAccessMask param set parameters can come in through the pipeline by propertyname. This enables the following pattern:
Get-AccessControlEntry | Add-AccessControlEntry -SDObject <object>
Get-AccessControlEntry <-FilteringParams> | Remove-AccessControlEntry
AppliesTo and OnlyApplytoThisContainer can come from the pipeline now. AppliesTo will beat AceFlags if their values conflict. AceFlags
can be used to provide AuditFlags and Inheritance/Propagation flags (WMI ACE objects use AceFlags)
#>
[CmdletBinding(DefaultParameterSetName="FileRights")]
param(
#
[Parameter(Position=0, ValueFromPipelineByPropertyName=$true)]
[ValidateSet(
"AccessAllowed",
"AccessDenied",
"SystemAudit"
)]
[string] $AceType = "AccessAllowed",
[Parameter(Mandatory=$true, Position=1, ValueFromPipelineByPropertyName=$true)]
[Alias('IdentityReference','SecurityIdentifier')]
$Principal,
[Parameter(Mandatory=$true, ParameterSetName='FileRights')]
[Alias('FileSystemRights')]
[System.Security.AccessControl.FileSystemRights] $FileRights,
[Parameter(Mandatory=$true, ParameterSetName='FolderRights')]
[System.Security.AccessControl.FileSystemRights] $FolderRights,
[Parameter(Mandatory=$true, ParameterSetName='RegistryRights')]
[System.Security.AccessControl.RegistryRights] $RegistryRights,
[Parameter(Mandatory=$true, ParameterSetName='ActiveDirectoryRights')]
[PowerShellAccessControl.ActiveDirectoryRights] $ActiveDirectoryRights,
[Parameter(Mandatory=$true, ParameterSetName='GenericAccessMask', ValueFromPipelineByPropertyName=$true)]
[int] $AccessMask,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[PowerShellAccessControl.AppliesTo] $AppliesTo = "Object",
[Parameter(ValueFromPipelineByPropertyName=$true)]
[switch] $OnlyApplyToThisContainer,
[Parameter(ValueFromPipelineByPropertyName=$true, ParameterSetName='ActiveDirectoryRights')]
[Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName='ActiveDirectoryRightsObjectAceType')]
[Parameter(ParameterSetName='GenericAccessMask', ValueFromPipelineByPropertyName=$true)]
$ObjectAceType,
[Parameter(ValueFromPipelineByPropertyName=$true, ParameterSetName='ActiveDirectoryRights')]
[Parameter(ValueFromPipelineByPropertyName=$true, ParameterSetName='ActiveDirectoryRightsObjectAceType')]
[Parameter(ParameterSetName='GenericAccessMask', ValueFromPipelineByPropertyName=$true)]
$InheritedObjectAceType,
[Parameter(ParameterSetName='GenericAccessMask', ValueFromPipelineByPropertyName=$true)]
[System.Security.AccessControl.AceFlags] $AceFlags,
[Parameter(ParameterSetName='GenericAccessMask')]
[Parameter(ParameterSetName='FileRights')]
[Parameter(ParameterSetName='FolderRights')]
[Parameter(ParameterSetName='RegistryRights')]
[Parameter(ParameterSetName='ActiveDirectoryRights')]
[switch] $GenericAce
)
dynamicparam {
# Two sets of dynamic parameters are created:
# 1. Create a dynamic parameter for each of the access mask enumerations contained in the $__AccessMaskEnumerations
# variable
# 2. If -AceType is SystemAudit, create -AuditSuccess and -AuditFailure parameters
# Create the dictionary that this scriptblock will return:
$DynParamDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
foreach ($Enumeration in $__AccessMaskEnumerations) {
$ParamAttributes = New-Object System.Management.Automation.ParameterAttribute
$ParamAttributes.ParameterSetName = "Generic{0}" -f $Enumeration.Name
$ParamAttributes.Mandatory = $true
#$ParamAttributes.ValueFromPipelineByPropertyName = $true
# Create the attribute collection (PSv3 allows you to simply cast a single attribute
# to this type, but that doesn't work in PSv2)
$AttribColl = New-Object System.Collections.ObjectModel.Collection[System.Attribute] # needed for v2
$AttribColl.Add($ParamAttributes)
$DynamicParameter = New-Object System.Management.Automation.RuntimeDefinedParameter (
$Enumeration.Name,
$Enumeration,
$AttribColl #[System.Collections.ObjectModel.Collection[System.Attribute]] $ParamAttributes
)
$DynParamDictionary.Add($Enumeration.Name, $DynamicParameter)
}
if ($PSBoundParameters.AceType -eq "SystemAudit") {
foreach ($ParameterName in "AuditSuccess","AuditFailure") {
$ParamAttributes = New-Object System.Management.Automation.ParameterAttribute
# Create the attribute collection (PSv3 allows you to simply cast a single attribute
# to this type, but that doesn't work in PSv2)
$AttribColl = New-Object System.Collections.ObjectModel.Collection[System.Attribute] # needed for v2
$AttribColl.Add($ParamAttributes)
$AttribColl.Add([System.Management.Automation.AliasAttribute] [string[]] ($ParameterName -replace "Audit"))
$DynamicParameter = New-Object System.Management.Automation.RuntimeDefinedParameter (
$ParameterName,
[switch],
$AttribColl
)
$DynParamDictionary.Add($ParameterName, $DynamicParameter)
}
}
# Return the dynamic parameters
$DynParamDictionary
}
process {
$AceType = [System.Security.AccessControl.AceQualifier] $AceType
$AccessRightsParamName = $PSCmdlet.ParameterSetName -replace "^Generic", ""
$AccessRightsParamName = $AccessRightsParamName -replace "ObjectAceType$", "" # Special paramset so that AccessMask isn't required
if ($AccessRightsParamName -eq "ActiveDirectoryRights") {
$AccessMaskEnumeration = [PowerShellAccessControl.ActiveDirectoryRights]
}
else {
$AccessMaskEnumeration = $PSBoundParameters[$AccessRightsParamName].GetType()
}
#region Get Inheritance and Propagation flags
if (-not $PSBoundParameters.ContainsKey("AppliesTo")) {
if ($PSBoundParameters.ContainsKey("AceFlags") -and $AceFlags.value__ -band [System.Security.AccessControl.AceFlags]::InheritanceFlags.value__) {
# AceFlags contains inheritance/propagation info, so get the AppliesTo from that
$InheritanceFlags = $PropagationFlags = 0
foreach ($CurrentFlag in "ContainerInherit", "ObjectInherit") {
if ($AceFlags.value__ -band ([int][System.Security.AccessControl.AceFlags]::$CurrentFlag)) {
$InheritanceFlags = $InheritanceFlags -bor [System.Security.AccessControl.InheritanceFlags]::$CurrentFlag
}
}
foreach ($CurrentFlag in "NoPropagateInherit","InheritOnly") {
if ($AceFlags.value__ -band ([int][System.Security.AccessControl.AceFlags]::$CurrentFlag)) {
$PropagationFlags = $PropagationFlags -bor [System.Security.AccessControl.PropagationFlags]::$CurrentFlag
}
}
# This is extra work b/c inheritance and propagation flags will be obtained from $AppliesTo again in a minute,
# but AceFlags coming in is actually pretty rare, so I don't mind the wasted work on the function's part
$AppliesTo = GetAppliesToMapping -InheritanceFlags $InheritanceFlags -PropagationFlags $PropagationFlags
$OnlyApplyToThisContainer = [bool] ($PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::NoPropagateInherit)
}
else {
# ACEs for different types of objects have different default "AppliesTo". If -AppliesTo param wasn't specified,
# then figure out the default. Function needs to know the access mask enumeration and whether or not the ACE
# will belong to an SD that is a container. We can't know that for sure, but we can make assumptions based on
# the parameter set name:
$DefaultAppliesToParams = @{
AccessMaskEnumeration = $AccessMaskEnumeration
}
if ("RegistryRights", "GenericWmiNamespaceRights", "ActiveDirectoryRights", "ActiveDirectoryRightsObjectAceType", "FolderRights" -contains $PSCmdlet.ParameterSetName) {
$DefaultAppliesToParams.IsContainer = $true
}
$AppliesTo = GetDefaultAppliesTo @DefaultAppliesToParams
}
}
# Convert $AppliesTo and $OnlyAppliesToThisContainer to separate
# inheritance flags and propagation flags enums:
$AppliesToFlags = GetAppliesToMapping -AppliesTo $AppliesTo
$InheritanceFlags = $AppliesToFlags.InheritanceFlags
$PropagationFlags = $AppliesToFlags.PropagationFlags
if ($OnlyApplyToThisContainer) {
[System.Security.AccessControl.PropagationFlags] $PropagationFlags = $PropagationFlags -bor [System.Security.AccessControl.PropagationFlags]::NoPropagateInherit
}
#endregion
# Make sure -Principal parameter is an identity reference (NTAccount or SID)
$Principal = $Principal | ConvertToIdentityReference -ErrorAction Stop -ReturnSid
#region Get Audit flags
# Check to see if this should be an audit ACE. If so, set up the AuditFlags (these will be used
# as is when File or Registry SACL ACEs are used, and will be used to build the proper flags for
# a generic ACE)
if ($AceType -eq [System.Security.AccessControl.AceQualifier]::SystemAudit) {
$AuditFlags = @()
# Success/Failure audits may have been specified through parameters (interactive use)
if ($PSBoundParameters.AuditSuccess) { $AuditFlags += "Success" }
if ($PSBoundParameters.AuditFailure) { $AuditFlags += "Failure" }
# Or Success/Failure audits may have been specified through AceFlags (usually happens
# when another ACE is fed to New-AccessControlEntry through pipeline.
if ([int] $PSBoundParameters.AceFlags -band [System.Security.AccessControl.AceFlags]::SuccessfulAccess) { $AuditFlags += "Success" }
if ([int] $PSBoundParameters.AceFlags -band [System.Security.AccessControl.AceFlags]::FailedAccess) { $AuditFlags += "Failure" }
if ($AuditFlags) {
$AuditFlags = $AuditFlags -as [System.Security.AccessControl.AuditFlags]
}
else {
# You've got to have some audit flags
throw "You must specify audit flags when AceType is SystemAudit. Please use one or more of the following parameters: -AuditSuccess, -AuditFailure"
}
}
else {
# If this ACE will be a native .NET class ACE, then no need to worry about this variable. If this
# is going to be a generic ACE, though, the $AuditFlags, $InheritanceFlags, and $PropagationFlags
# will all be combined into a single $AceType variable, so we need to define $AuditFlags:
$AuditFlags = 0
}
#endregion
# Assign numeric access rights
$AccessRights = [int] $PSBoundParameters[$AccessRightsParamName]
# Finalize parameters to the New-Object call after switch statement:
switch -Regex ($PSCmdlet.ParameterSetName) {
"^(File|Folder)Rights$" {
$AccessControlObject = "System.Security.AccessControl.FileSystem{0}Rule"
}
"^RegistryRights$" {
$AccessControlObject = "System.Security.AccessControl.Registry{0}Rule"
}
"^ActiveDirectoryRights" {
$AccessControlObject = "System.DirectoryServices.ActiveDirectory{0}Rule"
# These actions are shared between both AD rule and GenericAce rule creations:
# We need GUIDs for ObjectAceType and InheritedObjectAceType. The parameters can come
# in as a GUID, a string (string form of GUID, or a string to search on), or a PSObject
# returned from Get-ADObjectAceGuid. The code to fix both are the same, except the variable
# name changes. For that reason, we just use Get/Set variable cmdlets to do the same thing
# for both:
foreach ($AceTypeName in "ObjectAceType", "InheritedObjectAceType") {
$AceTypeValue = Get-Variable -Name $AceTypeName -ValueOnly -Scope 0 -ErrorAction SilentlyContinue
if ($AceTypeValue -is [array]) {
Write-Error "$AceTypeName parameter takes a single value"
return
}
if ($AceTypeValue) {
# If this isn't a GUID, then do a lookup using Get-AdObjectAceGuid helper function. If it is a GUID, no
# lookup necessary (assume user or ConvertToCommonAce knows what it wants when GUID was specified)
$AceTypeObject = if ($AceTypeValue -is [PSObject] -and $AceTypeValue.Guid -is [guid]) {
New-Object PSObject -Property @{
Guid = $AceTypeValue.Guid
}
}
else {
try {
# Attempt to convert to a GUID (since string GUID may have been passed):
New-Object PSObject -Property @{
Guid = [guid] $AceTypeValue
}
}
catch {
# Conversion failed, so attempt lookup via name
$Params = @{}
$Params.Name = "^{0}$" -f $AceTypeValue
if ($AceTypeName -eq "InheritedObjectAceType") {
# This should be limited to ClassObjects (I think)
$Params.TypesToSearch = "ClassObject"
}
try {
Get-ADObjectAceGuid -ErrorAction Stop @Params | Select-SingleObject
}
catch {
Write-Error $_
return
}
}
}
$AceTypeValue = $AceTypeObject | select -ExpandProperty Guid
# If ObjectAceType was specified, this next check will make sure that the access mask contains the right access depending on the
# object type:
if ($AceTypeName -eq "ObjectAceType") {
# Find out what the access mask must contain ($ValidAccessMask) and what to
# set it to if no access mask was provided ($DefaultAccessMask)
switch -regex ($AceTypeObject.Type) {
"Property(Set)?" {
$ValidAccessMask = [PowerShellAccessControl.ActiveDirectoryRights] "ReadProperty, WriteProperty"
$DefaultAccessMask = [PowerShellAccessControl.ActiveDirectoryRights]::ReadProperty
break
}
"ExtendedRight" {
$DefaultAccessMask = $ValidAccessMask = [System.DirectoryServices.ActiveDirectoryRights]::ExtendedRight
break
}
"ValidatedWrite" {
$DefaultAccessMask = $ValidAccessMask = [System.DirectoryServices.ActiveDirectoryRights]::Self
break
}
"ClassObject" {
$ValidAccessMask = [System.DirectoryServices.ActiveDirectoryRights] "CreateChild, DeleteChild"
$DefaultAccessMask = [System.DirectoryServices.ActiveDirectoryRights]::CreateChild
break
}
default {
# Don't do anything
$ValidAccessMask = $ActiveDirectoryRights
$DefaultAccessMask = $ActiveDirectoryRights
}
}
if (-not ($AccessRights -band $ValidAccessMask)) {
if (-not $ValidAccessMask) {
Write-Error "Please provide access rights to the -ActiveDirectoryRights parameter."
return
}
elseif ($ValidAccessMask -ne $DefaultAccessMask) {
# If this happens, that means there's more than one access right implied
# by the ObjectAceType. Let the user know that we made a choice for them,
# and that they can fix that choice if they like
Write-Warning ("Valid access rights for {0} {1} are {2}. Since neither was supplied to the -ActiveDirectoryRights parameter, the {3} right was added to the access mask. If this is incorrect, please use the -ActiveDirectoryRights parameter." -f $AceTypeObject.Name, $AceTypeObject.Type, $ValidAccessMask, $DefaultAccessMask)
}
$AccessRights = $AccessRights -bor $DefaultAccessMask
}
}
}
else {
$AceTypeValue = [guid]::Empty
}
Set-Variable -Name $AceTypeName -Value $AceTypeValue -Scope 0
}
}
#region Build constructor array for non-generic ACEs
{ ("Filerights", "FolderRights", "RegistryRights", "ActiveDirectoryRights", "ActiveDirectoryRightsObjectAceType" -contains $_) -and
(-not $GenericAce) } {
# These three scenarios use the exact same actions for the ACE type/flags, so
# might as well handle them together. Constructing the rule is also identical
# besides changing the object type. all of that was handled in the previous
# two blocks, though.
if ($AceType -eq [System.Security.AccessControl.AceQualifier]::SystemAudit) {
$Flags = $AuditFlags
}
elseif ($AceType -eq [System.Security.AccessControl.AceQualifier]::AccessAllowed) {
$Flags = [System.Security.AccessControl.AccessControlType]::Allow
}
elseif ($AceType -eq [System.Security.AccessControl.AceQualifier]::AccessDenied) {
$Flags = [System.Security.AccessControl.AccessControlType]::Deny
}
else {
# Only other enum option is SystemAlarm, and that was checked on earlier, so this
# shouldn't ever happen:
throw "Unknown ACE qualifier"
}
if ($_ -match "ActiveDirectoryRights") {
# AD rule constructors are slightly different than the other rule types:
$AdSecurityInheritance = GetAppliesToMapping -ADAppliesTo $AppliesTo -OnlyApplyToThisADContainer:$OnlyApplyToThisContainer
$Arguments = @(
$Principal
$AccessRights
$Flags
$ObjectAceType
$AdSecurityInheritance
$InheritedObjectAceType
)
}
else {
# All other rule types share the same constructor
$Arguments = @(
$Principal # System.String
$AccessRights # System.Security.AccessControl.RegistryRights or FileSystemRights
$InheritanceFlags # System.Security.AccessControl.InheritanceFlags
$PropagationFlags # System.Security.AccessControl.PropagationFlags
$Flags # System.Security.AccessControl.AccessControlType or AuditFlags
)
}
}
#endregion
#region Build constructor array for generic ACEs
{ $_ -like "Generic*" -or $GenericAce } {
# Always a CommonAce, no matter if it is for DACL or SACL (AceQualifier distinguishes this)
$AccessControlObject = "System.Security.AccessControl.CommonAce"
# Instead of inheritance, propagation, and audit flags being specified separately to the constructor,
# all flags are combined into the AceFlags enumeration.
# Start with $InheritanceFlags and $PropagationFlags first:
[int] $AceFlags = [System.Security.AccessControl.AceFlags] (($InheritanceFlags.ToString() -split ", ") + ($PropagationFlags.ToString() -split ", "))
# And finish with the $AuditFlags:
if ($AuditFlags) {
# Convert the audit flag only enumeration into the right values for AceType enumeration
if ($AuditFlags -band [System.Security.AccessControl.AuditFlags]::Success) {
$AceFlags += [System.Security.AccessControl.AceFlags]::SuccessfulAccess.value__
}
if ($AuditFlags -band [System.Security.AccessControl.AuditFlags]::Failure) {
$AceFlags += [System.Security.AccessControl.AceFlags]::FailedAccess.value__
}
}
# These params are common between an ObjectAce and a CommonAce
$Arguments = @( $AceFlags # System.Security.AccessControl.AceFlags
$AceType # System.Security.AccessControl.AceQualifier
$AccessRights
$Principal
)
# If Object ACE guids were specified, we're going to create an ObjectAce instead
# of a CommonAce
if ($PSBoundParameters.ContainsKey("ObjectAceType") -or $PSBoundParameters.ContainsKey("InheritedObjectAceType")) {
$AccessControlObject = "System.Security.AccessControl.ObjectAce"
$ObjectAceFlags = 0
if ($PSBoundParameters.ContainsKey("ObjectAceType") -and $ObjectAceType -ne [guid]::Empty) {
$ObjectAceFlags = $ObjectAceFlags -bor [System.Security.AccessControl.ObjectAceFlags]::ObjectAceTypePresent
}
else {
$ObjectAceType = [guid]::Empty
}
if ($PSBoundParameters.ContainsKey("InheritedObjectAceType") -and $InheritedObjectAceType -ne [guid]::Empty) {
$ObjectAceFlags = $ObjectAceFlags -bor [System.Security.AccessControl.ObjectAceFlags]::InheritedObjectAceTypePresent
# $ObjectAceType guid already defined from parameters
}
else {
$InheritedObjectAceType = [guid]::Empty
}
$Arguments += $ObjectAceFlags
$Arguments += $ObjectAceType
$Arguments += $InheritedObjectAceType
}
# These params are common between an ObjectAce and a CommonAce; they are currently not used, but may
# be in the future
$Arguments += $false # isCallback?
$Arguments += $null # opaque data
}
#endregion
default {
Write-Error "Unknown ParameterSetName"
return
}
}
# Create the ACE object
if ($AuditFlags) {
$AuditOrAccess = "Audit"
}
else {
$AuditOrAccess = "Access"
}
$AccessControlObject = $AccessControlObject -f $AuditOrAccess
New-Object -TypeName $AccessControlObject -ArgumentList $Arguments
}
}
# Since dynamic parameters have been removed, get a list of New-Ace parameters for the functions
# that need to call New-Ace internally (they need to have a list of valid params to build hash
# tables for splatting
$__CommonParameterNames = [System.Runtime.Serialization.FormatterServices]::GetUninitializedObject([type] [System.Management.Automation.Internal.CommonParameters]) |
Get-Member -MemberType Properties |
Select-Object -ExpandProperty Name
$__NewAceParameterNames = Get-Command New-AccessControlEntry -ArgumentList SystemAudit | select -exp Parameters | select -exp Keys | where { $__CommonParameterNames -notcontains $_ }
#.ExternalHelp PowerShellAccessControl.Help.xml
function Get-AccessControlEntry {
[CmdletBinding(DefaultParameterSetName='__AllParameterSets')]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Path')]
# An object that contains a security descriptor
$InputObject,
[switch] $Audit,
[switch] $Inherited,
[switch] $NotInherited,
[switch] $Specific,
[object[]] $ObjectAceType,
[object[]] $InheritedObjectAceType,
[System.Security.AccessControl.AuditFlags] $AuditFlags,
# Old dynamic params start here:
[ValidateSet(
"AccessAllowed",
"AccessDenied",
"SystemAudit"
)]
[string[]] $AceType = "AccessAllowed",
[Alias('IdentityReference','SecurityIdentifier')]
[string[]] $Principal,
[Alias('FileSystemRights')]
[System.Security.AccessControl.FileSystemRights] $FileRights,
[System.Security.AccessControl.FileSystemRights] $FolderRights,
[System.Security.AccessControl.RegistryRights] $RegistryRights,
[PowerShellAccessControl.ActiveDirectoryRights] $ActiveDirectoryRights,
[PowerShellAccessControl.LogicalShareRights] $LogicalShareRights,
[PowerShellAccessControl.PrinterRights] $PrinterRights,
[PowerShellAccessControl.WmiNamespaceRights] $WmiNameSpaceRights,
[PowerShellAccessControl.ServiceAccessRights] $ServiceAccessRights,
[PowerShellAccessControl.ProcessAccessRights] $ProcessAccessRights,
[int] $AccessMask,
[PowerShellAccessControl.AppliesTo] $AppliesTo,
[switch] $OnlyApplyToThisContainer
)
<#
dynamicparam {
$DynamicParams = GetNewAceParams -RemoveMandatoryAttribute -ConvertTypesToArrays
# These params have their own parameter sets that shouldn't be enforced on this
# function. They've been added to the param block, so they need to be removed
# from the dynamic param dictionary.
foreach ($ParamToRemove in "ObjectAceType", "InheritedObjectAceType") {
[void] $DynamicParams.Remove($ParamToRemove)
}
$DynamicParams
}
#>
begin {
# This function is going to call New-AdaptedAcl on a security descriptor object. New-AdaptedAcl
# takes switch parameters for -Dacl and -Sacl (or both). Build a hash table based on -AceType
# sent to this function that can be splatted to New-AdaptedAcl (since that can save work that
# New-AdaptedAcl might have to do otherwise)
$AdaptedAclParams = @{
GetInheritanceSource = $__GetInheritanceSource
DontTranslateGenericRights = $__DontTranslateGenericRights
}
if (-not $PSBoundParameters.AceType) {
# No AceType specified, so show both DACL and SACL
$AdaptedAclParams.Dacl = $true
$AdaptedAclParams.Sacl = $true
}
else {
if ($PSBoundParameters.AceType -match "^Access") {
$AdaptedAclParams.Dacl = $true
}
if ($PSBoundParameters.AceType -match "^SystemAudit") {
$AdaptedAclParams.Sacl = $true
}
}
#region Build the filter array
# Any parameter that New-AccessControlEntry has can be used to build the ACE filter,
# so get each of the parameter names:
# $NewAceParamNames = (GetNewAceParams).GetEnumerator() | select -exp Key
$NewAceParamNames = $__NewAceParameterNames
$NewAceParamNames += "Inherited", "NotInherited", "AuditFlags" # Add params defined for the function but not in New-AccessControlEntry
$Filter = @()
foreach ($ParamName in $NewAceParamNames) {
$CurrentFilter = @()
foreach ($Object in $PSBoundParameters.$ParamName) {
if ($Object -eq $null) { continue } # Ignore nulls
switch -regex ($ParamName) {
Principal {
# Add Principal condition to the Where-Object SB; using regular expression to search
# "^(.*\\)?" and "$" are added to string to allow for an optional domain before the
# username.
#
# There is no need for different behavior when -Specific is used because the ^ and $
# achors are already being used. User can still use * wildcard.
#
# Two replace operations:
# 1. Replaces a * with a .* so that regex will behave the way that * does with the
# -like operator
# 2. Escape any single backslashes with double backslashes
$CurrentFilter += '$_.Principal -match "^(.*\\)?{0}$"' -f (($Object | ModifySearchRegex) -replace "(?<!\\)\\(?!\\)", '\$0') # Replace single backslash w/ double backslash. This present problems if user presents a regex that has a character escaped...
break
}
"ObjectAceType$" {
# Object ace. Because Get-ADObjectAceGuid helper function returns an object, need to
# check to see what type this parameter is
if ($Object -is [PSObject] -and $Object.Guid -is [guid]) {
# Assume object came from Get-AdObjectAceGuid
$Object = $Object.Guid
}
elseif ($Object -as [guid]) {
# User passed in a GUID object, or a string representation of a GUID
$Object = $Object -as [guid]
}
# We need to build a filter string. The left side of the comparison operation
# will differ depending on whether or not a GUID or string was passed, but it
# will always start the same:
$LeftSide = '$_.{0}' -f $ParamName
if ($Object -isnot [guid]) {
# If it's a string, the filter scriptblock will need to call Get-AdObjectAceGuid
$LeftSide += ' -and ((Get-ADObjectAceGuid -Guid $_.{0} -ErrorAction SilentlyContinue) | select -exp Name)' -f $ParamName
$ObjectAceTypeParamName = "Name" # Used for looking up unique types below
}
else {
$ObjectAceTypeParamName = "Guid" # Used for looking up unique types below
}
# Build the right side of the comparison (only different if $Specific is specified)
$RightSide = $Object.ToString() | ModifySearchRegex
if ($Specific) {
$RightSide = "^$RightSide`$"
}
$FilterString = '{0} -match "{1}"' -f $LeftSide, $RightSide
# If -Specific was provided, we're done here. If not, there are a few other things to check
if ($Specific) {
$CurrentFilter += $FilterString
break
}
if ($ParamName -eq "ObjectAceType") {
# An ACE doesn't have to have an ObjectAceType to allow permission over the object type for that GUID. For example, an ACE giving
# Administrators the 'ExtendedRight' access w/o specifying an ObjectAceType would give Administrators ALL extended rights. This
# extra -or for the $FilterString attempts to take care of that
$ParamHashTable = @{
$ObjectAceTypeParamName = $Object | ModifySearchRegex
ErrorAction = "SilentlyContinue"
}
$ExtraFilterStrings = Get-ADObjectAceGuid @ParamHashTable | Select-Object -Unique -ExpandProperty Type | Where-Object { $_ } | ForEach-Object {
switch -wildcard ($_) {
ValidatedWrite {
$LimitingAccess = "Self"
break
}
Property* {
$LimitingAccess = "ReadProperty, WriteProperty"
break
}
ClassObject {
$LimitingAccess = "CreateChild, DeleteChild"
break
}
default {
# If it makes it here, the object type matches the right's name
$LimitingAccess = $_
}
}
'($_.AccessMask -band {0})' -f ([PowerShellAccessControl.ActiveDirectoryRights] $LimitingAccess).value__
}
if ($ExtraFilterStrings) {
$ExtraFilterString = '(-not ($_.ObjectAceFlags -band [System.Security.AccessControl.ObjectAceFlags]::ObjectAceTypePresent) -and ({0}))' -f ($ExtraFilterStrings -join " -or ")
$FilterString = "({0}) -or ({1})" -f $FilterString, $ExtraFilterString
}
}
elseif ($ParamName -eq "InheritedObjectAceType") {
$FilterString = "({0}) -or ({1})" -f $FilterString, '(-not ($_.ObjectAceFlags -band [System.Security.AccessControl.ObjectAceFlags]::InheritedObjectAceTypePresent))'
}
$CurrentFilter += $FilterString
break
}
"(Not)?Inherited" {
if ($ParamName -eq "NotInherited") {
# Negate the $Object value
$Object = (-not $Object) -as [switch]
}
$ParamName = "IsInherited"
}
"Audit(Success|Failure)" {
$Object = [System.Security.AccessControl.AuditFlags]::($ParamName -replace "Audit")
$ParamName = "AuditFlags"
}
"Rights$" {
# Lots of different names for the AccessMask. Treat any of the parameters that end
# in 'Rights' as an access mask
$ParamName = "AccessMask"
}
.* {
# Match on anything. Some parameters will have met a condition and broken out. Others
# may have hit, but it was just to massage the ParamName or the data. Finish their
# filter building here:
$Type = $Object.GetType()
if (($Type.IsEnum -and ($Type.GetCustomAttributes([System.FlagsAttribute], $false))) -or $ParamName -eq "AccessMask") {
# AccessMask can be numeric, so treat that the same as a flags enumeration:
if ($Specific) {
# Enumerations must match exactly what was input.
$CurrentFilter += '($_.{0} -eq {1})' -f $ParamName, ([int] $Object)
}
else {
# Not specific, so a setting that gives more access/rights than what is
# being requested can also be returned (so Modify file rights will match
# on FullControl as well as Modify)
$CurrentFilter += '($_.{0} -band {1}) -eq {1}' -f $ParamName, ([int] $Object)
}
}
elseif ($Type -eq [switch]) {
# Any switches (remember -AuditSuccess and -AuditFailure won't make it here)
# get a simple filter added:
$CurrentFilter += '$_.{0} -eq ${1}' -f $ParamName, $Object.IsPresent
}
else {
# Treat any other types as a string (allow wildcards)
$CurrentFilter += '$_.{0} -match "^{1}$"' -f $ParamName, ($Object.ToString() | ModifySearchRegex)
}
}
}
}
if ($CurrentFilter.Count -gt $__MaxFilterConditionCount) {
# I've seen PS crash when this is too big (I ran it with 'Get-AccessControlEntry -ObjectAceType (Get-ADObjectAceGuid -Name * -TypesToSearch Property)',
# which is an insane amount of conditions since the -ObjectAceType just isn't built for that type of filter
Write-Warning "The condition filter count for the '$ParamName' parameter ($($CurrentFilter.Count)) is greater than the maximum count of $__MaxFilterConditionCount. The '$ParamName' parameter is being ignored."
$CurrentFilter = @()
}
if ($CurrentFilter.Count -gt 0) {
$Filter += "({0})" -f ($CurrentFilter -join ") -or (")
}
}
#endregion
# No conditions, so create a script block that will always return true:
if ($Filter.Count -eq 0) { $Filter += '$true' }
try {
$FilterSB = [scriptblock]::Create("({0})" -f ($Filter -join ") -and ("))
}
catch {
Write-Error $_
continue
}
Write-Debug "$($PSCmdlet.MyInvocation.MyCommand): Filtering SB: $FilterSB"
}
process {
# Go through each SD object:
foreach ($CurrentObject in $InputObject) {
if ($CurrentObject.pstypenames -notcontains $__AdaptedSecurityDescriptorTypeName) {
# If this isn't a Get-Sd or Get-Acl object, try to run Get-SecurityDescriptor on it
$AuditPropertyExists = [bool] $CurrentObject.Audit
try {
# Call with -Audit switch if the object has an audit property that contains stuff or if the
# function itself was called with -Audit
$null = $PSBoundParameters.Remove("InputObject")
# Didn't come from Get-SecurityDescriptor, so see if Get-SecurityDescriptor can handle it
$CurrentObject | Get-SecurityDescriptor -Audit:($AuditPropertyExists -or $Audit) | Get-AccessControlEntry @PSBoundParameters
}
catch {
Write-Error $_
}
continue
}
# Build a script block
$ScriptBlockString = '$CurrentObject | New-AdaptedAcl @AdaptedAclParams'
if ($__ObjectsToMergeAces -contains $CurrentObject.ObjectType) {
$ScriptBlockString += " | MergeAclEntries"
}
& ([scriptblock]::Create($ScriptBlockString)) | Where-Object $FilterSB
}
}
}
#.ExternalHelp PowerShellAccessControl.Help.xml
function New-AdaptedSecurityDescriptor {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="BySddl")]
[string] $Sddl,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="ByBinaryForm")]
[byte[]] $BinarySD,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateScript({$_.BaseType.FullName -eq "System.Enum"})]
[type] $AccessMaskEnumeration,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateScript({
("System.Management.Automation.ScriptBlock","System.String") -contains $_.GetType().FullName
})]
[Alias("Description")]
[string] $Path = "[NO PATH PROVIDED]",
[Parameter(ValueFromPipelineByPropertyName=$true)]
[System.Security.AccessControl.ResourceType] $ObjectType = "Unknown",
[Parameter(ValueFromPipelineByPropertyName=$true)]
$SdPath = $Path, # Kept as an object so that HandleRefs can come through
[Parameter(ValueFromPipelineByPropertyName=$true)]
[string] $DisplayName = $Path,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias("PsIsContainer")]
[switch] $IsContainer = $false,
[switch] $IsDsObject = $false,
# This can probably simply replace IsDsObject switch. If this is present, then the
# object must be a DsObject...
[string] $DsObjectClass
)
process {
try {
switch ($PSCmdlet.ParameterSetName) {
"BySddl" {
$SecurityDescriptor = New-Object System.Security.AccessControl.CommonSecurityDescriptor($IsContainer, $IsDsObject, $Sddl)
}
"ByBinaryForm" {
$SecurityDescriptor = New-Object System.Security.AccessControl.CommonSecurityDescriptor($IsContainer, $IsDsObject, $BinarySD, 0)
}
default {
# Shouldn't get here...
throw "Unknown parameter set"
}
}
}
catch {
Write-Error $_
return
}
# "Adapt" the object to look more like something we would get with Get-Acl by adding some custom properties:
# This stuff belongs in a type file (for PS extended type system) (better) or a C# class (best), but using
# type file, the scripts run don't have access to helper functions, and I haven't gotten around to trying to
# create a C# class for the 'Adapted' security descriptor
$AdaptedSdProperites = @{
Path = $Path
SdPath = $SdPath
DisplayName = $DisplayName
ObjectType = $ObjectType
SecurityDescriptor = $SecurityDescriptor
}
if ($PSBoundParameters.ContainsKey("DsObjectClass")) {
$AdaptedSdProperites.DsObjectClass = $DsObjectClass
}
# This next section is to work around this issue: https://connect.microsoft.com/PowerShell/feedback/details/1045858/add-member-cmdlet-invokes-scriptproperty-members-when-adding-new-member
$ReturnObject = New-Object object
foreach ($PropertyEnum in $AdaptedSdProperites.GetEnumerator()) {
$ReturnObject | Add-Member -MemberType NoteProperty -Name $PropertyEnum.Key -Value $PropertyEnum.Value
}
$ReturnObject | Add-Member -MemberType ScriptProperty -Name InheritanceString -Value {
$Output = @()
if ($this.SecurityDescriptor.ControlFlags -band [System.Security.AccessControl.ControlFlags]::DiscretionaryAclPresent) {
$Output += "DACL Inheritance: $(if ($this.AreAccessRulesProtected) { "Dis" } else { "En" })abled"
}
if ($this.SecurityDescriptor.ControlFlags -band [System.Security.AccessControl.ControlFlags]::SystemAclPresent) {
$Output += "SACL Inheritance: $(if ($this.AreAuditRulesProtected) { "Dis" } else { "En" })abled"