forked from Qazeer/FarsightAD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FarsightAD.ps1
12784 lines (10808 loc) · 806 KB
/
FarsightAD.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
#requires -Module ActiveDirectory
# Requires the updated ActiveDirectory module compatible with PowerShell 7.
# Add-WindowsCapability -Online -Name Rsat.ServerManager.Tools~~~~0.0.1.0
Param(
[Parameter(Mandatory=$False)][String]$Server = $null,
[Parameter(Mandatory=$False)][System.Management.Automation.PSCredential]$Credential = $null,
[Parameter(Mandatory=$False)][String]$ADDriveName = "ADHunting"
)
Add-Type -AssemblyName System.Security
$ProgressPreference = 'SilentlyContinue'
########################################################
#
#
# Const for properties retrieval using Get-AD* cmdlets.
#
#
########################################################
$Script:OBJECT_MINIMAL_PROPERTIES_SET = @(
"Name",
"ObjectGUID",
"DistinguishedName",
"ObjectClass"
)
$Script:ACCOUNT_MINIMAL_PROPERTIES_SET = $OBJECT_MINIMAL_PROPERTIES_SET +
@(
"Enabled",
"SamAccountName",
"objectSid",
"Description",
"whenCreated",
"pwdLastSet",
"lastLogon",
"lastLogonTimestamp",
"logonCount"
)
$Script:ACCOUNT_EXTENDED_PROPERTIES_SET = $ACCOUNT_MINIMAL_PROPERTIES_SET +
@(
"userAccountControl",
"UserPrincipalName",
"ServicePrincipalName",
"ScriptPath"
)
$Script:ACCOUNT_ALL_PROPERTIES_SET = $ACCOUNT_EXTENDED_PROPERTIES_SET +
@(
"userCertificate"
"mS-DS-CreatorSID"
"primaryGroupID"
"SIDHistory"
"mail"
"mailNickName"
"altSecurityIdentities"
"msDS-AllowedToDelegateTo"
"msDS-AllowedToActOnBehalfOfOtherIdentity"
)
# For retriving user constructed attributes with Get-ADUser.
$Script:USER_SPECIFIC_PROPERTIES_SET = $ACCOUNT_EXTENDED_PROPERTIES_SET +
@(
"Enabled",
"Certificates",
"PasswordNeverExpires",
"PasswordNotRequired",
"AccountNotDelegated",
"DoesNotRequirePreAuth",
"SmartcardLogonRequired"
)
# For retriving computer constructed attributes with Get-ADComputer.
$Script:COMPUTER_SPECIFIC_PROPERTIES_SET = $ACCOUNT_EXTENDED_PROPERTIES_SET +
@(
"Enabled",
"Certificates",
"PasswordNeverExpires",
"PasswordNotRequired",
"AccountNotDelegated",
"DoesNotRequirePreAuth",
"dNSHostName",
"OperatingSystem",
"OperatingSystemVersion"
)
# Certificate EKU OIDs.
$Script:CERT_EKU_CLIENT_AUTH_OID = @(
"2.5.29.37.0"
"1.3.6.1.5.5.7.3.2"
"1.3.6.1.5.2.3.4"
"1.3.6.1.4.1.311.20.2.2"
)
########################################################
#
#
# Helper functions.
#
#
########################################################
function Convert-UnixTimeToISO8601 {
<#
.SYNOPSIS
Convert a Unix timestamp to a ISO 8601 date in the format yyyy-MM-dd HH:mm:ss.fff.
.PARAMETER UnixTime
Specifies the UnixTime attribute as a Int64.
.OUTPUTS
[string]
#>
Param(
[Parameter(Mandatory=$True)][Int64]$UnixTime
)
return [datetime]::FromFileTime($unixTime).ToString('yyyy-MM-dd HH:mm:ss.fff')
}
Function Get-ClassRelatedClasses {
<#
.SYNOPSIS
Get the (eventual) classes related to the specified class (subClassOf, auxiliaryClass, and systemAuxiliaryClass).
.PARAMETER ClassName
Specifies the ObjectClass attribute as a string.
.PARAMETER Server
Specifies the Active Directory Domain Services instance to connect to.
If set, passed through the cmdlets of the ActiveDirectory module as a default parameter.
.PARAMETER Credential
Specifies the user account credentials to use to perform this task.
If set, passed through the cmdlets of the ActiveDirectory module as a default parameter.
.OUTPUTS
[System.Collections.ArrayList]
#>
Param(
[Parameter(Mandatory=$True)][string]$ClassName,
[Parameter(Mandatory=$False)][String]$Server = $null,
[Parameter(Mandatory=$False)][System.Management.Automation.PSCredential]$Credential = $null
)
$PSDefaultParameterValues = @{}
If (!$Server) {
$Server = (Get-ADDomain).PDCEmulator
}
$PSDefaultParameterValues.Add("*-AD*:Server", $Server)
$PSDefaultParameterValues.Add("*-ADHunting*:Server", $Server)
$PSDefaultParameterValues.Add("Get-Class*:Server", $Server)
If ($Credential) {
$PSDefaultParameterValues.Add("*-AD*:Credential", $Credential)
$PSDefaultParameterValues.Add("*-ADHunting*:Credential", $Credential)
$PSDefaultParameterValues.Add("Get-Class*:Credential", $Credential)
}
$Classes = New-Object System.Collections.ArrayList
$null = $Classes.Add($ClassName)
$ObjectSchema = Get-ADObject -SearchBase "$((Get-ADRootDSE).SchemaNamingContext)" -LDAPFilter "(lDAPDisplayName=$ClassName)" -properties subClassOf, auxiliaryClass, systemAuxiliaryClass
$AdditionalClasses = @($ObjectSchema.subClassOf) + @($ObjectSchema.auxiliaryClass) + @($ObjectSchema.systemAuxiliaryClass)
$AdditionalClasses | Foreach-Object {
If ($_ -and !($_ -in $Classes)) {
Get-ClassRelatedClasses $_ | Where-Object { $_ -notin $Classes } | ForEach-Object {
$null = $Classes.Add($_)
}
}
}
return $Classes
}
function Get-ClassSupportedAttributes {
<#
.SYNOPSIS
Get the attributes supported by a class through a Schema lookup (of all the related classes).
.PARAMETER ClassName
Specifies the ClassName attribute as a string.
.PARAMETER Server
Specifies the Active Directory Domain Services instance to connect to.
If set, passed through the cmdlets of the ActiveDirectory module as a default parameter.
.PARAMETER Credential
Specifies the user account credentials to use to perform this task.
If set, passed through the cmdlets of the ActiveDirectory module as a default parameter.
.OUTPUTS
[System.Collections.ArrayList]
#>
Param(
[Parameter(Mandatory=$True)][string]$ClassName,
[Parameter(Mandatory=$False)][String]$Server = $null,
[Parameter(Mandatory=$False)][System.Management.Automation.PSCredential]$Credential = $null
)
$PSDefaultParameterValues = @{}
If (!$Server) {
$Server = (Get-ADDomain).PDCEmulator
}
$PSDefaultParameterValues.Add("*-AD*:Server", $Server)
$PSDefaultParameterValues.Add("*-ADHunting*:Server", $Server)
$PSDefaultParameterValues.Add("Get-Class*:Server", $Server)
If ($Credential) {
$PSDefaultParameterValues.Add("*-AD*:Credential", $Credential)
$PSDefaultParameterValues.Add("*-ADHunting*:Credential", $Credential)
$PSDefaultParameterValues.Add("Get-Class*:Credential", $Credential)
}
$ATTRIBUTE_TYPES = 'MayContain','MustContain','systemMayContain','systemMustContain'
$AllClasses = Get-ClassRelatedClasses -ClassName $ClassName
$SchemaNamingContext = (Get-ADRootDSE).SchemaNamingContext
$AllAttributes = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList))
$AllClasses | ForEach-Object {
$ClassInfo = Get-ADObject -SearchBase "$SchemaNamingContext" -LDAPFilter "(lDAPDisplayName=$_)" -Properties $ATTRIBUTE_TYPES
ForEach ($attribute in $ATTRIBUTE_TYPES) {
$null = $AllAttributes.AddRange(@($ClassInfo.$attribute))
# $AllAttributes += $ClassInfo.$attribute
}
}
return $AllAttributes
}
function Get-GPOFromGPLink {
<#
.SYNOPSIS
Extract the GPOs' DistinguishedName and link status from a gPLink attribute.
.DESCRIPTION
Extract the GPOs' DistinguishedName and link status from a gPLink attribute using a regex match.
gPLink attribute format exemple (string):
[LDAP://cn={E6913ADB-5E9D-43E0-8550-AC21456C8795},cn=policies,cn=system,DC=forest1,DC=loc;0][LDAP://CN={6AC1786C-016F-11D2-945F-00C04fB984F9},CN=Policies,CN=System,DC=forest1,DC=loc;0]
.PARAMETER gPLinkAttribute
Specifies the gPLink attribute as a string.
.OUTPUTS
[System.Collections.ArrayList]
#>
Param(
[Parameter(Mandatory=$True)][String]$gPLinkAttribute
)
If (!$gPLinkAttribute) {
return $null
}
[System.Collections.ArrayList] $GPOs = New-Object System.Collections.ArrayList
[regex]::Matches($gPLinkAttribute, "://(.*?;\d)") | ForEach-Object {
$match = $_.groups[1].value.Split(';')
$null = $GPOs.Add([PSCustomObject]@{
DistinguishedName = $match[0]
IsLinkEnabled = $match[1] % 2 -eq 0
IsLinkEnforced = $match[1] -ge 2
})
}
return ,$GPOs
}
function Get-AllOUsFromDistinguishedName {
<#
.SYNOPSIS
Extract all the OUs' DistinguishedNames from an object DistinguishedName, ordered by proximity with the object.
.PARAMETER DistinguishedNames
Specifies the DistinguishedNames attribute as a string.
.OUTPUTS
[System.Collections.ArrayList]
#>
Param(
[Parameter(Mandatory=$True)][String]$DistinguishedName
)
$Output = New-Object System.Collections.ArrayList
while ($DistinguishedName.IndexOf('OU=') -ge 0) {
$DistinguishedName = $DistinguishedName.Substring($DistinguishedName.IndexOf('OU='))
$null = $Output.Add($DistinguishedName)
# Skip "OU=" to go the next eventual OU.
$DistinguishedName = $DistinguishedName.Substring(3)
}
return ,$Output
}
function Get-X509CertificateStringFromUserCertificate {
<#
.SYNOPSIS
Return a formated string constructed from an object's usercertificate attribute.
.PARAMETER usercertificate
Specifies the Certificates attribute.
.OUTPUTS
[string]
#>
Param(
[Parameter(Mandatory=$True)] $usercertificate
)
$CertificatesString = ""
for ($i = 0; $i -lt $usercertificate.Count; $i++) {
# Requires PowerShell >= v5.
# New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($usercertificate[$i]) bugs in PowerShell v7+.
# And "X509Certificates immutable on this platform" in PowerShell v7+ so no usage of the Import method is possible.
$X509Certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([byte[]] $usercertificate[$i])
$EnhancedKeyUsageListString = If ($X509Certificate.EnhancedKeyUsageList) { [string]::join("-", $X509Certificate.EnhancedKeyUsageList) } Else { "None" }
$X509CertificateAsString = [string]::Format("SerialNumber={0}|Subject={1}|NotBefore={2}|NotAfter={3}|EnhancedKeyUsageList={4}", $X509Certificate.SerialNumber, $X509Certificate.Subject, $X509Certificate.NotBefore, $X509Certificate.NotAfter, $EnhancedKeyUsageListString)
$CertificatesString += "$X509CertificateAsString;"
}
return $CertificatesString
}
########################################################
#
#
# ACL / ACE helper functions.
#
#
########################################################
function Add-PrivilegeLevelType {
# Try catch as Add-Type may fail in a new PowerShell session with "An item with the same key has already been added" errors.
# https://github.com/PowerShell/CompletionPredictor/issues/14
If (-not ([System.Management.Automation.PSTypeName]'PrivilegeLevel').Type) {
try {
$PRIVILEGE_LEVEL_STRING =
@"
public enum PrivilegeLevel : uint {
Everyone = 0,
NonPrivileged = 1,
Privileged = 2,
}
"@
Add-Type -TypeDefinition $PRIVILEGE_LEVEL_STRING
}
catch {}
}
}
$Script:ACE_GUID_MAPPING = @{
"00000000-0000-0000-0000-000000000000" = "All"
"bf9679a8-0de6-11d0-a285-00aa003049e2" = "Script-Path property"
"e48d0154-bcf8-11d1-8702-00c04fb96050" = "Public-Information property"
"f3a64788-5306-11d1-a9c5-0000f80367c1" = "servicePrincipalName property"
"00fbf30c-91fe-11d1-aebc-0000f80367c1" = "Alt-Security-Identities property"
"5b47d60f-6090-40b2-9f37-2a4de88f3063" = "msDS-KeyCredentialLink property"
"bf9679c0-0de6-11d0-a285-00aa003049e2" = "Member property"
"3f78c3e5-f79a-46bd-a0b8-9d18116ddc79" = "msDS-AllowedToActOnBehalfOfOtherIdentity property"
"564e9325-d057-c143-9e3b-4f9e5ef46f93" = "ms-DS-principal-name property"
"00299570-246d-11d0-a768-00aa006e0529" = "User-Force-Change-Password right"
"e362ed86-b728-0842-b27d-2dea7a9df218" = "ms-DS-ManagedPassword property"
"1131f6aa-9c07-11d1-f79f-00c04fc2dcd2" = "DS-Replication-Get-Changes right"
"1131f6ad-9c07-11d1-f79f-00c04fc2dcd2" = "DS-Replication-Get-Changes-All right"
"9923a32a-3607-11d2-b9be-0000f87a36b2" = "DS-Install-Replica right"
"1131f6ac-9c07-11d1-f79f-00c04fc2dcd2" = "DS-Replication-Manage-Topology right"
"1131f6ab-9c07-11d1-f79f-00c04fc2dcd2" = "DS-Replication-Synchronize right"
"e2a36dc9-ae17-47c3-b58b-be34c55ba633" = "Create-Inbound-Forest-Trust right"
"f30e3bbe-9ff0-11d1-b603-0000f80367c1" = "gPLink property"
"f30e3bc1-9ff0-11d1-b603-0000f80367c1" = "gPCFileSysPath property"
"bf967a86-0de6-11d0-a285-00aa003049e2" = "Computer object"
"bf967a9c-0de6-11d0-a285-00aa003049e2" = "Group property object"
"f30e3bc2-9ff0-11d1-b603-0000f80367c1" = "GroupPolicyObject object"
"7b8b558a-93a5-4af7-adca-c017e67f1057" = "msDS-GroupManagedServiceAccount object"
"ce206244-5827-4a86-ba1c-1c0c386c1b64" = "msDS-ManagedServiceAccount object"
"bf967aa5-0de6-11d0-a285-00aa003049e2" = "Organizational Unit object"
"bf967aba-0de6-11d0-a285-00aa003049e2" = "User object"
"bf967a80-0de6-11d0-a285-00aa003049e2" = "attributeSchema object"
"bf967a83-0de6-11d0-a285-00aa003049e2" = "classSchema object"
"1c332fe0-0c2a-4f32-afca-23c5e45a9e77" = "ms-DFSR-ReplicationGroup object"
"18976af6-3b9e-11d2-90cc-00c04fd91ab1" = "pKIExtendedKeyUsage property"
"d15ef7d8-f226-46db-ae79-b34e560bd12c" = "msPKI-Enrollment-Flag property"
"dbd90548-aa37-4202-9966-8c537ba5ce32" = "msPKI-Certificate-Application-Policy property"
"bf967932-0de6-11d0-a285-00aa003049e2" = "cACertificate"
}
function Is-DangerousADACE {
<#
.SYNOPSIS
Determine if a given ACE is dangerous, based on the ACE access rights and impacted attributes.
Required Dependencies: ActiveDirectory module and Get-ADHuntingAllPrivilegedSIDs.
.DESCRIPTION
Return True if a given ACE is dangerous, False otherwise.
An ACE is judged to be dangerous if (all) the following conditions are meet:
- The ACE grant access (i.e AccessControlType == "Allow").
- The ACE apply to the object (i.e not InheritOnly).
- The ACE is not granted to a privileged principal (enumerated using Get-ADHuntingAllPrivilegedSIDs)
- The ACE access right is one of the following right:
- GenericAll, WriteDacl, or WriteOwner
- GenericWrite or WriteProperty on all properties
- GenericWrite or WriteProperty on one of the following attributes:
- Script-Path (bf9679a8-0de6-11d0-a285-00aa003049e2)
- Public-Information (e48d0154-bcf8-11d1-8702-00c04fb96050)
- servicePrincipalName (f3a64788-5306-11d1-a9c5-0000f80367c1)
- Alt-Security-Identities (00fbf30c-91fe-11d1-aebc-0000f80367c1)
- msDS-KeyCredentialLink (5b47d60f-6090-40b2-9f37-2a4de88f3063)
- Member (bf9679c0-0de6-11d0-a285-00aa003049e2)
- msDS-AllowedToActOnBehalfOfOtherIdentity (3f78c3e5-f79a-46bd-a0b8-9d18116ddc79)
- ms-DS-principal-name (564e9325-d057-c143-9e3b-4f9e5ef46f93)
- msPKI-Certificate-Application-Policy (dbd90548-aa37-4202-9966-8c537ba5ce32)
- pKIExtendedKeyUsage property (18976af6-3b9e-11d2-90cc-00c04fd91ab1), by precaution as msPKI-Certificate-Application-Policy seems to prevail
- msPKI-Enrollment-Flag (d15ef7d8-f226-46db-ae79-b34e560bd12c)
- cACertificate (bf967932-0de6-11d0-a285-00aa003049e2)
- AllExtendedRight or one of the following extended right:
- User-Force-Change-Password right (right's GUID: 00299570-246d-11d0-a768-00aa006e0529)
- DS-Replication-Get-Changes (rights' GUID: 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2)
- DS-Replication-Get-Changes-All (rights' GUID: 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2)
- DS-Install-Replica (right's GUID: 9923a32a-3607-11d2-b9be-0000f87a36b2)
- DS-Replication-Manage-Topology (right's GUID: 1131f6ac-9c07-11d1-f79f-00c04fc2dcd2)
- DS-Replication-Synchronize (right's GUID: 1131f6ab-9c07-11d1-f79f-00c04fc2dcd2)
- Create-Inbound-Forest-Trust (right's GUID: e2a36dc9-ae17-47c3-b58b-be34c55ba633)
- Self on all or the Member attribue (bf9679c0-0de6-11d0-a285-00aa003049e2) => right to self add one-self to a group.
For more information: https://notes.qazeer.io/active-directory/exploitation-acl_exploiting
.PARAMETER ACE
Specifies the ACE to evaluate.
.PARAMETER ACE
Specifies the object type on which the GPO was applied.
.PARAMETER Server
Specifies the Active Directory Domain Services instance to connect to.
If set, passed through the cmdlets of the ActiveDirectory module as a default parameter.
.PARAMETER Credential
Specifies the user account credentials to use to perform this task.
If set, passed through the cmdlets of the ActiveDirectory module as a default parameter.
.PARAMETER PrivilegedSIDs
Specifies the list of privileged SIDs in the domain. If not specified, the list is determined using Get-ADHuntingAllPrivilegedSIDs.
Used for optimization purposes for subsequent calls to the function.
.PARAMETER AttributedToSID
Specifies the principal (identified by its SID) the ACE is granted to.
If not specified, the SID is determined directly using the ACE.
Used for optimization purposes for subsequent calls to the function.
.OUTPUTS
[System.ValueType.Boolean]
#>
Param(
[Parameter(Mandatory=$True)][System.DirectoryServices.ActiveDirectoryAccessRule]$ACE,
[Parameter(Mandatory=$False)][String]$Server = $null,
[Parameter(Mandatory=$False)][System.Management.Automation.PSCredential]$Credential = $null,
[Parameter(Mandatory=$False)]$PrivilegedSIDs = $null,
[Parameter(Mandatory=$False)][string]$AttributedToSID,
[Parameter(Mandatory=$True)][string]$ObjectClass
)
If (!$PrivilegedSIDs) {
If (!$Server) {
$Server = (Get-ADDomain).PDCEmulator
}
$PrivilegedSIDs = If ($Credential) { Get-ADHuntingAllPrivilegedSIDs -Server $Server -Credential $Credential } Else { Get-ADHuntingAllPrivilegedSIDs -Server $Server }
}
If (!$AttributedToSID) {
try { $AttributedToSID = $ACE.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value }
catch { $AttributedToSID = $ACE.IdentityReference.Value }
}
# Deny access rights.
If ($ACE.AccessControlType -ne "Allow") {
return $False
}
# Inherit only access rights with no impact on current object.
If ($ACE.PropagationFlags -eq "InheritOnly") {
return $False
}
If ($PrivilegedSIDs.Contains($AttributedToSID) -or $AttributedToSID.EndsWith('-519')) {
#If ($AttributedToSID -in $PrivilegedSIDs -or $AttributedToSID.EndsWith('-519')) {
return $False
}
$AccessRights = $ACE.ActiveDirectoryRights.ToString()
# Take over rights.
If ($AccessRights -match 'GenericAll|WriteDacl|WriteOwner|268435456') {
# If ($ACE.ActiveDirectoryRights -match 'GenericAll|WriteDacl|WriteOwner' -or $ACE.ActiveDirectoryRights -eq 268435456) {
return $True
}
# Right to write any property of the object.
# Right to write a property that would allow potential takeover of the object.
# Script-Path bf9679a8-0de6-11d0-a285-00aa003049e2
# Public-Information e48d0154-bcf8-11d1-8702-00c04fb96050
# servicePrincipalName f3a64788-5306-11d1-a9c5-0000f80367c1
# Alt-Security-Identities 00fbf30c-91fe-11d1-aebc-0000f80367c1
# msDS-KeyCredentialLink 5b47d60f-6090-40b2-9f37-2a4de88f3063
# Member bf9679c0-0de6-11d0-a285-00aa003049e2
# msDS-AllowedToActOnBehalfOfOtherIdentity 3f78c3e5-f79a-46bd-a0b8-9d18116ddc79
# ms-DS-principal-name 564e9325-d057-c143-9e3b-4f9e5ef46f93
# gPLink (for Organizational Units) f30e3bbe-9ff0-11d1-b603-0000f80367c1
# gPCFileSysPath (for group policy object) f30e3bc1-9ff0-11d1-b603-0000f80367c1
# pKIExtendedKeyUsage 18976af6-3b9e-11d2-90cc-00c04fd91ab1
# msPKI-Enrollment-Flag d15ef7d8-f226-46db-ae79-b34e560bd12c
# msPKI-Certificate-Application-Policy dbd90548-aa37-4202-9966-8c537ba5ce32
# cACertificate bf967932-0de6-11d0-a285-00aa003049e2
# For more information: https://notes.qazeer.io/active-directory/exploitation-acl_exploiting
If ($AccessRights -match 'GenericWrite|WriteProperty|1073741824' -and $ACE.ObjectType -match '00000000-0000-0000-0000-000000000000|bf9679a8-0de6-11d0-a285-00aa003049e2|e48d0154-bcf8-11d1-8702-00c04fb96050|f3a64788-5306-11d1-a9c5-0000f80367c1|00fbf30c-91fe-11d1-aebc-0000f80367c1|5b47d60f-6090-40b2-9f37-2a4de88f3063|bf9679c0-0de6-11d0-a285-00aa003049e2|3f78c3e5-f79a-46bd-a0b8-9d18116ddc79|564e9325-d057-c143-9e3b-4f9e5ef46f93|f30e3bbe-9ff0-11d1-b603-0000f80367c1|f30e3bc1-9ff0-11d1-b603-0000f80367c1|18976af6-3b9e-11d2-90cc-00c04fd91ab1|d15ef7d8-f226-46db-ae79-b34e560bd12c|dbd90548-aa37-4202-9966-8c537ba5ce32|bf967932-0de6-11d0-a285-00aa003049e2') {
return $True
}
# All extended rights (0-[...]-0)
# User-Force-Change-Password right (right's GUID: 00299570-246d-11d0-a768-00aa006e0529)
# Replication rights to conduct a DcSync attack:
# - DS-Replication-Get-Changes (rights' GUID: 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2)
# - DS-Replication-Get-Changes-All (rights' GUID: 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2)
# Minimal rights to conduct a DCShadow attack:
# - DS-Install-Replica (right's GUID: 9923a32a-3607-11d2-b9be-0000f87a36b2)
# - DS-Replication-Manage-Topology (right's GUID: 1131f6ac-9c07-11d1-f79f-00c04fc2dcd2)
# - DS-Replication-Synchronize (right's GUID: 1131f6ab-9c07-11d1-f79f-00c04fc2dcd2)
# Right to create a forest trust Create-Inbound-Forest-Trust (right's GUID: e2a36dc9-ae17-47c3-b58b-be34c55ba633)
# Rights to generate resultant set of policy (RSOP) planning / logging: b7b1b3dd-ab09-4242-9e30-9980e5d322f7 / b7b1b3de-ab09-4242-9e30-9980e5d322f7
# Other potentially dangerous extended rights:
# - Change-Domain-MasterChange-Domain-Master (right's GUID: 014bf69c-7b3b-11d1-85f6-08002be74fab)
# - Change-Infrastructure-Master (right's GUID: cc17b1fb-33d9-11d2-97d4-00c04fd8d5cd)
# - Change-PDC (right's GUID: bae50096-4752-11d1-9052-00c04fc2d4cf)
# - Change-Rid-Master (right's GUID: d58d5f36-0a98-11d1-adbb-00c04fd8d5cd)
# - Change-Schema-Master (right's GUID: e12b56b6-0a95-11d1-adbb-00c04fd8d5cd)
# - Reanimate-Tombstones (right's GUID: 45ec5156-db7e-47bb-b53f-dbeb2d03c40f)
If ($AccessRights -match 'ExtendedRight' -and $ACE.ObjectType -match '00000000-0000-0000-0000-000000000000|00299570-246d-11d0-a768-00aa006e0529|1131f6aa-9c07-11d1-f79f-00c04fc2dcd2|1131f6ad-9c07-11d1-f79f-00c04fc2dcd2|9923a32a-3607-11d2-b9be-0000f87a36b2|1131f6ac-9c07-11d1-f79f-00c04fc2dcd2|1131f6ab-9c07-11d1-f79f-00c04fc2dcd2|e2a36dc9-ae17-47c3-b58b-be34c55ba633|b7b1b3de-ab09-4242-9e30-9980e5d322f7|b7b1b3dd-ab09-4242-9e30-9980e5d322f7|014bf69c-7b3b-11d1-85f6-08002be74fab|cc17b1fb-33d9-11d2-97d4-00c04fd8d5cd|bae50096-4752-11d1-9052-00c04fc2d4cf|d58d5f36-0a98-11d1-adbb-00c04fd8d5cd|e12b56b6-0a95-11d1-adbb-00c04fd8d5cd') {
# Filter false positive on Enterprise Read-only Domain Controllers, that have DS-Replication-Get-Changes right (1131f6aa-9c07-11d1-f79f-00c04fc2dcd2)
if ($ACE.ObjectType -eq '1131f6aa-9c07-11d1-f79f-00c04fc2dcd2' -and $AttributedToSID.EndsWith('498')) {
return $False
}
return $True
}
# Validated writes
# All validated writes: 00000000-0000-0000-0000-000000000000
# Right to add one-self to a group: bf9679c0-0de6-11d0-a285-00aa003049e2
# Validated write to service principal name: f3a64788-5306-11d1-a9c5-0000f80367c1
If (($AccessRights -match 'Self') -and ($ACE.ObjectType -match '00000000-0000-0000-0000-000000000000|bf9679c0-0de6-11d0-a285-00aa003049e2|f3a64788-5306-11d1-a9c5-0000f80367c1')) {
return $True
}
# Rights on containers (such as Organizational Units, Schema container, DFSR-GlobalSettings, etc.)
# Delete / delete subtree: Delete / DeleteTree
# Create / delete child items:
# - CreateChild: Rights to create child objects (+ optionnal object GUID)
# - DeleteChild: Rights to delete child objects (+ optionnal object GUID)
# All objects: 00000000-0000-0000-0000-000000000000
# Computer: bf967a86-0de6-11d0-a285-00aa003049e2
# Group: bf967a9c-0de6-11d0-a285-00aa003049e2
# Group policy object: f30e3bc2-9ff0-11d1-b603-0000f80367c1
# msDS-GroupManagedServiceAccount: 7b8b558a-93a5-4af7-adca-c017e67f1057
# msDS-ManagedServiceAccount: ce206244-5827-4a86-ba1c-1c0c386c1b64
# Organizational Unit: bf967aa5-0de6-11d0-a285-00aa003049e2
# User: bf967aba-0de6-11d0-a285-00aa003049e2
# attributeSchema (an attribute object in the schema): bf967a80-0de6-11d0-a285-00aa003049e2
# classSchema (a class object in the schema): bf967a83-0de6-11d0-a285-00aa003049e2
# ms-DFSR-ReplicationGroup: 1c332fe0-0c2a-4f32-afca-23c5e45a9e77
If (($ObjectClass -match 'domainDNS|msDFSR-ReplicationGroup|organizationalUnit|groupPolicyContainer') -and ($AccessRights -match 'Delete|DeleteTree|CreateChild|DeleteChild') -and ($ACE.ObjectType -match '00000000-0000-0000-0000-000000000000|bf967a86-0de6-11d0-a285-00aa003049e2|bf967a9c-0de6-11d0-a285-00aa003049e2|f30e3bc2-9ff0-11d1-b603-0000f80367c1|7b8b558a-93a5-4af7-adca-c017e67f1057|ce206244-5827-4a86-ba1c-1c0c386c1b64|bf967aa5-0de6-11d0-a285-00aa003049e2|bf967aba-0de6-11d0-a285-00aa003049e2|bf967a80-0de6-11d0-a285-00aa003049e2|bf967a83-0de6-11d0-a285-00aa003049e2|1c332fe0-0c2a-4f32-afca-23c5e45a9e77')) {
return $True
}
# Specific rights for gMSA accounts.
# Read / write on the msDS-ManagedPassword attribute (e362ed86-b728-0842-b27d-2dea7a9df218)
If ($AccessRights -match 'ReadProperty|WriteProperty|1073741824' -and $ACE.ObjectType -match 'e362ed86-b728-0842-b27d-2dea7a9df218') {
return $True
}
# Return False by default (if no matching dangerous rights found).
return $False
}
function Is-DangerousFileACE {
<#
.SYNOPSIS
Determine if a given file ACE is dangerous.
Required Dependencies: ActiveDirectory module and Get-ADHuntingAllPrivilegedSIDs.
.DESCRIPTION
Return True if a given ACE is dangerous, False otherwise.
An ACE is judged to be dangerous if (all) the following conditions are meet:
- The ACE grant access (i.e AccessControlType == "Allow").
- The ACE is not granted to a privileged principal (enumerated using Get-ADHuntingAllPrivilegedSIDs)
- The ACE access right is one of the following right:
- GenericAll, WriteDacl, or WriteOwner
- GenericWrite or WriteProperty on one of the following attributes:
.PARAMETER Server
Specifies the Active Directory Domain Services instance to connect to.
If set, passed through the cmdlets of the ActiveDirectory module as a default parameter.
.PARAMETER Credential
Specifies the user account credentials to use to perform this task.
If set, passed through the cmdlets of the ActiveDirectory module as a default parameter.
.PARAMETER PrivilegedSIDs
Specifies the list of privileged SIDs in the domain. If not specified, the list is determined using Get-ADHuntingAllPrivilegedSIDs.
Used for optimization purposes for subsequent calls to the function.
.PARAMETER ACE
Specifies the ACE to evaluate.
.PARAMETER AttributedToSID
Specifies the principal (identified by its SID) the ACE is granted to.
If not specified, the SID is determined directly using the ACE.
Used for optimization purposes for subsequent calls to the function.
.OUTPUTS
[System.ValueType.Boolean]
#>
Param(
[Parameter(Mandatory=$True)][System.Security.AccessControl.FileSystemAccessRule]$ACE,
[Parameter(Mandatory=$False)][String]$Server = $null,
[Parameter(Mandatory=$False)][System.Management.Automation.PSCredential]$Credential = $null,
[Parameter(Mandatory=$False)]$PrivilegedSIDs = $null,
[Parameter(Mandatory=$False)][string]$AttributedToSID
)
If (!$PrivilegedSIDs) {
If (!$Server) {
$Server = (Get-ADDomain).PDCEmulator
}
$PrivilegedSIDs = If ($Credential) { Get-ADHuntingAllPrivilegedSIDs -Server $Server -Credential $Credential } Else { Get-ADHuntingAllPrivilegedSIDs -Server $Server }
}
If (!$AttributedToSID) {
try { $AttributedToSID = $ACE.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value }
catch { $AttributedToSID = $ACE.IdentityReference.Value }
}
# Deny access rights.
If ($ACE.AccessControlType -ne "Allow") {
return $False
}
# Inherit only access rights with no impact on current object.
If ($ACE.PropagationFlags -eq "InheritOnly") {
return $False
}
If ($PrivilegedSIDs.Contains($AttributedToSID) -or $AttributedToSID.EndsWith('-519')) {
return $False
}
# Sensitive Windows filesystem rights (https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights)
If ($ACE.FileSystemRights -match 'FullControl|ChangePermissions|TakeOwnership|Modify|Write|WriteAttributes|WriteExtendedAttributes|WriteData|AppendData|CreateFiles|Delete|DeleteSubdirectoriesAndFiles') {
return $True
}
# Some Generic FileSystem rights may not be parsed, requiring additionnal checks.
# https://blog.cjwdev.co.uk/2011/06/28/permissions-not-included-in-net-accessrule-filesystemrights-enum/
# https://www.powershellgallery.com/packages/GPOZaurr/0.0.59/Content/GPOZaurr.psm1
# GENERIC_WRITE = 0x40000000
# GENERIC_ALL = 0x10000000
If (($ACE.FileSystemRights -eq 0x40000000) -or ($ACE.FileSystemRights -eq 0x10000000)) {
return $True
}
return $False
}
# TODO doc
function Get-ADHuntingFileParsedACL {
Param(
[Parameter(Mandatory=$True)][String]$FilePath,
[Parameter(Mandatory=$False)][Boolean]$IncludeFileInOutput = $True,
[Parameter(Mandatory=$False)]$PrivilegedSIDs = $null,
[Parameter(Mandatory=$False)]$UnprivilegedSIDs = $null,
[Parameter(Mandatory=$False)][String]$Server = $null,
[Parameter(Mandatory=$False)][System.Management.Automation.PSCredential]$Credential = $null
)
$PSDefaultParameterValues = @{}
If (!$Server) {
$Server = (Get-ADDomain).PDCEmulator
}
$PSDefaultParameterValues.Add("*-AD*:Server", $Server)
$PSDefaultParameterValues.Add("*-ADHunting*:Server", $Server)
If ($Credential) {
$PSDefaultParameterValues.Add("*-AD*:Credential", $Credential)
$PSDefaultParameterValues.Add("*-ADHunting*:Credential", $Credential)
}
If (!$PrivilegedSIDs) {
$PrivilegedSIDs = Get-ADHuntingAllPrivilegedSIDs
}
If (!$UnprivilegedSIDs) {
$UnprivilegedSIDs = Get-ADHuntingUnprivilegedSIDs
}
$FileACL = Get-Acl $FilePath
If (!$FileACL) { return $null }
$OutputObject = [PSCustomObject]@{
FileOwnerSID = $null
DangerousFileOwner = $null
DangerousFilesOwnerAsString = ""
FileSenstiveRightGrantedTo = $null
FilesSenstiveRightsAsString = ""
}
# Checks on GPO file owner.
$OutputObject.FileOwnerSID = $FileACL.GetOwner([System.Security.Principal.SecurityIdentifier]).Value
If (!$PrivilegedSIDs.Contains($OutputObject.FileOwnerSID)) {
If ($IncludeFileInOutput) { $OutputObject.DangerousFilesOwnerAsString = "File=$($FilePath) | " }
$OutputObject.DangerousFilesOwnerAsString += "Owner=$($FileACL.Owner) | OwnerSID=$($OutputObject.FileOwnerSID);"
If ($UnprivilegedSIDs.Contains($OutputObject.FileOwnerSID)) { $OutputObject.DangerousFileOwner = [PrivilegeLevel]::Everyone }
Else { $OutputObject.DangerousFileOwner = [PrivilegeLevel]::NonPrivileged }
}
# Checks on GPO file access rights.
foreach ($FileACE in $FileACL.Access) {
# Attempt to retrieve SID from ACE IdentityReference if automatically translated to principal name.
try { $FileACEAttributedToSID = $FileACE.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value }
catch { $FileACEAttributedToSID = $FileACE.IdentityReference }
# Skip non dangerous access rights (i.e rights granted to privileged principals or that do not allow modification of the file).
If (!(Is-DangerousFileACE -ACE $FileACE -AttributedToSID $FileACEAttributedToSID -PrivilegedSIDs $PrivilegedSIDs)) { continue }
If ($IncludeFileInOutput) { $OutputObject.FilesSenstiveRightsAsString += "File=$($FilePath) | " }
$OutputObject.FilesSenstiveRightsAsString += "GrantedTo=$($FileACE.IdentityReference) | GrantedToSID=$FileACEAttributedToSID | AccessType=$($FileACE.AccessControlType) | FileSystemRights=$($FileACE.FileSystemRights) | IsInherited=$($FileACE.IsInherited) | PropagationFlags=$($FileACE.PropagationFlags);"
# Check if Everyone is owner (only if no previous senstive access rights granted to every was found for performance reason).
If ($OutputObject.FileSenstiveRightGrantedTo -ne [PrivilegeLevel]::Everyone) {
If ($UnprivilegedSIDs.Contains($FileACEAttributedToSID)) { $OutputObject.FileSenstiveRightGrantedTo = [PrivilegeLevel]::Everyone }
Else { $OutputObject.FileSenstiveRightGrantedTo = [PrivilegeLevel]::NonPrivileged }
}
}
return $OutputObject
}
function Is-EnrollmentADACE {
<#
.SYNOPSIS
Determine if a given ACE allows direct or indirect certificate enrollment.
.DESCRIPTION
Return True if a given ACE allows direct or indirect certificate enrollment, False otherwise.
An ACE allows direct or indirect certificate enrollment if (all) the following conditions are meet:
- The ACE grant access (i.e AccessControlType == "Allow").
- The ACE apply to the object (i.e not InheritOnly).
- The ACE access right is one of the following right:
- GenericAll, WriteDacl, or WriteOwner
- GenericWrite or WriteProperty on all properties
- GenericWrite or WriteProperty on one of the following attributes:
- msPKI-Certificate-Application-Policy (dbd90548-aa37-4202-9966-8c537ba5ce32)
- pKIExtendedKeyUsage property (18976af6-3b9e-11d2-90cc-00c04fd91ab1), by precaution as msPKI-Certificate-Application-Policy seems to prevail.
- AllExtendedRight or one of the following extended right:
- Certificate-Enrollment right (right's GUID: 0e10c968-78fb-11d2-90d4-00c04f79dc55)
- Certificate-AutoEnrollment right (right's GUID: a05b8cc2-17bc-4802-a710-e7c15ab866a2)
For more information: https://notes.qazeer.io/active-directory/exploitation-acl_exploiting
.PARAMETER ACE
Specifies the ACE to evaluate.
.OUTPUTS
[System.ValueType.Boolean]
#>
Param(
[Parameter(Mandatory=$True)][System.DirectoryServices.ActiveDirectoryAccessRule]$ACE
)
# Deny access rights.
If ($ACE.AccessControlType -ne "Allow") {
return $False
}
# Inherit only access rights with no impact on current object.
If ($ACE.PropagationFlags -eq "InheritOnly") {
return $False
}
$AccessRights = $ACE.ActiveDirectoryRights.ToString()
# Take over rights.
If ($AccessRights -match 'GenericAll|WriteDacl|WriteOwner|268435456') {
return $True
}
# Right to write any property of the object or properties related to certificate enrollment.
If ($AccessRights -match 'GenericWrite|WriteProperty|1073741824' -and $ACE.ObjectType -match '00000000-0000-0000-0000-000000000000|dbd90548-aa37-4202-9966-8c537ba5ce32|18976af6-3b9e-11d2-90cc-00c04fd91ab1') {
return $True
}
# All extended rights (0-[...]-0)
# Certificate-Enrollment 0e10c968-78fb-11d2-90d4-00c04f79dc55
# Certificate-AutoEnrollment a05b8cc2-17bc-4802-a710-e7c15ab866a2
If ($AccessRights -match 'ExtendedRight' -and $ACE.ObjectType -match '00000000-0000-0000-0000-000000000000|0e10c968-78fb-11d2-90d4-00c04f79dc55|a05b8cc2-17bc-4802-a710-e7c15ab866a2') {
return $True
}
# Return False by default (if no matching dangerous rights found).
return $False
}
########################################################
#
#
# Hidden objects and attributes hunting.
#
#
########################################################
$Script:sourceDrsr =
@"
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
namespace drsrdotnet
{
public class drsr
{
public const int MAX_ATTRIBUTES_TO_REPLICATE = <TEMPLATE_MAX_ATTRIBUTES_TO_REPLICATE>;
// public const int MAX_ATTRIBUTES_TO_REPLICATE = 38;
#region pinvoke
[DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingFromStringBindingW",
CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Unicode, SetLastError = false)]
private static extern Int32 RpcBindingFromStringBinding(String bindingString, out IntPtr lpBinding);
[DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Unicode, SetLastError = false)]
private static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, __arglist);
[DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Unicode, SetLastError = false)]
private static extern IntPtr NdrClientCall2x64_DrsBind(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr hBinding, Guid NtdsDsaObjectGuid, DRS_EXTENSIONS_INT extensions_in, ref IntPtr pDrsExtensionsExt, ref IntPtr hDrs);
[DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Unicode, SetLastError = false)]
private static extern IntPtr NdrClientCall2x64_DrsUnbind(IntPtr pMIDL_STUB_DESC, IntPtr formatString, ref IntPtr hDrs);
[DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Unicode, SetLastError = false)]
private static extern IntPtr NdrClientCall2x64_DrsDomainControllerInfo(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr hDrs, UInt32 dcInVersion, DRS_MSG_DCINFOREQ_V1 dcInfoReq, ref UInt32 dcOutVersion, ref DRS_MSG_DCINFOREPLY_V2 dcInfoRep);
[DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Unicode, SetLastError = false)]
private static extern IntPtr NdrClientCall2x64_GetNCChanges(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr hDrs, UInt32 dwInVersion, DRS_MSG_GETCHGREQ_V8 pmsgIn, out UInt32 dwOutVersion, out DRS_MSG_GETCHGREPLY_V6 pmsgOut);
[DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Unicode, SetLastError = false)]
private static extern IntPtr NdrClientCall2x86(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr args);
[DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingFree", CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Unicode, SetLastError = false)]
private static extern Int32 RpcBindingFree(ref IntPtr lpString);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr LoadLibrary(string lib);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern void FreeLibrary(IntPtr module);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr module, string proc);
//#region RpcStringBindingCompose
[DllImport("Rpcrt4.dll", EntryPoint = "RpcStringBindingComposeW", CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Unicode, SetLastError = false)]
private static extern Int32 RpcStringBindingCompose(
String ObjUuid, String ProtSeq, String NetworkAddr, String Endpoint, String Options,
out IntPtr lpBindingString
);
[StructLayout(LayoutKind.Sequential)]
private struct RPC_SECURITY_QOS
{
public Int32 Version;
public Int32 Capabilities;
public Int32 IdentityTracking;
public Int32 ImpersonationType;
};
[DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingSetAuthInfoExW", CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Unicode, SetLastError = false)]
private static extern Int32 RpcBindingSetAuthInfoEx(IntPtr lpBinding, string ServerPrincName,
UInt32 AuthnLevel, UInt32 AuthnSvc, IntPtr identity, UInt32 AuthzSvc, ref RPC_SECURITY_QOS SecurityQOS);
[DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingSetOption", CallingConvention = CallingConvention.StdCall, SetLastError = false)]
private static extern Int32 RpcBindingSetOption(IntPtr Binding, UInt32 Option, IntPtr OptionValue);
[DllImport("Rpcrt4.dll", EntryPoint = "I_RpcBindingInqSecurityContext", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern Int32 I_RpcBindingInqSecurityContext(IntPtr Binding, out IntPtr SecurityContextHandle);
[StructLayout(LayoutKind.Sequential)]
private struct SecPkgContext_SessionKey
{
public UInt32 SessionKeyLength;
public IntPtr SessionKey;
}
[DllImport("secur32.Dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern int QueryContextAttributes(IntPtr hContext,
uint ulAttribute,
ref SecPkgContext_SessionKey pContextAttributes);