-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathS.DS.P.psm1
1872 lines (1636 loc) · 76.5 KB
/
S.DS.P.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
Function Find-LdapObject {
<#
.SYNOPSIS
Searches LDAP server in given search root and using given search filter
.DESCRIPTION
Searches LDAP server identified by LDAP connection passed as parameter.
Attributes of returned objects are retrieved via ranged attribute retrieval by default. This allows to retrieve all attributes, including computed ones, but has impact on performace as each attribute generated own LDAP server query. Tu turn ranged attribute retrieval off, set parameter RangeSize to zero.
Optionally, attribute values can be transformed to complex types using transform registered for an attribute with 'Load' action.
.OUTPUTS
Search results as PSCustomObjects with requested properties as strings, byte streams or complex types produced by transforms
.EXAMPLE
Find-LdapObject -LdapConnection [string]::Empty -SearchFilter:"(&(sn=smith)(objectClass=user)(objectCategory=organizationalPerson))" -SearchBase:"cn=Users,dc=myDomain,dc=com"
Description
-----------
This command connects to domain controller of caller's domain on port 389 and performs the search
.EXAMPLE
$Ldap = Get-LdapConnection
Find-LdapObject -LdapConnection $Ldap -SearchFilter:'(&(cn=jsmith)(objectClass=user)(objectCategory=organizationalPerson))' -SearchBase:'ou=Users,dc=myDomain,dc=com' -PropertiesToLoad:@('sAMAccountName','objectSid') -BinaryProps:@('objectSid')
Description
-----------
This command connects to to domain controller of caller's domain and performs the search, returning value of objectSid attribute as byte stream
.EXAMPLE
$Ldap = Get-LdapConnection -LdapServer:mydc.mydomain.com -EncryptionType:SSL
Find-LdapObject -LdapConnection $Ldap -SearchFilter:"(&(sn=smith)(objectClass=user)(objectCategory=organizationalPerson))" -SearchBase:"ou=Users,dc=myDomain,dc=com"
Description
-----------
This command connects to given LDAP server and performs the search via SSL
.EXAMPLE
$Ldap = Get-LdapConnection -LdapServer "mydc.mydomain.com"
Find-LdapObject -LdapConnection:$Ldap -SearchFilter:"(&(sn=smith)(objectClass=user)(objectCategory=organizationalPerson))" -SearchBase:"cn=Users,dc=myDomain,dc=com"
Find-LdapObject -LdapConnection:$Ldap -SearchFilter:"(&(cn=myComputer)(objectClass=computer)(objectCategory=organizationalPerson))" -SearchBase:"ou=Computers,dc=myDomain,dc=com" -PropertiesToLoad:@("cn","managedBy")
Description
-----------
This command creates the LDAP connection object and passes it as parameter. Connection remains open and ready for reuse in subsequent searches
.EXAMPLE
$Ldap = Get-LdapConnection -LdapServer "mydc.mydomain.com"
Find-LdapObject -LdapConnection:$Ldap -SearchFilter:"(&(cn=SEC_*)(objectClass=group)(objectCategory=group))" -SearchBase:"cn=Groups,dc=myDomain,dc=com" | `
Find-LdapObject -LdapConnection:$Ldap -ASQ:"member" -SearchScope:"Base" -SearchFilter:"(&(objectClass=user)(objectCategory=organizationalPerson))" -propertiesToLoad:@("sAMAccountName","givenName","sn") | `
Select-Object * -Unique
Description
-----------
This one-liner lists sAMAccountName, first and last name, and DN of all users who are members of at least one group whose name starts with "SEC_" string
.EXAMPLE
$Ldap = Get-LdapConnection -Credential (Get-Credential)
Find-LdapObject -LdapConnection $Ldap -SearchFilter:"(&(cn=myComputer)(objectClass=computer)(objectCategory=organizationalPerson))" -SearchBase:"ou=Computers,dc=myDomain,dc=com" -PropertiesToLoad:@("cn","managedBy") -RangeSize 0
Description
-----------
This command creates explicit credential and uses it to authenticate LDAP query.
Then command retrieves data without ranged attribute value retrieval.
.EXAMPLE
$Users = Find-LdapObject -LdapConnection (Get-LdapConnection) -SearchFilter:"(&(sn=smith)(objectClass=user)(objectCategory=organizationalPerson))" -SearchBase:"cn=Users,dc=myDomain,dc=com" -AdditionalProperties:@("Result")
foreach($user in $Users)
{
try
{
#do some processing
$user.Result="OK"
}
catch
{
#report processing error
$user.Result=$_.Exception.Message
}
}
#report users with results of processing for each of them
$Users
Description
-----------
This command connects to domain controller of caller's domain on port 389 and performs the search.
For each user found, it also defines 'Result' property on returned object. Property is later used to store result of processing on user account
.EXAMPLE
$Ldap = Get-LdapConnection -LdapServer:ldap.mycorp.com -AuthType:Anonymous
Find-LdapObject -LdapConnection $ldap -SearchFilter:"(&(sn=smith)(objectClass=user)(objectCategory=organizationalPerson))" -SearchBase:"ou=People,ou=mycorp,o=world"
Description
-----------
This command connects to given LDAP server and performs the search anonymously.
.EXAMPLE
$Ldap = Get-LdapConnection -LdapServer:ldap.mycorp.com
$dse = Get-RootDSE -LdapConnection $conn
Find-LdapObject -LdapConnection $ldap -SearchFilter:"(&(objectClass=user)(objectCategory=organizationalPerson))" -SearchBase:"ou=People,ou=mycorp,o=world" -PropertiesToLoad *
Description
-----------
This command connects to given LDAP server and performs the direct search, retrieving all properties with value from objects found by search
.EXAMPLE
$Ldap = Get-LdapConnection -LdapServer:ldap.mycorp.com
$dse = Get-RootDSE -LdapConnection $conn
Find-LdapObject -LdapConnection $ldap -SearchFilter:"(&(objectClass=group)(objectCategory=group)(cn=MyVeryLargeGroup))" -SearchBase:"ou=People,ou=mycorp,o=world" -PropertiesToLoad member -RageSize 1000
Description
-----------
This command connects to given LDAP server and lists all members of the group, using ranged retrieval ("paging support on LDAP attributes")
.LINK
More about System.DirectoryServices.Protocols: http://msdn.microsoft.com/en-us/library/bb332056.aspx
#>
Param (
[parameter(Mandatory = $true)]
[System.DirectoryServices.Protocols.LdapConnection]
#existing LDAPConnection object retrieved with cmdlet Get-LdapConnection
#When we perform many searches, it is more effective to use the same conbnection rather than create new connection for each search request.
$LdapConnection,
[parameter(Mandatory = $true)]
[String]
#Search filter in LDAP syntax
$searchFilter,
[parameter(Mandatory = $false, ValueFromPipeline=$true)]
[Object]
#DN of container where to search
$searchBase,
[parameter(Mandatory = $false)]
[System.DirectoryServices.Protocols.SearchScope]
#Search scope
#Default: Subtree
$searchScope='Subtree',
[parameter(Mandatory = $false)]
[String[]]
#List of properties we want to return for objects we find.
#Default: empty array, meaning no properties are returned
$PropertiesToLoad=@(),
[parameter(Mandatory = $false)]
[String]
#Name of attribute for ASQ search. Note that searchScope must be set to Base for this type of seach
#Default: empty string
$ASQ,
[parameter(Mandatory = $false)]
[UInt32]
#Page size for paged search. Zero means that paging is disabled
#Default: 500
$PageSize=500,
[parameter(Mandatory = $false)]
[Int32]
# Specification of attribute value retrieval mode
# Negative value means that attribute values are loaded directly with list of objects
# Zero means that ranged attribute value retrieval is disabled and attribute values are returned in single request.
# Positive value means that each attribute value is loaded in dedicated requests in batches of given size. Usable for loading of group members
# Note: Default in query policy in AD is 1500; make sure that you do not use here higher value than allowed by LDAP server
# Default: -1 (means that ranged attribute retrieval is not used by default)
# IMPORTANT: default changed in v2.1.1 - previously it was 1000. Changed because it typically caused large perforrmance impact when using -PropsToLoad '*'
$RangeSize=-1,
[parameter(Mandatory = $false)]
[alias('BinaryProperties')]
[String[]]
#List of properties that we want to load as byte stream.
#Note: Those properties must also be present in PropertiesToLoad parameter. Properties not listed here are loaded as strings
#Note: When using transform for a property, then transform "knows" if it's binary or not, so no need to specify it in BinaryProps
#Default: empty list, which means that all properties are loaded as strings
$BinaryProps=@(),
[parameter(Mandatory = $false)]
[String[]]
<#
List of properties that we want to be defined on output object, but we do not want to load them from AD.
Properties listed here must NOT occur in propertiesToLoad list
Command defines properties on output objects and sets the value to $null
Good for having output object with all props that we need for further processing, so we do not need to add them ourselves
Default: empty list, which means that we don't want any additional propertis defined on output object
#>
$AdditionalProperties=@(),
[parameter(Mandatory = $false)]
[System.DirectoryServices.Protocols.DirectoryControl[]]
#additional controls that caller may need to add to request
$AdditionalControls=@(),
[parameter(Mandatory = $false)]
[Timespan]
#Number of seconds before request times out.
#Default: 120 seconds
$Timeout = (New-Object System.TimeSpan(0,0,120)),
[Switch]
#Whether to alphabetically sort attributes on returned objects
$SortAttributes
)
Begin
{
Function PostProcess {
param
(
[Parameter(ValueFromPipeline)]
[System.Collections.Hashtable]$data,
[bool]$Sort
)
process
{
#Flatten
$coll=@($data.Keys)
foreach($prop in $coll) {$data[$prop] = [Flattener]::FlattenArray($data[$prop])}
if($Sort)
{
#flatten and sort attributes
$coll=@($coll | Sort-Object)
$sortedData=[ordered]@{}
foreach($prop in $coll) {$sortedData[$prop] = $data[$prop]}
#return result to pipeline
[PSCustomObject]$sortedData
}
else {
[PSCustomObject]$data
}
}
}
#remove unwanted props
$PropertiesToLoad=@($propertiesToLoad | where-object {$_ -notin @('distinguishedName','1.1')})
#if asterisk in list of props to load, load all props available on object despite of required list
if($propertiesToLoad.Count -eq 0) {$NoAttributes=$true} else {$NoAttributes=$false}
if('*' -in $PropertiesToLoad) {$PropertiesToLoad=@()}
#configure LDAP connection
#preserve original value of referral chasing
$referralChasing = $LdapConnection.SessionOptions.ReferralChasing
if($pageSize -gt 0) {
#paged search silently fails in AD when chasing referrals
$LdapConnection.SessionOptions.ReferralChasing="None"
}
}
Process {
#build request
$rq=new-object System.DirectoryServices.Protocols.SearchRequest
#search base
#we support passing $null as SearchBase - user for Global Catalog searches
if($null -ne $searchBase)
{
#we support pipelining of strings, or objects containing distinguishedName property
switch($searchBase.GetType().Name) {
"String"
{
$rq.DistinguishedName=$searchBase
}
default
{
if($null -ne $searchBase.distinguishedName)
{
$rq.DistinguishedName=$searchBase.distinguishedName
}
}
}
}
#search filter in LDAP syntax
$rq.Filter=$searchFilter
#search scope
$rq.Scope=$searchScope
#paged search control for paged search
if($pageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultRequestControl]$pagedRqc = new-object System.DirectoryServices.Protocols.PageResultRequestControl($pageSize)
#asking server for best effort with paging
$pagedRqc.IsCritical=$false
$rq.Controls.Add($pagedRqc) | Out-Null
}
#add additional controls that caller may have passed
foreach($ctrl in $AdditionalControls) {$rq.Controls.Add($ctrl) | Out-Null}
#server side timeout
$rq.TimeLimit=$Timeout
#Attribute scoped query
if(-not [String]::IsNullOrEmpty($asq)) {
[System.DirectoryServices.Protocols.AsqRequestControl]$asqRqc=new-object System.DirectoryServices.Protocols.AsqRequestControl($ASQ)
$rq.Controls.Add($asqRqc) | Out-Null
}
if($NoAttributes)
{
#just run as fast as possible when not loading any attribs
GetResultsDirectlyInternal -rq $rq -conn $LdapConnection -PropertiesToLoad $PropertiesToLoad -AdditionalProperties $AdditionalProperties -BinaryProperties $BinaryProps -Timeout $Timeout -NoAttributes
}
else {
#load attributes according to desired strategy
switch($RangeSize)
{
{$_ -lt 0} {
#directly via single ldap call
#some attribs may not be loaded (e.g. computed)
GetResultsDirectlyInternal -rq $rq -conn $LdapConnection -PropertiesToLoad $PropertiesToLoad -AdditionalProperties $AdditionalProperties -BinaryProperties $BinaryProps -Timeout $Timeout | PostProcess -Sort $SortAttributes
break
}
0 {
#query attributes for each object returned using base search
#but not using ranged retrieval, so multivalued attributes with many values may not be returned completely
GetResultsIndirectlyInternal -rq $rq -conn $LdapConnection -PropertiesToLoad $PropertiesToLoad -AdditionalProperties $AdditionalProperties -AdditionalControls $AdditionalControls -BinaryProperties $BinaryProps -Timeout $Timeout | PostProcess -Sort $SortAttributes
break
}
{$_ -gt 0} {
#query attributes for each object returned using base search and each attribute value with ranged retrieval
#so even multivalued attributes with many values are returned completely
GetResultsIndirectlyRangedInternal -rq $rq -conn $LdapConnection -PropertiesToLoad $PropertiesToLoad -AdditionalProperties $AdditionalProperties -AdditionalControls $AdditionalControls -BinaryProperties $BinaryProps -Timeout $Timeout -RangeSize $RangeSize | PostProcess -Sort $SortAttributes
break
}
}
}
}
End
{
if(($pageSize -gt 0) -and ($null -ne $ReferralChasing)) {
#revert to original value of referral chasing on connection
$LdapConnection.SessionOptions.ReferralChasing=$ReferralChasing
}
}
}
Function Get-RootDSE {
<#
.SYNOPSIS
Connects to LDAP server and retrieves metadata
.DESCRIPTION
Retrieves LDAP server metadata from Root DSE object
Current implementation is specialized to metadata foung on Windows LDAP server, so on other platforms, some metadata may be empty.
Or other platforms may publish interesting metadata not available on Windwos LDAP - feel free to add here
.OUTPUTS
Custom object containing information about LDAP server
.EXAMPLE
Get-LdapConnection | Get-RootDSE
Description
-----------
This command connects to domain controller of caller's domain on port 389 and returns metadata about the server
.LINK
More about System.DirectoryServices.Protocols: http://msdn.microsoft.com/en-us/library/bb332056.aspx
#>
Param (
[parameter(Mandatory = $true, ValueFromPipeline = $true)]
[System.DirectoryServices.Protocols.LdapConnection]
#existing LDAPConnection object retrieved via Get-LdapConnection
#When we perform many searches, it is more effective to use the same connection rather than create new connection for each search request.
$LdapConnection
)
Begin
{
#initialize output objects via hashtable --> faster than add-member
#create default initializer beforehand
$propDef=[ordered]@{`
rootDomainNamingContext=$null; configurationNamingContext=$null; schemaNamingContext=$null; `
'defaultNamingContext'=$null; 'namingContexts'=$null; `
'dnsHostName'=$null; 'ldapServiceName'=$null; 'dsServiceName'=$null; 'serverName'=$null;`
'supportedLdapPolicies'=$null; 'supportedSASLMechanisms'=$null; 'supportedControl'=$null; 'supportedConfigurableSettings'=$null; `
'currentTime'=$null; 'highestCommittedUSN' = $null; 'approximateHighestInternalObjectID'=$null; `
'dsSchemaAttrCount'=$null; 'dsSchemaClassCount'=$null; 'dsSchemaPrefixCount'=$null; `
'isGlobalCatalogReady'=$null; 'isSynchronized'=$null; 'pendingPropagations'=$null; `
'domainControllerFunctionality' = $null; 'domainFunctionality'=$null; 'forestFunctionality'=$null; `
'subSchemaSubEntry'=$null; `
'msDS-ReplAllInboundNeighbors'=$null; 'msDS-ReplConnectionFailures'=$null; 'msDS-ReplLinkFailures'=$null; 'msDS-ReplPendingOps'=$null; `
'dsaVersionString'=$null; 'serviceAccountInfo'=$null; 'LDAPPoliciesEffective'=$null `
}
}
Process {
#build request
$rq=new-object System.DirectoryServices.Protocols.SearchRequest
$rq.Scope = [System.DirectoryServices.Protocols.SearchScope]::Base
$rq.Attributes.AddRange($propDef.Keys) | Out-Null
#try to get extra information with ExtendedDNControl
#RFC4511: Server MUST ignore unsupported controls marked as not critical
[System.DirectoryServices.Protocols.ExtendedDNControl]$exRqc = new-object System.DirectoryServices.Protocols.ExtendedDNControl('StandardString')
$exRqc.IsCritical=$false
$rq.Controls.Add($exRqc) | Out-Null
try {
$rsp=$LdapConnection.SendRequest($rq)
}
catch {
throw $_.Exception
return
}
#if there was error, let the exception go to caller and do not continue
#sometimes server does not return anything if we ask for property that is not supported by protocol
if($rsp.Entries.Count -eq 0) {
return;
}
$data=[PSCustomObject]$propDef
if ($rsp.Entries[0].Attributes['configurationNamingContext']) {
$data.configurationNamingContext = [NamingContext]::Parse($rsp.Entries[0].Attributes['configurationNamingContext'].GetValues([string])[0])
}
if ($rsp.Entries[0].Attributes['schemaNamingContext']) {
$data.schemaNamingContext = [NamingContext]::Parse(($rsp.Entries[0].Attributes['schemaNamingContext'].GetValues([string]))[0])
}
if ($rsp.Entries[0].Attributes['rootDomainNamingContext']) {
$data.rootDomainNamingContext = [NamingContext]::Parse($rsp.Entries[0].Attributes['rootDomainNamingContext'].GetValues([string])[0])
}
if ($rsp.Entries[0].Attributes['defaultNamingContext']) {
$data.defaultNamingContext = [NamingContext]::Parse($rsp.Entries[0].Attributes['defaultNamingContext'].GetValues([string])[0])
}
if($null -ne $rsp.Entries[0].Attributes['approximateHighestInternalObjectID']) {
try {
$data.approximateHighestInternalObjectID=[long]::Parse($rsp.Entries[0].Attributes['approximateHighestInternalObjectID'].GetValues([string]))
}
catch {
#it isn't a numeric, just return what's stored without parsing
$data.approximateHighestInternalObjectID=$rsp.Entries[0].Attributes['approximateHighestInternalObjectID'].GetValues([string])
}
}
if($null -ne $rsp.Entries[0].Attributes['highestCommittedUSN']) {
try {
$data.highestCommittedUSN=[long]::Parse($rsp.Entries[0].Attributes['highestCommittedUSN'].GetValues([string]))
}
catch {
#it isn't a numeric, just return what's stored without parsing
$data.highestCommittedUSN=$rsp.Entries[0].Attributes['highestCommittedUSN'].GetValues([string])
}
}
if($null -ne $rsp.Entries[0].Attributes['currentTime']) {
$val = ($rsp.Entries[0].Attributes['currentTime'].GetValues([string]))[0]
try {
$data.currentTime = [DateTime]::ParseExact($val,'yyyyMMddHHmmss.fZ',[CultureInfo]::InvariantCulture,[System.Globalization.DateTimeStyles]::None)
}
catch {
$data.currentTime=$val
}
}
if($null -ne $rsp.Entries[0].Attributes['dnsHostName']) {
$data.dnsHostName = ($rsp.Entries[0].Attributes['dnsHostName'].GetValues([string]))[0]
}
if($null -ne $rsp.Entries[0].Attributes['ldapServiceName']) {
$data.ldapServiceName = ($rsp.Entries[0].Attributes['ldapServiceName'].GetValues([string]))[0]
}
if($null -ne $rsp.Entries[0].Attributes['dsServiceName']) {
$val = ($rsp.Entries[0].Attributes['dsServiceName'].GetValues([string]))[0]
if($val.Contains(';'))
{
$data.dsServiceName = $val.Split(';')
}
else {
$data.dsServiceName=$val
}
}
if($null -ne $rsp.Entries[0].Attributes['serverName']) {
$val = ($rsp.Entries[0].Attributes['serverName'].GetValues([string]))[0]
if($val.Contains(';'))
{
$data.serverName = $val.Split(';')
}
else {
$data.serverName=$val
}
}
if($null -ne $rsp.Entries[0].Attributes['supportedControl']) {
$data.supportedControl = ( ($rsp.Entries[0].Attributes['supportedControl'].GetValues([string])) | Sort-Object )
}
if($null -ne $rsp.Entries[0].Attributes['supportedLdapPolicies']) {
$data.supportedLdapPolicies = ( ($rsp.Entries[0].Attributes['supportedLdapPolicies'].GetValues([string])) | Sort-Object )
}
if($null -ne $rsp.Entries[0].Attributes['supportedSASLMechanisms']) {
$data.supportedSASLMechanisms = ( ($rsp.Entries[0].Attributes['supportedSASLMechanisms'].GetValues([string])) | Sort-Object )
}
if($null -ne $rsp.Entries[0].Attributes['supportedConfigurableSettings']) {
$data.supportedConfigurableSettings = ( ($rsp.Entries[0].Attributes['supportedConfigurableSettings'].GetValues([string])) | Sort-Object )
}
if($null -ne $rsp.Entries[0].Attributes['namingContexts']) {
$data.namingContexts = @()
foreach($ctxDef in ($rsp.Entries[0].Attributes['namingContexts'].GetValues([string]))) {
$data.namingContexts+=[NamingContext]::Parse($ctxDef)
}
}
if($null -ne $rsp.Entries[0].Attributes['dsSchemaAttrCount']) {
[long]$outVal=-1
[long]::TryParse($rsp.Entries[0].Attributes['dsSchemaAttrCount'].GetValues([string]),[ref]$outVal) | Out-Null
$data.dsSchemaAttrCount=$outVal
}
if($null -ne $rsp.Entries[0].Attributes['dsSchemaClassCount']) {
[long]$outVal=-1
[long]::TryParse($rsp.Entries[0].Attributes['dsSchemaClassCount'].GetValues([string]),[ref]$outVal) | Out-Null
$data.dsSchemaClassCount=$outVal
}
if($null -ne $rsp.Entries[0].Attributes['dsSchemaPrefixCount']) {
[long]$outVal=-1
[long]::TryParse($rsp.Entries[0].Attributes['dsSchemaPrefixCount'].GetValues([string]),[ref]$outVal) | Out-Null
$data.dsSchemaPrefixCount=$outVal
}
if($null -ne $rsp.Entries[0].Attributes['isGlobalCatalogReady']) {
$data.isGlobalCatalogReady=[bool]$rsp.Entries[0].Attributes['isGlobalCatalogReady'].GetValues([string])
}
if($null -ne $rsp.Entries[0].Attributes['isSynchronized']) {
$data.isSynchronized=[bool]$rsp.Entries[0].Attributes['isSynchronized'].GetValues([string])
}
if($null -ne $rsp.Entries[0].Attributes['pendingPropagations']) {
$data.pendingPropagations=$rsp.Entries[0].Attributes['pendingPropagations'].GetValues([string])
}
if($null -ne $rsp.Entries[0].Attributes['subSchemaSubEntry']) {
$data.subSchemaSubEntry=$rsp.Entries[0].Attributes['subSchemaSubEntry'].GetValues([string])[0]
}
if($null -ne $rsp.Entries[0].Attributes['domainControllerFunctionality']) {
$data.domainControllerFunctionality=[int]$rsp.Entries[0].Attributes['domainControllerFunctionality'].GetValues([string])[0]
}
if($null -ne $rsp.Entries[0].Attributes['domainFunctionality']) {
$data.domainFunctionality=[int]$rsp.Entries[0].Attributes['domainFunctionality'].GetValues([string])[0]
}
if($null -ne $rsp.Entries[0].Attributes['forestFunctionality']) {
$data.forestFunctionality=[int]$rsp.Entries[0].Attributes['forestFunctionality'].GetValues([string])[0]
}
if($null -ne $rsp.Entries[0].Attributes['msDS-ReplAllInboundNeighbors']) {
$data.'msDS-ReplAllInboundNeighbors'=@()
foreach($val in $rsp.Entries[0].Attributes['msDS-ReplAllInboundNeighbors'].GetValues([string])) {
$data.'msDS-ReplAllInboundNeighbors'+=[xml]$Val.SubString(0,$Val.Length-2)
}
}
if($null -ne $rsp.Entries[0].Attributes['msDS-ReplConnectionFailures']) {
$data.'msDS-ReplConnectionFailures'=@()
foreach($val in $rsp.Entries[0].Attributes['msDS-ReplConnectionFailures'].GetValues([string])) {
$data.'msDS-ReplConnectionFailures'+=[xml]$Val.SubString(0,$Val.Length-2)
}
}
if($null -ne $rsp.Entries[0].Attributes['msDS-ReplLinkFailures']) {
$data.'msDS-ReplLinkFailures'=@()
foreach($val in $rsp.Entries[0].Attributes['msDS-ReplLinkFailures'].GetValues([string])) {
$data.'msDS-ReplLinkFailures'+=[xml]$Val.SubString(0,$Val.Length-2)
}
}
if($null -ne $rsp.Entries[0].Attributes['msDS-ReplPendingOps']) {
$data.'msDS-ReplPendingOps'=@()
foreach($val in $rsp.Entries[0].Attributes['msDS-ReplPendingOps'].GetValues([string])) {
$data.'msDS-ReplPendingOps'+=[xml]$Val.SubString(0,$Val.Length-2)
}
}
if($null -ne $rsp.Entries[0].Attributes['dsaVersionString']) {
$data.dsaVersionString=$rsp.Entries[0].Attributes['dsaVersionString'].GetValues([string])[0]
}
if($null -ne $rsp.Entries[0].Attributes['serviceAccountInfo']) {
$data.serviceAccountInfo=$rsp.Entries[0].Attributes['serviceAccountInfo'].GetValues([string])
}
if($null -ne $rsp.Entries[0].Attributes['LDAPPoliciesEffective']) {
$data.LDAPPoliciesEffective=@{}
foreach($val in $rsp.Entries[0].Attributes['LDAPPoliciesEffective'].GetValues([string]))
{
$vals=$val.Split(':')
if($vals.Length -gt 1) {
$data.LDAPPoliciesEffective[$vals[0]]=$vals[1]
}
}
}
$data
}
}
Function Get-LdapConnection
{
<#
.SYNOPSIS
Connects to LDAP server and returns LdapConnection object
.DESCRIPTION
Creates connection to LDAP server according to parameters passed.
.OUTPUTS
LdapConnection object
.EXAMPLE
Get-LdapConnection -LdapServer "mydc.mydomain.com" -EncryptionType Kerberos
Description
-----------
Returns LdapConnection for caller's domain controller, with active Kerberos Encryption for data transfer security
.EXAMPLE
Get-LdapConnection -LdapServer "mydc.mydomain.com" -EncryptionType Kerberos -Credential (Get-AdmPwdCredential)
Description
-----------
Returns LdapConnection for caller's domain controller, with active Kerberos Encryption for data transfer security, authenticated by automatically retrieved password from AdmPwd.E client
.EXAMPLE
$thumb = '059d5318118e61fe54fd361ae07baf4644a67347'
$cert = (dir Cert:\CurrentUser\my).Where{$_.Thumbprint -eq $Thumb}[0]
Get-LdapConnection -LdapServer "mydc.mydomain.com" -Port 636 -CertificateValidationFlags ([System.Security.Cryptography.X509Certificates.X509VerificationFlags]::AllowUnknownCertificateAuthority) -ClientCertificate $cert
Description
-----------
Returns LdapConnection over SSL for given LDAP server, authenticated by a client certificate and allowing LDAP server to use self-signed certificate
.LINK
More about System.DirectoryServices.Protocols: http://msdn.microsoft.com/en-us/library/bb332056.aspx
#>
Param
(
[parameter(Mandatory = $false)]
[String[]]
#LDAP server name
#Default: default server given by environment
$LdapServer=[String]::Empty,
[parameter(Mandatory = $false)]
[Int32]
#LDAP server port
#Default: 389
$Port=389,
[parameter(Mandatory = $false)]
[PSCredential]
#Use different credentials when connecting
$Credential=$null,
[parameter(Mandatory = $false)]
[ValidateSet('None','TLS','SSL','Kerberos')]
[string]
#Type of encryption to use.
$EncryptionType='None',
[Switch]
#enable support for Fast Concurrent Bind
$FastConcurrentBind,
[Switch]
#enable support for UDP transport
$ConnectionLess,
[parameter(Mandatory = $false)]
[Timespan]
#Time before connection times out.
#Default: 120 seconds
$Timeout = (New-Object System.TimeSpan(0,0,120)),
[Parameter(Mandatory = $false)]
[System.DirectoryServices.Protocols.AuthType]
#The type of authentication to use with the LdapConnection
$AuthType,
[Parameter(Mandatory = $false)]
[int]
#Requested LDAP protocol version
$ProtocolVersion = 3,
[Parameter(Mandatory = $false)]
[System.Security.Cryptography.X509Certificates.X509VerificationFlags]
#Requested LDAP protocol version
$CertificateValidationFlags = 'NoFlag',
[Parameter(Mandatory = $false)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]
#Client certificate used for authenticcation instead of credentials
#See https://docs.microsoft.com/en-us/windows/win32/api/winldap/nc-winldap-queryclientcert
$ClientCertificate
)
Begin
{
if($null -eq $script:ConnectionParams)
{
$script:ConnectionParams=@{}
}
}
Process
{
$FullyQualifiedDomainName=$false;
[System.DirectoryServices.Protocols.LdapDirectoryIdentifier]$di=new-object System.DirectoryServices.Protocols.LdapDirectoryIdentifier($LdapServer, $Port, $FullyQualifiedDomainName, $ConnectionLess)
if($null -ne $Credential)
{
$LdapConnection=new-object System.DirectoryServices.Protocols.LdapConnection($di, $Credential.GetNetworkCredential())
}
else
{
$LdapConnection=new-object System.DirectoryServices.Protocols.LdapConnection($di)
}
$LdapConnection.SessionOptions.ProtocolVersion=$ProtocolVersion
#store connection params for each server in grobal variable, so as it is reachable from callback scriptblocks
$connectionParams=@{}
foreach($server in $LdapServer) {$script:ConnectionParams[$server]=$connectionParams}
if($CertificateValidationFlags -ne 'NoFlag')
{
$connectionParams['ServerCertificateValidationFlags'] = $CertificateValidationFlags
#server certificate validation callback
$LdapConnection.SessionOptions.VerifyServerCertificate = { param(
[Parameter(Mandatory)][DirectoryServices.Protocols.LdapConnection]$LdapConnection,
[Parameter(Mandatory)][Security.Cryptography.X509Certificates.X509Certificate2]$Certificate
)
[System.Security.Cryptography.X509Certificates.X509Chain] $chain = new-object System.Security.Cryptography.X509Certificates.X509Chain
foreach($server in $LdapConnection.Directory.Servers)
{
if($server -in $script:ConnectionParams.Keys)
{
$connectionParam=$script:ConnectionParams[$server]
if($null -ne $connectionParam['ServerCertificateValidationFlags'])
{
$chain.ChainPolicy.VerificationFlags = $connectionParam['ServerCertificateValidationFlags']
break;
}
}
}
$result = $chain.Build($Certificate)
return $result
}
}
if($null -ne $ClientCertificate)
{
$connectionParams['ClientCertificate'] = $ClientCertificate
#client certificate retrieval callback
#we just support explicit certificate now
$LdapConnection.SessionOptions.QueryClientCertificate = { param(
[Parameter(Mandatory)][DirectoryServices.Protocols.LdapConnection]$LdapConnection,
[Parameter(Mandatory)][byte[][]]$TrustedCAs
)
$clientCert = $null
foreach($server in $LdapConnection.Directory.Servers)
{
if($server -in $script:ConnectionParams.Keys)
{
$connectionParam=$script:ConnectionParams[$server]
if($null -ne $connectionParam['ClientCertificate'])
{
$clientCert = $connectionParam['ClientCertificate']
break;
}
}
}
return $clientCert
}
}
if ($null -ne $AuthType) {
$LdapConnection.AuthType = $AuthType
}
switch($EncryptionType) {
'None' {break}
'TLS' {
$LdapConnection.SessionOptions.StartTransportLayerSecurity($null)
break
}
'Kerberos' {
$LdapConnection.SessionOptions.Sealing=$true
$LdapConnection.SessionOptions.Signing=$true
break
}
'SSL' {
$LdapConnection.SessionOptions.SecureSocketLayer=$true
break
}
}
$LdapConnection.Timeout = $Timeout
if($FastConcurrentBind) {
$LdapConnection.SessionOptions.FastConcurrentBind()
}
$LdapConnection
}
}
Function Add-LdapObject
{
<#
.SYNOPSIS
Creates a new object in LDAP server
.DESCRIPTION
Creates a new object in LDAP server.
Optionally performs attribute transforms registered for Save action before saving changes
.OUTPUTS
Nothing
.EXAMPLE
$obj = [PSCustomObject]@{distinguishedName=$null; objectClass=$null; sAMAccountName=$null; unicodePwd=$null; userAccountControl=0}
$obj.DistinguishedName = "cn=user1,cn=users,dc=mydomain,dc=com"
$obj.sAMAccountName = "User1"
$obj.ObjectClass = "User"
$obj.unicodePwd = "P@ssw0rd"
$obj.userAccountControl = "512"
$Ldap = Get-LdapConnection -LdapServer "mydc.mydomain.com" -EncryptionType Kerberos
Register-LdapAttributeTransform -name UnicodePwd -AttributeName unicodePwd
Add-LdapObject -LdapConnection $Ldap -Object $obj -BinaryProps unicodePwd
Description
-----------
Creates new user account in domain.
Password is transformed to format expected by LDAP services by registered attribute transform
.LINK
More about System.DirectoryServices.Protocols: http://msdn.microsoft.com/en-us/library/bb332056.aspx
#>
Param (
[parameter(Mandatory = $true, ValueFromPipeline=$true)]
[PSObject]
#Source object to copy properties from
$Object,
[parameter()]
[String[]]
#Properties to ignore on source object
$IgnoredProps=@(),
[parameter(Mandatory = $false)]
[String[]]
#List of properties that we want to handle as byte stream.
#Note: Properties not listed here are handled as strings
#Default: empty list, which means that all properties are handled as strings
$BinaryProps=@(),
[parameter(Mandatory = $true)]
[System.DirectoryServices.Protocols.LdapConnection]
#Existing LDAPConnection object.
$LdapConnection,
[parameter(Mandatory = $false)]
[System.DirectoryServices.Protocols.DirectoryControl[]]
#Additional controls that caller may need to add to request
$AdditionalControls=@(),
[parameter(Mandatory = $false)]
[Timespan]
#Time before connection times out.
#Default: 120 seconds
$Timeout = (New-Object System.TimeSpan(0,0,120))
)
Process
{
if([string]::IsNullOrEmpty($Object.DistinguishedName)) {
throw (new-object System.ArgumentException("Input object missing DistinguishedName property"))
}
[System.DirectoryServices.Protocols.AddRequest]$rqAdd=new-object System.DirectoryServices.Protocols.AddRequest
$rqAdd.DistinguishedName=$Object.DistinguishedName
#add additional controls that caller may have passed
foreach($ctrl in $AdditionalControls) {$rqAdd.Controls.Add($ctrl) | Out-Null}
foreach($prop in (Get-Member -InputObject $Object -MemberType NoteProperty)) {
if($prop.Name -eq "distinguishedName") {continue}
if($IgnoredProps -contains $prop.Name) {continue}
[System.DirectoryServices.Protocols.DirectoryAttribute]$propAdd=new-object System.DirectoryServices.Protocols.DirectoryAttribute
$transform = $script:RegisteredTransforms[$prop.Name]
$binaryInput = ($null -ne $transform -and $transform.BinaryInput -eq $true) -or ($prop.Name -in $BinaryProps)
$propAdd.Name=$prop.Name
if($null -ne $transform -and $null -ne $transform.OnSave) {
#transform defined -> transform to form accepted by directory
$attrVal = ,(& $transform.OnSave -Values $Object.($prop.Name))
}
else {
#no transform defined - take value as-is
$attrVal = $Object.($prop.Name)
}
if($null -ne $attrVal) #ignore empty props
{
if($binaryInput) {
foreach($val in $attrVal) {
$propAdd.Add([byte[]]$val) | Out-Null
}
} else {
$propAdd.AddRange([string[]]($attrVal))
}
if($propAdd.Count -gt 0) {
$rqAdd.Attributes.Add($propAdd) | Out-Null
}
}
}
if($rqAdd.Attributes.Count -gt 0) {
$LdapConnection.SendRequest($rqAdd, $Timeout) -as [System.DirectoryServices.Protocols.AddResponse] | Out-Null
}
}
}
Function Edit-LdapObject
{
<#
.SYNOPSIS
Modifies existing object in LDAP server
.DESCRIPTION
Modifies existing object in LDAP server.
Optionally performs attribute transforms registered for Save action before saving changes
.OUTPUTS
Nothing
.EXAMPLE
$obj = [PSCustomObject]@{distinguishedName=$null; employeeNumber=$null}
$obj.DistinguishedName = "cn=user1,cn=users,dc=mydomain,dc=com"
$obj.employeeNumber = "12345"
$Ldap = Get-LdapConnection -LdapServer "mydc.mydomain.com" -EncryptionType Kerberos
Edit-LdapObject -LdapConnection $Ldap -Object $obj
Description
-----------
Modifies existing user account in domain.
.EXAMPLE
$conn = Get-LdapConnection -LdapServer "mydc.mydomain.com" -EncryptionType Kerberos
$dse = Get-RootDSE -LdapConnection $conn
$User = Find-LdapObject -LdapConnection $conn -searchFilter '(&(objectClass=user)(objectCategory=organizationalPerson)(sAMAccountName=myUser1))' -searchBase $dse.defaultNamingContext
$Group = Find-LdapObject -LdapConnection $conn -searchFilter '(&(objectClass=group)(objectCategory=group)(cn=myGroup1))' -searchBase $dse.defaultNamingContext -AdditionalProperties @('member')
$Group.member=@($User.distinguishedName)
Edit-LdapObject -LdapConnection $conn -Object $Group -Mode Add
Description
-----------
Finds user account in LDAP server and adds it to group
.LINK
More about System.DirectoryServices.Protocols: http://msdn.microsoft.com/en-us/library/bb332056.aspx
#>
Param (
[parameter(Mandatory = $true, ValueFromPipeline=$true)]
[PSObject]
#Source object to copy properties from
$Object,
[parameter()]
[String[]]
#Properties to ignore on source object. If not specified, no props are ignored
$IgnoredProps=@(),
[parameter()]
[String[]]
#Properties to include on source object. If not specified, all props are included
$IncludedProps=@(),
[parameter(Mandatory = $false)]
[String[]]
#List of properties that we want to handle as byte stream.
#Note: Those properties must also be present in IncludedProps parameter. Properties not listed here are handled as strings
#Default: empty list, which means that all properties are handled as strings
$BinaryProps=@(),
[parameter(Mandatory = $true)]
[System.DirectoryServices.Protocols.LdapConnection]
#Existing LDAPConnection object.
$LdapConnection,
[parameter(Mandatory=$false)]
[System.DirectoryServices.Protocols.DirectoryAttributeOperation]
#Mode of operation
#Replace: Replaces attribute values on target
#Add: Adds attribute values to existing values on target
#Delete: Removes atribute values from existing values on target
$Mode=[System.DirectoryServices.Protocols.DirectoryAttributeOperation]::Replace,
[parameter(Mandatory = $false)]
[System.DirectoryServices.Protocols.DirectoryControl[]]
#Additional controls that caller may need to add to request
$AdditionalControls=@(),
[parameter(Mandatory = $false)]
[timespan]
#Time before request times out.
#Default: 120 seconds
$Timeout = (New-Object System.TimeSpan(0,0,120)),
[Switch]
#when turned on, we are returning modified object to pipeline
$Passthrough
)