-
Notifications
You must be signed in to change notification settings - Fork 58
/
ADTimeline.ps1
executable file
·2727 lines (2505 loc) · 141 KB
/
ADTimeline.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
# Active directory timeline generated with replication metadata
# Leonard SAVINA - ANSSI\SDO\DR\INM - CERT-FR
# Issues and PR welcome https://github.com/ANSSI-FR/ADTimeline
# Use paramater server if running offline mode or GC is not found
# Use parameter customgroups to retrieve replication metadata from specific groups.
# customgroups argument can be a string with multiple group comma separated (no space)
# PS>./ADTimeline -customgroups "VIP-group1,ESX-Admins,Tier1-admins"
# customgroups can also be an array, in case you import the list from a file (one group per line)
# PS>$customgroups = get-content customgroups.txt
# PS>./ADTimeline -customgroups $customgroups
# Use parameter groupslike to search for groups using "like" instead of exact match operator
# Note that the names will be automatically surrounded by '*'
# PS>./ADTimeline -customgroups "admin"
# -> will use a search filter { Name -eq "admin" }
# PS>./ADTimeline -customgroups "admin" -groupslike
# -> will use a search filter { Name -like "*admin*" }
# Use parameter nofwdSMTP in a large MSExchange organization context with forwarders massively used.
# PS>./ADTimeline -nofwdSMTPaltRecipient
Param (
[parameter(Mandatory=$false)][string]$server = $null,
[parameter(Mandatory=$false)]$customgroups = $null,
[parameter(Mandatory=$false)][switch]$nofwdSMTP,
[parameter(Mandatory = $false)][switch]$groupslike = $False
)
if($customgroups)
{
if(($customgroups.gettype()).FullName -eq "System.String")
{
$groupscustom = $customgroups.split(",")
write-output -inputobject "---- Custom groups argument is a string ----"
}
elseif(($customgroups.gettype()).FullName -eq "System.Object[]")
{
$groupscustom = $customgroups
"---- Custom groups argument is an array ----"
}
else
{
write-output -inputobject "---- Wrong argument object type ----"
Exit $WRONG_ARG_TYPE
}
}
# You can also directly uncomment and edit the below $customgroups variable if you do not want to set an argument
# Example of custom groups variable
# $groupscustom = ("VIP-group1","ESX-Admins","Tier1-admins")
# Set Variables for error handling
Set-Variable -name ERR_BAD_OS_VERSION -option Constant -value 1
Set-Variable -name ERR_NO_AD_MODULE -option Constant -value 2
Set-Variable -name ERR_NO_GC_FOUND -option Constant -value 3
Set-Variable -name ERR_GC_BIND_FAILED -option Constant -value 4
Set-Variable -name WRONG_ARG_TYPE -option Constant -value 5
# AD Timeline is supported on Windows 6.1 +
if([Environment]::OSVersion.version -lt (new-object 'Version' 6,1))
{
write-output -inputobject "---- Script must be launched on a Windows 6.1 + computer ----"
Exit $ERR_BAD_OS_VERSION
}
# Check AD Psh module
If(-not(Get-Module -name activedirectory -listavailable))
{
write-output -inputobject "---- Script must be launched on a computer with Active Directory PowerShell module installed ----"
Exit $ERR_NO_AD_MODULE
}
Else
{import-module activedirectory}
# Check Global Catalog
$GCsinmysite = $null
if(-not($server))
{
$mySite = (nltest /dsgetsite 2>$null)[0]
$ADroot = $(get-adDomain).DNSroot
$GCsinmysite = get-ADDomainController -Filter {(IsGlobalCatalog -eq $true) -and (Site -eq $mySite) -and (Domain -eq $ADroot) -and (Enabled -eq $true)}
if($GCsinmysite)
{ $server = ($GCsinmysite | select-object -first 1).Hostname }
Else
{
write-output -inputobject "---- No Global Catalog found in current AD site, please run the script and specify a Global Catalog name with the server argument ----"
Exit $ERR_NO_GC_FOUND
}
}
$error.clear()
# LDAP root information, to retrieve partitions paths
$root = Get-ADRootDSE -server $server
if($error)
{
write-output -inputobject "---- Retrieving AD root on $($server) failed ----"
Exit $ERR_GC_BIND_FAILED
}
# Check if script is running offline or online and set GC port
if([string]$server.contains(":") -eq $true)
{
$gcport = [int]::parse($server.split(":")[1]) + 2
$gc = $server.split(":")[0] + ":" + $gcport
$isonline = $false
}
else {
$error.clear()
$dntstroot = [void]([adsi]"LDAP://$server").distinguishedName
[void][adsi]"GC://$server/$dntstroot"
if($error)
{
write-output -inputobject "---- DC is not Global Catalog, please provide a GC with the server argument ----"
Exit $ERR_NO_GC_FOUND
}
Else
{
$gc = $server + ':3268'
$isonline = $true
}
}
write-output -inputobject "---- Running script on: $($server) ----"
write-output -inputobject "---- Collecting AD objects ----"
# TimeStamp formating for log file
function Get-TimeStamp
{
return "{0:yyyy-MM-dd} {0:HH:mm:ss}" -f (get-date)
}
"$(Get-TimeStamp) Starting script on $($server)" | out-file logfile.log
if($isonline -eq $true)
{
"$(Get-TimeStamp) Script running in online mode" | out-file logfile.log -append
}
else
{
"$(Get-TimeStamp) Script running in offline mode" | out-file logfile.log -append
}
# Getting folder fully qualifed name length to compute MAX_PATH
$maxfilenamelen = 0
$folderlen = ((get-item .\logfile.log).directoryName).length
$maxfilenamelen = 256 - $folderlen + 2
# Function adapted from https://www.petri.com/expanding-active-directory-searcher-powershell Added SID processing
Function Convert-ADSearchResult
{
[cmdletbinding()]
Param(
[Parameter(Position = 0,Mandatory = $true,ValueFromPipeline = $true)]
[ValidateNotNullorEmpty()]
[System.DirectoryServices.SearchResult]$SearchResult
)
Begin {
Write-Verbose "Starting $($MyInvocation.MyCommand)"
}
Process {
Write-Verbose "Processing result for $($searchResult.Path)"
#create an ordered hashtable with property names alphabetized
$props = $SearchResult.Properties.PropertyNames | Sort-Object
$objHash = @{}
foreach ($p in $props)
{
if(($p -eq "objectSID") -or ($p -eq "SIDHistory"))
{
$value = @()
$binaryvalue = $searchresult.Properties.item($p)
foreach($SID in $binaryvalue)
{
$value += (New-Object System.Security.Principal.SecurityIdentifier($SID,0)).value
}
}
else
{
$value = $searchresult.Properties.item($p)
}
if ($value.count -eq 1)
{$value = $value[0]}
$objHash.add($p,$value)
}
new-object psobject -property $objHash
}
End
{
Write-Verbose "Ending $($MyInvocation.MyCommand)"
}
}
# Initializing PowerShell objects in order to store results from LDAP queries
$criticalobjects = @()
$gcobjects = @()
#Getting root domain information
$dom = Get-ADObject -SearchBase ($root.defaultNamingContext) -SearchScope Base -Server $server -Filter * -properties *
#If operation times out a different ResultPageSize is used
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$dom = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($root.defaultNamingContext) -SearchScope Base -Server $server -Filter * -properties *
$i++
}
if($dom){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$criticalobjects += $dom
if($error)
{ "$(Get-TimeStamp) Error while retrieving domain root information $($error)" | out-file logfile.log -append ; $error.clear() }
else
{
#Get current domain SID and PDCe, will be used later
$domSID = $dom.ObjectSID.value
$PDCe = ((($dom.fsmoRoleOwner).replace($root.configurationNamingContext,"")).replace("CN=NTDS Settings,","")).replace("CN=Sites,","CN=Sites")
"$(Get-TimeStamp) Domain root information retrieved" | out-file logfile.log -append
"$(Get-TimeStamp) Domain DistinguishedName is: $($dom.distinguishedName) " | out-file logfile.log -append
"$(Get-TimeStamp) Domain SID is: $($domSID)" | out-file logfile.log -append
$domainfqdn = (($dom.distinguishedName).replace("DC=","")).replace(",",".")
#Getting accounts having an ACE on domain root
$accountsACEondomain = ($dom.ntsecuritydescriptor).getaccessrules($true , $true , [System.Security.Principal.SecurityIdentifier]) | Where-Object {$_.IdentityReference -like "S-1-5-21-*"} | group-object -property IdentityReference
if($error)
{ "$(Get-TimeStamp) Error while retrieving accounts having an ACE on domain $($error)" | out-file logfile.log -append ; $error.clear() }
else
{
$usrcount = 0
$ismsol = $false
$userACE = $null
foreach($accountACE in $accountsACEondomain)
{#If SID is from current domain launch LDAP query, otherwise try GC
if($accountACE.Name -like "$domSID*")
{
$userACE = Get-ADObject -Filter {ObjectSID -eq $accountACE.Name} -Server $server -properties *
if($userACE){$criticalobjects += $userACE}
}
else
{
$search = new-object System.DirectoryServices.DirectorySearcher
$search.searchroot = [ADSI]"GC://$($gc)"
$search.filter = "(ObjectSID=$($accountACE.Name))"
$userACE = $search.findone() | Convert-ADSearchResult
if($userACE){$gcobjects += $userACE}
}
if($error)
{ "$(Get-TimeStamp) Error while getting object SID $($accountACE.Name) with error $($error)" | out-file logfile.log -append ; $error.clear() }
else
{#Check if objectclass is user, if yes check if name matches AADConnect account
if(($userACE.ObjectClass -eq "user") -or ($userACE.ObjectClass -eq "inetOrgPerson"))
{$usrcount++
if($userACE.SamAccountName -like "MSOL_*")
{$ismsol = $true}
}
}
}
}
"$(Get-TimeStamp) Number of user accounts having an ACE on domain root: $($usrcount)" | out-file logfile.log -append
if($ismsol)
{"$(Get-TimeStamp) Account starting with MSOL having an ACE on domain root, Default Azure AD connect installation might be setup" | out-file logfile.log -append}
}
#Renaming log file and setting filenames for result files
if($domainfqdn)
{
if($domainfqdn.length -ge $maxfilenamelen)
{
$logfilename = "logfile_" + $domainfqdn.substring(0,$maxfilenamelen) + ".log"
$timelinefilename = "timeline_" + $domainfqdn.substring(0,$maxfilenamelen) + ".csv"
$adobjectsfilename = "ADobjects_" + $domainfqdn.substring(0,$maxfilenamelen) + ".xml"
$gcADobjectsfilename = "gcADobjects_" + $domainfqdn.substring(0,$maxfilenamelen) + ".xml"
}
else {
$logfilename = "logfile_" + $domainfqdn + ".log"
$timelinefilename = "timeline_" + $domainfqdn + ".csv"
$adobjectsfilename = "ADobjects_" + $domainfqdn + ".xml"
$gcADobjectsfilename = "gcADobjects_" + $domainfqdn + ".xml"
}
if(test-path($logfilename)){remove-item $logfilename -force -confirm:$false}
Rename-item ".\logfile.log" $logfilename -force -confirm:$false
New-Item -ItemType File -Name $timelinefilename -force -confirm:$false | Out-Null
New-Item -ItemType File -Name $adobjectsfilename -force -confirm:$false | Out-Null
New-Item -ItemType File -Name $gcADobjectsfilename -force -confirm:$false | Out-Null
if($error)
{ "$(Get-TimeStamp) Error while setting setting filenames for output files with error $($error)" | out-file logfile.log -append
$error.clear()
$logfilename = "logfile.log"
$timelinefilename = "timeline.csv"
$adobjectsfilename = "ADobjects.xml"
$gcADobjectsfilename = "gcADobjects.xml"
}
}
else
{
$logfilename = "logfile.log"
$timelinefilename = "timeline.csv"
$adobjectsfilename = "ADobjects.xml"
$gcADobjectsfilename = "gcADobjects.xml"
}
#Getting root of the configuration partition
$rootconf = Get-ADObject -SearchBase ($root.ConfigurationNamingContext) -SearchScope Base -Server $server -Filter * -properties *
#If operation times out a different ResultPageSize is used
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$rootconf = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($root.ConfigurationNamingContext) -SearchScope Base -Server $server -Filter * -properties *
$i++
}
if($rootconf){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$criticalobjects += $rootconf
if($error)
{ "$(Get-TimeStamp) Error while retrieving root of the configuration partition $($error)" | out-file $logfilename -append ; $error.clear() }
else
{
"$(Get-TimeStamp) Root of the configuration partition retrieved" | out-file $logfilename -append
}
#Getting root of the schema partition
$rootschema = Get-ADObject -SearchBase ($root.SchemaNamingContext) -SearchScope Base -Server $server -Filter * -properties *
#If operation times out a different ResultPageSize is used
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$rootschema = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($root.SchemaNamingContext) -SearchScope Base -Server $server -Filter * -properties *
$i++
}
if($rootschema){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$criticalobjects += $rootschema
if($error)
{ "$(Get-TimeStamp) Error while retrieving root of the schema partition $($error)" | out-file $logfilename -append ; $error.clear() }
else
{
$SchemaMaster = ((($rootschema.fsmoRoleOwner).replace($root.configurationNamingContext,"")).replace("CN=NTDS Settings,","")).replace("CN=Sites,","CN=Sites")
"$(Get-TimeStamp) Root of the schema partition retrieved" | out-file $logfilename -append
"$(Get-TimeStamp) Schema version is $($rootschema.objectVersion)" | out-file $logfilename -append
}
#Check if current user is DA or EA when online mode running
if($isonline -eq $true)
{
$mygrps = whoami /groups /fo csv | ConvertFrom-Csv
$Dasid = $domsid + "-512"
$isda = $mygrps | where-object{($_.SID -eq $Dasid) -or ($_.SID -like "*-519")}
if($isda)
{
"$(Get-TimeStamp) Current user is domain admin or enterprise admin" | out-file $logfilename -append
}
else
{
write-output -inputobject "Script not running as domain or enterprise admin, some objects might be missing"
"$(Get-TimeStamp) Script not running as domain or enterprise admin, some objects might be missing" | out-file $logfilename -append
}
}
#Retrieving objects located directly under the root domain, except Organizational Units
$dom1 = Get-ADObject -SearchBase ($root.defaultNamingContext) -SearchScope OneLevel -Server $server -filter {ObjectClass -ne "organizationalUnit"} -properties *
#If operation times out a different ResultPageSize is used
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$dom1 = Get-ADObject -SearchBase ($root.defaultNamingContext) -SearchScope OneLevel -Server $server -filter {ObjectClass -ne "organizationalUnit"} -properties *
$i++
}
if($dom1){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$criticalobjects += $dom1
$countdom1 = ($dom1 | measure-object).count
if($error)
{ "$(Get-TimeStamp) Error while retrieving objects directly under domain root $($error)" | out-file $logfilename -append ; $error.clear() }
else {"$(Get-TimeStamp) Number of objects directly under domain root, OU excluded: $($countdom1)" | out-file $logfilename -append
$inframaster = (((($dom1 | where-object{($_.Name -eq "Infrastructure") -and ($_.ObjectClass -eq "infrastructureUpdate")}).fsmoRoleOwner).replace($root.configurationNamingContext,"")).replace("CN=NTDS Settings,","")).replace("CN=Sites,","CN=Sites")
}
#Objects protected by the SDProp process (AdminSDHolder ACL, Admincount=1)
$SDPropObjects = Get-ADObject -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -filter {AdminCount -eq 1} -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$SDPropObjects = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -filter {AdminCount -eq 1} -Server $server -properties *
$i++
}
if($SDPropObjects){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$criticalobjects += $SDPropObjects
$countSDPROP = ($SDPropObjects | measure-object).count
if($error)
{ "$(Get-TimeStamp) Error while retrieving objects protected by the SDProp process $($error)" | out-file $logfilename -append ; $error.clear() }
else {"$(Get-TimeStamp) Number of objects protected by the SDProp process: $($countSDPROP)" | out-file $logfilename -append}
#Objects with mail forwarders (msExchGenericForwardingAddress, altRecipient)
if(-not($nofwdSMTP))
{
$ForwardedObjects = Get-ADObject -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -filter {(msExchGenericForwardingAddress -like "*") -or (altRecipient -like "*")} -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$ForwardedObjects = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -filter {(msExchGenericForwardingAddress -like "*") -or (altRecipient -like "*")} -Server $server -properties *
$i++
}
if($ForwardedObjects){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$criticalobjects += $ForwardedObjects
$countForwardedObjects = ($ForwardedObjects | measure-object).count
if($error)
{ "$(Get-TimeStamp) Error while retrieving objects with forwarders $($error)" | out-file $logfilename -append ; $error.clear() }
else {"$(Get-TimeStamp) Number of objects with forwaders: $($countForwardedObjects)" | out-file $logfilename -append}
}
#Grabing "Pre Windows 2000 Compatibility access group", not recursive...
$pre2000SID = "S-1-5-32-554"
$pre2000grp = Get-ADObject -filter {ObjectSID -eq $pre2000SID} -Server $server -properties *
if($error)
{ "$(Get-TimeStamp) Error while retrieving Pre Windows 2000 Compatibility access group $($error)" | out-file $logfilename -append ; $error.clear() }
else
{
if($pre2000grp)
{
$criticalobjects += $pre2000grp
$countpre2000grp = ($pre2000grp | measure-object).count
if($countpre2000grp -eq 1)
{
if($pre2000grp.member -eq ('CN=S-1-1-0,CN=ForeignSecurityPrincipals,'+ $root.defaultNamingContext))
{ "$(Get-TimeStamp) Member of Pre Windows 2000 Compatibility access group is Everyone" | out-file $logfilename -append}
Elseif($pre2000grp.member -eq ('CN=S-1-5-11,CN=ForeignSecurityPrincipals,'+ $root.defaultNamingContext))
{ "$(Get-TimeStamp) Member of Pre Windows 2000 Compatibility access group is Authenticated users" | out-file $logfilename -append}
Elseif($pre2000grp.member -eq ('CN=S-1-5-7,CN=ForeignSecurityPrincipals,'+ $root.defaultNamingContext))
{ "$(Get-TimeStamp) Member of Pre Windows 2000 Compatibility access group is Anonymous logon" | out-file $logfilename -append}
else
{ "$(Get-TimeStamp) Member of Pre Windows 2000 Compatibility access group is $($pre2000grp.member)" | out-file $logfilename -append}
}
else
{"$(Get-TimeStamp) Number of Pre Windows 2000 Compatibility access group members: $($countpre2000grp)" | out-file $logfilename -append}
}
}
#Grabing Guest Account
$guestaccsid = $domSID + "-501"
$guestacc = Get-ADObject -filter {ObjectSID -eq $guestaccsid} -Server $server -properties *
if($error)
{ "$(Get-TimeStamp) Error while retrieving Guest account $($error)" | out-file $logfilename -append ; $error.clear() }
else
{
if($guestacc)
{
$criticalobjects += $guestacc
if(($guestacc.UserAccountControl -band 2) -eq 2)
{
"$(Get-TimeStamp) Guest account is disabled" | out-file $logfilename -append
}
else
{
"$(Get-TimeStamp) Guest account is enabled!" | out-file $logfilename -append
}
}
}
#Grabing the DNSAdmin groups and its members well knwon SID is S-1-5-21-<Domain>-1101
$dndnsadminSID = $domSID + "-1101"
$dnsadmin = Get-ADObject -filter {ObjectSID -eq $dndnsadminSID} -Server $server -properties *
#Group might not exist if DNS role not installed
if($dnsadmin)
{
$criticalobjects += $dnsadmin
if($isonline -eq $true)
{
#Get recursive membership
$dnsadminsmembers = (Get-ADGroupMember -recursive $dnsadmin -server $server | foreach-object{get-adobject $_ -server $server -properties *})
#Get groups till level 2 is reached if groups are nested.
if($dnsadminsmembers)
{
$criticalobjects += $dnsadminsmembers
$nestedgrp = @()
$level1 = Get-ADGroupMember $dnsadmin -server $server | where-object{$_.objectclass -eq "Group"} | select-object distinguishedName
if($level1)
{
$nestedgrp += $level1
$nestedgrp += $level1 | foreach-object{Get-ADGroupMember $_.DistinguishedName -server $server | where-object{$_.objectclass -eq "Group"} | select-object distinguishedName}
$criticalobjects += ($nestedgrp | foreach-object{get-adobject $_.DistinguishedName -server $server -properties *})
}
}
}
else
{
#Cannot use recursive membership cmdlet in offline mode, get direct members only
$dnsadminsmembers = ($dnsadmin | select-object -expandproperty member | foreach-object{get-adobject $_ -server $server -properties *})
$criticalobjects += $dnsadminsmembers
#Get groups till level 2 is reached if groups are nested.
$continue = $dnsadminsmembers | where-object{$_.ObjectClass -eq "Group"}
if($continue)
{foreach($grp in $continue){$dnsadmingrpcn2 = $grp | select-object -expandproperty member | foreach-object{get-adobject $_ -server $server -properties *};$criticalobjects += $dnsadmingrpcn2}}
}
$countdnsadminsmembers = ($dnsadminsmembers | measure-object).count
if($error)
{ "$(Get-TimeStamp) Error while retrieving DNSADmins group members $($error)" | out-file $logfilename -append ; $error.clear() }
else
{"$(Get-TimeStamp) Number of DNSAdmins group members: $($countdnsadminsmembers)" | out-file $logfilename -append}
}
#Grabing the DNSUpdateProxy groups and its members well knwon SID is S-1-5-21-<Domain>-1102
$DNSUpdateProxySID = $domSID + "-1102"
$DNSUpdateProxy = Get-ADObject -filter {ObjectSID -eq $DNSUpdateProxySID} -Server $server -properties *
#Group might not exist if DNS role not installed
if($DNSUpdateProxy)
{
$criticalobjects += $DNSUpdateProxy
if($isonline -eq $true)
{
#Get recursive membership
$DNSUpdateProxymembers = (Get-ADGroupMember -recursive $DNSUpdateProxy -server $server | foreach-object{get-adobject $_ -server $server -properties *})
#Get groups till level 2 is reached if groups are nested.
if($DNSUpdateProxymembers)
{
$criticalobjects += $DNSUpdateProxymembers
$nestedgrp = @()
$level1 = Get-ADGroupMember $DNSUpdateProxy -server $server | where-object{$_.objectclass -eq "Group"} | select-object distinguishedName
if($level1)
{
$nestedgrp += $level1
$nestedgrp += $level1 | foreach-object{Get-ADGroupMember $_.DistinguishedName -server $server | where-object{$_.objectclass -eq "Group"} | select-object distinguishedName}
$criticalobjects += ($nestedgrp | foreach-object{get-adobject $_.DistinguishedName -server $server -properties *})
}
}
}
else
{
#Cannot use recursive membership cmdlet in offline mode, get direct members only
$DNSUpdateProxymembers = ($DNSUpdateProxy | select-object -expandproperty member | foreach-object{get-adobject $_ -server $server -properties *})
$criticalobjects += $DNSUpdateProxymembers
#Get groups till level 2 is reached if groups are nested.
$continue = $DNSUpdateProxymembers | where-object{$_.ObjectClass -eq "Group"}
if($continue)
{foreach($grp in $continue){$dnsadmingrpcn2 = $grp | select-object -expandproperty member | foreach-object{get-adobject $_ -server $server -properties *};$criticalobjects += $dnsadmingrpcn2}}
}
$countDNSUpdateProxymembers = ($DNSUpdateProxymembers | measure-object).count
if($error)
{ "$(Get-TimeStamp) Error while retrieving DNSUpdateProxy group members $($error)" | out-file $logfilename -append ; $error.clear() }
else
{"$(Get-TimeStamp) Number of DNSUpdateProxy group members: $($countDNSUpdateProxymembers)" | out-file $logfilename -append}
}
#Grabing Group Policy Creators owners, using SID because name depends on the installation language
$gpoownersSID = $domSID + "-520"
$gpoowners = Get-ADObject -filter {ObjectSID -eq $gpoownersSID} -Server $server -properties *
$criticalobjects += $gpoowners
if($isonline -eq $true)
{
#Get recursive membership
$gpoownersmembers = (Get-ADGroupMember -recursive $gpoowners -server $server | foreach-object{get-adobject $_ -server $server -properties *})
#Get groups till level 2 is reached if groups are nested.
if($gpoownersmembers)
{
$criticalobjects += $gpoownersmembers
$nestedgrp = @()
$level1 = Get-ADGroupMember $gpoowners -server $server | where-object{$_.objectclass -eq "Group"} | select-object distinguishedName
if($level1)
{
$nestedgrp += $level1
$nestedgrp += $level1 | foreach-object{Get-ADGroupMember $_.DistinguishedName -server $server | where-object{$_.objectclass -eq "Group"} | select-object distinguishedName}
$criticalobjects += ($nestedgrp | foreach-object{get-adobject $_.DistinguishedName -server $server -properties *})
}
}
}
else
{
#Cannot use recursive membership cmdlet in offline mode, get direct members only
$gpoownersmembers = ($gpoowners | select-object -expandproperty member | foreach-object{get-adobject $_ -server $server -properties *})
$criticalobjects += $gpoownersmembers
#Get groups till level 2 is reached if groups are nested.
$continue = $gpoownersmembers | where-object{$_.ObjectClass -eq "Group"}
if($continue)
{foreach($grp in $continue){$gpoownersgrpcn2 = $grp | select-object -expandproperty member | foreach-object{get-adobject $_ -server $server -properties *};$criticalobjects += $gpoownersgrpcn2}}
}
$countgpoownersmembers = ($gpoownersmembers | measure-object).count
if($error)
{ "$(Get-TimeStamp) Error while retrieving GPO owners group members $($error)" | out-file $logfilename -append ; $error.clear() }
else
{"$(Get-TimeStamp) Number of GPO creators ownners group members: $($countgpoownersmembers)" | out-file $logfilename -append}
#Grabing Cert publishers, using SID because name depends on the installation language
$certpublishersSID = $domSID + "-517"
$certpublishers = Get-ADObject -filter {ObjectSID -eq $certpublishersSID} -Server $server -properties *
$criticalobjects += $certpublishers
if($isonline -eq $true)
{
#Get recursive membership
$certpublishersmembers = (Get-ADGroupMember -recursive $certpublishers -server $server | foreach-object{get-adobject $_ -server $server -properties *})
#Get groups till level 2 is reached if groups are nested.
if($certpublishersmembers)
{
$criticalobjects += $certpublishersmembers
$nestedgrp = @()
$level1 = Get-ADGroupMember $certpublishers -server $server | where-object{$_.objectclass -eq "Group"} | select-object distinguishedName
if($level1)
{
$nestedgrp += $level1
$nestedgrp += $level1 | foreach-object{Get-ADGroupMember $_.DistinguishedName -server $server | where-object{$_.objectclass -eq "Group"} | select-object distinguishedName}
$criticalobjects += ($nestedgrp | foreach-object{get-adobject $_.DistinguishedName -server $server -properties *})
}
}
}
else
{
#Cannot use recursive membership cmdlet in offline mode, get direct members only
$certpublishersmembers = ($certpublishers | select-object -expandproperty member | foreach-object{get-adobject $_ -server $server -properties *})
$criticalobjects += $certpublishersmembers
#Get groups till level 2 is reached if groups are nested.
$continue = $certpublishersmembers | where-object{$_.ObjectClass -eq "Group"}
if($continue)
{foreach($grp in $continue){$certpublishersgrpcn2 = $grp | select-object -expandproperty member | foreach-object{get-adobject $_ -server $server -properties *};$criticalobjects += $certpublishersgrpcn2}}
}
$countcertpublishersmembers = ($certpublishersmembers | measure-object).count
if($error)
{ "$(Get-TimeStamp) Error while retrieving Cert publishers group members $($error)" | out-file $logfilename -append ; $error.clear() }
else
{"$(Get-TimeStamp) Number of Cert publishers group members: $($countcertpublishersmembers)" | out-file $logfilename -append}
#Retrieving deleted Group Policy Objects
$DeleteBase = "CN=Deleted Objects," + $root.defaultNamingContext
$deletedgpo = Get-ADObject -searchbase $DeleteBase -filter {(IsDeleted -eq $true) -and (ObjectClass -eq "groupPolicyContainer")} -IncludeDeletedObjects -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$deletedgpo = Get-ADObject -ResultPageSize $resultspagesize -searchbase $DeleteBase -filter {(IsDeleted -eq $true) -and (ObjectClass -eq "groupPolicyContainer")} -IncludeDeletedObjects -Server $server -properties *
$i++
}
if($deletedgpo){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$criticalobjects += $deletedgpo
$countdeletedgpo = ($deletedgpo | measure-object).count
if($error)
{ "$(Get-TimeStamp) Erreur while retrieving deleted GPOs $($error)" | out-file $logfilename -append ; $error.clear() }
else {"$(Get-TimeStamp) Number of deleted (tombstoned) GPOs: $($countdeletedgpo)" | out-file $logfilename -append}
#Retrieving Deleted (tombstoned) users, NTSecurityDescriptor porperty is excluded because with a large number of tombstoned users it can take a large amount of RAM. This property is not relevant for analysis if object is in the "Deleted Objects" container.
$deletedusers = Get-ADObject -searchbase $DeleteBase -filter {(IsDeleted -eq $true) -and ((ObjectClass -eq "User") -or (ObjectClass -eq "InetOrgPerson"))} -IncludeDeletedObjects -Server $server -properties CanonicalName, CN, Deleted, Description, DisplayName, DistinguishedName, instanceType, isDeleted, isRecycled, LastKnownParent, Modified, modifyTimeStamp, Name, ObjectCategory, ObjectClass, ObjectGUID, objectSid, ProtectedFromAccidentalDeletion, sAMAccountName, sDRightsEffective, userAccountControl, uSNChanged, uSNCreated, whenChanged, whenCreated
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$deletedusers = Get-ADObject -ResultPageSize $resultspagesize -searchbase $DeleteBase -filter {(IsDeleted -eq $true) -and ((ObjectClass -eq "User") -or (ObjectClass -eq "InetOrgPerson"))} -IncludeDeletedObjects -Server $server -properties CanonicalName, CN, Deleted, Description, DisplayName, DistinguishedName, instanceType, isDeleted, isRecycled, LastKnownParent, Modified, modifyTimeStamp, Name, ObjectCategory, ObjectClass, ObjectGUID, objectSid, ProtectedFromAccidentalDeletion, sAMAccountName, sDRightsEffective, userAccountControl, uSNChanged, uSNCreated, whenChanged, whenCreated
$i++
}
if($deletedusers){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$countdeletedusers = ($deletedusers | measure-object).count
if($countdeletedusers -ge 3000)
{
#If number of deleted objects is larger than 3000, metadata retrieval might take a while. As a consequence we sort them by creation date and take only the last 3000 created accounts.
$criticalobjects += $deletedusers | where-object{$_.WhenCreated -ne $null} | Sort-Object -Property whencreated -Descending | select-object -first 3000
"$(Get-TimeStamp) Number of deleted (tombstoned) user objects is $($countdeletedusers), because it is larger than 3000 only last 3000 newly created accounts will be retrieved" | out-file $logfilename -append
}
else
{
$criticalobjects += $deletedusers
"$(Get-TimeStamp) Number of deleted (tombstoned) user objects: $($countdeletedusers)" | out-file $logfilename -append
}
if($error)
{ "$(Get-TimeStamp) Error while retrieving deleted (tombstoned) user objects $($error)" | out-file $logfilename -append ; $error.clear() }
#Retrieving deleted objects located in configuration partition, msExchActiveSyncDevice objectclass is excluded as it can generate some noise
$deleteconf = Get-ADObject -searchbase $root.configurationNamingContext -filter {(IsDeleted -eq $true) -and (ObjectClass -ne "msExchActiveSyncDevice")} -IncludeDeletedObjects -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$deleteconf = Get-ADObject -ResultPageSize $resultspagesize -searchbase $root.configurationNamingContext -filter {(IsDeleted -eq $true) -and (ObjectClass -ne "msExchActiveSyncDevice")} -IncludeDeletedObjects -Server $server -properties *
$i++
}
if($deleteconf){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$criticalobjects += $deleteconf
$countdeleteconf = ($deleteconf | measure-object).count
if($error)
{ "$(Get-TimeStamp) Error while retrieving deleted (tombstoned) objects located in configuration partition $($error)" | out-file $logfilename -append ; $error.clear() }
else {"$(Get-TimeStamp) Number of deleted (tombstoned) objects located in configuration partition: $($countdeleteconf)" | out-file $logfilename -append}
#Retrieving classSchema objects (defaultSecurityDescriptor backdoor)
$Classesschema = Get-ADObject -searchbase $root.schemaNamingContext -Filter {ObjectClass -eq "classSchema"} -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$Classesschema = Get-ADObject -ResultPageSize $resultspagesize -searchbase $root.schemaNamingContext -Filter {ObjectClass -eq "classSchema"} -Server $server -properties *
$i++
}
if($Classesschema){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$criticalobjects += $Classesschema
$countClassesschema = ($Classesschema | measure-object).count
if($error)
{ "$(Get-TimeStamp) Error while retrieving classSchema objects $($error)" | out-file $logfilename -append ; $error.clear() }
else {"$(Get-TimeStamp) Number of classSchema objects: $($countClassesschema)" | out-file $logfilename -append}
#Retrieving Service Connection Point class objects of interest located in the domain partition
#SCP Objectclass/categories of interest mSSMSManagementPoint = SCCM, Service-Administration-Point holds binding information for connecting to a service to administer it, intellimirrorSCP contains configuration information for the service that responds to Remote Boot clients that request attention from a Remote Install Server.
$SAdminPointCat = "CN=Service-Administration-Point," + $root.SchemaNamingContext
$scpsdomain1 = Get-ADObject -searchbase $root.defaultNamingContext -Filter {(objectclass -eq "mSSMSManagementPoint") -or (ObjectCategory -eq $SAdminPointCat) -or (objectclass -eq "intellimirrorSCP")} -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$scpsdomain1 = Get-ADObject -ResultPageSize $resultspagesize -searchbase $root.defaultNamingContext -Filter {(objectclass -eq "mSSMSManagementPoint") -or (ObjectCategory -eq $SAdminPointCat) -or (objectclass -eq "intellimirrorSCP")} -Server $server -properties *
$i++
}
if($scpsdomain1){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$criticalobjects += $scpsdomain1
$countscpsdomain1 = ($scpsdomain1 | measure-object).count
#SCP serviceClassName of interest
$scpsdomain2 = Get-ADObject -searchbase $root.defaultNamingContext -Filter {(objectclass -eq "serviceConnectionPoint") -and (serviceClassName -like "*")} -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$scpsdomain2 = Get-ADObject -ResultPageSize $resultspagesize -searchbase $root.defaultNamingContext -Filter {(objectclass -eq "serviceConnectionPoint") -and (serviceClassName -like "*")} -Server $server -properties *
$i++
}
if($scpsdomain2){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
#Known list of relevant serviceClassName ldap = ADLDS, Vcenter..., TSGateway = RDS Gateway, BEMainService = BackupExec server, Groupwise = Novell Groupwise
$knowrelevantscpsdomain2 = $scpsdomain2 | where-object{($_.serviceClassName -eq "ldap") -or ($_.serviceClassName -eq "TSGateway") -or ($_.serviceClassName -eq "BEMainService") -or ($_.serviceClassName -eq "groupwise")}
$criticalobjects += $knowrelevantscpsdomain2
$countscpsdomain2 = ($knowrelevantscpsdomain2 | measure-object).count
#Get serviceClassName with few occurences outisde known list to discover new intersting serviceClassName.
$remainingscpsdomain2 = $scpsdomain2 | where-object{($_.serviceClassName -ne "ldap") -and ($_.serviceClassName -ne "TSGateway") -and ($_.serviceClassName -ne "BEMainService") -and ($_.serviceClassName -ne "groupwise")}
if($remainingscpsdomain2)
{
$rarescp = $remainingscpsdomain2 | Group-Object -Property serviceClassName | where-object{($_.count -le 3)}
if($rarescp)
{
foreach($rareserviceclassname in $rarescp)
{
$rarescptoadd = $remainingscpsdomain2 | Where-Object{$_.serviceClassName -eq $rareserviceclassname.Name}
$countscpsdomain2 = $countscpsdomain2 + $rareserviceclassname.count
$criticalobjects += $rarescptoadd
}
}
}
if($error)
{ "$(Get-TimeStamp) Error while retrieving Service Connection Point class objects of interest located in the domain partition $($error)" | out-file $logfilename -append ; $error.clear() }
else {$countscpsdomain = $countscpsdomain1 + $countscpsdomain2; "$(Get-TimeStamp) Number of Service Connection Point class objects of interest located in the domain partition: $($countscpsdomain)" | out-file $logfilename -append}
#Retrieving Service Connection Point class objects located in the configuration partition
$countallscps = 0
$scps = Get-ADObject -searchbase $root.configurationNamingContext -filter {ObjectClass -eq 'ServiceConnectionPoint'} -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$scps = Get-ADObject -ResultPageSize $resultspagesize -searchbase $root.configurationNamingContext -filter {ObjectClass -eq 'ServiceConnectionPoint'} -Server $server -properties *
$i++
}
if($scps){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
#Might be read rights issues, trying GC
if($error -like '*Directory object not found*')
{
$search = new-object System.DirectoryServices.DirectorySearcher
$search.pagesize = 256
$scpCategory = "CN=Service-Connection-Point," + $root.SchemaNamingContext
$search.filter = "((ObjectCategory=$($scpCategory)))"
$search.searchroot = [ADSI]"GC://$($gc)"
$scpquery = $search.findall()
$scpsgc = $scpquery | where-object{$_.properties.distinguishedname -like "*CN=Services,CN=Configuration*"} | Convert-ADSearchResult
if($scpsgc){
$error.clear()
$countallscps = ($scpsgc | measure-object).count
$gcobjects += $scpsgc
}
}
if($scps){
$criticalobjects += $scps
$countallscps = ($scps | measure-object).count
}
if($error)
{ "$(Get-TimeStamp) Error while retrieving Service Connection Point objects located in the configuration partition $($error)" | out-file $logfilename -append ; $error.clear() }
else
{ if($scps){"$(Get-TimeStamp) Number of Service Connection Point objects located in the configuration partition retrieved via LDAP: $($countallscps)" | out-file $logfilename -append}
elseif($scpsgc){"$(Get-TimeStamp) Number of Service Connection Point objects located in the configuration partition retrieved via GC: $($countallscps)" | out-file $logfilename -append}
else{"$(Get-TimeStamp) Number of Service Connection Point objects located in the configuration partition: $($countallscps)" | out-file $logfilename -append}
}
#Retrieving server and ntdsdsa class objects located in the configuration partition (Domain Controllers)
$dcrepls = Get-ADObject -searchbase $root.configurationNamingContext -filter {(ObjectClass -eq 'Server') -or (ObjectClass -eq 'nTDSDSA')} -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$dcrepls = Get-ADObject -ResultPageSize $resultspagesize -searchbase $root.configurationNamingContext -filter {(ObjectClass -eq 'Server') -or (ObjectClass -eq 'nTDSDSA')} -Server $server -properties *
$i++
}
if($dcrepls){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
$criticalobjects += $dcrepls
$countdcrepls = ($dcrepls | measure-object).count
$countserverd = ($deleteconf | where-object{$_.ObjectClass -eq 'Server'} | measure-object).count
$countnTDSDSAd = ($deleteconf | where-object{$_.ObjectClass -eq 'nTDSDSA'} | measure-object).count
if($error)
{ "$(Get-TimeStamp) Error while retrieving server and ntdsdsa class objects located in the configuration partition and in the tombstone $($error)" | out-file $logfilename -append ; $error.clear() }
else
{
"$(Get-TimeStamp) Number of server and ntdsdsa class objects located in the configuration partition: $($countdcrepls)" | out-file $logfilename -append
if(($countnTDSDSAd -ge 1) -or ($countserverd -ge 1))
{"$(Get-TimeStamp) Domain Controller demotion or use of DCShadow: $($countserverd) deleted server objects and $($countnTDSDSAd) deleted nTDSDSA objects located in the tombstone" | out-file $logfilename -append}
}
#Domain controller computer objects (existing en deleted)
$OUDCs = "OU=Domain Controllers," + $root.defaultNamingContext
#Existing Domain controllers in current domain
$DCpresents = Get-ADObject -searchbase $OUDCs -filter {(ObjectClass -eq 'Computer') -and ((PrimaryGroupID -eq 521) -or (PrimaryGroupID -eq 516))} -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$DCpresents = Get-ADObject -ResultPageSize $resultspagesize -searchbase $OUDCs -filter {(ObjectClass -eq 'Computer') -and ((PrimaryGroupID -eq 521) -or (PrimaryGroupID -eq 516))} -Server $server -properties *
$i++
}
if($DCpresents){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
if($error)
{ "$(Get-TimeStamp) Error while retrieving existing domain controllers in current domain $($error)" | out-file $logfilename -append ; $error.clear() }
$countDCpresents = ($DCpresents | measure-object).count
$criticalobjects += $DCpresents
# Deleted domain controllers in current domain (tombstoned)
$DCeffaces = Get-ADObject -searchbase $DeleteBase -filter {(IsDeleted -eq $true) -and (LastKnownParent -eq $OUDCs) -and (ObjectClass -eq 'Computer')} -IncludeDeletedObjects -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$DCeffaces = Get-ADObject -ResultPageSize $resultspagesize -searchbase $DeleteBase -filter {(IsDeleted -eq $true) -and (LastKnownParent -eq $OUDCs) -and (ObjectClass -eq 'Computer')} -IncludeDeletedObjects -Server $server -properties *
$i++
}
if($DCeffaces){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
}
if($error)
{ "$(Get-TimeStamp) Error while retrieving deleted domain controllers in current domain $($error)" | out-file $logfilename -append ; $error.clear() }
$countDCeffaces = ($DCeffaces| measure-object).count
$criticalobjects += $DCeffaces
# Retrieving existing domain controllers outside current domain and inside the current forest
$ComputerCategory = "CN=Computer," + $root.SchemaNamingContext
$search = new-object System.DirectoryServices.DirectorySearcher
$search.pagesize = 256
$search.filter = "(&(ObjectCategory=$($ComputerCategory))(|(PrimaryGroupID=521)(PrimaryGroupID=516)))"
$search.searchroot = [ADSI]"GC://$($gc)"
$allDCs = $search.findall() | Convert-ADSearchResult
$otherDCs = $allDCs | where-object{$_.DistinguishedName -notlike "*$($OUDCs)"}
$countallDCs = ($allDCs | measure-object).count
$gcobjects += $otherDCs
if($error)
{ "$(Get-TimeStamp) Error while retrieving domain controllers in the current forest via GC $($error)" | out-file $logfilename -append ; $error.clear() }
else
{
"$(Get-TimeStamp) Total number of existing domain controllers computer objects in the current forest: $($countallDCs)" | out-file $logfilename -append
"$(Get-TimeStamp) Total number of existing domain controllers computer objects in the current domain: $($countDCpresents)" | out-file $logfilename -append
"$(Get-TimeStamp) Total number of deleted domain controllers computer objects in the current domain: $($countDCeffaces)" | out-file $logfilename -append
}
#Objects with kerberos delegation configured
$delegkrb = Get-ADObject -filter {(UserAccountControl -BAND 0x0080000) -OR (UserAccountControl -BAND 0x1000000) -OR (msDS-AllowedToDelegateTo -like "*") -OR (msDS-AllowedToActOnBehalfOfOtherIdentity -like "*")} -Server $server -properties *
if(($error -like '*timeout*') -or ($error -like '*invalid enumeration context*'))
{
$i = 1
while((($error -like '*timeout*') -or ($error -like '*invalid enumeration context*')) -and ($i -le 5))
{
$resultspagesize = 256 - $i * 40
write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
$error.clear()
$delegkrb = Get-ADObject -ResultPageSize $resultspagesize -filter {(UserAccountControl -BAND 0x0080000) -OR (UserAccountControl -BAND 0x1000000) -OR (msDS-AllowedToDelegateTo -like "*") -OR (msDS-AllowedToActOnBehalfOfOtherIdentity -like "*")} -Server $server -properties *
$i++
}