Full Code of ANSSI-FR/ADTimeline for AI

master fa570aa15a03 cached
20 files
430.4 KB
122.4k tokens
1 requests
Download .txt
Showing preview only (445K chars total). Download the full file or copy to clipboard to get everything.
Repository: ANSSI-FR/ADTimeline
Branch: master
Commit: fa570aa15a03
Files: 20
Total size: 430.4 KB

Directory structure:
gitextract_qju42vfu/

├── .github/
│   └── workflows/
│       └── buildsplunkapp.yml
├── ADTimeline.ps1
├── LICENSE
├── README.md
└── SA-ADTimeline/
    ├── README
    ├── default/
    │   ├── app.conf
    │   ├── data/
    │   │   └── ui/
    │   │       ├── nav/
    │   │       │   └── default.xml
    │   │       └── views/
    │   │           ├── ad_infra.xml
    │   │           ├── getting_started.xml
    │   │           ├── investigate_timeframe.xml
    │   │           ├── sensitive_accounts.xml
    │   │           ├── suspicious_activity.xml
    │   │           └── suspicious_exchange_activity.xml
    │   ├── props.conf
    │   └── transforms.conf
    ├── lookups/
    │   ├── CSE_matching
    │   ├── ExchangeSchemaVersions
    │   ├── ObjectVersionSchema
    │   └── fsmoroleowner
    └── metadata/
        └── default.meta

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/workflows/buildsplunkapp.yml
================================================
name: Build Splunk App

on:
  push:
    branches:
      - 'master'

jobs:
  build_splunk_app:
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v4

      - name: Change permissions of folders
        run: find $GITHUB_WORKSPACE/SA-ADTimeline -type d -exec chmod 700 {} +

      - name: Change permissions of files
        run: find $GITHUB_WORKSPACE/SA-ADTimeline -type f -exec chmod 600 {} +

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.7'

      - name: Install Splunk Packaging Toolkit
        run: pip install 'https://download.splunk.com/misc/packaging-toolkit/splunk-packaging-toolkit-1.0.1.tar.gz'

      - name: SLIM Package App
        run: slim package $GITHUB_WORKSPACE/SA-ADTimeline
        
      - name: Upload Artifact
        uses: actions/upload-artifact@v4
        with:
          name: "SA-ADTimeline_${{github.sha}}"
          path: SA-ADTimeline*.gz

================================================
FILE: ADTimeline.ps1
================================================
# 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++
		}
	if($delegkrb){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
	else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
	}
$countdelegkrb = ($delegkrb | measure-object).count
$delegkrbnoconstrained = $delegkrb | where-object{($_.UserAccountControl -BAND 0x0080000)}
$countdelegkrbnoconstrained  = ($delegkrbnoconstrained | measure-object).count
$criticalobjects += $delegkrb
if($error)
    { "$(Get-TimeStamp) Error while retrieving objects trusted for Kerberos delegation: $($error)" | out-file $logfilename -append ; $error.clear() }
else
	{
	"$(Get-TimeStamp) Number of objects kerberos delegation setup: $($countdelegkrb) "  | out-file $logfilename -append
	"$(Get-TimeStamp) Number of objects with Kerberos unconstrained delegation configured: $($countdelegkrbnoconstrained) - $($countDCpresents) of them are domain controllers"  | out-file $logfilename -append
	}


#Directory Service Information object
$DSInfo = "CN=Directory Service,CN=Windows NT,CN=Services," + $root.configurationNamingContext
$criticalobjects += Get-ADObject $DSInfo -Server $server -properties *
if($error)
    { "$(Get-TimeStamp) Error while retrieving Directory Service Information object information $($error)" | out-file $logfilename -append ; $error.clear() }
else
	{
	"$(Get-TimeStamp) Directory Service Information object retrieved in the configuration partition "  | out-file $logfilename -append
	}


#Getting all existing and deleted DNS Zones
$DNSZones = $root.namingcontexts | where-object{$_ -like "*DnsZones,*"} | foreach-object{get-adobject -searchbase $_ -Filter {ObjectClass -eq 'DNSZone'} -includedeletedobjects -properties * -server $server}
$criticalobjects += $DNSZones
$countDNSZones = ($DNSZones | measure-object).count
if($error)
    { "$(Get-TimeStamp) Error while retrieving DNS zones $($error)" | out-file $logfilename -append ; $error.clear() }
else {"$(Get-TimeStamp) Number of existing and deleted DNS zones: $($countDNSZones)" | out-file $logfilename -append}


#Group Policy Objects, trusts, DPAPI secrets, AdminSDHolder, domainPolicy, RIDManager under the System container, GPO WMI Filters
$sysroot = "CN=System,"  + ($root.defaultNamingContext)
$sysobjects =  get-adobject -searchbase $sysroot -SearchScope SubTree -Filter {(ObjectClass -eq "groupPolicyContainer") -or (ObjectClass -eq "trustedDomain") -or (ObjectClass -eq "msWMI-Som") -or (ObjectClass  -eq "rIDManager")  -or (ObjectClass -eq "secret")  -or (ObjectClass -eq "domainPolicy") -or (Name -eq "AdminSDHolder")} -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()
		$sysobjects = Get-ADObject -ResultPageSize $resultspagesize -searchbase $sysroot -SearchScope SubTree -Filter {(ObjectClass -eq "groupPolicyContainer") -or (ObjectClass -eq "trustedDomain")  -or (ObjectClass  -eq "rIDManager") -or (ObjectClass -eq "secret") -or (ObjectClass -eq "domainPolicy") -or (Name -eq "AdminSDHolder")} -server $server -properties *
		$i++
		}
	if($sysobjects){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
	else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
	}
$criticalobjects += $sysobjects
$countsysobjects = ($sysobjects | measure-object).count
if($error)
    { "$(Get-TimeStamp) Error while retrieving objects under the system container $($error)" | out-file $logfilename -append ; $error.clear() }
else {
	$ridmanager = (((($sysobjects | where-object{$_.ObjectClass  -eq "rIDManager"}).fsmoRoleOwner).replace($root.configurationNamingContext,"")).replace("CN=NTDS Settings,","")).replace("CN=Sites,","CN=Sites")
	"$(Get-TimeStamp) Number of objects of interest under the system container (GPOs, domain trusts, DPAPI secrets, AdminSDHolder, RID Manager, WMI filters and domainPolicy): $($countsysobjects)" | out-file $logfilename -append
}

$adminSDHolder = $sysobjects | Where-Object{($_.Name -eq "AdminSDHolder") -and ($_.ObjectClass -eq "Container")}
if($adminSDHolder)
	{
	$accountsACEadminSDHolder = ($adminSDHolder.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 AdminSDHolder object $($error)" | out-file $logfilename -append ; $error.clear() }
	else
		{
		$usrcount = 0
		$userACE = $null
		foreach($accountACE in $accountsACEadminSDHolder)
			{
			#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 $logfilename -append ; $error.clear() }
			else
				{#Check if objectclass is user
				if(($userACE.ObjectClass -eq "user") -or ($userACE.ObjectClass -eq "inetOrgPerson"))
					{$usrcount++
					}
				}

			}
		}
		 "$(Get-TimeStamp) Number of user accounts having an ACE on AdminSDHolder object: $($usrcount)" | out-file $logfilename -append
	}

#Loop through domain trusts and return their state
$trusts = $sysobjects | where-object{$_.ObjectClass -eq "trustedDomain"}

if($trusts)
    {
    $counttrusts = ($trusts | measure-object).count
    "$(Get-TimeStamp) Number of domain trusts: $($counttrusts)" | out-file $logfilename -append

    foreach($trust in $trusts)
	    {
		$sidfilt = "enabled"
	    if(([int32]$trust.trustattributes -band 0x00000004) -eq 0)
		    {
		    $sidfilt = "disabled"
		    }
		if(([int32]$trust.trustattributes -band 0x00000008) -eq 8)
		    {
		    $type = "inter-forest"
		    }
		if(([int32]$trust.trustattributes -band 0x00000032) -eq 32)
		    {
		    $type = "forest internal"
		    }
		if(([int32]$trust.trustattributes -band 0x00000016) -eq 16)
		    {
		    $type = "cross org trust with selective authentication"
		    }
		if(([int32]$trust.trustdirection) -eq 3)
		    {
		    $dir = "both directions"
		    }
		if(([int32]$trust.trustdirection) -eq 2)
		    {
		    $dir = "outgoing"
		    }
		if(([int32]$trust.trustdirection) -eq 1)
		    {
		    $dir = "incoming"
		    }
		if(([int32]$trust.trustdirection) -eq 0)
		    {
		    $dir = "disabled"
		    }
		"$(Get-TimeStamp) The domain trust with $($trust.name) is $($type) and $($dir) , SID filtering is $($sidfilt)" | out-file $logfilename -append
	    }
    }
else
    { "$(Get-TimeStamp) No domain trusts to process" | out-file $logfilename -append }

if($error)
    { "$(Get-TimeStamp) Error while retrieving domain trusts $($error)" | out-file $logfilename -append ; $error.clear() }

# Get all domain trusts of each domain in the forest through global catalog
$ContSys = "CN=System," + $root.defaultNamingContext
$TrustCat = "CN=Trusted-Domain," + $root.SchemaNamingContext
$search = new-object System.DirectoryServices.DirectorySearcher
$search.searchroot = [ADSI]"GC://$($gc)"
$search.pagesize = 256
$search.filter = "(ObjectCategory=$($TrustCat))"
$allTrustsquery = $search.findall()
if($allTrustsquery)
	{
	$allTrusts  = $allTrustsquery  | Convert-ADSearchResult
	$otherTrusts = $allTrusts | where-object{$_.DistinguishedName -notlike "*$($ContSys)"}
	$countallTrusts = ($allTrusts | group-object -property TrustPartner | measure-object).count
	$gcobjects += $otherTrusts
	if($error)
		{ "$(Get-TimeStamp) Error while retrieving domain trusts of each domain in the forest through GC $($error)" | out-file $logfilename -append ; $error.clear() }
	else {"$(Get-TimeStamp) Number of trust partners in the forest: $($countallTrusts)" | out-file $logfilename -append}
	}

# Get all domain roots in the forest through global catalog
$DomainCat = "CN=Domain-DNS," + $root.SchemaNamingContext
$search = new-object System.DirectoryServices.DirectorySearcher
$search.searchroot = [ADSI]"GC://$($gc)"
$search.pagesize = 256
$search.filter = "(ObjectCategory=$($DomainCat))"
$alldomains = $search.findall()  | Convert-ADSearchResult
$otherdomains = $alldomains | where-object{$_.DistinguishedName -ne $root.DefaultNamingContext}
$gcobjects += $otherdomains
$countallDomains = ($alldomains  | measure-object).count
	if($error)
		{ "$(Get-TimeStamp) Error while retrieving forest domain roots through GC $($error)" | out-file $logfilename -append ; $error.clear() }
	else {"$(Get-TimeStamp) Number of domain roots located in the forest: $($countallDomains)" | out-file $logfilename -append}

# Processing SID History accounts
# Get all accounts with SIDHistory present in the forest, limit properties loaded (DN,SID,SIDHistory) for performance
$search = new-object System.DirectoryServices.DirectorySearcher
$search.filter = "(SIDHistory=*)"
$search.pagesize = 256
$search.searchroot = [ADSI]"GC://$($gc)"
$search.PropertiesToLoad.Addrange(('DistinguishedName','SIDHistory','objectSID'))
$allSIDHistory  = $search.findall() | Convert-ADSearchResult
$countSIDHistory = ($allSIDHistory | measure-object).count
if($error)
    { "$(Get-TimeStamp) Error while retrieving accounts with SID History through GC $($error)" | out-file $logfilename -append ; $error.clear() }
else {"$(Get-TimeStamp) Number of accounts with SIDHistory in the forest: $($countSIDHistory)" | out-file $logfilename -append}

#Get accounts in the current domain with a suspicious SIDHistory: Meaning with a SIDHistory of its own domain or a well known SID with high privileges
$CurrDomainSIDHistory = $allSIDHistory | where-object {($_.objectSID -like "$domSID*") -and (($_.SIDHistory -like "*$domSID*") -or ($_.SIDHistory -like "*-500") -or ($_.SIDHistory -eq "S-1-5-32-548") -or ($_.SIDHistory -eq "S-1-5-32-544") -or ($_.SIDHistory -eq "S-1-5-32-551") -or ($_.SIDHistory -like "*-512") -or ($_.SIDHistory -like "*-516") -or ($_.SIDHistory -like "*-519") -or ($_.SIDHistory -eq "S-1-5-32-550") -or ($_.SIDHistory -like "*-498") -or ($_.SIDHistory -like "*-518")  -or ($_.SIDHistory -eq "S-1-5-32-549"))}
if($CurrDomainSIDHistory)
	{
	$NbCurrDomainSIDHistory = ($CurrDomainSIDHistory | measure-object).count
	 "$(Get-TimeStamp) Number of accounts with a suspicious SIDHistory in the current domain: $($NbCurrDomainSIDHistory)" | out-file $logfilename -append
	 foreach($objSIDH in $CurrDomainSIDHistory)
		{
		$criticalobjects += get-adobject $objSIDH.DistinguishedName -Server $server -properties *
		if($error){ "$(Get-TimeStamp) Error while retrieving accounts with a suspicious SIDHistory in the current domain $($error)" | out-file $logfilename -append ; $error.clear() }
		}
	}

# Get accounts in other domains than the current one within the forest which have an SIDHistory belonging to the current domain.
$OtherDomainSIDHistory = $allSIDHistory | where-object {($_.objectSID -notlike "$domSID*") -and ($_.SIDHistory -like "*$domSID*")}
if($OtherDomainSIDHistory)
	{
	# Get SIDs of accounts protected by SDProp in the current domain (i.e. privileged accounts)
	$sensibeSID = ($SDPropObjects | where-object{$_.objectSID -like "$domSID*"} | select-object -expandproperty objectSID).value
	$DangerOtherDomainSIDHistory = @()
	$NbOtherDomainSIDHistory = ($OtherDomainSIDHistory | measure-object).count
	$search = new-object System.DirectoryServices.DirectorySearcher
	$search.searchroot = [ADSI]"GC://$($gc)"
	"$(Get-TimeStamp) Number of accounts in other domains within the forest which have an SIDHistory belonging to the current domain $($NbOtherDomainSIDHistory)" | out-file $logfilename -append
	# Foreach account in other domains within the forest which have an SIDHistory belonging to the current domain we compare his SIDHistory with SIDs of accounts protected in the current domain by SDProp. If there is a match that could be suspicious.
	foreach($objSIDH in $OtherDomainSIDHistory)
			{
			foreach($SIDH in $objSIDH.SIDHistory)
				{

				if($sensibeSID.contains($SIDH))
					{
					$search.filter = "(DistinguishedName=$($objSIDH.DistinguishedName))"
					$DangerOtherDomainSIDHistory += $search.findone() | Convert-ADSearchResult
					}
				}
			if($error){ "$(Get-TimeStamp) Error while retrieving accounts in other domains within the forest which have an SIDHistory belonging to the current domain $($error)" | out-file $logfilename -append ; $error.clear() }

			}
	if($DangerOtherDomainSIDHistory)
		{
		$nbDangerOtherDomainSIDHistory = ($DangerOtherDomainSIDHistory | measure-object).count
		"$(Get-TimeStamp) Number of accounts in the forest with a suspicious SIDHistory value matching the current domain: $($nbDangerOtherDomainSIDHistory)" | out-file $logfilename -append
		$gcobjects += $DangerOtherDomainSIDHistory
		}
	}



#Fetch Organizational Units Objects, do not load all poperties for performance issues
$objOUs = Get-ADObject  -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -Filter {ObjectClass -eq "organizationalUnit"}  -Server $server

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()
		$objOUs = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -Filter {ObjectClass -eq "organizationalUnit"}  -Server $server
		$i++
		}
	if($objOUs){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 OUs $($error)" | out-file $logfilename -append ; $error.clear() }
else
	{
	$countobjOUs = ($objOUs | measure-object).count
	#If there is more than 1000 OUs we take only the level 1 + level 2 OUs and load all properties
	if($countobjOUs -ge 1000)
		{
		"$(Get-TimeStamp) Total number of OUs: $($countobjOUs), only level 1 and 2 OUs will be processed" | out-file $logfilename -append
		$OULevel1 = Get-ADObject -SearchBase ($root.defaultNamingContext) -SearchScope OneLevel -Server $server  -filter {ObjectClass -eq "organizationalUnit"} -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))
				{
				write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
				$resultspagesize = 256 - $i * 40
				$error.clear()
				$OULevel1 = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($root.defaultNamingContext) -SearchScope OneLevel -Server $server  -filter {ObjectClass -eq "organizationalUnit"} -properties *
				$i++
				}
			if($OULevel1){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
			else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
			}
		$totalOU = ($OULevel1 | measure-object).count
		$criticalobjects += $OULevel1
		if($error)
    			{ "$(Get-TimeStamp) Error while retrieving level 1 OUs $($error)" | out-file $logfilename -append ; $error.clear() }
		foreach($OU in $OULevel1)
			{
			$OULevel2 = Get-ADObject -SearchBase ($OU.DistinguishedName) -SearchScope OneLevel -Server $server  -filter {ObjectClass -eq "organizationalUnit"} -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()
					$OULevel2 = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($OU.DistinguishedName) -SearchScope OneLevel -Server $server  -filter {ObjectClass -eq "organizationalUnit"} -properties *
					$i++
					}
				if($OULevel2){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
				else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
				}
			$totalOU = $totalOU + ($OULevel2 | measure-object).count
			$criticalobjects += $OULevel2
			if($error)
    				{ "$(Get-TimeStamp) Error while retrieving level 2 OUs $($error)" | out-file $logfilename -append ; $error.clear() }
			}

		"$(Get-TimeStamp) Total number of OUs processed: $($totalOU)" | out-file $logfilename -append
		}
	else
		{
		#Less than 1000 OUs we process every OU and load all properties
		"$(Get-TimeStamp) Total number of OUs: $($countobjOUs)" | out-file $logfilename -append
		$objOUsfull = Get-ADObject  -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -Filter {ObjectClass -eq "organizationalUnit"}  -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()
				$objOUsfull = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -Filter {ObjectClass -eq "organizationalUnit"}  -Server $server -Properties *
				$i++
				}
			if($objOUsfull){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
			else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
			}
		$criticalobjects += $objOUsfull
		if($error)
    			{ "$(Get-TimeStamp) Error while retrieving OUs $($error)" | out-file $logfilename -append ; $error.clear() }
		}
	}


#Get AD replication sites, CertificationAuthority, pKIEnrollmentService, msDS-AuthNPolicySilo, msDS-AuthNPolicy and CrossRefs objects in the configuration partition
$sitesIGC = get-adobject -searchbase $root.configurationNamingContext -SearchScope SubTree -Filter {(ObjectClass -eq "CertificationAuthority") -or (ObjectClass -eq "pKIEnrollmentService") -or (ObjectClass -eq "msDS-AuthNPolicySilo") -or (ObjectClass -eq "msDS-AuthNPolicy") -or (ObjectClass -eq "site") -or (ObjectClass -eq "crossRefContainer") -or (ObjectClass -eq "crossRef")} -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()
		$sitesIGC = Get-ADObject -ResultPageSize $resultspagesize -searchbase $root.configurationNamingContext -SearchScope SubTree -Filter {(ObjectClass -eq "CertificationAuthority") -or (ObjectClass -eq "pKIEnrollmentService") -or (ObjectClass -eq "msDS-AuthNPolicySilo") -or (ObjectClass -eq "msDS-AuthNPolicy") -or (ObjectClass -eq "site") -or (ObjectClass -eq "crossRefContainer") -or (ObjectClass -eq "crossRef")} -server $server -properties *
		$i++
		}
	if($sitesIGC){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
	else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
	}
$criticalobjects +=  $sitesIGC
$countADreplsites = ($sitesIGC | where-object{$_.ObjectClass -eq "site"} |  measure-object).count
$countpKIEnrollmentService = ($sitesIGC | where-object{$_.ObjectClass -eq "pKIEnrollmentService"} |  measure-object).count
$countADIGC = ($sitesIGC | where-object{$_.ObjectClass -eq "CertificationAuthority"} |  measure-object).count
$countAuthN = ($sitesIGC | where-object{($_.ObjectClass -eq "msDS-AuthNPolicySilo") -or ($_.ObjectClass -eq "msDS-AuthNPolicy")} |  measure-object).count
if($error)
    { "$(Get-TimeStamp) Error while retrieving AD replication sites, CertificationAuthority, pKIEnrollmentService, msDS-AuthNPolicy and msDS-AuthNPolicysilos objects $($error)" | out-file $logfilename -append ; $error.clear() }
else {
	"$(Get-TimeStamp) Number of AD replication sites in the configuration partition: $($countADreplsites)" | out-file $logfilename -append
	"$(Get-TimeStamp) Number of CertificationAuthority objects in the configuration partition: $($countADIGC)" | out-file $logfilename -append
	"$(Get-TimeStamp) Number of pKIEnrollmentService objects in the configuration partition: $($countpKIEnrollmentService)" | out-file $logfilename -append
	"$(Get-TimeStamp) Number of AuthNPolicy or silos objects in the configuration partition: $($countAuthN)" | out-file $logfilename -append
	$crossrefcontainer = $sitesIGC | where-object{($_.Name -eq "Partitions") -and ($_.ObjectClass -eq "crossRefContainer")}
	$DomainNamingMaster = (((($crossrefcontainer.fsmoRoleOwner).replace($root.configurationNamingContext,"")).replace("CN=NTDS Settings,","")).replace("CN=Sis,","")).replace("CN=Sites,","CN=Sites")
	}


# Displayin FSMO role holders and FFL + DFL
if($PDCe)
	{ "$(Get-TimeStamp) PDCe for the domain is: $($PDCe)" | out-file $logfilename -append}
if($inframaster)
	{ "$(Get-TimeStamp) Infrastructure master for the domain is: $($inframaster)" | out-file $logfilename -append}
if($ridmanager)
	{ "$(Get-TimeStamp) RID Manager for the domain is: $($ridmanager)" | out-file $logfilename -append}
if($DomainNamingMaster)
	{ "$(Get-TimeStamp) Domain naming master for the forest is: $($DomainNamingMaster)" | out-file $logfilename -append}
if($SchemaMaster)
	{ "$(Get-TimeStamp) Schema master for the forest is: $($SchemaMaster)" | out-file $logfilename -append}
if($crossrefcontainer)
	{ "$(Get-TimeStamp) Forest functional level is: $($crossrefcontainer."msDS-Behavior-Version")" | out-file $logfilename -append}
$refdomains = $sitesIGC | where-object{($_.Objectclass -eq "crossRef") -and ($_.SystemFlags -eq 3)}
if($refdomains)
	{
	foreach($refdomain in $refdomains){ "$(Get-TimeStamp) $($refdomain.dnsRoot) domain functional level is $($refdomain."msDS-Behavior-Version")" | out-file $logfilename -append}
	}

#Find user accounts sensitive to Kerberoast attack (Service Principal Name not null)
$ObjCategoryusr = "CN=Person," + ($root.schemaNamingContext)
$kerberoast = Get-ADObject -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -LDAPFilter "(&(objectCategory=$ObjCategoryusr)(ServicePrincipalName=*))" -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()
		$kerberoast = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -LDAPFilter "(&(objectCategory=$ObjCategoryusr)(ServicePrincipalName=*))" -Server $server -properties *
		$i++
		}
	if($kerberoast){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
	else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
	}
$criticalobjects += $kerberoast
$kerberoastcount = ($kerberoast | where-object{($_.Name -ne "krbtgt")} | measure-object).count
$kerberoastadmcount = ($kerberoast | where-object{($_.Name -ne "krbtgt") -and ($_.Admincount -eq 1)} | measure-object).count
if($error)
    { "$(Get-TimeStamp) Error while retrieving kerberoastable accounts  $($error)" | out-file $logfilename -append ; $error.clear() }
else
	{
		"$(Get-TimeStamp) Number of kerberoastable accounts: $($kerberoastcount)" | out-file $logfilename -append
		if($kerberoastadmcount -ge 1)
			{"$(Get-TimeStamp) Number of kerberoastable accounts protected by SDProp: $($kerberoastadmcount)" | out-file $logfilename -append}
	}

#Find user accounts sensitive to AS-REP roast attack
$asreproast = Get-ADObject -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -ldapfilter {(&(objectCategory=person)(userAccountControl:1.2.840.113556.1.4.803:=4194304))} -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))
		{
		write-output -inputobject "LDAP time out, trying again with ResultPageSize $($resultspagesize)"
		$resultspagesize = 256 - $i * 40
		$error.clear()
		$asreproast = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -ldapfilter {(&(objectCategory=person)(userAccountControl:1.2.840.113556.1.4.803:=4194304))}  -Server $server -properties *
		$i++
		}
	if($asreproast){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
	else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
	}
$criticalobjects += $asreproast
$asreproastcount = ($asreproast | measure-object).count
$asreproastadmcount = ($asreproast | where-object {($_.Admincount -eq 1)} | measure-object).count
if($error)
    { "$(Get-TimeStamp) Error while retrieving AS-Rep roastables accounts  $($error)" | out-file $logfilename -append ; $error.clear() }
else
	{
		"$(Get-TimeStamp) Number of AS-Rep roastables accounts: $($asreproastcount)" | out-file $logfilename -append
		if($asreproastadmcount -ge 1)
			{"$(Get-TimeStamp) Number of AS-Rep roastable accounts protected by SDProp: $($asreproastadmcount)" | out-file $logfilename -append}
	}


#Get Extended rights defined in the Configuration partition
$extroot = "CN=Extended-Rights," +  $root.configurationNamingContext
$extrights = Get-ADObject -SearchBase $extroot -SearchScope OneLevel -Server $server -filter {ObjectClass -eq "controlAccessRight"} -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()
		$extrights = Get-ADObject -ResultPageSize $resultspagesize -SearchBase $extroot -SearchScope OneLevel -Server $server -filter * -properties *
		$i++
		}
	if($extrights){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
	else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
	}
$criticalobjects +=  $extrights
$countextrights = ($extrights | measure-object).count
if($error)
    { "$(Get-TimeStamp) Error while retrieving extended rights $($error)" | out-file $logfilename -append ; $error.clear() }
else {"$(Get-TimeStamp) Number of extended rights: $($countextrights)" | out-file $logfilename -append}


# Get schema attributes with Searchflags marked as confidential
$confidattr = Get-ADObject -SearchBase $root.SchemaNamingContext  -SearchScope OneLevel -Server $server -filter {(SearchFlags -BAND 0x00000080) -and (ObjectClass -eq "attributeSchema")} -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()
		$confidattr = Get-ADObject -ResultPageSize $resultspagesize -SearchBase $root.SchemaNamingContext  -SearchScope OneLevel -Server $server -filter {(SearchFlags -BAND 0x00000080) -and (ObjectClass -eq "attributeSchema")} -properties *
		$i++
		}
	if($extrights){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
	else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
	}
$criticalobjects +=  $confidattr
$countconfidattr = ($confidattr | measure-object).count
if($error)
    { "$(Get-TimeStamp) Error while retrieving schema attributes marked as confidential $($error)" | out-file $logfilename -append ; $error.clear() }
else
	{
	"$(Get-TimeStamp) Number of schema attributes marked as confidential: $($countconfidattr)" | out-file $logfilename -append
	$laps = $confidattr | where-object{$_.Name -eq "ms-Mcs-AdmPwd"}
	if($laps)
		{"$(Get-TimeStamp) LAPS is setup in this forest and ms-Mcs-AdmPwd is marked as confidential" | out-file $logfilename -append}
	else
		{"$(Get-TimeStamp) LAPS is not setup in the forest or ms-Mcs-AdmPwd is not marked as confidential" | out-file $logfilename -append}
	$bitlocker = $confidattr | where-object{$_.Name -eq "ms-FVE-RecoveryPassword"}
	if($bitlocker)
		{"$(Get-TimeStamp) Bitlocker recovery key attribute is marked as confidential" | out-file $logfilename -append}
	else
		{"$(Get-TimeStamp) Bitlocker recovery key attribute is not marked as confidential" | out-file $logfilename -append}
	}


# Get schema attributes with Searchflags marked as never audit
$neveraudit = Get-ADObject -SearchBase $root.SchemaNamingContext  -SearchScope OneLevel -Server $server -filter {(SearchFlags -BAND 0x00000100) -and (ObjectClass -eq "attributeSchema")} -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()
		$neveraudit = Get-ADObject -ResultPageSize $resultspagesize -SearchBase $root.SchemaNamingContext  -SearchScope OneLevel -Server $server -filter {(SearchFlags -BAND 0x00000100) -and (ObjectClass -eq "attributeSchema")} -properties *
		$i++
		}
	if($extrights){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
	else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
	}
$criticalobjects +=  $neveraudit
$countneveraudit = ($neveraudit | measure-object).count
if($error)
    { "$(Get-TimeStamp) Error while retrieving schema attributes marked as never to audit $($error)" | out-file $logfilename -append ; $error.clear() }
else {"$(Get-TimeStamp) Number of schema attributes marked as never to audit: $($countneveraudit)" | out-file $logfilename -append}



#Check if current domain is root or child domain. if child domain get domain, enterprise, schema admins of root domain
if($root.rootDomainNamingContext -eq $root.DefaultNamingContext)
	{
	"$(Get-TimeStamp) Current domain is the root domain" | out-file $logfilename -append
	}
Else
	{
	"$(Get-TimeStamp) Current domain is a child domain" | out-file $logfilename -append
	$search = new-object System.DirectoryServices.DirectorySearcher
	$search.searchroot = [ADSI]"GC://$($gc)/$($root.rootDomainNamingContext)"
	$search.searchscope = "Base"
	$search.filter = "(ObjectSID=*)"
	$rootdom = $search.Findone() | Convert-ADSearchResult
	$gcobjects  += $rootdom
	$rootdomSID = $rootdom.ObjectSID
	$rootDomadmSID = $rootdomSID + "-512"
	$rootEntadmSID = $rootdomSID + "-519"
	$rootSchemaSID = $rootdomSID + "-518"
	#Cannot retrieve privileged accounts via SDProp, because AdminCount is not in partial attribute set, getting by group membership.
	#Retrieving the domain admins group which is global: cannot get members via GC
	$search.searchscope = "Subtree"
	$search.filter = "(ObjectSID=$($rootDomadmSID))"
	$rootda = $search.Findone() | Convert-ADSearchResult
	$gcobjects += $rootda
	if($error)
			{ "$(Get-TimeStamp) Error while retrieving domain admins group in root domain $($error)" | out-file $logfilename -append ; $error.clear() }
	else
			{"$(Get-TimeStamp) Domain admins group sucessfully retrieved in root domain" | out-file $logfilename -append}
	#Retrieving the schema and enterprise admins groups which are universal: we can retrieve members via GC
	$search.filter = "(|(ObjectSID=$($rootEntadmSID))(ObjectSID=$($rootSchemaSID)))"
	$rootUadmins = $search.FindAll() | Convert-ADSearchResult
	$gcobjects += $rootUadmins
	$countrootadminsmembers = 0
	foreach($rootadmin in $rootUadmins)
		{
		$rootadminsmembers = $null
		$search.searchroot = [ADSI]"GC://$($gc)"
		if($rootadmin.Member){$rootadminsmembers = $rootadmin.Member | foreach-object{$search.filter = "(DistinguishedName=$($_))"; $search.FindOne() | Convert-ADSearchResult}}
		$countrootadminsmembers = ($rootadminsmembers | measure-object).count + $countrootadminsmembers
		$gcobjects += $rootadminsmembers
		}
		if($error)
			{ "$(Get-TimeStamp) Error while retrieving enterprise and schema admins members located in the root domain $($error)" | out-file $logfilename -append ; $error.clear() }
				else
			{"$(Get-TimeStamp) Number of level 1 enterprise and schema admins members located in the root domain: $($countrootadminsmembers)" | out-file $logfilename -append}
	}


$IsADFS = $false
$IsADFSroot = $false
$IsADFScurrent = $false
#Processing ADFS
if($root.rootDomainNamingContext -eq $root.DefaultNamingContext)
	{
	#If root domain just check ADFS in current domain
	$ADFS = "CN=ADFS,CN=Microsoft,CN=Program Data," + ($root.DefaultNamingContext)
	$IsADFS = [ADSI]::Exists("GC://$($gc)/$($ADFS)")
	if($error)
		{ "$(Get-TimeStamp) Error while testing existance of ADFS objects $($error)" | out-file $logfilename -append ; $error.clear() }
	if($IsADFS -eq $true)
		{
		#Current domain is root domain using LDAP to retrieve ADFS Objects
		$ADFSObjects = get-ADObject -searchbase $ADFS -filter * -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()
				$ADFSObjects = Get-ADObject -ResultPageSize $resultspagesize -searchbase $ADFS -filter * -server $server -properties *
				$i++
				}
			if($ADFSObjects){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
			else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
			}
		$criticalobjects +=  $ADFSObjects
		$ADFSFarms = $ADFSObjects | Where-Object{($_.ObjectClass -eq "Container") -and ($_.Name -ne "ADFS")}
		$ADFSrootobj = $ADFSObjects | Where-Object{($_.ObjectClass -eq "Container") -and ($_.Name -eq "ADFS")}
		$countADFSFarms = ( $ADFSFarms | measure-object).count
		if($error)
			{ "$(Get-TimeStamp) Error while retrieving ADFS Objects $($error)" | out-file $logfilename -append ; $error.clear() }
		else {"$(Get-TimeStamp) Number of ADFS farms (containers) in the current domain: $($countADFSFarms)" | out-file $logfilename -append}

		# If ADFS farms are found searching for service accounts running ADFS, ACE is present on objects storing DKM information
		if($ADFSFarms -and $ADFSrootobj)
			{
			$accountsACEADFSRoot = 	($ADFSrootobj.ntsecuritydescriptor).getaccessrules($true , $true , [System.Security.Principal.SecurityIdentifier]) | Where-Object {$_.IdentityReference -like "S-1-5-21-*"} | group-object -property IdentityReference
			foreach($ADFSFarm in $ADFSFarms)
				{
				#Comparing ACL of ADFS root object and child objects (i.e) farms in order to retrieve ADFS service accounts
				$accountsACEADFSFarm = ($ADFSFarm.ntsecuritydescriptor).getaccessrules($true , $true , [System.Security.Principal.SecurityIdentifier]) | Where-Object {$_.IdentityReference -like "S-1-5-21-*"} | group-object -property IdentityReference
				$compareACEfarmroot = compare-object $accountsACEADFSFarm $accountsACEADFSRoot -Property Name
				if($error)
					{ "$(Get-TimeStamp) Error while retrieving accounts having an ACE on ADFS Farm object $($error)" | out-file $logfilename -append ; $error.clear() }
				else
					{
					$userACE = $null
					foreach($accountACE in $compareACEfarmroot)
						{
						#If ACE for the given SID is in the current domain, use LDAP
						if($accountACE.Name -like "$domSID*")
							{
							$sidtomatch = $accountACE.Name
							$userACE = Get-ADObject -Filter {ObjectSID -eq $sidtomatch} -Server $server -properties *
							if($userACE){$criticalobjects += $userACE}
							}
						#Otherwise try GC
						else
							{
							$search = new-object System.DirectoryServices.DirectorySearcher
							$search.searchroot = [ADSI]"GC://$($gc)"
							$sidtomatch = $accountACE.Name
							$search.filter = "(ObjectSID=$($sidtomatch))"
							$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 $logfilename -append ; $error.clear() }

						}
					}

				}

			}
		}


	}
else
	{
	#Domain is child domain. Check if ADFS is in current domain or parent domain.
	$ADFSroot = "CN=ADFS,CN=Microsoft,CN=Program Data," + ($root.rootDomainNamingContext)
	$IsADFSroot = [ADSI]::Exists("GC://$($gc)/$($ADFSroot)")
	$ADFScurrent = "CN=ADFS,CN=Microsoft,CN=Program Data," + ($root.DefaultNamingContext)
	$IsADFScurrent = [ADSI]::Exists("GC://$($gc)/$($ADFScurrent)")
	if($error)
		{ "$(Get-TimeStamp) Error while testing existance of ADFS objects $($error)" | out-file $logfilename -append ; $error.clear() }
	if($IsADFSroot -eq $true)
		{
		$search = new-object System.DirectoryServices.DirectorySearcher
		$search.searchroot = [ADSI]"GC://$($gc)/$($ADFSroot)"
		$search.pagesize = 256
		$search.filter = "(ObjectClass=*)"
		$ADFSObjects = $search.FindAll() | Convert-ADSearchResult
		$gcobjects +=  $ADFSObjects
		$ADFSFarms = $ADFSObjects | Where-Object{($_.ObjectClass -eq "Container") -and ($_.Name -ne "ADFS")}
		$countADFSFarms = ( $ADFSFarms | measure-object).count
		if($error)
			{ "$(Get-TimeStamp) Error while retrieving ADFS Objects $($error)" | out-file $logfilename -append ; $error.clear() }
		else {"$(Get-TimeStamp) Number of ADFS farms (containers) in the root domain: $($countADFSFarms)" | out-file $logfilename -append}
		}
	if($IsADFScurrent -eq $true)
		{
		$ADFSObjects = get-ADObject -searchbase $ADFScurrent -filter * -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()
				$ADFSObjects = Get-ADObject -ResultPageSize $resultspagesize -searchbase $ADFS -filter * -server $server -properties *
				$i++
				}
			if($ADFSObjects){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
			else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
			}
		$criticalobjects +=  $ADFSObjects
		$ADFSFarms = $ADFSObjects | Where-Object{($_.ObjectClass -eq "Container") -and ($_.Name -ne "ADFS")}
		$ADFSrootobj = $ADFSObjects | Where-Object{($_.ObjectClass -eq "Container") -and ($_.Name -eq "ADFS")}
		$countADFSFarms = ( $ADFSFarms | measure-object).count
		if($error)
			{ "$(Get-TimeStamp) Error while retrieving ADFS Objects $($error)" | out-file $logfilename -append ; $error.clear() }
		else {"$(Get-TimeStamp) Number of ADFS farms (containers) in the current domain: $($countADFSFarms)" | out-file $logfilename -append}

		# If ADFS farms are found searching for service accounts running ADFS, ACE is present on objects storing DKM information
		if($ADFSFarms -and $ADFSrootobj)
			{
			$accountsACEADFSRoot = 	($ADFSrootobj.ntsecuritydescriptor).getaccessrules($true , $true , [System.Security.Principal.SecurityIdentifier]) | Where-Object {$_.IdentityReference -like "S-1-5-21-*"} | group-object -property IdentityReference
			foreach($ADFSFarm in $ADFSFarms)
				{
				#Comparing ACL of ADFS root object and child objects (i.e) farms in order to retrieve ADFS service accounts
				$accountsACEADFSFarm = ($ADFSFarm.ntsecuritydescriptor).getaccessrules($true , $true , [System.Security.Principal.SecurityIdentifier]) | Where-Object {$_.IdentityReference -like "S-1-5-21-*"} | group-object -property IdentityReference
				$compareACEfarmroot = compare-object $accountsACEADFSFarm $accountsACEADFSRoot -Property Name
				if($error)
					{ "$(Get-TimeStamp) Error while retrieving accounts having an ACE on ADFS Farm object $($error)" | out-file $logfilename -append ; $error.clear() }
				else
					{
					$userACE = $null
					foreach($accountACE in $compareACEfarmroot)
						{
						#If ACE for the given SID is in the current domain, use LDAP
						if($accountACE.Name -like "$domSID*")
							{
							$sidtomatch = $accountACE.Name
							$userACE = Get-ADObject -Filter {ObjectSID -eq $sidtomatch} -Server $server -properties *
							if($userACE){$criticalobjects += $userACE}
							}
						#Otherwise try GC
						else
							{
							$search = new-object System.DirectoryServices.DirectorySearcher
							$search.searchroot = [ADSI]"GC://$($gc)"
							$sidtomatch = $accountACE.Name
							$search.filter = "(ObjectSID=$($sidtomatch))"
							$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 $logfilename -append ; $error.clear() }

						}
					}
				}
			}
		}

	}


#Check if MS Exchange is installed by testing the Exchange Trusted SubSystem (ETS) existance
$trustedSubSystem = "CN=Exchange Trusted Subsystem,OU=Microsoft Exchange Security Groups," + ($root.rootDomainNamingContext)
$ISets = [ADSI]::Exists("GC://$($gc)/$($trustedSubSystem)")
$serviceNC = "CN=Services," + ($root.configurationNamingContext)
$RBAC = $null
if($error)
    { "$(Get-TimeStamp) Error while retrieving Exchange trusted subsystem  object $($error)" | out-file $logfilename -append ; $error.clear() }

if($ISets -eq $true)
	{
	$exchschemaverpath = "CN=ms-Exch-Schema-Version-Pt," + ($root.schemaNamingContext)
	$exchschemaver = get-adobject $exchschemaverpath -server $server -properties *
	$criticalobjects += $exchschemaver
	if($error)
		{ "$(Get-TimeStamp) Error while retrieving Exchange schema version $($error)" | out-file $logfilename -append ; $error.clear() }
	else {"$(Get-TimeStamp) Exchange schema version is: $($exchschemaver.rangeUpper)" | out-file $logfilename -append}

	if($root.rootDomainNamingContext -eq $root.DefaultNamingContext)
		{
		# If current domain is root domain, we do not need GC to retrieve Exchange objects information.
		$ets = get-adobject $trustedSubSystem -server $server -properties *
		$criticalobjects += $ets
		"$(Get-TimeStamp) Retrieving Exchange Trusted Subsytem, Exchange servers and Exchange Windows Permissions groups" | out-file $logfilename -append
		$Winperm = "CN=Exchange Windows Permissions,OU=Microsoft Exchange Security Groups," + ($root.rootDomainNamingContext)
		$ExcSRV = "CN=Exchange Servers,OU=Microsoft Exchange Security Groups," + ($root.rootDomainNamingContext)
		$criticalobjects += get-adobject $Winperm -server $server -properties *
		$criticalobjects += get-adobject $ExcSRV -server $server -properties *

		if($error)
			{ "$(Get-TimeStamp) Error while retrieving Exchange Trusted Subsytem or Exchange servers or Exchange Windows Permissions groups $($error)" | out-file $logfilename -append ; $error.clear() }

		if($isonline -eq $true)
			{
			$trustedsubsysmembers = (Get-ADGroupMember -recursive $ets -server $server  | foreach-object{get-adobject $_ -server $server -properties *})
			$criticalobjects += $trustedsubsysmembers
			$nestedgrp = @()
			$level1 = Get-ADGroupMember $ets -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 *})
				}
				$counttrustedsubsysmembers = ($trustedsubsysmembers | measure-object).count
				if($error)
				{ "$(Get-TimeStamp) Error while retrieving ETS members $($error)" | out-file $logfilename -append ; $error.clear() }
				else
				{"$(Get-TimeStamp) Number of  ETS members: $($counttrustedsubsysmembers)" | out-file $logfilename -append}
			}
		else
			{
			$trustedsubsysmembers = ($ets | select-object -expandproperty member  | foreach-object{get-adobject $_ -server $server -properties *})
			$criticalobjects += $trustedsubsysmembers
			$continue = $trustedsubsysmembers | where-object{$_.ObjectClass -eq "Group"}
			if($continue)
				{foreach($grp in $continue){$trustedsubsysmembersn2 = $grp | select-object -expandproperty member  | foreach-object{get-adobject $_ -server $server -properties *};$criticalobjects += $trustedsubsysmembersn2}}
			if($error)
				{ "$(Get-TimeStamp) Error while retrieving ETS members $($error)" | out-file $logfilename -append ; $error.clear() }
				else
				{"$(Get-TimeStamp) ETS members processed, getting nested groups till level 2 " | out-file $logfilename -append}
			}
		# Fetching transport rules, accepted domains, remote domains, hybrid relationship, SMTP connectors, and Mailbox databases
		$countSMTP = 0
		$SMTP = Get-ADObject -searchbase $root.configurationNamingContext -filter {(ObjectClass -eq "msExchTransportRule") -or (ObjectClass -eq "msExchAcceptedDomain") -or (ObjectClass -eq "msExchDomainContentConfig") -or (ObjectClass -eq "msExchCoexistenceRelationship")  -or (ObjectClass -eq "msExchRoutingSMTPConnector")  -or (ObjectClass -eq "msExchSmtpReceiveConnector") -or (ObjectClass -eq "msExchAcceptedDomain") -or (ObjectClass -eq "msExchMDB") -or (ObjectClass -eq "msExchMRSRequest")} -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()
				$SMTP = Get-ADObject -ResultPageSize $resultspagesize -searchbase $root.configurationNamingContext -filter {(ObjectClass -eq "msExchTransportRule") -or (ObjectClass -eq "msExchAcceptedDomain") -or (ObjectClass -eq "msExchDomainContentConfig") -or (ObjectClass -eq "msExchCoexistenceRelationship") -or (ObjectClass -eq "msExchRoutingSMTPConnector")  -or (ObjectClass -eq "msExchSmtpReceiveConnector") -or (ObjectClass -eq "msExchMDB") -or (ObjectClass -eq "msExchMRSRequest")} -server $server -Properties *
				$i++
				}
			if($SMTP){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
			$TransportCategory = "CN=ms-Exch-Transport-Rule," + $root.SchemaNamingContext
			$AcceptedCategory = "CN=ms-Exch-Accepted-Domain," + $root.SchemaNamingContext
			$RouteCategory = "CN=ms-Exch-Routing-SMTP-Connector," + $root.SchemaNamingContext
			$ReceiveCategory = "CN=ms-Exch-Smtp-Receive-Connector," + $root.SchemaNamingContext
			$RemoteCategory = "CN=ms-Exch-Domain-Content-Config," + $root.SchemaNamingContext
			$HybridCategory = "CN=ms-Exch-Coexistence-Relationship," + $root.SchemaNamingContext
			$MDBCategory = "CN=ms-Exch-MDB," + $root.SchemaNamingContext
			$MDBprivCategory = "CN=ms-Exch-Private-MDB," + $root.SchemaNamingContext
			$search.filter = "(|(ObjectCategory=$($MDBprivCategory))(ObjectCategory=$($RouteCategory))(ObjectCategory=$($AcceptedCategory))(ObjectCategory=$($RemoteCategory))(ObjectCategory=$($HybridCategory))(ObjectCategory=$($TransportCategory))(ObjectCategory=$($ReceiveCategory))(ObjectCategory=$($MDBCategory)))"
			$search.searchroot = [ADSI]"GC://$($gc)"
			$smtpgc =  $search.findall() | Convert-ADSearchResult
			if($smtpgc){
				$error.clear()
				$countSMTP  = ($smtpgc | measure-object).count
				$gcobjects += $smtpgc
				}
			}

		if($SMTP){
			$criticalobjects += $SMTP
			$countSMTP = ($SMTP | measure-object).count
			}
		if($error)
			{ "$(Get-TimeStamp) Error while retrieving mail flow and storage related objects $($error)" | out-file $logfilename -append ; $error.clear() }
				else
				{
				if($SMTP)
						{"$(Get-TimeStamp) Number of mail flow and storage related objects retrieved via LDAP: $($countSMTP)" | out-file $logfilename -append}
				elseif($smtpgc)
						{"$(Get-TimeStamp) Number of mail flow and storage related objects retrieved via GC: $($countSMTP)" | out-file $logfilename -append}
				else
						{"$(Get-TimeStamp) Cannot read mail flow and storage related objects with the account running the script" | out-file $logfilename -append}
				}

		#Getting RBAC rol assignements
		"$(Get-TimeStamp) Retrieving RBAC role assignements" | out-file $logfilename -append
		$RBAC = Get-ADObject -SearchBase $serviceNC -SearchScope SubTree -filter {ObjectClass -eq "msExchRoleAssignment"} -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()
				$RBAC = Get-ADObject -ResultPageSize $resultspagesize -SearchBase $serviceNC -SearchScope SubTree -filter {ObjectClass -eq "msExchRoleAssignment"} -server $server -properties *
				$i++
				}
			if($RBAC){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
			else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
			}
		if($RBAC)
			{
			$countRBAC = ($RBAC | Measure-object).count
			"$(Get-TimeStamp) Number of RBAC role assignements: $($countRBAC)" | out-file $logfilename -append
			$criticalobjects += $RBAC
			# Get accounts with an RBAC role assigned
			$RBACassignements =  $RBAC | Group-Object -Property msExchUserLink | foreach-object{if($_.Name){get-adobject -Filter {DistinguishedName -eq $_.Name} -server $server -Properties *}}

				if($error)
					{ "$(Get-TimeStamp) Error while retrieving accounts with an RBAC role assigned $($error)" | out-file $logfilename -append ; $error.clear() }

			#Get direct assignements
			$usrRBACassignements = $RBACassignements | where-object{($_.objectClass -eq "user") -or ($_.objectClass -eq "inetOrgPerson") -or ($_.objectClass -eq "Computer")}
			$criticalobjects += $usrRBACassignements
				$countusrRBACassignements = ($usrRBACassignements | Measure-Object).count
				"$(Get-TimeStamp) Number of accounts with RBAC direct assignement: $($countusrRBACassignements)" | out-file $logfilename -append
			if($error)
					{ "$(Get-TimeStamp) Error while retrieving RBAC direct assignements $($error)" | out-file $logfilename -append ; $error.clear() }
			#Get assignements by groups, retrieve group membership
			$grpRBACassignements = $RBACassignements | where-object{($_.objectClass -eq "group")}
			$countgrpRBACassignements = ( $grpRBACassignements | measure-object).count
			"$(Get-TimeStamp) Number of accounts with RBAC indirect assignement: $($countgrpRBACassignements)" | out-file $logfilename -append
			$criticalobjects += $grpRBACassignements
			foreach($grp in $grpRBACassignements)
				{
				$membersROLE = $null
				if($isonline -eq $true)
					{
					$membersROLE = Get-ADGroupMember -recursive $grp -server $server
					if($membersROLE)
						{
						$criticalobjects += ($membersROLE | foreach-object{get-adobject $_ -server $server -properties *})
						$nestedgrp = @()
						$level1 = Get-ADGroupMember $grp -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
					{
					$membersROLE = ($grp | select-object -expandproperty member  | foreach-object{get-adobject $_ -server $server -properties *})
					$criticalobjects += $membersROLE
					$continue = $membersROLE | where-object{$_.ObjectClass -eq "Group"}
					if($continue)
						{foreach($grprole in $continue){$membersROLEn2 = $grprole | select-object -expandproperty member  | foreach-object{get-adobject $_ -server $server -properties *};$criticalobjects += $membersROLEn2}}
					if($error)
						{ "$(Get-TimeStamp) Error while retrieving RBAC indirect assignements $($error)" | out-file $logfilename -append ; $error.clear() }
					}
				}
			if($error)
				{ "$(Get-TimeStamp) Error while retrieving RBAC indirect assignements $($error)" | out-file $logfilename -append ; $error.clear() }

			}
		else
			{
			"$(Get-TimeStamp) Cannot read RBAC role assignements with the account running the script" | out-file $logfilename -append
			$OUGrpExch = "OU=Microsoft Exchange Security Groups," + $root.DefaultNamingContext
			$GrpsExch = get-adobject -searchbase $OUGrpExch -Filter {ObjectClass -eq "Group"} -server $server -Properties *
			$countGrpsExch = ($GrpsExch | measure-object).count
			if($error)
				{ "$(Get-TimeStamp) Error while retrieving groups under MS Exchange Security Groups container $($error)" | out-file $logfilename -append ; $error.clear() }
			else
				{"$(Get-TimeStamp) Number of groups under MS Exchange Security Groups container: $($countGrpsExch)" | out-file $logfilename -append}

			if($GrpsExch)
				{
				$criticalobjects += $GrpsExch
				if($isonline -eq $true)
					{
					foreach($GrpExch in $GrpsExch)
						{
						$criticalobjects += (Get-ADGroupMember -recursive $GrpExch -server $server  | foreach-object{get-adobject $_ -server $server -properties *})
						$nestedgrp = @()
						$level1 = Get-ADGroupMember $GrpExch -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
					{
					foreach($GrpExch in $GrpsExch)
						{
							$exchgrpc = ($GrpExch | select-object -expandproperty member  | foreach-object{get-adobject $_ -server $server -properties *})
							$criticalobjects += $exchgrpc
							$continue = $exchgrpc | where-object{$_.ObjectClass -eq "Group"}
							if($continue)
								{foreach($grp in $continue){$exchgrpcn2 = $grp | select-object -expandproperty member  | foreach-object{get-adobject $_ -server $server -properties *};$criticalobjects += $exchgrpcn2}}
						}
					}

				if($error)
					{ "$(Get-TimeStamp) Error while retrieving group membership of groups located under MS Exchange Security Groups container $($error)" | out-file $logfilename -append ; $error.clear() }
				}

			}

		}

	else
		{
		# If current domain is child domain, we need GC to retrieve some Exchange objects information.
		"$(Get-TimeStamp) Retrieving Exchange Trusted Subsystem on root domain" | out-file $logfilename -append
		$search = new-object System.DirectoryServices.DirectorySearcher
		$search.searchroot = [ADSI]"GC://$($gc)"
		$search.filter = "(DistinguishedName=$($trustedSubSystem))"
		$ets = $search.FindOne() | Convert-ADSearchResult
		$gcobjects += $ets
		if($ets.Member)
			{
			$rootobjectsmembers = $ets.Member | foreach-object{$search.filter = "(DistinguishedName=$($_))"; $search.FindOne() | Convert-ADSearchResult}
			$counttrustedsubsysmembers = ($rootobjectsmembers | measure-object).count
			$gcobjects += $rootobjectsmembers
			}
		if($error)
			{ "$(Get-TimeStamp) Error while retrieving Exchange Trusted SubSystem members in root domain $($error)" | out-file $logfilename -append ; $error.clear() }
				else
			{"$(Get-TimeStamp) Number of level 1 Exchange Trusted SubSystem members $($counttrustedsubsysmembers)" | out-file $logfilename -append}
		# Windows Permissions and Exchange Servers is also retieved
		$Winperm = "CN=Exchange Windows Permissions,OU=Microsoft Exchange Security Groups," + ($root.rootDomainNamingContext)
		$ExcSRV = "CN=Exchange Servers,OU=Microsoft Exchange Security Groups," + ($root.rootDomainNamingContext)
		$search.filter = "(DistinguishedName=$($Winperm))"
		$gcobjects += $search.FindOne() | Convert-ADSearchResult
		$search.filter = "(DistinguishedName=$($ExcSRV))"
		$gcobjects += $search.FindOne() | Convert-ADSearchResult
		if($error)
			{ "$(Get-TimeStamp) Error while retrieving Exchange Windows Permissions or Exchange servers groups $($error)" | out-file $logfilename -append ; $error.clear() }
		# Fetching transport rules, accepted domains, remote domains, hybrid relationship, SMTP connectors, and Mailbox databases
		$countSMTP = 0
		$SMTP = Get-ADObject -searchbase $root.configurationNamingContext -filter {(ObjectClass -eq "msExchTransportRule") -or (ObjectClass -eq "msExchAcceptedDomain") -or (ObjectClass -eq "msExchDomainContentConfig") -or (ObjectClass -eq "msExchCoexistenceRelationship") -or (ObjectClass -eq "msExchRoutingSMTPConnector")  -or (ObjectClass -eq "msExchSmtpReceiveConnector") -or (ObjectClass -eq "msExchMDB") -or (ObjectClass -eq "msExchMRSRequest")} -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()
				$SMTP = Get-ADObject -ResultPageSize $resultspagesize -searchbase $root.configurationNamingContext -filter {(ObjectClass -eq "msExchTransportRule") -or (ObjectClass -eq "msExchAcceptedDomain") -or (ObjectClass -eq "msExchDomainContentConfig") -or (ObjectClass -eq "msExchCoexistenceRelationship") -or (ObjectClass -eq "msExchRoutingSMTPConnector")  -or (ObjectClass -eq "msExchSmtpReceiveConnector") -or (ObjectClass -eq "msExchMDB") -or (ObjectClass -eq "msExchMRSRequest")} -server $server -Properties *
				$i++
				}
			if($SMTP){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
			$TransportCategory = "CN=ms-Exch-Transport-Rule," + $root.SchemaNamingContext
			$AcceptedCategory = "CN=ms-Exch-Accepted-Domain," + $root.SchemaNamingContext
			$RemoteCategory = "CN=ms-Exch-Domain-Content-Config," + $root.SchemaNamingContext
			$HybridCategory = "CN=ms-Exch-Coexistence-Relationship," + $root.SchemaNamingContext
			$RouteCategory = "CN=ms-Exch-Routing-SMTP-Connector," + $root.SchemaNamingContext
			$ReceiveCategory = "CN=ms-Exch-Smtp-Receive-Connector," + $root.SchemaNamingContext
			$MDBCategory = "CN=ms-Exch-MDB," + $root.SchemaNamingContext
			$MDBprivCategory = "CN=ms-Exch-Private-MDB," + $root.SchemaNamingContext
			$search.filter = "(|(ObjectCategory=$($MDBprivCategory))(ObjectCategory=$($RouteCategory))(ObjectCategory=$($AcceptedCategory))(ObjectCategory=$($RemoteCategory))(ObjectCategory=$($HybridCategory))(ObjectCategory=$($TransportCategory))(ObjectCategory=$($ReceiveCategory))(ObjectCategory=$($MDBCategory)))"
			$search.searchroot = [ADSI]"GC://$($gc)"
			$smtpgc =  $search.findall() | Convert-ADSearchResult
			if($smtpgc){
				$error.clear()
				$countSMTP  = ($smtpgc | measure-object).count
				$gcobjects += $smtpgc
				}
			}

			if($SMTP){
				$criticalobjects += $SMTP
				$countSMTP = ($SMTP | measure-object).count
				}
				if($error)
					{ "$(Get-TimeStamp) Error while retrieving mail flow and storage related objects $($error)" | out-file $logfilename -append ; $error.clear() }
				else
					{
					if($SMTP)
						{"$(Get-TimeStamp) Number of mail flow and storage related objects retrieved via LDAP: $($countSMTP)" | out-file $logfilename -append}
					elseif($smtpgc)
						{"$(Get-TimeStamp) Number of mail flow and storage related objects retrieved via GC: $($countSMTP)" | out-file $logfilename -appe
					else
						{"$(Get-TimeStamp) Cannot read mail flow and storage related objects with the account running the script" | out-file $logfilename -append}
					}

		#Getting RBAC role assignements
		$RBAC = Get-ADObject -SearchBase $serviceNC -SearchScope SubTree -filter {ObjectClass -eq "msExchRoleAssignment"} -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()
				$RBAC = Get-ADObject -ResultPageSize $resultspagesize -SearchBase $serviceNC -SearchScope SubTree -filter {ObjectClass -eq "msExchRoleAssignment"} -server $server -properties *
				$i++
				}
			if($RBAC){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
			else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
			}
		if($RBAC)
			{
			$countRBAC = ($RBAC | Measure-object).count
			"$(Get-TimeStamp) Number of RBAC role assignements: $($countRBAC)" | out-file $logfilename -append
			$criticalobjects += $RBAC
			# Get objects assigned to role via GC
			$RBACassignements =  $RBAC | Group-Object -Property msExchUserLink | foreach-object{if($_.Name){$search.filter = "(DistinguishedName=$($_.Name))"; $search.FindOne() | Convert-ADSearchResult}}
			if($error)
				{ "$(Get-TimeStamp) Error while retrieving accounts with an RBAC role assigned $($error)" | out-file $logfilename -append ; $error.clear() }

			$usrRBACassignements = $RBACassignements | where-object{($_.objectClass -eq "user") -or ($_.objectClass -eq "inetOrgPerson") -or ($_.objectClass -eq "Computer")}
			$gcobjects += $usrRBACassignements
			$countusrRBACassignements = ($usrRBACassignements | Measure-Object).count
			"$(Get-TimeStamp) Number of accounts with a direct RBAC assignement: $($countusrRBACassignements)" | out-file $logfilename -append
			$grpRBACassignements = $RBACassignements | where-object{($_.objectClass -eq "group")}
			# Get RBAC indirect assignements but not group membership
			$countgrpRBACassignements = ( $grpRBACassignements | measure-object).count
			"$(Get-TimeStamp) Number of groups with an indirect RBAC assignement:  $($countgrpRBACassignements)" | out-file $logfilename -append
			$gcobjects += $grpRBACassignements
			}
		else
			{
			"$(Get-TimeStamp) RBAC roles could not be retrieved by current account" | out-file $logfilename -append
			"$(Get-TimeStamp) Retrieving groups located in the Microsoft Exchange Security Groups container via GC" | out-file $logfilename -append
			$OUGrpExch = "OU=Microsoft Exchange Security Groups," + $root.rootDomainNamingContext
			$search.searchroot = [ADSI]"GC://$($gc)/$($OUGrpExch)"
			$search.filter = "(ObjectClass=Group)"
			$search.pagesize = 256
			$GrpsExch = $search.FindAll() | Convert-ADSearchResult
			$gcobjects += $GrpsExch
			$countGrpsExch = ( $GrpsExch | measure-object).count
			$search.searchroot = [ADSI]"GC://$($gc)"
			foreach($GrpExch in $GrpsExch)
				{
				$GrpExchmembers = $null
				if($GrpExch.Member){$GrpExchmembers = $GrpExch.Member | foreach-object{$search.filter = "(DistinguishedName=$($_))"; $search.FindOne() | Convert-ADSearchResult}}
				$gcobjects += $GrpExchmembers
				}
			if($error)
				{ "$(Get-TimeStamp) Error while retrieving groups plus members located under the Microsoft Exchange Security Groups container in the root domain $($error)" | out-file $logfilename -append ; $error.clear() }
			else
				{"$(Get-TimeStamp) Number of groups located in Microsoft Exchange Security Groups container in the root domain: $($countGrpsExch)" | out-file $logfilename -append}

			}
		}

	}
}

$error.clear()

#Processing custom group, please fill in table at the begining of the script for processing
if($groupscustom)
	{
    $cache=@{}
    "$(Get-TimeStamp) Custom groups provided by the analyst" | out-file $logfilename -append
	foreach($grpcustom in $groupscustom)
		{
        Write-Output "Searching for group(s) '$grpcustom' ..."
		try {
  			if ($groupslike) {
				Write-Output "Searching for group(s) '*$($grpcustom)*' ..."
				$grpcs = get-adobject -filter { Name -like "*$($grpcustom)*" } -server $server -properties *
			}
			else {
				Write-Output "Searching for group(s) '$grpcustom' ..."
				$grpcs = get-adobject -filter { Name -eq $grpcustom } -server $server -properties *
			}
		}
        catch {
			Write-Output "Error while retrieving group(s) '$grpcustom' : $_"
			{ "$(Get-TimeStamp) Error while retrieving group(s) '$grpcustom' : $_" | out-file $logfilename -append ; }
            continue
        }
        if ($grpcs -is [array]) { Write-Output "Got multiple results for '$grpcustom'" }
        else { $grpcs = ($grpcs) }
		foreach ($grpc in $grpcs)
			{
            Write-Output "isonline: $isonline"
            Write-Output "grpc: $grpc"
			$criticalobjects += $grpc
			if($isonline -eq $true)
				{
            	try {
                	Write-Output "Fetching members of '$grpc' ..."
                	$members = Get-ADGroupMember -recursive $grpc -server $server
					foreach ($member in $members)
					{
						try {
							if ($cache.ContainsKey("$member")) {
							   Write-Output "skipping member '$member' properties ..."
                               continue
                            }
                            $cache["$member"]=1
							Write-Output "fetching member '$member' properties ..."
							$grpc_obj = get-adobject $member -server $server -properties *
							$criticalobjects += ($grpc_obj)
						}
						catch {
							Write-Output "Error during group $grpc traversal: $_"
							{ "$(Get-TimeStamp) Error during group $grpc traversal: $_" | out-file $logfilename -append ; }
							continue
						}
                	}
            	}
				catch {
					Write-Output "Unable to fetch group '$grpc' members: $_"
					{ "$(Get-TimeStamp) Unable to fetch group '$grpc' members: $_" | out-file $logfilename -append ; }
					continue
				}
				$nestedgrp = @()
            	$level1 = @()
				try {
					$levels1 = Get-ADGroupMember $grpc -server $server | where-object{$_.objectclass -eq "Group"}
					foreach ($l in $levels1) {
						try {
							$level1 += $l.distinguishedName
						}
						catch {
							Write-Output "Unable to get distinghishedname from '$l': $_"
							{ "$(Get-TimeStamp) Unable to get distinghishedname from '$l': $_" | out-file $logfilename -append ; }
						}
					}
				}
				catch {
					Write-Output "Unable to fetch level1 group member for '$grpc' : $_"
					{ "$(Get-TimeStamp) Unable to fetch level1 group member for '$grpc' : $_" | out-file $logfilename -append ; }
					continue
				}
				if($level1.length -gt 0) {
					$nestedgrp += $level1
					$level1 | foreach-object {
						$level1_obj = $_
						try {
							$level1_members = Get-ADGroupMember $_.DistinguishedName -server $server | where-object{$_.objectclass -eq "Group"} | select-object distinguishedName
							$nestedgrp += ($level1_members)
						}
						catch {
							Write-Output "Error getting level1 '$level1_obj' members: $_"
							{ "$(Get-TimeStamp) Error getting level1 '$level1_obj' members: $_" | out-file $logfilename -append ; }
							continue
						}
					}
					$nestedgrp | foreach-object{
						try {
							if ($cache.ContainsKey("$_.DistinguishedName")) {
							   Write-Output "skipping adobject $_.DistinguishedName ..."
                               continue
                            }
                            Write-Output "fetching adobject $_.DistinguishedName ..."
							$cache["$_.DistinguishedName"]=1
							$nestedgrp_obj = get-adobject $_.DistinguishedName -server $server -properties *
							$criticalobjects += ($nestedgrp_obj)
						}
						catch {
							Write-Output "Error getting nested group object: $_"
							{ "$(Get-TimeStamp) Error getting nested group object: $_" | out-file $logfilename -append ; }
							continue
						}
					}
				}
			}
			else {
				$customgrpc = ($grpc | select-object -expandproperty member  | foreach-object{get-adobject $_ -server $server -properties *})
				$criticalobjects += $customgrpc
				$continue = $customgrpc | where-object{$_.ObjectClass -eq "Group"}
				if($continue)
					{
						foreach ($grp in $continue) {
							$customgrpcn2 = $grp | select-object -expandproperty member  | foreach-object {
								get-adobject $_ -server $server -properties *
							};
							$criticalobjects += $customgrpcn2
						}
					}
				}
			}
        }

        if($error)
            { "$(Get-TimeStamp) Error while retrieving custom groups $($error)" | out-file $logfilename -append ; $error.clear() }
        "$(Get-TimeStamp) Custom groups retrieved" | out-file $logfilename -append
	}



 #Get dynamic objects
 $DynObjects = Get-ADObject  -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -Filter {ObjectClass -eq "dynamicObject"}  -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()
		$DynObjects = Get-ADObject -ResultPageSize $resultspagesize -SearchBase ($root.defaultNamingContext) -SearchScope SubTree -Filter {ObjectClass -eq "dynamicObject"}  -Server $server -properties *
		$i++
		}
	if($DynObjects){write-output -inputobject "LDAP query succeeded with different ResultPageSize"}
	else{write-output -inputobject "LDAP query failure despite different ResultPageSize, resuming script"}
	}
$countDynObjects = ($DynObjects | measure-object).count
if($error)
    { "$(Get-TimeStamp) Error while retrieving dynamic objects $($error)" | out-file $logfilename -append ; $error.clear() }
else {
	"$(Get-TimeStamp) Number of dynamic objects: $($countDynObjects)" | out-file $logfilename -append
	}
if($DynObjects)
	{
	$ttlcount = 0
	#Merging TTL constructed attributes with AD Object
	foreach($DynObject in $DynObjects)
		{
		$ttl = Get-ADObject $DynObject -Server $server -properties msDS-Entry-Time-To-Die,entryTTL | select-object msDS-Entry-Time-To-Die,entryTTL
		if($ttl."msDS-Entry-Time-To-Die" -and $ttl.entryTTL)
			{
			$a = $ttl.entryTTL.tostring()
			$b = $ttl."msDS-Entry-Time-To-Die".tostring()
			$DynObject | add-member -MemberType NoteProperty -Name msDS-Entry-Time-To-Die -Value $a -force
			$DynObject |  add-member -MemberType NoteProperty -Name entryTTL -Value $b -force
			$DynObject |  add-member -MemberType NoteProperty -Name IsDynamic -Value $true -force
			$criticalobjects = $criticalobjects | where-object{$_.DistinguishedName -ne $DynObject.DistinguishedName}
			$criticalobjects += $DynObject
			$ttlcount++
			}
		else
			{
			$DynObject |  add-member -MemberType NoteProperty -Name IsDynamic -Value $true -force
			$criticalobjects = $criticalobjects | where-object{$_.DistinguishedName -ne $DynObject.DistinguishedName}
			$criticalobjects += $DynObject
			}
		}

	if($error)
		{ "$(Get-TimeStamp) Error while retrieving TTL for dynamic objects $($error)" | out-file $logfilename -append ; $error.clear() }
	else
		{"$(Get-TimeStamp) Number of dynamic objects with TTL set: $($ttlcount)" | out-file $logfilename -append}
	}


write-output -inputobject "---- AD objects collected ----"



#Removing variables
if($SDPropObjects){Remove-variable SDPropObjects}
if($deletedusersgpo){Remove-variable deletedusersgpo}
if($sysobjects){Remove-variable sysobjects}
if($trusts){Remove-variable trusts}
if($allSIDHistory){Remove-variable allSIDHistory}
if($CurrDomainSIDHistory){Remove-variable CurrDomainSIDHistory}
if($OtherDomainSIDHistory){Remove-variable OtherDomainSIDHistory}
if($objOUs){Remove-variable objOUs}
if($kerberoast){Remove-variable kerberoast}
if($sitesIGC){Remove-variable sitesIGC}
if($RBAC){Remove-variable RBAC}
if($RBACassignements){Remove-variable RBACassignements}
if($usrRBACassignements){Remove-variable usrRBACassignements}
if($grpRBACassignements){Remove-variable grpRBACassignements}
if($membersROLE){Remove-variable membersROLE}
if($trustedsubsysmembers){Remove-variable trustedsubsysmembers}
if($deleteconf){Remove-variable deleteconf}
if($GrpsExch){Remove-variable GrpsExch}
if($GrpExchmembers){Remove-variable GrpExchmembers}
if($SMTP){Remove-variable SMTP}
if($dom1){Remove-variable dom1}
if($dcrepls){Remove-variable dcrepls}
if($DCpresents){Remove-variable DCpresents}
if($DCeffaces){Remove-variable DCeffaces}
if($customgrpc){Remove-variable customgrpc}
if($exchgrpc){Remove-variable exchgrpc}
if($otherDCs){Remove-variable otherDCs}
if($otherdomains){Remove-variable otherdomains}
if($DangerOtherDomainSIDHistory){Remove-variable DangerOtherDomainSIDHistory}
if($rootdom){Remove-variable rootdom}
if($rootda){Remove-variable rootda}
if($rootUadmins ){Remove-variable rootUadmins}
if($rootadminsmembers){Remove-variable rootadminsmembers}
if($deletedgpo){Remove-variable deletedgpo}
if($deletedusers){Remove-variable deletedusers}
if($OULevel1){Remove-variable OULevel1}
if($OULevel2){Remove-variable OULevel2}
if($asreproast){Remove-variable asreproast}
if($Classesschema){Remove-variable Classesschema}
if($dnsadmin){Remove-variable dnsadmin}
if($dnsadminsmembers){Remove-variable dnsadminsmembers}
if($delegkrb){Remove-variable delegkrb}
if($DNSZones){Remove-variable DNSZones}
if($objOUsfull){Remove-variable objOUsfull}
if($extrights){Remove-variable extrights}
if($confidattr){Remove-variable confidattr}
if($neveraudit){Remove-variable neveraudit}
if($rootschema){Remove-variable rootschema}
if($rootconf){Remove-variable rootconf}
if($DynObjectswithttl){Remove-variable DynObjectswithttl}
if($DynObjects){Remove-variable DynObjects}
if($ADFSObjects){Remove-variable ADFSObjects}
if($ADFSFarms){Remove-variable ADFSFarms}
if($ADFSrootobj){Remove-variable ADFSrootobj}
if($scps){Remove-variable scps}
if($scpsdomain1){Remove-variable scpsdomain1}
if($scpsdomain2){Remove-variable scpsdomain2}





#Launching garbage collector to free up some RAM
"$(Get-TimeStamp) Freeing up memory" | out-file $logfilename -append
write-output -inputobject "---- Freeing up memory ----"
[System.GC]::Collect()
if($error)
    { "$(Get-TimeStamp) Error while freeing up memory $($error)" | out-file $logfilename -append ; $error.clear() }



write-output -inputobject "---- Exporting objects as XML ----"
#Removing objects collected twice or more
$criticalobjects = $criticalobjects | sort-object -unique -Property DistinguishedName
"$(Get-TimeStamp) Removed LDAP objects collected twice or more" | out-file $logfilename -append
# Exporting objects, first try
try {
	$criticalobjects | Export-Clixml $adobjectsfilename -Encoding UTF8
	"$(Get-TimeStamp) All objects retrieved via LDAP exported in ADobjects.xml" | out-file $logfilename -append
}
catch {
	# Exporting objects, second try
	"$(Get-TimeStamp) Error while exporting some objects retrieved via LDAP $($error)" | out-file $logfilename -append
	"$(Get-TimeStamp) Retrying by filtering out invalid objects ..." | out-file $logfilename -append
	$newcriticalobjects = $criticalobjects | Where-Object { 
		try {
			[System.Management.Automation.PSSerializer]::Serialize($_) | Out-Null
			return $true
		}
		catch {
			"$(Get-TimeStamp) Discarding unserializable object $($_.DistinguishedName)" | out-file $logfilename -append
			return $null
		}
	}
	$newcriticalobjects | Export-Clixml -Force $adobjectsfilename -Encoding UTF8
	"$(Get-TimeStamp) $($newcriticalobjects.Count)/$($criticalobject.Count) objects retrieved via LDAP exported in ADobjects.xml" | out-file $logfilename -append
	if($error)
		{ "$(Get-TimeStamp) Error while exporting objects $($error)" | out-file $logfilename -append ; $error.clear() }
}

$nbviaLDAP = $null
$nbviagc = $null
if($gcobjects)
	{
	$gcobjects = $gcobjects | sort-object -unique -Property DistinguishedName
	"$(Get-TimeStamp) Removed GC objects collected twice or more" | out-file $logfilename -append

	# Exporting gcobjects, first try
	try {
		$gcobjects | Export-Clixml $gcADobjectsfilename -Encoding UTF8
		"$(Get-TimeStamp) Global Catalog objects exported in gcADobjects.xml" | out-file $logfilename -append
	}
	catch {
		# Exporting gcobjects, second try
		"$(Get-TimeStamp) Error while exporting some Global Catalog objects retrieved via LDAP $($error)" | out-file $logfilename -append
		"$(Get-TimeStamp) Retrying by filtering out invalid Global Catalog objects ..." | out-file $logfilename -append
		$newgcobjects = $gcobjects | Where-Object { 
			try {
				[System.Management.Automation.PSSerializer]::Serialize($_) | Out-Null
				return $true
			}
			catch {
				"$(Get-TimeStamp) Discarding unserializable object $($_.distinguishedname)" | out-file $logfilename -append
				return $null
			}
		}
		$newgcobjects | Export-Clixml -Force $gcADobjectsfilename -Encoding UTF8
		"$(Get-TimeStamp) $($newgcobjects.Count)/$($gcobjects.Count) Global Catalog objects retrieved via LDAP exported in gcADobjects.xml" | out-file $logfilename -append
		if($error)
			{ "$(Get-TimeStamp) Error while exporting global catalog objects $($error)" | out-file $logfilename -append ; $error.clear() }
	}

	$nbviaLDAP = ($criticalobjects | measure-object).count
	$nbviagc = ($gcobjects | measure-object).count
	"$(Get-TimeStamp) Number of objects retrieved via LDAP $($nbviaLDAP) and via Global Catalog $($nbviagc)" | out-file $logfilename -append
	$criticalobjects += $gcobjects
	}
else {
	remove-item $gcADobjectsfilename -force -confirm:$false
	}


# Generating TimeLine from replication metadata
write-output -inputobject "---- Export done ----"
write-output -inputobject "---- Generating AD timeline ----"
"$(Get-TimeStamp) Starting to retrieve AD replication metadata" | out-file $logfilename -append
$countcrit = ($criticalobjects | measure-object).count
"$(Get-TimeStamp) Number of objects to process: $($countcrit)" | out-file $logfilename -append
write-output -inputobject "---- $($countcrit) Objects to process ----"


$groupClass = "CN=Group," + $root.SchemaNamingContext
$personClass = "CN=Person," + $root.SchemaNamingContext

# Initializing AD replication metadata object
$Replinfo = [System.Collections.ArrayList]@()
$i = 0

foreach ($criticalobject in $criticalobjects)
	{
	if($criticalobject.DistinguishedName)
	{
	#Displaying progress bar
	write-progress -Activity "AD replication metadata" -Status "$i objects processed:" -percentcomplete ($i/$countcrit*100)
	#Parsing de msDS-ReplAttributeMetadata see blog Once Upon a Case https://blogs.technet.microsoft.com/pie/2014/08/25

	if($nbviagc -and ($i -ge $nbviaLDAP))
		{
		$search = new-object System.DirectoryServices.DirectorySearcher
		$search.searchroot = [ADSI]"GC://$($gc)"
		$search.Tombstone = $true
		$search.PropertiesToLoad.Addrange(('msDS-ReplAttributeMetadata','Name','DistinguishedName'))
		$search.filter = "(DistinguishedName=$($criticalobject.DistinguishedName))"
		$search.pagesize = 256
		$obj = 	$search.FindAll()  | Convert-ADSearchResult

		}
	else
		{$obj = get-adobject $criticalobject.DistinguishedName -Properties msDS-ReplAttributeMetadata -server $server -IncludeDeletedObjects}

	$metadas = $obj."msDS-ReplAttributeMetadata" | foreach-object{ ([xml] $_.Replace("`0","").Replace("&","&amp;")).DS_REPL_ATTR_META_DATA }

	if($criticalobject.whencreated)
		{$whencreatedUTC = get-date (get-date($criticalobject.whencreated)).ToUniversalTime() -format u}
	else{$whencreatedUTC = "N/A"}

    	if($error)
        {"$(Get-TimeStamp) Error while retrieving AD replication metadata attributes msDS-ReplAttributeMetadata for $($criticalobject.DistinguishedName) $($error)" | out-file $logfilename -append ; $error.clear() }
	else
        {
	    foreach($metada in $metadas)
		    {

		    # Creating temp object with AD replication metadata attributes plus some object attributes relevant for timeline analysis
		    $tmpobj = new-object psobject
		    add-member -InputObject $tmpobj -MemberType NoteProperty -Name ftimeLastOriginatingChange -Value $metada.ftimeLastOriginatingChange
		    add-member -InputObject $tmpobj -MemberType NoteProperty -Name Name -Value $obj.Name
		    add-member -InputObject $tmpobj -MemberType NoteProperty -Name pszAttributeName -Value $metada.pszAttributeName
			add-member -InputObject $tmpobj -MemberType NoteProperty -Name ObjectClass -Value $criticalobject.ObjectClass
			add-member -InputObject $tmpobj -MemberType NoteProperty -Name DN -Value $obj.DistinguishedName
		    add-member -InputObject $tmpobj -MemberType NoteProperty -Name ObjectCategory -Value $criticalobject.ObjectCategory
		    add-member -InputObject $tmpobj -MemberType NoteProperty -Name SamAccountName -Value $criticalobject.SamAccountName
		    add-member -InputObject $tmpobj -MemberType NoteProperty -Name dwVersion -Value $metada.dwVersion
		    add-member -InputObject $tmpobj -MemberType NoteProperty -Name WhenCreated -Value $whencreatedUTC
		    add-member -InputObject $tmpobj -MemberType NoteProperty -Name Member -Value ""
		    add-member -InputObject $tmpobj -MemberType NoteProperty -Name ftimeCreated -Value ""
		    add-member -InputObject $tmpobj -MemberType NoteProperty -Name ftimeDeleted -Value ""
		    add-member -InputObject $tmpobj -MemberType NoteProperty -Name SID -Value $criticalobject.objectSid
			add-member -InputObject $tmpobj -MemberType NoteProperty -Name pszLastOriginatingDsaDN -Value $metada.pszLastOriginatingDsaDN
	    	add-member -InputObject $tmpobj -MemberType NoteProperty -Name uuidLastOriginatingDsaInvocationID -Value $metada.uuidLastOriginatingDsaInvocationID
	    	add-member -InputObject $tmpobj -MemberType NoteProperty -Name usnOriginatingChange -Value $metada.usnOriginatingChange
	    	add-member -InputObject $tmpobj -MemberType NoteProperty -Name usnLocalChange -Value $metada.usnLocalChange

	    	    # Append temp object to global AD replication metadata object
	    	    [void]$Replinfo.add($tmpobj)
		    if($error){ "$(Get-TimeStamp) Error while editing global AD replication metadata object $($error) for $($criticalobject.DistinguishedName)" | out-file $logfilename -append ; $error.clear() }
		    }
        }

	if($criticalobject.ObjectCategory -eq $groupClass)
		{
		#For groups we retrieve also the msDS-ReplValueMetadata attribute
		$isgcanduniversalorindom = $true
		if($nbviagc -and ($i -ge $nbviaLDAP))
			{
			# Only universal groups are processed
			if($criticalobject.GroupType -eq "-2147483640")
					{
					$search = new-object System.DirectoryServices.DirectorySearcher
					$search.searchroot = [ADSI]"GC://$($gc)"
					$search.Tombstone = $true
					$search.PropertiesToLoad.Addrange(('msDS-ReplValueMetadata','Name','DistinguishedName'))
					$search.filter = "(DistinguishedName=$($criticalobject.DistinguishedName))"
					$search.pagesize = 256
					$objgrp = 	$search.FindAll() | Convert-ADSearchResult
					}
			else
				{$isgcanduniversalorindom = $false}
			}

		else
			{$objgrp = get-adobject $criticalobject.DistinguishedName -Properties msDS-ReplValueMetadata -server $server -IncludeDeletedObjects}

			if($error)
        			{ "$(Get-TimeStamp) Error while retrieving AD replication metadata attributes msDS-ReplValueMetadata for $($criticalobject.DistinguishedName) $($error)" | out-file $logfilename -append ; $error.clear() }

					if($isgcanduniversalorindom -and $objgrp."msDS-ReplValueMetadata")
						{
						$metadasgrp = $objgrp."msDS-ReplValueMetadata" | foreach-object{ ([xml] $_.Replace("`0","")).DS_REPL_VALUE_META_DATA}
					if($error)
        				{ "$(Get-TimeStamp) Error while parsing AD replication metadata attributes msDS-ReplValueMetadata for $($criticalobject.DistinguishedName) $($error)" | out-file $logfilename -append ; $error.clear() }
			else
				{
				$metadasgrpmbr = $metadasgrp | where-object{$_.pszAttributeName -eq "member"}
				if($metadasgrpmbr)
					{
					foreach($metada in $metadasgrpmbr)
						{

						$tmpobj = new-object psobject
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name ftimeLastOriginatingChange -Value $metada.ftimeLastOriginatingChange
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name Name -Value $obj.Name
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name pszAttributeName -Value $metada.pszAttributeName
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name ObjectClass -Value $criticalobject.ObjectClass
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name DN -Value $obj.DistinguishedName
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name ObjectCategory -Value $criticalobject.ObjectCategory
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name SamAccountName -Value $criticalobject.SamAccountName
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name dwVersion -Value $metada.dwVersion
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name WhenCreated -Value $whencreatedUTC
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name Member -Value $metada.pszObjectDn
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name ftimeCreated -Value $metada.ftimeCreated
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name ftimeDeleted -Value $metada.ftimeDeleted
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name SID -Value $criticalobject.objectSid
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name pszLastOriginatingDsaDN -Value $metada.pszLastOriginatingDsaDN
	   					add-member -InputObject $tmpobj -MemberType NoteProperty -Name uuidLastOriginatingDsaInvocationID -Value $metada.uuidLastOriginatingDsaInvocationID
	    				add-member -InputObject $tmpobj -MemberType NoteProperty -Name usnOriginatingChange -Value $metada.usnOriginatingChange
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name usnLocalChange -Value $metada.usnLocalChange

	    				[void]$Replinfo.add($tmpobj)
						if($error){ "$(Get-TimeStamp) Error while editing global AD replication metadata object $($error) for $($criticalobject.DistinguishedName)" | out-file $logfilename -append ; $error.clear() }
						}


					}
				}
		    }    
            else {$metadasgrp  = $null}
		}
	
		if(($criticalobject.ObjectCategory -eq $personClass) -and ($null -ne $criticalobject.altRecipient))
		{
		#For persons with altRecipients attribute we retrieve also the msDS-ReplValueMetadata attribute
		$isgcanduniversalorindom = $true
		if($nbviagc -and ($i -ge $nbviaLDAP))
			{
					$search = new-object System.DirectoryServices.DirectorySearcher
					$search.searchroot = [ADSI]"GC://$($gc)"
					$search.Tombstone = $true
					$search.PropertiesToLoad.Addrange(('msDS-ReplValueMetadata','Name','DistinguishedName'))
					$search.filter = "(DistinguishedName=$($criticalobject.DistinguishedName))"
					$search.pagesize = 256
					$objpers = 	$search.FindAll() | Convert-ADSearchResult
			}

		else
			{$objpers = get-adobject $criticalobject.DistinguishedName -Properties msDS-ReplValueMetadata -server $server -IncludeDeletedObjects}

            if($error)
            { "$(Get-TimeStamp) Error while retrieving AD replication metadata attributes msDS-ReplValueMetadata for $($criticalobject.DistinguishedName) $($error)" | out-file $logfilename -append ; $error.clear() }

		if($objpers."msDS-ReplValueMetadata")
            {$metadaspers = $objpers."msDS-ReplValueMetadata" | foreach-object{ ([xml] $_.Replace("`0","")).DS_REPL_VALUE_META_DATA}

			if($error)
        			{ "$(Get-TimeStamp) Error while parsing AD replication metadata attributes msDS-ReplValueMetadata for $($criticalobject.DistinguishedName) $($error)" | out-file $logfilename -append ; $error.clear() }

			else
				{
				$metadaspersrec = $metadaspers | where-object{$_.pszAttributeName -eq "altRecipient"}
				if($metadaspersrec)
					{
					foreach($metada in $metadaspersrec)
						{

						$tmpobj = new-object psobject
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name ftimeLastOriginatingChange -Value $metada.ftimeLastOriginatingChange
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name Name -Value $obj.Name
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name pszAttributeName -Value $metada.pszAttributeName
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name ObjectClass -Value $criticalobject.ObjectClass
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name DN -Value $obj.DistinguishedName
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name ObjectCategory -Value $criticalobject.ObjectCategory
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name SamAccountName -Value $criticalobject.SamAccountName
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name dwVersion -Value $metada.dwVersion
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name WhenCreated -Value $whencreatedUTC
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name Member -Value $metada.pszObjectDn
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name ftimeCreated -Value $metada.ftimeCreated
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name ftimeDeleted -Value $metada.ftimeDeleted
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name SID -Value $criticalobject.objectSid
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name pszLastOriginatingDsaDN -Value $metada.pszLastOriginatingDsaDN
	   					add-member -InputObject $tmpobj -MemberType NoteProperty -Name uuidLastOriginatingDsaInvocationID -Value $metada.uuidLastOriginatingDsaInvocationID
	    				add-member -InputObject $tmpobj -MemberType NoteProperty -Name usnOriginatingChange -Value $metada.usnOriginatingChange
						add-member -InputObject $tmpobj -MemberType NoteProperty -Name usnLocalChange -Value $metada.usnLocalChange

	    				[void]$Replinfo.add($tmpobj)
						if($error){ "$(Get-TimeStamp) Error while editing global AD replication metadata object $($error) for $($criticalobject.DistinguishedName)" | out-file $logfilename -append ; $error.clear() }
						}


					}
				}
		
            }
            else {$metadaspers  = $null}       
        
        }

	}
	$i++
	}

"$(Get-TimeStamp) AD replication metadata retrieved" | out-file $logfilename -append


# Sort by ftimeLastOriginatingChange to generate timeline and export as csv
"$(Get-TimeStamp) Sorting AD replication metadata to generate timeline " | out-file $logfilename -append

$Replinfo | Sort-Object -Property ftimeLastOriginatingChange | export-csv $timelinefilename -delimiter ";" -NoTypeInformation -Encoding UTF8
    if($error)
        { "$(Get-TimeStamp) Error while sortig timeline $($error)" | out-file $logfilename -append ; $error.clear() }
    else
        { "$(Get-TimeStamp) Timeline created" | out-file $logfilename -append }

write-output -inputobject "---- Timeline created ----"


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
![ADTimeline](./logo.png)
---
# Table of contents:
1. [The ADTimeline PowerShell script](#thescript)
    1. [Description](#description)
    2. [Prerequisites](#prerequisites)
    3. [Usage](#usage)
    4. [Files generated](#files)
    5. [Custom groups](#groups)
2. [The ADTimeline App for Splunk](#theapp)
    1. [Description](#descriptionsplk)
    2. [Sourcetypes](#sourcetype)
    3. [AD General information dashboards](#infradashboards)
    4. [AD threat hunting dashboards](#threathuntdashboards)
    5. [Enhance your traditional event logs threat hunting with ADTimeline](#threathuntevtx)

# The ADTimeline PowerShell script:  <a name="thescript"></a>

## Description: <a name="description"></a>

The ADTimeline script generates a timeline based on Active Directory replication metadata for objects considered of interest.  
Replication metadata gives you the time at which each replicated attribute for a given object was last changed. As a result the timeline of modifications is partial. For each modification of a replicated attribute a version number is incremented.  
ADTimeline was first presented at the [CoRI&IN 2019](https://www.cecyf.fr/coriin/coriin-2019/) (Conférence sur la réponse aux incidents et l’investigation numérique). Slides of the presentation, in french language,  are available [here](https://cyber.gouv.fr/publications/investigation-numerique-sur-lannuaire-active-directory-avec-les-metadonnees-de). It was also presented at the [Amsterdam 2019 FIRST Technical Colloquium](https://www.first.org/events/colloquia/amsterdam2019/program#pActive-Directory-forensics-with-replication-metadata-ADTimeline-tool), slides in english are available [here](https://cyber.gouv.fr/en/actualites/adtimeline-active-directory-forensics-replication-metadata-first-technical-colloquium).

Objects considered of interest retrieved by the script include:

- Schema and configuration partition root objects.
- Domain root and objects located directly under the root.
- Objects having an ACE on the domain root.
- Domain roots located in the AD forest.
- Domain trusts.
- Deleted users (i.e. tombstoned).
- Objects protected by the SDProp process (i.e. AdminCount equals 1).
- The Guest account.
- The AdminSDHolder object.
- Objects having an ACE on the AdminSDHolder object.
- Class Schema objects.
- Existing and deleted Group Policy objects.
- DPAPI secrets.
- Domain controllers (Computer objects, ntdsdsa and server objects).
- DNS zones.
- WMI filters.
- Accounts with suspicious SIDHistory (scope is forest wide).
- Sites.
- Organizational Units.
- Objects with Kerberos delegation enabled.
- Extended rights.
- Schema attributes with particular SearchFlags (Do not audit or confidential).
- Kerberoastable user accounts (SPN value).
- AS-REP roastable accounts (UserAccountControl value).
- Authentication policy silos.
- CertificationAuthority and pKIEnrollmentService objects.
- Cross Reference containers.
- Exchange RBAC roles and accounts assigned to a role.
- Exchange mail flow configuration objects.
- Exchange mailbox databases objects.
- Exchange Mailbox Replication Service objects
- Deleted objects under the configuration partition.
- Dynamic objects.
- The directory service and RID manager objects.
- The Pre Windows 2000 compatible access, Cert publishers, GPO creator owners and DNS Admins groups.
- ADFS DKM containers.
- Service connection point objects considered of interest.
- Custom groups which have to be manually defined.
- User objects with mail forwarder enabled (msExchGenericForwardingAddress and altRecipient attributes).

## Prerequisites: <a name="prerequisites"></a>

- The account launching the script should be able to read objects in the tombstone (Deleted Objects Container) and some parts of the Exchange settings located in the configuration partition (View-Only Organization management). Delegation can be tricky to setup (especially for reading the tombstone). That is why we advise you to run the script with a domain admin account. If you launch the script as a standard user, it will process the timeline without the objects mentioned.
- Computer should run Windows NT 6.1 or later with PowerShell 2.0 or later and have the Active Directory Powershell module installed (part of RSAT-AD-Tools).
- If you enabled PowerShell Constrained Language Mode the script might fail (calling $error.clear()). Consider whitelisting the script via your device guard policy.
- If you are using offline mode install the ADLDS role on a Windows Server edition in order to use dsamain.exe and mount the NTDS database.

    The version of the Windows Server you install the role on should be the same as the version of the Windows Server which the ntds.dit came from. If you do not know that version and you have the SOFTWARE hive available, you can look at the CurrentVersion key.
    
    If you can not mount the ntds.dit file with dsamain.exe, this might be because the NTDS dump is corrupted. In that case, you can follow [advice from cert-cwatch](https://github.com/ANSSI-FR/ADTimeline/issues/17#issuecomment-1984049537).

## Usage: <a name="usage"></a>

In online mode no argument is mandatory and the closest global catalog is used for processing. If no global catalog is found run the script with the server argument :
```DOS
PS> .\ADTimeline.ps1 -server <GLOBAL CATALOG FQDN>
```
In offline mode: Replay if necessary transaction logs of the NTDS database, mount it on your analysis machine (ADLDS + RSAT-AD-Tools installed) and use 3266 as LDAP port.
```DOS
C:\Windows\System32> dsamain.exe -dbpath <NTDS.DIT path> -ldapport 3266 -allownonadminaccess
```
If necessary use the allowupgrade switch.

Launch the script targetting localhost on port 3266:
```DOS
PS> .\ADTimeline.ps1 -server "127.0.0.1:3266"
```

If you encounter performance issues when running against a large MSExchange organization with forwarders massively used, use the nofwdSMTP parameter:
```DOS
PS>.\ADTimeline -nofwdSMTPaltRecipient
```
## Files generated <a name="files"></a>

Output files are generated in the current directory:

- timeline_%DOMAINFQDN%.csv: The timeline generated with the AD replication metadata of objects retrieved.
- logfile_%DOMAINFQDN%.log: Script log file. You will also find various information on the domain.
- ADobjects_%DOMAINFQDN%.xml: Objects of interest retrieved via LDAP.
- gcADobjects_%DOMAINFQDN%.xml: Objects of interest retrieved via the Global Catalog.


To import files for analysis with powershell. 
```powershell
PS> import-csv timeline_%DOMAINFQDN%.csv -delimiter ";"
PS> import-clixml ADobjects_%DOMAINFQDN%.xml
PS> import-clixml gcADobjects_%DOMAINFQDN%.xml
```
The analysis with the ADTimeline for Splunk is a better solution.

## Custom groups <a name="groups"></a>

If you want to include custom AD groups in the timeline (for example virtualization admin groups, network admins, VIP groups...) use the *Customgroups* parameter.

*Customgroups* parameter can be a string with multiple group comma separated (no space):
```powershell
PS>./ADTimeline -customgroups "VIP-group1,ESX-Admins,Tier1-admins"
```
*Customgroups* parameter can also be an array, in case you import the list from a file (one group per line):
```powershell
PS>$customgroups = get-content customgroups.txt
PS>./ADTimeline -customgroups $customgroups
```
If you do not want to use a parameter you can also uncomment and edit the following array at the  begining of the script:
```powershell
$groupscustom = ("VIP-group1","ESX-Admis","Tier1-admins")
```

# The ADTimeline App for Splunk: <a name="theapp"></a>

## Description: <a name="descriptionsplk"></a>

The ADTimeline application for Splunk processes and analyses the Active Directory data collected by the ADTimeline PowerShell script. The app was presented at the 32nd annual FIRST Conference, a recording of the presentation is available [here](https://www.first.org/conference/2020/recordings).

The app's "Getting started" page will give you the instructions for the import process.

Once indexed the dashboards provided by the app will help the DFIR analyst to spot some Acitve Directory persistence mechanisms, misconfigurations, security audit logging bypass, mail exfiltration, brute force attacks ...

The app is also packaged and available on [Splunkbase](https://splunkbase.splunk.com/app/4897/). It has no prerequisite and will work with a [free Splunk](https://docs.splunk.com/Documentation/Splunk/latest/Admin/MoreaboutSplunkFree) license.

![Splunkapp](./SA-ADTimeline.png)

## Sourcetypes: <a name="sourcetype"></a>

After processing the ADTimeline script you should have two or three files to import in Splunk (%DOMAINFQDN% is the Active Directory fully qualified domain name):

- timeline_%DOMAINFQDN%.csv: The timeline generated with the AD replication metadata of objects retrieved. The corresponding source type is *adtimeline*.
- ADobjects_%DOMAINFQDN%.xml: Objects of interest retrieved via LDAP. The corresponding sourcetype is *adobjects*.
- gcADobjects_%DOMAINFQDN%.xml: If any, objects of interest retrieved via the Global Catalog. The corresponding source type is *gcobjects*.

### The adtimeline sourcetype:

 The *adtimeline* sourcetype is the data from the timeline_%DOMAINFQDN%.csv file, which is the Active Directory timeline built with replication metadata for objects considered of interest.

The timestamp value is the ftimeLastOriginatingChange value of the replication metadata, which is the time the attribute was last changed, time is UTC.

The extracted fields are:

- Name: LDAP object name.
- pszAttributeName: The attribute name.
- dwVersion: Counter incremented every time the attribute is changed.
- DN: LDAP object DistinguishedName.
- WhenCreated: LDAP object creation time.
- ObjectClass and ObjectCategory: LDAP object type (user, computer, group...)
- SamAccountName and SID: Account Name and security identifier, only applies to users, computers and groups.
- usnOriginatingChange: USN on the originating server at which the last change to this attribute was made.
- pszLastOriginatingDsaDN: DC on which the last change was made to this attribute.
- uuidLastOriginatingDsaInvocationID: ID corresponding to the pszLastOriginatingDsaDN.
- usnLocalChange: USN on the destination server (the server your LDAP bind is made) at which the last change to this attribute was applied.
- Member: Only applies to the group ObjectClass and when the attribute name is member. Contains the value of the group member DistinguishedName.
- ftimeCreated: Only applies to group ObjectClass and when the attribute name is member. Contains the time the member was added in the group.
- ftimeDeleted: Only applies to group ObjectClass and when the attribute name is member. Contains the time the member was removed from the group.

### The adobjects sourcetype:

The *adobjects* sourcetype is the data from the ADobjects_%DOMAINFQDN%.xml file, which is an export of the Active Directory objects considered of interested and retrieved via the LDAP protocol.

The timestamp value is the createTimeStamp attribute value, time zone is specified in the attribute value.

The extracted fields are:

- Name: LDAP object name.
- DN: LDAP object DistinguishedName.
- DisplayName: LDAP object displayname.
- WhenCreated: LDAP object creation time.
- ObjectClass and ObjectCategory: LDAP object type (user, computer, group...)
- SamAccountName and SID: Account Name and security identifier, only applies to users, computers and groups.
- Members and MemberOf: Members of a group ObjectClass can be users, computers or groups and its linked attribute MemberOf which applies to groups, users and computers.
- Owner, AccessToString and SDDL: Are values computed from the nTSecurityDescriptor attribute
- adminCount: Privileged accounts protected by the SDProp process.
- userAccountControl: Attribute which contains a range of flags which define some important basic properties of a computer or user object.
- lastLogonTimestamp: This attribute is not updated with all logon types or at every logon but is replicated and gives you an idea of wether a user or computer account has recently logged on to the domain.
- dNSHostName: DNS hostname attribute of a computer account.
- SPNs: List of Service Principal Names of a computer or user account.

### The gcobjects sourcetype:

The *gcobjects* sourcetype is the data from the gcADobjects_%DOMAINFQDN%.xml file, which is an export of the Active Directory objects within the forest but outside the current domain and considered of interested, those objects are retrieved via the Global Catalog protocol.

The timestamp value is the WhenCreated attribute value, time zone is UTC.

The extracted fields are:

- Name: LDAP object name.
- DN: LDAP object DistinguishedName.
- DisplayName: LDAP object displayname.
- WhenCreated: LDAP object creation time.
- ObjectClass and ObjectCategory: LDAP object type (user, computer, group...)
- SamAccountName and SID: Account Name and security identifier, only applies to users, computers and groups.
- userAccountControl: Attribute which contains a range of flags which define some important basic properties of a computer or user object.
- lastLogonTimestamp: This attribute is not updated with all logon types or at every logon but is replicated and gives you an idea if a user or computer account has recently logged onto the domain.
- dNSHostName: DNS hostname attribute of a computer account.
- SPNs: List of Service Principal Names of a computer or user account.

## AD General information dashboards: <a name="infradashboards"></a>

### The Active Directory Infrastructure dashboard:

This dashboard analyses Adtimeline data in order to create some panels giving you information on the Windows domain infrastructure.

The different panels are:

- General information: Information about the Schema version and functional levels. Depending on the result some AD security features may or may not be available. The Domain Controllers are also listed in this panel
- Microsoft infrastructure products: Tells you if some important Microsoft Infrastructure components such as Exchange on premises, Active Directory Federation Services or Active Directory Certificate Services are installed. Please consider monitoring events related to those services (MSExchange CmdletLogs, ADFS auditing...)
- Domain Trusts: List domain trusts by type and direction. Run ADTimeline on all your trusted domains, but most importantly make sure they are audited, monitored and secured as rigorously as the domain you are analyzing.
- ADDS security features: Tells you if some security features are enabled or not. First feature is the AD Recycle bin which gives the administrator the ability to easily recover deleted objects, it will also change the time after an object is removed from the AD database after deletion. Second feature tells you if the schema extension for the Local Admin Password Solution was performed, if yes sysadmins can enable password randomization for local administrators accounts in order to mitigate lateral movement. Another feature is authentication silos which can help to restrict privileged user account logons in order to mitigate privilege escalation by implementing a tiered administrative model. The last feature is the Protected Users group, with a DFL 2012R2 or more the members of this group receive some additional hardening
- Service Connection Points: Inventory of serviceConnectionPoint (SCP) object class. SCP make it easy for a service to publish service-specific data in the directory Clients of the service use the data in an SCP to locate an instance of the service. Infrastructure assets such as RDS Gateway, SCCM, VMWare Vcenter, some Backup solutions publish an SCP in the directory.
- Active Directory infrastructure timeline: Displays a timeline of the infrastructure changes listed above. This timeline tells you the story of the evolution of your infrastructure.

### The sensitive accounts dashboard:

This dashboard provides an inventory of the privileged accounts in the domain and accounts prone to common attack scenarios due to their configuration.

 The different panels are:

- Admin Accounts: This panel lists the accounts where the Admincount attribute value equals 1. Those accounts have their ACL protected by the SDProp process and it means the account has or had at some point high privileges in Active Directory. The first table lists them and provides some information about the accounts, the second table displays a timeline of modifications for some attributes of these accounts.
- Accounts sensitive to Kerberoast attacks: Kerberoasting is an attack method that allows an attacker to crack the passwords of service accounts in Active Directory offline. The chart is a ratio of accounts prone to this attack and whether or not they are privileged accounts. The table lists them and provides some information about the accounts. Use least privilege principle for those accounts and consider using Group Managed Service Accounts.
- Accounts sensitive to AS-REP Roast attacks: AS-REP Roast is an attack method that allows an attacker to crack the passwords of accounts in Active Directory offline. The chart is a ratio of accounts prone to this attack and whether or not they are privileged accounts. The table lists them and provides some information about the accounts. Use least privilege principle for those accounts.
- Sensitive default accounts: Some general information about the default administrator, guest and krbtgt accounts. Administrator can be disabled or renamed as a measure against account lockout. Guest account must be disabled and krbtgt password should be changed on a regular schedule.
- Accounts trusted for delegation: Kerberos Delegation is a feature that allows an application to reuse the end-user credentials to access resources hosted on a different server. An account trusted for unconstrained delegation is allowed to impersonate almost any user to any service within the network, whereas an account trusted for constrained delegation is allowed to impersonate almost any user for a given service within the network. The chart is a ratio of accounts trusted for constrained/unconstrained delegation. The tables list those accounts, the service name is given for accounts trusted for constrained delegation. A table listing objects with resource based constrained delegation configured is also displayed

## AD threat hunting dashboards: <a name="threathuntdashboards"></a>

### The investigate timeframe dashboard:

Use this dashboard to investigate a particular timeframe.

 The different panels are:

- AD Timeline: A table displaying the timeline for the given timeframe.
- Global stats: Global statistics on modifications occurring during the given timeframe, including modifications by ObjectClass, by pszAttributeName, by Originating DC, by time (i.e. day of the week or hour of the day) and finally stats on deletions by ObjectClass.
- Items created and deleted within timeframe: A table displaying the creations and deletions of the same object within the given timeframe. A first ch
Download .txt
gitextract_qju42vfu/

├── .github/
│   └── workflows/
│       └── buildsplunkapp.yml
├── ADTimeline.ps1
├── LICENSE
├── README.md
└── SA-ADTimeline/
    ├── README
    ├── default/
    │   ├── app.conf
    │   ├── data/
    │   │   └── ui/
    │   │       ├── nav/
    │   │       │   └── default.xml
    │   │       └── views/
    │   │           ├── ad_infra.xml
    │   │           ├── getting_started.xml
    │   │           ├── investigate_timeframe.xml
    │   │           ├── sensitive_accounts.xml
    │   │           ├── suspicious_activity.xml
    │   │           └── suspicious_exchange_activity.xml
    │   ├── props.conf
    │   └── transforms.conf
    ├── lookups/
    │   ├── CSE_matching
    │   ├── ExchangeSchemaVersions
    │   ├── ObjectVersionSchema
    │   └── fsmoroleowner
    └── metadata/
        └── default.meta
Condensed preview — 20 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (463K chars).
[
  {
    "path": ".github/workflows/buildsplunkapp.yml",
    "chars": 952,
    "preview": "name: Build Splunk App\n\non:\n  push:\n    branches:\n      - 'master'\n\njobs:\n  build_splunk_app:\n    runs-on: ubuntu-22.04\n"
  },
  {
    "path": "ADTimeline.ps1",
    "chars": 144330,
    "preview": "# Active directory timeline generated with replication metadata\n# Leonard SAVINA - ANSSI\\SDO\\DR\\INM - CERT-FR\n# Issues a"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 31583,
    "preview": "![ADTimeline](./logo.png)\n---\n# Table of contents:\n1. [The ADTimeline PowerShell script](#thescript)\n    1. [Description"
  },
  {
    "path": "SA-ADTimeline/README",
    "chars": 298,
    "preview": "Contact information: adtimeline@ssi.gouv.fr\r\nThere is no package requirements to install the app.\r\nThis is an open sourc"
  },
  {
    "path": "SA-ADTimeline/default/app.conf",
    "chars": 437,
    "preview": "#\r\n# Splunk app configuration file\r\n#\r\n[package]\r\nid = SA-ADTimeline\r\ncheck_for_updates = true\r\n\r\n[install]\r\nis_configur"
  },
  {
    "path": "SA-ADTimeline/default/data/ui/nav/default.xml",
    "chars": 577,
    "preview": "<nav search_view=\"search\" color=\"#2B2BA1\">\r\n  <view name=\"search\" default='true' />\r\n  <view name=\"getting_started\" />\r\n"
  },
  {
    "path": "SA-ADTimeline/default/data/ui/views/ad_infra.xml",
    "chars": 39735,
    "preview": "<form version=\"1.1\">\r\n  <label>Active Directory infrastructure</label>\r\n  <fieldset submitButton=\"false\"></fieldset>\r\n  "
  },
  {
    "path": "SA-ADTimeline/default/data/ui/views/getting_started.xml",
    "chars": 29250,
    "preview": "<dashboard version=\"1.1\">\r\n  <label>Getting started</label>\r\n  <row>\r\n    <panel>\r\n      <html>\r\n<style>\r\n.images {\r\n  d"
  },
  {
    "path": "SA-ADTimeline/default/data/ui/views/investigate_timeframe.xml",
    "chars": 31654,
    "preview": "<form version=\"1.1\" theme=\"light\">\r\n  <label>Investigate timeframe</label>\r\n  <fieldset submitButton=\"false\"></fieldset>"
  },
  {
    "path": "SA-ADTimeline/default/data/ui/views/sensitive_accounts.xml",
    "chars": 38813,
    "preview": "<form version=\"1.1\">\r\n  <label>Sensitive accounts</label>\r\n  <fieldset submitButton=\"false\"></fieldset>\r\n  <row>\r\n    <p"
  },
  {
    "path": "SA-ADTimeline/default/data/ui/views/suspicious_activity.xml",
    "chars": 56348,
    "preview": "<form version=\"1.1\">\r\n  <label>Track suspicious activity</label>\r\n  <search>\r\n    <query>index=$ad_index$ host=$domain_h"
  },
  {
    "path": "SA-ADTimeline/default/data/ui/views/suspicious_exchange_activity.xml",
    "chars": 21801,
    "preview": "<form version=\"1.1\">\n  <label>Track suspicious Exchange activity</label>\n  <fieldset submitButton=\"false\"></fieldset>\n  "
  },
  {
    "path": "SA-ADTimeline/default/props.conf",
    "chars": 3851,
    "preview": "\r\n[adtimeline]\r\nBREAK_ONLY_BEFORE_DATE =\r\nFIELD_DELIMITER = ;\r\nINDEXED_EXTRACTIONS = csv\r\nKV_MODE = none\r\nLINE_BREAKER "
  },
  {
    "path": "SA-ADTimeline/default/transforms.conf",
    "chars": 428,
    "preview": "[adxml_remove_header]\r\nREGEX = ^<Objs Version=\r\nDEST_KEY = queue\r\nFORMAT = nullQueue\r\n\r\n[Schema_lookup]\r\nfilename = Obje"
  },
  {
    "path": "SA-ADTimeline/lookups/CSE_matching",
    "chars": 3582,
    "preview": "GUID,CSE\r\r\n{35378EAC-683F-11D2-A89A-00C04FBBCFA2},Registry settings\r\r\n{0ACDD40C-75AC-47AB-BAA0-BF6DE7E7FE63},Wireless Gr"
  },
  {
    "path": "SA-ADTimeline/lookups/ExchangeSchemaVersions",
    "chars": 1419,
    "preview": "\"Exchange\",\"rangeUpper\"\r\n\r\n\"Exchange 2019 CU10-CU11 schema version\",\"17003\"\r\n\r\n\"Exchange 2019 CU8-CU9 schema version\",\"1"
  },
  {
    "path": "SA-ADTimeline/lookups/ObjectVersionSchema",
    "chars": 258,
    "preview": "ObjectVersion,SchemaVersion\r\r\n13,Windows 2000 Server\r\r\n30,Windows 2003 Server\r\r\n31,Windows 2003R2 Server\r\r\n44,Windows 20"
  },
  {
    "path": "SA-ADTimeline/lookups/fsmoroleowner",
    "chars": 176,
    "preview": "ObjectClass,FSMORole\r\r\ncrossRefContainer,Domain Naming Master\r\r\ndMD,Schema Master\r\r\ndomainDNS,PDC Emulator\r\r\ninfrastruct"
  },
  {
    "path": "SA-ADTimeline/metadata/default.meta",
    "chars": 134,
    "preview": "\r\n# Application-level permissions\r\n[]\r\naccess = read : [ user ], write : [ admin, power, sc_admin ]\r\nexport = system\r\now"
  }
]

About this extraction

This page contains the full source code of the ANSSI-FR/ADTimeline GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 20 files (430.4 KB), approximately 122.4k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!